-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathreduce.py
More file actions
1861 lines (1621 loc) · 87.3 KB
/
reduce.py
File metadata and controls
1861 lines (1621 loc) · 87.3 KB
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
# TODO THIS IS NOT USED ANYMORE, SHOULD WE MOVE IT TO DEPRECATED?
"""
Main driver class for skysubtraction and extraction
.. include common links, assuming primary doc root is up one directory
.. include:: ../include/links.rst
"""
import inspect
import numpy as np
import os
from astropy import stats
from abc import ABCMeta
from linetools import utils as ltu
from scipy import interpolate
from scipy.optimize import least_squares
from pypeit import specobjs
from pypeit import msgs, utils
from pypeit import masterframe, flatfield
from pypeit.display import display
from pypeit.core import skysub, extract, pixels, wave, flexure, flat, procimg, qa, parse
from pypeit.images import buildimage
from pypeit.core.moment import moment1d
from linetools.spectra import xspectrum1d
from IPython import embed
class Reduce:
"""
This class will organize and run actions related to
finding objects, sky subtraction, and extraction for
a Science or Standard star exposure
Args:
sciImg (:class:`~pypeit.images.pypeitimage.PypeItImage`):
Image to reduce.
spectrograph (:class:`~pypeit.spectrographs.spectrograph.Spectrograph`):
par (:class:`~pypeit.par.pypeitpar.PypeItPar`):
caliBrate (:class:`~pypeit.calibrations.Calibrations`):
objtype (:obj:`str`):
Specifies object being reduced 'science' 'standard' 'science_coadd2d'
det (:obj:`int`, optional):
Detector index
setup (:obj:`str`, optional):
Used for naming
maskslits (`numpy.ndarray`_, optional):
Specifies masked out slits
True = Masked
bkg_redux (:obj:`bool`, optional):
If True, the sciImg has been subtracted by
a background image (e.g. standard treatment in the IR)
show (:obj:`bool`, optional):
Show plots along the way?
manual (:class:`~pypeit.manual_extract.ManualExtractObj`, optional):
Attributes:
ivarmodel (`numpy.ndarray`_):
Model of inverse variance
objimage (`numpy.ndarray`_):
Model of object
skyimage (`numpy.ndarray`_):
Final model of sky
initial_sky (`numpy.ndarray`_):
Initial sky model after first pass with global_skysub()
global_sky (`numpy.ndarray`_):
Fit to global sky
skymask (`numpy.ndarray`_):
Mask of the sky fit
outmask (`numpy.ndarray`_):
Final output mask
extractmask (`numpy.ndarray`_):
Extraction mask
slits (:class:`pypeit.slittrace.SlitTraceSet`):
sobjs_obj (:class:`pypeit.specobjs.SpecObjs`):
Only object finding but no extraction
sobjs (:class:`pypeit.specobjs.SpecObjs`):
Final extracted object list with trace corrections applied
spat_flexure_shift (float):
tilts (`numpy.ndarray`_):
WaveTilts images generated on-the-spot
waveimg (`numpy.ndarray`_):
WaveImage image generated on-the-spot
slitshift (`numpy.ndarray`_):
Global spectral flexure correction for each slit (in pixels)
vel_corr (float):
Relativistic reference frame velocity correction (e.g. heliocentyric/barycentric/topocentric)
"""
__metaclass__ = ABCMeta
# Superclass factory method generates the subclass instance
@classmethod
def get_instance(cls, sciImg, spectrograph, par, caliBrate,
objtype, bkg_redux=False, find_negative=False, det=1, std_redux=False, show=False,
binning=None, setup=None, basename=None, manual=None):
"""
Instantiate the Reduce subclass appropriate for the provided
spectrograph.
The class must be subclassed from Reduce. See :class:`Reduce` for
the description of the valid keyword arguments.
Args:
sciImg (pypeit.images.scienceimage.ScienceImage):
spectrograph (:class:`pypeit.spectrographs.spectrograph.Spectrograph`):
par (pypeit.par.pyepeitpar.PypeItPar):
caliBrate (:class:`pypeit.calibrations.Calibrations`):
basename (str, optional):
Output filename used for spectral flexure QA
**kwargs
Passed to Parent init
Returns:
:class:`pypeit.reduce.Reduce`:
"""
return next(c for c in utils.all_subclasses(Reduce)
if c.__name__ == (spectrograph.pypeline + 'Reduce'))(
sciImg, spectrograph, par, caliBrate, objtype, bkg_redux=bkg_redux,
find_negative=find_negative, det=det, std_redux=std_redux, show=show,
binning=binning, setup=setup, basename=basename,
manual=manual)
def __init__(self, sciImg, spectrograph, par, caliBrate,
objtype, bkg_redux=False, find_negative=False, det=1, std_redux=False, show=False,
binning=None, setup=None, basename=None, manual=None):
# Setup the parameters sets for this object. NOTE: This uses objtype, not frametype!
# Instantiation attributes for this object
self.sciImg = sciImg
self.spectrograph = spectrograph
self.objtype = objtype
self.par = par
self.caliBrate = caliBrate
self.scaleimg = np.array([1.0], dtype=np.float) # np.array([1]) applies no scale
self.basename = basename
self.manual = manual
# Parse
# Slit pieces
# WARNING -- It is best to unpack here then pass around self.slits
# Otherwise you have to keep in mind flexure, tweaking, etc.
# TODO: The spatial flexure is not copied to the PypeItImage object if
# the image (science or otherwise) is from a combination of multiple
# frames. Is that okay for this usage?
# Flexure
self.spat_flexure_shift = None
if objtype == 'science':
if self.par['scienceframe']['process']['spat_flexure_correct']:
self.spat_flexure_shift = self.sciImg.spat_flexure
elif objtype == 'standard':
if self.par['calibrations']['standardframe']['process']['spat_flexure_correct']:
self.spat_flexure_shift = self.sciImg.spat_flexure
elif objtype == 'science_coadd2d':
self.spat_flexure_shift = None
else:
msgs.error("Not ready for this objtype in Reduce")
# Initialise the slits
msgs.info("Initialising slits")
self.initialise_slits()
# Internal bpm mask
# We want to keep the 'BOXSLIT', which has bpm=2. But we don't want to keep 'BOXSLIT'
# with other bad flag (for which bpm>2)
self.reduce_bpm = (self.slits.mask > 2) & (np.invert(self.slits.bitmask.flagged(
self.slits.mask, flag=self.slits.bitmask.exclude_for_reducing)))
self.reduce_bpm_init = self.reduce_bpm.copy()
# These may be None (i.e. COADD2D)
self.waveTilts = caliBrate.wavetilts
self.wv_calib = caliBrate.wv_calib
# Load up other input items
self.bkg_redux = bkg_redux
self.find_negative = find_negative
self.std_redux = std_redux
self.det = det
self.binning = binning
self.setup = setup
self.pypeline = spectrograph.pypeline
self.reduce_show = show
self.steps = []
# Key outputs images for extraction
self.ivarmodel = None
self.objimage = None
self.skyimage = None
self.initial_sky = None
self.global_sky = None
self.skymask = None
self.outmask = None
self.extractmask = None
# SpecObjs object
self.sobjs_obj = None # Only object finding but no extraction
self.sobjs = None # Final extracted object list with trace corrections applied
self.slitshift = np.zeros(self.slits.nslits) # Global spectral flexure slit shifts (in pixels) that are applied to all slits.
self.vel_corr = None
def initialise_slits(self, initial=False):
"""
Initialise the slits
Args:
initial (:obj:`bool`, optional):
Use the initial definition of the slits. If False,
tweaked slits are used.
"""
# Slits
self.slits = self.caliBrate.slits
# Select the edges to use
self.slits_left, self.slits_right, _ \
= self.slits.select_edges(initial=initial, spat_flexure=self.spat_flexure_shift)
# Slitmask
self.slitmask = self.slits.slit_img(initial=initial, spat_flexure=self.spat_flexure_shift,
exclude_flag=self.slits.bitmask.exclude_for_reducing+['BOXSLIT'])
# Now add the slitmask to the mask (i.e. post CR rejection in proc)
# NOTE: this uses the par defined by EdgeTraceSet; this will
# use the tweaked traces if they exist
self.sciImg.update_mask_slitmask(self.slitmask)
# # For echelle
# self.spatial_coo = self.slits.spatial_coordinates(initial=initial, flexure=self.spat_flexure_shift)
def extract(self, global_sky, sobjs_obj):
"""
Main method to extract spectra from the ScienceImage
Args:
global_sky (`numpy.ndarray`_):
Sky estimate
sobjs_obj (:class:`pypeit.specobjs.SpecObjs`):
List of SpecObj that have been found and traced
"""
# This holds the objects, pre-extraction
self.sobjs_obj = sobjs_obj
if self.par['reduce']['extraction']['skip_optimal']: # Boxcar only with global sky subtraction
msgs.info("Skipping optimal extraction")
# This will hold the extracted objects
self.sobjs = self.sobjs_obj.copy()
# Purge out the negative objects if this was a near-IR reduction unless negative objects are requested
# Quick loop over the objects
for iobj in range(self.sobjs.nobj):
sobj = self.sobjs[iobj]
bin_spec, bin_spat = parse.parse_binning(self.binning)
plate_scale = self.get_platescale(sobj)*bin_spat
# True = Good, False = Bad for inmask
thismask = self.slitmask == sobj.SLITID # pixels for this slit
inmask = self.sciImg.select_flag(invert=True) & thismask
# Do it
if sobj.MASKDEF_EXTRACT is True:
box_rad = self.par['reduce']['slitmask']['missing_objs_boxcar_rad'] / plate_scale
else:
box_rad = self.par['reduce']['extraction']['boxcar_radius']/plate_scale
extract.extract_boxcar(self.sciImg.image, self.sciImg.ivar, inmask, self.waveimg,
global_sky, box_rad, sobj, base_var=self.sciImg.base_var,
count_scale=self.sciImg.img_scale,
noise_floor=self.sciImg.noise_floor)
# Fill up extra bits and pieces
self.objmodel = np.zeros_like(self.sciImg.image)
self.ivarmodel = np.copy(self.sciImg.ivar)
# NOTE: fullmask is a bit mask, make sure it's treated as such, not
# a boolean (e.g., bad pixel) mask.
self.outmask = self.sciImg.fullmask
self.skymodel = global_sky.copy()
else: # Local sky subtraction and optimal extraction.
self.skymodel, self.objmodel, self.ivarmodel, self.outmask, self.sobjs = \
self.local_skysub_extract(global_sky, self.sobjs_obj,
model_noise=(not self.bkg_redux),
show_profile=self.reduce_show,
show=self.reduce_show)
# Return
return self.skymodel, self.objmodel, self.ivarmodel, self.outmask, self.sobjs
def get_platescale(self, sobj):
"""
Return the platescale for the current detector/echelle order
Over-loaded by the children
Args:
sobj (:class:`pypeit.specobj.SpecObj`):
Returns:
float:
"""
pass
def run_objfind(self, std_trace=None, show_peaks=False):
"""
Primary code flow for object finding in PypeIt reductions
*NOT* used by COADD2D
Parameters
----------
std_trace : `numpy.ndarray`_, optional
Trace of the standard star
show_peaks : :obj:`bool`, optional
Show peaks in find_objects methods
Returns
-------
global_sky : `numpy.ndarray`_
Initial global sky model
sobjs_obj : :class:`~pypeit.specobjs.SpecObjs`
List of objects found
skymask : `numpy.ndarray`_
Boolean mask
"""
# Deal with dynamic calibrations
# Tilts
self.waveTilts.is_synced(self.slits)
# Deal with Flexure
if self.par['calibrations']['tiltframe']['process']['spat_flexure_correct']:
_spat_flexure = 0. if self.spat_flexure_shift is None else self.spat_flexure_shift
# If they both shifted the same, there will be no reason to shift the tilts
tilt_flexure_shift = _spat_flexure - self.waveTilts.spat_flexure
else:
tilt_flexure_shift = self.spat_flexure_shift
msgs.info("Generating tilts image")
self.tilts = self.waveTilts.fit2tiltimg(self.slitmask, spat_flexure=tilt_flexure_shift)
#
# First pass object finding
self.sobjs_obj, self.nobj, skymask_init = \
self.find_objects(self.sciImg.image, std_trace=std_trace,
show_peaks=show_peaks,
show=self.reduce_show & (not self.std_redux),
save_objfindQA=self.par['reduce']['findobj']['skip_second_find'] | self.std_redux)
# Check if the user wants to overwrite the skymask with a pre-defined sky regions file. IFU only
skymask_init, usersky = self.load_skyregions(skymask_init)
# Global sky subtract (self.global_sky is also generated here)
self.initial_sky = self.global_skysub(skymask=skymask_init).copy()
# Second pass object finding on sky-subtracted image
if (not self.std_redux) and (not self.par['reduce']['findobj']['skip_second_find']):
self.sobjs_obj, self.nobj, self.skymask = \
self.find_objects(self.sciImg.image - self.initial_sky,
std_trace=std_trace,
show=self.reduce_show,
show_peaks=show_peaks)
else:
msgs.info("Skipping 2nd run of finding objects")
self.skymask = skymask_init
return self.global_sky, self.sobjs_obj, self.skymask
def prepare_extraction(self, global_sky):
""" Prepare the masks and wavelength image for extraction.
"""
# Update bpm mask to remove `BOXSLIT`, i.e., we don't want to extract those
self.reduce_bpm = (self.slits.mask > 0) & \
(np.invert(self.slits.bitmask.flagged(self.slits.mask,
flag=self.slits.bitmask.exclude_for_reducing)))
# Update Slitmask to remove `BOXSLIT`, i.e., we don't want to extract those
self.slitmask = self.slits.slit_img(spat_flexure=self.spat_flexure_shift,
exclude_flag=self.slits.bitmask.exclude_for_reducing)
# use the tweaked traces if they exist - DP: I'm not sure this is necessary
self.sciImg.update_mask_slitmask(self.slitmask)
# Deal with dynamic calibrations
# Tilts
self.waveTilts.is_synced(self.slits)
# Deal with Flexure
if self.par['calibrations']['tiltframe']['process']['spat_flexure_correct']:
_spat_flexure = 0. if self.spat_flexure_shift is None else self.spat_flexure_shift
# If they both shifted the same, there will be no reason to shift the tilts
tilt_flexure_shift = _spat_flexure - self.waveTilts.spat_flexure
else:
tilt_flexure_shift = self.spat_flexure_shift
msgs.info("Generating tilts image")
self.tilts = self.waveTilts.fit2tiltimg(self.slitmask, spat_flexure=tilt_flexure_shift)
# Wavelengths (on unmasked slits)
msgs.info("Generating wavelength image")
self.waveimg = self.wv_calib.build_waveimg(self.tilts, self.slits, spat_flexure=self.spat_flexure_shift)
# Set the initial and global sky
self.initial_sky = global_sky.copy()
self.global_sky = global_sky
def run_extraction(self, global_sky, sobjs_obj, skymask, ra=None, dec=None, obstime=None, return_negative=False):
"""
Primary code flow for PypeIt reductions
*NOT* used by COADD2D
Args:
global_sky (`numpy.ndarray`_):
Initial global sky model
sobjs_obj (:class:`pypeit.specobjs.SpecObjs`):
List of objects found during `run_objfind`
skymask (`numpy.ndarray`_):
Boolean image indicating which pixels are useful for global sky subtraction
ra (float, optional):
Required if helio-centric correction is to be applied
dec (float, optional):
Required if helio-centric correction is to be applied
obstime (:obj:`astropy.time.Time`, optional):
Required if helio-centric correction is to be applied
Returns:
tuple: skymodel (ndarray), objmodel (ndarray), ivarmodel (ndarray),
outmask (ndarray), sobjs (SpecObjs), waveimg (`numpy.ndarray`_),
tilts (`numpy.ndarray`_).
See main doc string for description
"""
# Start by preparing some masks and the wavelength image, ready for extraction
# TODO this should return things to make the control flow less opqaque.
self.prepare_extraction(global_sky)
# Check if the user wants to overwrite the skymask with a pre-defined sky regions file
skymask, usersky = self.load_skyregions(skymask)
# remove objects found in `BOXSLIT` (we don't want to extract those)
remove_idx = []
for i, sobj in enumerate(sobjs_obj):
if sobj.SLITID in list(self.slits.spat_id[self.reduce_bpm]):
remove_idx.append(i)
# remove
sobjs_obj.remove_sobj(remove_idx)
# # Create skymask for maskdef_extracted objects
if self.par['reduce']['slitmask']['extract_missing_objs']:
gdslits = np.where(np.invert(self.reduce_bpm))[0]
bin_spec, bin_spat = parse.parse_binning(self.binning)
# Loop on slits
for slit_idx in gdslits:
slit_spat = self.slits.spat_id[slit_idx]
slit_objs = sobjs_obj[sobjs_obj.SLITID == slit_spat]
thismask = self.slitmask == slit_spat
# sobj index of maskdef_extract
maskdef_extract = np.where(slit_objs.MASKDEF_EXTRACT == True)[0] if slit_objs.nobj > 0 else np.array([])
if maskdef_extract.size > 0:
plate_scale = self.get_platescale(slit_objs[maskdef_extract][0])*bin_spat
skymask_fwhm = extract.create_skymask_fwhm(slit_objs[maskdef_extract], skymask,
box_rad_pix=self.par['reduce']['extraction']['boxcar_radius']/plate_scale \
if self.par['reduce']['skysub']['mask_by_boxcar'] else None)
skymask[thismask] = skymask_fwhm[thismask]
self.sobjs_obj = sobjs_obj
self.skymask = skymask
self.nobj = len(sobjs_obj)
# Do we have any positive objects to proceed with?
if self.nobj > 0:
# Global sky subtraction second pass. Uses skymask from 2nd object finding and maskdef_extracted objects
if ((not self.std_redux) and (not self.par['reduce']['findobj']['skip_second_find']) and (not usersky)) \
or (self.par['reduce']['slitmask']['extract_missing_objs']):
self.global_sky = self.global_skysub(skymask=skymask, show=self.reduce_show,
previous_sky=self.initial_sky)
# Apply a global flexure correction to each slit
# provided it's not a standard star
if self.par['flexure']['spec_method'] != 'skip' and not self.std_redux:
self.spec_flexure_correct(mode='global')
# Extract + Return
self.skymodel, self.objmodel, self.ivarmodel, self.outmask, self.sobjs \
= self.extract(self.global_sky, self.sobjs_obj)
if self.find_negative:
self.sobjs.make_neg_pos() if return_negative else self.sobjs.purge_neg()
else: # No objects, pass back what we have
# Apply a global flexure correction to each slit
# provided it's not a standard star
if self.par['flexure']['spec_method'] != 'skip' and not self.std_redux:
self.spec_flexure_correct(mode='global')
#Could have negative objects but no positive objects so purge them
if self.find_negative:
self.sobjs_obj.make_neg_pos() if return_negative else self.sobjs_obj.purge_neg()
self.skymodel = self.initial_sky
self.objmodel = np.zeros_like(self.sciImg.image)
# Set to sciivar. Could create a model but what is the point?
self.ivarmodel = np.copy(self.sciImg.ivar)
# Set to the initial mask in case no objects were found
# NOTE: fullmask is a bit mask, make sure it's treated as such, not
# a boolean (e.g., bad pixel) mask.
self.outmask = self.sciImg.fullmask
# empty specobjs object from object finding
self.sobjs = self.sobjs_obj
# If a global spectral flexure has been applied to all slits, store this correction as metadata in each specobj
if self.par['flexure']['spec_method'] != 'skip' and not self.std_redux:
for iobj in range(self.sobjs.nobj):
islit = self.slits.spatid_to_zero(self.sobjs[iobj].SLITID)
self.sobjs[iobj].update_flex_shift(self.slitshift[islit], flex_type='global')
# Correct for local spectral flexure
if self.sobjs.nobj == 0:
msgs.warn('No objects to extract!')
elif self.par['flexure']['spec_method'] not in ['skip', 'slitcen'] and not self.std_redux:
# Apply a refined estimate of the flexure to objects, and then apply reference frame correction to objects
self.spec_flexure_correct(mode='local', sobjs=self.sobjs)
# Apply a reference frame correction to each object and the waveimg
self.refframe_correct(ra, dec, obstime, sobjs=self.sobjs)
# Update the mask
reduce_masked = np.where(np.invert(self.reduce_bpm_init) & self.reduce_bpm & (self.slits.mask > 2))[0]
if len(reduce_masked) > 0:
self.slits.mask[reduce_masked] = self.slits.bitmask.turn_on(
self.slits.mask[reduce_masked], 'BADREDUCE')
# Return
return self.skymodel, self.objmodel, self.ivarmodel, self.outmask, self.sobjs, \
self.scaleimg, self.waveimg, self.tilts
def find_objects(self, image, std_trace=None,
show_peaks=False, show_fits=False,
show_trace=False, show=False, save_objfindQA=True,
manual_extract_dict=None, debug=False):
"""
Single pass at finding objects in the input image
If self.find_negative is True, do a search for negative objects too
Parameters
----------
image : `numpy.ndarray`_
Input image
std_trace : `numpy.ndarray`_, optional
???
show_peaks : :obj:`bool`, optional
???
show_fits : :obj:`bool`, optional
???
show_trace : :obj:`bool`, optional
???
show : :obj:`bool`, optional
???
save_objfindQA : :obj:`bool`, optional
Save to disk (png file) QA showing the object profile
manual_extract_dict : :obj:`dict`, optional
This is only used by 2D coadd
debug : :obj:`bool`, optional
???
Returns
-------
sobjs_obj_single : :class:`~pypeit.specobjs.SpecObjs`
Objects found
nobj_single : :obj:`int`
Number of objects found
skymask : `numpy.ndarray`_
Boolean sky mask
"""
# Positive image
if manual_extract_dict is None:
manual_extract_dict= self.manual.dict_for_objfind(self.det, neg=False) if self.manual is not None else None
#parse_manual = self.parse_manual_dict(manual_extract_dict, neg=False)
sobjs_obj_single, nobj_single, skymask_pos = \
self.find_objects_pypeline(image,
std_trace=std_trace,
show_peaks=show_peaks, show_fits=show_fits,
show_trace=show_trace, save_objfindQA=save_objfindQA,
manual_extract_dict=manual_extract_dict, neg=False, debug=debug)
# For nobj we take only the positive objects
if self.find_negative:
msgs.info("Finding objects in the negative image")
# Parses
manual_extract_dict = self.manual.dict_for_objfind(self.det, neg=True) if self.manual is not None else None
sobjs_obj_single_neg, nobj_single_neg, skymask_neg = \
self.find_objects_pypeline(-image, std_trace=std_trace,
show_peaks=show_peaks, show_fits=show_fits,
show_trace=show_trace, save_objfindQA=save_objfindQA,
manual_extract_dict=manual_extract_dict, neg=True,
debug=debug)
# Mask
skymask = skymask_pos & skymask_neg
# Add (if there are any)
sobjs_obj_single.append_neg(sobjs_obj_single_neg)
else:
skymask = skymask_pos
if show:
gpm = self.sciImg.select_flag(invert=True)
self.show('image', image=image*gpm.astype(float), chname='objfind',
sobjs=sobjs_obj_single, slits=True)
# For nobj we take only the positive objects
return sobjs_obj_single, nobj_single, skymask
def find_objects_pypeline(self, image, std_trace=None,
show_peaks=False, show_fits=False, show_trace=False,
show=False, save_objfindQA=False, neg=False, debug=False,
manual_extract_dict=None):
"""
Dummy method for object finding. Overloaded by class specific object finding.
Returns:
"""
return None, None, None
def global_skysub(self, skymask=None, update_crmask=True, trim_edg=(3,3),
previous_sky=None,
show_fit=False, show=False, show_objs=False):
"""
Perform global sky subtraction, slit by slit
Wrapper to skysub.global_skysub
Args:
skymask (`numpy.ndarray`_, None):
A 2D image indicating sky regions (1=sky)
update_crmask (bool, optional):
show_fit (bool, optional):
show (bool, optional):
show_objs (bool, optional):
previous_sky (`numpy.ndarray`_, optional):
Sky model estimate from a previous run of global_sky
Used to generate an improved estimated of the variance
Returns:
`numpy.ndarray`_: image of the the global sky model
"""
# Prep
self.global_sky = np.zeros_like(self.sciImg.image)
# Parameters for a standard star
if self.std_redux:
sigrej = 7.0
update_crmask = False
if not self.par['reduce']['skysub']['global_sky_std']:
msgs.info('Skipping global sky-subtraction for standard star.')
return self.global_sky
else:
sigrej = 3.0
# We use this tmp bpm so that we exclude the BOXSLITS during the global_skysub
tmp_bpm = (self.slits.mask > 0) & \
(np.invert(self.slits.bitmask.flagged(self.slits.mask,
flag=self.slits.bitmask.exclude_for_reducing)))
gdslits = np.where(np.invert(tmp_bpm))[0]
# Mask objects using the skymask? If skymask has been set by objfinding, and masking is requested, then do so
skymask_now = skymask if (skymask is not None) else np.ones_like(self.sciImg.image, dtype=bool)
# Allow for previous sky to better estimate ivar
# Unless we used a background image (i.e. bkg_redux=True)
if (previous_sky is not None) and (not self.bkg_redux):
# Estimate the variance using the input sky model
var = procimg.variance_model(self.sciImg.base_var,
counts=previous_sky,
count_scale=self.sciImg.img_scale,
noise_floor=self.sciImg.noise_floor)
self.sciImg.ivar = utils.inverse(var)
# Loop on slits
for slit_idx in gdslits:
slit_spat = self.slits.spat_id[slit_idx]
msgs.info("Global sky subtraction for slit: {:d}".format(slit_spat))
thismask = self.slitmask == slit_spat
inmask = self.sciImg.select_flag(invert=True) & thismask & skymask_now
# All masked?
if not np.any(inmask):
msgs.warn("No pixels for fitting sky. If you are using mask_by_boxcar=True, your radius may be too large.")
self.reduce_bpm[slit_idx] = True
continue
# Find sky
self.global_sky[thismask] = skysub.global_skysub(
self.sciImg.image, self.sciImg.ivar, self.tilts, thismask,
self.slits_left[:,slit_idx], self.slits_right[:,slit_idx],
inmask=inmask, sigrej=sigrej,
bsp=self.par['reduce']['skysub']['bspline_spacing'],
no_poly=self.par['reduce']['skysub']['no_poly'],
pos_mask=(not self.bkg_redux), show_fit=show_fit)
# Mask if something went wrong
if np.sum(self.global_sky[thismask]) == 0.:
msgs.warn("Bad fit to sky. Rejecting slit: {:d}".format(slit_idx))
self.reduce_bpm[slit_idx] = True
if update_crmask and self.par['scienceframe']['process']['mask_cr']:
# Find CRs with sky subtraction
# TODO: Shouldn't the saturation flagging account for the
# subtraction of the sky?
self.sciImg.build_crmask(self.par['scienceframe']['process'],
subtract_img=self.global_sky)
# Update the fullmask
self.sciImg.update_mask_cr(self.sciImg.crmask)
# Step
self.steps.append(inspect.stack()[0][3])
if show:
sobjs_show = None if show_objs else self.sobjs_obj
# Global skysub is the first step in a new extraction so clear the channels here
self.show('global', slits=True, sobjs=sobjs_show, clear=False)
# Return
return self.global_sky
def local_skysub_extract(self, global_sky, sobjs, model_noise=True, spat_pix=None,
show_profile=False, show_resids=False, show=False):
"""
Dummy method for local sky-subtraction and extraction.
Overloaded by class specific skysub and extraction.
"""
return None, None, None, None, None
# TODO This method only used for IFUs, so it should be present in the IFU subclass not here.
def load_skyregions(self, skymask_init):
"""
Load or generate the sky regions
Parameters
----------
skymask_init : `numpy.ndarray`_
A boolean array of sky pixels (True is pixel is a sky region)
Returns
-------
skymask_init : `numpy.ndarray`_
A boolean array of sky pixels (True is pixel is a sky region)
usersky : bool
If the user has defined the sky, set this variable to True (otherwise False).
"""
usersky = False
if self.par['reduce']['skysub']['load_mask']:
# Check if a master Sky Regions file exists for this science frame
file_base = os.path.basename(self.sciImg.files[0])
prefix = os.path.splitext(file_base)
if prefix[1] == ".gz":
sciName = os.path.splitext(prefix[0])[0]
else:
sciName = prefix[0]
# Setup the master frame name
master_dir = self.caliBrate.master_dir
master_key = self.caliBrate.fitstbl.master_key(0, det=self.det) + "_" + sciName
regfile = masterframe.construct_file_name(buildimage.SkyRegions,
master_key=master_key,
master_dir=master_dir)
# Check if a file exists
if os.path.exists(regfile):
msgs.info("Loading SkyRegions file for: {0:s} --".format(sciName) + msgs.newline() + regfile)
skyreg = buildimage.SkyRegions.from_file(regfile)
skymask_init = skyreg.image.astype(np.bool)
usersky = True
else:
msgs.warn("SkyRegions file not found:" + msgs.newline() + regfile)
elif self.par['reduce']['skysub']['user_regions'] is not None:
if len(self.par['reduce']['skysub']['user_regions']) != 0:
skyregtxt = self.par['reduce']['skysub']['user_regions']
if type(skyregtxt) is list:
skyregtxt = ",".join(skyregtxt)
msgs.info("Generating skysub mask based on the user defined regions {0:s}".format(skyregtxt))
# The resolution probably doesn't need to be a user parameter
maxslitlength = np.max(self.slits_right-self.slits_left)
# Get the regions
status, regions = skysub.read_userregions(skyregtxt, self.slits.nslits, maxslitlength)
# Generate image
skymask_init = skysub.generate_mask(self.pypeline, regions, self.slits, self.slits_left, self.slits_right, spat_flexure=self.spat_flexure_shift)
usersky = True
return skymask_init, usersky
def spec_flexure_correct(self, mode="local", sobjs=None):
""" Correct for spectral flexure
Spectra are modified in place (wavelengths are shifted)
Args:
mode (str):
"local" - Use sobjs to determine flexure correction
"global" - Use waveimg and global_sky to determine flexure correction at the centre of the slit
sobjs (:class:`pypeit.specobjs.SpecObjs`, None):
Spectrally extracted objects
"""
if self.par['flexure']['spec_method'] == 'skip':
msgs.info('Skipping flexure correction.')
else:
# Perform some checks
if mode == "local" and sobjs is None:
msgs.error("No spectral extractions provided for flexure, using slit center instead")
elif mode not in ["local", "global"]:
msgs.error("mode must be 'global' or 'local'. Assuming 'global'.")
# Prepare a list of slit spectra, if required.
if mode == "global":
gd_slits = np.logical_not(self.reduce_bpm)
# TODO :: Need to think about spatial flexure - is the appropriate spatial flexure already included in trace_spat via left/right slits?
trace_spat = 0.5 * (self.slits_left + self.slits_right)
trace_spec = np.arange(self.slits.nspec)
slit_specs = []
for ss in range(self.slits.nslits):
if not gd_slits[ss]:
slit_specs.append(None)
continue
slit_spat = self.slits.spat_id[ss]
thismask = (self.slitmask == slit_spat)
box_denom = moment1d(self.waveimg * thismask > 0.0, trace_spat[:, ss], 2, row=trace_spec)[0]
wghts = (box_denom + (box_denom == 0.0))
slit_sky = moment1d(self.global_sky * thismask, trace_spat[:, ss], 2, row=trace_spec)[0] / wghts
# Denom is computed in case the trace goes off the edge of the image
slit_wave = moment1d(self.waveimg * thismask, trace_spat[:, ss], 2, row=trace_spec)[0] / wghts
# TODO :: Need to remove this XSpectrum1D dependency - it is required in: flexure.spec_flex_shift
slit_specs.append(xspectrum1d.XSpectrum1D.from_tuple((slit_wave, slit_sky)))
# Measure flexure
# If mode == global: specobjs = None and slitspecs != None
flex_list = flexure.spec_flexure_slit(self.slits, self.slits.slitord_id, self.reduce_bpm,
self.par['flexure']['spectrum'],
method=self.par['flexure']['spec_method'],
mxshft=self.par['flexure']['spec_maxshift'],
specobjs=sobjs, slit_specs=slit_specs)
# Store the slit shifts that were applied to each slit
# These corrections are later needed so the specobjs metadata contains the total spectral flexure
self.slitshift = np.zeros(self.slits.nslits)
for islit in range(self.slits.nslits):
if (not gd_slits[islit]) or len(flex_list[islit]['shift']) == 0:
continue
self.slitshift[islit] = flex_list[islit]['shift'][0]
# Apply flexure to the new wavelength solution
msgs.info("Regenerating wavelength image")
self.waveimg = self.wv_calib.build_waveimg(self.tilts, self.slits,
spat_flexure=self.spat_flexure_shift,
spec_flexure=self.slitshift)
elif mode == "local":
# Measure flexure:
# If mode == local: specobjs != None and slitspecs = None
flex_list = flexure.spec_flexure_slit(self.slits, self.slits.slitord_id, self.reduce_bpm,
self.par['flexure']['spectrum'],
method=self.par['flexure']['spec_method'],
mxshft=self.par['flexure']['spec_maxshift'],
specobjs=sobjs, slit_specs=None)
# Apply flexure to objects
for islit in range(self.slits.nslits):
i_slitord = self.slits.slitord_id[islit]
indx = sobjs.slitorder_indices(i_slitord)
this_specobjs = sobjs[indx]
this_flex_dict = flex_list[islit]
# Loop through objects
cntr = 0
for ss, sobj in enumerate(this_specobjs):
if sobj is None:
continue
if sobj['BOX_WAVE'] is None: # Nothing extracted; only the trace exists
continue
# Interpolate
new_sky = sobj.apply_spectral_flexure(this_flex_dict['shift'][cntr],
this_flex_dict['sky_spec'][cntr])
flex_list[islit]['sky_spec'][cntr] = new_sky.copy()
cntr += 1
# Save QA
basename = f'{self.basename}_{mode}_{self.spectrograph.get_det_name(self.det)}'
out_dir = os.path.join(self.par['rdx']['redux_path'], 'QA')
flexure.spec_flexure_qa(self.slits.slitord_id, self.reduce_bpm, basename, flex_list,
specobjs=sobjs, out_dir=out_dir)
def refframe_correct(self, ra, dec, obstime, sobjs=None):
""" Correct the calibrated wavelength to the user-supplied reference frame
Args:
radec (astropy.coordiantes.SkyCoord):
Sky Coordinate of the observation
obstime (:obj:`astropy.time.Time`):
Observation time
sobjs (:class:`pypeit.specobjs.Specobjs`, None):
Spectrally extracted objects
"""
# Correct Telescope's motion
refframe = self.par['calibrations']['wavelengths']['refframe']
if (refframe in ['heliocentric', 'barycentric']) \
and (self.par['calibrations']['wavelengths']['reference'] != 'pixel'):
msgs.info("Performing a {0} correction".format(self.par['calibrations']['wavelengths']['refframe']))
# Calculate correction
radec = ltu.radec_to_coord((ra, dec))
vel, vel_corr = wave.geomotion_correct(radec, obstime,
self.spectrograph.telescope['longitude'],
self.spectrograph.telescope['latitude'],
self.spectrograph.telescope['elevation'],
refframe)
# Apply correction to objects
msgs.info('Applying {0} correction = {1:0.5f} km/s'.format(refframe, vel))
if (sobjs is not None) and (sobjs.nobj != 0):
# Loop on slits to apply
gd_slitord = self.slits.slitord_id[np.logical_not(self.reduce_bpm)]
for slitord in gd_slitord:
indx = sobjs.slitorder_indices(slitord)
this_specobjs = sobjs[indx]
# Loop on objects
for specobj in this_specobjs:
if specobj is None:
continue
specobj.apply_helio(vel_corr, refframe)
# Apply correction to wavelength image
self.vel_corr = vel_corr
self.waveimg *= vel_corr
else:
msgs.info('A wavelength reference frame correction will not be performed.')
return
def show(self, attr, image=None, showmask=False, sobjs=None,
chname=None, slits=False,clear=False):
"""
Show one of the internal images
.. todo::
Should probably put some of these in ProcessImages
Parameters
----------
attr : str
global -- Sky model (global)
sci -- Processed science image
rawvar -- Raw variance image
modelvar -- Model variance image
crmasked -- Science image with CRs set to 0
skysub -- Science image with global sky subtracted
image -- Input image
display : str, optional
image : ndarray, optional
User supplied image to display
Returns
-------
"""
if showmask:
mask_in = self.sciImg.fullmask
bitmask_in = self.sciImg.bitmask
else:
mask_in = None
bitmask_in = None
img_gpm = self.sciImg.select_flag(invert=True)
detname = self.spectrograph.get_det_name(self.det)
if attr == 'global':
# global sky subtraction
if self.sciImg.image is not None and self.global_sky is not None \
and self.sciImg.fullmask is not None:
# sky subtracted image
image = (self.sciImg.image - self.global_sky) * img_gpm.astype(float)
mean, med, sigma = stats.sigma_clipped_stats(image[img_gpm], sigma_lower=5.0,
sigma_upper=5.0)
cut_min = mean - 1.0 * sigma
cut_max = mean + 4.0 * sigma
ch_name = chname if chname is not None else f'global_sky_{detname}'
viewer, ch = display.show_image(image, chname=ch_name, bitmask=bitmask_in,
mask=mask_in, clear=clear, wcs_match=True)
#, cuts=(cut_min, cut_max))
elif attr == 'local':
# local sky subtraction
if self.sciImg.image is not None and self.skymodel is not None \
and self.sciImg.fullmask is not None:
# sky subtracted image
image = (self.sciImg.image - self.skymodel) * img_gpm.astype(float)
mean, med, sigma = stats.sigma_clipped_stats(image[img_gpm], sigma_lower=5.0,
sigma_upper=5.0)
cut_min = mean - 1.0 * sigma
cut_max = mean + 4.0 * sigma
ch_name = chname if chname is not None else f'local_sky_{detname}'
viewer, ch = display.show_image(image, chname=ch_name, bitmask=bitmask_in,
mask=mask_in, clear=clear, wcs_match=True)
#, cuts=(cut_min, cut_max))
elif attr == 'sky_resid':
# sky residual map with object included
if self.sciImg.image is not None and self.skymodel is not None \
and self.objmodel is not None and self.ivarmodel is not None \
and self.sciImg.fullmask is not None:
image = (self.sciImg.image - self.skymodel) * np.sqrt(self.ivarmodel)
image *= img_gpm.astype(float)
ch_name = chname if chname is not None else f'sky_resid_{detname}'