{ "cells": [ { "cell_type": "code", "execution_count": 3, "id": "c2058f8d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "522" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import os\n", "from tqdm import tqdm\n", "import glob\n", "from astropy.io import fits\n", "import os\n", "from astropy.io import fits\n", "from astropy.wcs import WCS\n", "from spherical_geometry.polygon import SphericalPolygon\n", "import os\n", "from astropy.io import fits\n", "from astropy.wcs import WCS\n", "from spherical_geometry.polygon import SphericalPolygon\n", "from sklearn.cluster import AgglomerativeClustering\n", "import matplotlib.pyplot as plt\n", "import pandas as pd\n", "from astropy.io import fits\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "\"\"\"\n", "\n", "Use this code after downloading all SDSS data first, using the file\n", "titled sdss_downloading.\n", "\n", "\"\"\"\n", "\n", "def get_all_fits_files(root_dir):\n", " # Use glob to recursively find all .fits files\n", " pattern = os.path.join(root_dir, '**', '*.fits')\n", " fits_files = glob.glob(pattern, recursive=True)\n", " return fits_files\n", "\n", "valid_fits_paths = get_all_fits_files('./data')\n", "len(valid_fits_paths)" ] }, { "cell_type": "code", "execution_count": 11, "id": "554c2fa7", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ " 9%|███▊ | 47/522 [00:28<06:45, 1.17it/s]WARNING: FITSFixedWarning: RADECSYS= 'ICRS ' / International Celestial Reference Sys \n", "the RADECSYS keyword is deprecated, use RADESYSa. [astropy.wcs.wcs]\n", "100%|█████████████████████████████████████████| 522/522 [06:48<00:00, 1.28it/s]\n" ] } ], "source": [ "\"\"\"\n", "Computes a spherical polygon object for each FITS file using WCS coordinates.\n", "Stores each in a list.\n", "\n", "\"\"\"\n", "\n", "\n", "# Initialize the list of confirmed FITS paths\n", "confirmed_fits_paths = []\n", "\n", "all_polys = []\n", "\n", "for i in tqdm(range(len(valid_fits_paths))):\n", " path1 = valid_fits_paths[i]\n", " try:\n", " with fits.open(path1) as hdul:\n", " hdul[0].data = hdul[0].data[0, 0]\n", " wcs1a = WCS(hdul[0].header)\n", " shape1a = sorted(tuple(wcs1a.pixel_shape))[:2]\n", " footprint1a = wcs1a.calc_footprint(axes=shape1a)\n", " poly1a = SphericalPolygon.from_radec(footprint1a[:, 0], footprint1a[:, 1])\n", " all_polys.append(poly1a)\n", " except Exception as e:\n", " print(e)\n", " continue" ] }, { "cell_type": "code", "execution_count": 13, "id": "c58c3c55", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████████████████████████████████| 522/522 [00:00<00:00, 17983.71it/s]\n" ] } ], "source": [ "latitudes = []\n", "longitudes = []\n", "\n", "\"\"\"\n", "Get a list of all RA and DEC into a list before filtering.\n", "\n", "\"\"\"\n", "\n", "for poly in tqdm(all_polys):\n", " pts = list(poly.to_radec())[0]\n", " ra = pts[0][0]\n", " dec = pts[1][0]\n", " \n", " longitudes.append(ra)\n", " latitudes.append(dec)" ] }, { "cell_type": "code", "execution_count": 14, "id": "1c83484e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Symmetric?\n", "True\n", "(522, 522)\n" ] } ], "source": [ "n_points = len(latitudes)\n", "\n", "# Repeat each point n_points times for lat1, lon1\n", "lat1 = np.repeat(latitudes, n_points)\n", "lon1 = np.repeat(longitudes, n_points)\n", "\n", "# Tile the whole array n_points times for lat2, lon2\n", "lat2 = np.tile(latitudes, n_points)\n", "lon2 = np.tile(longitudes, n_points)\n", "\n", "# Calculates angular separation between two spherical coords\n", "# This can be lat/lon or ra/dec\n", "# Taken from astropy\n", "def angular_separation_deg(lon1, lat1, lon2, lat2):\n", " lon1 = np.deg2rad(lon1)\n", " lon2 = np.deg2rad(lon2)\n", " lat1 = np.deg2rad(lat1)\n", " lat2 = np.deg2rad(lat2)\n", " \n", " sdlon = np.sin(lon2 - lon1)\n", " cdlon = np.cos(lon2 - lon1)\n", " slat1 = np.sin(lat1)\n", " slat2 = np.sin(lat2)\n", " clat1 = np.cos(lat1)\n", " clat2 = np.cos(lat2)\n", "\n", " num1 = clat2 * sdlon\n", " num2 = clat1 * slat2 - slat1 * clat2 * cdlon\n", " denominator = slat1 * slat2 + clat1 * clat2 * cdlon\n", "\n", " return np.rad2deg(np.arctan2(np.hypot(num1, num2), denominator))\n", "\n", "# Compute the pairwise angular separations\n", "angular_separations = angular_separation_deg(lon1, lat1, lon2, lat2)\n", "\n", "# Reshape the result into a matrix form\n", "angular_separations_matrix = angular_separations.reshape(n_points, n_points)\n", "\n", "def check_symmetric(a, rtol=1e-05, atol=1e-07):\n", " return np.allclose(a, a.T, rtol=rtol, atol=atol)\n", "\n", "print(\"Symmetric?\")\n", "print(check_symmetric(angular_separations_matrix))\n", "print(angular_separations_matrix.shape)" ] }, { "cell_type": "code", "execution_count": 19, "id": "c66e8c1e", "metadata": {}, "outputs": [], "source": [ "SDSS_FOV = 0.088\n", "\n", "THRESH = SDSS_FOV * 4\n", "\n", "\"\"\"\n", "Initial clustering phase using just RA DEC, not WCS polygon footprints.\n", "\n", "\"\"\"\n", "\n", "clustering = AgglomerativeClustering(n_clusters=None, metric='precomputed', linkage='single', distance_threshold=THRESH)\n", "labels = clustering.fit_predict(angular_separations_matrix)" ] }, { "cell_type": "code", "execution_count": 24, "id": "51da93b0", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ " 3%|█▍ | 13/377 [00:00<00:21, 16.71it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "FAIL label: 10, i: 1 IoU: 0.25944657797281734\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " 8%|███▏ | 29/377 [00:01<00:15, 21.76it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "FAIL label: 23, i: 2 IoU: 0.4090236242653364\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " 9%|███▉ | 35/377 [00:02<00:15, 22.08it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "FAIL label: 29, i: 2 IoU: 0.9007704140270892\n", "FAIL label: 32, i: 2 IoU: 0.4056510771965438\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\r", " 10%|████▏ | 38/377 [00:02<00:18, 18.22it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "FAIL label: 36, i: 2 IoU: 0.5762689111619909\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " 15%|██████▏ | 55/377 [00:02<00:10, 31.49it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "FAIL label: 47, i: 1 IoU: 0.9250531562187404\n", "FAIL label: 48, i: 1 IoU: 0.8360586649509192\n", "FAIL label: 53, i: 1 IoU: 0.10008227926664898\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " 19%|████████▏ | 73/377 [00:03<00:09, 33.33it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "FAIL label: 68, i: 2 IoU: 0.49064401487956755\n", "FAIL label: 69, i: 2 IoU: 0.9662692069365345\n", "FAIL label: 71, i: 1 IoU: 0.09857753647298885\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " 22%|█████████▎ | 84/377 [00:03<00:07, 38.05it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "FAIL label: 74, i: 3 IoU: 0.5845239934642943\n", "FAIL label: 81, i: 2 IoU: 0.7402716532101037\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " 28%|███████████▋ | 107/377 [00:03<00:03, 69.94it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "FAIL label: 91, i: 2 IoU: 0.30092583437382314\n", "FAIL label: 106, i: 1 IoU: 0.5437761463648566\n", "FAIL label: 110, i: 1 IoU: 0.978096219321612\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " 43%|█████████████████▎ | 163/377 [00:04<00:01, 124.92it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "FAIL label: 137, i: 1 IoU: 0.5768840711253176\n", "FAIL label: 138, i: 1 IoU: 0.426858068191846\n", "FAIL label: 142, i: 1 IoU: 1.0\n", "FAIL label: 151, i: 1 IoU: 0.6865076393310577\n", "FAIL label: 162, i: 1 IoU: 0.40902362440677925\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "100%|█████████████████████████████████████████| 377/377 [00:04<00:00, 82.43it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "FAIL label: 166, i: 2 IoU: 0.3312197305714273\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "failed_labels = []\n", "failed_paths = []\n", "\n", "for label in tqdm(np.unique(labels)):\n", " polys = [(all_polys[i], valid_fits_paths[i]) for i in range(len(labels)) if labels[i] == label]\n", " if len(polys) > 1:\n", " total_poly = polys[0][0]\n", " for i in range(1, len(polys)):\n", " new_poly = polys[i][0]\n", " new_path = polys[i][1]\n", " if total_poly.intersects_poly(new_poly):\n", " union_over_max = total_poly.intersection(new_poly).area() / new_poly.area()\n", " print(f\"FAIL label: {label}, i: {i} IoU: {union_over_max}\")\n", " failed_labels.append(label)\n", " failed_paths.append(new_path)\n", " continue\n", " else:\n", " total_poly = total_poly.union(new_poly)" ] }, { "cell_type": "code", "execution_count": 18, "id": "46c6217a", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['./data/cube_center_run4203_camcol6_f746_73-5-800-800.fits',\n", " './data/cube_center_run2700_camcol2_f56_86-5-800-800.fits',\n", " './data/cube_center_run4198_camcol6_f243_3-5-800-800.fits',\n", " './data/cube_center_run5658_camcol2_f33_25-5-800-800.fits',\n", " './data/cube_center_run4933_camcol2_f695_81-5-800-800.fits',\n", " './data/cube_center_run2709_camcol5_f236_72-5-800-800.fits',\n", " './data/cube_center_run5637_camcol4_f385_1-5-800-800.fits',\n", " './data/cube_center_run5759_camcol4_f118_72-5-800-800.fits',\n", " './data/cube_center_run2700_camcol5_f163_86-5-800-800.fits',\n", " './data/cube_center_run3434_camcol4_f456_34-5-800-800.fits',\n", " './data/cube_center_run5792_camcol6_f342_73-5-800-800.fits',\n", " './data/cube_center_run5918_camcol5_f278_69-5-800-800.fits',\n", " './data/cube_center_run4128_camcol3_f475_1-5-800-800.fits',\n", " './data/cube_center_run5590_camcol2_f272_56-5-800-800.fits',\n", " './data/cube_center_run5836_camcol6_f545_52-5-800-800.fits',\n", " './data/cube_center_run4933_camcol3_f554_85-5-800-800.fits',\n", " './data/cube_center_run4128_camcol5_f348_8-5-800-800.fits',\n", " './data/cube_center_run2886_camcol1_f164_78-5-800-800.fits',\n", " './data/cube_center_run5642_camcol1_f374_80-5-800-800.fits',\n", " './data/cube_center_run4188_camcol5_f87_42-5-800-800.fits',\n", " './data/cube_center_run5628_camcol5_f238_69-5-800-800.fits',\n", " './data/cube_center_run5781_camcol5_f291_76-5-800-800.fits']" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "failed_paths" ] }, { "cell_type": "code", "execution_count": 29, "id": "4af5240f", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['tiny_train.jsonl', 'full_train.jsonl', 'full_test.jsonl', 'tiny_test.jsonl']" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.listdir('./splits')" ] }, { "cell_type": "code", "execution_count": 42, "id": "abce2e5a", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "\n", "# Path to the JSONL file\n", "file_path = './splits/full_train.jsonl'\n", "\n", "# Read the JSONL file into a DataFrame\n", "df_train = pd.read_json(file_path, lines=True)\n", "\n", "# Path to the JSONL file\n", "file_path = './splits/full_test.jsonl'\n", "\n", "# Read the JSONL file into a DataFrame\n", "df_test = pd.read_json(file_path, lines=True)" ] }, { "cell_type": "code", "execution_count": 49, "id": "c5844d7a", "metadata": {}, "outputs": [], "source": [ "df = pd.concat([df_train, df_test])\n", "df = df[~df['image'].isin(failed_paths)]" ] }, { "cell_type": "code", "execution_count": 54, "id": "b94657a0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Train and test datasets have been saved to 'train_data.csv' and 'test_data.csv'.\n" ] } ], "source": [ "import pandas as pd\n", "from sklearn.model_selection import train_test_split\n", "\n", "# Assuming df is your DataFrame\n", "# df = pd.DataFrame(...) # Your DataFrame should already be defined\n", "\n", "# Perform an 85/15 train-test split\n", "train_df, test_df = train_test_split(df, test_size=0.15, random_state=42)\n", "\n", "# Save the train and test DataFrames to CSV files\n", "train_df.to_csv('full_train.csv', index=False)\n", "test_df.to_csv('full_test.csv', index=False)\n", "\n", "print(\"Train and test datasets have been saved to 'train_data.csv' and 'test_data.csv'.\")" ] }, { "cell_type": "code", "execution_count": 55, "id": "987b9fd7", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "1\n", "Train and test datasets have been saved to 'train_data.csv' and 'test_data.csv'.\n" ] } ], "source": [ "import pandas as pd\n", "\n", "# Path to the JSONL file\n", "file_path = './splits/tiny_train.jsonl'\n", "\n", "# Read the JSONL file into a DataFrame\n", "df_train = pd.read_json(file_path, lines=True)\n", "\n", "# Path to the JSONL file\n", "file_path = './splits/tiny_test.jsonl'\n", "\n", "# Read the JSONL file into a DataFrame\n", "df_test = pd.read_json(file_path, lines=True)\n", "\n", "print(len(df_train))\n", "print(len(df_test))\n", "\n", "# Save the train and test DataFrames to CSV files\n", "df_train.to_csv('tiny_train.csv', index=False)\n", "df_test.to_csv('tiny_test.csv', index=False)\n", "\n", "print(\"Train and test datasets have been saved to 'train_data.csv' and 'test_data.csv'.\")" ] }, { "cell_type": "code", "execution_count": 59, "id": "dd0209ef", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CSV file has been converted and saved as JSONL at ./splits/tiny_train.jsonl\n", "CSV file has been converted and saved as JSONL at ./splits/tiny_test.jsonl\n", "CSV file has been converted and saved as JSONL at ./splits/full_train.jsonl\n", "CSV file has been converted and saved as JSONL at ./splits/full_test.jsonl\n" ] } ], "source": [ "import pandas as pd\n", "\n", "names = [\"./splits/tiny_train\", \"./splits/tiny_test\", \"./splits/full_train\", \"./splits/full_test\"]\n", "\n", "for name in names:\n", "\n", " # Step 1: Load the CSV file into a DataFrame\n", " csv_file_path = f'{name}.csv' # Replace with your actual CSV file path\n", " df = pd.read_csv(csv_file_path)\n", "\n", " # Step 2: Save the DataFrame as a JSONL file\n", " jsonl_file_path = f'{name}.jsonl' # Replace with your desired output file path\n", " df.to_json(jsonl_file_path, orient='records', lines=True)\n", "\n", " print(f\"CSV file has been converted and saved as JSONL at {jsonl_file_path}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "dfafd26c", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.13" } }, "nbformat": 4, "nbformat_minor": 5 }