{ "cells": [ { "cell_type": "markdown", "id": "259a50df-42d1-497d-862c-bc6137f5c0ae", "metadata": {}, "source": [ "# Setup" ] }, { "cell_type": "code", "execution_count": null, "id": "9bc0cb9f-ae27-48cd-8562-8ed4f33d331d", "metadata": { "scrolled": true }, "outputs": [], "source": [ "from pycocotools.coco import COCO\n", "import os\n", "from colorama import Fore, Style\n", "import json\n", "import numpy as np" ] }, { "cell_type": "code", "execution_count": null, "id": "a6843cd1-030a-4df8-a461-8f230d0c7871", "metadata": {}, "outputs": [], "source": [ "use_skf_splits = False" ] }, { "cell_type": "markdown", "id": "428bb1c7-36ba-4919-bc73-188f0f1aa697", "metadata": {}, "source": [ "# Dataset load" ] }, { "cell_type": "code", "execution_count": null, "id": "c6fb9073-5dcc-40fa-bd6a-f0538de52f8d", "metadata": { "scrolled": true }, "outputs": [], "source": [ "dataset_path = './dataset_archive/'\n", "train_annotations_path = os.path.join(dataset_path, 'train/', '_annotations.coco.json')\n", "valid_annotations_path = os.path.join(dataset_path, 'valid/', '_annotations.coco.json')\n", "\n", "with open(train_annotations_path) as f1, open(valid_annotations_path) as f2:\n", " train_data_in = json.load(f1)\n", " valid_data_in = json.load(f2)" ] }, { "cell_type": "code", "execution_count": null, "id": "d2f36b48-c584-4927-9558-f88ce82adaf7", "metadata": {}, "outputs": [], "source": [ "len(train_data_in['annotations'])" ] }, { "cell_type": "code", "execution_count": null, "id": "ccf3258b-39ec-4b3b-be3e-e5f02b65003e", "metadata": {}, "outputs": [], "source": [ "len(valid_data_in['annotations'])" ] }, { "cell_type": "markdown", "id": "bd265787-d3d0-4d41-b057-85e8ff10b7f3", "metadata": {}, "source": [ "# (Optional) Split the dataset using the multi-Stratified K-fold CSV files" ] }, { "cell_type": "markdown", "id": "9ea78bc7-c374-44ea-b791-91dd8ae02e34", "metadata": {}, "source": [ "The CSV files have been previously generated using the multilabel Stratified K-Fold (**mskf**) technique in order to balance classes distributions across dataset splits. If you wish to generate different versions of dataset splits (e.g. with different *k*, different algorithm, etc...), you can do that in the `stratified_kfold.ipynb` notebook. We have provided these splits to make them a baseline as they are used for our metrics. \n", "\n", "Each CSV file has the following columns:\n", "\n", "- `IMADE_ID` - an integer representing the image ID from the original json annottaions file\n", "- `IMAGE_PATH` - the corresponding image path\n", "- `SPLIT` - either **train** or **valid**" ] }, { "cell_type": "code", "execution_count": null, "id": "e850bac4-c548-4721-998d-a2e0d40af961", "metadata": { "scrolled": true }, "outputs": [], "source": [ "import pandas as pd\n", "import utils\n", "\n", "if use_skf_splits:\n", " csv_files = ['mskf_0.csv', 'mskf_1.csv', 'mskf_2.csv', 'mskf_3.csv'] \n", " \n", " for idx, csv_file in enumerate(csv_files):\n", " mskf = pd.read_csv(csv_file)\n", " utils.create_directories_and_copy_files('path/to/dest', data_in, mskf, idx)" ] }, { "cell_type": "markdown", "id": "c9b2c0ae-0d88-4bb1-a636-040f28b83fdf", "metadata": {}, "source": [ "# Visualise a dataset version" ] }, { "cell_type": "markdown", "id": "629d7f66-0ded-4c6f-94c9-bd26149912ad", "metadata": {}, "source": [ "Now, let's choose one of the dataset versions and visualize it." ] }, { "cell_type": "code", "execution_count": null, "id": "b93ed46b-d1ad-4193-8eb7-ac2dda791b42", "metadata": { "scrolled": true }, "outputs": [], "source": [ "data_dir = dataset_path\n", "splits = ['train', 'valid']\n", "\n", "coco_objects = {}\n", "\n", "for split in splits:\n", " annotations_file = os.path.join(str(data_dir), str(split), '_annotations.coco.json')\n", " coco_objects[split] = COCO(annotations_file)\n", " \n", " # get class categories in the current split\n", " categories = coco_objects[split].loadCats(coco_objects[split].getCatIds())\n", " category_names = [cat['name'] for cat in categories]\n", " print(f\"{Fore.BLUE}Class categories in {split}: {category_names}{Style.RESET_ALL}\")\n", "\n", " annotation_ids = {}\n", "\n", " # get annotations in the current split\n", " annotation_ids[split] = coco_objects[split].getAnnIds()\n", " annotations = coco_objects[split].loadAnns(annotation_ids[split])\n", " print(f\"{Fore.BLUE}Number of annotations in {split}: {len(annotations)}{Style.RESET_ALL}\")\n", " \n", " # get image IDs in the current split\n", " img_ids = coco_objects[split].getImgIds()\n", " images = coco_objects[split].loadImgs(img_ids)\n", " print(f\"{Fore.BLUE}Number of images in {split}: {len(images)}{Style.RESET_ALL}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "eb018f21-beae-48cb-9f63-1793b8f9a558", "metadata": { "scrolled": true }, "outputs": [], "source": [ "from tabulate import tabulate\n", "\n", "table_data = []\n", "\n", "for split in splits:\n", " annotations_file = os.path.join(data_dir, split, '_annotations.coco.json')\n", " coco = COCO(annotations_file)\n", " cat_ids = coco.getCatIds()\n", " categories = coco.loadCats(cat_ids)\n", " cat_names = [cat['name'] for cat in categories]\n", " cat_counts = [len(coco.getAnnIds(catIds=[cat_id])) for cat_id in cat_ids]\n", " total_count = sum(cat_counts)\n", "\n", " for cat_name, count in zip(cat_names, cat_counts):\n", " percentage = (count / total_count) * 100 if total_count > 0 else 0\n", " if percentage > 0:\n", " table_data.append({\n", " 'Split': '#'+split.capitalize()+' (%)',\n", " 'Category': cat_name,\n", " 'Count': count,\n", " 'Percentage': np.round(percentage, 3)\n", " })\n", "\n", "df = pd.DataFrame(table_data)\n", "pivot_count = df.pivot_table(index='Category', columns='Split', values='Count', fill_value=0)\n", "pivot_percentage = df.pivot_table(index='Category', columns='Split', values='Percentage', fill_value=0.0)\n", "combined_df = pivot_count.astype(str) + \" (\" + pivot_percentage.astype(str) + \")\"\n", "\n", "styled_df = combined_df.style.apply(utils.highlight_max_str, subset=['#Train (%)', '#Valid (%)'])\\\n", " .format({'#Train (%)': \"{:}\", '#Valid (%)': \"{:}\"})\\\n", " .set_properties(**{'text-align': 'center', 'font-size': '10pt'})\\\n", " .set_table_styles([{'selector': 'th', 'props': [('font-size', '12pt')]}])\\\n", " .set_caption(\"Annotation Counts and Percentages by Filter and Split\")\n", "styled_df" ] }, { "cell_type": "markdown", "id": "9bbe486b-117c-4545-b952-959b53979b16", "metadata": {}, "source": [ "We can also see how many images per filter we have." ] }, { "cell_type": "code", "execution_count": null, "id": "1c74762d-3ead-4d24-8128-684cee708151", "metadata": { "scrolled": true }, "outputs": [], "source": [ "filter_count = {'U': 0, 'V': 0, 'B': 0, 'W': 0, 'S': 0, 'M': 0, 'L': 0}\n", "filter_annots_count = filter_count.copy()\n", "\n", "\n", "for split in splits:\n", " annotations_file = os.path.join(data_dir, split, '_annotations.coco.json')\n", " \n", " with open(annotations_file) as f:\n", " data_in = json.load(f)\n", " \n", " for img in data_in['images']:\n", " filter = img['file_name'][:13][-1] # The OM observations IDs are 13 characters long, the last of them representing the filter\n", " filter_count[filter] += 1\n", " image_annots = [annot for annot in data_in['annotations'] if annot['image_id'] == img['id']]\n", " for annot in image_annots:\n", " filter_annots_count[filter] += 1\n", " \n", " df_counts = pd.DataFrame(list(filter_count.items()), columns=['Observing Filter', 'Image Count'])\n", " df_annot_counts = pd.DataFrame(list(filter_annots_count.items()), columns=['Observing Filter', 'Annotation Count'])\n", " df_merged = pd.merge(df_counts, df_annot_counts, on='Observing Filter')\n", " \n", "filters_df = df_merged.style.apply(utils.highlight_max, subset=['Image Count', 'Annotation Count'])\\\n", " .format({'Image Count': \"{:,}\", 'Annotation Count': \"{:,}\"})\\\n", " .set_properties(**{'text-align': 'center', 'font-size': '10pt'})\\\n", " .set_table_styles([{'selector': 'th', 'props': [('font-size', '10pt')]}])\\\n", " .set_caption(\"Counts of Images and Annotations per Filter\")\n", " \n", "filters_df" ] }, { "cell_type": "markdown", "id": "0eec287f-68b3-44e3-9c96-d906e70c472e", "metadata": {}, "source": [ "## Mask heatmap" ] }, { "cell_type": "code", "execution_count": null, "id": "34e13739-98f0-4aff-bb4f-072ee36f38b7", "metadata": { "scrolled": true }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from pycocotools.coco import COCO\n", "from matplotlib.colors import LinearSegmentedColormap\n", "from matplotlib import style\n", "import matplotlib.pyplot as plt\n", "plt.rcParams[\"font.family\"] = \"serif\"\n", "plt.rcParams[\"mathtext.fontset\"] = \"dejavuserif\"\n", "\n", "all_categories = set()\n", "coco_objects = {}\n", "for split in splits:\n", " annotations_file = os.path.join(str(data_dir), str(split), '_annotations.coco.json')\n", " coco = COCO(annotations_file)\n", " coco_objects[split] = coco\n", " categories = coco.loadCats(coco.getCatIds())\n", " all_categories.update([cat['name'] for cat in categories])\n", "\n", "sorted_categories = ['star-loop', 'smoke-ring', 'read-out-streak', 'central-ring', 'other'] # sorted(list(all_categories))\n", "img_width, img_height = 512, 512\n", "\n", "style.use('ggplot')\n", "fig, axes = plt.subplots(len(splits), len(sorted_categories), figsize=(3 * len(sorted_categories), 6), squeeze=False)\n", "\n", "for i, cat_name in enumerate(sorted_categories):\n", " for j, split in enumerate(splits):\n", " coco = coco_objects[split]\n", " cat_id = coco.getCatIds(catNms=[cat_name])\n", " ann_ids = coco.getAnnIds(catIds=cat_id)\n", " annotations = coco.loadAnns(ann_ids)\n", " heatmap = np.zeros((img_height, img_width))\n", "\n", " for ann in annotations:\n", " bbox = ann['bbox']\n", " x, y, w, h = map(int, bbox)\n", " heatmap[y:y + h, x:x + w] += 1\n", "\n", " colors = ['white', 'skyblue', 'navy']\n", " cm = LinearSegmentedColormap.from_list('custom_blue', colors, N=256)\n", " ax = axes[j, i] # Change here: use two indices for axes\n", " im = ax.imshow(heatmap, cmap=cm, interpolation='nearest')\n", " ax.set_title(f'{split.capitalize()} - {cat_name}', fontsize=10)\n", " ax.set_xticks([])\n", " ax.set_yticks([])\n", " ax.grid(False)\n", "\n", "plt.tight_layout(pad=0.0)\n", "plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1, hspace=0.2, wspace=0.07)\n", "plt.savefig('./plots/artefact_distributions.png')\n", "plt.show()\n", "plt.close()" ] }, { "cell_type": "markdown", "id": "2fe7db86-980a-48ba-be72-a7b1575665e9", "metadata": {}, "source": [ "## Galactic coordinates plotting" ] }, { "cell_type": "code", "execution_count": null, "id": "b7e08403-7aaa-47ac-acb4-43b5650e453e", "metadata": { "scrolled": true }, "outputs": [], "source": [ "import json\n", "from astropy.coordinates import SkyCoord\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "import astropy.units as u\n", "from astropy.io import ascii\n", "from astropy.coordinates import SkyCoord\n", "from astropy.visualization import astropy_mpl_style\n", "\n", "# import the filename that contains observations with coordinates and exposure times\n", "all_obs_coords = './obs_info_1024_all.json'\n", "\n", "with open(all_obs_coords, 'r') as file:\n", " coords_data = json.load(file)\n", "\n", "ra = []\n", "dec = []\n", "exposures = []\n", "\n", "for split in splits: \n", " for image_file in os.listdir(data_dir + f'/{split}'):\n", " obs = image_file.split('.')[0].replace('_png', '.fits')\n", " if obs in coords_data:\n", " ra.append(coords_data[obs]['RA'])\n", " dec.append(coords_data[obs]['DEC'])\n", " exposures.append(coords_data[obs]['EXPOSURE'])\n", "\n", "coords = SkyCoord(ra=ra*u.degree, dec=dec*u.degree, frame='icrs')\n", "galactic = coords.galactic\n", "\n", "exposure_norm = (exposures - np.min(exposures)) / (np.max(exposures) - np.min(exposures))\n", "\n", "plt.style.use(astropy_mpl_style)\n", "plt.rcParams.update({'font.size': 16, 'font.family': 'sans-serif'})\n", "\n", "fig = plt.figure(figsize=(10, 5))\n", "ax = fig.add_subplot(111, projection=\"aitoff\")\n", "sc = ax.scatter(galactic.l.wrap_at(180*u.deg).radian, galactic.b.wrap_at(180*u.deg).radian,\n", " c=exposure_norm, cmap='magma_r', alpha=0.7, edgecolor='none', zorder=1)\n", "\n", "ax.grid(True, color='silver', linestyle='--', linewidth=0.5)\n", "\n", "ax.tick_params(axis='x', labelsize=14, colors='black', zorder=2)\n", "ax.tick_params(axis='y', labelsize=14, colors='black', zorder=2)\n", "\n", "ax.set_facecolor('aliceblue') # A soft white background color\n", "\n", "cbar = plt.colorbar(sc, orientation='horizontal', pad=0.1, aspect=50)\n", "cbar.set_label('Normalized Exposure', fontsize=25)\n", "cbar.ax.tick_params(labelsize=17) \n", "cbar.outline.set_visible(False) \n", "cbar.ax.xaxis.set_tick_params(color='black') \n", "\n", "for spine in ax.spines.values():\n", " spine.set_visible(False)\n", "\n", "plt.tight_layout(pad=0.3)\n", "# plt.savefig('dataset_galactic_distribution.png', dpi=300) \n", "plt.show()" ] } ], "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.11.7" }, "widgets": { "application/vnd.jupyter.widget-state+json": { "state": {}, "version_major": 2, "version_minor": 0 } } }, "nbformat": 4, "nbformat_minor": 5 }