From 7a22e7b0820f77e2f0b862917633b609c0add4e0 Mon Sep 17 00:00:00 2001 From: Hatice Karatay Date: Tue, 3 Oct 2023 16:47:39 -0400 Subject: [PATCH] Correct some of the style errors on the 02729 nb --- .../ero_nirspec_ifu_02729_demo.ipynb | 323 +++++++++--------- 1 file changed, 159 insertions(+), 164 deletions(-) diff --git a/notebooks/NIRSpec_IFU_spectral_extraction/ero_nirspec_ifu_02729_demo.ipynb b/notebooks/NIRSpec_IFU_spectral_extraction/ero_nirspec_ifu_02729_demo.ipynb index e4cfcac37..58fd4d1cb 100644 --- a/notebooks/NIRSpec_IFU_spectral_extraction/ero_nirspec_ifu_02729_demo.ipynb +++ b/notebooks/NIRSpec_IFU_spectral_extraction/ero_nirspec_ifu_02729_demo.ipynb @@ -68,47 +68,42 @@ "metadata": {}, "outputs": [], "source": [ - "#Import Library\n", + "# Import Library\n", "\n", - "#--------------------------------------JWST Calibration Pipeline Imports-------------------------------------------\n", + "# --------------------------------------JWST Calibration Pipeline Imports-------------------------------------------\n", "\n", "import jwst\n", "import crds\n", "from jwst import datamodels\n", - "from jwst.pipeline import Detector1Pipeline #calwebb_detector1\n", - "from jwst.pipeline import Spec2Pipeline #calwebb_spec2\n", - "from jwst.pipeline import Spec3Pipeline #calwebb_spec3\n", - "from jwst.extract_1d import Extract1dStep #Extract1D Individual Step\n", + "from jwst.pipeline import Detector1Pipeline # calwebb_detector1\n", + "from jwst.pipeline import Spec2Pipeline # calwebb_spec2\n", + "from jwst.pipeline import Spec3Pipeline # calwebb_spec3\n", "\n", "print(\"JWST Calibration Pipeline Version={}\".format(jwst.__version__))\n", "print(\"Current Operational CRDS Context = {}\".format(crds.get_default_context()))\n", "\n", - "#----------------------------------------------General Imports-----------------------------------------------------\n", + "# ----------------------------------------------General Imports-----------------------------------------------------\n", "\n", "import numpy as np\n", "import warnings\n", - "warnings.filterwarnings('ignore') #Set to 'default' to turn warnings back on\n", + "warnings.filterwarnings('ignore') # Set to 'default' to turn warnings back on\n", "\n", - "#--------------------------------------------File Operation Imports------------------------------------------------\n", + "# --------------------------------------------File Operation Imports------------------------------------------------\n", "\n", "import glob\n", "import os\n", - "import asdf\n", "import json\n", "from shutil import copy\n", "\n", - "#--------------------------------------------Astropy/Astroquery Imports--------------------------------------------\n", + "# --------------------------------------------Astropy/Astroquery Imports--------------------------------------------\n", "\n", "from astropy.io import fits\n", "from astropy import wcs\n", "from astropy.wcs import WCS\n", - "from astropy.visualization import ImageNormalize, ManualInterval, LogStretch, LinearStretch, AsinhStretch, SqrtStretch\n", - "from astropy.stats import sigma_clipped_stats\n", - "import astroquery\n", - "from astroquery.mast import Mast\n", + "from astropy.visualization import ImageNormalize, ManualInterval, LogStretch, LinearStretch, AsinhStretch\n", "from astroquery.mast import Observations\n", "\n", - "#------------------------------------------------Plotting Imports--------------------------------------------------\n", + "# ------------------------------------------------Plotting Imports--------------------------------------------------\n", "\n", "import matplotlib.pyplot as plt\n", "import matplotlib as mpl\n", @@ -119,7 +114,7 @@ "# Use this version for non-interactive plots (easier scrolling of the notebook)\n", "%matplotlib inline\n", "# Use this version (outside of Jupyter Lab) if you want interactive plots\n", - "#%matplotlib notebook\n", + "# %matplotlib notebook\n", "\n", "# These gymnastics are needed to make the sizes of the figures\n", "# be the same in both the inline and notebook versions\n", @@ -184,7 +179,7 @@ " norm = ImageNormalize(data_2d, interval=ManualInterval(vmin=vmin, vmax=vmax),\n", " stretch=AsinhStretch())\n", " \n", - " #--------------------------------------------Set Up Figure-------------------------------------------\n", + " # --------------------------------------------Set Up Figure-------------------------------------------\n", "\n", " fig = plt.figure(figsize=(xsize, ysize))\n", " ax = fig.add_subplot(1, 1, 1)\n", @@ -198,9 +193,9 @@ " if title:\n", " plt.title(title)\n", "\n", - " #Zoom in on a portion of the image? \n", + " # Zoom in on a portion of the image? \n", " if zoom_in:\n", - " #inset axis \n", + " # inset axis \n", " axins = ax.inset_axes([0.5, 0.6, 0.5, 0.3])\n", " \n", " axins.imshow(data_2d, origin=\"lower\", norm=norm, aspect=aspect, cmap=cmap)\n", @@ -210,7 +205,7 @@ " axins.set_ylim(zoom_in[2], zoom_in[3])\n", " axins.set_xticklabels([])\n", " axins.set_yticklabels([])\n", - " ax.indicate_inset_zoom(axins, color=\"black\",edgecolor=\"black\", linewidth=3)" + " ax.indicate_inset_zoom(axins, color=\"black\", edgecolor=\"black\", linewidth=3)" ] }, { @@ -220,7 +215,7 @@ "metadata": {}, "outputs": [], "source": [ - "def show_ifu_cubeslices(s3d_file_list, wavelength_slices=[], spaxel_locs=[], y_scale=None, cmap='jet', vmin_vmax = [[[0,15e1]]], save_figure=False, title=None, title_font = 30):\n", + "def show_ifu_cubeslices(s3d_file_list, wavelength_slices=[], spaxel_locs=[], y_scale=None, cmap='jet', vmin_vmax=[[[0, 15e1]]], save_figure=False, title=None, title_font=30):\n", " \"\"\"\n", " Function to that takes a 3-D IFU data cube and generates: \n", " \n", @@ -256,48 +251,48 @@ " #---------------------------------------------- Set-up Figure -------------------------------------------------\n", "\n", " #Plot Slices From the Cube\n", - " fig, axs = plt.subplots(3, np.array(wavelength_slices).size, figsize=(8*np.array(wavelength_slices).size,18))\n", - " gs = grd.GridSpec(3, np.array(wavelength_slices).size, height_ratios=[1]*3, width_ratios=[1]*np.array(wavelength_slices).size, hspace=0.4,wspace=0.7)\n", + " fig, axs = plt.subplots(3, np.array(wavelength_slices).size, figsize=(8*np.array(wavelength_slices).size, 18))\n", + " gs = grd.GridSpec(3, np.array(wavelength_slices).size, height_ratios=[1]*3, width_ratios=[1]*np.array(wavelength_slices).size, hspace=0.4, wspace=0.7)\n", "\n", - " total_num_plots=3*np.array(wavelength_slices).size\n", + " total_num_plots = 3*np.array(wavelength_slices).size\n", " \n", " plot_count = 0\n", - " #---------------------------------------------Open Files------------------------------------------------------\n", + " # ---------------------------------------------Open Files------------------------------------------------------\n", " \n", " for s3d_file in s3d_file_list:\n", " \n", - " root=s3d_file[:-9] #Root file name \n", + " root = s3d_file[:-9] # Root file name \n", "\n", - " s3d = fits.open(s3d_file) #3-D IFU data cube fits file \n", - " x1d3 = datamodels.open(root+'_x1d.fits') #1-D Extracted Spectrum \n", + " s3d = fits.open(s3d_file) # 3-D IFU data cube fits file \n", + " x1d3 = datamodels.open(root+'_x1d.fits') # 1-D Extracted Spectrum \n", " \n", - " #--------------------------------Wavelength & Surface Brightness/Flux Arrays------------------------------\n", + " # --------------------------------Wavelength & Surface Brightness/Flux Arrays------------------------------\n", " \n", " x1d3wave = x1d3.spec[0].spec_table.WAVELENGTH\n", " \n", - " #--------------------------------------Data & Header Information------------------------------------------\n", + " # --------------------------------------Data & Header Information------------------------------------------\n", "\n", " \n", - " #SCI Extension: [Type:ImageHDU Cards:92 Dimensions:(57, 61, 973) Format:float32]\n", + " # SCI Extension: [Type:ImageHDU Cards:92 Dimensions:(57, 61, 973) Format:float32]\n", " cube = s3d[1].data #Science data\n", - " wcs = WCS(s3d[1].header) #World Coordinate System (WCS) Transformation keywords \n", + " wcs = WCS(s3d[1].header) # World Coordinate System (WCS) Transformation keywords \n", " wmap = s3d[4].data #3-D weight image giving the relative weights of the output spaxels.\n", - " cdelt1 = s3d[1].header['CDELT1']*3600. #Axis 1 coordinate increment at reference point \n", - " cdelt2 = s3d[1].header['CDELT2']*3600. #Axis 2 coordinate increment at reference point \n", - " cdelt3 = s3d[1].header['CDELT3'] #Axis 3 coordinate increment at reference point \n", - " crval3 = s3d[1].header['CRVAL3'] #third axis value at the reference pixel \n", + " cdelt1 = s3d[1].header['CDELT1']*3600. # Axis 1 coordinate increment at reference point \n", + " cdelt2 = s3d[1].header['CDELT2']*3600. # Axis 2 coordinate increment at reference point \n", + " cdelt3 = s3d[1].header['CDELT3'] # Axis 3 coordinate increment at reference point \n", + " crval3 = s3d[1].header['CRVAL3'] # third axis value at the reference pixel \n", "\n", - " #Wavelength range of the grating/filter combination\n", + " # Wavelength range of the grating/filter combination\n", " wavstart = s3d[1].header['WAVSTART']\n", " wavend = s3d[1].header['WAVEND']\n", " s3d.close()\n", " \n", - " #---------------------------------------------------Plots-------------------------------------------------\n", + " # ---------------------------------------------------Plots-------------------------------------------------\n", " \n", - " cmap_custom = cm.colors.LinearSegmentedColormap.from_list(\"\", [\"darkred\",\"darkturquoise\",\"blue\"])\n", + " cmap_custom = cm.colors.LinearSegmentedColormap.from_list(\"\", [\"darkred\", \"darkturquoise\", \"blue\"])\n", " colors = cmap_custom(np.linspace(0, 1, np.array(wavelength_slices).size))\n", "\n", - " #To Account for if NRS1 & NRS2 are both being plotted Side-by-side\n", + " # To Account for if NRS1 & NRS2 are both being plotted Side-by-side\n", " if len(wavelength_slices) != 1:\n", " if 'nrs1' in s3d_file:\n", " wavelengths = wavelength_slices[0]\n", @@ -322,14 +317,14 @@ " y_scales = y_scale[0]\n", "\n", " \n", - " #Loop through each wavelength slices\n", + " # Loop through each wavelength slices\n", " for i, wave_slice in enumerate(wavelengths):\n", "\n", " if float(wavstart)<=wave_slice*10**-6<=float(wavend):\n", " \n", - " #--------------------------------------------2-D Cube Slice------------------------------------------------\n", + " # --------------------------------------------2-D Cube Slice------------------------------------------------\n", " \n", - " #Min & Max Image Values & Scaling\n", + " # Min & Max Image Values & Scaling\n", " if len(vmin_vmax_vals) != 1:\n", " vmax_val = vmin_vmax_vals[i][1]\n", " vmin_val = vmin_vmax_vals[i][0]\n", @@ -338,23 +333,23 @@ " vmin_val = vmin_vmax_vals[0][0]\n", "\n", " slicewave = wave_slice\n", - " nslice = int((slicewave - crval3)/cdelt3) #the slice of the cube we want to plot\n", - " ax1 = plt.subplot(gs[0+plot_count], projection=wcs, slices=('x', 'y', nslice)) #set up the subplot space\n", - " #ax1 = plt.subplot(3,len(wavelength_slices), 0+plot_count, projection=wcs, slices=('x', 'y', nslice)) #set up the subplot space\n", + " nslice = int((slicewave - crval3)/cdelt3) # the slice of the cube we want to plot\n", + " ax1 = plt.subplot(gs[0+plot_count], projection=wcs, slices=('x', 'y', nslice)) # set up the subplot space\n", + " # ax1 = plt.subplot(3,len(wavelength_slices), 0+plot_count, projection=wcs, slices=('x', 'y', nslice)) #set up the subplot space\n", "\n", - " slice_mean = np.nanmean(cube[(nslice-2):(nslice+2), :, :], axis=0) #Mean of the slice looking in the range (nslice-2):(nslice+2)\n", - " slice_norm=ImageNormalize(slice_mean, vmin=vmin_val, vmax=vmax_val, stretch=AsinhStretch()) #normalize &stretch \n", - " slice_image= ax1.imshow(slice_mean, norm=slice_norm, origin='lower', aspect='auto',cmap=cmap) #plot slice\n", + " slice_mean = np.nanmean(cube[(nslice-2):(nslice+2), :, :], axis=0) # Mean of the slice looking in the range (nslice-2):(nslice+2)\n", + " slice_norm=ImageNormalize(slice_mean, vmin=vmin_val, vmax=vmax_val, stretch=AsinhStretch()) # normalize &stretch \n", + " slice_image= ax1.imshow(slice_mean, norm=slice_norm, origin='lower', aspect='auto',cmap=cmap) # plot slice\n", "\n", " cb_image = fig.colorbar(slice_image, fraction=0.046, pad=0.04)\n", - " cb_image.set_label('MJy/sr', labelpad=-1, fontsize = 22)\n", + " cb_image.set_label('MJy/sr', labelpad=-1, fontsize=22)\n", " cb_image.ax.tick_params(labelsize=20)\n", " cb_image.ax.yaxis.get_offset_text().set_fontsize(20)\n", " \n", - " ax1.set_xlabel('RA', fontsize =22)\n", + " ax1.set_xlabel('RA', fontsize=22)\n", " ax1.set_ylabel('DEC', labelpad=-1, fontsize=22)\n", " #ax1.grid(color='white', ls='solid')\n", - " ax1.set_title('Detector {} \\n Grating/Filter: {}/{} \\n {} microns'.format(s3d[0].header['DETECTOR'],s3d[0].header['GRATING'], s3d[0].header['FILTER'], str(slicewave)), fontsize =25)\n", + " ax1.set_title('Detector {} \\n Grating/Filter: {}/{} \\n {} microns'.format(s3d[0].header['DETECTOR'],s3d[0].header['GRATING'], s3d[0].header['FILTER'], str(slicewave)), fontsize=25)\n", " ax1.tick_params(axis='both', which='major', labelsize=20)\n", " ax1.coords[0].set_ticklabel(rotation=13, ha='right', pad=24)\n", "\n", @@ -390,15 +385,15 @@ " ax2.yaxis.set_tick_params(labelsize=20)\n", " ax2.set_aspect(0.5/ax2.get_data_ratio())\n", " \n", - " #-----------------------------------------------Weight Map-------------------------------------------------\n", + " # -----------------------------------------------Weight Map-------------------------------------------------\n", " \n", - " #Corresponding Weight Map (wmap) for Cube Slice\n", + " # Corresponding Weight Map (wmap) for Cube Slice\n", " ax3 = plt.subplot(gs[int(total_num_plots)-np.array(wavelength_slices).size+plot_count], projection=wcs, slices=('x', 'y', nslice)) #set up the subplot space\n", - " #ax3 = plt.subplot(3, len(wavelength_slices), int(total_num_plots)-len(wavelength_slices)+plot_count, projection=wcs, slices=('x', 'y', nslice)) #set up the subplot space\n", + " # ax3 = plt.subplot(3, len(wavelength_slices), int(total_num_plots)-len(wavelength_slices)+plot_count, projection=wcs, slices=('x', 'y', nslice)) #set up the subplot space\n", " \n", - " slice_mean_wmap = np.nanmean(wmap[(nslice-2):(nslice+2), :, :], axis=0) #Mean of the wmap slice looking in the range (nslice-2):(nslice+2)\n", - " slice_norm_wmap=ImageNormalize(slice_mean_wmap, stretch=AsinhStretch()) #normalize &stretch\n", - " slice_wmap = ax3.imshow(slice_mean_wmap, norm=slice_norm_wmap, origin='lower',aspect='auto', cmap=cmap) #plot slice\n", + " slice_mean_wmap = np.nanmean(wmap[(nslice-2):(nslice+2), :, :], axis=0) # Mean of the wmap slice looking in the range (nslice-2):(nslice+2)\n", + " slice_norm_wmap=ImageNormalize(slice_mean_wmap, stretch=AsinhStretch()) # normalize &stretch\n", + " slice_wmap = ax3.imshow(slice_mean_wmap, norm=slice_norm_wmap, origin='lower',aspect='auto', cmap=cmap) # plot slice\n", "\n", " cb_wmap = fig.colorbar(slice_wmap, fraction=0.046, pad=0.04)\n", " cb_wmap.set_label('Weight', labelpad=-1, fontsize = 22)\n", @@ -407,7 +402,7 @@ " \n", " ax3.set_xlabel('RA', fontsize=22)\n", " ax3.set_ylabel('DEC', labelpad=-1, fontsize=22)\n", - " #ax3.grid(color='gray', ls='solid')\n", + " # ax3.grid(color='gray', ls='solid')\n", " ax3.set_title(str(slicewave)+' microns: Weight Map', fontsize=25)\n", " ax3.tick_params(axis='both', which='major', labelsize=20)\n", " ax3.coords[0].set_ticklabel(rotation=13, ha='right', pad=24)\n", @@ -444,14 +439,14 @@ "metadata": {}, "outputs": [], "source": [ - "#To rerun the notebook and all the pipeline steps set runflag=True\n", + "# To rerun the notebook and all the pipeline steps set runflag=True\n", "runflag = True \n", "\n", - "#Demo directory -- contains pre-computed products\n", + "# Demo directory -- contains pre-computed products\n", "if runflag == False:\n", " output_dir = './nirspec_ifu_02729_demo/'\n", "\n", - "#Rerun directory\n", + "# Rerun directory\n", "elif runflag == True:\n", " #If you want to actually re-download the data and run everything offline, \n", " #then comment out this line, set runflag=True, & specify a desired local directory\n", @@ -502,9 +497,9 @@ }, "outputs": [], "source": [ - "#Download data from MAST \n", + "# Download data from MAST \n", "\n", - "#Setup your account \n", + "# Setup your account \n", "\n", "# NOTE:\n", "# The data in this notebook is public and does not require a token.\n", @@ -515,37 +510,37 @@ "\n", "sessioninfo = Observations.session_info()\n", "\n", - "#Define the general search criteria\n", + "# Define the general search criteria\n", "obs = Observations.query_criteria(\n", - " obs_collection = 'JWST',\n", - " instrument_name = ['NIRSPEC/IFU'],\n", - " proposal_id = '02729')\n", + " obs_collection='JWST',\n", + " instrument_name=['NIRSPEC/IFU'],\n", + " proposal_id='02729')\n", "\n", - "#Print the Observations returned from the general serach criteria\n", + "# Print the Observations returned from the general search criteria\n", "products = Observations.get_product_list(obs)\n", - "#print(products)\n", + "# print(products)\n", "\n", - "#Filter the list of observations\n", - "#In this case we look for UNCAL products and ASN files to manually run pipeline stage 1-3\n", - "#We also look for pre-processed MAST products for comparison: RATE (stage 1) & CAL (stage 2&3) & S3D (stage 2&3) & X1D (stage2&3) \n", + "# Filter the list of observations\n", + "# In this case we look for UNCAL products and ASN files to manually run pipeline stage 1-3\n", + "# We also look for pre-processed MAST products for comparison: RATE (stage 1) & CAL (stage 2&3) & S3D (stage 2&3) & X1D (stage2&3) \n", "filtered = Observations.filter_products(products,\n", " productSubGroupDescription=[\"UNCAL\", \"RATE\", \"CAL\", \"S3D\", \"X1D\", \"ASN\"],\n", " mrp_only=False)\n", - "#Print the filtered products \n", + "# Print the filtered products \n", "number = len(filtered)\n", "for k in range(number):\n", " print(filtered['productFilename'][k])\n", "\n", - "#Download the filtered products\n", - "#This creates a mastDownload directory, unless you set flat=True and set a download_dir\n", + "# Download the filtered products\n", + "# This creates a mastDownload directory, unless you set flat=True and set a download_dir\n", "for i in range(len(filtered)):\n", " mast_products_dir = output_dir+'mast_products/'\n", " if not os.path.exists(mast_products_dir):\n", " os.makedirs(mast_products_dir)\n", " if runflag == True:\n", - " Observations.download_products(filtered[i], mrp_only=False, cache=False, flat=True, download_dir=mast_products_dir) #Override any cached files and download the most up-to-date ones\n", + " Observations.download_products(filtered[i], mrp_only=False, cache=False, flat=True, download_dir=mast_products_dir) # Override any cached files and download the most up-to-date ones\n", " else:\n", - " Observations.download_products(filtered[i], mrp_only=False, cache=True, flat=True, download_dir=mast_products_dir) #Find any cached files first before downloading new ones" + " Observations.download_products(filtered[i], mrp_only=False, cache=True, flat=True, download_dir=mast_products_dir) # Find any cached files first before downloading new ones" ] }, { @@ -579,17 +574,17 @@ }, "outputs": [], "source": [ - "#Stage 1 slope products -- level 2a images\n", + "# Stage 1 slope products -- level 2a images\n", "\n", - "#Plot 4th (out of 8) dither position (spectra fall on both NRS1 & NRS2) for GRATING/FILTER G235H/F170LP combination \n", + "# Plot 4th (out of 8) dither position (spectra fall on both NRS1 & NRS2) for GRATING/FILTER G235H/F170LP combination \n", "for rate_file in sorted(glob.glob(mast_products_dir+'*02103*00004_nrs?_rate.fits')):\n", " \n", " ratefile_open = datamodels.open(rate_file)\n", " ratefile_sci = ratefile_open.data #get the pixel data (the SCI extension of the fits file)\n", " ratefile_dq = ratefile_open.dq #data quality map data (DQ extension)\n", " \n", - " #Plot the slope image and small section of the countrate image & corresponding section of the DQ map\n", - " show_image(ratefile_sci, 0,10, units='DN/s',zoom_in=[650,700, 1250,1300], ysize=20, xsize=20,\n", + " # Plot the slope image and small section of the countrate image & corresponding section of the DQ map\n", + " show_image(ratefile_sci, 0, 10, units='DN/s', zoom_in=[650, 700, 1250, 1300], ysize=20, xsize=20,\n", " title='Countrate Image \\n Detector: {} \\n 8-Cycle Dither Position Index: {} \\n GRATING/FILTER: {}/{}'.format(ratefile_open.meta.instrument.detector,\n", " ratefile_open.meta.dither.position_number, \n", " ratefile_open.meta.instrument.grating,\n", @@ -597,9 +592,9 @@ " \n", " show_image(ratefile_dq, 0, 10, units='Bit Value', scale='linear',zoom_in=[650,700, 1250,1300], ysize=20, xsize=20,\n", " title='Data Quality Map \\n Detector: {} \\n 8-Cycle Dither Position Index: {} \\n GRATING/FILTER: {}/{}'.format(ratefile_open.meta.instrument.detector,\n", - " ratefile_open.meta.dither.position_number, \n", - " ratefile_open.meta.instrument.grating,\n", - " ratefile_open.meta.instrument.filter)) \n", + " ratefile_open.meta.dither.position_number, \n", + " ratefile_open.meta.instrument.grating,\n", + " ratefile_open.meta.instrument.filter)) \n", " " ] }, @@ -631,9 +626,9 @@ "metadata": {}, "outputs": [], "source": [ - "#Stage 2 Products -- Calibrated 3-D data cubes for each GRATING/FILTER combination\n", + "# Stage 2 Products -- Calibrated 3-D data cubes for each GRATING/FILTER combination\n", "\n", - "#Plotting the 4th (out of 8) dither position for both NRS1 and NRS2\n", + "# Plotting the 4th (out of 8) dither position for both NRS1 and NRS2\n", "s3d_g140h_stage2 = sorted(glob.glob(mast_products_dir+'*2105*00004_nrs?_s3d.fits'))\n", "s3d_g235h_stage2 = sorted(glob.glob(mast_products_dir+'*2103*00004_nrs?_s3d.fits'))\n", "s3d_g395h_stage2 = sorted(glob.glob(mast_products_dir+'*2101*00004_nrs?_s3d.fits'))\n", @@ -641,23 +636,23 @@ "\n", "title_stage2_mast='Tarantula Nebula \\n Level 2 IFU Product: 3-D Cube Slices vs. Corresponding 3-D Weighted Map'\n", "\n", - "#Characteristics of the plot \n", - "nrs1_wavelengths = [1.0,2.3,3.4] #Wavelength slices (microns) to take from the 3-D data cube\n", - "nrs2_wavelengths = [1.4,2.5,4.0]\n", + "# Characteristics of the plot \n", + "nrs1_wavelengths = [1.0, 2.3, 3.4] # Wavelength slices (microns) to take from the 3-D data cube\n", + "nrs2_wavelengths = [1.4, 2.5, 4.0]\n", "\n", - "nrs1_spaxel_locs = [[30,29],[28,39],[14,25]] #Spaxel locations for associated 1-D spectrum (one spaxel plotted per slice)\n", - "nrs2_spaxel_locs = [[30,29],[28,39],[14,25]]\n", + "nrs1_spaxel_locs = [[30, 29], [28, 39], [14, 25]] # Spaxel locations for associated 1-D spectrum (one spaxel plotted per slice)\n", + "nrs2_spaxel_locs = [[30, 29], [28, 39], [14, 25]]\n", "\n", - "nrs1_vmin_vmax = [[0,2e2],[0,1e2],[0,1.2e3]] #Minimum & Maximum signal values for scaling each slice\n", - "nrs2_vmin_vmax = [[0,2e2],[0,1e2],[0,1.2e3]]\n", + "nrs1_vmin_vmax = [[0, 2e2], [0, 1e2], [0, 1.2e3]] # Minimum & Maximum signal values for scaling each slice\n", + "nrs2_vmin_vmax = [[0, 2e2], [0, 1e2], [0, 1.2e3]]\n", "\n", - "nrs1_yscales = [[-80,150], [-80,150], [-80,200]] #Spaxel plot y-limits\n", - "nrs2_yscales = [[-80,200], [-80,150], [-80,200]]\n", + "nrs1_yscales = [[-80, 150], [-80, 150], [-80, 200]] # Spaxel plot y-limits\n", + "nrs2_yscales = [[-80, 200], [-80, 150], [-80, 200]]\n", "\n", - "#Plot using the convience function defined above\n", - "show_ifu_cubeslices(s3d_stage2_list, wavelength_slices=[nrs1_wavelengths,nrs2_wavelengths], \n", - " spaxel_locs=[nrs1_spaxel_locs,nrs2_spaxel_locs],vmin_vmax=[nrs1_vmin_vmax,nrs2_vmin_vmax], \n", - " y_scale = [nrs1_yscales,nrs2_yscales], title=title_stage2_mast)" + "# Plot using the convience function defined above\n", + "show_ifu_cubeslices(s3d_stage2_list, wavelength_slices=[nrs1_wavelengths, nrs2_wavelengths], \n", + " spaxel_locs=[nrs1_spaxel_locs, nrs2_spaxel_locs], vmin_vmax=[nrs1_vmin_vmax, nrs2_vmin_vmax], \n", + " y_scale=[nrs1_yscales, nrs2_yscales], title=title_stage2_mast)" ] }, { @@ -676,22 +671,22 @@ "metadata": {}, "outputs": [], "source": [ - "#Stage 3 Products -- Combined Calibrated 3-D data cubes for each GRATING/FILTER combination\n", + "# Stage 3 Products -- Combined Calibrated 3-D data cubes for each GRATING/FILTER combination\n", "\n", "s3d_stage3_list = sorted(glob.glob(mast_products_dir+'*nirspec*_s3d.fits'))\n", "\n", - "title_stage3_mast='Tarantula Nebula \\n Level 3 IFU Product: 3-D Cube Slices vs. Corresponding 3-D Weighted Map'\n", + "title_stage3_mast = 'Tarantula Nebula \\n Level 3 IFU Product: 3-D Cube Slices vs. Corresponding 3-D Weighted Map'\n", "\n", - "#Characteristics of the plot \n", - "wavelengths = [1.4,2.3,4.0] #Wavelength slices (microns) to take from the combined 3-D data cube\n", - "spaxel_locs = [[30,29],[28,39],[14,25]] #Spaxel locations for associated 1-D spectrum (one spaxel plotted per slice)\n", - "vmin_vmax = [[0,2e2],[0,1e2],[0,1.2e3]] #Minimum & Maximum signal values for scaling each slice\n", - "yscales = [[-80,150], [-80,150], [-80,200]] #Spaxel plot y-limits\n", + "# Characteristics of the plot \n", + "wavelengths = [1.4, 2.3, 4.0] # Wavelength slices (microns) to take from the combined 3-D data cube\n", + "spaxel_locs = [[30, 29], [28, 39], [14, 25]] # Spaxel locations for associated 1-D spectrum (one spaxel plotted per slice)\n", + "vmin_vmax = [[0, 2e2], [0, 1e2], [0, 1.2e3]] # Minimum & Maximum signal values for scaling each slice\n", + "yscales = [[-80, 150], [-80, 150], [-80, 200]] # Spaxel plot y-limits\n", "\n", - "#Plot using the convience function defined above\n", - "show_ifu_cubeslices(s3d_stage3_list, wavelength_slices=[wavelengths],spaxel_locs=[spaxel_locs],\n", + "# Plot using the convience function defined above\n", + "show_ifu_cubeslices(s3d_stage3_list, wavelength_slices=[wavelengths], spaxel_locs=[spaxel_locs],\n", " vmin_vmax=[vmin_vmax], \n", - " y_scale = [yscales], title=title_stage3_mast)" + " y_scale=[yscales], title=title_stage3_mast)" ] }, { @@ -712,9 +707,9 @@ "metadata": {}, "outputs": [], "source": [ - "#Stage 3 Products -- Combined Extracted 1-D Spectrum \n", + "# Stage 3 Products -- Combined Extracted 1-D Spectrum \n", "\n", - "fig = plt.figure(figsize=(15,9))\n", + "fig = plt.figure(figsize=(15, 9))\n", "colors = ['darkred', 'darkturquoise', 'blue']\n", "\n", "x1d3_mast_list = sorted(glob.glob(mast_products_dir+'*nirspec*_x1d.fits'))\n", @@ -722,20 +717,20 @@ "for i, x1d3_file in enumerate(x1d3_mast_list):\n", " x1d3_file_open = datamodels.open(x1d3_file) \n", " \n", - " #Wavelength & Surface Brightness Arrays\n", + " # Wavelength & Surface Brightness Arrays\n", " x1d3wave_mast = x1d3_file_open.spec[0].spec_table.WAVELENGTH\n", " x1d3flux_mast = x1d3_file_open.spec[0].spec_table.SURF_BRIGHT\n", " \n", - " plt.plot(x1d3wave_mast,x1d3flux_mast, linewidth =2, color=colors[i], label='Grating/Filter: {}/{}'.format(x1d3_file_open.meta.instrument.grating,\n", + " plt.plot(x1d3wave_mast, x1d3flux_mast, linewidth =2, color=colors[i], label='Grating/Filter: {}/{}'.format(x1d3_file_open.meta.instrument.grating,\n", " x1d3_file_open.meta.instrument.filter))\n", - "#Where wavelength slice was taken above\n", + "# Where wavelength slice was taken above\n", "plt.vlines(1.4, -1e1, 400., 'black', 'dotted', label='1.4 microns', linewidth=5)\n", - "plt.vlines(2.3, -1e1, 400., 'black', 'dotted', label='2.3 microns', linewidth =5)\n", + "plt.vlines(2.3, -1e1, 400., 'black', 'dotted', label='2.3 microns', linewidth=5)\n", "plt.vlines(4.0, -1e1, 400., 'black', 'dotted', label='4.0 microns', linewidth=5)\n", "\n", - "plt.xlabel('$\\lambda [\\mu$m]', fontsize =15)\n", - "plt.ylabel('Surface Brightness (MJy/sr)', fontsize =15)\n", - "plt.title(\"Tarantula Nebula \\n Level 3 IFU Product in MAST: Extracted 1-D Spectrum\", fontsize =20)\n", + "plt.xlabel('$\\lambda [\\mu$m]', fontsize=15)\n", + "plt.ylabel('Surface Brightness (MJy/sr)', fontsize=15)\n", + "plt.title(\"Tarantula Nebula \\n Level 3 IFU Product in MAST: Extracted 1-D Spectrum\", fontsize=20)\n", "plt.ylim(-1e1, 2e2)\n", "plt.legend()" ] @@ -782,7 +777,7 @@ "metadata": {}, "outputs": [], "source": [ - "#Just a check to see what verison of the pipeline and what pmap was used\n", + "# Just a check to see what verison of the pipeline and what pmap was used\n", "x1d3_mast = fits.open(glob.glob(mast_products_dir+'*_x1d.fits')[0])\n", "\n", "print(\"Products found in MAST used JWST calibration pipeline version: {} and {}\".format(x1d3_mast[0].header['CAL_VER']\n", @@ -807,7 +802,7 @@ "metadata": {}, "outputs": [], "source": [ - "#Directory for rerun of stage 1 to avoid overwritting MAST products\n", + "# Directory for rerun of stage 1 to avoid overwritting MAST products\n", "output_dir_rerun = output_dir+'rerun/' \n", "if not os.path.exists(output_dir_rerun):\n", " os.makedirs(output_dir_rerun)" @@ -831,7 +826,7 @@ }, "outputs": [], "source": [ - "#Stage 1 Processing \n", + "# Stage 1 Processing \n", "\n", "if runflag == True:\n", "\n", @@ -840,8 +835,8 @@ " print(\"Applying Stage 1 Corrections & Calibrations to: \"+ os.path.basename(uncal_file))\n", "\n", " result = Detector1Pipeline.call(uncal_file,\n", - " save_results = True,\n", - " output_dir = output_dir_rerun)" + " save_results=True,\n", + " output_dir=output_dir_rerun)" ] }, { @@ -853,9 +848,9 @@ }, "outputs": [], "source": [ - "#Stage 1 slope products -- level 2a images\n", + "# Stage 1 slope products -- level 2a images\n", "\n", - "#Plot 4th (out of 8) dither position (spectra fall on both NRS1 & NRS2) for GRATING/FILTER G235H/F170LP combination \n", + "# Plot 4th (out of 8) dither position (spectra fall on both NRS1 & NRS2) for GRATING/FILTER G235H/F170LP combination \n", "for rate_file in sorted(glob.glob(output_dir_rerun+'*02103*00004_nrs?_rate.fits')):\n", " \n", " ratefile_open = datamodels.open(rate_file)\n", @@ -863,17 +858,17 @@ " ratefile_dq = ratefile_open.dq #data quality map data (DQ extension)\n", " \n", " #Plot the slop image and zoom in on a small section of the countrate image & corresponding section of the DQ map\n", - " show_image(ratefile_sci, 0,10, units='DN/s',zoom_in=[650,700, 1250,1300], ysize=20, xsize=20,\n", + " show_image(ratefile_sci, 0, 10, units='DN/s',zoom_in=[650, 700, 1250, 1300], ysize=20, xsize=20,\n", " title='Countrate Image \\n Detector: {} \\n 8-Cycle Dither Position Index: {} \\n GRATING/FILTER: {}/{}'.format(ratefile_open.meta.instrument.detector,\n", " ratefile_open.meta.dither.position_number, \n", " ratefile_open.meta.instrument.grating,\n", " ratefile_open.meta.instrument.filter)) #rate files have units of DN/s\n", " \n", - " show_image(ratefile_dq, 0, 10, units='Bit Value', scale='linear',zoom_in=[650,700, 1250,1300], ysize=20, xsize=20,\n", + " show_image(ratefile_dq, 0, 10, units='Bit Value', scale='linear', zoom_in=[650,700, 1250,1300], ysize=20, xsize=20,\n", " title='Data Quality Map \\n Detector: {} \\n 8-Cycle Dither Position Index: {} \\n GRATING/FILTER: {}/{}'.format(ratefile_open.meta.instrument.detector,\n", - " ratefile_open.meta.dither.position_number, \n", - " ratefile_open.meta.instrument.grating,\n", - " ratefile_open.meta.instrument.filter)) \n", + " ratefile_open.meta.dither.position_number, \n", + " ratefile_open.meta.instrument.grating,\n", + " ratefile_open.meta.instrument.filter)) \n", " " ] }, @@ -916,7 +911,7 @@ }, "outputs": [], "source": [ - "#Stage 2 Processing \n", + "# Stage 2 Processing \n", "\n", "if runflag == True:\n", " \n", @@ -926,8 +921,8 @@ " print(\"Applying Stage 2 Calibrations & Corrections to: \"+ os.path.basename(rate_file))\n", " \n", " result = Spec2Pipeline.call(rate_file,\n", - " save_results = True,\n", - " output_dir = output_dir_rerun) " + " save_results=True,\n", + " output_dir=output_dir_rerun) " ] }, { @@ -939,30 +934,30 @@ }, "outputs": [], "source": [ - "#Stage 2 Products -- Calibrated 3-D data cubes for each GRATING/FILTER combination\n", + "# Stage 2 Products -- Calibrated 3-D data cubes for each GRATING/FILTER combination\n", "\n", - "#Plotting the 4th (out of 8) dither position for both NRS1 and NRS2\n", + "# Plotting the 4th (out of 8) dither position for both NRS1 and NRS2\n", "s3d_stage2_list = sorted(glob.glob(output_dir_rerun+'*2103*00004_nrs?_s3d.fits'))\n", "\n", "title_stage2_rerun='Tarantula Nebula \\n Level 2 IFU Product: 3-D Cube Slices vs. Corresponding 3-D Weighted Map'\n", "\n", - "#Characteristics of the plot \n", - "nrs1_wavelengths = [2.3] #Wavelength slices (microns) to take from the 3-D data cube\n", + "# Characteristics of the plot \n", + "nrs1_wavelengths = [2.3] # Wavelength slices (microns) to take from the 3-D data cube\n", "nrs2_wavelengths = [2.5]\n", "\n", - "nrs1_spaxel_locs = [[28,39]] #Spaxel locations for associated 1-D spectrum (one spaxel plotted per slice)\n", - "nrs2_spaxel_locs = [[28,39]]\n", + "nrs1_spaxel_locs = [[28, 39]] # Spaxel locations for associated 1-D spectrum (one spaxel plotted per slice)\n", + "nrs2_spaxel_locs = [[28, 39]]\n", "\n", - "nrs1_vmin_vmax = [[0,1e2]] #Minimum & Maximum signal values for scaling each slice\n", - "nrs2_vmin_vmax = [[0,1e2]]\n", + "nrs1_vmin_vmax = [[0, 1e2]] # Minimum & Maximum signal values for scaling each slice\n", + "nrs2_vmin_vmax = [[0, 1e2]]\n", "\n", - "nrs1_yscales = [[-80,150]] #Spaxel plot y-limits\n", - "nrs2_yscales = [[-80,150]]\n", + "nrs1_yscales = [[-80, 150]] # Spaxel plot y-limits\n", + "nrs2_yscales = [[-80, 150]]\n", "\n", - "#Plot using the convience function defined above\n", - "show_ifu_cubeslices(s3d_stage2_list, wavelength_slices=[nrs1_wavelengths,nrs2_wavelengths], \n", - " spaxel_locs=[nrs1_spaxel_locs,nrs2_spaxel_locs],vmin_vmax=[nrs1_vmin_vmax,nrs2_vmin_vmax], \n", - " y_scale = [nrs1_yscales,nrs2_yscales], title=title_stage2_rerun)" + "# Plot using the convience function defined above\n", + "show_ifu_cubeslices(s3d_stage2_list, wavelength_slices=[nrs1_wavelengths, nrs2_wavelengths], \n", + " spaxel_locs=[nrs1_spaxel_locs, nrs2_spaxel_locs], vmin_vmax=[nrs1_vmin_vmax, nrs2_vmin_vmax], \n", + " y_scale=[nrs1_yscales, nrs2_yscales], title=title_stage2_rerun)" ] }, { @@ -989,7 +984,7 @@ }, "outputs": [], "source": [ - "#Copy ASN file from MAST (for G235H/F170LP) into the stage 1 rerun directory\n", + "# Copy ASN file from MAST (for G235H/F170LP) into the stage 1 rerun directory\n", "\n", "asnfile_mast = glob.glob(mast_products_dir+'*_spec3_00001_asn.json')[0] #ASN file found in MAST\n", "\n", @@ -997,7 +992,7 @@ "if not os.path.exists(asnfile_rerun):\n", " copy(asnfile_mast, asnfile_rerun)\n", " \n", - "#Check the ASN file contents\n", + "# Check the ASN file contents\n", "with open(asnfile_rerun, 'r') as f_obj:\n", " asnfile_rerun_data = json.load(f_obj)\n", " \n", @@ -1039,13 +1034,13 @@ }, "outputs": [], "source": [ - "#Rerun stage 3 with outlier detection off\n", + "# Rerun stage 3 with outlier detection off\n", "if runflag==True:\n", " \n", " result = Spec3Pipeline.call(asnfile_rerun,\n", - " save_results = True,\n", - " output_dir = output_dir_rerun,\n", - " steps = {\"outlier_detection\":{\"skip\": False,\n", + " save_results=True,\n", + " output_dir=output_dir_rerun,\n", + " steps={\"outlier_detection\": {\"skip\": False,\n", " \"save_results\": True,\n", " \"kernel_size\": '3 3'}})" ] @@ -1067,12 +1062,12 @@ "\n", "#Characteristics of the plot \n", "wavelengths = [2.3] #Wavelength slices (microns) to take from the combined 3-D data cube\n", - "spaxel_locs = [[28,39]] #Spaxel locations for associated 1-D spectrum (one spaxel plotted per slice)\n", - "vmin_vmax = [[0,1e2]] #Minimum & Maximum signal values for scaling each slice\n", - "yscales = [[-80,150]] #Spaxel plot y-limits\n", + "spaxel_locs = [[28, 39]] #Spaxel locations for associated 1-D spectrum (one spaxel plotted per slice)\n", + "vmin_vmax = [[0, 1e2]] #Minimum & Maximum signal values for scaling each slice\n", + "yscales = [[-80, 150]] #Spaxel plot y-limits\n", "\n", "#Plot using the convience function defined above\n", - "show_ifu_cubeslices(s3d_stage3_list, wavelength_slices=[wavelengths],spaxel_locs=[spaxel_locs],\n", + "show_ifu_cubeslices(s3d_stage3_list, wavelength_slices=[wavelengths], spaxel_locs=[spaxel_locs],\n", " vmin_vmax=[vmin_vmax], \n", " y_scale = [yscales], title=title_stage3_rerun, title_font=20)" ] @@ -1096,7 +1091,7 @@ "metadata": {}, "outputs": [], "source": [ - "#Stage 3 Products -- Combined Extracted 1-D Spectrum \n", + "# Stage 3 Products -- Combined Extracted 1-D Spectrum \n", "\n", "fig = plt.figure(figsize=(15,9))\n", "colors = ['darkred', 'darkturquoise', 'blue']\n", @@ -1106,13 +1101,13 @@ "for i, x1d3_file in enumerate(x1d3_rerun_list):\n", " x1d3_file_open = datamodels.open(x1d3_file) \n", " \n", - " #Wavelength & Surface Brightness Arrays\n", + " # Wavelength & Surface Brightness Arrays\n", " x1d3wave_rerun = x1d3_file_open.spec[0].spec_table.WAVELENGTH\n", " x1d3flux_rerun = x1d3_file_open.spec[0].spec_table.SURF_BRIGHT\n", " \n", - " plt.plot(x1d3wave_rerun,x1d3flux_rerun, linewidth =2, color=colors[i], label='Grating/Filter: {}/{}'.format(x1d3_file_open.meta.instrument.grating,\n", + " plt.plot(x1d3wave_rerun,x1d3flux_rerun, linewidth=2, color=colors[i], label='Grating/Filter: {}/{}'.format(x1d3_file_open.meta.instrument.grating,\n", " x1d3_file_open.meta.instrument.filter))\n", - "#Where wavelength slice was taken above\n", + "# Where wavelength slice was taken above\n", "plt.vlines(2.3, -1e1, 400., 'black', 'dotted', label='2.3 microns', linewidth =5)\n", "\n", "plt.xlabel('$\\lambda [\\mu$m]', fontsize =15)\n", @@ -1163,7 +1158,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.10" + "version": "3.11.6" } }, "nbformat": 4,