-
Notifications
You must be signed in to change notification settings - Fork 50
/
multifit.py
3110 lines (2423 loc) · 116 KB
/
multifit.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
import os
import time
import glob
from collections import OrderedDict
import multiprocessing as mp
import scipy.ndimage as nd
import numpy as np
import matplotlib.pyplot as plt
from astropy.table import Table
import astropy.io.fits as pyfits
## local imports
from . import grismconf
from . import utils
from . import model
from . import stack
from .utils_c import disperse
from .utils_c import interp
grism_colors = {'G800L':(0.0, 0.4470588235294118, 0.6980392156862745),
'G102':(0.0, 0.6196078431372549, 0.45098039215686275),
'G141':(0.8352941176470589, 0.3686274509803922, 0.0),
'none':(0.8, 0.4745098039215686, 0.6549019607843137),
'GRISM':'k',
'G280':'purple',
'F090W':(0.0, 0.4470588235294118, 0.6980392156862745),
'F115W':(0.0, 0.6196078431372549, 0.45098039215686275),
'F150W':(0.8352941176470589, 0.3686274509803922, 0.0),
'F200W':(0.8, 0.4745098039215686, 0.6549019607843137),
'F140M':'orange',
'CLEARP':'b'}
grism_major = {'G102':0.1, 'G141':0.1, 'G800L':0.2, 'F090W':0.1, 'F115W':0.1, 'F150W':0.1, 'F200W':0.1}
grism_limits = {'G800L':[0.545, 1.02, 50.], # ACS/WFC
'G280':[0.2,0.4, 14], # WFC3/UVIS
'G102':[0.77, 1.18, 23.5], # WFC3/IR
'G141':[1.06, 1.73, 47.0],
'GRISM':[0.98, 1.98, 11.], # WFIRST
'F090W':[0.76,1.04, 45.0], # NIRISS
'F115W':[0.97,1.32, 45.0],
'F150W':[1.28,1.72, 45.0],
'F200W':[1.68,2.30, 45.0],
'F140M':[1.20,1.60, 45.0],
'CLEARP':[0.76, 2.3,45.0]}
default_line_list = ['SIII', 'SII', 'Ha', 'OI-6302', 'OIII', 'Hb', 'OIII-4363', 'Hg', 'Hd', 'NeIII', 'OII', 'MgII']
def test():
import glob
from grizlidev import utils
import grizlidev.multifit
reload(utils)
reload(grizlidev.model)
reload(grizlidev.multifit)
files=glob.glob('i*flt.fits')
output_list, filter_list = utils.parse_flt_files(files, uniquename=False)
# grism_files = filter_list['G141'][164]
# #grism_files.extend(filter_list['G141'][247])
#
# direct_files = filter_list['F140W'][164][:4]
#direct_files.extend(filter_list['F140W'][247][:4])
# grp = grizlidev.multifit.GroupFLT(grism_files=grism_files, direct_files=direct_files)
#
#
# grp = grizlidev.multifit.GroupFLT(grism_files=grism_files, direct_files=direct_files, ref_file=ref)
# ref = 'MACS0416-F140W_drz_sci_filled.fits'
# seg = 'hff_m0416_v0.1_bkg_detection_seg_grow.fits'
# catalog = 'hff_m0416_v0.1_f140w.cat'
#
# key = 'cl1301-11.3-122.5-g102'
# seg = 'cl1301-11.3-14-122-f105w_seg.fits'
# catalog = 'cl1301-11.3-14-122-f105w.cat'
# #ref = 'cl1301-11.3-14-122-f105w_drz_sci.fits'
# grism_files = output_list[key]
# direct_files = output_list[key.replace('f105w','g102')]
grism_files = filter_list['G141'][1]
grism_files.extend(filter_list['G141'][33])
grism_files = glob.glob('*cmb.fits')
ref = 'F160W_mosaic.fits'
seg = 'F160W_seg_blot.fits'
catalog = '/Users/brammer/3DHST/Spectra/Work/3DHST_Detection/GOODS-N_IR.cat'
direct_files = []
reload(utils)
reload(grizlidev.model)
reload(grizlidev.multifit)
grp = grizlidev.multifit.GroupFLT(grism_files=grism_files[:8], direct_files=direct_files, ref_file=ref, seg_file=seg, catalog=catalog)
self = grp
fit_info = {3286: {'mag':-99, 'spec': None},
3279: {'mag':-99, 'spec': None}}
fit_info = OrderedDict()
bright = self.catalog['MAG_AUTO'] < 25
ids = self.catalog['NUMBER'][bright]
mags = self.catalog['MAG_AUTO'][bright]
for id, mag in zip(ids, mags):
fit_info[id] = {'mag':mag, 'spec': None}
# Fast?
#fit_info = {3212: {'mag':-99, 'spec': None}}
#self.compute_single_model(3212)
### parallel
self.compute_full_model(fit_info, store=False)
## Refine
bright = (self.catalog['MAG_AUTO'] < 22) & (self.catalog['MAG_AUTO'] > 16)
ids = self.catalog['NUMBER'][bright]*1
mags = self.catalog['MAG_AUTO'][bright]*1
so = np.argsort(mags)
ids, mags = ids[so], mags[so]
self.refine_list(ids, mags, ds9=ds9, poly_order=1)
# bright = (self.catalog['MAG_AUTO'] < 22) & (self.catalog['MAG_AUTO'] > 16)
# ids = self.catalog['NUMBER'][bright]*1
# mags = self.catalog['MAG_AUTO'][bright]*1
# so = np.argsort(mags)
#
# self.refine_list(ids, mags, ds9=ds9, poly_order=5)
beams = self.get_beams(3212)
### serial
t0 = time.time()
out = _compute_model(0, self.FLTs[i], fit_info, False)
t1 = time.time()
#print t1-t0
id = 3219
fwhm = 1200
zr = [0.58,2.4]
beams = grp.get_beams(id, size=30)
mb = grizlidev.multifit.MultiBeam(beams)
fit, fig = mb.fit_redshift(fwhm=fwhm, zr=zr, poly_order=3, dz=[0.003, 0.003])
A, out_coeffs, chi2, modelf = mb.fit_at_z(poly_order=1)
m2d = mb.reshape_flat(modelf)
def _loadFLT(grism_file, sci_extn, direct_file, pad, ref_file,
ref_ext, seg_file, verbose, catalog, ix):
"""Helper function for loading `.model.GrismFLT` objects with `multiprocessing`.
TBD
"""
import time
try:
import cPickle as pickle
except:
# Python 3
import pickle
## slight random delay to avoid synchronization problems
# np.random.seed(ix)
# sleeptime = ix*1
# print '%s sleep %.3f %d' %(grism_file, sleeptime, ix)
# time.sleep(sleeptime)
#print grism_file, direct_file
save_file = grism_file.replace('_flt.fits', '_GrismFLT.fits')
save_file = save_file.replace('_flc.fits', '_GrismFLT.fits')
save_file = save_file.replace('_cmb.fits', '_GrismFLT.fits')
save_file = save_file.replace('_rate.fits', '_GrismFLT.fits')
if grism_file.find('_') < 0:
save_file = 'xxxxxxxxxxxxxxxxxxx'
if os.path.exists(save_file):
print('Load {0}!'.format(save_file))
fp = open(save_file.replace('GrismFLT.fits', 'GrismFLT.pkl'), 'rb')
flt = pickle.load(fp)
fp.close()
status = flt.load_from_fits(save_file)
else:
flt = model.GrismFLT(grism_file=grism_file, sci_extn=sci_extn,
direct_file=direct_file, pad=pad,
ref_file=ref_file, ref_ext=ref_ext,
seg_file=seg_file, shrink_segimage=True,
verbose=verbose)
if catalog is not None:
flt.catalog = flt.blot_catalog(catalog,
sextractor=('X_WORLD' in catalog.colnames))
flt.catalog_file = catalog
else:
flt.catalog = None
if flt.grism.instrument == 'NIRISS':
flt.transform_NIRISS()
return flt #, out_cat
def _fit_at_z(self, zgrid, i, templates, fitter, fit_background, poly_order):
"""
For parallel processing
"""
# self, z=0., templates={}, fitter='nnls',
# fit_background=True, poly_order=0
print(i, zgrid[i])
out = self.fit_at_z(z=zgrid[i], templates=templates,
fitter=fitter, poly_order=poly_order,
fit_background=fit_background)
data = {'out':out, 'i':i}
return data
#A, coeffs[i,:], chi2[i], model_2d = out
def test_parallel():
zgrid = np.linspace(1.1,1.3,10)
templates = mb.load_templates(fwhm=800)
fitter = 'nnls'
fit_background = True
poly_order = 0
self.FLTs = []
t0_pool = time.time()
pool = mp.Pool(processes=4)
results = [pool.apply_async(_fit_at_z, (mb, zgrid, i, templates, fitter, fit_background, poly_order)) for i in range(len(zgrid))]
pool.close()
pool.join()
chi = zgrid*0.
for res in results:
data = res.get(timeout=1)
A, coeffs, chi[data['i']], model_2d = data['out']
#flt_i.catalog = cat_i
t1_pool = time.time()
def _compute_model(i, flt, fit_info, store):
"""Helper function for computing model orders.
"""
for id in fit_info:
status = flt.compute_model_orders(id=id, compute_size=True,
mag=fit_info[id]['mag'], in_place=True, store=store,
spectrum_1d = fit_info[id]['spec'],
verbose=False)
print('{0}: _compute_model Done'.format(flt.grism.parent_file))
return i, flt.model, flt.object_dispersers
class GroupFLT():
def __init__(self, grism_files=[], sci_extn=1, direct_files=[],
pad=200, group_name='group',
ref_file=None, ref_ext=0, seg_file=None,
shrink_segimage=True, verbose=True, cpu_count=0,
catalog=''):
"""Main container for handling multiple grism exposures together
Parameters
----------
grism_files : list
List of grism exposures (typically WFC3/IR "FLT" or ACS/UVIS "FLC"
files). These can be from different grisms and/or orients.
sci_extn : int
Science extension to extract from the files in `grism_files`. For
WFC3/IR this can only be 1, though for the two-chip instruments
WFC3/UVIS and ACS/WFC3 this can be 1 or 2.
direct_files : list
List of direct exposures (typically WFC3/IR "FLT" or ACS/UVIS
"FLC" files). This list should either be empty or should
correspond one-to-one with entries in the `grism_files` list,
i.e., from an undithered pair of direct and grism exposures. If
such pairs weren't obtained or if you simply wish to ignore them
and just use the `ref_file` reference image, set to an empty list
(`[]`).
pad : int
Padding in pixels to apply around the edge of the detector to
allow modeling of sources that fall off of the nominal FOV. For
this to work requires using a `ref_file` reference image that
covers this extra area.
group_name : str
Name to apply to products produced by this group.
ref_file : `None` or str
Undistorted reference image filename, e.g., a drizzled mosaic
covering the area around a given grism exposure.
ref_ext : 0
FITS extension of the reference file where to find the image
itself.
seg_file : `None` or str
Segmentation image filename.
shrink_segimage : bool
Do some preprocessing on the segmentation image to speed up the
blotting to the distorted frame of the grism exposures.
verbose : bool
Print verbose information.
cpu_count : int
Use parallelization if > 0. If equal to zero, then use the
maximum number of available cores.
catalog : str
Catalog filename assocated with `seg_file`. These are typically
generated with "SExtractor", but the source of the files
themselves isn't critical.
Attributes
----------
catalog : `~astropy.table.Table`
The table read in with from the above file specified in `catalog`.
FLTs : list
List of `~grizli.model.GrismFLT` objects generated from each of
the files in the `grism_files` list.
grp.N : int
Number of grism files (i.e., `len(FLTs)`.)
"""
self.N = len(grism_files)
if len(direct_files) != len(grism_files):
direct_files = ['']*self.N
self.grism_files = grism_files
self.direct_files = direct_files
self.group_name = group_name
### Read catalog
if catalog:
if isinstance(catalog, str):
try:
self.catalog = Table.read(catalog,
format='ascii.sextractor')
except:
self.catalog = Table.read(catalog,
format='ascii.commented_header')
else:
self.catalog = catalog
# necessary columns from SExtractor / photutils
pairs = [['NUMBER','id'],
['MAG_AUTO', 'mag'],
['MAGERR_AUTO', 'mag_err']]
cols = self.catalog.colnames
for pair in pairs:
if (pair[0] not in cols) & (pair[1] in cols):
self.catalog[pair[0]] = self.catalog[pair[1]]
else:
self.catalog = None
if cpu_count == 0:
cpu_count = mp.cpu_count()
if cpu_count < 0:
### serial
self.FLTs = []
t0_pool = time.time()
for i in range(self.N):
flt = _loadFLT(self.grism_files[i], sci_extn, self.direct_files[i], pad, ref_file, ref_ext, seg_file, verbose, self.catalog, i)
self.FLTs.append(flt)
t1_pool = time.time()
else:
### Read files in parallel
self.FLTs = []
t0_pool = time.time()
pool = mp.Pool(processes=cpu_count)
results = [pool.apply_async(_loadFLT, (self.grism_files[i], sci_extn, self.direct_files[i], pad, ref_file, ref_ext, seg_file, verbose, self.catalog, i)) for i in range(self.N)]
pool.close()
pool.join()
for res in results:
flt_i = res.get(timeout=1)
#flt_i.catalog = cat_i
# somehow WCS getting flipped from cd to pc in res.get()???
if flt_i.direct.wcs.wcs.has_pc():
for obj in [flt_i.grism, flt_i.direct]:
obj.get_wcs()
self.FLTs.append(flt_i)
t1_pool = time.time()
if verbose:
print('Files loaded - {0:.2f} sec.'.format(t1_pool - t0_pool))
def save_full_data(self, warn=True):
"""Save models and data files for fast regeneration.
Parameters
----------
warn : bool
Print a warning and skip if an output file is already found to
exist.
The filenames of the outputs are generated from the input grism
exposure filenames with the following:
>>> file = 'ib3701ryq_flt.fits'
>>> save_file = file.replace('_flt.fits', '_GrismFLT.fits')
>>> save_file = save_file.replace('_flc.fits', '_GrismFLT.fits')
>>> save_file = save_file.replace('_cmb.fits', '_GrismFLT.fits')
>>> save_file = save_file.replace('_rate.fits', '_GrismFLT.fits')
It will also save data to a `~pickle` file:
>>> pkl_file = save_file.replace('.fits', '.pkl')
"""
for i in range(self.N):
file = self.FLTs[i].grism_file
if self.FLTs[i].grism.data is None:
if warn:
print('{0}: Looks like data already saved!'.format(file))
continue
save_file = file.replace('_flt.fits', '_GrismFLT.fits')
save_file = save_file.replace('_flc.fits', '_GrismFLT.fits')
save_file = save_file.replace('_cmb.fits', '_GrismFLT.fits')
save_file = save_file.replace('_rate.fits', '_GrismFLT.fits')
print('Save {0}'.format(save_file))
self.FLTs[i].save_full_pickle()
### Reload initialized data
self.FLTs[i].load_from_fits(save_file)
def extend(self, new, verbose=True):
"""Add another `GroupFLT` instance to `self`
This function appends the exposures if a separate `GroupFLT` instance
to the current instance. You might do this, for example, if you
generate separate `GroupFLT` instances for different grisms and
reference images with different filters.
"""
self.FLTs.extend(new.FLTs)
self.N = len(self.FLTs)
self.direct_files.extend(new.direct_files)
self.grism_files.extend(new.grism_files)
if verbose:
print('Now we have {0:d} FLTs'.format(self.N))
def compute_single_model(self, id, mag=-99, size=-1, store=False, spectrum_1d=None, get_beams=None, in_place=True):
"""Compute model spectrum in all exposures
TBD
Parameters
----------
id : type
mag : type
size : type
store : type
spectrum_1d : type
get_beams : type
in_place : type
Returns
-------
TBD
"""
out_beams = []
for flt in self.FLTs:
status = flt.compute_model_orders(id=id, verbose=False,
size=size, compute_size=(size < 0),
mag=mag, in_place=in_place, store=store,
spectrum_1d = spectrum_1d, get_beams=get_beams)
out_beams.append(status)
if get_beams:
return out_beams
else:
return True
def compute_full_model(self, fit_info=None, verbose=True, store=False,
mag_limit=25, coeffs=[1.2, -0.5], cpu_count=0):
"""TBD
"""
if cpu_count == 0:
cpu_count = mp.cpu_count()
if fit_info is None:
bright = self.catalog['MAG_AUTO'] < mag_limit
ids = self.catalog['NUMBER'][bright]
mags = self.catalog['MAG_AUTO'][bright]
xspec = np.arange(0.3, 2.35, 0.05)-1
yspec = [xspec**o*coeffs[o] for o in range(len(coeffs))]
xspec = (xspec+1)*1.e4
yspec = np.sum(yspec, axis=0)
fit_info = OrderedDict()
for id, mag in zip(ids, mags):
fit_info[id] = {'mag':mag, 'spec': [xspec, yspec]}
t0_pool = time.time()
pool = mp.Pool(processes=cpu_count)
results = [pool.apply_async(_compute_model, (i, self.FLTs[i], fit_info, store)) for i in range(self.N)]
pool.close()
pool.join()
for res in results:
i, model, dispersers = res.get(timeout=1)
self.FLTs[i].object_dispersers = dispersers
self.FLTs[i].model = model
t1_pool = time.time()
if verbose:
print('Models computed - {0:.2f} sec.'.format(t1_pool - t0_pool))
def get_beams(self, id, size=10, beam_id='A', min_overlap=0.2,
get_slice_header=True):
"""TBD
"""
beams = self.compute_single_model(id, size=size, store=False, get_beams=[beam_id])
out_beams = []
for flt, beam in zip(self.FLTs, beams):
try:
out_beam = model.BeamCutout(flt=flt, beam=beam[beam_id],
conf=flt.conf,
get_slice_header=get_slice_header)
except:
continue
hasdata = ((out_beam.grism['SCI'] != 0).sum(axis=0) > 0).sum()
if hasdata*1./out_beam.model.shape[1] < min_overlap:
continue
out_beams.append(out_beam)
return out_beams
def refine_list(self, ids=[], mags=[], poly_order=2, mag_limits=[16,24],
max_coeff=5, ds9=None, verbose=True):
"""TBD
bright = self.catalog['MAG_AUTO'] < 24
ids = self.catalog['NUMBER'][bright]*1
mags = self.catalog['MAG_AUTO'][bright]*1
so = np.argsort(mags)
ids, mags = ids[so], mags[so]
self.refine_list(ids, mags, ds9=ds9)
"""
if (len(ids) == 0) | (len(ids) != len(mags)):
bright = ((self.catalog['MAG_AUTO'] < mag_limits[1]) &
(self.catalog['MAG_AUTO'] > mag_limits[0]))
ids = self.catalog['NUMBER'][bright]*1
mags = self.catalog['MAG_AUTO'][bright]*1
so = np.argsort(mags)
ids, mags = ids[so], mags[so]
for id, mag in zip(ids, mags):
self.refine(id, mag=mag, poly_order=poly_order,
max_coeff=max_coeff, size=30, ds9=ds9,
verbose=verbose)
def refine(self, id, mag=-99, poly_order=1, size=30, ds9=None, verbose=True, max_coeff=2.5):
"""TBD
"""
beams = self.get_beams(id, size=size, min_overlap=0.5, get_slice_header=False)
if len(beams) == 0:
return True
mb = MultiBeam(beams)
try:
A, out_coeffs, chi2, modelf = mb.fit_at_z(poly_order=poly_order, fit_background=True, fitter='lstsq')
except:
return False
xspec = np.arange(0.3, 2.35, 0.05)-1
scale_coeffs = out_coeffs[mb.N*mb.fit_bg:mb.N*mb.fit_bg+mb.n_poly]
yspec = [xspec**o*scale_coeffs[o] for o in range(mb.poly_order+1)]
if np.abs(scale_coeffs).max() > max_coeff:
return True
self.compute_single_model(id, mag=mag, size=-1, store=False, spectrum_1d=[(xspec+1)*1.e4, np.sum(yspec, axis=0)], get_beams=None, in_place=True)
if ds9:
flt = self.FLTs[0]
mask = flt.grism['SCI'] != 0
ds9.view((flt.grism['SCI'] - flt.model)*mask,
header=flt.grism.header)
if verbose:
print('{0} mag={1:6.2f} {2}'.format(id, mag, scale_coeffs))
return True
#m2d = mb.reshape_flat(modelf)
def make_stack(self, id, size=20, target='grism', skip=True, fcontam=1., scale=1, save=True):
"""Make drizzled 2D stack for a given object
Parameters
----------
id : int
Object ID number.
target : str
Rootname for output files.
skip : bool
If True and the stack PNG file already exists, don't proceed.
fcontam : float
Contamination weighting parameter.
save : bool
Save the figure and FITS HDU to files with names like
>>> img_file = '{0}_{1:05d}.stack.png'.format(target, id)
>>> fits_file = '{0}_{1:05d}.stack.fits'.format(target, id)
Returns
-------
hdu : `~astropy.io.fits.HDUList`
FITS HDU of the stacked spectra.
fig : `~matplotlib.figure.Figure`
Stack figure object.
"""
print(target, id)
if os.path.exists('{0}_{1:05d}.stack.png'.format(target, id)) & skip:
return True
beams = self.get_beams(id, size=size, beam_id='A')
if len(beams) == 0:
print('id = {0}: No beam cutouts available.'.format(id))
return None
mb = MultiBeam(beams, fcontam=fcontam, group_name=target)
hdu, fig = mb.drizzle_grisms_and_PAs(fcontam=fcontam, flambda=False,
kernel='point', size=size,
scale=scale)
if save:
fig.savefig('{0}_{1:05d}.stack.png'.format(target, id))
hdu.writeto('{0}_{1:05d}.stack.fits'.format(target, id),
clobber=True)
return hdu, fig
def drizzle_full_wavelength(self, wave=1.4e4, ref_header=None,
kernel='point', pixfrac=1., verbose=True,
offset=[0,0], fcontam=0.):
"""Drizzle FLT frames recentered at a specified wavelength
Script computes polynomial coefficients that define the dx and dy
offsets to a specific dispersed wavelengh relative to the reference
position and adds these to the SIP distortion keywords before
drizzling the input exposures to the output frame.
Parameters
----------
wave : float
Reference wavelength to center the output products
ref_header : `~astropy.io.fits.Header`
Reference header for setting the output WCS and image dimensions.
kernel : str, ('square' or 'point')
Drizzle kernel to use
pixfrac : float
Drizzle PIXFRAC (for `kernel` = 'point')
verbose : bool
Print information to terminal
Returns
-------
sci, wht : `~np.ndarray`
Drizzle science and weight arrays with dimensions set in
`ref_header`.
"""
from astropy.modeling import models, fitting
from drizzlepac.astrodrizzle import adrizzle
import astropy.wcs as pywcs
## Quick check now for which grism exposures we should use
if wave < 1.1e4:
use_grism = 'G102'
else:
use_grism = 'G141'
# Get the configuration file
conf = None
for i in range(self.N):
if self.FLTs[i].grism.filter == use_grism:
conf = self.FLTs[i].conf
# Grism not found in list
if conf is None:
return False
# Compute field-dependent dispersion parameters
dydx_0_p = conf.conf['DYDX_A_0']
dydx_1_p = conf.conf['DYDX_A_1']
dldp_0_p = conf.conf['DLDP_A_0']
dldp_1_p = conf.conf['DLDP_A_1']
yp, xp = np.indices((1014,1014)) # hardcoded for WFC3/IR
sk = 10 # don't need to evaluate at every pixel
dydx_0 = conf.field_dependent(xp[::sk,::sk], yp[::sk,::sk], dydx_0_p)
dydx_1 = conf.field_dependent(xp[::sk,::sk], yp[::sk,::sk], dydx_1_p)
dldp_0 = conf.field_dependent(xp[::sk,::sk], yp[::sk,::sk], dldp_0_p)
dldp_1 = conf.field_dependent(xp[::sk,::sk], yp[::sk,::sk], dldp_1_p)
# Inverse pixel offsets from the specified wavelength
dp = (wave - dldp_0)/dldp_1
i_x, i_y = 1, 0 # indexing offsets
dx = dp/np.sqrt(1+dydx_1) + i_x
dy = dydx_0 + dydx_1*dx + i_y
dx += offset[0]
dy += offset[1]
# Compute polynomial coefficients
p_init = models.Polynomial2D(degree=4)
#fit_p = fitting.LevMarLSQFitter()
fit_p = fitting.LinearLSQFitter()
p_dx = fit_p(p_init, xp[::sk,::sk]-507, yp[::sk,::sk]-507, -dx)
p_dy = fit_p(p_init, xp[::sk,::sk]-507, yp[::sk,::sk]-507, -dy)
# Output WCS
out_wcs = pywcs.WCS(ref_header, relax=True)
out_wcs.pscale = utils.get_wcs_pscale(out_wcs)
# Initialize outputs
shape = (ref_header['NAXIS2'], ref_header['NAXIS1'])
outsci = np.zeros(shape, dtype=np.float32)
outwht = np.zeros(shape, dtype=np.float32)
outctx = np.zeros(shape, dtype=np.int32)
# Loop through exposures
for i in range(self.N):
flt = self.FLTs[i]
if flt.grism.filter != use_grism:
continue
h = flt.grism.header.copy()
# Update SIP coefficients
for j, p in enumerate(p_dx.param_names):
key = 'A_'+p[1:]
if key in h:
h[key] += p_dx.parameters[j]
else:
h[key] = p_dx.parameters[j]
for j, p in enumerate(p_dy.param_names):
key = 'B_'+p[1:]
if key in h:
h[key] += p_dy.parameters[j]
else:
h[key] = p_dy.parameters[j]
line_wcs = pywcs.WCS(h, relax=True)
line_wcs.pscale = utils.get_wcs_pscale(line_wcs)
# Science and wht arrays
sci = flt.grism['SCI'] - flt.model
wht = 1/(flt.grism['ERR']**2)
scl = np.exp(-(fcontam*np.abs(flt.model)/flt.grism['ERR']))
wht *= scl
wht[~np.isfinite(wht)] = 0
# Drizzle it
if verbose:
print('Drizzle {0} to wavelength {1:.2f}'.format(flt.grism.parent_file, wave))
adrizzle.do_driz(sci, line_wcs, wht, out_wcs,
outsci, outwht, outctx, 1., 'cps', 1,
wcslin_pscale=line_wcs.pscale, uniqid=1,
pixfrac=pixfrac, kernel=kernel, fillval=0,
stepsize=10, wcsmap=None)
# Done!
return outsci, outwht
class MultiBeam():
def __init__(self, beams, group_name='group', fcontam=0., psf=False):
"""Tools for dealing with multiple `~.model.BeamCutout` instances
Parameters
----------
beams : list
List of `~.model.BeamCutout` objects.
group_name : type
Rootname to use for saved products
fcontam : type
Factor to use to downweight contaminated pixels.
Attributes
----------
TBD : type
"""
self.N = len(beams)
self.group_name = group_name
if hasattr(beams[0], 'lower'):
### `beams` is list of strings
self.load_beam_fits(beams)
else:
self.beams = beams
self.Ngrism = {}
for i in range(self.N):
if self.beams[i].grism.instrument == 'NIRISS':
grism = self.beams[i].grism.pupil
else:
grism = self.beams[i].grism.filter
if grism in self.Ngrism:
self.Ngrism[grism] += 1
else:
self.Ngrism[grism] = 1
self.PA = {}
for g in self.Ngrism:
self.PA[g] = {}
for i in range(self.N):
if self.beams[i].grism.instrument == 'NIRISS':
grism = self.beams[i].grism.pupil
else:
grism = self.beams[i].grism.filter
PA = self.beams[i].get_dispersion_PA(decimals=0)
if PA in self.PA[grism]:
self.PA[grism][PA].append(i)
else:
self.PA[grism][PA] = [i]
self.id = self.beams[0].id
self.poly_order = None
self.shapes = [beam.model.shape for beam in self.beams]
self.Nflat = [np.product(shape) for shape in self.shapes]
self.Ntot = np.sum(self.Nflat)
### Big array of normalized wavelengths (wave / 1.e4 - 1)
self.xpf = np.hstack([np.dot(np.ones((b.beam.sh_beam[0],1)),
b.beam.lam[None,:]).flatten()/1.e4
for b in self.beams]) - 1
### Flat-flambda model spectra
self.flat_flam = np.hstack([b.flat_flam for b in self.beams])
self.fit_mask = np.hstack([b.fit_mask*b.contam_mask
for b in self.beams])
self.DoF = self.fit_mask.sum()
self.ivarf = np.hstack([b.ivarf for b in self.beams])
self.ivarf[~np.isfinite(self.ivarf)] = 0
self.fit_mask &= (self.ivarf >= 0)
self.scif = np.hstack([b.scif for b in self.beams])
self.contamf = np.hstack([b.contam.flatten() for b in self.beams])
self.weight = np.exp(-(fcontam*np.abs(self.contamf)*np.sqrt(self.ivarf)))
self.DoF = int((self.weight*self.fit_mask).sum())
self.fcontam = fcontam
# if fcontam > 0:
# self.ivarf = 1./(1./self.ivarf + (fcontam*self.contamf)**2)
# self.ivarf[~np.isfinite(self.ivarf)] = 0
# self.ivarf[self.ivarf < 0] = 0
#mask = (self.contamf*np.sqrt(self.ivarf) > fcontam) & (self.contamf > fcontam*self.flat_flam)
#self.ivarf[mask] = 0
### Initialize background fit array
self.A_bg = np.zeros((self.N, self.Ntot))
i0 = 0
for i in range(self.N):
self.A_bg[i, i0:i0+self.Nflat[i]] = 1.
i0 += self.Nflat[i]
self.init_poly_coeffs(poly_order=1)
self.ra, self.dec = self.beams[0].get_sky_coords()
def write_beam_fits(self, verbose=True):
"""TBD
"""
outfiles = []
for beam in self.beams:
root = beam.grism.parent_file.split('.fits')[0]
outfile = beam.write_fits(root)
if verbose:
print('Wrote {0}'.format(outfile))
outfiles.append(outfile)
return outfiles
def load_beam_fits(self, beam_list, conf=None, verbose=True):
"""TBD
"""
self.beams = []
for file in beam_list:
if verbose:
print(file)
beam = model.BeamCutout(fits_file=file, conf=conf)
self.beams.append(beam)
def reshape_flat(self, flat_array):
"""TBD
"""
out = []
i0 = 0
for ib in range(self.N):
im2d = flat_array[i0:i0+self.Nflat[ib]].reshape(self.shapes[ib])
out.append(im2d)
i0 += self.Nflat[ib]
return out
def init_poly_coeffs(self, flat=None, poly_order=1):
"""TBD
"""
### Already done?
if poly_order == self.poly_order:
return None
self.poly_order = poly_order
if flat is None:
flat = self.flat_flam
### Polynomial continuum arrays
self.A_poly = np.array([self.xpf**order*flat
for order in range(poly_order+1)])
self.n_poly = poly_order + 1
self.x_poly = np.array([(self.beams[0].beam.lam/1.e4-1)**order
for order in range(poly_order+1)])