forked from gbrammer/grizli
/
jwst_utils.py
3495 lines (2671 loc) · 111 KB
/
jwst_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Utilities for handling JWST file/data formats.
Requires https://github.com/spacetelescope/jwst
"""
import os
import inspect
import logging
import traceback
import astropy.io.fits as pyfits
import astropy.wcs as pywcs
import numpy as np
from . import utils
from . import GRIZLI_PATH
QUIET_LEVEL = logging.INFO
# CRDS_CONTEXT = 'jwst_0942.pmap' # July 29, 2022 with updated NIRCAM ZPs
# CRDS_CONTEXT = 'jwst_0995.pmap' # 2022-10-06 NRC ZPs and flats
CRDS_CONTEXT = 'jwst_1123.pmap' # 2023-09-08 NRC specwcs, etc.
# Global variable to control whether or not to try to update
# PP file WCS
DO_PURE_PARALLEL_WCS = True
def set_crds_context(fits_file=None, override_environ=False, verbose=True):
"""
Set CRDS_CONTEXT
Parameters
----------
fits_file : str
If provided, try to get CRDS_CONTEXT from header
override_environ : bool
Override environment variable if True, otherwise will not change
the value of an already-set CRDS_CONTEXT environment variable.
Returns
-------
crds_context : str
The value of the CRDS_CONTEXT environment variable
"""
from importlib import reload
import crds
import crds.core
import crds.core.heavy_client
_CTX = CRDS_CONTEXT
if fits_file is not None:
with pyfits.open(fits_file) as im:
if 'CRDS_CONTEXT' in im[0].header:
_CTX = im[0].header['CRDS_CTX']
if os.getenv('CRDS_CONTEXT') is None:
os.environ['CRDS_CONTEXT'] = _CTX
elif override_environ:
os.environ['CRDS_CONTEXT'] = _CTX
msg = f"ENV CRDS_CONTEXT = {os.environ['CRDS_CONTEXT']}"
utils.log_comment(utils.LOGFILE, msg, verbose=verbose)
# Need to reload CRDS modules to catch new CONTEXT
reload(crds.core); reload(crds); reload(crds.core.heavy_client)
return os.environ['CRDS_CONTEXT']
def crds_reffiles(instrument='NIRCAM', filter='F444W', pupil='GRISMR', module='A', detector=None, exp_type=None, date=None, reftypes=('photom', 'specwcs'), header=None, context=CRDS_CONTEXT, verbose=False, **kwargs):
"""
Get WFSS reffiles from CRDS
Parameters
----------
instrument, filter, pupil, module : str
Observation mode parameters
detector, exp_type : str, None
If not specified, try to set automatically based on the filter / module
date : `astropy.time.Time`, None
Observation epoch. If `None`, use "now".
reftypes : list
Reference types to query
header : `~astropy.io.fits.Header`
FITS header with keywords that define the mode and supersede the string
parameters
context : str
CRDS_CONTEXT specification
verbose : bool
Messaging
Returns
-------
refs : dict
Result from `crds.getreferences` with keys of ``reftypes`` and values of paths
to the reference files, which will be downloaded if they're not already found.
"""
import astropy.time
import crds
from . import jwst_utils
if context is not None:
jwst_utils.CRDS_CONTEXT = context
jwst_utils.set_crds_context(verbose=False, override_environ=True)
if header is not None:
if 'INSTRUME' in header:
instrument = header['INSTRUME']
if 'FILTER' in header:
filter = header['FILTER']
if 'PUPIL' in header:
pupil = header['PUPIL']
if 'MODULE' in header:
module = header['MODULE']
if 'EXP_TYPE' in header:
exp_type = header['EXP_TYPE']
cpars = {}
if instrument in ('NIRISS', 'NIRCAM', 'MIRI'):
observatory = 'jwst'
if instrument not in ['MIRI']:
cpars['meta.instrument.pupil'] = pupil
else:
observatory = 'hst'
if instrument == 'NIRISS':
cpars['meta.instrument.detector'] = 'NIS'
if 'GR150' in filter:
cpars['meta.exposure.type'] = 'NIS_WFSS'
else:
cpars['meta.exposure.type'] = 'NIS_IMAGE'
elif instrument == 'NIRCAM':
cpars['meta.instrument.detector'] = f'NRC{module}LONG'
cpars['meta.instrument.module'] = module
cpars['meta.exposure.type'] = exp_type
if 'GRISM' in pupil:
cpars['meta.exposure.type'] = 'NRC_WFSS'
else:
cpars['meta.exposure.type'] = 'NRC_IMAGE'
elif instrument == 'MIRI':
cpars['meta.instrument.detector'] = 'MIR'
cpars['meta.exposure.type'] = 'MIR_IMAGE'
if exp_type is not None:
cpars['meta.exposure.type'] = exp_type
if detector is not None:
cpars['meta.instrument.detector'] = detector
if date is None:
date = astropy.time.Time.now().iso
cpars['meta.observation.date'] = date.split()[0]
cpars['meta.observation.time'] = date.split()[1]
cpars['meta.instrument.name'] = instrument
cpars['meta.instrument.filter'] = filter
refs = crds.getreferences(cpars, reftypes=reftypes, observatory=observatory)
if verbose:
msg = f'crds_reffiles: {instrument} {filter} {pupil} {module} ({context})'
ref_files = ' '.join([os.path.basename(refs[k]) for k in refs])
msg += '\n' + f'crds_reffiles: {ref_files}'
print(msg)
return refs
def set_quiet_logging(level=QUIET_LEVEL):
"""
Silence the verbose logs set by `stpipe`
"""
try:
import jwst
logging.disable(level)
except ImportError:
pass
def hdu_to_imagemodel(in_hdu):
"""
Workaround for initializing a `jwst.datamodels.ImageModel` from a
normal FITS ImageHDU that could contain HST header keywords and
unexpected WCS definition.
TBD
Parameters
----------
in_hdu : `astropy.io.fits.ImageHDU`
Returns
-------
img : `jwst.datamodels.ImageModel`
"""
from astropy.io.fits import ImageHDU, HDUList
from astropy.coordinates import ICRS
from jwst.datamodels import util
import gwcs
set_quiet_logging(QUIET_LEVEL)
hdu = ImageHDU(data=in_hdu.data, header=in_hdu.header)
new_header = strip_telescope_header(hdu.header)
hdu.header = new_header
# Initialize data model
img = util.open(HDUList([hdu]))
# Initialize GWCS
tform = gwcs.wcs.utils.make_fitswcs_transform(new_header)
hwcs = gwcs.WCS(forward_transform=tform, output_frame=ICRS()) # gwcs.CelestialFrame())
sh = hdu.data.shape
hwcs.bounding_box = ((-0.5, sh[0]-0.5), (-0.5, sh[1]-0.5))
# Put gWCS in meta, where blot/drizzle expect to find it
img.meta.wcs = hwcs
return img
def change_header_pointing(header, ra_ref=0., dec_ref=0., pa_v3=0.):
"""
Update a FITS header for a new pointing (center + roll).
Parameters
----------
header : `~astropy.io.fits.Header`
Parent header (must contain `V2_REF`, `V3_REF` keywords).
ra_ref, dec_ref : float
Pointing center, in decimal degrees, at reference the pixel defined
in.
pa_v3 : float
Position angle of the telescope V3 axis, degrees.
.. warning::
Doesn't update PC keywords based on pa_v3, which would rather have to
be computed from the new `gwcs`.
"""
from jwst.lib.set_telescope_pointing import compute_local_roll
set_quiet_logging(QUIET_LEVEL)
v2_ref = header['V2_REF']
v3_ref = header['V3_REF']
# Strip units, if any
args = []
for v in (pa_v3, ra_ref, dec_ref, v2_ref, v3_ref):
if hasattr(v, 'value'):
args.append(v.value)
else:
args.append(v)
roll_ref = compute_local_roll(*tuple(args))
new_header = header.copy()
new_header['XPA_V3'] = args[0]
new_header['CRVAL1'] = new_header['RA_REF'] = args[1]
new_header['CRVAL2'] = new_header['DEC_REF'] = args[2]
new_header['ROLL_REF'] = roll_ref
return new_header
def get_jwst_skyflat(header, verbose=True, valid_flat=(0.7, 1.4)):
"""
Get sky flat for JWST instruments
Parameters
----------
header : `astropy.io.fits.Header`
Primary header
verbose : bool
Verbose messaging
valid_flat : (float, float)
Range of values to define where the flat is valid to avoid corrections
that are too large
Returns
-------
skyfile : str
Filename of the sky flat file
flat_corr : array-like
The flat correction, equal to the original flat divided by the
new sky flat, i.e., to take out the former and apply the latter
dq : array-like
DQ array with 1024 where flat outside of ``valid_flat`` range
If no flat file is found, returns ``None`` for all outputs
"""
filt = utils.parse_filter_from_header(header)
key = ('{0}-{1}'.format(header['detector'], filt)).lower()
conf_path = os.path.join(GRIZLI_PATH, 'CONF', 'NircamSkyFlat')
if 'nrcb4' in key:
skyfile = os.path.join(conf_path, f'{key}_skyflat.fits')
elif key.startswith('nis-'):
skyfile = os.path.join(conf_path, f'{key}_skyflat.fits')
elif key.startswith('mirimage-'):
key += '-'+header['readpatt'].lower()
skyfile = os.path.join(conf_path, f'{key}_skyflat.fits')
else:
skyfile = os.path.join(conf_path, f'{key}_skyflat_smooth.fits')
if not os.path.exists(skyfile):
msg = f'jwst_utils.get_jwst_skyflat: {skyfile} not found'
utils.log_comment(utils.LOGFILE, msg, verbose=True)
return None, None, None
with pyfits.open(skyfile) as _im:
skyflat = _im[0].data*1
# flat == 1 are bad
skyflat[skyflat == 1] = np.nan
if 'R_FLAT' in header:
oflat = os.path.basename(header['R_FLAT'])
crds_path = os.getenv('CRDS_PATH')
crds_path = os.path.join(crds_path, 'references/jwst',
header['instrume'].lower(), oflat)
msg = f'jwst_utils.get_jwst_skyflat: pipeline flat = {crds_path}\n'
with pyfits.open(crds_path) as oim:
try:
flat_corr = oim['SCI'].data / skyflat
except ValueError:
msg = f'jwst_utils.get_jwst_skyflat: flat_corr failed'
utils.log_comment(utils.LOGFILE, msg, verbose=True)
return None, None, None
else:
msg = f'jwst_utils.get_jwst_skyflat: NO pipeline flat\n'
flat_corr = 1./skyflat
bad = skyflat < valid_flat[0]
bad |= skyflat > valid_flat[1]
bad |= ~np.isfinite(flat_corr)
flat_corr[bad] = 1
dq = bad*1024
msg += f'jwst_utils.get_jwst_skyflat: new sky flat = {skyfile}\n'
msg += f'jwst_utils.get_jwst_skyflat: valid_flat={valid_flat}'
msg += f' nmask={bad.sum()}'
if 'SUBSTRT1' in header:
if header['SUBSIZE1'] != 2048:
slx = slice(header['SUBSTRT1']-1,
header['SUBSTRT1']-1 + header['SUBSIZE1'])
sly = slice(header['SUBSTRT2']-1,
header['SUBSTRT2']-1 + header['SUBSIZE2'])
msg += f"\njwst_utils.get_jwst_skyflat: subarray "
msg += header['APERNAME']
msg += f' [{sly.start}:{sly.stop},{slx.start}:{slx.stop}]'
flat_corr = flat_corr[sly, slx]
dq = dq[sly, slx]
utils.log_comment(utils.LOGFILE, msg, verbose=True)
return skyfile, flat_corr, dq
def img_with_flat(input, verbose=True, overwrite=True, apply_photom=True, use_skyflats=True):
"""
Apply flat-field and photom corrections if nessary
"""
import gc
import astropy.io.fits as pyfits
from jwst.datamodels import util
from jwst.flatfield import FlatFieldStep
from jwst.gain_scale import GainScaleStep
from jwst.photom import PhotomStep
set_quiet_logging(QUIET_LEVEL)
_ = set_crds_context()
if not isinstance(input, pyfits.HDUList):
_hdu = pyfits.open(input)
else:
_hdu = input
skip = False
if 'S_FLAT' in _hdu[0].header:
if _hdu[0].header['S_FLAT'] == 'COMPLETE':
skip = True
if 'OINSTRUM' not in _hdu[0].header:
copy_jwst_keywords(_hdu[0].header)
# if _hdu[0].header['OINSTRUM'] == 'NIRISS':
# if _hdu[0].header['OFILTER'].startswith('GR'):
# _hdu[0].header['FILTER'] = 'CLEAR'
# _hdu[0].header['EXP_TYPE'] = 'NIS_IMAGE'
# NIRCam grism flats are empty
# NIRISS has slitless flats that include the mask spots
if _hdu[0].header['OINSTRUM'] == 'NIRCAM':
if _hdu[0].header['OPUPIL'].startswith('GR'):
_opup = _hdu[0].header['OPUPIL']
msg = f'Set NIRCAM slitless PUPIL {_opup} -> CLEAR for flat'
utils.log_comment(utils.LOGFILE, msg, verbose=True)
_hdu[0].header['PUPIL'] = 'CLEAR'
_hdu[0].header['EXP_TYPE'] = 'NRC_IMAGE'
else:
# MIRI, NIRISS
pass
img = util.open(_hdu)
if not skip:
flat_step = FlatFieldStep()
_flatfile = flat_step.get_reference_file(img, 'flat')
utils.log_comment(utils.LOGFILE,
f'jwst.flatfield.FlatFieldStep: {_flatfile}',
verbose=verbose, show_date=False)
with_flat = flat_step.process(img)
# Photom
if 'OPUPIL' in _hdu[0].header:
_opup = _hdu[0].header['OPUPIL']
else:
_opup = ''
_ofilt = _hdu[0].header['OFILTER']
if _opup.startswith('GR') | _ofilt.startswith('GR') | (not apply_photom):
output = with_flat
_photfile = None
else:
photom_step = PhotomStep()
with_phot = photom_step.process(with_flat)
output = with_phot
_photfile = photom_step.get_reference_file(img, 'photom')
utils.log_comment(utils.LOGFILE,
f'jwst.flatfield.PhotomStep: {_photfile}',
verbose=verbose, show_date=False)
else:
utils.log_comment(utils.LOGFILE,
f'jwst_utils.img_with_flat: Flat already applied',
verbose=verbose, show_date=False)
output = img
if isinstance(input, str) & overwrite:
output.write(input, overwrite=overwrite)
_hdu.close()
# Add reference files
if not skip:
with pyfits.open(input, mode='update') as _hdu:
_hdu[0].header['UPDA_CTX'] = (os.environ['CRDS_CONTEXT'],
'CRDS_CTX for modified files')
_hdu[0].header['R_FLAT'] = (os.path.basename(_flatfile),
'Applied flat')
if _photfile is not None:
_hdu[0].header['R_PHOTOM'] = (os.path.basename(_photfile),
'Applied photom')
_hdu.flush()
if use_skyflats:
with pyfits.open(input, mode='update') as _hdu:
if 'FIXFLAT' not in _hdu[0].header:
_sky = get_jwst_skyflat(_hdu[0].header)
if _sky[0] is not None:
if _hdu['SCI'].data.shape == _sky[1].shape:
_hdu['SCI'].data *= _sky[1]
_skyf = os.path.basename(_sky[0])
_hdu[0].header['FIXFLAT'] = (True,
'Skyflat correction applied')
_hdu[0].header['FIXFLATF'] = _skyf, 'Skyflat file'
_dt = _hdu['DQ'].data.dtype
_hdu['DQ'].data |= _sky[2].astype(_dt)
_hdu.flush()
else:
msg = f'jwst_utils.get_jwst_skyflat: FIXFLAT found'
utils.log_comment(utils.LOGFILE, msg,
verbose=verbose, show_date=False)
gc.collect()
return output
def img_with_wcs(input, overwrite=True, fit_sip_header=True, skip_completed=True, verbose=True):
"""
Open a JWST exposure and apply the distortion model.
Parameters
----------
input : object
Anything `jwst.datamodels.util.open` can accept for initialization.
overwrite : bool
Overwrite FITS file
fit_sip_header : bool
Run `pipeline_model_wcs_header` to rederive SIP distortion header
Returns
-------
with_wcs : `jwst.datamodels.ImageModel`
Image model with full `~gwcs` in `with_wcs.meta.wcs`.
"""
from jwst.datamodels import util
from jwst.assign_wcs import AssignWcsStep
set_quiet_logging(QUIET_LEVEL)
_ = set_crds_context()
# HDUList -> jwst.datamodels.ImageModel
# Generate WCS as image
if not isinstance(input, pyfits.HDUList):
_hdu = pyfits.open(input)
else:
_hdu = input
if 'OINSTRUM' not in _hdu[0].header:
copy_jwst_keywords(_hdu[0].header)
if _hdu[0].header['OINSTRUM'] == 'NIRISS':
if _hdu[0].header['OFILTER'].startswith('GR'):
_hdu[0].header['FILTER'] = 'CLEAR'
_hdu[0].header['EXP_TYPE'] = 'NIS_IMAGE'
elif _hdu[0].header['OINSTRUM'] == 'NIRCAM':
if _hdu[0].header['OPUPIL'].startswith('GR'):
_hdu[0].header['PUPIL'] = 'CLEAR'
_hdu[0].header['EXP_TYPE'] = 'NRC_IMAGE'
elif _hdu[0].header['OINSTRUM'] == 'NIRSPEC':
if _hdu[0].header['OGRATING'] not in 'MIRROR':
_hdu[0].header['FILTER'] = 'F140X'
_hdu[0].header['GRATING'] = 'MIRROR'
_hdu[0].header['EXP_TYPE'] = 'NRS_TACONFIRM'
else:
# MIRI
pass
img = util.open(_hdu)
# AssignWcs to pupulate img.meta.wcsinfo
step = AssignWcsStep()
_distor_file = step.get_reference_file(img, 'distortion')
utils.log_comment(utils.LOGFILE,
f'jwst.assign_wcs.AssignWcsStep: {_distor_file}',
verbose=verbose, show_date=False)
with_wcs = step.process(img)
output = with_wcs
# Write to a file
if isinstance(input, str) & overwrite:
output.write(input, overwrite=overwrite)
_hdu = pyfits.open(input)
if 'GRIZLWCS' in _hdu[0].header:
if (_hdu[0].header['GRIZLWCS']) & (skip_completed):
fit_sip_header=False
#wcs = pywcs.WCS(_hdu['SCI'].header, relax=True)
if fit_sip_header:
hsip = pipeline_model_wcs_header(output,
set_diff_step=False,
step=64,
degrees=[3,4,5,5],
initial_header=None)
wcs = pywcs.WCS(hsip, relax=True)
for k in hsip:
if k in hsip.comments:
_hdu[1].header[k] = hsip[k], hsip.comments[k]
else:
_hdu[1].header[k] = hsip[k]
else:
wcs = utils.wcs_from_header(_hdu['SCI'].header, relax=True)
# Remove WCS inverse keywords
for _ext in [0, 'SCI']:
for k in list(_hdu[_ext].header.keys()):
if k[:3] in ['AP_','BP_','PC1','PC2']:
_hdu[_ext].header.remove(k)
pscale = utils.get_wcs_pscale(wcs)
_hdu[1].header['IDCSCALE'] = pscale, 'Pixel scale calculated from WCS'
_hdu[0].header['PIXSCALE'] = pscale, 'Pixel scale calculated from WCS'
_hdu[0].header['GRIZLWCS'] = True, 'WCS modified by grizli'
_hdu[0].header['UPDA_CTX'] = (os.environ['CRDS_CONTEXT'],
'CRDS_CTX for modified files')
_hdu[0].header['R_DISTOR'] = (os.path.basename(_distor_file),
'Distortion reference file')
_hdu.writeto(input, overwrite=True)
_hdu.close()
if DO_PURE_PARALLEL_WCS:
try:
# Update pointing of pure-parallel exposures
status = update_pure_parallel_wcs(input, fix_vtype='PARALLEL_PURE')
except:
pass
return output
def match_gwcs_to_sip(input, step=64, transform=None, verbose=True, overwrite=True):
"""
Calculate transformation of gwcs to match SIP header, which may have been
realigned (shift, rotation, scale)
Parameters
----------
input : str, `~astropy.io.fits.HDUList`
FITS filename of a JWST image or a previously-opened
`~astropy.io.fits.HDUList` with SIP wcs information stored in the
first extension.
img : `~pyfits.io.fits.HDUList`
HDU list from FITS files, where SIP wcs information stored in the
first extension
step : int
Step size of the pixel grid for calculating the tranformation
transform : `skimage.transform`
Transform object, e.g., `skimage.transform.SimilarityTransform`
or `skimage.transform.Euclideanransform`
verbose : bool
Verbose messages
overwrite : bool
If True and ``input`` is a string, re-write to file
Returns
-------
obj : `jwst.datamodels.image.ImageModel`
Datamodel with updated WCS object. The `REF` keywords are updated in
`img[1].header`.
Notes
-----
The scale factor of transformation is applied by multiplying the
scale to the last parameters of the `distortion` WCS pipeline. These
might not necessarily be scale coefficients for all instrument WCS
pipelines
"""
from skimage.transform import SimilarityTransform
if transform is None:
transform = SimilarityTransform
if isinstance(input, str):
img = pyfits.open(input)
elif isinstance(input, pyfits.HDUList):
img = input
if img[0].header['TELESCOP'] not in ['JWST']:
img = set_jwst_to_hst_keywords(img, reset=True)
obj = img_with_wcs(img)
# this should be put into `img_with_wcs` with more checks that it's being
# applied correctly
if 'SCL_REF' in img[1].header:
tr = obj.meta.wcs.pipeline[0].transform
for i in range(-8,-2):
setattr(tr, tr.param_names[i],
tr.parameters[i]*img[1].header['SCL_REF'])
else:
if hasattr(transform, 'scale'):
img[1].header['SCL_REF'] = (1.0, 'Transformation scale factor')
wcs = pywcs.WCS(img[1].header, relax=True)
sh = obj.data.shape
if obj.meta.instrument.name in ['MIRI']:
xmin = 300
else:
xmin = step
ymin = step
xx = np.arange(xmin, sh[1]-1, step)
yy = np.arange(ymin, sh[0]-1, step)
yp, xp = np.meshgrid(yy, xx)
rdg = obj.meta.wcs.forward_transform(xp, yp)
rdw = wcs.all_pix2world(xp, yp, 0)
Vg = np.array([rdg[0].flatten(), rdg[1].flatten()])
Vw = np.array([rdw[0].flatten(), rdw[1].flatten()])
r0 = np.median(Vw, axis=1)
Vg = (Vg.T - r0).T
Vw = (Vw.T - r0).T
cosd = np.cos(r0[1]/180*np.pi)
Vg[0,:] *= cosd
Vw[0,:] *= cosd
tf = transform()
tf.estimate(Vg.T, Vw.T)
asec = np.array(tf.translation)*np.array([1., 1.])*3600
rot_deg = tf.rotation/np.pi*180
Vt = tf(Vg.T).T
resid = Vt - Vw
if 'PIXSCALE' in img[0].header:
pscale = img[0].header['PIXSCALE']
else:
pscale = utils.get_wcs_pscale(wcs)
rms = [utils.nmad(resid[i,:])*3600/pscale for i in [0,1]]
if hasattr(tf, 'scale'):
img[1].header['SCL_REF'] *= tf.scale
_tfscale = tf.scale
else:
_tfscale = 1.
msg = f'Align to wcs: ({asec[0]:6.3f} {asec[1]:6.3f}) {_tfscale:7.5f}'
msg += f' {rot_deg:7.5f} ; rms = {rms[0]:6.1e} {rms[1]:6.1e} pix'
utils.log_comment(utils.LOGFILE, msg, verbose=verbose)
img[1].header['RA_REF'] += tf.translation[0]/cosd
img[1].header['DEC_REF'] += tf.translation[1]
img[1].header['ROLL_REF'] -= rot_deg
obj = img_with_wcs(img)
# Update scale parameters in transform, but parameters
# might not be in correct order
if 'SCL_REF' in img[1].header:
tr = obj.meta.wcs.pipeline[0].transform
for i in range(-8,-2):
setattr(tr, tr.param_names[i],
tr.parameters[i]*img[1].header['SCL_REF'])
if overwrite:
img.writeto(img.filename(), overwrite=True)
return obj
def get_phot_keywords(input, verbose=True):
"""Calculate conversions between JWST ``MJy/sr`` units and PHOTFLAM/PHOTFNU
Parameters
----------
input : str, `~astropy.io.fits.HDUList`
FITS filename of a `cal`ibrated JWST image or a previously-opened
`~astropy.io.fits.HDUList`
Returns
-------
info : dict
Photometric information
"""
import astropy.units as u
if isinstance(input, str):
img = pyfits.open(input, mode='update')
elif isinstance(input, pyfits.HDUList):
img = input
# Get tabulated filter info
filter_info = get_jwst_filter_info(img[0].header)
# Get pixel area
if 'PIXAR_A2' in img['SCI'].header:
pscale = np.sqrt(img['SCI'].header['PIXAR_A2'])
elif 'PIXSCALE' in img['SCI'].header:
pscale = img['SCI'].header['PIXSCALE']
else:
_wcs = pywcs.WCS(img['SCI'].header, relax=True)
pscale = utils.get_wcs_pscale(_wcs)
# Check image units
if 'OBUNIT' in img['SCI'].header:
unit_key = 'OBUNIT'
else:
unit_key = 'BUNIT'
if img['SCI'].header[unit_key].upper() == 'MJy/sr'.upper():
in_unit = u.MJy/u.sr
to_mjysr = 1.0
else:
if filter_info is None:
in_unit = u.MJy/u.sr
to_mjysr = -1.
else:
if 'photmjsr' in filter_info:
in_unit = 1.*filter_info['photmjsr']*u.MJy/u.sr
to_mjysr = filter_info['photmjsr']
else:
in_unit = u.MJy/u.sr
to_mjysr = 1.0
# Conversion factor
pixel_area = (pscale*u.arcsec)**2
tojy = (1*in_unit).to(u.Jy/pixel_area).value
# Pivot wavelength
if filter_info is not None:
plam = filter_info['pivot']*1.e4
else:
plam = 5.0e4
photflam = tojy*2.99e-5/plam**2
_ZP = -2.5*np.log10(tojy)+8.9
if verbose:
msg = '# photometry keywords\n'
msg += f'PHOTFNU = {tojy:.4e}\n'
msg += f'PHOTPLAM = {plam:.1f}\n'
msg += f'PHOTFLAM = {photflam:.4e}\n'
msg += f'ZP = {_ZP:.2f}\n'
msg += f'TO_MJYSR = {to_mjysr:.3f}\n'
utils.log_comment(utils.LOGFILE, msg, verbose=True)
# Set header keywords
for e in [0, 'SCI']:
img[e].header['PHOTFNU'] = tojy, 'Scale factor to Janskys'
img[e].header['PHOTPLAM'] = (plam, 'Bandpass pivot wavelength, A')
img[e].header['PHOTFLAM'] = (photflam, 'Scale to erg/s/cm2/A')
img[e].header['ZP'] = _ZP, 'AB mag zeropoint'
img[e].header['TO_MJYSR'] = (to_mjysr, 'Scale to MJy/sr')
# Drizzlepac needs ELECTRONS/S
if 'OBUNIT' not in img['SCI'].header:
img['SCI'].header['OBUNIT'] = (img['SCI'].header['BUNIT'],
'Original image units')
img['SCI'].header['BUNIT'] = 'ELECTRONS/S'
# Write FITS file if filename provided as input
if isinstance(input, str):
img.writeto(input, overwrite=True)
img.close()
info = {'photfnu':tojy,
'photplam':plam,
'photflam':img[0].header['PHOTFLAM'],
'zp':img[0].header['ZP'],
'tomjysr':to_mjysr}
return info
ORIG_KEYS = ['TELESCOP','INSTRUME','DETECTOR','FILTER','PUPIL','EXP_TYPE','GRATING']
def copy_jwst_keywords(header, orig_keys=ORIG_KEYS, verbose=True):
"""
Make copies of some header keywords that may need to be modified to
force the pipeline / astrodrizzle to interpret the images in different
ways
"""
for k in orig_keys:
newk = 'O'+k[:7]
if newk not in header:
if k in header:
header[newk] = header[k]
msg = f'{newk} = {k} {header[k]}'
utils.log_comment(utils.LOGFILE, msg, verbose=verbose)
def exposure_oneoverf_correction(file, axis=None, thresholds=[5,4,3], erode_mask=None, dilate_iterations=3, deg_pix=64, make_plot=True, init_model=0, in_place=False, skip_miri=True, force_oneoverf=False, verbose=True, **kwargs):
"""
1/f correction for individual exposure
1. Create a "background" mask with `sep`
2. Identify sources above threshold limit in the background-subtracted
image
3. Iterate a row/column correction on threshold-masked images. A
chebyshev polynomial is fit to the correction array to try to isolate
just the high-frequency oscillations.
Parameters
----------
file : str
JWST raw image filename
axis : int
Axis over which to calculated the correction. If `None`, then defaults
to ``axis=1`` (rows) for NIRCam and ``axis=1`` (columns) for NIRISS.
thresholds : list
List of source identification thresholds
erode_mask : bool
Erode the source mask to try to remove individual pixels that satisfy
the S/N threshold. If `None`, then set to False if the exposure is a
NIRISS dispersed image to avoid clipping compact high-order spectra
from the mask and True otherwise (for NIRISS imaging and NIRCam
generally).
dilate_iterations : int
Number of `binary_dilation` iterations of the source mask
deg_pix : int
Scale in pixels for each degree of the smooth chebyshev polynomial
make_plot : bool
Make a diagnostic plot
init_model : scalar, array-like
Initial correction model, e.g., for doing both axes
in_place : bool
If True, remove the model from the 'SCI' extension of ``file``
skip_miri : bool
Don't run on MIRI exposures
force_oneoverf : bool
Force the correction even if the `ONEFEXP` keyword is already set
verbose : bool
Print status messages
Returns
-------
fig : `~matplotlib.figure.Figure`, None
Diagnostic figure if `make_plot=True`
model : array-like
The row- or column-average correction array
"""
import numpy as np
import scipy.ndimage as nd
import matplotlib.pyplot as plt
import astropy.io.fits as pyfits
import sep
im = pyfits.open(file)
if (im[0].header['INSTRUME'] in 'MIRI') & (skip_miri):
im.close()
msg = 'exposure_oneoverf_correction: Skip for MIRI'
utils.log_comment(utils.LOGFILE, msg, verbose=verbose)