forked from gbrammer/grizli
/
model.py
5733 lines (4563 loc) · 201 KB
/
model.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
"""
Model grism spectra in individual FLTs
"""
import os
import glob
from collections import OrderedDict
import copy
import traceback
import numpy as np
import scipy.ndimage as nd
import matplotlib.pyplot as plt
import astropy.io.fits as pyfits
from astropy.table import Table
import astropy.wcs as pywcs
import astropy.units as u
#import stwcs
# Helper functions from a document written by Pirzkal, Brammer & Ryan
from . import grismconf
from . import utils
# from .utils_c import disperse
# from .utils_c import interp
from . import GRIZLI_PATH
# Would prefer 'nearest' but that occasionally segment faults out
SEGMENTATION_INTERP = 'nearest'
# Factors for converting HST countrates to Flamba flux densities
photflam_list = {'F098M': 6.0501324882418389e-20,
'F105W': 3.038658152508547e-20,
'F110W': 1.5274130068787271e-20,
'F125W': 2.2483414275260141e-20,
'F140W': 1.4737154005353565e-20,
'F160W': 1.9275637653833683e-20,
'F435W': 3.1871480286278679e-19,
'F606W': 7.8933594352047833e-20,
'F775W': 1.0088466875014488e-19,
'F814W': 7.0767633156044843e-20,
'VISTAH': 1.9275637653833683e-20*0.95,
'GRISM': 1.e-20,
'G150': 1.e-20,
'G800L': 1.,
'G280': 1.,
'F444W': 1.e-20,
'F115W': 1.,
'F150W': 1.,
'F200W': 1.}
# Filter pivot wavelengths
photplam_list = {'F098M': 9864.722728110915,
'F105W': 10551.046906405772,
'F110W': 11534.45855553774,
'F125W': 12486.059785775655,
'F140W': 13922.907350356367,
'F160W': 15369.175708965562,
'F435W': 4328.256914042873,
'F606W': 5921.658489236346,
'F775W': 7693.297933335407,
'F814W': 8058.784799323767,
'VISTAH': 1.6433e+04,
'GRISM': 1.6e4, # WFIRST/Roman
'G150': 1.46e4, # WFIRST/Roman
'G800L': 7.4737026e3,
'G280': 3651.,
'F070W': 7.043e+03, # NIRCam
'F090W': 9.023e+03,
'F115W': 1.150e+04, # NIRISS
'F150W': 1.493e+04, # NIRISS
'F200W': 1.993e+04, # NIRISS
'F150W2': 1.658e+04,
'F140M': 1.405e+04,
'F158M': 1.582e+04, # NIRISS
'F162M': 1.627e+04,
'F182M': 1.845e+04,
'F210M': 2.096e+04,
'F164N': 1.645e+04,
'F187N': 1.874e+04,
'F212N': 2.121e+04,
'F277W': 2.758e+04,
'F356W': 3.568e+04,
'F444W': 4.404e+04,
'F322W2': 3.232e+04,
'F250M': 2.503e+04,
'F300M': 2.987e+04,
'F335M': 3.362e+04,
'F360M': 3.624e+04,
'F380M': 3.825e+04, # NIRISS
'F410M': 4.082e+04,
'F430M': 4.280e+04,
'F460M': 4.626e+04,
'F480M': 4.816e+04,
'F323N': 3.237e+04,
'F405N': 4.052e+04,
'F466N': 4.654e+04,
'F470N': 4.708e+04}
# character to skip clearing line on STDOUT printing
#no_newline = '\x1b[1A\x1b[1M'
# Demo for computing photflam and photplam with pysynphot
if False:
import pysynphot as S
n = 1.e-20
spec = S.FlatSpectrum(n, fluxunits='flam')
photflam_list = {}
photplam_list = {}
for filter in ['F098M', 'F105W', 'F110W', 'F125W', 'F140W', 'F160W', 'G102', 'G141']:
bp = S.ObsBandpass('wfc3,ir,{0}'.format(filter.lower()))
photplam_list[filter] = bp.pivot()
obs = S.Observation(spec, bp)
photflam_list[filter] = n/obs.countrate()
for filter in ['F435W', 'F606W', 'F775W', 'F814W']:
bp = S.ObsBandpass('acs,wfc1,{0}'.format(filter.lower()))
photplam_list[filter] = bp.pivot()
obs = S.Observation(spec, bp)
photflam_list[filter] = n/obs.countrate()
class GrismDisperser(object):
def __init__(self, id=0, direct=None,
segmentation=None, origin=[500, 500],
xcenter=0., ycenter=0., pad=(0,0), grow=1, beam='A',
conf=['WFC3', 'F140W', 'G141'], scale=1.,
fwcpos=None, MW_EBV=0., yoffset=0, xoffset=None):
"""Object for computing dispersed model spectra
Parameters
----------
id : int
Only consider pixels in the segmentation image with value `id`.
Default of zero to match the default empty segmentation image.
direct : `~numpy.ndarray`
Direct image cutout in f_lambda units (i.e., e-/s times PHOTFLAM).
Default is a trivial zeros array.
segmentation : `~numpy.ndarray` (float32) or None
Segmentation image. If None, create a zeros array with the same
shape as `direct`.
origin : [int, int]
`origin` defines the lower left pixel index (y,x) of the `direct`
cutout from a larger detector-frame image
xcenter, ycenter : float, float
Sub-pixel centering of the exact center of the object, relative
to the center of the thumbnail. Needed for getting exact
wavelength grid correct for the extracted 2D spectra.
pad : int, int
Offset between origin = [0,0] and the true lower left pixel of the
detector frame. This can be nonzero for cases where one creates
a direct image that extends beyond the boundaries of the nominal
detector frame to model spectra at the edges.
grow : int >= 1
Interlacing factor.
beam : str
Spectral order to compute. Must be defined in `self.conf.beams`
conf : [str, str, str] or `grismconf.aXeConf` object.
Pre-loaded aXe-format configuration file object or if list of
strings determine the appropriate configuration filename with
`grismconf.get_config_filename` and load it.
scale : float
Multiplicative factor to apply to the modeled spectrum from
`compute_model`.
fwcpos : float
Rotation position of the NIRISS filter wheel
MW_EBV : float
Galactic extinction
yoffset : float
Cross-dispersion offset to apply to the trace
xoffset : float
Dispersion offset to apply to the trace
Attributes
----------
sh : 2-tuple
shape of the direct array
sh_beam : 2-tuple
computed shape of the 2D spectrum
seg : `~numpy.array`
segmentation array
lam : `~numpy.array`
wavelength along the trace
ytrace : `~numpy.array`
y pixel center of the trace. Has same dimensions as sh_beam[1].
sensitivity : `~numpy.array`
conversion factor from native e/s to f_lambda flux densities
lam_beam, ytrace_beam, sensitivity_beam : `~numpy.array`
Versions of the above attributes defined for just the specific
pixels of the pixel beam, not the full 2D extraction.
modelf, model : `~numpy.array`, `~numpy.ndarray`
2D model spectrum. `model` is linked to `modelf` with "reshape",
the later which is a flattened 1D array where the fast
calculations are actually performed.
model : `~numpy.ndarray`
2D model spectrum linked to `modelf` with reshape.
slx_parent, sly_parent : slice
slices defined relative to `origin` to match the location of the
computed 2D spectrum.
total_flux : float
Total f_lambda flux in the thumbail within the segmentation
region.
"""
self.id = id
# lower left pixel of the `direct` array in native detector
# coordinates
self.origin = origin
if isinstance(pad, int):
self.pad = [pad, pad]
else:
self.pad = pad
self.grow = grow
# Galactic extinction
self.MW_EBV = MW_EBV
self.init_galactic_extinction(self.MW_EBV)
self.fwcpos = fwcpos
self.scale = scale
# Direct image
if direct is None:
direct = np.zeros((20, 20), dtype=np.float32)
self.direct = direct
self.sh = self.direct.shape
if self.direct.dtype is not np.float32:
self.direct = np.cast[np.float32](self.direct)
# Segmentation image, defaults to all zeros
if segmentation is None:
#self.seg = np.zeros_like(self.direct, dtype=np.float32)
empty = np.zeros_like(self.direct, dtype=np.float32)
self.set_segmentation(empty)
else:
self.set_segmentation(segmentation.astype(np.float32))
# Initialize attributes
self.spectrum_1d = None
self.is_cgs = False
self.xc = self.sh[1]/2+self.origin[1]
self.yc = self.sh[0]/2+self.origin[0]
# Sub-pixel centering of the exact center of the object, relative
# to the center of the thumbnail
self.xcenter = xcenter
self.ycenter = ycenter
self.beam = beam
# Config file
if isinstance(conf, list):
conf_f = grismconf.get_config_filename(*conf)
self.conf = grismconf.load_grism_config(conf_f)
else:
self.conf = conf
# Get Pixel area map (xxx need to add test for WFC3)
self.PAM_value = self.get_PAM_value(verbose=False)
self.process_config()
self.yoffset = yoffset
if xoffset is not None:
self.xoffset = xoffset
if (yoffset != 0) | (xoffset is not None):
#print('yoffset!', yoffset)
self.add_ytrace_offset(yoffset)
def set_segmentation(self, seg_array):
"""
Set Segmentation array and `total_flux`.
"""
self.seg = seg_array*1
self.seg_ids = list(np.unique(self.seg))
try:
self.total_flux = self.direct[self.seg == self.id].sum()
if self.total_flux == 0:
self.total_flux = 1
except:
self.total_flux = 1.
def init_galactic_extinction(self, MW_EBV=0., R_V=utils.MW_RV):
"""
Initialize Fitzpatrick 99 Galactic extinction
Parameters
----------
MW_EBV : float
Local E(B-V)
R_V : float
Relation between specific and total extinction,
``a_v = r_v * ebv``.
Returns
-------
Sets `self.MW_F99` attribute, which is a callable function that
returns the extinction for a supplied array of wavelengths.
If MW_EBV <= 0, then sets `self.MW_F99 = None`.
"""
self.MW_F99 = None
if MW_EBV > 0:
self.MW_F99 = utils.MW_F99(MW_EBV*R_V, r_v=R_V)
def process_config(self):
"""Process grism config file
Parameters
----------
none
Returns
-------
Sets attributes that define how the dispersion is computed. See the
attributes list for `~grizli.model.GrismDisperser`.
"""
from .utils_c import interp
# Get dispersion parameters at the reference position
self.dx = self.conf.dxlam[self.beam] # + xcenter #-xoffset
if self.grow > 1:
self.dx = np.arange(self.dx[0]*self.grow, self.dx[-1]*self.grow)
xoffset = 0.
if ('G14' in self.conf.conf_file) & (self.beam == 'A'):
xoffset = -0.5 # necessary for WFC3/IR G141, v4.32
# xoffset = 0. # suggested by ACS
# xoffset = -2.5 # test
self.xoffset = xoffset
self.ytrace_beam, self.lam_beam = self.conf.get_beam_trace(
x=(self.xc+self.xcenter-self.pad[1])/self.grow,
y=(self.yc+self.ycenter-self.pad[0])/self.grow,
dx=(self.dx+self.xcenter*0+self.xoffset)/self.grow,
beam=self.beam, fwcpos=self.fwcpos)
self.ytrace_beam *= self.grow
# Integer trace
# Add/subtract 20 for handling int of small negative numbers
dyc = np.cast[int](self.ytrace_beam+20)-20+1
# Account for pixel centering of the trace
self.yfrac_beam = self.ytrace_beam - np.floor(self.ytrace_beam)
# Interpolate the sensitivity curve on the wavelength grid.
ysens = self.lam_beam*0
so = np.argsort(self.lam_beam)
conf_sens = self.conf.sens[self.beam]
if self.MW_F99 is not None:
MWext = 10**(-0.4*(self.MW_F99(conf_sens['WAVELENGTH']*u.AA)))
else:
MWext = 1.
ysens[so] = interp.interp_conserve_c(self.lam_beam[so],
conf_sens['WAVELENGTH'],
conf_sens['SENSITIVITY']*MWext,
integrate=1, left=0, right=0)
self.lam_sort = so
# Needs term of delta wavelength per pixel for flux densities
# dl = np.abs(np.append(self.lam_beam[1] - self.lam_beam[0],
# np.diff(self.lam_beam)))
# ysens *= dl#*1.e-17
self.sensitivity_beam = ysens
# Initialize the model arrays
self.NX = len(self.dx)
self.sh_beam = (self.sh[0], self.sh[1]+self.NX)
self.modelf = np.zeros(np.product(self.sh_beam), dtype=np.float32)
self.model = self.modelf.reshape(self.sh_beam)
self.idx = np.arange(self.modelf.size,
dtype=np.int64).reshape(self.sh_beam)
# Indices of the trace in the flattened array
self.x0 = np.array(self.sh, dtype=np.int64) // 2
self.x0 -= 1 # zero index!
self.dxpix = self.dx - self.dx[0] + self.x0[1] # + 1
try:
self.flat_index = self.idx[dyc + self.x0[0], self.dxpix]
except IndexError:
#print('Index Error', id, dyc.dtype, self.dxpix.dtype, self.x0[0], self.xc, self.yc, self.beam, self.ytrace_beam.max(), self.ytrace_beam.min())
raise IndexError
# Trace, wavelength, sensitivity across entire 2D array
self.dxfull = np.arange(self.sh_beam[1], dtype=int)
self.dxfull += self.dx[0]-self.x0[1]
# self.ytrace, self.lam = self.conf.get_beam_trace(x=self.xc,
# y=self.yc, dx=self.dxfull, beam=self.beam)
self.ytrace, self.lam = self.conf.get_beam_trace(
x=(self.xc+self.xcenter-self.pad[1])/self.grow,
y=(self.yc+self.ycenter-self.pad[0])/self.grow,
dx=(self.dxfull+self.xcenter+xoffset)/self.grow,
beam=self.beam, fwcpos=self.fwcpos)
self.ytrace *= self.grow
ysens = self.lam*0
so = np.argsort(self.lam)
ysens[so] = interp.interp_conserve_c(self.lam[so],
conf_sens['WAVELENGTH'],
conf_sens['SENSITIVITY']*MWext,
integrate=1, left=0, right=0)
# dl = np.abs(np.append(self.lam[1] - self.lam[0],
# np.diff(self.lam)))
# ysens *= dl#*1.e-17
self.sensitivity = ysens
# Slices of the parent array based on the origin parameter
self.slx_parent = slice(self.origin[1] + self.dxfull[0] + self.x0[1],
self.origin[1] + self.dxfull[-1] + self.x0[1]+1)
self.sly_parent = slice(self.origin[0], self.origin[0] + self.sh[0])
# print 'XXX wavelength: %s %s %s' %(self.lam[-5:], self.lam_beam[-5:], dl[-5:])
def add_ytrace_offset(self, yoffset):
"""Add an offset in Y to the spectral trace
Parameters
----------
yoffset : float
Y-offset to apply
"""
from .utils_c.interp import interp_conserve_c
self.ytrace_beam, self.lam_beam = self.conf.get_beam_trace(
x=(self.xc+self.xcenter-self.pad[1])/self.grow,
y=(self.yc+self.ycenter-self.pad[0])/self.grow,
dx=(self.dx+self.xcenter*0+self.xoffset)/self.grow,
beam=self.beam, fwcpos=self.fwcpos)
self.ytrace_beam *= self.grow
self.yoffset = yoffset
self.ytrace_beam += yoffset
# Integer trace
# Add/subtract 20 for handling int of small negative numbers
dyc = np.cast[int](self.ytrace_beam+20)-20+1
# Account for pixel centering of the trace
self.yfrac_beam = self.ytrace_beam - np.floor(self.ytrace_beam)
try:
self.flat_index = self.idx[dyc + self.x0[0], self.dxpix]
except IndexError:
# print 'Index Error', id, self.x0[0], self.xc, self.yc, self.beam, self.ytrace_beam.max(), self.ytrace_beam.min()
raise IndexError
# Trace, wavelength, sensitivity across entire 2D array
self.ytrace, self.lam = self.conf.get_beam_trace(
x=(self.xc+self.xcenter-self.pad[1])/self.grow,
y=(self.yc+self.ycenter-self.pad[0])/self.grow,
dx=(self.dxfull+self.xcenter+self.xoffset)/self.grow,
beam=self.beam, fwcpos=self.fwcpos)
self.ytrace *= self.grow
self.ytrace += yoffset
# Reset sensitivity
ysens = self.lam_beam*0
so = np.argsort(self.lam_beam)
conf_sens = self.conf.sens[self.beam]
if self.MW_F99 is not None:
MWext = 10**(-0.4*(self.MW_F99(conf_sens['WAVELENGTH']*u.AA)))
else:
MWext = 1.
ysens[so] = interp_conserve_c(self.lam_beam[so],
conf_sens['WAVELENGTH'],
conf_sens['SENSITIVITY']*MWext,
integrate=1, left=0, right=0)
self.lam_sort = so
self.sensitivity_beam = ysens
# Full array
ysens = self.lam*0
so = np.argsort(self.lam)
ysens[so] = interp_conserve_c(self.lam[so],
conf_sens['WAVELENGTH'],
conf_sens['SENSITIVITY']*MWext,
integrate=1, left=0, right=0)
self.sensitivity = ysens
def compute_model(self, id=None, thumb=None, spectrum_1d=None,
in_place=True, modelf=None, scale=None, is_cgs=False,
apply_sensitivity=True, reset=True):
"""Compute a model 2D grism spectrum
Parameters
----------
id : int
Only consider pixels in the segmentation image (`self.seg`) with
values equal to `id`.
thumb : `~numpy.ndarray` with shape = `self.sh` or None
Optional direct image. If `None` then use `self.direct`.
spectrum_1d : [`~numpy.array`, `~numpy.array`] or None
Optional 1D template [wave, flux] to use for the 2D grism model.
If `None`, then implicitly assumes flat f_lambda spectrum.
in_place : bool
If True, put the 2D model in `self.model` and `self.modelf`,
otherwise put the output in a clean array or preformed `modelf`.
modelf : `~numpy.array` with shape = `self.sh_beam`
Preformed (flat) array to which the 2D model is added, if
`in_place` is False.
scale : float or None
Multiplicative factor to apply to the modeled spectrum.
is_cgs : bool
Units of `spectrum_1d` fluxes are f_lambda cgs.
Returns
-------
model : `~numpy.ndarray`
If `in_place` is False, returns the 2D model spectrum. Otherwise
the result is stored in `self.model` and `self.modelf`.
"""
from .utils_c import disperse
from .utils_c import interp
if id is None:
id = self.id
total_flux = self.total_flux
else:
self.id = id
total_flux = self.direct[self.seg == id].sum()
# Template (1D) spectrum interpolated onto the wavelength grid
if in_place:
self.spectrum_1d = spectrum_1d
if scale is None:
scale = self.scale
else:
self.scale = scale
if spectrum_1d is not None:
xspec, yspec = spectrum_1d
scale_spec = self.sensitivity_beam*0.
int_func = interp.interp_conserve_c
scale_spec[self.lam_sort] = int_func(self.lam_beam[self.lam_sort],
xspec, yspec)*scale
else:
scale_spec = scale
self.is_cgs = is_cgs
if is_cgs:
scale_spec /= total_flux
# Output data, fastest is to compute in place but doesn't zero-out
# previous result
if in_place:
self.modelf *= (1-reset)
modelf = self.modelf
else:
if modelf is None:
modelf = self.modelf*(1-reset)
# Optionally use a different direct image
if thumb is None:
thumb = self.direct
else:
if thumb.shape != self.sh:
print("""
Error: `thumb` must have the same dimensions as the direct image! ({0:d},{1:d})
""".format(self.sh[0], self.sh[1]))
return False
# Now compute the dispersed spectrum using the C helper
if apply_sensitivity:
sens_curve = self.sensitivity_beam
else:
sens_curve = 1.
nonz = (sens_curve*scale_spec) != 0
if (nonz.sum() > 0) & (id in self.seg_ids):
status = disperse.disperse_grism_object(thumb, self.seg,
np.float32(id),
self.flat_index[nonz],
self.yfrac_beam[nonz].astype(np.float64),
(sens_curve*scale_spec)[nonz].astype(np.float64),
modelf,
self.x0,
np.array(self.sh, dtype=np.int64),
self.x0,
np.array(self.sh_beam, dtype=np.int64))
#print('yyy PAM')
modelf /= self.PAM_value # = self.get_PAM_value()
if not in_place:
return modelf
else:
self.model = modelf.reshape(self.sh_beam)
return True
def init_optimal_profile(self, seg_ids=None):
"""Initilize optimal extraction profile
"""
if seg_ids is None:
ids = [self.id]
else:
ids = seg_ids
for i, id in enumerate(ids):
if hasattr(self, 'psf_params'):
m_i = self.compute_model_psf(id=id, in_place=False)
else:
m_i = self.compute_model(id=id, in_place=False)
#print('Add {0} to optimal profile'.format(id))
if i == 0:
m = m_i
else:
m += m_i
m = m.reshape(self.sh_beam)
m[m < 0] = 0
self.optimal_profile = m/m.sum(axis=0)
def optimal_extract(self, data, bin=0, ivar=1., weight=1.):
"""`Horne (1986) <http://adsabs.harvard.edu/abs/1986PASP...98..609H>`_ optimally-weighted 1D extraction
Parameters
----------
data : `~numpy.ndarray` with shape `self.sh_beam`
2D data to extract
bin : int, optional
Simple boxcar averaging of the output 1D spectrum
ivar : float or `~numpy.ndarray` with shape `self.sh_beam`
Inverse variance array or scalar float that multiplies the
optimal weights
weight : TBD
Returns
-------
wave, opt_flux, opt_rms : `~numpy.array`
`wave` is the wavelength of 1D array
`opt_flux` is the optimally-weighted 1D extraction
`opt_rms` is the weighted uncertainty of the 1D extraction
All are optionally binned in wavelength if `bin` > 1.
"""
import scipy.ndimage as nd
if not hasattr(self, 'optimal_profile'):
self.init_optimal_profile()
if data.shape != self.sh_beam:
print("""
`data` ({0},{1}) must have the same shape as the data array ({2},{3})
""".format(data.shape[0], data.shape[1], self.sh_beam[0],
self.sh_beam[1]))
return False
if not isinstance(ivar, float):
if ivar.shape != self.sh_beam:
print("""
`ivar` ({0},{1}) must have the same shape as the data array ({2},{3})
""".format(ivar.shape[0], ivar.shape[1], self.sh_beam[0],
self.sh_beam[1]))
return False
num = self.optimal_profile*data*ivar*weight
den = self.optimal_profile**2*ivar*weight
opt_flux = num.sum(axis=0)/den.sum(axis=0)
opt_var = 1./den.sum(axis=0)
if bin > 1:
kern = np.ones(bin, dtype=float)/bin
opt_flux = nd.convolve(opt_flux, kern)[bin // 2::bin]
opt_var = nd.convolve(opt_var, kern**2)[bin // 2::bin]
wave = self.lam[bin // 2::bin]
else:
wave = self.lam
opt_rms = np.sqrt(opt_var)
opt_rms[opt_var == 0] = 0
return wave, opt_flux, opt_rms
def trace_extract(self, data, r=0, bin=0, ivar=1., dy0=0):
"""Aperture extraction along the trace
Parameters
----------
data : array-like
Data array with dimenions equivalent to those of `self.model`
r : int
Radius of of the aperture to extract, in pixels. The extraction
will be performed from `-r` to `+r` pixels below and above the
central pixel of the trace.
bin : int, optional
Simple boxcar averaging of the output 1D spectrum
ivar : float or `~numpy.ndarray` with shape `self.sh_beam`
Inverse variance array or scalar float that multiplies the
optimal weights
dy0 : float
Central pixel to extract, relative to the central pixel of
the trace
Returns
-------
wave, opt_flux, opt_rms : `~numpy.array`
`wave` is the wavelength of 1D array
`opt_flux` is the 1D aperture extraction
`opt_rms` is the uncertainty of the 1D extraction, derived from
the sum of the pixel variances within the aperture
All are optionally binned in wavelength if `bin` > 1.
"""
dy = np.cast[int](np.round(self.ytrace+dy0))
aper = np.zeros_like(self.model)
y0 = self.sh_beam[0] // 2
for d in range(-r, r+1):
for i in range(self.sh_beam[1]):
aper[y0+d+dy[i]-1, i] = 1
var = 1./ivar
if not np.isscalar(ivar):
var[ivar == 0] = 0
opt_flux = np.sum(data*aper, axis=0)
opt_var = np.sum(var*aper, axis=0)
if bin > 1:
kern = np.ones(bin, dtype=float)/bin
opt_flux = nd.convolve(opt_flux, kern)[bin // 2::bin]
opt_var = nd.convolve(opt_var, kern**2)[bin // 2::bin]
wave = self.lam[bin // 2::bin]
else:
wave = self.lam
opt_rms = np.sqrt(opt_var)
return wave, opt_flux, opt_rms
def contained_in_full_array(self, full_array):
"""Check if subimage slice is fully contained within larger array
"""
sh = full_array.shape
if (self.sly_parent.start < 0) | (self.slx_parent.start < 0):
return False
if (self.sly_parent.stop >= sh[0]) | (self.slx_parent.stop >= sh[1]):
return False
return True
def add_to_full_image(self, data, full_array):
"""Add spectrum cutout back to the full array
`data` is *added* to `full_array` in place, so, for example, to
subtract `self.model` from the full array, call the function with
>>> self.add_to_full_image(-self.model, full_array)
Parameters
----------
data : `~numpy.ndarray` shape `self.sh_beam` (e.g., `self.model`)
Spectrum cutout
full_array : `~numpy.ndarray`
Full detector array, where the lower left pixel of `data` is given
by `origin`.
"""
if self.contained_in_full_array(full_array):
full_array[self.sly_parent, self.slx_parent] += data
else:
sh = full_array.shape
xpix = np.arange(self.sh_beam[1])
xpix += self.origin[1] + self.dxfull[0] + self.x0[1]
ypix = np.arange(self.sh_beam[0])
ypix += self.origin[0]
okx = (xpix >= 0) & (xpix < sh[1])
oky = (ypix >= 0) & (ypix < sh[1])
if (okx.sum() == 0) | (oky.sum() == 0):
return False
sly = slice(ypix[oky].min(), ypix[oky].max()+1)
slx = slice(xpix[okx].min(), xpix[okx].max()+1)
full_array[sly, slx] += data[oky, :][:, okx]
# print sly, self.sly_parent, slx, self.slx_parent
return True
def cutout_from_full_image(self, full_array):
"""Get beam-sized cutout from a full image
Parameters
----------
full_array : `~numpy.ndarray`
Array of the size of the parent array from which the cutout was
extracted. If possible, the function first tries the slices with
>>> sub = full_array[self.sly_parent, self.slx_parent]
and then computes smaller slices for cases where the beam spectrum
falls off the edge of the parent array.
Returns
-------
cutout : `~numpy.ndarray`
Array with dimensions of `self.model`.
"""
# print self.sly_parent, self.slx_parent, full_array.shape
if self.contained_in_full_array(full_array):
data = full_array[self.sly_parent, self.slx_parent]
else:
sh = full_array.shape
###
xpix = np.arange(self.sh_beam[1])
xpix += self.origin[1] + self.dxfull[0] + self.x0[1]
ypix = np.arange(self.sh_beam[0])
ypix += self.origin[0]
okx = (xpix >= 0) & (xpix < sh[1])
oky = (ypix >= 0) & (ypix < sh[1])
if (okx.sum() == 0) | (oky.sum() == 0):
return False
sly = slice(ypix[oky].min(), ypix[oky].max()+1)
slx = slice(xpix[okx].min(), xpix[okx].max()+1)
data = self.model*0.
data[oky, :][:, okx] += full_array[sly, slx]
return data
def twod_axis_labels(self, wscale=1.e4, limits=None, mpl_axis=None):
"""Set 2D wavelength (x) axis labels based on spectral parameters
Parameters
----------
wscale : float
Scale factor to divide from the wavelength units. The default
value of 1.e4 results in wavelength ticks in microns.
limits : None, list = `[x0, x1, dx]`
Will automatically use the whole wavelength range defined by the
spectrum. To change, specify `limits = [x0, x1, dx]` to
interpolate `self.beam.lam_beam` between x0*wscale and x1*wscale.
mpl_axis : `matplotlib.axes._axes.Axes`
Plotting axis to place the labels, e.g.,
>>> fig = plt.figure()
>>> mpl_axis = fig.add_subplot(111)
Returns
-------
Nothing if `mpl_axis` is supplied, else pixels and wavelengths of the
tick marks.
"""
xarr = np.arange(len(self.lam))
if limits:
xlam = np.arange(limits[0], limits[1], limits[2])
xpix = np.interp(xlam, self.lam/wscale, xarr)
else:
xlam = np.unique(np.cast[int](self.lam / 1.e4*10)/10.)
xpix = np.interp(xlam, self.lam/wscale, xarr)
if mpl_axis is None:
return xpix, xlam
else:
mpl_axis.set_xticks(xpix)
mpl_axis.set_xticklabels(xlam)
def twod_xlim(self, x0, x1=None, wscale=1.e4, mpl_axis=None):
"""Set wavelength (x) axis limits on a 2D spectrum
Parameters
----------
x0 : float or list/tuple of floats
minimum or (min,max) of the plot limits
x1 : float or None
max of the plot limits if x0 is a float
wscale : float
Scale factor to divide from the wavelength units. The default
value of 1.e4 results in wavelength ticks in microns.
mpl_axis : `matplotlib.axes._axes.Axes`
Plotting axis to place the labels.
Returns
-------
Nothing if `mpl_axis` is supplied else pixels the desired wavelength
limits.
"""
if isinstance(x0, list) | isinstance(x0, tuple):
x0, x1 = x0[0], x0[1]
xarr = np.arange(len(self.lam))
xpix = np.interp([x0, x1], self.lam/wscale, xarr)
if mpl_axis:
mpl_axis.set_xlim(xpix)
else:
return xpix
def x_init_epsf(self, flat_sensitivity=False, psf_params=None, psf_filter='F140W', yoff=0.0, skip=0.5, get_extended=False, seg_mask=True):
"""Initialize ePSF fitting for point sources
TBD
"""
import scipy.sparse
import scipy.ndimage
#print('SKIP: {0}'.format(skip))
EPSF = utils.EffectivePSF()
if psf_params is None:
self.psf_params = [self.total_flux, 0., 0.]
else:
self.psf_params = psf_params
if self.psf_params[0] is None:
self.psf_params[0] = self.total_flux # /photflam_list[psf_filter]
origin = np.array(self.origin) - np.array(self.pad)
self.psf_yoff = yoff
self.psf_filter = psf_filter
self.psf = EPSF.get_ePSF(self.psf_params, sci=self.psf_sci,
ivar=self.psf_ivar, origin=origin,
shape=self.sh, filter=psf_filter,