Coverage for python/lsst/atmospec/processStar.py: 27%
332 statements
« prev ^ index » next coverage.py v7.3.0, created at 2023-09-01 11:42 +0000
« prev ^ index » next coverage.py v7.3.0, created at 2023-09-01 11:42 +0000
1# This file is part of atmospec.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
22__all__ = ['ProcessStarTask', 'ProcessStarTaskConfig']
24import os
25import shutil
26import numpy as np
27import matplotlib.pyplot as plt
29import lsstDebug
30import lsst.afw.image as afwImage
31import lsst.geom as geom
32from lsst.ip.isr import IsrTask
33import lsst.pex.config as pexConfig
34from lsst.pex.config import FieldValidationError
35import lsst.pipe.base as pipeBase
36import lsst.pipe.base.connectionTypes as cT
37from lsst.pipe.base.task import TaskError
39from lsst.utils import getPackageDir
40from lsst.pipe.tasks.characterizeImage import CharacterizeImageTask
41from lsst.meas.algorithms import ReferenceObjectLoader, MagnitudeLimit
42from lsst.meas.astrom import AstrometryTask, FitAffineWcsTask
44import lsst.afw.detection as afwDetect
46from .spectraction import SpectractorShim
47from .utils import getLinearStagePosition, isDispersedExp, getFilterAndDisperserFromExp
49COMMISSIONING = False # allows illegal things for on the mountain usage.
51# TODO:
52# Sort out read noise and gain
53# remove dummy image totally
54# talk to Jeremy about turning the image beforehand and giving new coords
55# deal with not having ambient temp
56# Gen3ification
57# astropy warning for units on save
58# but actually just remove all manual saves entirely, I think?
59# Make SED persistable
60# Move to QFM for star finding failover case
61# Remove old cruft functions
62# change spectractions run method to be ~all kwargs with *,...
65class ProcessStarTaskConnections(pipeBase.PipelineTaskConnections,
66 dimensions=("instrument", "visit", "detector")):
67 inputExp = cT.Input(
68 name="icExp",
69 doc="Image-characterize output exposure",
70 storageClass="ExposureF",
71 dimensions=("instrument", "visit", "detector"),
72 multiple=False,
73 )
74 inputCentroid = cT.Input(
75 name="atmospecCentroid",
76 doc="The main star centroid in yaml format.",
77 storageClass="StructuredDataDict",
78 dimensions=("instrument", "visit", "detector"),
79 multiple=False,
80 )
81 spectractorSpectrum = cT.Output(
82 name="spectractorSpectrum",
83 doc="The Spectractor output spectrum.",
84 storageClass="SpectractorSpectrum",
85 dimensions=("instrument", "visit", "detector"),
86 )
87 spectractorImage = cT.Output(
88 name="spectractorImage",
89 doc="The Spectractor output image.",
90 storageClass="SpectractorImage",
91 dimensions=("instrument", "visit", "detector"),
92 )
93 spectrumForwardModelFitParameters = cT.Output(
94 name="spectrumForwardModelFitParameters",
95 doc="The full forward model fit parameters.",
96 storageClass="SpectractorFitParameters",
97 dimensions=("instrument", "visit", "detector"),
98 )
99 spectrumLibradtranFitParameters = cT.Output(
100 name="spectrumLibradtranFitParameters",
101 doc="The fitted Spectractor atmospheric parameters from fitting the atmosphere with libradtran"
102 " on the spectrum.",
103 storageClass="SpectractorFitParameters",
104 dimensions=("instrument", "visit", "detector"),
105 )
106 spectrogramLibradtranFitParameters = cT.Output(
107 name="spectrogramLibradtranFitParameters",
108 doc="The fitted Spectractor atmospheric parameters from fitting the atmosphere with libradtran"
109 " directly on the spectrogram.",
110 storageClass="SpectractorFitParameters",
111 dimensions=("instrument", "visit", "detector"),
112 )
114 def __init__(self, *, config=None):
115 super().__init__(config=config)
116 if not config.doFullForwardModelDeconvolution:
117 self.outputs.remove("spectrumForwardModelFitParameters")
118 if not config.doFitAtmosphere:
119 self.outputs.remove("spectrumLibradtranFitParameters")
120 if not config.doFitAtmosphereOnSpectrogram:
121 self.outputs.remove("spectrogramLibradtranFitParameters")
124class ProcessStarTaskConfig(pipeBase.PipelineTaskConfig,
125 pipelineConnections=ProcessStarTaskConnections):
126 """Configuration parameters for ProcessStarTask."""
127 # Spectractor parameters:
128 targetCentroidMethod = pexConfig.ChoiceField(
129 dtype=str,
130 doc="Method to get target centroid. "
131 "SPECTRACTOR_FIT_TARGET_CENTROID internally.",
132 default="auto",
133 allowed={
134 # note that although this config option controls
135 # SPECTRACTOR_FIT_TARGET_CENTROID, it doesn't map there directly,
136 # because Spectractor only has the concepts of guess, fit and wcs,
137 # and it calls "exact" "guess" internally, so that's remapped.
138 "auto": "If the upstream astrometric fit succeeded, and therefore"
139 " the centroid is an exact one, use that as an ``exact`` value,"
140 " otherwise tell Spectractor to ``fit`` the centroid",
141 "exact": "Use a given input value as source of truth.",
142 "fit": "Fit a 2d Moffat model to the target.",
143 "WCS": "Use the target's catalog location and the image's wcs.",
144 }
145 )
146 rotationAngleMethod = pexConfig.ChoiceField(
147 dtype=str,
148 doc="Method used to get the image rotation angle. "
149 "SPECTRACTOR_COMPUTE_ROTATION_ANGLE internally.",
150 default="disperser",
151 allowed={
152 # XXX MFL: probably need to use setDefaults to set this based on
153 # the disperser. I think Ronchi gratings want hessian and the
154 # holograms want disperser.
155 "False": "Do not rotate the image.",
156 "disperser": "Use the disperser angle geometry as specified in the disperser definition.",
157 "hessian": "Compute the angle from the image using a Hessian transform.",
158 }
159 )
160 doDeconvolveSpectrum = pexConfig.Field(
161 dtype=bool,
162 doc="Deconvolve the spectrogram with a simple 2D PSF analysis? "
163 "SPECTRACTOR_DECONVOLUTION_PSF2D internally.",
164 default=False,
165 )
166 doFullForwardModelDeconvolution = pexConfig.Field(
167 dtype=bool,
168 doc="Deconvolve the spectrogram with full forward model? "
169 "SPECTRACTOR_DECONVOLUTION_FFM internally.",
170 default=True,
171 )
172 deconvolutionSigmaClip = pexConfig.Field(
173 dtype=float,
174 doc="Sigma clipping level for the deconvolution when fitting the full forward model? "
175 "SPECTRACTOR_DECONVOLUTION_SIGMA_CLIP internally.",
176 default=100,
177 )
178 doSubtractBackground = pexConfig.Field(
179 dtype=bool,
180 doc="Subtract the background with Spectractor? "
181 "SPECTRACTOR_BACKGROUND_SUBTRACTION internally.",
182 default=True,
183 )
184 rebin = pexConfig.Field(
185 dtype=int,
186 doc="Rebinning factor to use on the input image, in pixels. "
187 "CCD_REBIN internally.",
188 default=2, # TODO Change to 1 once speed issues are resolved
189 )
190 xWindow = pexConfig.Field(
191 dtype=int,
192 doc="Window x size to search for the target object. Ignored if targetCentroidMethod in ('exact, wcs')"
193 "XWINDOW internally.",
194 default=100,
195 )
196 yWindow = pexConfig.Field(
197 dtype=int,
198 doc="Window y size to search for the targeted object. Ignored if targetCentroidMethod in "
199 "('exact, wcs')"
200 "YWINDOW internally.",
201 default=100,
202 )
203 xWindowRotated = pexConfig.Field(
204 dtype=int,
205 doc="Window x size to search for the target object in the rotated image. "
206 "Ignored if rotationAngleMethod=False"
207 "XWINDOW_ROT internally.",
208 default=50,
209 )
210 yWindowRotated = pexConfig.Field(
211 dtype=int,
212 doc="Window y size to search for the target object in the rotated image. "
213 "Ignored if rotationAngleMethod=False"
214 "YWINDOW_ROT internally.",
215 default=50,
216 )
217 pixelShiftPrior = pexConfig.Field( 217 ↛ exitline 217 didn't jump to the function exit
218 dtype=float,
219 doc="Prior on the reliability of the centroid estimate in pixels. "
220 "PIXSHIFT_PRIOR internally.",
221 default=5,
222 check=lambda x: x > 0,
223 )
224 doFilterRotatedImage = pexConfig.Field(
225 dtype=bool,
226 doc="Apply a filter to the rotated image? If not True, this creates residuals and correlated noise. "
227 "ROT_PREFILTER internally.",
228 default=True,
229 )
230 imageRotationSplineOrder = pexConfig.Field(
231 dtype=int,
232 doc="Order of the spline used when rotating the image. "
233 "ROT_ORDER internally.",
234 default=5,
235 # XXX min value of 3 for allowed range, max 5
236 )
237 rotationAngleMin = pexConfig.Field(
238 dtype=float,
239 doc="In the Hessian analysis to compute the rotation angle, cut all angles below this, in degrees. "
240 "ROT_ANGLE_MIN internally.",
241 default=-10,
242 )
243 rotationAngleMax = pexConfig.Field(
244 dtype=float,
245 doc="In the Hessian analysis to compute rotation angle, cut all angles above this, in degrees. "
246 "ROT_ANGLE_MAX internally.",
247 default=10,
248 )
249 plotLineWidth = pexConfig.Field(
250 dtype=float,
251 doc="Line width parameter for plotting. "
252 "LINEWIDTH internally.",
253 default=2,
254 )
255 verbose = pexConfig.Field(
256 dtype=bool,
257 doc="Set verbose mode? "
258 "VERBOSE internally.",
259 default=True, # sets INFO level logging in Spectractor
260 )
261 spectractorDebugMode = pexConfig.Field(
262 dtype=bool,
263 doc="Set spectractor debug mode? "
264 "DEBUG internally.",
265 default=True,
266 )
267 spectractorDebugLogging = pexConfig.Field(
268 dtype=bool,
269 doc="Set spectractor debug logging? "
270 "DEBUG_LOGGING internally.",
271 default=False
272 )
273 doDisplay = pexConfig.Field(
274 dtype=bool,
275 doc="Display plots, for example when running in a notebook? "
276 "DISPLAY internally.",
277 default=True
278 )
279 lambdaMin = pexConfig.Field(
280 dtype=int,
281 doc="Minimum wavelength for spectral extraction (in nm). "
282 "LAMBDA_MIN internally.",
283 default=300
284 )
285 lambdaMax = pexConfig.Field(
286 dtype=int,
287 doc=" maximum wavelength for spectrum extraction (in nm). "
288 "LAMBDA_MAX internally.",
289 default=1100
290 )
291 lambdaStep = pexConfig.Field(
292 dtype=float,
293 doc="Step size for the wavelength array (in nm). "
294 "LAMBDA_STEP internally.",
295 default=1,
296 )
297 spectralOrder = pexConfig.ChoiceField(
298 dtype=int,
299 doc="The spectral order to extract. "
300 "SPEC_ORDER internally.",
301 default=1,
302 allowed={
303 1: "The first order spectrum in the positive y direction",
304 -1: "The first order spectrum in the negative y direction",
305 2: "The second order spectrum in the positive y direction",
306 -2: "The second order spectrum in the negative y direction",
307 }
308 )
309 signalWidth = pexConfig.Field( # TODO: change this to be set wrt the focus/seeing, i.e. FWHM from imChar
310 dtype=int,
311 doc="Half transverse width of the signal rectangular window in pixels. "
312 "PIXWIDTH_SIGNAL internally.",
313 default=40,
314 )
315 backgroundDistance = pexConfig.Field(
316 dtype=int,
317 doc="Distance from dispersion axis to analyse the background in pixels. "
318 "PIXDIST_BACKGROUND internally.",
319 default=140,
320 )
321 backgroundWidth = pexConfig.Field(
322 dtype=int,
323 doc="Transverse width of the background rectangular window in pixels. "
324 "PIXWIDTH_BACKGROUND internally.",
325 default=40,
326 )
327 backgroundBoxSize = pexConfig.Field(
328 dtype=int,
329 doc="Box size for sextractor evaluation of the background. "
330 "PIXWIDTH_BOXSIZE internally.",
331 default=20,
332 )
333 backgroundOrder = pexConfig.Field(
334 dtype=int,
335 doc="The order of the polynomial background to fit in the transverse direction. "
336 "BGD_ORDER internally.",
337 default=1,
338 )
339 psfType = pexConfig.ChoiceField(
340 dtype=str,
341 doc="The PSF model type to use. "
342 "PSF_TYPE internally.",
343 default="Moffat",
344 allowed={
345 "Moffat": "A Moffat function",
346 "MoffatGauss": "A Moffat plus a Gaussian"
347 }
348 )
349 psfPolynomialOrder = pexConfig.Field(
350 dtype=int,
351 doc="The order of the polynomials to model wavelength dependence of the PSF shape parameters. "
352 "PSF_POLY_ORDER internally.",
353 default=2
354 )
355 psfRegularization = pexConfig.Field(
356 dtype=float,
357 doc="Regularisation parameter for the chisq minimisation to extract the spectrum. "
358 "PSF_FIT_REG_PARAM internally.",
359 default=1,
360 # XXX allowed range strictly positive
361 )
362 psfTransverseStepSize = pexConfig.Field(
363 dtype=int,
364 doc="Step size in pixels for the first transverse PSF1D fit. "
365 "PSF_PIXEL_STEP_TRANSVERSE_FIT internally.",
366 default=50,
367 )
368 psfFwhmClip = pexConfig.Field(
369 dtype=float,
370 doc="PSF is not evaluated outside a region larger than max(signalWidth, psfFwhmClip*fwhm) pixels. "
371 "PSF_FWHM_CLIP internally.",
372 default=2,
373 )
374 calibBackgroundOrder = pexConfig.Field(
375 dtype=int,
376 doc="Order of the background polynomial to fit. "
377 "CALIB_BGD_ORDER internally.",
378 default=3,
379 )
380 calibPeakWidth = pexConfig.Field(
381 dtype=int,
382 doc="Half-range to look for local extrema in pixels around tabulated line values. "
383 "CALIB_PEAK_WIDTH internally.",
384 default=7
385 )
386 calibBackgroundWidth = pexConfig.Field(
387 dtype=int,
388 doc="Size of the peak sides to use to fit spectrum base line. "
389 "CALIB_BGD_WIDTH internally.",
390 default=15,
391 )
392 calibSavgolWindow = pexConfig.Field(
393 dtype=int,
394 doc="Window size for the savgol filter in pixels. "
395 "CALIB_SAVGOL_WINDOW internally.",
396 default=5,
397 )
398 calibSavgolOrder = pexConfig.Field(
399 dtype=int,
400 doc="Polynomial order for the savgol filter. "
401 "CALIB_SAVGOL_ORDER internally.",
402 default=2,
403 )
404 offsetFromMainStar = pexConfig.Field(
405 dtype=int,
406 doc="Number of pixels from the main star's centroid to start extraction",
407 default=100
408 )
409 spectrumLengthPixels = pexConfig.Field(
410 dtype=int,
411 doc="Length of the spectrum in pixels",
412 default=5000
413 )
414 # ProcessStar own parameters
415 isr = pexConfig.ConfigurableField(
416 target=IsrTask,
417 doc="Task to perform instrumental signature removal",
418 )
419 charImage = pexConfig.ConfigurableField(
420 target=CharacterizeImageTask,
421 doc="""Task to characterize a science exposure:
422 - detect sources, usually at high S/N
423 - estimate the background, which is subtracted from the image and returned as field "background"
424 - estimate a PSF model, which is added to the exposure
425 - interpolate over defects and cosmic rays, updating the image, variance and mask planes
426 """,
427 )
428 doWrite = pexConfig.Field(
429 dtype=bool,
430 doc="Write out the results?",
431 default=True,
432 )
433 doFlat = pexConfig.Field(
434 dtype=bool,
435 doc="Flatfield the image?",
436 default=True
437 )
438 doCosmics = pexConfig.Field(
439 dtype=bool,
440 doc="Repair cosmic rays?",
441 default=True
442 )
443 doDisplayPlots = pexConfig.Field(
444 dtype=bool,
445 doc="Matplotlib show() the plots, so they show up in a notebook or X window",
446 default=False
447 )
448 doSavePlots = pexConfig.Field(
449 dtype=bool,
450 doc="Save matplotlib plots to output rerun?",
451 default=False
452 )
453 forceObjectName = pexConfig.Field(
454 dtype=str,
455 doc="A supplementary name for OBJECT. Will be forced to apply to ALL visits, so this should only"
456 " ONLY be used for immediate commissioning debug purposes. All long term fixes should be"
457 " supplied as header fix-up yaml files.",
458 default=""
459 )
460 referenceFilterOverride = pexConfig.Field(
461 dtype=str,
462 doc="Which filter in the reference catalog to match to?",
463 default="phot_g_mean"
464 )
465 # This is a post-processing function in Spectractor and therefore isn't
466 # controlled by its top-level function, and thus doesn't map to a
467 # spectractor.parameters ALL_CAPS config option
468 doFitAtmosphere = pexConfig.Field(
469 dtype=bool,
470 doc="Use uvspec to fit the atmosphere? Requires the binary to be available.",
471 default=False
472 )
473 # This is a post-processing function in Spectractor and therefore isn't
474 # controlled by its top-level function, and thus doesn't map to a
475 # spectractor.parameters ALL_CAPS config option
476 doFitAtmosphereOnSpectrogram = pexConfig.Field(
477 dtype=bool,
478 doc="Experimental option to use uvspec to fit the atmosphere directly on the spectrogram?"
479 " Requires the binary to be available.",
480 default=False
481 )
483 def setDefaults(self):
484 self.isr.doWrite = False
485 self.charImage.doWriteExposure = False
487 self.charImage.doApCorr = False
488 self.charImage.doMeasurePsf = False
489 self.charImage.repair.cosmicray.nCrPixelMax = 100000
490 self.charImage.repair.doCosmicRay = False
491 if self.charImage.doMeasurePsf:
492 self.charImage.measurePsf.starSelector['objectSize'].signalToNoiseMin = 10.0
493 self.charImage.measurePsf.starSelector['objectSize'].fluxMin = 5000.0
494 self.charImage.detection.includeThresholdMultiplier = 3
495 self.isr.overscan.fitType = 'MEDIAN_PER_ROW'
497 def validate(self):
498 super().validate()
499 uvspecPath = shutil.which('uvspec')
500 if uvspecPath is None and self.doFitAtmosphere is True:
501 raise FieldValidationError(self.__class__.doFitAtmosphere, self, "uvspec is not in the path,"
502 " but doFitAtmosphere is True.")
503 if uvspecPath is None and self.doFitAtmosphereOnSpectrogram is True:
504 raise FieldValidationError(self.__class__.doFitAtmosphereOnSpectrogram, self, "uvspec is not in"
505 " the path, but doFitAtmosphere is True.")
508class ProcessStarTask(pipeBase.PipelineTask):
509 """Task for the spectral extraction of single-star dispersed images.
511 For a full description of how this tasks works, see the run() method.
512 """
514 ConfigClass = ProcessStarTaskConfig
515 _DefaultName = "processStar"
517 def __init__(self, **kwargs):
518 # TODO: rename psfRefObjLoader to refObjLoader
519 super().__init__(**kwargs)
520 self.makeSubtask("isr")
521 self.makeSubtask("charImage", refObjLoader=None)
523 self.debug = lsstDebug.Info(__name__)
524 if self.debug.enabled:
525 self.log.info("Running with debug enabled...")
526 # If we're displaying, test it works and save displays for later.
527 # It's worth testing here as displays are flaky and sometimes
528 # can't be contacted, and given processing takes a while,
529 # it's a shame to fail late due to display issues.
530 if self.debug.display:
531 try:
532 import lsst.afw.display as afwDisp
533 afwDisp.setDefaultBackend(self.debug.displayBackend)
534 afwDisp.Display.delAllDisplays()
535 # pick an unlikely number to be safe xxx replace this
536 self.disp1 = afwDisp.Display(987, open=True)
538 im = afwImage.ImageF(2, 2)
539 im.array[:] = np.ones((2, 2))
540 self.disp1.mtv(im)
541 self.disp1.erase()
542 afwDisp.setDefaultMaskTransparency(90)
543 except NameError:
544 self.debug.display = False
545 self.log.warn('Failed to setup/connect to display! Debug display has been disabled')
547 if self.debug.notHeadless:
548 pass # other backend options can go here
549 else: # this stop windows popping up when plotting. When headless, use 'agg' backend too
550 plt.interactive(False)
552 self.config.validate()
553 self.config.freeze()
555 def findObjects(self, exp, nSigma=None, grow=0):
556 """Find the objects in a postISR exposure."""
557 nPixMin = self.config.mainStarNpixMin
558 if not nSigma:
559 nSigma = self.config.mainStarNsigma
560 if not grow:
561 grow = self.config.mainStarGrow
562 isotropic = self.config.mainStarGrowIsotropic
564 threshold = afwDetect.Threshold(nSigma, afwDetect.Threshold.STDEV)
565 footPrintSet = afwDetect.FootprintSet(exp.getMaskedImage(), threshold, "DETECTED", nPixMin)
566 if grow > 0:
567 footPrintSet = afwDetect.FootprintSet(footPrintSet, grow, isotropic)
568 return footPrintSet
570 def _getEllipticity(self, shape):
571 """Calculate the ellipticity given a quadrupole shape.
573 Parameters
574 ----------
575 shape : `lsst.afw.geom.ellipses.Quadrupole`
576 The quadrupole shape
578 Returns
579 -------
580 ellipticity : `float`
581 The magnitude of the ellipticity
582 """
583 ixx = shape.getIxx()
584 iyy = shape.getIyy()
585 ixy = shape.getIxy()
586 ePlus = (ixx - iyy) / (ixx + iyy)
587 eCross = 2*ixy / (ixx + iyy)
588 return (ePlus**2 + eCross**2)**0.5
590 def getRoundestObject(self, footPrintSet, parentExp, fluxCut=1e-15):
591 """Get the roundest object brighter than fluxCut from a footPrintSet.
593 Parameters
594 ----------
595 footPrintSet : `lsst.afw.detection.FootprintSet`
596 The set of footprints resulting from running detection on parentExp
598 parentExp : `lsst.afw.image.exposure`
599 The parent exposure for the footprint set.
601 fluxCut : `float`
602 The flux, below which, sources are rejected.
604 Returns
605 -------
606 source : `lsst.afw.detection.Footprint`
607 The winning footprint from the input footPrintSet
608 """
609 self.log.debug("ellipticity\tflux/1e6\tcentroid")
610 sourceDict = {}
611 for fp in footPrintSet.getFootprints():
612 shape = fp.getShape()
613 e = self._getEllipticity(shape)
614 flux = fp.getSpans().flatten(parentExp.image.array, parentExp.image.getXY0()).sum()
615 self.log.debug("%.4f\t%.2f\t%s"%(e, flux/1e6, str(fp.getCentroid())))
616 if flux > fluxCut:
617 sourceDict[e] = fp
619 return sourceDict[sorted(sourceDict.keys())[0]]
621 def getBrightestObject(self, footPrintSet, parentExp, roundnessCut=1e9):
622 """Get the brightest object rounder than the cut from a footPrintSet.
624 Parameters
625 ----------
626 footPrintSet : `lsst.afw.detection.FootprintSet`
627 The set of footprints resulting from running detection on parentExp
629 parentExp : `lsst.afw.image.exposure`
630 The parent exposure for the footprint set.
632 roundnessCut : `float`
633 The ellipticity, above which, sources are rejected.
635 Returns
636 -------
637 source : `lsst.afw.detection.Footprint`
638 The winning footprint from the input footPrintSet
639 """
640 self.log.debug("ellipticity\tflux\tcentroid")
641 sourceDict = {}
642 for fp in footPrintSet.getFootprints():
643 shape = fp.getShape()
644 e = self._getEllipticity(shape)
645 flux = fp.getSpans().flatten(parentExp.image.array, parentExp.image.getXY0()).sum()
646 self.log.debug("%.4f\t%.2f\t%s"%(e, flux/1e6, str(fp.getCentroid())))
647 if e < roundnessCut:
648 sourceDict[flux] = fp
650 return sourceDict[sorted(sourceDict.keys())[-1]]
652 def findMainSource(self, exp):
653 """Return the x,y of the brightest or roundest object in an exposure.
655 Given a postISR exposure, run source detection on it, and return the
656 centroid of the main star. Depending on the task configuration, this
657 will either be the roundest object above a certain flux cutoff, or
658 the brightest object which is rounder than some ellipticity cutoff.
660 Parameters
661 ----------
662 exp : `afw.image.Exposure`
663 The postISR exposure in which to find the main star
665 Returns
666 -------
667 x, y : `tuple` of `float`
668 The centroid of the main star in the image
670 Notes
671 -----
672 Behavior of this method is controlled by many task config params
673 including, for the detection stage:
674 config.mainStarNpixMin
675 config.mainStarNsigma
676 config.mainStarGrow
677 config.mainStarGrowIsotropic
679 And post-detection, for selecting the main source:
680 config.mainSourceFindingMethod
681 config.mainStarFluxCut
682 config.mainStarRoundnessCut
683 """
684 # TODO: probably replace all this with QFM
685 fpSet = self.findObjects(exp)
686 if self.config.mainSourceFindingMethod == 'ROUNDEST':
687 source = self.getRoundestObject(fpSet, exp, fluxCut=self.config.mainStarFluxCut)
688 elif self.config.mainSourceFindingMethod == 'BRIGHTEST':
689 source = self.getBrightestObject(fpSet, exp,
690 roundnessCut=self.config.mainStarRoundnessCut)
691 else:
692 # should be impossible as this is a choice field, but still
693 raise RuntimeError("Invalid source finding method "
694 f"selected: {self.config.mainSourceFindingMethod}")
695 return source.getCentroid()
697 def updateMetadata(self, exp, **kwargs):
698 """Update an exposure's metadata with set items from the visit info.
700 Spectractor expects many items, like the hour angle and airmass, to be
701 in the metadata, so pull them out of the visit info etc and put them
702 into the main metadata. Also updates the metadata with any supplied
703 kwargs.
705 Parameters
706 ----------
707 exp : `lsst.afw.image.Exposure`
708 The exposure to update.
709 **kwargs : `dict`
710 The items to add.
711 """
712 md = exp.getMetadata()
713 vi = exp.getInfo().getVisitInfo()
715 ha = vi.getBoresightHourAngle().asDegrees()
716 airmass = vi.getBoresightAirmass()
718 md['HA'] = ha
719 md.setComment('HA', 'Hour angle of observation start')
721 md['AIRMASS'] = airmass
722 md.setComment('AIRMASS', 'Airmass at observation start')
724 if 'centroid' in kwargs:
725 centroid = kwargs['centroid']
726 else:
727 centroid = (None, None)
729 md['OBJECTX'] = centroid[0]
730 md.setComment('OBJECTX', 'x pixel coordinate of object centroid')
732 md['OBJECTY'] = centroid[1]
733 md.setComment('OBJECTY', 'y pixel coordinate of object centroid')
735 exp.setMetadata(md)
737 def runQuantum(self, butlerQC, inputRefs, outputRefs):
738 inputs = butlerQC.get(inputRefs)
740 inputs['dataIdDict'] = inputRefs.inputExp.dataId.byName()
742 outputs = self.run(**inputs)
743 butlerQC.put(outputs, outputRefs)
745 def getNormalizedTargetName(self, target):
746 """Normalize the name of the target.
748 All targets which start with 'spec:' are converted to the name of the
749 star without the leading 'spec:'. Any objects with mappings defined in
750 data/nameMappings.txt are converted to the mapped name.
752 Parameters
753 ----------
754 target : `str`
755 The name of the target.
757 Returns
758 -------
759 normalizedTarget : `str`
760 The normalized name of the target.
761 """
762 target = target.replace('spec:', '')
764 nameMappingsFile = os.path.join(getPackageDir('atmospec'), 'data', 'nameMappings.txt')
765 names, mappedNames = np.loadtxt(nameMappingsFile, dtype=str, unpack=True)
766 assert len(names) == len(mappedNames)
767 conversions = {name: mapped for name, mapped in zip(names, mappedNames)}
769 if target in conversions.keys():
770 converted = conversions[target]
771 self.log.info(f"Converted target name {target} to {converted}")
772 return converted
773 return target
775 def _getSpectractorTargetSetting(self, inputCentroid):
776 """Calculate the value to set SPECTRACTOR_FIT_TARGET_CENTROID to.
778 Parameters
779 ----------
780 inputCentroid : `dict`
781 The `atmospecCentroid` dict, as received in the task input data.
783 Returns
784 -------
785 centroidMethod : `str`
786 The value to set SPECTRACTOR_FIT_TARGET_CENTROID to.
787 """
789 # if mode is auto and the astrometry worked then it's an exact
790 # centroid, and otherwise we fit, as per docs on this option.
791 if self.config.targetCentroidMethod == 'auto':
792 if inputCentroid['astrometricMatch'] is True:
793 self.log.info("Auto centroid is using exact centroid for target from the astrometry")
794 return 'guess' # this means exact
795 else:
796 self.log.info("Auto centroid is using FIT in Spectractor to get the target centroid")
797 return 'fit' # this means exact
799 # this is just renaming the config parameter because guess sounds like
800 # an instruction, and really we're saying to take this as given.
801 if self.config.targetCentroidMethod == 'exact':
802 return 'guess'
804 # all other options fall through
805 return self.config.targetCentroidMethod
807 def run(self, *, inputExp, inputCentroid, dataIdDict):
808 if not isDispersedExp(inputExp):
809 raise RuntimeError(f"Exposure is not a dispersed image {dataIdDict}")
810 starNames = self.loadStarNames()
812 overrideDict = {
813 # normal config parameters
814 'SPECTRACTOR_FIT_TARGET_CENTROID': self._getSpectractorTargetSetting(inputCentroid),
815 'SPECTRACTOR_COMPUTE_ROTATION_ANGLE': self.config.rotationAngleMethod,
816 'SPECTRACTOR_DECONVOLUTION_PSF2D': self.config.doDeconvolveSpectrum,
817 'SPECTRACTOR_DECONVOLUTION_FFM': self.config.doFullForwardModelDeconvolution,
818 'SPECTRACTOR_DECONVOLUTION_SIGMA_CLIP': self.config.deconvolutionSigmaClip,
819 'SPECTRACTOR_BACKGROUND_SUBTRACTION': self.config.doSubtractBackground,
820 'CCD_REBIN': self.config.rebin,
821 'XWINDOW': self.config.xWindow,
822 'YWINDOW': self.config.yWindow,
823 'XWINDOW_ROT': self.config.xWindowRotated,
824 'YWINDOW_ROT': self.config.yWindowRotated,
825 'PIXSHIFT_PRIOR': self.config.pixelShiftPrior,
826 'ROT_PREFILTER': self.config.doFilterRotatedImage,
827 'ROT_ORDER': self.config.imageRotationSplineOrder,
828 'ROT_ANGLE_MIN': self.config.rotationAngleMin,
829 'ROT_ANGLE_MAX': self.config.rotationAngleMax,
830 'LINEWIDTH': self.config.plotLineWidth,
831 'VERBOSE': self.config.verbose,
832 'DEBUG': self.config.spectractorDebugMode,
833 'DEBUG_LOGGING': self.config.spectractorDebugLogging,
834 'DISPLAY': self.config.doDisplay,
835 'LAMBDA_MIN': self.config.lambdaMin,
836 'LAMBDA_MAX': self.config.lambdaMax,
837 'LAMBDA_STEP': self.config.lambdaStep,
838 'SPEC_ORDER': self.config.spectralOrder,
839 'PIXWIDTH_SIGNAL': self.config.signalWidth,
840 'PIXDIST_BACKGROUND': self.config.backgroundDistance,
841 'PIXWIDTH_BACKGROUND': self.config.backgroundWidth,
842 'PIXWIDTH_BOXSIZE': self.config.backgroundBoxSize,
843 'BGD_ORDER': self.config.backgroundOrder,
844 'PSF_TYPE': self.config.psfType,
845 'PSF_POLY_ORDER': self.config.psfPolynomialOrder,
846 'PSF_FIT_REG_PARAM': self.config.psfRegularization,
847 'PSF_PIXEL_STEP_TRANSVERSE_FIT': self.config.psfTransverseStepSize,
848 'PSF_FWHM_CLIP': self.config.psfFwhmClip,
849 'CALIB_BGD_ORDER': self.config.calibBackgroundOrder,
850 'CALIB_PEAK_WIDTH': self.config.calibPeakWidth,
851 'CALIB_BGD_WIDTH': self.config.calibBackgroundWidth,
852 'CALIB_SAVGOL_WINDOW': self.config.calibSavgolWindow,
853 'CALIB_SAVGOL_ORDER': self.config.calibSavgolOrder,
855 # Hard-coded parameters
856 'OBS_NAME': 'AUXTEL',
857 'CCD_IMSIZE': 4000, # short axis - we trim the CCD to square
858 'CCD_MAXADU': 170000, # XXX need to set this from camera value
859 'CCD_GAIN': 1.1, # set programatically later, this is default nominal value
860 'OBS_NAME': 'AUXTEL',
861 'OBS_ALTITUDE': 2.66299616375123, # XXX get this from / check with utils value
862 'OBS_LATITUDE': -30.2446389756252, # XXX get this from / check with utils value
863 'OBS_DIAMETER': 1.20,
864 'OBS_EPOCH': "J2000.0",
865 'OBS_CAMERA_DEC_FLIP_SIGN': 1,
866 'OBS_CAMERA_RA_FLIP_SIGN': 1,
867 'OBS_SURFACE': np.pi * 1.2 ** 2 / 4.,
868 'PAPER': False,
869 'SAVE': False,
870 'DISTANCE2CCD_ERR': 0.4,
872 # Parameters set programatically
873 'LAMBDAS': np.arange(self.config.lambdaMin,
874 self.config.lambdaMax,
875 self.config.lambdaStep),
876 'CALIB_BGD_NPARAMS': self.config.calibBackgroundOrder + 1,
878 # Parameters set elsewhere
879 # OBS_CAMERA_ROTATION
880 # DISTANCE2CCD
881 }
883 supplementDict = {'CALLING_CODE': 'LSST_DM',
884 'STAR_NAMES': starNames}
886 # anything that changes between dataRefs!
887 resetParameters = {}
888 # TODO: look at what to do with config option doSavePlots
890 # TODO: think if this is the right place for this
891 # probably wants to go in spectraction.py really
892 linearStagePosition = getLinearStagePosition(inputExp)
893 _, grating = getFilterAndDisperserFromExp(inputExp)
894 if grating == 'holo4_003':
895 # the hologram is sealed with a 4 mm window and this is how
896 # spectractor handles this, so while it's quite ugly, do this to
897 # keep the behaviour the same for now.
898 linearStagePosition += 4 # hologram is sealed with a 4 mm window
899 overrideDict['DISTANCE2CCD'] = linearStagePosition
901 target = inputExp.visitInfo.object
902 target = self.getNormalizedTargetName(target)
903 if self.config.forceObjectName:
904 self.log.info(f"Forcing target name from {target} to {self.config.forceObjectName}")
905 target = self.config.forceObjectName
907 if target in ['FlatField position', 'Park position', 'Test', 'NOTSET']:
908 raise ValueError(f"OBJECT set to {target} - this is not a celestial object!")
910 packageDir = getPackageDir('atmospec')
911 configFilename = os.path.join(packageDir, 'config', 'auxtel.ini')
913 spectractor = SpectractorShim(configFile=configFilename,
914 paramOverrides=overrideDict,
915 supplementaryParameters=supplementDict,
916 resetParameters=resetParameters)
918 if 'astrometricMatch' in inputCentroid:
919 centroid = inputCentroid['centroid']
920 else: # it's a raw tuple
921 centroid = inputCentroid # TODO: put this support in the docstring
923 spectraction = spectractor.run(inputExp, *centroid, target,
924 self.config.doFitAtmosphere,
925 self.config.doFitAtmosphereOnSpectrogram)
927 self.log.info("Finished processing %s" % (dataIdDict))
929 return pipeBase.Struct(
930 spectractorSpectrum=spectraction.spectrum,
931 spectractorImage=spectraction.image,
932 spectrumForwardModelFitParameters=spectraction.spectrumForwardModelFitParameters,
933 spectrumLibradtranFitParameters=spectraction.spectrumLibradtranFitParameters,
934 spectrogramLibradtranFitParameters=spectraction.spectrogramLibradtranFitParameters
935 )
937 def runAstrometry(self, butler, exp, icSrc):
938 refObjLoaderConfig = ReferenceObjectLoader.ConfigClass()
939 refObjLoaderConfig.pixelMargin = 1000
940 # TODO: needs to be an Input Connection
941 refObjLoader = ReferenceObjectLoader(config=refObjLoaderConfig)
943 astromConfig = AstrometryTask.ConfigClass()
944 astromConfig.wcsFitter.retarget(FitAffineWcsTask)
945 astromConfig.referenceSelector.doMagLimit = True
946 magLimit = MagnitudeLimit()
947 magLimit.minimum = 1
948 magLimit.maximum = 15
949 astromConfig.referenceSelector.magLimit = magLimit
950 astromConfig.referenceSelector.magLimit.fluxField = "phot_g_mean_flux"
951 astromConfig.matcher.maxRotationDeg = 5.99
952 astromConfig.matcher.maxOffsetPix = 3000
953 astromConfig.sourceSelector['matcher'].minSnr = 10
954 solver = AstrometryTask(config=astromConfig, refObjLoader=refObjLoader)
956 # TODO: Change this to doing this the proper way
957 referenceFilterName = self.config.referenceFilterOverride
958 referenceFilterLabel = afwImage.FilterLabel(physical=referenceFilterName, band=referenceFilterName)
959 originalFilterLabel = exp.getFilter() # there's a better way of doing this with the task I think
960 exp.setFilter(referenceFilterLabel)
962 try:
963 astromResult = solver.run(sourceCat=icSrc, exposure=exp)
964 exp.setFilter(originalFilterLabel)
965 except (RuntimeError, TaskError):
966 self.log.warn("Solver failed to run completely")
967 exp.setFilter(originalFilterLabel)
968 return None
970 scatter = astromResult.scatterOnSky.asArcseconds()
971 if scatter < 1:
972 return astromResult
973 else:
974 self.log.warn("Failed to find an acceptable match")
975 return None
977 def pause(self):
978 if self.debug.pauseOnDisplay:
979 input("Press return to continue...")
980 return
982 def loadStarNames(self):
983 """Get the objects which should be treated as stars which do not begin
984 with HD.
986 Spectractor treats all objects which start HD as stars, and all which
987 don't as calibration objects, e.g. arc lamps or planetary nebulae.
988 Adding items to data/starNames.txt will cause them to be treated as
989 regular stars.
991 Returns
992 -------
993 starNames : `list` of `str`
994 The list of all objects to be treated as stars despite not starting
995 with HD.
996 """
997 starNameFile = os.path.join(getPackageDir('atmospec'), 'data', 'starNames.txt')
998 with open(starNameFile, 'r') as f:
999 lines = f.readlines()
1000 return [line.strip() for line in lines]
1002 def flatfield(self, exp, disp):
1003 """Placeholder for wavelength dependent flatfielding: TODO: DM-18141
1005 Will probably need a dataRef, as it will need to be retrieving flats
1006 over a range. Also, it will be somewhat complex, so probably needs
1007 moving to its own task"""
1008 self.log.warn("Flatfielding not yet implemented")
1009 return exp
1011 def repairCosmics(self, exp, disp):
1012 self.log.warn("Cosmic ray repair not yet implemented")
1013 return exp
1015 def measureSpectrum(self, exp, sourceCentroid, spectrumBBox, dispersionRelation):
1016 """Perform the spectral extraction, given a source location and exp."""
1018 self.extraction.initialise(exp, sourceCentroid, spectrumBBox, dispersionRelation)
1020 # xxx this method currently doesn't return an object - fix this
1021 spectrum = self.extraction.getFluxBasic()
1023 return spectrum
1025 def calcSpectrumBBox(self, exp, centroid, aperture, order='+1'):
1026 """Calculate the bbox for the spectrum, given the centroid.
1028 XXX Longer explanation here, inc. parameters
1029 TODO: Add support for order = "both"
1030 """
1031 extent = self.config.spectrumLengthPixels
1032 halfWidth = aperture//2
1033 translate_y = self.config.offsetFromMainStar
1034 sourceX = centroid[0]
1035 sourceY = centroid[1]
1037 if order == '-1':
1038 translate_y = - extent - self.config.offsetFromMainStar
1040 xStart = sourceX - halfWidth
1041 xEnd = sourceX + halfWidth - 1
1042 yStart = sourceY + translate_y
1043 yEnd = yStart + extent - 1
1045 xEnd = min(xEnd, exp.getWidth()-1)
1046 yEnd = min(yEnd, exp.getHeight()-1)
1047 yStart = max(yStart, 0)
1048 xStart = max(xStart, 0)
1049 assert (xEnd > xStart) and (yEnd > yStart)
1051 self.log.debug('(xStart, xEnd) = (%s, %s)'%(xStart, xEnd))
1052 self.log.debug('(yStart, yEnd) = (%s, %s)'%(yStart, yEnd))
1054 bbox = geom.Box2I(geom.Point2I(xStart, yStart), geom.Point2I(xEnd, yEnd))
1055 return bbox