├── columnjump ├── columnjump │ ├── __init__.py │ ├── columnjump.py │ ├── columnjump_step.py │ └── rampbreaks.py ├── README.md ├── setup.py └── LICENSE ├── bpmreadnoise_nis006_20220620.cfg ├── dopersistflags.py ├── image1overf.py ├── README.md ├── checkifstar.py ├── dosnowballflags.py ├── makedarknoisefilesgdq.py ├── makenirissimagingflats.py ├── getipc.py ├── makenirissgrismflats.py └── LICENSE /columnjump/columnjump/__init__.py: -------------------------------------------------------------------------------- 1 | from .columnjump_step import ColumnJumpStep 2 | 3 | __version__ = '1.1.0' 4 | __all__ = ['ColumnJumpStep'] 5 | -------------------------------------------------------------------------------- /columnjump/README.md: -------------------------------------------------------------------------------- 1 | # Columnjump 2 | 3 | Performs column jump detection on each ramp integration within a JWST NIRISS exposure to correct for jumps in columns. Note that 'columns' are defined in 4 | original detector coordinates (not DMS coordinates) so appear in 3rd 5 | axis of 4D data array. Uses modified version of algorithm documented in CSA-JWST-TN-0003. 6 | 7 | It is intended this module be run during the DETECTOR1 pipeline between the dark current subtraction and jump detection step. 8 | 9 | Version 1.1.0 removes a dependency on the jwst pipeline version 10 | -------------------------------------------------------------------------------- /columnjump/setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r", encoding="utf-8") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="columnjump", # Replace with your own username 8 | version="1.1.0", 9 | author="Chris Willott", 10 | author_email="chriswillott1@gmail.com", 11 | description="Fix column jumps for JWST NIRISS detector", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/chriswillott/jwst/columnjump", 15 | packages=setuptools.find_packages(), 16 | classifiers=[ 17 | "Programming Language :: Python :: 3", 18 | "License :: OSI Approved :: MIT License", 19 | "Operating System :: OS Independent", 20 | ], 21 | python_requires='>=3.6', 22 | ) 23 | -------------------------------------------------------------------------------- /columnjump/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2021 The Python Packaging Authority 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /columnjump/columnjump/columnjump.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | 4 | from . import rampbreaks as rbreaks 5 | 6 | log = logging.getLogger(__name__) 7 | log.setLevel(logging.DEBUG) 8 | 9 | def detect_columnjumps (input_model, nsigma1jump, nsigma2jumps, outputdiagnostics): 10 | """ 11 | This is the high-level controlling routine for the column jump detection 12 | process. It loads and sets the various input data and parameters needed 13 | and then calls the detection method. 14 | """ 15 | 16 | # Load the data arrays that we need from the input model 17 | output_model = input_model.copy() 18 | data = input_model.data 19 | #err = input_model.err 20 | gdq = input_model.groupdq 21 | pdq = input_model.pixeldq 22 | 23 | ngroups = data.shape[1] 24 | nframes = input_model.meta.exposure.nframes 25 | filename = input_model.meta.filename 26 | filename = filename.replace('.fits','') 27 | 28 | # Apply the column jump detection and correction algorithm 29 | log.info('Executing column jump detection and correction algorithm') 30 | start = time.time() 31 | 32 | rbreaks.findfix_jumps(data, pdq, nsigma1jump, nsigma2jumps, nframes, filename, outputdiagnostics) 33 | 34 | elapsed = time.time() - start 35 | log.debug('Elapsed time = %g sec' %elapsed) 36 | 37 | # Update the arrays of the output model with the jump detection results 38 | output_model.data = data 39 | output_model.groupdq = gdq 40 | output_model.pixeldq = pdq 41 | 42 | return output_model 43 | -------------------------------------------------------------------------------- /columnjump/columnjump/columnjump_step.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | from jwst.stpipe import Step 4 | from jwst import datamodels 5 | from .columnjump import detect_columnjumps 6 | import time 7 | 8 | __all__ = ["ColumnJumpStep"] 9 | 10 | class ColumnJumpStep(Step): 11 | """ 12 | ColumnJumpStep: Performs column jump detection on each ramp integration within an 13 | exposure to correct for jumps in columns. 14 | Uses modified version of algorithm in CSA-JWST-TN-0003. 15 | """ 16 | 17 | spec = """ 18 | nsigma1jump = float(default=5.0,min=0) # sigma rejection threshold for one jump 19 | nsigma2jumps = float(default=3.0,min=0) # sigma rejection threshold for two jumps 20 | outputdiagnostics = boolean(default=False) # output table of columns corrected? 21 | """ 22 | 23 | #It is assumed that most bad reference pixels are flagged in the PixelDQ array of the data so no mask reference file is required. 24 | 25 | def process(self, input): 26 | 27 | with datamodels.RampModel(input) as input_model: 28 | tstart = time.time() 29 | 30 | # Check for consistency between keyword values and data shape 31 | ngroups = input_model.data.shape[1] 32 | ngroups_kwd = input_model.meta.exposure.ngroups 33 | if ngroups != ngroups_kwd: 34 | self.log.error("Keyword 'NGROUPS' value of '{0}' does not match data array size of '{1}'".format(ngroups_kwd,ngroups)) 35 | raise ValueError("Bad data dimensions") 36 | 37 | # Check for an input model with NGROUPS<=6. 38 | if ngroups <= 6: 39 | self.log.warn('Will not apply column jump detection when NGROUPS<=6;') 40 | self.log.warn('Column jump step will be skipped') 41 | result = input_model.copy() 42 | result.meta.cal_step.jump = 'SKIPPED' 43 | return result 44 | 45 | # Retrieve the parameter values 46 | nsigma1jump = self.nsigma1jump 47 | nsigma2jumps = self.nsigma2jumps 48 | outputdiagnostics = self.outputdiagnostics 49 | self.log.info('Sigma rejection threshold for one break = %g ', nsigma1jump) 50 | self.log.info('Sigma rejection threshold for two breaks = %g ', nsigma2jumps) 51 | self.log.info('Output Diagnostic files = %s ', outputdiagnostics) 52 | 53 | # Call the column jump detection routine 54 | result = detect_columnjumps(input_model, nsigma1jump, nsigma2jumps, outputdiagnostics) 55 | 56 | tstop = time.time() 57 | self.log.info('The execution time in seconds: %f', tstop - tstart) 58 | 59 | result.meta.cal_step.columnjump = 'COMPLETE' 60 | 61 | return result 62 | 63 | -------------------------------------------------------------------------------- /bpmreadnoise_nis006_20220620.cfg: -------------------------------------------------------------------------------- 1 | instrument: NIRISS 2 | author: Chris Willott 3 | pedigree: 'INFLIGHT 04/19/2022 04/23/2022' 4 | useafter: '2022-01-01T00:00:00' 5 | #Give FPA temperature for reference file header because not in raw data file headers 6 | fpa_temp: 39.03 7 | description_readnoise: This is a readnoise reference file.--------------------------- 8 | history_readnoise: Created with makebpmreadnoise.py 9 | description_mask: This is a bad pixel mask reference file.--------------------------- 10 | history_mask: Created with makebpmreadnoise.py 11 | 12 | #Raw data directory containing the full-frame NISRAPID darks 13 | rawdir: /home/user/darks/allffnisrapid/raw 14 | 15 | #Location of output files 16 | outdir: /home/user/darks/codeoutput_20220620 17 | 18 | #Root filename of output reference files 19 | rootreadnoise: jwst_niriss_com_nisrapid_readnoise 20 | rootbpm: jwst_niriss_com_bpm 21 | 22 | #Analysis on the darks takes the longest time. If only illuminated or linearity files have changed since the last run, set this to False. 23 | refinddarkbadpixels: False 24 | 25 | #The linearity reference file has a DQ array with NONLINEAR pixels flagged. Don't need to include these as linearity step flags them in science obs DQ. 26 | #Deprecated. This will always be false as I am repurposing this bit in the mask for NO_SAT_CHECK 27 | includelinearity: False 28 | 29 | #Input reference files 30 | #Superbias made from data at same temperature - the file named below will be generated by makesuperbias_jwst_reffiles.py if does not already exist 31 | reffile_superbias: /home/user/crds_cache/references/jwst/niriss/jwst_niriss_superbias_0183.fits 32 | #dark current made from data at same temperature - the file named below will be generated by makedarknoisefilesgdq.py if does not already exist 33 | reffile_dark: /home/user/crds_cache/references/jwst/niriss/jwst_niriss_dark_0179.fits 34 | #Any NIRISS GR150 grism flat field file - this must already exist 35 | reffile_flat: /home/user/crds_cache/references/jwst/niriss/jwst_niriss_flat_0265.fits 36 | #Linearity reference file - used for flagging NONLINEAR pixels and in running level 1 pipeline 37 | reffile_linearity: /home/user/crds_cache/references/jwst/niriss/jwst_niriss_linearity_0016.fits 38 | 39 | #noise files are in units of ADU so need a value of gain to convert to electrons, however readnoise reference file will be in units of ADU. 40 | #use 1.60 for now - might redo when get a better gain value 41 | gain: 1.60 42 | 43 | #Set threshold parameters that determine when a pixel is bad and the category 44 | #Usable QE threshold 45 | thresh_lowqe: 0.6 46 | #QE below which to flag as DEAD 47 | thresh_dead: 0.05 48 | #QE (normalized locally) of nearest 4 pixels to an open or RC pixel to flag as ADJ_OPEN 49 | thresh_adjopen: 1.05 50 | #QE (normalized locally) of nearest 4 pixels to an open or RC pixel to flag further 4 pixels as ADJ_OPEN 51 | thresh_nearopen: 1.10 52 | #Dark current above which to flag as HOT 53 | thresh_hot: 0.5 54 | #Dark current above which to flag as WARM (not marked as DO_NOT_USE) 55 | thresh_warm: 0.1 56 | #Dark current below which pixels are unusual and to flag as OTHER_BAD_PIXEL 57 | thresh_cold: 0.004 58 | #Bias level above which to flag as UNRELIABLE_BIAS 59 | thresh_bias: 30000.0 60 | #Variability in bias sigma above which to flag as UNRELIABLE_BIAS 61 | thresh_bias_sigma: 2.0 62 | #Dark slope noise factor times median above which to always flag as UNRELIABLE_SLOPE 63 | thresh_slopenoise: 2.5 64 | #Dark CDS noise factor times median above which to always flag as UNRELIABLE_DARK 65 | thresh_cdsnoise: 2.5 66 | #Dark slope noise factor times median above which to flag as UNRELIABLE_SLOPE for long exposures only 67 | thresh_slopenoise_longonly: 1.8 68 | #Dark CDS noise factor times median above which to flag as UNRELIABLE_DARK for short exposures only 69 | thresh_cdsnoise_shortonly: 1.8 70 | #Reference pixel noise factor times median above which to flag for all 71 | thresh_slopenoise_refpix: 1.5 72 | thresh_cdsnoise_refpix: 1.5 73 | 74 | 75 | 76 | ##For passing to runDetector1_niriss_fullframedark.py to run JWST pipeline 77 | #These are reference file locations; set to 'crds' if want to use the CRDS default. 78 | #Mask file should only contain bad ref pixels so doesn't impact good pixels that were only bad in previous runs 79 | #Note the superbias and linearity files used by this script are defined earlier in this config file 80 | reffile_bpm: /home/user/jwst_niriss_mask_0015_refpixonly.fits 81 | reffile_saturation: crds 82 | reffile_gain: crds 83 | 84 | ##For passing to makedarknoisefilesgqd.py 85 | #The maximum fraction of exposures affected by jumps to classify the jumps as cosmic rays rather than noisy pixels (default=0.33) 86 | fraction_maxcr: 0.33 87 | #Number of iterations in iterative sigma clipping to exclude cosmic rays. 88 | #If there are lots of cosmic rays use up to 20% of the number of input images. 89 | #If no simulated cosmic rays use sigiters=3 90 | sigiters_temp: 13 91 | sigiters_final: 13 92 | 93 | 94 | #Running RTS pixel finding takes the longest time. If don't care about categorizing RTS, set to False here. 95 | runrtscheck: False 96 | 97 | #Output a separate file for each type of bad pixel (useful for inspection and correlation); if required set to True. 98 | outputseparatefiles: True 99 | -------------------------------------------------------------------------------- /dopersistflags.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import numpy as np 4 | import os 5 | from astropy.io import fits 6 | from astropy.table import Table 7 | from jwst.datamodels import dqflags 8 | from jwst.refpix.irs2_subtract_reference import make_irs2_mask 9 | from datetime import datetime 10 | import logging 11 | 12 | def persistflags(prevrawdirfile,rawdirfile,jumpdirfile,countlimit,timeconstant): 13 | """ 14 | Flag pixels that reached a very high number of counts (countlimit) in the previous integration 15 | The GROUPDQ array will be flagged with the JUMP_DET flag (this is called after the jump step and snowball flagging so won't interfere with that) 16 | Only groups within timeconstant after end of previous integration are flagged 17 | The input file is overwritten 18 | 19 | Parameters: 20 | prevrawdirfile - path to the raw exposure taken before this one, can set equal to ' ' if there is not a previous exposure in the dataset 21 | rawdirfile - path to this raw exposure 22 | jumpdirfile - path to the input ramp file, which has jump step and snowball flagging applied 23 | countlimit - count level in raw data in previous integration above which to flag persistence in following integration - default 50000 24 | timeconstant - how long after end of previous integration to flag groups 25 | """ 26 | with fits.open(jumpdirfile) as hdulist: 27 | gdq = hdulist['GROUPDQ'].data 28 | header = hdulist[0].header 29 | detector = header['DETECTOR'] 30 | readpatt = header['READPATT'] 31 | nint = header['NINTS'] 32 | tgroup = header['TGROUP'] 33 | ngroup = header['NGROUPS'] 34 | grouparray=np.arange(ngroup)+1 35 | inttimes = Table.read(rawdirfile, hdu='INT_TIMES') 36 | 37 | #iterate over integrations 38 | for h in range(nint): 39 | #print ('working on int',(h+1)) 40 | previntend = 0.0 41 | 42 | if h==0: 43 | #for first integration must get raw data from last integration of previous exposure if it exists 44 | if os.path.exists(prevrawdirfile): 45 | rawheader = fits.getheader(prevrawdirfile) 46 | rawdata = fits.getdata(prevrawdirfile) 47 | #If data is NIRSpec IRS2 need to removed interleaved reference pixels 48 | if readpatt=='NRSIRS2RAPID' or readpatt=='NRSIRS2': 49 | rawdata = reshapeirs2(rawdata,detector,header) 50 | maxrawdata = np.max(np.squeeze(rawdata[-1,:,:,:]),axis=0) 51 | intstart = inttimes['int_start_MJD_UTC'][0] 52 | previnttimes = Table.read(prevrawdirfile, hdu='INT_TIMES') 53 | previntend = previnttimes['int_end_MJD_UTC'][-1] 54 | else: 55 | #for later integrations must get raw data from same file 56 | rawheader = fits.getheader(rawdirfile) 57 | rawdata = fits.getdata(rawdirfile) 58 | #If data is NIRSpec IRS2 need to removed interleaved reference pixels 59 | if readpatt=='NRSIRS2RAPID' or readpatt=='NRSIRS2': 60 | rawdata = reshapeirs2(rawdata,detector,header) 61 | maxrawdata = np.max(np.squeeze(rawdata[(h-1),:,:,:]),axis=0) 62 | intstart = inttimes['int_start_MJD_UTC'][h] 63 | previntend = inttimes['int_end_MJD_UTC'][(h-1)] 64 | 65 | #skip the update if there was no previous integration in the raw file set 66 | if previntend>0: 67 | satindices = np.where(maxrawdata>countlimit) 68 | i_yy,i_xx, = np.where(maxrawdata>countlimit) 69 | numsat = maxrawdata[satindices].size 70 | #print ('number of pixels above countlimit ',numsat) 71 | 72 | mjdintegration = intstart+((grouparray+0.5)*tgroup/(24*3600.0)) 73 | timesinceend = (mjdintegration - previntend)*(24*3600.0) 74 | 75 | for k in range(1,ngroup): 76 | if timesinceend[k] < timeconstant: 77 | gdq[h,k,i_yy,i_xx] = np.bitwise_or(gdq[h,k,i_yy,i_xx],dqflags.group['JUMP_DET']) 78 | 79 | #write out results 80 | outfile = jumpdirfile 81 | #uncomment below to output ramp in a different file 82 | #outfile = jumpdirfile.replace('.fits','_persist.fits') 83 | hdulist['GROUPDQ'].data = gdq 84 | hdulist.writeto(outfile, overwrite=True) 85 | 86 | 87 | def reshapeirs2(rawdata,detector,header): 88 | """ 89 | Take in a raw NIRSpec IRS2 data array and return an array containing only the non-reference pixels. 90 | """ 91 | 92 | #switch from DMS to detector orientation 93 | if detector == "NRS1": 94 | rawdata = np.swapaxes(rawdata, 2, 3) 95 | elif detector == "NRS2": 96 | rawdata = np.swapaxes(rawdata, 2, 3)[:, :, ::-1, ::-1] 97 | ny = rawdata.shape[-2] 98 | nx = rawdata.shape[-1] 99 | scipix_n = header['NRS_NORM'] 100 | refpix_r = header['NRS_REF'] 101 | #use jwst pipeline function to make a 1D mask of the non-reference pixels 102 | irs2_mask = make_irs2_mask(nx, ny, scipix_n, refpix_r) 103 | rawdata = rawdata[:, :, :, irs2_mask] 104 | #switch back from detector to DMS orientation 105 | if detector == "NRS1": 106 | rawdata = np.swapaxes(rawdata, 2, 3) 107 | elif detector == "NRS2": 108 | rawdata = np.swapaxes(rawdata[:, :, ::-1, ::-1], 2, 3) 109 | 110 | return rawdata 111 | 112 | 113 | #Run directly for testing 114 | direct=False 115 | if direct: 116 | prevrawdirfile = 'jw01222002001_03104_00002_nrs1_uncal.fits' 117 | rawdirfile = 'jw01222002001_03104_00003_nrs1_uncal.fits' 118 | jumpdirfile = 'jw01222002001_03104_00003_nrs1_jump.fits' 119 | countlimit=50000 120 | timeconstant=1000.0 121 | persistflags(prevrawdirfile,rawdirfile,jumpdirfile,countlimit,timeconstant) 122 | -------------------------------------------------------------------------------- /image1overf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import numpy as np 4 | from astropy.io import fits 5 | from astropy.stats import SigmaClip 6 | from astropy.convolution import Gaussian2DKernel,convolve 7 | from photutils import Background2D, MedianBackground 8 | from photutils.segmentation import detect_sources, make_2dgaussian_kernel 9 | from jwst.datamodels import dqflags 10 | from copy import deepcopy 11 | 12 | def sub1fimaging(cal2hdulist,sigma_bgmask,sigma_1fmask,splitamps,usesegmask): 13 | """ 14 | Determine a 1/f correction for JWST imaging data. 15 | Input is a level 2 calibrated NIRISS or NIRCam image. 16 | Subtracts a background and masks sources to determine 1/f stripes. 17 | Assumes stripes are constant along full detector row, unless splitamps set to True. 18 | Only does a correction for FULL (NIRCam and NIRISS) and SUB256 (NIRISS) subarrays. 19 | Uses 'SLOWAXIS' keyword to determine detector orientation. 20 | 21 | Output: 22 | Returns data array of corrected image, not including the reference pixels 23 | 24 | Parameters: 25 | cal2hdulist - hdulist of the input level 2 calibrated image 26 | sigma_bgmask - sigma of outliers for masking when making background (suggested value=3.0) 27 | sigma_1fmask - sigma of outliers for masking when making 1/f correction (suggested value=2.0) 28 | splitamps - fit each of the 4 amps separately when full-frame (set this to True when the field is sparse) 29 | usesegmask - whether to use a segmentation image as the mask before fitting 1/f stripes (recommend set to True in most cases) 30 | """ 31 | 32 | #Check subarray type and extract non-reference pixels 33 | if cal2hdulist['PRIMARY'].header['SUBARRAY']=='FULL': 34 | data = cal2hdulist['SCI'].data[4:2044,4:2044] 35 | dq = cal2hdulist['DQ'].data[4:2044,4:2044] 36 | elif cal2hdulist['PRIMARY'].header['SUBARRAY']=='SUB256': 37 | data = cal2hdulist['SCI'].data[:252,:252] 38 | dq = cal2hdulist['DQ'].data[:252,:252] 39 | else: 40 | print ('Will not do 1/f subtraction for subarray of type {}'.format(cal2hdulist['PRIMARY'].header['SUBARRAY'])) 41 | return data 42 | 43 | slowaxis = abs(cal2hdulist['PRIMARY'].header['SLOWAXIS']) 44 | 45 | #Get a mask of bad pixels from the DQ array 46 | mask = np.zeros(data.shape,dtype=bool) 47 | i_yy,i_xx = np.where((np.bitwise_and(dq, dqflags.group['DO_NOT_USE']) == 1)) 48 | mask[i_yy,i_xx] = 1 49 | 50 | #Make a flux distribution centered on the median that on the higher than median side is a reflection of the lower than median side. 51 | #Assumption here is not huge variation in background across field, so median is a useful value of typical background level 52 | #Note this mask is only used to generate the background model 53 | gooddata = data[np.where(mask==0)] 54 | median = np.median(gooddata) 55 | lowpixels = np.where(gooddata 3sigma of this flux distribution 58 | mask[np.where(data>(median+sigma_bgmask*np.std(bgpixels)))] = 1 59 | mask[np.where(data<(median-sigma_bgmask*np.std(bgpixels)))] = 1 60 | 61 | #testhdulist = deepcopy(cal2hdulist) 62 | #testdata = deepcopy(data) 63 | #testdata[np.where(mask>0)] = 0.0 64 | #testhdulist['SCI'].data = testdata 65 | #testoutfile='testmaskinit.fits' 66 | #testhdulist.writeto(testoutfile,overwrite=True) 67 | 68 | #Do a background subtraction to separate background variations from 1/f stripe determination 69 | sigma_clip_forbkg = SigmaClip(sigma=3., maxiters=5) 70 | bkg_estimator = MedianBackground() 71 | bkg = Background2D(data, (34, 34),filter_size=(5, 5), mask=mask, sigma_clip=sigma_clip_forbkg, bkg_estimator=bkg_estimator) 72 | bksubdata = data-bkg.background 73 | 74 | #Remake mask on background-subtracted data, 75 | #Two options - use segmentation region on smoothed image 76 | # - use same method as before but now clipping at < or > sigma_1fmask sigma of the flux distribution 77 | mask = np.zeros(data.shape,dtype=bool) 78 | mask[i_yy,i_xx] = 1 79 | if usesegmask: 80 | # Before detection, smooth image with Gaussian FWHM = 5 pixels - this gives better balance between stars and BCGs because ghosts are more diffuse than stars 81 | kernel = make_2dgaussian_kernel(5.0, size=5) 82 | convolved_bksubdata = convolve(bksubdata, kernel) 83 | bksubdata_masked = np.ma.masked_array(bksubdata, mask=mask) 84 | clippedsigma = np.std(sigma_clip_forbkg(bksubdata_masked, masked=True, copy=False)) 85 | #print (clippedsigma) 86 | photthreshold = sigma_1fmask*clippedsigma 87 | segm_detect = detect_sources(convolved_bksubdata, photthreshold, mask=mask, npixels=7) 88 | segimage = segm_detect.data.astype(np.uint32) 89 | mask[np.where(segimage>0)] = 1 90 | else: 91 | gooddata = bksubdata[np.where(mask==0)] 92 | median = np.median(gooddata) 93 | negpixels = np.where(gooddata(median+sigma_1fmask*np.std(bgpixels)))] = 1 96 | mask[np.where(bksubdata<(median-sigma_1fmask*np.std(bgpixels)))] = 1 97 | 98 | #testdata = deepcopy(bksubdata) 99 | #testdata[np.where(mask>0)] = 0.0 100 | #testhdulist['SCI'].data = testdata 101 | #testhdulist['ERR'].data = segimage 102 | #testoutfile='testmaskpostbkg_seg_sigma_1fmask0p7.fits' 103 | #testhdulist.writeto(testoutfile,overwrite=True) 104 | 105 | #Make masked array of background-subtracted data and then take median along columns (slowaxis=1) or rows (slowaxis=2) 106 | #if splitamps is True and full frame then define sections of 4 amps and fit and subtract each separately 107 | if splitamps==True and cal2hdulist['PRIMARY'].header['SUBARRAY']=='FULL': 108 | stripes=np.zeros(data.shape) 109 | #define sections - sub off 4 because reference pixels already removed 110 | loamp=np.array([4,512,1024,1536])-4 111 | hiamp=np.array([512,1024,1536,2044])-4 112 | numamps=loamp.size 113 | for k in range(numamps): 114 | if slowaxis==1: 115 | maskedbksubdata = np.ma.array(bksubdata[loamp[k]:hiamp[k],:], mask=mask[loamp[k]:hiamp[k],:]) 116 | stripes[loamp[k]:hiamp[k],:] = np.ma.median(maskedbksubdata, axis=(slowaxis-1),keepdims=True) 117 | elif slowaxis==2: 118 | maskedbksubdata = np.ma.array(bksubdata[:,loamp[k]:hiamp[k]], mask=mask[:,loamp[k]:hiamp[k]]) 119 | stripes[:,loamp[k]:hiamp[k]] = np.ma.median(maskedbksubdata, axis=(slowaxis-1),keepdims=True) 120 | else: 121 | maskedbksubdata = np.ma.array(bksubdata, mask=mask) 122 | stripes = np.ma.median(maskedbksubdata, axis=(slowaxis-1),keepdims=True) 123 | 124 | correcteddata = data-stripes 125 | 126 | return correcteddata 127 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jwst - Tools for processing and analyzing JWST data 2 | 3 | ## Additional modules for pipeline processing 4 | 5 | ### Columnjump 6 | columnjump is an additional step that can be applied as part of the JWST DETECTOR1 pipeline for data from the NIRISS instrument. The step should be called after dark current subtraction and before jump detection. The columnjump step removes random jumps in the levels of some columns (~50 columns per Ng=100 NISRAPID ramp) that cause increased noise along those columns. Note the term columns here refers to the original detector coordinates and these are actually rows in the DMS orientation, i.e. they are orthogonal and distinct from the well-known stripes of 1/f noise. 7 | 8 | Installation 9 | columnjump is available at pypi: 10 | ``` 11 | pip install columnjump 12 | ``` 13 | Usage 14 | A typical calling sequence is: 15 | ```python 16 | from columnjump import ColumnJumpStep 17 | columnjump = ColumnJumpStep() 18 | #Manually set any desired non-default parameter values 19 | columnjump.nsigma1jump = 5.00 \# sigma rejection threshold for one jump in the ramp 20 | columnjump.nsigma2jumps = 3.00 \# sigma rejection threshold for two jumps in the ramp 21 | columnjump.outputdiagnostics = True \# output a table of the columns corrected? 22 | columnjump.output_dir = out_dir 23 | columnjump.output_file = out_file 24 | #Run the step 25 | result = columnjump(inputfile) 26 | ``` 27 | ### image1overf.py 28 | image1overf.py performs a correction for 1/f readout noise on NIRISS or NIRCam imaging data. The operation is performed on the calibrated level 2 image. It includes the effect of a variable background (by temporarily removing it before determining the 1/f correction and adding it back afterwards) and masking pixels containing sources. Only two subarrays are supported: FULL and SUB256. Use with care and inspect the results for any unintended consequences. 29 | 30 | Usage 31 | A typical calling sequence on a single level2 image named cal2file is: 32 | ```python 33 | from image1overf import sub1fimaging 34 | cal21overffile = cal2file.replace('_cal.fits','_cal_1overf.fits') 35 | print ('Running 1/f correction on {} to produce {}'.format(cal2file,cal21overffile)) 36 | with fits.open(cal2file) as cal2hdulist: 37 | if cal2hdulist['PRIMARY'].header['SUBARRAY']=='FULL' or cal2hdulist['PRIMARY'].header['SUBARRAY']=='SUB256': 38 | sigma_bgmask = 3.0 39 | sigma_1fmask = 2.0 40 | splitamps = False #Set to True only in a sparse field so each amplifier will be fit separately. 41 | usesegmask = True #Recommend set to True in most cases 42 | correcteddata = sub1fimaging(cal2hdulist,sigma_bgmask,sigma_1fmask,splitamps,usesegmask) 43 | if cal2hdulist['PRIMARY'].header['SUBARRAY']=='FULL': 44 | cal2hdulist['SCI'].data[4:2044,4:2044] = correcteddata 45 | elif cal2hdulist['PRIMARY'].header['SUBARRAY']=='SUB256': 46 | cal2hdulist['SCI'].data[:252,:252] = correcteddata 47 | cal2hdulist.writeto(cal21overffile, overwrite=True) 48 | ``` 49 | 50 | ### dosnowballflags.py 51 | dosnowballflags.py flags pixels in snowballs - expand saturated ring and diffuse halo jump ring. 52 | The GROUPDQ array will be flagged with the SATURATED and JUMP_DET flags. 53 | Saturating snowballs early in short ramps can have unflagged central pixels that jump in the previous group. 54 | This is called after the regular jump step. 55 | The output file is overwritten. 56 | You need a working installation of WebbPSF. 57 | Works for NIRISS, NIRCam and NIRSpec. 58 | Requires checkifstar.py for differentiating between saturated stars and snowballs if imagingmode is True. 59 | 60 | Usage 61 | A typical calling sequence is: 62 | ```python 63 | from dosnowballflags import snowballflags 64 | jumpdirfile = './jw01345001001_02201_00001_nrca1_jump.fits' 65 | filtername = 'F115W' 66 | npixfind = 40 67 | satpixradius = 3 68 | halofactorradius = 2.0 69 | imagingmode = True 70 | snowballflags(jumpdirfile,filtername,npixfind,satpixradius,halofactorradius,imagingmode) 71 | ``` 72 | 73 | ### checkifstar.py 74 | checkifstar.py builds a WebbPSF model and then compares an image cutout with the model to determine if that cutout corresponds to a star or not. This use the diffraction spikes and PSF asymmetry. Currently works for NIRISS and NIRCam. Will fail on extremely saturated stars, but good on moderately saturated ones. 75 | 76 | ### dopersistflags.py 77 | dopersistflags.py flags pixels that reached a very high number of counts in the previous integration. 78 | The GROUPDQ array will be flagged with the JUMP_DET flag (this is called after the jump step and snowball flagging so won't interfere with that). 79 | Only groups within timeconstant after end of previous integration are flagged. 80 | The input file is overwritten. 81 | 82 | Usage 83 | A typical calling sequence is: 84 | ```python 85 | from dopersistflags import persistflags 86 | prevrawdirfile = 'jw01222002001_03104_00002_nrs1_uncal.fits' #note can be empty string for first exposure in visit 87 | rawdirfile = 'jw01222002001_03104_00003_nrs1_uncal.fits' 88 | jumpdirfile = 'jw01222002001_03104_00003_nrs1_jump.fits' 89 | countlimit=50000 90 | timeconstant=1000.0 91 | persistflags(prevrawdirfile,rawdirfile,jumpdirfile,countlimit,timeconstant) 92 | ``` 93 | 94 | ## Scripts for analyzing dark exposures 95 | 96 | makebpmreadnoise.py generates three bad pixel mask files and readnoise reference file for the NIRISS detector. 97 | The three masks have different dark noise thresholds appropriate to various types of calibration or science data. 98 | The routine is robust to high rates of cosmic rays and separates cosmic ray hits from noisy pixels. makebpmreadnoise.py calls makedarknoisefilesgdq.py. 99 | Inputs come from the config file, an example is bpmreadnoise_nis006_20220620.cfg. 100 | 101 | makedarknoisefilesgdq.py makes dark current and noise images from darks, optionally using GDQ flags to mark locations of cosmic ray jumps. 102 | 103 | getipc.py determines 5x5 and 3x3 IPC kernel images based on spread of charge from hot pixels. 104 | 105 | makenirissimagingflats.py generates NIRISS imaging flat fields for all filters from one or more integrations per filter that have passed through level 1 pipeline processing. 106 | 107 | makenirissgrismflats.py takes in direct (for all filters) and dispersed (currently only F115W and F150W are required) NIRISS WFSS flat field images to identify features of low transmission on the NIRISS pick-off mirror (POM), including the coronagraphic spots. The outputs per filter are 108 | 1. An oversized image of POM transmission including the measured POM outline and features of low transmission. 109 | 2. Grism flat field reference files. These grism flats are equal to the imaging flats over most of the detector, but with all the POM features corrected leaving only the detector response. 110 | 111 | For both types, files are generated for each of the GR150C and GR150R grisms. The contents of the files are identical, but separate copies are required for automatic CRDS selection for use with data from each grism. 112 | 113 | -------------------------------------------------------------------------------- /checkifstar.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import numpy as np 4 | import os 5 | from astropy.io import fits 6 | from jwst.datamodels import dqflags 7 | from photutils import CircularAnnulus 8 | import webbpsf 9 | from copy import deepcopy 10 | 11 | def checkif(cutout,cutoutdq,webbpsfcutoutmask,radmin,radmax,spikeratio): 12 | """ 13 | Given a NIRISS or NIRCam 2D image cutout check for diffraction spikes and return True or False for it being a star (or return a probability?) 14 | Parameters: 15 | cutout - 2D image cutout 16 | cutoutdq - 2D image cutout dq array 17 | webbpsfcutoutmask - same size and centered cutout from WebbPSF for this filter as a mask with values of 2 in spikes and 1 off spikes (0 elsewhere) 18 | radmin - starting radius in pixels to look for diffraction spikes 19 | radmax - ending radius in pixels to look for diffraction spikes 20 | spikeratio - ratio of mean flux in spike region to out of spike region above which to call it a star for one annulus 21 | Returns: 22 | isstar - True or False 23 | """ 24 | 25 | #Edit webbpsfcutoutmask to mask bad pixels 26 | webbpsfcutoutmaskhere = deepcopy(webbpsfcutoutmask) 27 | donotuseindices = np.where(np.bitwise_and(cutoutdq, dqflags.pixel['DO_NOT_USE'])) 28 | webbpsfcutoutmaskhere[donotuseindices] = 0 29 | 30 | #Subtract background off - use 5%-ile of non-saturated array pixels 31 | nonsatmask = np.ones((cutout.shape)) 32 | saturatedindices = np.where(np.bitwise_and(cutoutdq, dqflags.pixel['SATURATED'])) 33 | nonsatmask[saturatedindices] = 0 34 | cutoutnonsat = cutout[np.where(nonsatmask>0)] 35 | 36 | #Only continue if cutout is same shape as webbpsf mask. Otherwise assume not a star 37 | if cutout.shape==webbpsfcutoutmaskhere.shape: 38 | fifthpercentile = np.percentile(cutoutnonsat,5) 39 | cutout -= fifthpercentile 40 | 41 | #Set up separate masks for each region 42 | maskspikes = webbpsfcutoutmaskhere-1 43 | maskspikes[maskspikes<0] = 0 44 | masknotspikes = webbpsfcutoutmaskhere 45 | masknotspikes[np.where(webbpsfcutoutmaskhere>1)] = 0 46 | 47 | #Loop over annuli 48 | psfcenxy = (cutout.shape[0]-1)/2 49 | numrad = radmax-radmin+1 50 | radii = np.arange(numrad)+radmin 51 | yesspike=0 52 | #for k in range(1): 53 | for k in range(numrad): 54 | annulus_aperture = CircularAnnulus([psfcenxy,psfcenxy], r_in=radii[k]-0.5, r_out=radii[k]+0.5) 55 | 56 | #First for spikes 57 | annulus_mask = annulus_aperture.to_mask(method='center') 58 | annulus_measuredata = annulus_mask.multiply(cutout*maskspikes) 59 | annulus_maskdata = annulus_mask.data 60 | annulus_measuredata_1d = annulus_measuredata[annulus_maskdata > 0] 61 | spikes_mean = np.nanmean(annulus_measuredata_1d) 62 | 63 | #Then out of spikes 64 | annulus_mask = annulus_aperture.to_mask(method='center') 65 | annulus_measuredata = annulus_mask.multiply(cutout*masknotspikes) 66 | annulus_maskdata = annulus_mask.data 67 | annulus_measuredata_1d = annulus_measuredata[annulus_maskdata > 0] 68 | notspikes_mean = np.nanmean(annulus_measuredata_1d) 69 | 70 | #Keep count of annuli where spikes are brighter 71 | if spikes_mean/notspikes_mean > spikeratio: 72 | yesspike+=1 73 | 74 | #Find fraction of annuli where spikes are brighter 75 | fracyesspike = yesspike/numrad 76 | if fracyesspike >= 0.5: 77 | isstar = True 78 | else: 79 | isstar = False 80 | #print (fracyesspike,isstar) 81 | else: 82 | isstar = False 83 | return isstar 84 | 85 | 86 | def makewebbpsfmask(ins,filtername,pixscale,cutsize,radmin,radmax): 87 | """ 88 | make a WebbPSF cutout mask for this filter with values of 1 in diffraction spikes and 2 off spikes (0 elsewhere) 89 | Parameters: 90 | ins - instrument NIRISS or NIRCAM 91 | filtername - filter name as understood by webbpsf 92 | pixscale - pixel scale in arcsec per pixel 93 | cutsize - 2D image cutout length along one axis in pixels - should be odd to center PSF - will be a square - start with 37 pixels for NIRISS 94 | Returns: 95 | webbpsfcutoutmask - same size and centered cutout from WebbPSF for this filter as a mask with values of 2 in spikes and 1 off spikes (0 elsewhere) 96 | """ 97 | 98 | outfile='./temppsfmask_{}_{}_{}_{}.fits'.format(ins,filtername,str(pixscale).replace('.','p'),cutsize) 99 | psffile='./WebbPSF_{}_{}_{}_{}.fits'.format(ins,filtername,str(pixscale).replace('.','p'),cutsize) 100 | print (outfile,psffile) 101 | #If WebbPSF file already exists, do not generate it again 102 | if not os.path.exists(psffile): 103 | if ins.lower()=='niriss': 104 | nisornic = webbpsf.NIRISS() 105 | else: 106 | nisornic = webbpsf.NIRCam() 107 | nisornic.options['output_mode'] = 'detector sampled' 108 | nisornic.pixelscale = pixscale 109 | nisornic.filter=filtername 110 | psfhdulist = nisornic.calc_psf(psffile,fov_pixels=cutsize) 111 | else: 112 | psfhdulist = fits.open(psffile) 113 | psf=psfhdulist[0].data 114 | psf /= psf.sum() 115 | 116 | webbpsfcutoutmask = np.zeros((cutsize,cutsize)) 117 | psfcenxy = (cutsize-1)/2 118 | numrad = radmax-radmin+1 119 | radii = np.arange(numrad)+radmin 120 | for k in range(numrad): 121 | annulus_aperture = CircularAnnulus([psfcenxy,psfcenxy], r_in=radii[k]-0.5, r_out=radii[k]+0.5) 122 | annulus_mask = annulus_aperture.to_mask(method='center') 123 | masksize = annulus_mask.shape[0] 124 | xlo = int((cutsize-masksize)/2) 125 | xhi = xlo+masksize 126 | ylo=xlo 127 | yhi=xhi 128 | 129 | annulus_measuredata = annulus_mask.multiply(psf) 130 | annulus_maskdata = annulus_mask.data 131 | 132 | annulus_measuredata_1d = annulus_measuredata[annulus_maskdata > 0] 133 | annulus_measuredata_median=np.median(annulus_measuredata_1d) 134 | annulus_measuredata_std=np.std(annulus_measuredata_1d) 135 | #Set half the pixels in the annulus to value 1 and half to value 2 136 | thresh = annulus_measuredata_median+0.0*annulus_measuredata_std 137 | annulus_maskdata[np.where(annulus_measuredata>thresh)] = 2 138 | webbpsfcutoutmask[ylo:yhi,xlo:xhi] = webbpsfcutoutmask[ylo:yhi,xlo:xhi] + annulus_maskdata 139 | psfhdulist[0].data = webbpsfcutoutmask 140 | psfhdulist.writeto(outfile,overwrite=True) 141 | return webbpsfcutoutmask 142 | 143 | 144 | #Run directly for testing 145 | direct=False 146 | if direct: 147 | ins='niriss' 148 | #filtername='F150W' 149 | #pixscale=0.033 150 | #cutsize=276 151 | #radmin = 18 152 | #radmax = 32 153 | filtername='F115W' 154 | pixscale=0.0656 155 | cutsize=37 156 | radmin = 9 157 | radmax = 16 158 | spikeratio = 1.4 159 | 160 | 161 | #Make the WebbPSF mask 162 | webbpsfcutoutmask = makewebbpsfmask(ins,filtername,pixscale,cutsize,radmin,radmax) 163 | 164 | #Feed the cutouts and see if matches a star 165 | ratefile='./jw01324001001_02101_00001_nis_columnjumpstep_rate.fits' 166 | with fits.open(ratefile) as hdulist: 167 | cutout = hdulist['SCI'].data[1283:1320,1310:1347] 168 | cutoutdq = hdulist['DQ'].data[1283:1320,1310:1347] 169 | print (cutout.shape) 170 | isstar = checkif(cutout,cutoutdq,webbpsfcutoutmask,radmin,radmax,spikeratio) 171 | print (isstar) 172 | -------------------------------------------------------------------------------- /dosnowballflags.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import numpy as np 4 | import os 5 | from astropy.io import fits 6 | from jwst.datamodels import dqflags 7 | from photutils.segmentation import detect_sources 8 | from photutils.segmentation import SourceCatalog 9 | from copy import deepcopy 10 | from skimage.draw import disk 11 | 12 | 13 | def snowballflags(jumpdirfile,filtername,npixfind,satpixradius,halofactorradius,imagingmode): 14 | """ 15 | Flag pixels in snowballs - expand saturated ring and diffuse halo jump ring. 16 | The GROUPDQ array will be flagged with the SATURATED and JUMP_DET flags. 17 | Saturating snowballs early in short ramps can have unflagged central pixels that jump in the previous group. 18 | This is called after the regular jump step. 19 | The output file is overwritten. 20 | You need a working installation of WebbPSF. 21 | Requires checkifstar.py if imagingmode is True 22 | 23 | Parameters: 24 | jumpdirfile - path to the input file, which has jump step applied 25 | filtername - used for comparing to a WebbPSF star 26 | npixfind - number of connected pixels to find snowballs 27 | satpixradius - how many extra pixels to flag as saturated to account for slow charge migration near the saturated core - default 2 28 | halofactorradius - factor to increase radius of whole snowball for jump flagging - default 2.0 29 | imagingmode - boolean for whether imaging or spectroscopy. For imaging mode checks to see if the detected object is a star and then does not expand DQ arrays 30 | """ 31 | with fits.open(jumpdirfile) as hdulist: 32 | sci = hdulist['SCI'].data 33 | pdq = hdulist['PIXELDQ'].data 34 | gdq = hdulist['GROUPDQ'].data 35 | header = hdulist[0].header 36 | ins = header['INSTRUME'].lower() 37 | nint = header['NINTS'] 38 | ngroup = header['NGROUPS'] 39 | grouparray=np.arange(ngroup)+1 40 | 41 | #Set up webbpsf psfs for checking if a star 42 | if ins=='niriss': 43 | pixscale=0.0656 44 | cutsize=37 45 | radmin = 9 46 | radmax = 16 47 | spikeratio = 1.4 48 | elif ins=='nircam': 49 | channel = header['CHANNEL'] 50 | if channel == 'SHORT': 51 | pixscale = 0.033 52 | cutsize = 74 53 | radmin = 18 54 | radmax = 32 55 | spikeratio = 1.4 56 | else: 57 | pixscale = 0.66 58 | cutsize = 37 59 | radmin = 9 60 | radmax = 16 61 | spikeratio = 1.4 62 | elif ins=='nirspec': 63 | #Note these parameters only used for imaging mode so dummy values for NIRSpec 64 | pixscale = 0.10 65 | cutsize = 25 66 | radmin = 6 67 | radmax = 12 68 | spikeratio = 1.4 69 | 70 | #Make the WebbPSF mask (will not repeat the actual WebbPSF call if the file already exists) 71 | if imagingmode == True: 72 | from checkifstar import checkif, makewebbpsfmask 73 | print ('Running makewebbpsfmask',ins,filtername,pixscale,cutsize,radmin,radmax) 74 | webbpsfcutoutmask = makewebbpsfmask(ins,filtername,pixscale,cutsize,radmin,radmax) 75 | 76 | #iterate over integrations 77 | for h in range(nint): 78 | 79 | ctsnow=0 80 | #Skip first group because no jumps there 81 | for j in range(1,ngroup): 82 | #Find pixels in this group with jump detected and/or saturation detected 83 | jumps = np.zeros((2048,2048),dtype='uint8') 84 | sat = np.zeros((2048,2048),dtype='uint8') 85 | jumpsorsat = np.zeros((2048,2048),dtype='uint8') 86 | scithisgroup = np.squeeze(sci[h,j,:,:]) 87 | dqthisgroup = np.squeeze(gdq[h,j,:,:]) 88 | i_yy,i_xx, = np.where(np.bitwise_and(dqthisgroup, dqflags.group['JUMP_DET']) != 0) 89 | jumps[i_yy,i_xx] = 1 90 | jumpsorsat[i_yy,i_xx] = 1 91 | i_yy,i_xx, = np.where(np.bitwise_and(dqthisgroup, dqflags.group['SATURATED']) != 0) 92 | sat[i_yy,i_xx] = 1 93 | jumpsorsat[i_yy,i_xx] = 1 94 | 95 | #Set some low threshold for finding sources in noiseless DQ array 96 | threshsigma = 3.0 97 | bkg = 0.0 98 | stddev = 0.00007 99 | photthreshold = bkg + (threshsigma * stddev) 100 | 101 | #Run initial find on jumps or saturated because some short ramps do not have a jump in the regions that saturate 102 | segm_detect = detect_sources(jumpsorsat, photthreshold, npixels=npixfind) 103 | segimage = segm_detect.data.astype(np.uint32) 104 | if np.max(segimage)>0: 105 | segmcat = SourceCatalog(jumps, segm_detect) 106 | segmtbl = segmcat.to_table() 107 | ctsnowballs = segmtbl['xcentroid'][:].size 108 | #print (j,ctsnowballs,segmtbl) 109 | #Iterate over each possible snowball 110 | for k in range(ctsnowballs): 111 | #If low eccentricity proceed, otherwise remove source from segmentation image 112 | #Use both eccentricity and segmentation box axis since not always consistent, e.g. for merged jumps 113 | segboxaxisratio = np.abs((segmtbl['bbox_xmax'][k]-segmtbl['bbox_xmin'][k])/(segmtbl['bbox_ymax'][k]-segmtbl['bbox_ymin'][k])) 114 | if segboxaxisratio<1.0: 115 | segboxaxisratio = np.abs((segmtbl['bbox_ymax'][k]-segmtbl['bbox_ymin'][k])/(segmtbl['bbox_xmax'][k]-segmtbl['bbox_xmin'][k])) 116 | if ((segmtbl['eccentricity'][k]<0.6)&(segboxaxisratio<1.5)): 117 | #print (j,k+1,segmtbl['xcentroid'][k],segmtbl['ycentroid'][k],'eccen=',segmtbl['eccentricity'][k],segmtbl['bbox_ymin'][k],segmtbl['bbox_ymax'][k],segmtbl['bbox_xmin'][k],segmtbl['bbox_xmax'][k],segboxaxisratio) 118 | #Check if a star by running the checkifstar.py code on the relevant group of the jump cube sci array masking out bad pixels inc jump and saturated pixels 119 | #First cutout should be same size as WebbPSF PSF 120 | if imagingmode == True: 121 | xlo = int(segmtbl['xcentroid'][k]-(cutsize-1)/2) 122 | xhi = xlo+cutsize 123 | ylo = int(segmtbl['ycentroid'][k]-(cutsize-1)/2) 124 | yhi = ylo+cutsize 125 | 126 | scicutout = deepcopy(scithisgroup[ylo:yhi,xlo:xhi]) 127 | pdqcutout = deepcopy(pdq[ylo:yhi,xlo:xhi]) 128 | jumpscutout = jumps[ylo:yhi,xlo:xhi] 129 | satcutout = sat[ylo:yhi,xlo:xhi] 130 | pdqcutout[np.where(jumpscutout>0)] = 1 131 | pdqcutout[np.where(satcutout>0)] = 1 132 | #Run the check to see if this is a saturated star rather than a snowball 133 | isstar = checkif(scicutout,pdqcutout,webbpsfcutoutmask,radmin,radmax,spikeratio) 134 | else: 135 | isstar = False 136 | 137 | if isstar == False: 138 | jumpscutout = jumps[int(segmtbl['bbox_ymin'][k]):int(segmtbl['bbox_ymax'][k]),int(segmtbl['bbox_xmin'][k]):int(segmtbl['bbox_xmax'][k])] 139 | satcutout = sat[int(segmtbl['bbox_ymin'][k]):int(segmtbl['bbox_ymax'][k]),int(segmtbl['bbox_xmin'][k]):int(segmtbl['bbox_xmax'][k])] 140 | jumpsorsatcutout = jumpsorsat[int(segmtbl['bbox_ymin'][k]):int(segmtbl['bbox_ymax'][k]),int(segmtbl['bbox_xmin'][k]):int(segmtbl['bbox_xmax'][k])] 141 | #Triple box size for increased area to flag further out 142 | bigoffsetx = int((segmtbl['bbox_xmax'][k]-int(segmtbl['bbox_xmin'][k]))) 143 | bigoffsety = int((segmtbl['bbox_ymax'][k]-int(segmtbl['bbox_ymin'][k]))) 144 | bigsizex = jumpscutout.shape[1]+2*bigoffsetx 145 | bigsizey = jumpscutout.shape[0]+2*bigoffsety 146 | jumpsbigcutout = np.zeros((bigsizey,bigsizex),dtype=np.uint8) 147 | jumpsbigcutout[bigoffsety:(bigoffsety+jumpscutout.shape[0]),bigoffsetx:(bigoffsetx+jumpscutout.shape[1])] = jumpscutout 148 | satbigcutout = np.zeros((bigsizey,bigsizex),dtype=np.uint8) 149 | satbigcutout[bigoffsety:(bigoffsety+jumpscutout.shape[0]),bigoffsetx:(bigoffsetx+jumpscutout.shape[1])] = satcutout 150 | 151 | #For jumps assume round and use all jump or saturated pixels to get area 152 | numjumporsat = jumpsorsatcutout[np.where(jumpsorsatcutout>0)].size 153 | radiusjumporsat = (numjumporsat/3.14159)**0.5 154 | radius = int(halofactorradius*radiusjumporsat) 155 | rr, cc = disk((bigsizey/2-0.5,bigsizex/2-0.5), radius) 156 | jumpsbigcutout[rr, cc] = 4 157 | 158 | #For saturation assume round and use saturated pixels to get area 159 | numsat = satcutout[np.where(satcutout>0)].size 160 | radiussat = (numsat/3.14159)**0.5 161 | radius = int(radiussat+satpixradius) 162 | rr, cc = disk((bigsizey/2-0.5,bigsizex/2-0.5), radius) 163 | satbigcutout[rr, cc] = 2 164 | 165 | xlo = int(segmtbl['bbox_xmin'][k])-bigoffsetx 166 | xhi = xlo+bigsizex 167 | ylo = int(segmtbl['bbox_ymin'][k])-bigoffsety 168 | yhi = ylo+bigsizey 169 | 170 | #Update pixels in GROUPDQ array for halo 171 | i_yy,i_xx, = np.where(jumpsbigcutout>0) 172 | i_yy+=ylo 173 | i_xx+=xlo 174 | numpix = len(i_xx) 175 | for l in range(numpix): 176 | if ((i_xx[l]>3) & (i_xx[l]<2044) & (i_yy[l]>3) & (i_yy[l]<2044)): 177 | gdq[h,j,i_yy[l],i_xx[l]] = np.bitwise_or(gdq[h,j,i_yy[l],i_xx[l]],dqflags.group['JUMP_DET']) 178 | 179 | #Update pixels in GROUPDQ array for saturated core 180 | i_yy,i_xx, = np.where(satbigcutout>0) 181 | i_yy+=ylo 182 | i_xx+=xlo 183 | numpix = len(i_xx) 184 | for l in range(numpix): 185 | if ((i_xx[l]>3) & (i_xx[l]<2044) & (i_yy[l]>3) & (i_yy[l]<2044)): 186 | gdq[h,j,i_yy[l],i_xx[l]] = np.bitwise_or(gdq[h,j,i_yy[l],i_xx[l]],dqflags.group['SATURATED']) 187 | 188 | #if the snowball happened in the third group, flag the second group similarly in case first effects happened there and not enough data for good ramps up to there anyway. 189 | if j==2: 190 | i_yy,i_xx, = np.where(jumpsbigcutout>0) 191 | i_yy+=ylo 192 | i_xx+=xlo 193 | numpix = len(i_xx) 194 | for l in range(numpix): 195 | if ((i_xx[l]>3) & (i_xx[l]<2044) & (i_yy[l]>3) & (i_yy[l]<2044)): 196 | gdq[h,j-1,i_yy[l],i_xx[l]] = np.bitwise_or(gdq[h,j-1,i_yy[l],i_xx[l]],dqflags.group['JUMP_DET']) 197 | 198 | i_yy,i_xx, = np.where(satbigcutout>0) 199 | i_yy+=ylo 200 | i_xx+=xlo 201 | numpix = len(i_xx) 202 | for l in range(numpix): 203 | if ((i_xx[l]>3) & (i_xx[l]<2044) & (i_yy[l]>3) & (i_yy[l]<2044)): 204 | gdq[h,j-1,i_yy[l],i_xx[l]] = np.bitwise_or(gdq[h,j-1,i_yy[l],i_xx[l]],dqflags.group['SATURATED']) 205 | 206 | ctsnow+=1 207 | 208 | #Any pixel flagged as saturated in a group must be flagged as saturated in all subsequent groups 209 | for j in range(ngroup): 210 | #Find pixels in this group with saturation detected 211 | sat = np.zeros((2048,2048),dtype='uint8') 212 | dqthisgroup = np.squeeze(gdq[h,j,:,:]) 213 | i_yy,i_xx, = np.where(np.bitwise_and(dqthisgroup, dqflags.group['SATURATED']) != 0) 214 | numpix = len(i_xx) 215 | for l in range(numpix): 216 | gdq[h,j:,i_yy[l],i_xx[l]] = np.bitwise_or(gdq[h,j:,i_yy[l],i_xx[l]],dqflags.group['SATURATED']) 217 | 218 | header['HISTORY'] = 'Corrected {} snowballs in integration {}'.format(ctsnow,(h+1)) 219 | 220 | 221 | hdulist['GROUPDQ'].data = gdq 222 | header.set('SNOWCORR', 'COMPLETE', 'dosnowballflags.py DQ flagging applied') 223 | hdulist[0].header = header 224 | #uncomment below to output ramp in a different file 225 | #snowfile = jumpdirfile.replace('.fits','_snow.fits') 226 | snowfile = jumpdirfile 227 | hdulist.writeto(snowfile,overwrite=True) 228 | 229 | #Run directly for testing 230 | direct=False 231 | if direct: 232 | jumpdirfile = './jw01345001001_02201_00001_nrca1_jump.fits' 233 | imagingmode = True 234 | filtername = 'F115W' 235 | npixfind = 50 236 | satpixradius=3 237 | halofactorradius=2 238 | 239 | snowballflags(jumpdirfile,filtername,npixfind,satpixradius,halofactorradius,imagingmode) 240 | -------------------------------------------------------------------------------- /columnjump/columnjump/rampbreaks.py: -------------------------------------------------------------------------------- 1 | """ 2 | Find and fix jumps in columns of reference pixels in each 3 | integration within the input data array. The input data array 4 | is assumed to be in units of DN. Note that 'columns' are defined in 5 | original detector coordinates (not DMS coordinates) so appear in 3rd 6 | axis of 4D data array. 7 | """ 8 | 9 | import logging 10 | import numpy as np 11 | import numpy.ma as ma 12 | from astropy.stats import sigma_clip 13 | from astropy.table import Table 14 | from astropy.io import fits 15 | from astropy.io import ascii 16 | import sys 17 | import time 18 | 19 | from jwst import datamodels 20 | from jwst.datamodels import dqflags 21 | 22 | from .jwstpipe1p1p0_ramp_fit import calc_slope 23 | from .jwstpipe1p1p0_utils import OptRes 24 | 25 | log = logging.getLogger(__name__) 26 | log.setLevel(logging.DEBUG) 27 | 28 | HUGE_NUM = np.finfo(np.float32).max 29 | 30 | 31 | def quickrampfit(maskeddatathisint,ngroups): 32 | """ 33 | Perform quick ramp fit on all reference pixels to determine outliers in slope along each column 34 | """ 35 | #Calculate the slope of all reference pixels using pipeline ramp_fit routine 36 | data_sect = maskeddatathisint.data 37 | gain_sect = (0.0*data_sect)+1.0 38 | rn_sect = (0.0*data_sect)+1.0 39 | gdq_sect = (0.0*data_sect).astype(int) 40 | frame_time = 10.7 41 | save_opt = True 42 | opt_res = OptRes(1, np.squeeze(data_sect[0,:,:]).shape, 1, ngroups, save_opt) 43 | t_dq_cube, inv_var, opt_res, f_max_seg, num_seg = calc_slope(data_sect, gdq_sect, frame_time, opt_res, save_opt, rn_sect, gain_sect, 1, ngroups, 'optimal', 1) 44 | refpixslopes = opt_res.slope_2d.reshape(np.squeeze(data_sect[0,:,:]).shape) 45 | return refpixslopes 46 | 47 | 48 | def findcolrefpixsubmean(col,colstart,colstop,ampindex,maskeddatathisint,ngroups,nrows): 49 | """ 50 | Find clipped mean of a single column of reference pixels and return the reference pixels with 51 | the clipped mean subtracted. 52 | """ 53 | #Get 2.5sigma-clipped mean of the good reference pixels in this column for each group. 54 | #If a pixel is clipped out then remove it from all groups. 55 | datathiscol = maskeddatathisint[:,col,:] 56 | clipmaskeddata = sigma_clip(datathiscol,sigma = 2.5,maxiters=3,axis=1) 57 | clipmaskeddata = ma.mask_rowcols(clipmaskeddata,axis=1) 58 | colrefpix = np.mean(clipmaskeddata,axis=1) 59 | numgoodrefpix = clipmaskeddata.count(axis=1) 60 | 61 | #Get clipped mean of neighouring 20 columns of reference pixels and subtract it off. 62 | numcompare = 20 63 | colnear = np.arange((numcompare+1),dtype=int)+col-numcompare//2 64 | #For columns at edges of each amplifier, use the nearest 20 pixels in that amp. 65 | if (np.min(colnear)(colstop[ampindex]-1)): 68 | colnear -= ((np.max(colnear)-(colstop[ampindex]-1))) 69 | exclude = np.where(colnear==col) 70 | colnear = np.delete(colnear, exclude[0]) 71 | datathese20cols = maskeddatathisint[:,colnear,:] 72 | #Mask any rows that were masked for the single column 73 | singlemask = np.tile(clipmaskeddata[0,:].mask,(ngroups,numcompare,1)) 74 | datathese20cols = ma.array(datathese20cols.data, mask=singlemask) 75 | refpixcomparereshape = datathese20cols.reshape((ngroups,(nrows*numcompare))) 76 | cliprefpixcomparereshape = sigma_clip(refpixcomparereshape,sigma=2.5,maxiters=3,axis=1) 77 | meanrefpixcomparison = np.mean(cliprefpixcomparereshape,axis=1) 78 | 79 | #Subtract mean of comparison neighbouring columns from mean of this column 80 | colrefpixsubmean = colrefpix-meanrefpixcomparison 81 | colrefpixsubmean = colrefpixsubmean.astype('float16') 82 | return colrefpixsubmean 83 | 84 | 85 | def findfix_jumps(data, pdq, nsigma1jump, nsigma2jumps, nframes, filename, outputdiagnostics): 86 | """ 87 | Main function of rampbreaks.py 88 | """ 89 | #set up output diagnostic file if requested 90 | if outputdiagnostics == True: 91 | outtablename = 'rampbreaksout_'+filename+'.dat' 92 | outtable = Table(names=('Column','Numsigma1break','Numsigma2break','Ngroup1break','Ngroup2break1','Ngroup2break2','Size1break','Size2break1','Size2break2'),dtype=('i4', 'f8', 'f8', 'i4', 'i4', 'i4', 'f8', 'f8', 'f8')) 93 | 94 | #Set up correction array same shape as data 95 | correctionarray = np.zeros((data.shape),dtype='float16') 96 | 97 | #Make pixel DQ array same shape as data 98 | pdq = np.repeat(pdq[np.newaxis, :, :], data.shape[1], axis=0) 99 | pdq = np.repeat(pdq[np.newaxis, :, :, :], data.shape[0], axis=0) 100 | 101 | #Shrink data and pdq arrays to leave only top and bottom reference pixels of active columns 102 | databottom = data[:,:,4:2044,0:4] 103 | datatop = data[:,:,4:2044,2044:] 104 | datarp = np.concatenate((databottom,datatop),axis=3) 105 | pdqbottom = pdq[:,:,4:2044,0:4] 106 | pdqtop = pdq[:,:,4:2044,2044:] 107 | pdqrp = np.concatenate((pdqbottom,pdqtop),axis=3) 108 | 109 | #Mask reference pixels that have DO_NOT_USE flag set 110 | wh_donotuse = np.where(np.bitwise_and(pdqrp, dqflags.pixel['DO_NOT_USE'])) 111 | pdqrp[:,:,:,:] = 0 112 | pdqrp[wh_donotuse] = 1 113 | 114 | #Get refpix shrunken data characteristics 115 | (nints, ngroups, ncols, nrows) = datarp.shape 116 | 117 | #Scale sigma thresholds based on calibration in darks so approx 118 | #95% of corrections are good for full range of N_groups and N_frames 119 | if nframes == 1: 120 | gradient = 74.0 121 | scaling = 0.01*(100-gradient)+gradient/ngroups 122 | elif nframes == 4: 123 | gradient = 100.0/4.0 124 | scaling = 0.04*(22-gradient)+gradient/ngroups 125 | else: 126 | log.info('NFRAMES={} not valid for NIRISS (!=1 or 4)'.format(nframes)) 127 | log.info('Column jump step will be skipped') 128 | return 129 | 130 | nsigma1jump *= scaling 131 | nsigma2jumps *= scaling 132 | log.info('nsigma1jump scaled to %s' % nsigma1jump) 133 | log.info('nsigma2jumps scaled to %s' % nsigma2jumps) 134 | 135 | #Set up degrees of freedom based on ngroups 136 | dof = float(ngroups-1-1-1) 137 | countcoljump = 0 138 | 139 | # Loop over multiple integrations 140 | for integration in range(nints): 141 | log.info('working on integration %d' % (integration+1)) 142 | 143 | #Make masked array of reference pixel data for this integration only 144 | datathisint = datarp[integration,:,:,:] 145 | pdqthisint = pdqrp[integration,:,:,:] 146 | maskeddatathisint = ma.array(datathisint,mask=pdqthisint) 147 | 148 | #Make quick ramp fit to all reference pixels to identify outliers not in mask and add them to mask 149 | refpixslopes = quickrampfit(maskeddatathisint,ngroups) 150 | maskedrefpixslopes = ma.array(refpixslopes, mask=pdqthisint[0,:,:]) 151 | clipmaskedrefpixslopes = sigma_clip(maskedrefpixslopes,sigma=2.2,maxiters=3,axis=1) 152 | 153 | #Add these bad pixels to mask 154 | singlemask = np.tile(clipmaskedrefpixslopes.mask,(ngroups,1,1)) 155 | maskeddatathisint = ma.array(maskeddatathisint.data, mask=singlemask) 156 | 157 | #Use per amplifier mean of top-bottom reference pixels noise 158 | amplifier = np.array(['A','B','C','D']) 159 | colstart = np.array([4,512,1024,1536])-4 160 | colstop = np.array([512,1024,1536,2044])-4 161 | refpixareavarianceamp = np.zeros(4) 162 | for k in range(4): 163 | refpixelsthisamp = maskeddatathisint[:,colstart[k]:colstop[k],:] 164 | refpixelsnoisethisamp = sigma_clip(np.std(refpixelsthisamp,axis=0),sigma=3,maxiters=3) 165 | meanrefpixelsnoisethisamp = np.mean(refpixelsnoisethisamp) 166 | #refpixareanoiseamp is the expected noise for average of 7 reference pixels 167 | refpixareanoiseamp = meanrefpixelsnoisethisamp/(7.0**0.5) 168 | refpixareavarianceamp[k] = refpixareanoiseamp**2.0 169 | 170 | #set up arrays to store first pass results 171 | onebreaksize = np.zeros(ncols) 172 | onebreakbestk = np.zeros(ncols, dtype=int) 173 | onebreakchisqdiff = np.zeros(ncols) 174 | twobreak1size = np.zeros(ncols) 175 | twobreak2size = np.zeros(ncols) 176 | twobreakbestk = np.zeros(ncols, dtype=int) 177 | twobreakbestm = np.zeros(ncols, dtype=int) 178 | twobreakchisqdiff = np.zeros(ncols) 179 | 180 | #loop over original detector coordinate system columns 181 | for col in range(ncols): 182 | 183 | #which amplifier 184 | ampindex = np.where((col >= colstart)&(col < colstop)) 185 | refpixareavariance = refpixareavarianceamp[ampindex][0] 186 | 187 | #get reference pixels values for this column minus a clipped mean of them 188 | colrefpixsubmean = findcolrefpixsubmean(col,colstart,colstop,ampindex,maskeddatathisint,ngroups,nrows) 189 | 190 | #calculate chi-square for the flat model with no break 191 | chisqnobreak = (1.0/dof)*np.sum(((colrefpixsubmean-np.mean(colrefpixsubmean))**2.0)/refpixareavariance) 192 | 193 | chisqmin = chisqnobreak 194 | chisqmin2break = chisqnobreak 195 | 196 | #calculate chi-square for a model that has a break at each value of N_group 197 | chisqnorm = 1.0/(dof*refpixareavariance) 198 | for k in range(ngroups): 199 | if k>2 and k<(ngroups-3): 200 | lomean = np.mean(colrefpixsubmean[:k]) 201 | himean = np.mean(colrefpixsubmean[k:]) 202 | model = np.concatenate(((np.repeat(lomean,(k+1))),(np.repeat(himean,(ngroups-(k+1)))))) 203 | chisq = chisqnorm*np.sum((colrefpixsubmean-model)**2.0) 204 | 205 | #if the chi-square is better than any previous model set it as the best 206 | if chisqnsigma1jump: 224 | #which amplifier 225 | ampindex = np.where((col >= colstart)&(col < colstop)) 226 | refpixareavariance = refpixareavarianceamp[ampindex][0] 227 | 228 | #get reference pixels values for this column minus a clipped mean of them 229 | colrefpixsubmean = findcolrefpixsubmean(col,colstart,colstop,ampindex,maskeddatathisint,ngroups,nrows) 230 | 231 | #calculate chi-square for the flat model with no break 232 | chisqnobreak = (1.0/dof)*np.sum(((colrefpixsubmean-np.mean(colrefpixsubmean))**2.0)/refpixareavariance) 233 | 234 | chisqmin = chisqnobreak 235 | chisqmin2break = chisqnobreak 236 | chisqnorm = 1.0/(dof*refpixareavariance) 237 | 238 | #calculate chi-square for a model that has two breaks at different values of N_group 239 | for k in range(ngroups): 240 | if k>2 and k<(ngroups-6): 241 | for m in range(ngroups): 242 | if m-k>2 and m<(ngroups-3): 243 | lomean = np.mean(colrefpixsubmean[:k]) 244 | midmean = np.mean(colrefpixsubmean[k:m]) 245 | himean = np.mean(colrefpixsubmean[m:]) 246 | model2break = np.concatenate(((np.repeat(lomean,(k+1))),(np.repeat(midmean,(m-k))),(np.repeat(himean,(ngroups-(m+1)))))) 247 | chisq2break = chisqnorm*np.sum((colrefpixsubmean-model2break)**2.0) 248 | 249 | #if the chi-square is better than any previous model set it as the best 250 | if chisq2breaklimitonebreakchisqdiff)] 263 | clipsignificanttwominusoneb = sigma_clip(significanttwominusoneb,sigma=3.0,maxiters=3) 264 | limittwobreakchisqdiff = np.ma.max(clipsignificanttwominusoneb) 265 | mediantwobreakchisqdiff = np.ma.median(clipsignificanttwominusoneb) 266 | numsigmatwobreak = (twominusonebreakschisqdiff-mediantwobreakchisqdiff)/((limittwobreakchisqdiff-mediantwobreakchisqdiff)/3.0) 267 | 268 | #Loop over columns again to determine best model 269 | for col in range(ncols): 270 | #Run on only those that show a high chisqdiff for one break 271 | if numsigmaonebreak[col]>nsigma1jump: 272 | #Decide on whether to use 1 break or 2 break model 273 | if numsigmatwobreak[col]>nsigma2jumps: 274 | correctionarray[integration,twobreakbestk[col]:,(col+4),:]+=twobreak1size[col] 275 | correctionarray[integration,twobreakbestm[col]:,(col+4),:]+=twobreak2size[col] 276 | log.info(' column %d: 2 breaks of sizes %.3f,%.3f at groups %d,%d with numsigmatwobreak=%.3f' % ((col+4),twobreak1size[col],twobreak2size[col],twobreakbestk[col],twobreakbestm[col],numsigmatwobreak[col])) 277 | else: 278 | correctionarray[integration,onebreakbestk[col]:,(col+4),:]+=onebreaksize[col] 279 | log.info(' column %d: 1 break of size %.3f at group %d with numsigmaonebreak=%.3f' % ((col+4),onebreaksize[col],onebreakbestk[col],numsigmaonebreak[col])) 280 | 281 | countcoljump = countcoljump+1 282 | 283 | #Add to output table - column numbering is zero-indexed for full detector 284 | if outputdiagnostics == True: 285 | outtable.add_row(((col+4),numsigmaonebreak[col],numsigmatwobreak[col],onebreakbestk[col],twobreakbestk[col],twobreakbestm[col],onebreaksize[col],twobreak1size[col],twobreak2size[col])) 286 | 287 | #Finished all column loops 288 | log.info(' Done: corrected jumps in %d columns in this integration' % (countcoljump)) 289 | 290 | #Next integration (integration loop) 291 | 292 | #Output diagnostics if requested and at least one jump found 293 | if countcoljump > 0 and outputdiagnostics == True: 294 | #pdf_pages.close() 295 | ascii.write(outtable,outtablename,format='fixed_width_two_line',overwrite=True) 296 | 297 | #Update the data with the corrections before returning 298 | data+=correctionarray 299 | 300 | return 301 | 302 | 303 | -------------------------------------------------------------------------------- /makedarknoisefilesgdq.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | #module to make dark current and noise images from darks, optionally using GDQ flags 4 | #usage ./makedarknoisefilesgdq.py cubedir slopedir noisedir outfileroot fraction_maxcr --sigiters sigiters --reffile_dark reffile_dark --usegdq --logstats 5 | #e.g. ./makedarknoisefilesgdq.py /Users/willottc/niriss/detectors/cv3/colddarks/simcrs/cubefixcr/ /Users/willottc/niriss/detectors/cv3/colddarks/simcrs/rate/ /Users/willottc/niriss/detectors/cv3/colddarks/simcrs/noisewithdarksub/ test 0.33 --sigiters 3 --reffile_dark /Users/willottc/niriss/detectors/willott_reference_files/NIRISS_darkcube_cv3_38k_dms.fits --usegdq --logstats 6 | 7 | import numpy as np 8 | import os 9 | import argparse 10 | from astropy.io import fits 11 | from astropy.stats import sigma_clip 12 | import glob 13 | from copy import deepcopy 14 | import datetime 15 | import logging 16 | import stsci.imagestats as imagestats 17 | from jwst.datamodels import dqflags 18 | import natsort 19 | 20 | #=============================================================== 21 | # Command line arguments 22 | 23 | parser = argparse.ArgumentParser() 24 | parser.add_argument("cubedir", help="Location of dark cube images") 25 | parser.add_argument("slopedir", help="Location of slope or rate images") 26 | parser.add_argument("noisedir", help="Location of outout noise images") 27 | parser.add_argument("outfileroot", help="Leading string of output noise filenames") 28 | parser.add_argument("fraction_maxcr", type=float, help="If more than fraction_maxcr of the exposures of a pixel are cosmic-ray flagged, unset all the flags because these cannot all be due to cosmic rays and it must be a noisy pixel") 29 | parser.add_argument("--sigiters", type=int, default=3, help="Number of sigma-clipping iterations") 30 | parser.add_argument("--reffile_dark", default=None, help="Dark current reference file for doing dark subtraction step") 31 | parser.add_argument("--usegdq", help="Set if using GROUPDQ flagging", action="store_true") 32 | parser.add_argument("--logstats", help="Set if want to log output statistics to a file", action="store_true") 33 | 34 | args = parser.parse_args() 35 | 36 | cubedir = args.cubedir 37 | slopedir = args.slopedir 38 | noisedir = args.noisedir 39 | outfileroot = args.outfileroot 40 | fraction_maxcr = args.fraction_maxcr 41 | sigiters = args.sigiters 42 | reffile_dark = args.reffile_dark 43 | usegdq = args.usegdq 44 | logstats = args.logstats 45 | 46 | #=============================================================== 47 | #Make results directory if does not exist 48 | if not os.path.exists(noisedir): 49 | os.makedirs(noisedir) 50 | 51 | #Log statistics after making dark current and noise files if flag is set 52 | if logstats == True: 53 | 54 | #Set up logging 55 | logfile = datetime.datetime.now().strftime('darknoise_%Y%m%d_%H%M%S.log') 56 | logdirfile = os.path.join(noisedir,logfile) 57 | print ('makedarknoisefilesgdq log is {}'.format(logdirfile)) 58 | 59 | logging.basicConfig(filename=logdirfile, filemode='w', level=logging.INFO, force=True) 60 | logging.info('Running makedarknoisefilesgdq.py with parameters:') 61 | logging.info('cubedir = {}'.format(cubedir)) 62 | logging.info('slopedir = {}'.format(slopedir)) 63 | logging.info('noisedir = {}'.format(noisedir)) 64 | logging.info('outfileroot = {}'.format(outfileroot)) 65 | logging.info('fraction_maxcr = {}'.format(fraction_maxcr)) 66 | logging.info('sigiters = {}'.format(sigiters)) 67 | logging.info('reffile_dark = {}'.format(reffile_dark)) 68 | logging.info('usegdq = {}'.format(usegdq)) 69 | 70 | slope3d = [] 71 | cdsstd3d = [] 72 | 73 | #Get lists of all rate (slope) images from slopedir and cube files (after pipeline linearity step) 74 | slopedirlist = natsort.natsorted(os.listdir(slopedir)) 75 | slopedirlist[:] = (value for value in slopedirlist if value.endswith('rate.fits')) 76 | cubedirlist = natsort.natsorted(os.listdir(cubedir)) 77 | cubedirlist[:] = (value for value in cubedirlist if value.endswith('.fits')) 78 | numimages = len(slopedirlist) 79 | #reduce numimages for testing 80 | #numimages = 5 81 | print (numimages) 82 | 83 | #Load the dark reference file data extension if using 84 | if reffile_dark is not None: 85 | with fits.open(reffile_dark,memmap=True) as hdudarkref: 86 | dc = hdudarkref['SCI'].data 87 | 88 | #=============================================================== 89 | #Loop over exposures 90 | for j in range(numimages): 91 | slopefile=os.path.join(slopedir,slopedirlist[j]) 92 | cubefile=os.path.join(cubedir,cubedirlist[j]) 93 | #print ('Now running on j={} {} {}'.format(j,slopefile,cubefile)) 94 | #logging.info('Now running on j={} {} {}'.format(j,slopefile,cubefile)) 95 | with fits.open(slopefile) as slopehdulist: 96 | header = slopehdulist[0].header 97 | slope = slopehdulist['SCI'].data 98 | numgroups = header['NGROUPS'] 99 | #Trim dark current reference file to match same number of groups 100 | if reffile_dark is not None: 101 | dc = dc[:numgroups,:,:] 102 | with fits.open(cubefile) as hdulist: 103 | #Assume each dark exposure contains only one integration, so strip off that axis 104 | cube = np.squeeze(hdulist['SCI'].data) 105 | #If dark current reference file provided first subtract the dark currrent off each group 106 | if reffile_dark is not None: 107 | cube -= dc 108 | #Take cube differences to get CDS noise 109 | cds = np.diff(cube,axis=0) 110 | cds1f = deepcopy(cds) 111 | #Loop over each amp separately to separate 1/f from other readnoise 112 | numamp = 4 113 | for k in range(numamp): 114 | ymin = k*512 115 | ymax = ymin+512 116 | #Determine 1/f as median of each column 117 | medsec = np.median(cds1f[:,ymin:ymax,:],axis=1) 118 | medsecexpand = np.expand_dims(medsec, axis=1) 119 | medsecexpand = np.repeat(medsecexpand,512,axis=1) 120 | #Make CDS cube with 1/f noise subtracted 121 | cds1f[:,ymin:ymax,:] -= medsecexpand 122 | 123 | #Get std deviation of CDS cubes 124 | cdsstd = np.std(cds,axis=0) 125 | cds1fstd = np.std(cds1f,axis=0) 126 | 127 | #If using GroupDQ flagged data find cosmic ray-flagged groups and make a 2D array of all cosmic ray hit pixels 128 | if usegdq == True: 129 | gdq = hdulist['GROUPDQ'].data 130 | crflagged = np.where(np.bitwise_and(gdq, dqflags.group['JUMP_DET'])) 131 | crflag2d = np.zeros(slope.shape, dtype='uint8') 132 | crflag2d[crflagged[2],crflagged[3]] = 1 133 | 134 | #Stack slope and CDS arrays from all exposures 135 | if len(slope3d) == 0: 136 | slope3d = slope 137 | cdsstd3d = cdsstd 138 | cds1fstd3d = cds1fstd 139 | if usegdq ==True: 140 | crflag3d = crflag2d 141 | else: 142 | slope3d = np.dstack((slope3d,slope)) 143 | cdsstd3d = np.dstack((cdsstd3d,cdsstd)) 144 | cds1fstd3d = np.dstack((cds1fstd3d,cds1fstd)) 145 | if usegdq == True: 146 | crflag3d = np.dstack((crflag3d,crflag2d)) 147 | 148 | #Delete arrays that won't be used again to save space 149 | del cdsstd,cds1fstd,cds,cds1f 150 | if usegdq == True: 151 | del crflag2d 152 | 153 | 154 | 155 | #if more than some fraction of the exposures of a pixel are cosmic-ray flagged, unset all the flags because these cannot all be due to cosmic rays and it must be a noisy pixel 156 | if usegdq == True: 157 | numrampsflagged = np.sum(crflag3d,2) 158 | w = np.where(numrampsflagged>int(numimages*fraction_maxcr)) 159 | crflag3d[w[0],w[1],:] = 0 160 | #optional output image of numrampsflagged to check 161 | #print (np.mean(numrampsflagged),numrampsflagged[np.where(numrampsflagged>(numimages/3.0))].size) 162 | #fits.writeto('testnumrampsflagged.fits',numrampsflagged.astype('uint16'),header,overwrite=True) 163 | 164 | if usegdq == True: 165 | slope3dmasked = np.ma.masked_array(slope3d,mask=crflag3d) 166 | cdsstd3dmasked = np.ma.masked_array(cdsstd3d,mask=crflag3d) 167 | cds1fstd3dmasked = np.ma.masked_array(cds1fstd3d,mask=crflag3d) 168 | else: 169 | slope3dmasked = slope3d 170 | cdsstd3dmasked = cdsstd3d 171 | cds1fstd3dmasked = cds1fstd3d 172 | 173 | #=============================================================== 174 | #Make dark current and slope noise images 175 | clippedslope3d = sigma_clip(slope3dmasked,sigma=3,maxiters=sigiters,axis=2) 176 | clippedslope3dmean = np.ma.mean(clippedslope3d,axis=2) 177 | clippedslope3dmedian = np.ma.median(clippedslope3d,axis=2) 178 | clippedslope3dstd = np.ma.std(clippedslope3d,axis=2) 179 | 180 | #Make pedestal corrected version of slope images by median averaging of all 2d arrays 181 | clippedslope3dmedian1d = np.ma.median(clippedslope3d,axis=(0,1)) 182 | medclippedslope3dmedian1d = np.median(clippedslope3dmedian1d.data) 183 | offsetclippedslope1d = medclippedslope3dmedian1d-clippedslope3dmedian1d 184 | 185 | #Make pedestal corrected dark current and slope noise images 186 | clippedslope3dpc = clippedslope3d+offsetclippedslope1d 187 | clippedslope3dpcmean = np.ma.mean(clippedslope3dpc,axis=2) 188 | clippedslope3dpcmedian = np.ma.median(clippedslope3dpc,axis=2) 189 | clippedslope3dpcstd = np.ma.std(clippedslope3dpc,axis=2) 190 | 191 | header['NAXIS'] = 2 192 | 193 | clippedslope3dmean = clippedslope3dmean.data 194 | clippedslope3dmedian = clippedslope3dmedian.data 195 | clippedslope3dstd = clippedslope3dstd.data 196 | clippedslope3dpcmean = clippedslope3dpcmean.data 197 | clippedslope3dpcmedian = clippedslope3dpcmedian.data 198 | clippedslope3dpcstd = clippedslope3dpcstd.data 199 | 200 | #Write dark current and slope noise output files 201 | meanfile = os.path.join(noisedir,outfileroot+'meandark.fits') 202 | medianfile = meanfile.replace('meandark','mediandark') 203 | stdfile = meanfile.replace('meandark','sigmadark') 204 | fits.writeto(meanfile,clippedslope3dmean,header,overwrite=True) 205 | fits.writeto(medianfile,clippedslope3dmedian,header,overwrite=True) 206 | fits.writeto(stdfile,clippedslope3dstd,header,overwrite=True) 207 | 208 | meanpcfile = os.path.join(noisedir,outfileroot+'meandarkzero.fits') 209 | medianpcfile = meanpcfile.replace('meandarkzero','mediandarkzero') 210 | stdpcfile = meanpcfile.replace('meandarkzero','sigmadarkzero') 211 | fits.writeto(meanpcfile,clippedslope3dpcmean,header,overwrite=True) 212 | fits.writeto(medianpcfile,clippedslope3dpcmedian,header,overwrite=True) 213 | fits.writeto(stdpcfile,clippedslope3dpcstd,header,overwrite=True) 214 | 215 | #=============================================================== 216 | #Make and output CDS noise images 217 | #do sigma clipping on CDS std stacks 218 | clippedcdsstd3d = sigma_clip(cdsstd3dmasked,sigma=3,maxiters=sigiters,axis=2) 219 | clippedcdsstd3dmean = np.ma.mean(clippedcdsstd3d,axis=2) 220 | clippedcdsstd3dmedian = np.ma.median(clippedcdsstd3d,axis=2) 221 | clippedcdsstd3dstd = np.ma.std(clippedcdsstd3d,axis=2) 222 | 223 | clippedcdsstd3dmean = clippedcdsstd3dmean.data 224 | clippedcdsstd3dmedian = clippedcdsstd3dmedian.data 225 | clippedcdsstd3dstd = clippedcdsstd3dstd.data 226 | 227 | clippedcds1fstd3d = sigma_clip(cds1fstd3dmasked,sigma=3,maxiters=sigiters,axis=2) 228 | clippedcds1fstd3dmean = np.ma.mean(clippedcds1fstd3d,axis=2) 229 | clippedcds1fstd3dmedian = np.ma.median(clippedcds1fstd3d,axis=2) 230 | clippedcds1fstd3dstd = np.ma.std(clippedcds1fstd3d,axis=2) 231 | 232 | clippedcds1fstd3dmean = clippedcds1fstd3dmean.data 233 | clippedcds1fstd3dmedian = clippedcds1fstd3dmedian.data 234 | clippedcds1fstd3dstd = clippedcds1fstd3dstd.data 235 | 236 | #write output CDS noise files 237 | meancdsstdfile = os.path.join(noisedir,outfileroot+'meancdsstd.fits') 238 | mediancdsstdfile = meancdsstdfile.replace('meancdsstd','mediancdsstd') 239 | stdcdsstdfile = meancdsstdfile.replace('meancdsstd','sigmacdsstd') 240 | fits.writeto(meancdsstdfile,clippedcdsstd3dmean,header,overwrite=True) 241 | fits.writeto(mediancdsstdfile,clippedcdsstd3dmedian,header,overwrite=True) 242 | fits.writeto(stdcdsstdfile,clippedcdsstd3dstd,header,overwrite=True) 243 | 244 | mean1fcdsstdfile = os.path.join(noisedir,outfileroot+'meancds1fstd.fits') 245 | median1fcdsstdfile = mean1fcdsstdfile.replace('meancds1fstd','mediancds1fstd') 246 | std1fcdsstdfile = mean1fcdsstdfile.replace('meancds1fstd','sigmacds1fstd') 247 | fits.writeto(mean1fcdsstdfile,clippedcds1fstd3dmean,header,overwrite=True) 248 | fits.writeto(median1fcdsstdfile,clippedcds1fstd3dmedian,header,overwrite=True) 249 | fits.writeto(std1fcdsstdfile,clippedcds1fstd3dstd,header,overwrite=True) 250 | 251 | #=============================================================== 252 | #optionally log stats 253 | if logstats == True: 254 | 255 | logging.info('Pedestal Correction offsets: {}'.format(offsetclippedslope1d)) 256 | logging.info('Std dev of Pedestal Correction offsets: {}'.format(np.std(offsetclippedslope1d))) 257 | 258 | logging.info('') 259 | logging.info('Stats of slope and slope noise files, with and without predestal correction') 260 | 261 | i = imagestats.ImageStats(clippedslope3dmean[4:2044,4:2044],fields="npix,min,max,median,mean,stddev",nclip=3,lsig=3.0,usig=3.0,binwidth=0.1) 262 | logging.info('{} Mean: {}, Median: {}, Std dev: {}'.format(meanfile,i.mean,i.median,i.stddev)) 263 | i = imagestats.ImageStats(clippedslope3dmedian[4:2044,4:2044],fields="npix,min,max,median,mean,stddev",nclip=3,lsig=3.0,usig=3.0,binwidth=0.1) 264 | logging.info('{} Mean: {}, Median: {}, Std dev: {}'.format(medianfile,i.mean,i.median,i.stddev)) 265 | i = imagestats.ImageStats(clippedslope3dstd[4:2044,4:2044],fields="npix,min,max,median,mean,stddev",nclip=3,lsig=3.0,usig=3.0,binwidth=0.1) 266 | logging.info('{} Mean: {}, Median: {}, Std dev: {}'.format(stdfile,i.mean,i.median,i.stddev)) 267 | i = imagestats.ImageStats(clippedslope3dpcmean[4:2044,4:2044],fields="npix,min,max,median,mean,stddev",nclip=3,lsig=3.0,usig=3.0,binwidth=0.1) 268 | logging.info('{} Mean: {}, Median: {}, Std dev: {}'.format(meanpcfile,i.mean,i.median,i.stddev)) 269 | i = imagestats.ImageStats(clippedslope3dpcmedian[4:2044,4:2044],fields="npix,min,max,median,mean,stddev",nclip=3,lsig=3.0,usig=3.0,binwidth=0.1) 270 | logging.info('{} Mean: {}, Median: {}, Std dev: {}'.format(medianpcfile,i.mean,i.median,i.stddev)) 271 | i = imagestats.ImageStats(clippedslope3dpcstd[4:2044,4:2044],fields="npix,min,max,median,mean,stddev",nclip=3,lsig=3.0,usig=3.0,binwidth=0.1) 272 | logging.info('{} Mean: {}, Median: {}, Std dev: {}'.format(stdpcfile,i.mean,i.median,i.stddev)) 273 | 274 | logging.info('') 275 | logging.info('Stats of CDS noise files (non-reference pixels), with and without 1/f subtraction') 276 | i = imagestats.ImageStats(clippedcdsstd3dmean[4:2044,4:2044],fields="npix,min,max,median,mean,stddev",nclip=3,lsig=3.0,usig=3.0,binwidth=0.1) 277 | logging.info('{} Mean: {}, Median: {}, Std dev: {}'.format(meancdsstdfile,i.mean,i.median,i.stddev)) 278 | i = imagestats.ImageStats(clippedcdsstd3dmedian[4:2044,4:2044],fields="npix,min,max,median,mean,stddev",nclip=3,lsig=3.0,usig=3.0,binwidth=0.1) 279 | logging.info('{} Mean: {}, Median: {}, Std dev: {}'.format(mediancdsstdfile,i.mean,i.median,i.stddev)) 280 | i = imagestats.ImageStats(clippedcdsstd3dstd[4:2044,4:2044],fields="npix,min,max,median,mean,stddev",nclip=3,lsig=3.0,usig=3.0,binwidth=0.1) 281 | logging.info('{} Mean: {}, Median: {}, Std dev: {}'.format(stdcdsstdfile,i.mean,i.median,i.stddev)) 282 | #1/f subtracted CDS noise 283 | i = imagestats.ImageStats(clippedcds1fstd3dmean[4:2044,4:2044],fields="npix,min,max,median,mean,stddev",nclip=3,lsig=3.0,usig=3.0,binwidth=0.1) 284 | logging.info('1/f corrected {} Mean: {}, Median: {}, Std dev: {}'.format(mean1fcdsstdfile,i.mean,i.median,i.stddev)) 285 | i = imagestats.ImageStats(clippedcds1fstd3dmedian[4:2044,4:2044],fields="npix,min,max,median,mean,stddev",nclip=3,lsig=3.0,usig=3.0,binwidth=0.1) 286 | logging.info('1/f corrected {} Mean: {}, Median: {}, Std dev: {}'.format(median1fcdsstdfile,i.mean,i.median,i.stddev)) 287 | i = imagestats.ImageStats(clippedcds1fstd3dstd[4:2044,4:2044],fields="npix,min,max,median,mean,stddev",nclip=3,lsig=3.0,usig=3.0,binwidth=0.1) 288 | logging.info('1/f corrected {} Mean: {}, Median: {}, Std dev: {}'.format(std1fcdsstdfile,i.mean,i.median,i.stddev)) 289 | -------------------------------------------------------------------------------- /makenirissimagingflats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | #Generate NIRISS imaging flat field reference files. 4 | #Uses jwst and jwst_reffiles python packages 5 | #Normalize, sigma clip and combine multiple flat integrations/exposures. 6 | #The flat field will be normalized to a sigma-clipped average value of one as per the CALWEBB_IMAGE2 definition. 7 | #No surface fitting to account for uneven illumination is applied since the CV3 OSIM illumination pattern is unknown. 8 | #Four unusual blob regions in some filter images are replaced with the F200W flat that doesn't show them. 9 | #Inputs: place all flat field slope_rateints.fits and/or slope_rate.fits files in one sub-directory per filter under the input directory indir, e.g. ./slope/F150W/ 10 | #Outputs: final flat field images will be output to one sub-directory per filter under the output directory, e.g. ./imageflatreffiles/F150W/ 11 | 12 | #Usage, e.g. 13 | #makenirissimagingflats.py --indir='./slope' --outdir='./imageflatreffiles' 14 | 15 | import numpy as np 16 | import optparse, sys 17 | import os 18 | import astropy.io.fits as fits 19 | from astropy.stats import SigmaClip,sigma_clip,sigma_clipped_stats 20 | from copy import deepcopy 21 | from photutils import detect_threshold,detect_sources,Background2D, MedianBackground,source_properties, CircularAperture, CircularAnnulus 22 | import natsort 23 | from jwst.datamodels import FlatModel, util 24 | from jwst_reffiles.bad_pixel_mask import bad_pixel_mask 25 | 26 | # Command line options 27 | op = optparse.OptionParser() 28 | op.add_option("--indir") 29 | op.add_option("--outdir") 30 | 31 | o, a = op.parse_args() 32 | if a: 33 | print (sys.stderr, "unrecognized option: ",a) 34 | sys.exit(-1) 35 | 36 | indir=o.indir 37 | outdir=o.outdir 38 | if indir==None: 39 | indir='./' 40 | if outdir==None: 41 | outdir='./' 42 | 43 | if not os.path.exists(outdir): 44 | os.makedirs(outdir) 45 | 46 | def save_final_map(flat_map, flat_dq, flat_err, dqdef, instrument, detector, hdulist, filterdir, files, 47 | author, description, pedigree,useafter, fpatemp, history_text, outfile): 48 | """Save a flat field map into a CRDS-formatted reference file 49 | Parameters 50 | ---------- 51 | flat_map : numpy.ndarray 52 | 2D flat-field array 53 | flat_dq : numpy.ndarray 54 | 2D flat-field DQ array 55 | flat_err : numpy.ndarray 56 | 2D flat-field error array 57 | dqdef : numpy.ndarray 58 | binary table of DQ definitions 59 | instrument : str 60 | Name of instrument associated with the flat-field array 61 | detector : str 62 | Name of detector associated with the flat-field array 63 | hdulist : astropy.fits.HDUList 64 | HDUList containing "extra" fits keywords 65 | files : list 66 | List of files used to create reference file 67 | author : str 68 | Author of the reference file 69 | description : str 70 | CRDS description to use in the final reference file 71 | pedigree : str 72 | CRDS pedigree to use in the final reference file 73 | useafter : str 74 | CRDS useafter string for the reference file 75 | history_text : list 76 | List of strings to add as HISTORY entries to the reference file 77 | outfile : str 78 | Name of the output reference file 79 | """ 80 | yd, xd = flat_map.shape 81 | 82 | # Initialize the MaskModel using the hdu_list, so the new keywords will 83 | # be populated 84 | model = FlatModel(hdulist) 85 | model.data = flat_map 86 | model.dq = flat_dq 87 | model.err = flat_err 88 | model.dq_def = dqdef 89 | 90 | #Load a file to get some header info 91 | primaryheader=fits.getheader(os.path.join(filterdir,files[0])) 92 | filterwheel=primaryheader['FILTER'] 93 | pupilwheel=primaryheader['PUPIL'] 94 | 95 | model.meta.reftype = 'FLAT' 96 | model.meta.subarray.name = 'FULL' 97 | model.meta.subarray.xstart = 1 98 | model.meta.subarray.xsize = xd 99 | model.meta.subarray.ystart = 1 100 | model.meta.subarray.ysize = yd 101 | model.meta.instrument.name = instrument.upper() 102 | model.meta.instrument.detector = detector 103 | model.meta.instrument.filter=filterwheel 104 | model.meta.instrument.pupil=pupilwheel 105 | 106 | # Get the fast and slow axis directions from one of the input files 107 | fastaxis, slowaxis = bad_pixel_mask.badpix_from_flats.get_fastaxis(os.path.join(filterdir,files[0])) 108 | model.meta.subarray.fastaxis = fastaxis 109 | model.meta.subarray.slowaxis = slowaxis 110 | 111 | model.meta.author = author 112 | model.meta.description = description 113 | model.meta.pedigree = pedigree 114 | model.meta.useafter = useafter 115 | 116 | # Add HISTORY information 117 | package_note = ('This file was created using https://github.com/chriswillott/jwst/blob/master/makenirissimagingflats.py') 118 | entry = util.create_history_entry(package_note) 119 | model.history.append(entry) 120 | package_note = ('FPA Temperature={}K'.format(fpatemp)) 121 | entry = util.create_history_entry(package_note) 122 | model.history.append(entry) 123 | 124 | 125 | # Add the list of input files used to create the map 126 | model.history.append('DATA USED:') 127 | for file in files: 128 | totlen = len(file) 129 | div = np.arange(0, totlen, 60) 130 | for val in div: 131 | if totlen > (val+60): 132 | model.history.append(util.create_history_entry(file[val:val+60])) 133 | else: 134 | model.history.append(util.create_history_entry(file[val:])) 135 | 136 | # Add the do not use lists, pixel flag mappings, and user-provided 137 | # history text 138 | for history_entry in history_text: 139 | if history_entry != '': 140 | model.history.append(util.create_history_entry(history_entry)) 141 | 142 | model.save(outfile, overwrite=True) 143 | print('Final flat reference file save to: {}'.format(outfile)) 144 | 145 | 146 | ###Main program### 147 | 148 | #Information for file header 149 | author='Chris Willott' 150 | description='This is a pixel flat reference file.' 151 | pedigree= 'GROUND ' 152 | useafter= '2015-11-01T00:00:00' 153 | 154 | #Get list of directories with filter names 155 | filterdirlist=natsort.natsorted(os.listdir(indir)) 156 | filterdirlist[:] =(value for value in filterdirlist if value.startswith('F')) 157 | filterdirlist=np.array(filterdirlist) 158 | 159 | #Reorder to put F200W first since that will be used for patching some other filters 160 | w=np.where(filterdirlist=='F200W') 161 | filterdirlist[w]=filterdirlist[0] 162 | filterdirlist[0]='F200W' 163 | numfilters=len(filterdirlist) 164 | print (numfilters,' filters for flat-field reference files') 165 | 166 | #Iterate over filters 167 | for l in range(numfilters): 168 | 169 | #F090W only done at warm plateau in CV3 170 | if filterdirlist[l] =='F090W': 171 | fpatemp=43.699 172 | else: 173 | fpatemp=37.749 174 | 175 | normdata3d=[] 176 | #Get list of files in this directory 177 | filterdir=os.path.join(indir,filterdirlist[l]) 178 | dirlist=natsort.natsorted(os.listdir(filterdir)) 179 | dirlist[:] = (value for value in dirlist if value.endswith('.fits')) 180 | numfiles=len(dirlist) 181 | print(' ') 182 | print ('Filter=',filterdirlist[l],' with ',numfiles,' files') 183 | 184 | if numfiles>0: 185 | for j in range(numfiles): 186 | #Read in file 187 | slopefile=os.path.join(filterdir,dirlist[j]) 188 | instrument, detector = bad_pixel_mask.instrument_info(slopefile) 189 | print ('Processing file ',dirlist[j]) 190 | hdulist=fits.open(slopefile) 191 | header=hdulist[0].header 192 | data=hdulist['SCI'].data 193 | err=hdulist['ERR'].data 194 | #Stack data and error arrays into 3D arrays 195 | if '_rateints.fits' in slopefile: 196 | nint=data.shape[0] 197 | for k in range(nint): 198 | #Don't include reference pixels or pixels bordering reference pixels in statistics for normalization 199 | datafornormalize=data[k,5:2043,5:2043] 200 | normdata=data[k,:,:]/np.median(datafornormalize) 201 | normerr=err[k,:,:]/np.median(datafornormalize) 202 | if len(normdata3d)==0: 203 | normdata3d=normdata 204 | normerr3d=normerr 205 | else: 206 | normdata3d=np.dstack((normdata3d,normdata)) 207 | normerr3d=np.dstack((normerr3d,normerr)) 208 | elif '_rate.fits' in slopefile: 209 | #Don't include reference pixels or pixels bordering reference pixels in statistics for normalization 210 | datafornormalize=data[5:2043,5:2043] 211 | normdata=data/np.median(datafornormalize) 212 | normerr=err/np.median(datafornormalize) 213 | if len(normdata3d)==0: 214 | normdata3d=normdata 215 | normerr3d=normerr 216 | else: 217 | normdata3d=np.dstack((normdata3d,normdata)) 218 | normerr3d=np.dstack((normerr3d,normerr)) 219 | 220 | #Combine stacks clipping outliers and masked arrays 221 | #If 10 or more total integrations use sigma clipping with sigma=3.0 where sigma is std dev from all integrations 222 | #If less than 10 total integrations exclude everything >5sigma from median using sigma from error array 223 | numtotint=normdata3d.shape[2] 224 | print ('Total of ',numtotint,' integrations for this filter') 225 | if numtotint<10: 226 | numsigma=5 227 | meddata3d=np.median(normdata3d,axis=2,keepdims=True) 228 | datadiffs=normdata3d-meddata3d 229 | datadiffsdiverr=datadiffs/normerr3d 230 | datadiffsdiverrmasked=np.ma.masked_greater_equal(datadiffsdiverr,numsigma) 231 | clippeddata3d=np.ma.masked_array(normdata3d,datadiffsdiverrmasked.mask) 232 | clippederr3d=np.ma.masked_array(normerr3d,clippeddata3d.mask) 233 | else: 234 | numsigma=3.0 235 | clippeddata3d=sigma_clip(normdata3d,sigma=numsigma,maxiters=2,axis=2,cenfunc='median') 236 | clippederr3d=np.ma.masked_array(normerr3d,clippeddata3d.mask) 237 | #For data array use mean of clipped array 238 | meanclippeddata=np.ma.mean(clippeddata3d,axis=2) 239 | #For error array add errors in quadrature and divide by number of unmasked samples 240 | meanclippederr=(1.0/(np.sum((~clippederr3d.mask),axis=2)))*(np.ma.sum((clippederr3d**2),axis=2))**0.5 241 | 242 | #Patch unusual blob regions in some filter images, replacing with the F200W flat that doesn't show them. 243 | if filterdirlist[l] != 'F200W': 244 | hdulistf200w=fits.open('jwst_niriss_cv3_imageflat_F200W.fits') 245 | dataf200w=hdulistf200w['SCI'].data 246 | #These are x,y positions for photutils 247 | blobcen=np.array([[1218,1590],[1888,1044],[1975,963],[179,1865]]) 248 | #Radii covering complete blob regions to be replaced 249 | blobradius=np.array([13,10,13,6]) 250 | for k in range(4): 251 | if ((k==0)or((k==2)and((filterdirlist[l]=='F090W')or(filterdirlist[l]=='F140M')or(filterdirlist[l]=='F150W')or(filterdirlist[l]=='F158M')or(filterdirlist[l]=='F277W')))or(((k==1)or(k==3))and((filterdirlist[l]=='F090W')or(filterdirlist[l]=='F115W')or(filterdirlist[l]=='F140M')or(filterdirlist[l]=='F150W')or(filterdirlist[l]=='F158M')or(filterdirlist[l]=='F277W')))): 252 | #local normalization in nearby annulus just outside blobs 253 | blob_annulus_aperture = CircularAnnulus(blobcen[k,:], r_in=1.2*blobradius[k], r_out=2.0*blobradius[k]) 254 | blob_annulus_masks = blob_annulus_aperture.to_mask(method='center') 255 | 256 | blob_annulus_meanclippeddata = blob_annulus_masks.multiply(meanclippeddata) 257 | blob_annulus_mask = blob_annulus_masks.data 258 | blob_annulus_meanclippeddata_1d = blob_annulus_meanclippeddata[blob_annulus_mask > 0] 259 | blob_annulus_meanclippeddata_clipped=sigma_clip(blob_annulus_meanclippeddata_1d,sigma=3.0,maxiters=3) 260 | blob_annulus_meanclippeddata_median=np.ma.median(blob_annulus_meanclippeddata_clipped) 261 | 262 | blob_annulus_dataf200w = blob_annulus_masks.multiply(dataf200w) 263 | blob_annulus_dataf200w_1d = blob_annulus_dataf200w[blob_annulus_mask > 0] 264 | blob_annulus_dataf200w_clipped=sigma_clip(blob_annulus_dataf200w_1d,sigma=3.0,maxiters=3) 265 | blob_annulus_dataf200w_median=np.ma.median(blob_annulus_dataf200w_clipped) 266 | 267 | blob_scale_gr150c=blob_annulus_meanclippeddata_median/blob_annulus_dataf200w_median 268 | 269 | blob_scaled_dataf200w=dataf200w*blob_scale_gr150c 270 | 271 | xlo=blobcen[k,0]-blobradius[k] 272 | xhi=blobcen[k,0]+blobradius[k]+1 273 | ylo=blobcen[k,1]-blobradius[k] 274 | yhi=blobcen[k,1]+blobradius[k]+1 275 | 276 | #Replace with F200W values 277 | meanclippeddata[ylo:yhi,xlo:xhi]=blob_scaled_dataf200w[ylo:yhi,xlo:xhi] 278 | #Set S/N=100 for all replaced regions of blobs because of possible systematics 279 | meanclippederr[ylo:yhi,xlo:xhi]=meanclippeddata[ylo:yhi,xlo:xhi]/100.0 280 | 281 | 282 | #Renormalize using clipping after excluding all pixels with values <0.1 283 | fornormalize=meanclippeddata[5:2043,5:2043] 284 | quicknorm=fornormalize/np.median(fornormalize) 285 | w=np.where(quicknorm>0.10) 286 | fornormalize=fornormalize[w].flatten() 287 | fornormclipped=sigma_clip(fornormalize,sigma=3.0,maxiters=3,cenfunc='median') 288 | meanfornormclipped=np.ma.mean(fornormclipped) 289 | normdata=meanclippeddata/meanfornormclipped 290 | normdata=normdata.data 291 | normerr=meanclippederr/meanfornormclipped 292 | normerr=normerr.data 293 | 294 | #UNRELIABLE_FLAT for all pixels at active pixel border because 10% higher in flats 295 | unrelflat=np.zeros(normdata.shape,dtype=int) 296 | unrelflat[4:5,4:2044]=1 297 | unrelflat[2043:2044,4:2044]=1 298 | unrelflat[5:2043,4:5]=1 299 | unrelflat[5:2043,2043:2044]=1 300 | 301 | #UNRELIABLE_FLAT for all pixels with values <0.1 302 | unrelflat[np.where(normdata<0.1)]=1 303 | 304 | #Reference pixel flag for all reference pixels 305 | refpix=np.zeros(normdata.shape,dtype=int) 306 | refpix[:4,:]=1 307 | refpix[2044:,:]=1 308 | refpix[:,:4]=1 309 | refpix[:,2044:]=1 310 | 311 | #Set all reference pixels to one 312 | normdata[np.where(refpix==1)]=1.0 313 | normerr[np.where(refpix==1)]=1.0 314 | 315 | #Set all negative pixels to zero 316 | normerr[np.where(normdata<0.0)]=0.0 317 | normdata[np.where(normdata<0.0)]=0.0 318 | 319 | #Define DQ_DEF binary table HDU 320 | flagtable=np.rec.array([ 321 | ( 0, 0, 'GOOD', 'Good pixel'), 322 | ( 0, 1, 'DO_NOT_USE', 'Bad pixel. Do not use for science or calibration'), 323 | ( 1, 2, 'NO_FLAT_FIELD', 'Flat field cannot be measured'), 324 | ( 2, 4, 'UNRELIABLE_FLAT', 'Flat variance large'), 325 | ( 4, 8, 'REFERENCE_PIXEL', 'All reference pixels' )], 326 | formats='int8,int8,a40,a80', 327 | names='Bit,Value,Name,Description') 328 | dqdef = flagtable 329 | #dqdef = fits.BinTableHDU(flagtable,name='DQ_DEF ',ver=1) 330 | 331 | #Set up DQ array 332 | dq=np.zeros(normdata.shape,dtype=np.int8) 333 | 334 | #Set UNRELIABLE_FLAT and REFERENCE_PIXEL flagged pixels to DO_NOT_USE 335 | bitvalue=flagtable['Value'][np.where(flagtable['Name']==b'DO_NOT_USE')][0] 336 | flagarray=np.ones(normdata.shape, dtype=np.int8)*bitvalue 337 | w=np.where((unrelflat>0)|(refpix>0)) 338 | dq[w]=np.bitwise_or(dq[w],flagarray[w]) 339 | #dq[w]=flagarray[w] 340 | 341 | bitvalue=flagtable['Value'][np.where(flagtable['Name']==b'UNRELIABLE_FLAT')][0] 342 | flagarray=np.ones(normdata.shape, dtype=np.int8)*bitvalue 343 | w=np.where(unrelflat>0) 344 | dq[w]=np.bitwise_or(dq[w],flagarray[w]) 345 | #dq[w]=flagarray[w] 346 | 347 | bitvalue=flagtable['Value'][np.where(flagtable['Name']==b'REFERENCE_PIXEL')][0] 348 | flagarray=np.ones(normdata.shape, dtype=np.int8)*bitvalue 349 | w=np.where(refpix>0) 350 | dq[w]=np.bitwise_or(dq[w],flagarray[w]) 351 | #dq[w]=flagarray[w] 352 | 353 | history = [] 354 | hdu = fits.PrimaryHDU() 355 | all_files=dirlist 356 | 357 | #Output files in reference file format 358 | outfile = 'jwst_niriss_cv3_imageflat_{}.fits'.format(filterdirlist[l]) 359 | #outfile = 'jwst_niriss_cv3_imageflat_{}_{}.fits'.format(filterdirlist[l], current_time) 360 | outdirwithfilter=os.path.join(outdir, filterdirlist[l]) 361 | output_file = os.path.join(outdirwithfilter,outfile) 362 | if not os.path.exists(outdirwithfilter): 363 | os.makedirs(outdirwithfilter) 364 | hdu_list = fits.HDUList([hdu]) 365 | save_final_map(normdata, dq, normerr, dqdef, instrument.upper(), detector.upper(), hdu_list, filterdir, all_files, author, description, pedigree, useafter, fpatemp, history, output_file) 366 | 367 | -------------------------------------------------------------------------------- /getipc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #This procedure determines a 5x5 IPC kernel image based on spread of charge from hot pixels 3 | #Includes the NIRISS void map to calculate a different IPC kernel within the void region 4 | #Uses noise and bad pixel files output by makebpmreadnoise.py 5 | #Outputs 5x5 images for each amp in the void and outside and a 5x5x2048x2048 array of IPC across the full detector 6 | #Also outputs a normalized 3x3x2048x2048 array of IPC across the full detector as that is what is required for the JWST pipeline 7 | 8 | import numpy as np 9 | import re 10 | import os 11 | import optparse 12 | import shlex, subprocess, signal 13 | from astropy.io import fits 14 | from astropy.stats import sigma_clip 15 | from astropy.table import Table, Column 16 | import natsort 17 | from copy import deepcopy 18 | import time 19 | import stsci.imagestats as imagestats 20 | from photutils import CircularAnnulus 21 | from photutils import aperture_photometry 22 | import scipy.ndimage 23 | 24 | #Set to enforce IPC symmetry rather than use each of the 25 pixels independently 25 | makesymm=True 26 | 27 | #NIRISS Detector 28 | #noise files are in units of ADU so need gain to convert to electrons 29 | gain=1.62 30 | 31 | #define reference file locations 32 | refdir='/home/user/reffiles' 33 | darkrefdir='/home/user/darkresults' 34 | longbpmfile=darkrefdir+'jwst_niriss_com_bpm_long.fits' 35 | shortbpmfile=darkrefdir+'jwst_niriss_com_bpm_short.fits' 36 | typebpmdir=darkrefdir+'badpixeltypes/' 37 | typebpmfile=typebpmdir+'jwst_niriss_com_bpm_type' 38 | hotfile=typebpmfile+'_hot.fits' 39 | badflatfile=typebpmfile+'_unrelflat.fits' 40 | donotuselongfile=typebpmfile+'_donotuse_long.fits' 41 | refpixfile=typebpmfile+'_refpixel.fits' 42 | voidmaskfile=refdir+'volk_voidmask10.fits' 43 | ipcfile=refdir+'jwst_niriss_com_ipc.fits' 44 | 45 | ipc4d=np.zeros((5,5,2048,2048)) 46 | 47 | 48 | #location of dark noise files 49 | darknoisedir='/home/user/darkresults/noise/' 50 | 51 | #Load dark noise data and multiply by gain to get in e- 52 | slopenoisefile=darknoisedir+'gdqsigmadarkzero.fits' 53 | hdulist=fits.open(slopenoisefile) 54 | header=hdulist[0].header 55 | slopenoise=hdulist[0].data*gain 56 | 57 | darkcurrfile=darknoisedir+'gdqmediandark.fits' 58 | hdulist=fits.open(darkcurrfile) 59 | darkcurr=hdulist[0].data*gain 60 | 61 | cdsnoisefile=darknoisedir+'gdqmediancds1fstd.fits' 62 | hdulist=fits.open(cdsnoisefile) 63 | cdsnoise=hdulist[0].data*gain 64 | 65 | 66 | #load hot pixel array 67 | hdulist=fits.open(hotfile) 68 | hotflagged=hdulist[0].data 69 | 70 | #load bad flat to exclude pixels bordering on ref pixels 71 | hdulist=fits.open(badflatfile) 72 | badflatflagged=hdulist[0].data 73 | 74 | #load bad pixel file and refpixel file to exclude bad and ref pixels from median DC 75 | hdulist=fits.open(donotuselongfile) 76 | donotuselongflagged=hdulist[0].data 77 | hdulist=fits.open(refpixfile) 78 | refpixflagged=hdulist[0].data 79 | 80 | #load voidmask 81 | hdulist=fits.open(voidmaskfile) 82 | voidmask=hdulist[0].data 83 | 84 | #create an empty array for bad pixel mask and donotuse mask 85 | arrshape=(5,5) 86 | ipc=np.zeros(arrshape) 87 | 88 | 89 | ##Dark images section## 90 | #slopenoiseactive=slopenoise[4:2044,4:2044] 91 | #imstatslope = imagestats.ImageStats(slopenoiseactive,fields="npix,min,max,median,mean,stddev",binwidth=0.1,nclip=3) 92 | #imstatslope.printStats() 93 | 94 | #cdsnoiseactive=cdsnoise[4:2044,4:2044] 95 | #imstatcds = imagestats.ImageStats(cdsnoiseactive,fields="npix,min,max,median,mean,stddev",binwidth=0.1,nclip=3) 96 | #imstatcds.printStats() 97 | 98 | #darkcurractive=darkcurr[4:2044,4:2044] 99 | imstatdark = imagestats.ImageStats(darkcurr,fields="npix,min,max,median,mean,stddev",binwidth=0.1,nclip=3) 100 | imstatdark.printStats() 101 | 102 | #Get hot pixels not in void - need to add void mask sel below 103 | w=(np.where((voidmask!=1)&(hotflagged==1)&(badflatflagged!=1)&(darkcurr>1.0)&(darkcurr<100.0))) 104 | print (darkcurr[w].size) 105 | yhotnotvoid=w[0] 106 | xhotnotvoid=w[1] 107 | #print (yhotnotvoid,xhotnotvoid) 108 | numhotnotvoid=yhotnotvoid.size 109 | 110 | #Get hot pixels in void - repeat above block 111 | w=(np.where((voidmask==1)&(hotflagged==1)&(badflatflagged!=1)&(darkcurr>1.0)&(darkcurr<100.0))) 112 | print (darkcurr[w].size) 113 | yhotinvoid=w[0] 114 | xhotinvoid=w[1] 115 | #print (yhotinvoid,xhotinvoid) 116 | numhotinvoid=yhotinvoid.size 117 | 118 | 119 | 120 | #Use per amplifier - exclude pixels near amp edges 121 | amplifier=np.array(['4','3','2','1','all']) 122 | colstart=np.array([7,514,1028,1538,7]) 123 | colstop=np.array([510,1020,1534,2041,2041]) 124 | 125 | for j in range(5): 126 | 127 | ampmask=np.zeros((2048,2048),'uint16') 128 | ampmask[j*512:(1+j)*512,:]=1 129 | #Get stats in amplifier section for medians in out and of voids 130 | darkcurrsection=darkcurr[colstart[j]:colstop[j],:] 131 | badflatflaggedsection=badflatflagged[colstart[j]:colstop[j],:] 132 | donotuselongflaggedsection=donotuselongflagged[colstart[j]:colstop[j],:] 133 | refpixflaggedsection=refpixflagged[colstart[j]:colstop[j],:] 134 | voidmasksection=voidmask[colstart[j]:colstop[j],:] 135 | 136 | #===================================================================================================== 137 | #Firstly work on out of void region 138 | w=(np.where((voidmasksection!=1)&(badflatflaggedsection!=1)&(donotuselongflaggedsection!=1)&(refpixflaggedsection!=1))) 139 | clippeddarkcurrsection=sigma_clip(darkcurrsection[w],sigma=3,maxiters=5) 140 | mediandarkcurrnotvoid=np.ma.median(clippeddarkcurrsection) 141 | #mediandarkcurrnotvoid=np.median(darkcurrsection[w]) 142 | print (amplifier[j],mediandarkcurrnotvoid) 143 | #In void - not for amp A 144 | if j>0: 145 | w=(np.where((voidmasksection==1)&(badflatflaggedsection!=1)&(donotuselongflaggedsection!=1)&(refpixflaggedsection!=1))) 146 | mediandarkcurrinvoid=np.median(darkcurrsection[w]) 147 | print (amplifier[j],mediandarkcurrinvoid) 148 | 149 | #only use pixels >3 away from ref pixels and with no hot (>1 e/s) neighbours 150 | fiveby3d=[] 151 | for k in range(numhotnotvoid): 152 | if ((yhotnotvoid[k]>colstart[j])and(yhotnotvoid[k]6)and(xhotnotvoid[k]<2041)): 153 | fivebydc=darkcurr[yhotnotvoid[k]-3:yhotnotvoid[k]+4,xhotnotvoid[k]-3:xhotnotvoid[k]+4] 154 | numhotincutout=fivebydc[np.where(fivebydc>1.0)].size 155 | if numhotincutout<2: 156 | fiveby=fivebydc-mediandarkcurrnotvoid 157 | fiveby=fiveby/np.sum(fiveby) 158 | #if doing all amps together flip if in amps 4 or 2 159 | if ((j==4) and (((yhotnotvoid[k]>colstart[0]) and (yhotnotvoid[k]colstart[2]) and (yhotnotvoid[k]colstart[j])and(yhotinvoid[k]6)and(xhotinvoid[k]<2041)): 244 | fivebydc=darkcurr[yhotinvoid[k]-3:yhotinvoid[k]+4,xhotinvoid[k]-3:xhotinvoid[k]+4] 245 | numhotincutout=fivebydc[np.where(fivebydc>1.0)].size 246 | if numhotincutout<2: 247 | fiveby=fivebydc-mediandarkcurrinvoid 248 | fiveby=fiveby/np.sum(fiveby) 249 | #if doing all amps together flip if in amps 4 or 2 250 | if ((j==4) and (((yhotnotvoid[k]>colstart[0]) and (yhotnotvoid[k]colstart[2]) and (yhotnotvoid[k]0 and j<4: 339 | #put section in 4D IPC file 340 | w=np.where((voidmask==1)&(ampmask==1)) 341 | print (ipc4d[:,:,w[0],w[1]].shape,normclippedfiveby3dmedianinvoidexpand[:,:,w[0],w[1]].shape) 342 | ipc4d[:,:,w[0],w[1]]=normclippedfiveby3dmedianinvoidexpand[:,:,w[0],w[1]] 343 | 344 | 345 | #set all reference pixels to 1 in centre and zero elsewhere 346 | w=np.where(refpixflagged==1) 347 | print (refpixflagged[w].size) 348 | ipc4d[:,:,w[0],w[1]]=0 349 | ipc4d[2,2,w[0],w[1]]=1 350 | 351 | #output 4D IPC convolution reference file with 5x5 352 | header['NAXIS'] = 4 353 | fits.writeto(ipcfile,ipc4d,header,overwrite=True) 354 | 355 | 356 | #make a 4D IPC convolution reference file with 3x3 for the official reference file - will need to renormalize 357 | ipc4d_3by3=ipc4d[1:4,1:4,:,:] 358 | print (ipc4d_3by3.shape) 359 | 360 | #Do per amplifier 361 | amplifier=np.array(['4','3','2','1']) 362 | colstart=np.array([4,512,1024,1536]) 363 | colstop=np.array([512,1024,1536,2044]) 364 | for j in range(4): 365 | 366 | ampmask=np.zeros((2048,2048),'uint16') 367 | ampmask[j*512:(1+j)*512,:]=1 368 | 369 | #first do void region (only if not amp 4) 370 | if j>0: 371 | w=np.where((voidmask==1)&(ampmask==1)&(refpixflagged==0)) 372 | print (voidmask[w].size,w[0][0],w[1][0]) 373 | scale = np.sum(ipc4d_3by3[:,:,w[0][0],w[1][0]]) 374 | print (j, scale) 375 | print (w[0][0],w[1][0]) 376 | print (ipc4d_3by3[:,:,w[0][0],w[1][0]]) 377 | ipc4d_3by3[:,:,w[0],w[1]] = ipc4d_3by3[:,:,w[0],w[1]] / scale 378 | print (np.sum(ipc4d_3by3[:,:,w[0][0],w[1][0]])) 379 | 380 | #then do out of void region 381 | w=np.where((voidmask==0)&(ampmask==1)&(refpixflagged==0)) 382 | print (voidmask[w].size,w[0][0],w[1][0]) 383 | scale = np.sum(ipc4d_3by3[:,:,w[0][0],w[1][0]]) 384 | print (j, scale) 385 | print (w[0][0],w[1][0]) 386 | print (ipc4d_3by3[:,:,w[0][0],w[1][0]]) 387 | ipc4d_3by3[:,:,w[0],w[1]] = ipc4d_3by3[:,:,w[0],w[1]] / scale 388 | print (np.sum(ipc4d_3by3[:,:,w[0][0],w[1][0]])) 389 | 390 | #set all reference pixels to 1 in centre and zero elsewhere 391 | w=np.where(refpixflagged==1) 392 | print (refpixflagged[w].size) 393 | ipc4d_3by3[:,:,w[0],w[1]]=0 394 | ipc4d_3by3[1,1,w[0],w[1]]=1 395 | 396 | #output 4D IPC convolution reference file with 3x3 397 | header['NAXIS'] = 4 398 | ipcfile_3by3 = ipcfile.replace('.fits','_3x3.fits') 399 | fits.writeto(ipcfile_3by3,ipc4d_3by3,header,overwrite=True) 400 | 401 | -------------------------------------------------------------------------------- /makenirissgrismflats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | #Generate NIRISS WFSS grism flat field reference files by correcting the imaging flat with data from grism flats. 4 | #Uses jwst and jwst_reffiles python packages 5 | #Takes in direct and dispersed NIRISS WFSS flat field images to identify features of low transmission on the NIRISS pick-off mirror, including the coronagraphic spots. 6 | #Inputs: 7 | #Place all imaging flat field reference files in one sub-directory per filter under the input directory indirimages, e.g. ./imageflatreffiles/F150W/. These should be normalized to a sigma-clipped average value of one as per the CALWEBB_IMAGE2 definition. 8 | #Place one GR150C and one GR150R grism flat field slope_rate.fits files in a sub-directory per filter (for F115W and F150W only) under the input directory indirgrism, e.g. ./grismflatinputs/F150W/ 9 | #The POM feature 'detect' direct image and grism flats are usually F115W because this is best to detect the features (true for CV3 OSIM with very red source, will not be true for astrophysical source). 10 | #The POM feature 'measure' direct image flat is usually the output filter due to the wavelength-dependence of flux loss. 11 | #The four coronagraphic spots have too low S/N in the POM transmission image so will replace with regions from locally normalized F150W grism flats. 12 | #A bad pixel mask reference file is required so that interpolation is applied across bad pixels. 13 | #The outline of the rotated POM in the oversized field determined from the F200W dispersed flats. Must contain keywords OFFSETX & OFFSETY. 14 | #Outputs: 15 | #Final grism flat field images will be output to one sub-directory per filter under the output directory, e.g. ./grismflatreffiles/F150W/ 16 | #A POM transmission file is output in the same directory. This file is used to model sources in WFSS images. 17 | #The parameter ngrow (default=1) is the number of pixels by which to grow the segmentation map of each detected source. 18 | 19 | #Usage: 20 | #makenirissgrismflats.py --indirimage='./imageflatreffiles' --indirgrism='./grismflatinputs' --mask='/Users/willottc/niriss/detectors/willott_reference_files/nocrs/jwst_niriss_cv3_38k_nocrs_bpm_minimal.fits' --pomoutline='./plots/pomoutlinecv3flats_f200w.fits' --outdir='./grismflatreffiles' --ngrow=1 21 | 22 | import numpy as np 23 | from scipy import ndimage 24 | import optparse, sys 25 | import os 26 | import astropy.io.fits as fits 27 | from astropy.stats import SigmaClip,sigma_clip,sigma_clipped_stats 28 | from copy import deepcopy 29 | from photutils import detect_threshold,detect_sources,Background2D, MedianBackground,source_properties, CircularAperture, CircularAnnulus 30 | import natsort 31 | from datetime import datetime 32 | from jwst.datamodels import FlatModel, util, dqflags 33 | from jwst_reffiles.bad_pixel_mask import bad_pixel_mask 34 | 35 | # Command line options 36 | op = optparse.OptionParser() 37 | op.add_option("--indirimage") 38 | op.add_option("--indirgrism") 39 | op.add_option("--mask") 40 | op.add_option("--pomoutline") 41 | op.add_option("--outdir") 42 | op.add_option("--ngrow") 43 | 44 | o, a = op.parse_args() 45 | if a: 46 | print (sys.stderr, "unrecognized option: ",a) 47 | sys.exit(-1) 48 | 49 | indirimage=o.indirimage 50 | indirgrism=o.indirgrism 51 | maskfile=o.mask 52 | pomoutlinefile=o.pomoutline 53 | outdir=o.outdir 54 | ngrow=o.ngrow 55 | if ngrow==None: 56 | ngrow=1 57 | 58 | if not os.path.exists(outdir): 59 | os.makedirs(outdir) 60 | 61 | def save_final_map(datamap, dq, err, dqdef, instrument, detector, hdulist, filterdir, grism, files, 62 | author, description, pedigree,useafter, fpatemp, history_text, pomoutlineoffsetx, pomoutlineoffsety, ngrow, outfile): 63 | """Save a flat field or POM transmission map into a CRDS-formatted reference file 64 | Parameters 65 | ---------- 66 | datamap : numpy.ndarray 67 | 2D flat-field array 68 | dq : numpy.ndarray 69 | 2D flat-field DQ array 70 | err : numpy.ndarray 71 | 2D flat-field error array 72 | dqdef : numpy.ndarray 73 | binary table of DQ definitions 74 | instrument : str 75 | Name of instrument associated with the flat-field array 76 | detector : str 77 | Name of detector associated with the flat-field array 78 | hdulist : astropy.fits.HDUList 79 | HDUList containing "extra" fits keywords 80 | filterdir : str 81 | filter of flat file 82 | grism : str 83 | grism of flat file 84 | files : list 85 | List of files used to create reference file 86 | author : str 87 | Author of the reference file 88 | description : str 89 | CRDS description to use in the final reference file 90 | pedigree : str 91 | CRDS pedigree to use in the final reference file 92 | useafter : str 93 | CRDS useafter string for the reference file 94 | history_text : list 95 | List of strings to add as HISTORY entries to the reference file 96 | outfile : str 97 | Name of the output reference file 98 | """ 99 | yd, xd = datamap.shape 100 | 101 | # For now use FlatModel for the POM transmission as well so don't have to define a new model. 102 | # Initialize the FlatModel using the hdu_list, so the new keywords will 103 | # be populated 104 | if 'flat' in description: 105 | model = FlatModel(hdulist) 106 | model.meta.reftype = 'FLAT' 107 | elif 'transmission' in description: 108 | model = FlatModel(hdulist) 109 | model.meta.reftype = 'TRANSMISSION' 110 | model.data = datamap 111 | model.dq = dq 112 | model.err = err 113 | model.dq_def = dqdef 114 | 115 | #Load a file to get some header info 116 | primaryheader=fits.getheader(os.path.join(filterdir,files[0])) 117 | filterwheel=primaryheader['FILTER'] 118 | pupilwheel=primaryheader['PUPIL'] 119 | 120 | model.meta.subarray.name = 'FULL' 121 | model.meta.subarray.xstart = 1 122 | model.meta.subarray.xsize = xd 123 | model.meta.subarray.ystart = 1 124 | model.meta.subarray.ysize = yd 125 | model.meta.instrument.name = instrument.upper() 126 | model.meta.instrument.detector = detector 127 | if grism=='GR700XD': 128 | model.meta.instrument.filter='CLEAR' 129 | model.meta.instrument.pupil=grism 130 | else: 131 | model.meta.instrument.filter=grism 132 | model.meta.instrument.pupil=pupilwheel 133 | 134 | # Get the fast and slow axis directions from one of the input files 135 | fastaxis, slowaxis = bad_pixel_mask.badpix_from_flats.get_fastaxis(os.path.join(filterdir,files[0])) 136 | model.meta.subarray.fastaxis = fastaxis 137 | model.meta.subarray.slowaxis = slowaxis 138 | 139 | if 'transmission' in description: 140 | model.meta.offsetx=pomoutlineoffsetx 141 | model.meta.offsety=pomoutlineoffsety 142 | 143 | model.meta.author = author 144 | model.meta.description = description 145 | model.meta.pedigree = pedigree 146 | model.meta.useafter = useafter 147 | 148 | 149 | # Add HISTORY information 150 | package_note = ('This file was created using https://github.com/chriswillott/jwst/blob/master/makenirissgrismflats.py') 151 | entry = util.create_history_entry(package_note) 152 | model.history.append(entry) 153 | package_note = ('FPA Temperature={}K'.format(fpatemp)) 154 | entry = util.create_history_entry(package_note) 155 | model.history.append(entry) 156 | package_note = ('Number of pixels to grow POM features={}'.format(ngrow)) 157 | entry = util.create_history_entry(package_note) 158 | model.history.append(entry) 159 | 160 | 161 | # Add the list of input files used to create the map 162 | model.history.append('DATA USED:') 163 | for file in files: 164 | totlen = len(file) 165 | div = np.arange(0, totlen, 60) 166 | for val in div: 167 | if totlen > (val+60): 168 | model.history.append(util.create_history_entry(file[val:val+60])) 169 | else: 170 | model.history.append(util.create_history_entry(file[val:])) 171 | 172 | # Add the do not use lists, pixel flag mappings, and user-provided 173 | # history text 174 | for history_entry in history_text: 175 | if history_entry != '': 176 | model.history.append(util.create_history_entry(history_entry)) 177 | 178 | model.save(outfile, overwrite=True) 179 | print('Final reference file save to: {}'.format(outfile)) 180 | 181 | #Add the offsetx and offsety values manually since no schema yet for transmission files 182 | if 'transmission' in description: 183 | fits.setval(outfile, 'OFFSETX', value=pomoutlineoffsetx, ext=0, after='SLOWAXIS', comment='Transmision map-detector offset in x pixels') 184 | fits.setval(outfile, 'OFFSETY', value=pomoutlineoffsety, ext=0, after='OFFSETX', comment='Transmision map-detector offset in y pixels') 185 | 186 | ###Main program### 187 | 188 | #Information for file header 189 | author='Chris Willott' 190 | pedigree= 'GROUND ' 191 | useafter= '2015-11-01T00:00:00' 192 | 193 | #Load bad pixel file 194 | hdulist=fits.open(maskfile) 195 | maskdata=hdulist['DQ'].data 196 | donotuseindices=np.where(np.bitwise_and(maskdata, dqflags.pixel['DO_NOT_USE'])) 197 | numbadpix=donotuseindices[0].size 198 | 199 | #POM feature detection will use CV3 F115W imaging and grism flat data 200 | #Read in headers and active pixels from flat field data 201 | detectflatfile=os.listdir(os.path.join(indirimage,'F115W'))[0] 202 | hdulistdetect=fits.open(detectflatfile) 203 | detectheader=hdulistdetect['PRIMARY'].header 204 | detectactivedata=hdulistdetect['SCI'].data[4:2044,4:2044] 205 | activeshape=hdulistdetect['SCI'].data.shape 206 | 207 | #Load F115W grism data for finding POM features 208 | detectgrismdir=os.path.join(indirgrism,'F115W') 209 | detectgrismdirlist=os.listdir(detectgrismdir) 210 | numgrismfiles=len(detectgrismdirlist) 211 | for l in range(numgrismfiles): 212 | grismfilename=os.path.join(detectgrismdir,detectgrismdirlist[l]) 213 | hdulist=fits.open(grismfilename) 214 | hdulistpriheader=hdulist['PRIMARY'].header 215 | filterwheel=hdulistpriheader['FILTER'] 216 | if filterwheel=='GR150C': 217 | hdulistgr150c=hdulist 218 | gr150cflatfile=grismfilename 219 | elif filterwheel=='GR150R': 220 | hdulistgr150r=hdulist 221 | gr150rflatfile=grismfilename 222 | print (grismfilename,filterwheel) 223 | gr150cpriheader=hdulistgr150c['PRIMARY'].header 224 | gr150csciheader=hdulistgr150c['SCI'].header 225 | gr150cdetectactivedata=hdulistgr150c['SCI'].data[4:2044,4:2044] 226 | gr150rdetectactivedata=hdulistgr150r['SCI'].data[4:2044,4:2044] 227 | 228 | #Load F150W grism data for patching POM features 229 | patchgrismdir=os.path.join(indirgrism,'F150W') 230 | patchgrismdirlist=os.listdir(patchgrismdir) 231 | numgrismfiles=len(patchgrismdirlist) 232 | for l in range(numgrismfiles): 233 | grismfilename=os.path.join(patchgrismdir,patchgrismdirlist[l]) 234 | hdulist=fits.open(grismfilename) 235 | hdulistpriheader=hdulist['PRIMARY'].header 236 | filterwheel=hdulistpriheader['FILTER'] 237 | if filterwheel=='GR150C': 238 | hdulistgr150c=hdulist 239 | elif filterwheel=='GR150R': 240 | hdulistgr150r=hdulist 241 | print (grismfilename,filterwheel) 242 | gr150cpriheader=hdulistgr150c['PRIMARY'].header 243 | gr150csciheader=hdulistgr150c['SCI'].header 244 | gr150cpatchdata=hdulistgr150c['SCI'].data 245 | gr150rpatchdata=hdulistgr150r['SCI'].data 246 | 247 | #Loop over filters 248 | filterdirlist=natsort.natsorted(os.listdir(indirimage)) 249 | filterdirlist[:] = (value for value in filterdirlist if value.startswith('F')) 250 | numfilters=len(filterdirlist) 251 | print (numfilters,' filters for flat-field reference files') 252 | 253 | for l in range(numfilters): 254 | 255 | #F090W only done at warm plateau in CV3 256 | if filterdirlist[l] =='F090W': 257 | fpatemp=43.699 258 | else: 259 | fpatemp=37.749 260 | 261 | filterdir=os.path.join(indirimage,filterdirlist[l]) 262 | dirlist=natsort.natsorted(os.listdir(filterdir)) 263 | dirlist[:] = (value for value in dirlist if value.endswith('.fits')) 264 | numfiles=len(dirlist) 265 | print(' ') 266 | print (l, 'Filter=',filterdirlist[l]) 267 | 268 | #Read in file 269 | measureflatfile=os.path.join(filterdir,dirlist[0]) 270 | instrument, detector = bad_pixel_mask.instrument_info(measureflatfile) 271 | print ('Processing file',dirlist[0]) 272 | hdulistmeasure=fits.open(measureflatfile) 273 | measurepriheader=hdulistmeasure[0].header 274 | measuresciheader=hdulistmeasure['SCI'].header 275 | measuredata=hdulistmeasure['SCI'].data 276 | measureactivedata=measuredata[4:2044,4:2044] 277 | measureerr=hdulistmeasure['ERR'].data 278 | 279 | #Get values to normalise flats by median for detection and measurement 280 | normalizedetect=np.median(detectactivedata) 281 | normalizemeasure=np.median(measureactivedata) 282 | normalizegr150c=np.median(gr150cdetectactivedata) 283 | normalizegr150r=np.median(gr150rdetectactivedata) 284 | 285 | print ('Starting POM transmission generation') 286 | 287 | #According to Kevin Volk's CV3 report JWST-STScI-004825 all filters have <0.5 pixel shift w.r.t. F115W except F200W. 288 | #For F200W need to shift POM map by 1,2 pixels. 289 | if filterdirlist[l]=='F200W': 290 | xoff=-2 291 | yoff=1 292 | else: 293 | xoff=0 294 | yoff=0 295 | 296 | corocen=np.array([[1061+xoff,1884+yoff],[750+xoff,1860.45+yoff],[439.45+xoff,1837.45+yoff],[129+xoff,1814.45+yoff]]) 297 | corocenfloor=np.floor(corocen).astype('int') 298 | #Radii covering complete spot region to be replaced 299 | #For long-wave filters increase boxes by 20% because of larger PSF 300 | corofullradius=np.array([19,15,8,6]) 301 | if ((filterdirlist[l] =='F277W')or(filterdirlist[l] =='F356W')or(filterdirlist[l] =='F380M')or(filterdirlist[l] =='F430M')or(filterdirlist[l] =='F444W')or(filterdirlist[l] =='F480M')): 302 | corofullradius=np.floor(corofullradius*1.2).astype('int') 303 | #Get reduced radii from those that define the complete spot region to just cover dark central region for POM transmission map 304 | corosizereduce=np.array([0.65,0.6,0.50,0.48]) 305 | corodarkradius=(np.round(corofullradius*corosizereduce)).astype(int) 306 | 307 | #Subtract detect off grism flats, so POM features in detect appear positive 308 | gr150cminusdetect=gr150cdetectactivedata/normalizegr150c-detectactivedata/normalizedetect 309 | gr150rminusdetect=gr150rdetectactivedata/normalizegr150r-detectactivedata/normalizedetect 310 | 311 | #Subtract measure off grism flats, so POM features in measure appear positive 312 | gr150cminusmeasure=gr150cdetectactivedata/normalizegr150c-measureactivedata/normalizemeasure 313 | gr150rminusmeasure=gr150rdetectactivedata/normalizegr150r-measureactivedata/normalizemeasure 314 | 315 | #Initialize full size output arrays 316 | pommap=np.zeros(activeshape) 317 | pomintens=np.zeros(activeshape) 318 | 319 | #Iterate over the 'C' and 'R' grisms 320 | grismminusdetectdata=[gr150cminusdetect,gr150rminusdetect] 321 | grismminusmeasuredata=[gr150cminusmeasure,gr150rminusmeasure] 322 | for k in range(2): 323 | 324 | #Subtract a background from grismminusdetectdata 325 | #Don't need a mask excluding low and high pixels as sigma clipping will exclude bright and dark areas 326 | sigma_clip_forbkg = SigmaClip(sigma=3., maxiters=10) 327 | bkg_estimator = MedianBackground() 328 | bkg = Background2D(grismminusdetectdata[k], (24, 24),filter_size=(5, 5), sigma_clip=sigma_clip_forbkg, bkg_estimator=bkg_estimator) 329 | grismminusdetectdata[k]=grismminusdetectdata[k]-bkg.background 330 | 331 | #Replace all highly negative pixels (these are dispersed POM features) with zeros 332 | v=np.where(grismminusdetectdata[k]<-0.02) 333 | grismminusdetectdata[k][v]=0.0 334 | 335 | #Run source extraction twice 336 | #Do not use a filter as would make single bright pixels appear as sources 337 | #Do first run to find small things 338 | threshold_small = detect_threshold(grismminusdetectdata[k], nsigma=3.0) 339 | segm_small = detect_sources(grismminusdetectdata[k], threshold_small, npixels=4, connectivity=4, filter_kernel=None) 340 | #Do second run to find large things with lower significance and merge the two 341 | threshold_large = detect_threshold(grismminusdetectdata[k], nsigma=1.5) 342 | segm_large = detect_sources(grismminusdetectdata[k], threshold_large, npixels=100, connectivity=8, filter_kernel=None) 343 | 344 | #Remove some sources from large segmentation image 345 | catsegm_large = source_properties(grismminusdetectdata[k], segm_large) 346 | numsource=np.array(catsegm_large.label).size 347 | for ct in range(numsource): 348 | #Remove sources in lower 450 pixel strip because POM not in focus so can't be real. 349 | if (catsegm_large.ycentroid[ct].value<450.0): 350 | segm_large.remove_labels(labels=catsegm_large.label[ct]) 351 | #Remove sources in upper 100 pixel strip because due to fringing 352 | elif (catsegm_large.ycentroid[ct].value>1940): 353 | segm_large.remove_labels(labels=catsegm_large.label[ct]) 354 | #Remove bad detector region at x=12, y=1536 355 | elif ((catsegm_large.ycentroid[ct].value>1520)&(catsegm_large.ycentroid[ct].value<1555)&(catsegm_large.xcentroid[ct].value<25)): 356 | segm_large.remove_labels(labels=catsegm_large.label[ct]) 357 | 358 | #Remove some sources from small segmentation image 359 | catsegm_small = source_properties(grismminusdetectdata[k], segm_small) 360 | numsource=np.array(catsegm_small.label).size 361 | for ct in range(numsource): 362 | 363 | #Remove all sources in lower 450 pixel strip because POM not in focus so can't be real. 364 | if (catsegm_small.ycentroid[ct].value<450.0): 365 | segm_small.remove_labels(labels=catsegm_small.label[ct]) 366 | #Remove small sources (area<6 pixels) except in top part of detector because POM not in focus so can't be real. 367 | elif ((catsegm_small.ycentroid[ct].value>450.0 and catsegm_small.ycentroid[ct].value<1700.0 and catsegm_small.area[ct].value<6)): 368 | segm_small.remove_labels(labels=catsegm_small.label[ct]) 369 | #Remove bad detector region at x=12, y=1536 370 | elif ((catsegm_small.ycentroid[ct].value>1520)&(catsegm_small.ycentroid[ct].value<1555)&(catsegm_small.xcentroid[ct].value<25)): 371 | segm_small.remove_labels(labels=catsegm_small.label[ct]) 372 | 373 | #some intermediate outputs for testing 374 | #fits.writeto('testgrismminusdetectdata{}.fits'.format(k), grismminusdetectdata[k], overwrite=True) 375 | #fits.writeto('testsegsmall{}.fits'.format(k), segm_small.data, overwrite=True) 376 | #fits.writeto('testseglarge{}.fits'.format(k), segm_large.data, overwrite=True) 377 | 378 | #Subtract a background from grismminusmeasuredata 379 | #Don't need a mask excluding low and high pixels as sigma clipping will exclude bright and dark areas 380 | sigma_clip_forbkg = SigmaClip(sigma=3., maxiters=10) 381 | bkg_estimator = MedianBackground() 382 | bkg = Background2D(grismminusmeasuredata[k], (24, 24),filter_size=(5, 5), sigma_clip=sigma_clip_forbkg, bkg_estimator=bkg_estimator) 383 | grismminusmeasuredata[k]=grismminusmeasuredata[k]-bkg.background 384 | 385 | #Replace all negative pixels (these are dispersed POM features and noise) with zeros 386 | v=np.where(grismminusmeasuredata[k]<0.0) 387 | grismminusmeasuredata[k][v]=0.0 388 | 389 | #Make POM map and intensity map using this grism 390 | segm2040=segm_small.data 391 | w=np.where(segm_large.data>0) 392 | segm2040[w]=segm_large.data[w] 393 | pommap2040=deepcopy(segm2040) 394 | w=np.where(pommap2040>0) 395 | pommap2040[w]=1 396 | #Grow detection region 397 | growarray=2*int(ngrow)+1 398 | kern = np.ones((growarray,growarray)) 399 | pommap2040=ndimage.convolve(pommap2040, kern, mode='constant', cval=0.0) 400 | pommap2040[np.where(pommap2040>1.0)]=1.0 401 | 402 | #Merge the GR150C and GR150R images and shift if necessary when placing within the full detector 403 | if k==0: 404 | pommap[4+yoff:2044+yoff,4+xoff:2044+xoff]=pommap2040 405 | pomintens[4:2044,4:2044]=grismminusmeasuredata[k]*pommap[4:2044,4:2044] 406 | else: 407 | pommap[4+yoff:2044+yoff,4+xoff:2044+xoff]=np.maximum(pommap[4+yoff:2044+yoff,4+xoff:2044+xoff],pommap2040) 408 | pomintens[4:2044,4:2044]=np.maximum(pomintens[4:2044,4:2044],(grismminusmeasuredata[k]*pommap[4:2044,4:2044])) 409 | 410 | #Set constant high value in central regions of coronagraphic spots as too noisy to measure in flats 411 | #Iterate over the four spots 412 | for k in range(4): 413 | coroaperture = CircularAperture(corocen[k,:], r=corodarkradius[k]) 414 | coro_obj_mask = coroaperture.to_mask(method='center') 415 | coro_obj_mask_corr=2.0*coro_obj_mask.data 416 | pomintens[corocenfloor[k,1]-corodarkradius[k]:corocenfloor[k,1]+corodarkradius[k]+1,corocenfloor[k,0]-corodarkradius[k]:corocenfloor[k,0]+corodarkradius[k]+1]+=coro_obj_mask_corr 417 | 418 | #Replace pixels with intensity>0.98 to 1.00 as even though centres of spots in CV3 had values of a few percent this was probably scattered 419 | w=np.where(pomintens>0.98) 420 | pomintens[w]=1.00 421 | 422 | #Interpolate across bad pixels if at least 3 out of 4 corner neighbours are in POM mask 423 | pomintensfixbadpix=deepcopy(pomintens) 424 | for j in range(numbadpix): 425 | y=donotuseindices[0][j] 426 | x=donotuseindices[1][j] 427 | #Do not include reference pixels 428 | if y>3 and y<2044 and x>3 and x<2044: 429 | neighborsumpommap=pommap[y-1,x-1]+pommap[y-1,x+1]+pommap[y+1,x-1]+pommap[y+1,x+1] 430 | if neighborsumpommap>2: 431 | pomintensfixbadpix[y,x]=np.median([pomintens[y-1,x-1],pomintens[y-1,x+1],pomintens[y+1,x-1],pomintens[y+1,x+1]]) 432 | 433 | #Find total "flux" lost due to accounted POM features 434 | fractionfluxlost=np.sum(pomintensfixbadpix)/(2040.0*2040.0) 435 | print ('Total fraction of sensitivity decrease in accounted POM features=',fractionfluxlost) 436 | 437 | #Will output intensity files as transmission so do 1-intens 438 | pomtransmission=1.0-pomintensfixbadpix 439 | 440 | #Load F200W POM outline file derived in flatsplot.py 441 | hdulistpomoutline=fits.open(pomoutlinefile) 442 | pomoutlineheader=hdulistpomoutline[0].header 443 | fullpomtransmission=hdulistpomoutline[1].data 444 | pomoutlineoffsetx=pomoutlineheader['OFFSETX'] 445 | pomoutlineoffsety=pomoutlineheader['OFFSETY'] 446 | 447 | # POM outline file is for F200W so apply filter-dependent shifts for all others 448 | if filterdirlist[l]!='F200W': 449 | xofffilter=2 450 | yofffilter=-1 451 | fullpomtransmission[0:yofffilter,xofffilter:]=fullpomtransmission[-1*yofffilter:,0:-1*xofffilter] 452 | 453 | fullpomtransmission[pomoutlineoffsety:(pomoutlineoffsety+2048),pomoutlineoffsetx:(pomoutlineoffsetx+2048)]=pomtransmission 454 | fullpomtransmissionerr=fullpomtransmission/100.0 455 | 456 | filterwheel=measurepriheader['FILTER'] 457 | pupilwheel=measurepriheader['PUPIL'] 458 | 459 | #Add information about inputs to output POM transmission file header 460 | #hdup=fits.PrimaryHDU(data=None) 461 | # hdusci=fits.ImageHDU(data=fullpomtransmission,header=gr150csciheader,name='SCI') 462 | # hdup.header.append(('DATE',(datetime.isoformat(datetime.utcnow())),'Date this file was created (UTC)'),end=True) 463 | # hdup.header.append(('TELESCOP','JWST','Telescope used to acquire the data'),end=True) 464 | # hdup.header.append(('PEDIGREE','GROUND','The pedigree of the reference file'),end=True) 465 | # hdup.header.append(('DESCRIP','This is a POM transmission reference file.','Description of the reference file'),end=True) 466 | # hdup.header.append(('AUTHOR','Chris Willott','Author of the reference file'),end=True) 467 | # hdup.header.append(('', ''),end=True) 468 | # hdup.header.append(('', 'Instrument configuration information'),end=True) 469 | # hdup.header.append(('', ''),end=True) 470 | # hdup.header.append(('INSTRUME', 'NIRISS', 'Instrument used to acquire the data'),end=True) 471 | # hdup.header.append(('DETECTOR', 'NIS', 'Name of detector used to acquire the data'),end=True) 472 | # hdup.header.append(('FILTER', filterwheel, 'Name of filter element used'),end=True) 473 | # hdup.header.append(('PUPIL', pupilwheel, 'Name of the pupil element used'),end=True) 474 | # hdup.header.append(('SUBARRAY', 'FULL', 'Subarray used'),end=True) 475 | # hdup.header.append(('', ''),end=True) 476 | # hdup.header.append(('', 'POM Fitting Information'),end=True) 477 | # hdup.header.append(('', ''),end=True) 478 | # hdup.header.append(('DETPOM',os.path.basename(detectflatfile),'Direct flat for POM detection'),end=True) 479 | # hdup.header.append(('MEASPOM',os.path.basename(measureflatfile),'Direct flat for POM measurement'),end=True) 480 | # hdup.header.append(('CFLATPOM',os.path.basename(gr150cflatfile),'GR150C flat for POM'),end=True) 481 | # hdup.header.append(('RFLATPOM',os.path.basename(gr150rflatfile),'GR150R flat for POM'),end=True) 482 | # hdup.header.append(('BPMPOM',os.path.basename(maskfile),'Bad pixel mask for POM'),end=True) 483 | # hdup.header.append(('NGROWPOM',ngrow,'Number of pixels to grow POM features'),end=True) 484 | # hdup.header.append(('OFFSETX',pomoutlineoffsetx,'transmision map-detector offset in x pixels'),end=True) 485 | # hdup.header.append(('OFFSETY',pomoutlineoffsety,'transmision map-detector offset in y pixels'),end=True) 486 | # hdulistout=fits.HDUList([hdup,hdusci]) 487 | 488 | #Define DQ_DEF binary table HDU 489 | flagtable=np.rec.array([ 490 | ( 0, 0, 'GOOD', 'Good pixel')], 491 | formats='int8,int8,a40,a80', 492 | names='Bit,Value,Name,Description') 493 | dqdef = flagtable 494 | 495 | #Set up DQ array 496 | dq=np.zeros(fullpomtransmission.shape,dtype=np.int8) 497 | 498 | history = [] 499 | hdu = fits.PrimaryHDU() 500 | all_files=[os.path.basename(measureflatfile),os.path.basename(detectflatfile),os.path.basename(gr150cflatfile),os.path.basename(gr150rflatfile),os.path.basename(maskfile)] 501 | 502 | description='This is a pick-off mirror transmission reference file.' 503 | 504 | #Output 2 GR150 grism files per filter and a GR700XD grism file for F150W in reference file format 505 | grisms=['GR150C','GR150R','GR700XD'] 506 | for k in range(3): 507 | if ((k<2) or (filterdirlist[l]=='F200W')): 508 | outfile = 'jwst_niriss_cv3_pomtransmission_{}_{}.fits'.format(grisms[k],filterdirlist[l]) 509 | outdirwithfilter=os.path.join(outdir, filterdirlist[l]) 510 | output_file = os.path.join(outdirwithfilter,outfile) 511 | if not os.path.exists(outdirwithfilter): 512 | os.makedirs(outdirwithfilter) 513 | hdu_list = fits.HDUList([hdu]) 514 | save_final_map(fullpomtransmission, dq, fullpomtransmissionerr, dqdef, instrument.upper(), detector.upper(), hdu_list, filterdir, grisms[k], 515 | all_files, author, description, pedigree, useafter, fpatemp, history, pomoutlineoffsetx, pomoutlineoffsety, ngrow, output_file) 516 | 517 | #Output POM transmission file 518 | #print ('Writing',output_file) 519 | #hdulistout.writeto(output_file,overwrite=True) 520 | 521 | #End POM transmission file making 522 | 523 | ##################################################### 524 | #Start grism flat field reference file making 525 | 526 | print ('Starting grism flat field generation') 527 | #Do correction for all POM features using POM transmission image 528 | measuredata/=pomtransmission 529 | measureerr/=pomtransmission 530 | 531 | #Coronagraphic spots have too low S/N in POM transmission image so will replace with regions from locally normalized grism flats. 532 | #Iterate over the four spots 533 | for k in range(4): 534 | #local normalization in nearby annulus just outside coronagraphic spots 535 | coro_annulus_aperture = CircularAnnulus(corocen[k,:], r_in=1.2*corofullradius[k], r_out=2.0*corofullradius[k]) 536 | coro_annulus_masks = coro_annulus_aperture.to_mask(method='center') 537 | 538 | coro_annulus_measuredata = coro_annulus_masks.multiply(measuredata) 539 | coro_annulus_mask = coro_annulus_masks.data 540 | coro_annulus_measuredata_1d = coro_annulus_measuredata[coro_annulus_mask > 0] 541 | coro_annulus_measuredata_clipped=sigma_clip(coro_annulus_measuredata_1d,sigma=3.0,maxiters=3) 542 | coro_annulus_measuredata_median=np.ma.median(coro_annulus_measuredata_clipped) 543 | 544 | coro_annulus_gr150cpatchdata = coro_annulus_masks.multiply(gr150cpatchdata) 545 | coro_annulus_gr150cpatchdata_1d = coro_annulus_gr150cpatchdata[coro_annulus_mask > 0] 546 | coro_annulus_gr150cpatchdata_clipped=sigma_clip(coro_annulus_gr150cpatchdata_1d,sigma=3.0,maxiters=3) 547 | coro_annulus_gr150cpatchdata_median=np.ma.median(coro_annulus_gr150cpatchdata_clipped) 548 | 549 | coro_annulus_gr150rpatchdata = coro_annulus_masks.multiply(gr150rpatchdata) 550 | coro_annulus_gr150rpatchdata_1d = coro_annulus_gr150rpatchdata[coro_annulus_mask > 0] 551 | coro_annulus_gr150rpatchdata_clipped=sigma_clip(coro_annulus_gr150rpatchdata_1d,sigma=3.0,maxiters=3) 552 | coro_annulus_gr150rpatchdata_median=np.ma.median(coro_annulus_gr150rpatchdata_clipped) 553 | 554 | coro_scale_gr150c=coro_annulus_measuredata_median/coro_annulus_gr150cpatchdata_median 555 | coro_scale_gr150r=coro_annulus_measuredata_median/coro_annulus_gr150rpatchdata_median 556 | 557 | coro_scaled_gr150cpatchdata=gr150cpatchdata*coro_scale_gr150c 558 | coro_scaled_gr150rpatchdata=gr150rpatchdata*coro_scale_gr150r 559 | 560 | xlo=corocenfloor[k,0]-corofullradius[k] 561 | xhi=corocenfloor[k,0]+corofullradius[k]+1 562 | ylo=corocenfloor[k,1]-corofullradius[k] 563 | yhi=corocenfloor[k,1]+corofullradius[k]+1 564 | 565 | #Replace with maximum value from either C or R grism 566 | measuredata[ylo:yhi,xlo:xhi]=np.maximum(coro_scaled_gr150cpatchdata[ylo:yhi,xlo:xhi],coro_scaled_gr150rpatchdata[ylo:yhi,xlo:xhi]) 567 | #Set S/N=100 for all replaced regions of spots because of possible systematics 568 | measureerr[ylo:yhi,xlo:xhi]=measuredata[ylo:yhi,xlo:xhi]/100.0 569 | 570 | #Set DQ flags for bad pixels 571 | #UNRELIABLE_FLAT for all pixels at active pixel border because 10% higher in flats 572 | unrelflat=np.zeros(measuredata.shape,dtype=int) 573 | unrelflat[4:5,4:2044]=1 574 | unrelflat[2043:2044,4:2044]=1 575 | unrelflat[5:2043,4:5]=1 576 | unrelflat[5:2043,2043:2044]=1 577 | 578 | #UNRELIABLE_FLAT for all pixels with values <0.1 579 | unrelflat[np.where(measuredata<0.1)]=1 580 | 581 | #Reference pixel flag for all reference pixels 582 | refpix=np.zeros(measuredata.shape,dtype=int) 583 | refpix[:4,:]=1 584 | refpix[2044:,:]=1 585 | refpix[:,:4]=1 586 | refpix[:,2044:]=1 587 | 588 | #Set all reference pixels to one 589 | measuredata[np.where(refpix==1)]=1.0 590 | measureerr[np.where(refpix==1)]=1.0 591 | 592 | #Set all negative pixels to zero 593 | measureerr[np.where(measuredata<0.0)]=0.0 594 | measuredata[np.where(measuredata<0.0)]=0.0 595 | 596 | #Define DQ_DEF binary table HDU 597 | flagtable=np.rec.array([ 598 | ( 0, 0, 'GOOD', 'Good pixel'), 599 | ( 0, 1, 'DO_NOT_USE', 'Bad pixel. Do not use for science or calibration'), 600 | ( 1, 2, 'NO_FLAT_FIELD', 'Flat field cannot be measured'), 601 | ( 2, 4, 'UNRELIABLE_FLAT', 'Flat variance large'), 602 | ( 4, 8, 'REFERENCE_PIXEL', 'All reference pixels' )], 603 | formats='int8,int8,a40,a80', 604 | names='Bit,Value,Name,Description') 605 | dqdef = flagtable 606 | 607 | #Set up DQ array 608 | dq=np.zeros(measuredata.shape,dtype=np.int8) 609 | 610 | #Set UNRELIABLE_FLAT and REFERENCE_PIXEL flagged pixels to DO_NOT_USE 611 | bitvalue=flagtable['Value'][np.where(flagtable['Name']==b'DO_NOT_USE')][0] 612 | flagarray=np.ones(measuredata.shape, dtype=np.int8)*bitvalue 613 | w=np.where((unrelflat>0)|(refpix>0)) 614 | dq[w]=np.bitwise_or(dq[w],flagarray[w]) 615 | #dq[w]=flagarray[w] 616 | 617 | bitvalue=flagtable['Value'][np.where(flagtable['Name']==b'UNRELIABLE_FLAT')][0] 618 | flagarray=np.ones(measuredata.shape, dtype=np.int8)*bitvalue 619 | w=np.where(unrelflat>0) 620 | dq[w]=np.bitwise_or(dq[w],flagarray[w]) 621 | #dq[w]=flagarray[w] 622 | 623 | bitvalue=flagtable['Value'][np.where(flagtable['Name']==b'REFERENCE_PIXEL')][0] 624 | flagarray=np.ones(measuredata.shape, dtype=np.int8)*bitvalue 625 | w=np.where(refpix>0) 626 | dq[w]=np.bitwise_or(dq[w],flagarray[w]) 627 | #dq[w]=flagarray[w] 628 | 629 | history = [] 630 | hdu = fits.PrimaryHDU() 631 | all_files=[os.path.basename(measureflatfile),os.path.basename(detectflatfile),os.path.basename(detectgrismdirlist[0]),os.path.basename(detectgrismdirlist[1]),os.path.basename(patchgrismdirlist[0]),os.path.basename(patchgrismdirlist[1]),os.path.basename(maskfile)] 632 | 633 | description='This is a pixel flat reference file.' 634 | 635 | #Output 2 GR150 grism files per filter and a GR700XD grism file for F200W in reference file format 636 | grisms=['GR150C','GR150R','GR700XD'] 637 | for k in range(3): 638 | if ((k<2) or (filterdirlist[l]=='F200W')): 639 | outfile = 'jwst_niriss_cv3_grismflat_{}_{}.fits'.format(grisms[k],filterdirlist[l]) 640 | outdirwithfilter=os.path.join(outdir, filterdirlist[l]) 641 | output_file = os.path.join(outdirwithfilter,outfile) 642 | if not os.path.exists(outdirwithfilter): 643 | os.makedirs(outdirwithfilter) 644 | hdu_list = fits.HDUList([hdu]) 645 | save_final_map(measuredata, dq, measureerr, dqdef, instrument.upper(), detector.upper(), hdu_list, filterdir, grisms[k], 646 | all_files, author, description, pedigree, useafter, fpatemp, history, pomoutlineoffsetx, pomoutlineoffsety, ngrow, output_file) 647 | 648 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------