23"""Perform a single fit cycle of FGCM.
25This task runs a single "fit cycle" of fgcm. Prior to running this task
26one must run both fgcmMakeLut (to construct the atmosphere and instrumental
27look-up-table) and fgcmBuildStars (to extract visits and star observations
30The fgcmFitCycle is meant to be run multiple times, and is tracked by the
31'cycleNumber'. After each run of the fit cycle, diagnostic plots should
32be inspected to set parameters for outlier rejection on the following
33cycle. Please see the fgcmcal Cookbook for details.
45from .utilities
import makeConfigDict, translateFgcmLut, translateVisitCatalog
46from .utilities
import extractReferenceMags
47from .utilities
import makeZptSchema, makeZptCat
48from .utilities
import makeAtmSchema, makeAtmCat, makeStdSchema, makeStdCat
49from .sedterms
import SedboundarytermDict, SedtermDict
50from .focalPlaneProjector
import FocalPlaneProjector
54__all__ = [
'FgcmFitCycleConfig',
'FgcmFitCycleTask']
56MULTIPLE_CYCLES_MAX = 10
60 dimensions=(
"instrument",),
61 defaultTemplates={
"previousCycleNumber":
"-1",
63 camera = connectionTypes.PrerequisiteInput(
64 doc=
"Camera instrument",
66 storageClass=
"Camera",
67 dimensions=(
"instrument",),
71 fgcmLookUpTable = connectionTypes.PrerequisiteInput(
72 doc=(
"Atmosphere + instrument look-up-table for FGCM throughput and "
73 "chromatic corrections."),
74 name=
"fgcmLookUpTable",
75 storageClass=
"Catalog",
76 dimensions=(
"instrument",),
80 fgcmVisitCatalog = connectionTypes.Input(
81 doc=
"Catalog of visit information for fgcm",
82 name=
"fgcmVisitCatalog",
83 storageClass=
"Catalog",
84 dimensions=(
"instrument",),
88 fgcmStarObservationsParquet = connectionTypes.Input(
89 doc=(
"Catalog of star observations for fgcm, in parquet format. "
90 "Used if useParquetCatalogFormat is True."),
91 name=
"fgcm_star_observations",
92 storageClass=
"ArrowAstropy",
93 dimensions=(
"instrument",),
97 fgcmStarIdsParquet = connectionTypes.Input(
98 doc=(
"Catalog of fgcm calibration star IDs, in parquet format. "
99 "Used if useParquetCatalogFormat is True."),
100 name=
"fgcm_star_ids",
101 storageClass=
"ArrowAstropy",
102 dimensions=(
"instrument",),
106 fgcmReferenceStarsParquet = connectionTypes.Input(
107 doc=(
"Catalog of fgcm-matched reference stars, in parquet format. "
108 "Used if useParquetCatalogFormat is True."),
109 name=
"fgcm_reference_stars",
110 storageClass=
"ArrowAstropy",
111 dimensions=(
"instrument",),
115 fgcmStarObservations = connectionTypes.Input(
116 doc=(
"Catalog of star observations for fgcm; old format. "
117 "Used if useParquetCatalogFormat is False."),
118 name=
"fgcmStarObservations",
119 storageClass=
"Catalog",
120 dimensions=(
"instrument",),
124 fgcmStarIds = connectionTypes.Input(
125 doc=(
"Catalog of fgcm calibration star IDs. "
126 "Used if useParquetCatalogFormat is False."),
128 storageClass=
"Catalog",
129 dimensions=(
"instrument",),
133 fgcmStarIndices = connectionTypes.Input(
134 doc=(
"Catalog of fgcm calibration star indices; old format."
135 "Used if useParquetCatalogFormat is False."),
136 name=
"fgcmStarIndices",
137 storageClass=
"Catalog",
138 dimensions=(
"instrument",),
142 fgcmReferenceStars = connectionTypes.Input(
143 doc=(
"Catalog of fgcm-matched reference stars; old format."
144 "Used if useParquetCatalogFormat is False."),
145 name=
"fgcmReferenceStars",
146 storageClass=
"Catalog",
147 dimensions=(
"instrument",),
151 def __init__(self, *, config=None):
152 super().__init__(config=config)
157 if str(int(config.connections.cycleNumber)) != config.connections.cycleNumber:
158 raise ValueError(
"cycleNumber must be of integer format")
159 if str(int(config.connections.previousCycleNumber)) != config.connections.previousCycleNumber:
160 raise ValueError(
"previousCycleNumber must be of integer format")
164 if int(config.connections.previousCycleNumber) != (int(config.connections.cycleNumber) - 1):
165 raise ValueError(
"previousCycleNumber must be 1 less than cycleNumber")
167 instDims = (
"instrument",)
168 bandDims = (
"instrument",
"band")
169 filterDims = (
"instrument",
"physical_filter")
170 filterDetectorDims = (
"instrument",
"physical_filter",
"detector")
172 inputAndOutputConnections = [
173 (
"FitParameters",
"Catalog",
"Catalog of fgcm fit parameters.", instDims),
174 (
"FlaggedStars",
"Catalog",
"Catalog of flagged stars for fgcm calibration.", instDims),
176 multicycleOutputConnections = [
177 (
"OutputConfig",
"Config",
"Configuration for next fgcm fit cycle.", instDims),
179 optionalZpOutputConnections = [
180 (
"Zeropoints",
"Catalog",
"Catalog of fgcm zeropoint data.", instDims),
181 (
"AtmosphereParameters",
"Catalog",
"Catalog of atmospheric fit parameters.", instDims),
183 optionalStarOutputConnections = [
184 (
"StandardStars",
"SimpleCatalog",
"Catalog of standard star magnitudes.", instDims),
187 epochs = [f
"epoch{i}" for i
in range(len(config.epochMjds))]
191 (
"Zeropoints_Plot",
"Plot",
"Plot of fgcm zeropoints.", instDims),
194 "Plot of gray term per exposure per time for deep fields.",
196 (
"NightlyAlpha_Plot",
"Plot",
"Plot of nightly AOD alpha term.", instDims),
197 (
"NightlyTau_Plot",
"Plot",
"Plot of nightly aerosol optical depth (tau).", instDims),
198 (
"NightlyPwv_Plot",
"Plot",
"Plot of nightly water vapor.", instDims),
199 (
"NightlyO3_Plot",
"Plot",
"Plot of nightly ozone.", instDims),
200 (
"FilterOffsets_Plot",
"Plot",
"Plot of in-band filter offsets.", instDims),
201 (
"AbsThroughputs_Plot",
"Plot",
"Plot of absolute throughput fractions.", instDims),
202 (
"QESysWashesInitial_Plot",
"Plot",
"Plot of initial system QE with mirror washes.", instDims),
203 (
"QESysWashesFinal_Plot",
"Plot",
"Plot of final system QE with mirror washes.", instDims),
204 (
"RpwvVsRpwvInput_Plot",
206 "Plot of change in per-visit ``retrieved`` PWV from previous fit cycle.",
208 (
"RpwvVsRpwvSmooth_Plot",
210 "Plot of per-visit ``retrieved`` PWV vs. smoothed PWV.",
212 (
"ModelPwvVsRpwv_Plot",
214 "Plot of model PWV vs. per-visit ``retrieved`` PWV.",
218 "Plot of chisq as a function of iteration.",
222 plotConnections.extend(
224 (
"Apercorr_Plot",
"Plot",
"Plot of fgcm aperture corrections.", bandDims),
225 (
"EpsilonGlobal_Plot",
227 "Plot of global background over/undersubtraction.",
231 "Map of spatially varying background over/undersubtraction.",
233 (
"ExpgrayInitial_Plot",
235 "Histogram of initial gray term per exposure.",
237 (
"CompareRedblueExpgray_Plot",
239 "Plot of red/blue split gray term per exposure",
241 (
"Expgray_Plot",
"Plot",
"Histogram of gray term per exposure.", bandDims),
242 (
"ExpgrayAirmass_Plot",
244 "Plot of exposure gray term as a function of airmass.",
246 (
"ExpgrayCompareMjdRedblue_Plot",
248 "Plot of red/blue split gray term per exposure as a function of time.",
252 "Plot of grey term per exposure as a function of time of night.",
254 (
"ExpgrayCompareBands_Plot",
256 "Plot of gray term per exposure between bands nearby in time.",
258 (
"ExpgrayReference_Plot",
260 "Histogram of gray term per exposure compared to reference mags.",
262 (
"QESysRefstarsStdInitial_Plot",
264 "Plot of reference mag - calibrated (standard) mag vs. time (before fit).",
266 (
"QESysRefstarsStdFinal_Plot",
268 "Plot of reference mag - calibrated (standard) mag vs. time (after fit).",
270 (
"QESysRefstarsObsInitial_Plot",
272 "Plot of reference mag - observed (instrumental) mag vs. time (before fit).",
274 (
"QESysRefstarsObsFinal_Plot",
276 "Plot of reference mag - observed (instrumental) mag vs. time (after fit).",
278 (
"ModelMagerrInitial_Plot",
280 "Plots for magnitude error model, initial estimate.",
282 (
"ModelMagerrPostfit_Plot",
284 "Plots for magnitude error model, after fitting.",
286 (
"SigmaFgcmAllStars_Plot",
288 "Histograms for intrinsic scatter for all bright stars.",
290 (
"SigmaFgcmReservedStars_Plot",
292 "Histograms for intrinsic scatter for reserved bright stars.",
294 (
"SigmaFgcmReservedStarsCrunched_Plot",
296 "Histograms for intrinsic scatter for reserved bright stars (after gray correction).",
298 (
"SigmaFgcmPullsAllStars_Plot",
300 "Histograms for pulls for all bright stars.",
302 (
"SigmaFgcmPullsReservedStars_Plot",
304 "Histograms for pulls for reserved bright stars.",
306 (
"SigmaFgcmPullsReservedStarsCrunched_Plot",
308 "Histograms for pulls for reserved bright stars (after gray correction).",
312 "Plot showing scatter as a function of systematic error floor.",
316 "Histograms of scatter with respect to reference stars.",
318 (
"RefResidVsColorAll_Plot",
320 "Plot of reference star residuals vs. color (all stars).",
322 (
"RefResidVsColorCut_Plot",
324 "Plot of reference star residuals vs. color (reference star color cuts).",
329 plotConnections.extend(
331 (
"I1R1_Plot",
"Plot",
"Plot of fgcm R1 vs. I1.", filterDims),
332 (
"I1_Plot",
"Plot",
"Focal plane map of fgcm I1.", filterDims),
333 (
"R1_Plot",
"Plot",
"Focal plane map of fgcm R1.", filterDims),
334 (
"R1mI1Matchscale_Plot",
"Plot",
"Focal plane map of fgcm R1 - I1.", filterDims),
335 (
"R1mI1_Plot",
"Plot",
"Focal plane map of fgcm R1 - I1 (rescaled).", filterDims),
336 (
"R1mI1_vs_mjd_Plot",
"Plot",
"R1 - I1 residuals vs. mjd.", filterDims),
337 (
"CompareRedblueMirrorchrom_Plot",
339 "Comparison of mirror chromaticity residuals for red/blue stars.",
341 (
"CcdChromaticity_Plot",
343 "Focal plane map of fgcm ccd chromaticity.",
345 (
"EpsilonDetector_Plot",
347 "Focal plane map of background over/undersubtraction.",
349 (
"EpsilonDetectorMatchscale_Plot",
351 "Focal plane map of background over/undersubtraction.",
356 plotConnections.extend(
359 f
"Superstar_{epoch}_Plot",
361 "Plot of illumination Correction.",
366 if self.config.superStarPlotCcdResiduals:
367 plotConnections.extend(
370 f
"SuperstarResidual_{epoch}_Plot",
372 "Binned illumination correction residuals.",
376 f
"SuperstarResidualStd_{epoch}_Plot",
378 "Binned illumination correction residual stdev.",
384 if config.doMultipleCycles:
388 for cycle
in range(config.multipleCyclesFinalCycleNumber):
389 outputConnections = copy.copy(inputAndOutputConnections)
390 outputConnections.extend(multicycleOutputConnections)
391 if config.outputZeropointsBeforeFinalCycle:
392 outputConnections.extend(optionalZpOutputConnections)
393 if config.outputStandardsBeforeFinalCycle:
394 outputConnections.extend(optionalStarOutputConnections)
402 if cycle == (config.multipleCyclesFinalCycleNumber - 1) \
403 or config.doPlotsBeforeFinalCycles:
404 outputConnections.extend(plotConnections)
406 for (name, storageClass, doc, dims)
in outputConnections:
407 connectionName = f
"fgcm_Cycle{cycle}_{name}"
408 storageName = connectionName
409 outConnection = connectionTypes.Output(
411 storageClass=storageClass,
414 multiple=(len(dims) > 1),
416 setattr(self, connectionName, outConnection)
419 outputConnections = copy.copy(inputAndOutputConnections)
420 outputConnections.extend(multicycleOutputConnections)
421 outputConnections.extend(optionalZpOutputConnections)
422 outputConnections.extend(optionalStarOutputConnections)
424 outputConnections.extend(plotConnections)
425 for (name, storageClass, doc, dims)
in outputConnections:
426 connectionName = f
"fgcm_Cycle{config.multipleCyclesFinalCycleNumber}_{name}"
427 storageName = connectionName
428 outConnection = connectionTypes.Output(
430 storageClass=storageClass,
433 multiple=(len(dims) > 1),
435 setattr(self, connectionName, outConnection)
438 if config.cycleNumber > 0:
439 inputConnections = copy.copy(inputAndOutputConnections)
441 inputConnections = []
442 outputConnections = copy.copy(inputAndOutputConnections)
447 if config.isFinalCycle
or config.outputZeropointsBeforeFinalCycle:
448 outputConnections.extend(optionalZpOutputConnections)
449 if config.isFinalCycle
or config.outputStandardsBeforeFinalCycle:
450 outputConnections.extend(optionalStarOutputConnections)
453 outputConnections.extend(plotConnections)
455 for (name, storageClass, doc, dims)
in inputConnections:
456 connectionName = f
"fgcm{name}Input"
457 storageName = f
"fgcm_Cycle{config.cycleNumber - 1}_{name}"
458 inConnection = connectionTypes.PrerequisiteInput(
460 storageClass=storageClass,
464 setattr(self, connectionName, inConnection)
466 for (name, storageClass, doc, dims)
in outputConnections:
467 connectionName = f
"fgcm{name}"
468 storageName = f
"fgcm_Cycle{config.cycleNumber}_{name}"
470 if storageClass ==
"Plot":
471 connectionName = storageName
472 outConnection = connectionTypes.Output(
474 storageClass=storageClass,
477 multiple=(len(dims) > 1),
479 setattr(self, connectionName, outConnection)
481 if not config.doReferenceCalibration:
482 self.inputs.remove(
"fgcmReferenceStars")
483 self.inputs.remove(
"fgcmReferenceStarsParquet")
485 if config.useParquetCatalogFormat:
486 self.inputs.remove(
"fgcmStarObservations")
487 self.inputs.remove(
"fgcmStarIds")
488 self.inputs.remove(
"fgcmStarIndices")
489 if config.doReferenceCalibration:
490 self.inputs.remove(
"fgcmReferenceStars")
492 self.inputs.remove(
"fgcmStarObservationsParquet")
493 self.inputs.remove(
"fgcmStarIdsParquet")
494 if config.doReferenceCalibration:
495 self.inputs.remove(
"fgcmReferenceStarsParquet")
498class FgcmFitCycleConfig(pipeBase.PipelineTaskConfig,
499 pipelineConnections=FgcmFitCycleConnections):
500 """Config for FgcmFitCycle"""
502 doMultipleCycles = pexConfig.Field(
503 doc=
"Run multiple fit cycles in one task",
507 useParquetCatalogFormat = pexConfig.Field(
508 doc=
"Use parquet catalog format?",
512 multipleCyclesFinalCycleNumber = pexConfig.RangeField(
513 doc=(
"Final cycle number in multiple cycle mode. The initial cycle "
514 "is 0, with limited parameters fit. The next cycle is 1 with "
515 "full parameter fit. The final cycle is a clean-up with no "
516 "parameters fit. There will be a total of "
517 "(multipleCycleFinalCycleNumber + 1) cycles run, and the final "
518 "cycle number cannot be less than 2."),
522 max=MULTIPLE_CYCLES_MAX,
525 bands = pexConfig.ListField(
526 doc=
"Bands to run calibration",
530 fitBands = pexConfig.ListField(
531 doc=(
"Bands to use in atmospheric fit. The bands not listed here will have "
532 "the atmosphere constrained from the 'fitBands' on the same night. "
533 "Must be a subset of `config.bands`"),
537 requiredBands = pexConfig.ListField(
538 doc=(
"Bands that are required for a star to be considered a calibration star. "
539 "Must be a subset of `config.bands`"),
543 physicalFilterMap = pexConfig.DictField(
544 doc=
"Mapping from 'physicalFilter' to band.",
549 doReferenceCalibration = pexConfig.Field(
550 doc=
"Use reference catalog as additional constraint on calibration",
554 refStarSnMin = pexConfig.Field(
555 doc=
"Reference star signal-to-noise minimum to use in calibration. Set to <=0 for no cut.",
559 refStarOutlierNSig = pexConfig.Field(
560 doc=(
"Number of sigma compared to average mag for reference star to be considered an outlier. "
561 "Computed per-band, and if it is an outlier in any band it is rejected from fits."),
565 applyRefStarColorCuts = pexConfig.Field(
566 doc=(
"Apply color cuts defined in ``starColorCuts`` to reference stars? "
567 "These cuts are in addition to any cuts defined in ``refStarColorCuts``"),
571 refStarMaxFracUse = pexConfig.Field(
572 doc=(
"Maximum fraction of reference stars to use in the fit. Remainder will "
573 "be used only for validation."),
577 useExposureReferenceOffset = pexConfig.Field(
578 doc=(
"Use per-exposure (visit) offsets between calibrated stars and reference stars "
579 "for final zeropoints? This may help uniformity for disjoint surveys."),
583 nCore = pexConfig.Field(
584 doc=
"Number of cores to use",
587 deprecated=
"Number of cores is deprecated as a config, and will be removed after v27. "
588 "Please use ``pipetask run --cores-per-quantum`` instead.",
590 nStarPerRun = pexConfig.Field(
591 doc=
"Number of stars to run in each chunk",
595 nExpPerRun = pexConfig.Field(
596 doc=
"Number of exposures to run in each chunk",
600 reserveFraction = pexConfig.Field(
601 doc=
"Fraction of stars to reserve for testing",
605 freezeStdAtmosphere = pexConfig.Field(
606 doc=
"Freeze atmosphere parameters to standard (for testing)",
610 precomputeSuperStarInitialCycle = pexConfig.Field(
611 doc=
"Precompute superstar flat for initial cycle",
615 superStarSubCcdDict = pexConfig.DictField(
616 doc=(
"Per-band specification on whether to compute superstar flat on sub-ccd scale. "
617 "Must have one entry per band."),
622 superStarSubCcdChebyshevOrder = pexConfig.Field(
623 doc=(
"Order of the 2D chebyshev polynomials for sub-ccd superstar fit. "
624 "Global default is first-order polynomials, and should be overridden "
625 "on a camera-by-camera basis depending on the ISR."),
629 superStarSubCcdTriangular = pexConfig.Field(
630 doc=(
"Should the sub-ccd superstar chebyshev matrix be triangular to "
631 "suppress high-order cross terms?"),
635 superStarSigmaClip = pexConfig.Field(
636 doc=
"Number of sigma to clip outliers when selecting for superstar flats",
640 superStarPlotCcdResiduals = pexConfig.Field(
641 doc=
"If plotting is enabled, should per-detector residuals be plotted? "
642 "This may produce a lot of output, and should be used only for "
643 "debugging purposes.",
647 superStarForceZeroMean = pexConfig.Field(
648 doc=
"When computing the super-star flat, force the focal-plane mean to "
649 "zero (per band)? This should only be used when computing stand-alone "
650 "illumination corrections.",
654 focalPlaneSigmaClip = pexConfig.Field(
655 doc=
"Number of sigma to clip outliers per focal-plane.",
659 ccdGraySubCcdDict = pexConfig.DictField(
660 doc=(
"Per-band specification on whether to compute achromatic per-ccd residual "
661 "('ccd gray') on a sub-ccd scale."),
666 ccdGraySubCcdChebyshevOrder = pexConfig.Field(
667 doc=
"Order of the 2D chebyshev polynomials for sub-ccd gray fit.",
671 ccdGraySubCcdTriangular = pexConfig.Field(
672 doc=(
"Should the sub-ccd gray chebyshev matrix be triangular to "
673 "suppress high-order cross terms?"),
677 ccdGrayFocalPlaneDict = pexConfig.DictField(
678 doc=(
"Per-band specification on whether to compute focal-plane residual "
679 "('ccd gray') corrections."),
684 ccdGrayFocalPlaneFitMinCcd = pexConfig.Field(
685 doc=(
"Minimum number of 'good' CCDs required to perform focal-plane "
686 "gray corrections. If there are fewer good CCDs then the gray "
687 "correction is computed per-ccd."),
691 ccdGrayFocalPlaneChebyshevOrder = pexConfig.Field(
692 doc=
"Order of the 2D chebyshev polynomials for focal plane fit.",
696 ccdGrayFocalPlaneMaxStars = pexConfig.Field(
697 doc=
"Maximum number of stars to use for focal plane fit. Required to keep "
698 "matrix memory usage from running away. If there are more stars than "
699 "this then they will be down-sampled.",
703 cycleNumber = pexConfig.Field(
704 doc=(
"FGCM fit cycle number. This is automatically incremented after each run "
705 "and stage of outlier rejection. See cookbook for details."),
709 isFinalCycle = pexConfig.Field(
710 doc=(
"Is this the final cycle of the fitting? Will automatically compute final "
711 "selection of stars and photometric exposures, and will output zeropoints "
712 "and standard stars for use in fgcmOutputProducts"),
716 maxIterBeforeFinalCycle = pexConfig.Field(
717 doc=(
"Maximum fit iterations, prior to final cycle. The number of iterations "
718 "will always be 0 in the final cycle for cleanup and final selection."),
722 deltaMagBkgOffsetPercentile = pexConfig.Field(
723 doc=(
"Percentile brightest stars on a visit/ccd to use to compute net "
724 "offset from local background subtraction."),
728 deltaMagBkgPerCcd = pexConfig.Field(
729 doc=(
"Compute net offset from local background subtraction per-ccd? "
730 "Otherwise, use computation per visit."),
734 utBoundary = pexConfig.Field(
735 doc=
"Boundary (in UTC) from day-to-day",
739 washMjds = pexConfig.ListField(
740 doc=
"Mirror wash MJDs",
744 epochMjds = pexConfig.ListField(
745 doc=
"Epoch boundaries in MJD",
749 minObsPerBand = pexConfig.Field(
750 doc=
"Minimum good observations per band",
756 latitude = pexConfig.Field(
757 doc=
"Observatory latitude",
761 mirrorArea = pexConfig.Field(
762 doc=
"Mirror area (square meters) of telescope. If not set, will "
763 "try to estimate from camera.telescopeDiameter.",
768 cameraGain = pexConfig.Field(
769 doc=
"Average camera gain. If not set, will use the median of the "
770 "camera model/detector/amplifier gains.",
775 defaultCameraOrientation = pexConfig.Field(
776 doc=
"Default camera orientation for QA plots.",
780 brightObsGrayMax = pexConfig.Field(
781 doc=
"Maximum gray extinction to be considered bright observation",
785 minStarPerCcd = pexConfig.Field(
786 doc=(
"Minimum number of good stars per CCD to be used in calibration fit. "
787 "CCDs with fewer stars will have their calibration estimated from other "
788 "CCDs in the same visit, with zeropoint error increased accordingly."),
792 minCcdPerExp = pexConfig.Field(
793 doc=(
"Minimum number of good CCDs per exposure/visit to be used in calibration fit. "
794 "Visits with fewer good CCDs will have CCD zeropoints estimated where possible."),
798 maxCcdGrayErr = pexConfig.Field(
799 doc=
"Maximum error on CCD gray offset to be considered photometric",
803 minStarPerExp = pexConfig.Field(
804 doc=(
"Minimum number of good stars per exposure/visit to be used in calibration fit. "
805 "Visits with fewer good stars will have CCD zeropoints estimated where possible."),
809 minExpPerNight = pexConfig.Field(
810 doc=
"Minimum number of good exposures/visits to consider a partly photometric night",
814 expGrayInitialCut = pexConfig.Field(
815 doc=(
"Maximum exposure/visit gray value for initial selection of possible photometric "
820 expFwhmCutDict = pexConfig.DictField(
821 doc=(
"Per-band specification on maximum exposure FWHM (arcseconds) that will "
822 "be considered for the model fit. Exposures with median FWHM larger "
823 "than this threshold will get zeropoints based on matching to good "
829 expGrayPhotometricCutDict = pexConfig.DictField(
830 doc=(
"Per-band specification on maximum (negative) achromatic exposure residual "
831 "('gray term') for a visit to be considered photometric. Must have one "
832 "entry per band. Broad-band filters should be -0.05."),
837 expGrayHighCutDict = pexConfig.DictField(
838 doc=(
"Per-band specification on maximum (positive) achromatic exposure residual "
839 "('gray term') for a visit to be considered photometric. Must have one "
840 "entry per band. Broad-band filters should be 0.2."),
845 expGrayRecoverCut = pexConfig.Field(
846 doc=(
"Maximum (negative) exposure gray to be able to recover bad ccds via interpolation. "
847 "Visits with more gray extinction will only get CCD zeropoints if there are "
848 "sufficient star observations (minStarPerCcd) on that CCD."),
852 expVarGrayPhotometricCutDict = pexConfig.DictField(
853 doc=(
"Per-band specification on maximum exposure variance to be considered possibly "
854 "photometric. Must have one entry per band. Broad-band filters should be "
860 expGrayErrRecoverCut = pexConfig.Field(
861 doc=(
"Maximum exposure gray error to be able to recover bad ccds via interpolation. "
862 "Visits with more gray variance will only get CCD zeropoints if there are "
863 "sufficient star observations (minStarPerCcd) on that CCD."),
867 aperCorrPerCcd = pexConfig.Field(
868 doc=
"Use aperture corrections per-ccd (detector) instead of per-visit?",
872 aperCorrFitNBins = pexConfig.Field(
873 doc=(
"Number of aperture bins used in aperture correction fit. When set to 0"
874 "no fit will be performed, and the config.aperCorrInputSlopes will be "
875 "used if available."),
879 aperCorrInputSlopeDict = pexConfig.DictField(
880 doc=(
"Per-band specification of aperture correction input slope parameters. These "
881 "are used on the first fit iteration, and aperture correction parameters will "
882 "be updated from the data if config.aperCorrFitNBins > 0. It is recommended "
883 "to set this when there is insufficient data to fit the parameters (e.g. "
889 sedboundaryterms = pexConfig.ConfigField(
890 doc=
"Mapping from bands to SED boundary term names used is sedterms.",
891 dtype=SedboundarytermDict,
893 sedterms = pexConfig.ConfigField(
894 doc=
"Mapping from terms to bands for fgcm linear SED approximations.",
897 sigFgcmMaxErr = pexConfig.Field(
898 doc=
"Maximum mag error for fitting sigma_FGCM",
902 sigFgcmMaxEGrayDict = pexConfig.DictField(
903 doc=(
"Per-band specification for maximum (absolute) achromatic residual (gray value) "
904 "for observations in sigma_fgcm (raw repeatability). Broad-band filters "
910 ccdGrayMaxStarErr = pexConfig.Field(
911 doc=(
"Maximum error on a star observation to use in ccd gray (achromatic residual) "
916 approxThroughputDict = pexConfig.DictField(
917 doc=(
"Per-band specification of the approximate overall throughput at the start of "
918 "calibration observations. Must have one entry per band. Typically should "
924 sigmaCalRange = pexConfig.ListField(
925 doc=
"Allowed range for systematic error floor estimation",
927 default=(0.001, 0.003),
929 sigmaCalFitPercentile = pexConfig.ListField(
930 doc=
"Magnitude percentile range to fit systematic error floor",
932 default=(0.05, 0.15),
934 sigmaCalPlotPercentile = pexConfig.ListField(
935 doc=
"Magnitude percentile range to plot systematic error floor",
937 default=(0.05, 0.95),
939 sigma0Phot = pexConfig.Field(
940 doc=
"Systematic error floor for all zeropoints",
944 mapLongitudeRef = pexConfig.Field(
945 doc=
"Reference longitude for plotting maps",
949 mapNSide = pexConfig.Field(
950 doc=
"Healpix nside for plotting maps",
954 outfileBase = pexConfig.Field(
955 doc=
"Filename start for plot output files",
959 starColorCuts = pexConfig.ListField(
960 doc=(
"Encoded star-color cuts (using calibration star colors). "
961 "This is a list with each entry a string of the format "
962 "``band1,band2,low,high`` such that only stars of color "
963 "low < band1 - band2 < high will be used for calibration."),
965 default=(
"NO_DATA",),
967 refStarColorCuts = pexConfig.ListField(
968 doc=(
"Encoded star color cuts specifically to apply to reference stars. "
969 "This is a list with each entry a string of the format "
970 "``band1,band2,low,high`` such that only stars of color "
971 "low < band1 - band2 < high will be used as reference stars."),
973 default=(
"NO_DATA",),
975 colorSplitBands = pexConfig.ListField(
976 doc=
"Band names to use to split stars by color. Must have 2 entries.",
981 modelMagErrors = pexConfig.Field(
982 doc=
"Should FGCM model the magnitude errors from sky/fwhm? (False means trust inputs)",
986 useQuadraticPwv = pexConfig.Field(
987 doc=
"Model PWV with a quadratic term for variation through the night?",
991 instrumentParsPerBand = pexConfig.Field(
992 doc=(
"Model instrumental parameters per band? "
993 "Otherwise, instrumental parameters (QE changes with time) are "
994 "shared among all bands."),
998 instrumentSlopeMinDeltaT = pexConfig.Field(
999 doc=(
"Minimum time change (in days) between observations to use in constraining "
1000 "instrument slope."),
1004 fitMirrorChromaticity = pexConfig.Field(
1005 doc=
"Fit (intraband) mirror chromatic term?",
1009 fitCcdChromaticityDict = pexConfig.DictField(
1010 doc=
"Specification on whether to compute first-order quantum efficiency (QE) "
1011 "adjustments. Key is band, and value will be True or False. Any band "
1012 "not explicitly specified will default to False.",
1017 coatingMjds = pexConfig.ListField(
1018 doc=
"Mirror coating dates in MJD",
1022 outputStandardsBeforeFinalCycle = pexConfig.Field(
1023 doc=
"Output standard stars prior to final cycle? Used in debugging.",
1027 outputZeropointsBeforeFinalCycle = pexConfig.Field(
1028 doc=
"Output standard stars prior to final cycle? Used in debugging.",
1032 useRepeatabilityForExpGrayCutsDict = pexConfig.DictField(
1033 doc=(
"Per-band specification on whether to use star repeatability (instead of exposures) "
1034 "for computing photometric cuts. Recommended for tract mode or bands with few visits."),
1039 autoPhotometricCutNSig = pexConfig.Field(
1040 doc=(
"Number of sigma for automatic computation of (low) photometric cut. "
1041 "Cut is based on exposure gray width (per band), unless "
1042 "useRepeatabilityForExpGrayCuts is set, in which case the star "
1043 "repeatability is used (also per band)."),
1047 autoHighCutNSig = pexConfig.Field(
1048 doc=(
"Number of sigma for automatic computation of (high) outlier cut. "
1049 "Cut is based on exposure gray width (per band), unless "
1050 "useRepeatabilityForExpGrayCuts is set, in which case the star "
1051 "repeatability is used (also per band)."),
1055 quietMode = pexConfig.Field(
1056 doc=
"Be less verbose with logging.",
1060 doPlots = pexConfig.Field(
1061 doc=
"Make fgcm QA plots.",
1065 doPlotsBeforeFinalCycles = pexConfig.Field(
1066 doc=
"Make fgcm QA plots before the final two fit cycles? This only applies in"
1067 "multi-cycle mode, and if doPlots is True. These are typically the most"
1068 "important QA plots to inspect.",
1072 randomSeed = pexConfig.Field(
1073 doc=
"Random seed for fgcm for consistency in tests.",
1078 deltaAperFitMinNgoodObs = pexConfig.Field(
1079 doc=
"Minimum number of good observations to use mean delta-aper values in fits.",
1083 deltaAperFitPerCcdNx = pexConfig.Field(
1084 doc=(
"Number of x bins per ccd when computing delta-aper background offsets. "
1085 "Only used when ``doComputeDeltaAperPerCcd`` is True."),
1089 deltaAperFitPerCcdNy = pexConfig.Field(
1090 doc=(
"Number of y bins per ccd when computing delta-aper background offsets. "
1091 "Only used when ``doComputeDeltaAperPerCcd`` is True."),
1095 deltaAperFitSpatialNside = pexConfig.Field(
1096 doc=
"Healpix nside to compute spatial delta-aper background offset maps.",
1100 deltaAperInnerRadiusArcsec = pexConfig.Field(
1101 doc=(
"Inner radius used to compute deltaMagAper (arcseconds). "
1102 "Must be positive and less than ``deltaAperOuterRadiusArcsec`` if "
1103 "any of ``doComputeDeltaAperPerVisit``, ``doComputeDeltaAperPerStar``, "
1104 "``doComputeDeltaAperMap``, ``doComputeDeltaAperPerCcd`` are set."),
1108 deltaAperOuterRadiusArcsec = pexConfig.Field(
1109 doc=(
"Outer radius used to compute deltaMagAper (arcseconds). "
1110 "Must be positive and greater than ``deltaAperInnerRadiusArcsec`` if "
1111 "any of ``doComputeDeltaAperPerVisit``, ``doComputeDeltaAperPerStar``, "
1112 "``doComputeDeltaAperMap``, ``doComputeDeltaAperPerCcd`` are set."),
1116 doComputeDeltaAperPerVisit = pexConfig.Field(
1117 doc=(
"Do the computation of delta-aper background offsets per visit? "
1118 "Note: this option can be very slow when there are many visits."),
1122 doComputeDeltaAperPerStar = pexConfig.Field(
1123 doc=
"Do the computation of delta-aper mean values per star?",
1127 doComputeDeltaAperMap = pexConfig.Field(
1128 doc=(
"Do the computation of delta-aper spatial maps? "
1129 "This is only used if ``doComputeDeltaAperPerStar`` is True,"),
1133 doComputeDeltaAperPerCcd = pexConfig.Field(
1134 doc=
"Do the computation of per-ccd delta-aper background offsets?",
1142 if self.connections.previousCycleNumber != str(self.cycleNumber - 1):
1143 msg =
"cycleNumber in template must be connections.previousCycleNumber + 1"
1144 raise RuntimeError(msg)
1145 if self.connections.cycleNumber != str(self.cycleNumber):
1146 msg =
"cycleNumber in template must be equal to connections.cycleNumber"
1147 raise RuntimeError(msg)
1149 for band
in self.fitBands:
1150 if band
not in self.bands:
1151 msg =
'fitBand %s not in bands' % (band)
1152 raise pexConfig.FieldValidationError(FgcmFitCycleConfig.fitBands, self, msg)
1153 for band
in self.requiredBands:
1154 if band
not in self.bands:
1155 msg =
'requiredBand %s not in bands' % (band)
1156 raise pexConfig.FieldValidationError(FgcmFitCycleConfig.requiredBands, self, msg)
1157 for band
in self.colorSplitBands:
1158 if band
not in self.bands:
1159 msg =
'colorSplitBand %s not in bands' % (band)
1160 raise pexConfig.FieldValidationError(FgcmFitCycleConfig.colorSplitBands, self, msg)
1161 for band
in self.bands:
1162 if band
not in self.superStarSubCcdDict:
1163 msg =
'band %s not in superStarSubCcdDict' % (band)
1164 raise pexConfig.FieldValidationError(FgcmFitCycleConfig.superStarSubCcdDict,
1166 if band
not in self.ccdGraySubCcdDict:
1167 msg =
'band %s not in ccdGraySubCcdDict' % (band)
1168 raise pexConfig.FieldValidationError(FgcmFitCycleConfig.ccdGraySubCcdDict,
1170 if band
not in self.expGrayPhotometricCutDict:
1171 msg =
'band %s not in expGrayPhotometricCutDict' % (band)
1172 raise pexConfig.FieldValidationError(FgcmFitCycleConfig.expGrayPhotometricCutDict,
1174 if band
not in self.expGrayHighCutDict:
1175 msg =
'band %s not in expGrayHighCutDict' % (band)
1176 raise pexConfig.FieldValidationError(FgcmFitCycleConfig.expGrayHighCutDict,
1178 if band
not in self.expVarGrayPhotometricCutDict:
1179 msg =
'band %s not in expVarGrayPhotometricCutDict' % (band)
1180 raise pexConfig.FieldValidationError(FgcmFitCycleConfig.expVarGrayPhotometricCutDict,
1182 if band
not in self.sigFgcmMaxEGrayDict:
1183 msg =
'band %s not in sigFgcmMaxEGrayDict' % (band)
1184 raise pexConfig.FieldValidationError(FgcmFitCycleConfig.sigFgcmMaxEGrayDict,
1186 if band
not in self.approxThroughputDict:
1187 msg =
'band %s not in approxThroughputDict' % (band)
1188 raise pexConfig.FieldValidationError(FgcmFitCycleConfig.approxThroughputDict,
1190 if band
not in self.useRepeatabilityForExpGrayCutsDict:
1191 msg =
'band %s not in useRepeatabilityForExpGrayCutsDict' % (band)
1192 raise pexConfig.FieldValidationError(FgcmFitCycleConfig.useRepeatabilityForExpGrayCutsDict,
1195 if self.doComputeDeltaAperPerVisit
or self.doComputeDeltaAperMap \
1196 or self.doComputeDeltaAperPerCcd:
1197 if self.deltaAperInnerRadiusArcsec <= 0.0:
1198 msg =
'deltaAperInnerRadiusArcsec must be positive if deltaAper computations are turned on.'
1199 raise pexConfig.FieldValidationError(FgcmFitCycleConfig.deltaAperInnerRadiusArcsec,
1201 if self.deltaAperOuterRadiusArcsec <= 0.0:
1202 msg =
'deltaAperOuterRadiusArcsec must be positive if deltaAper computations are turned on.'
1203 raise pexConfig.FieldValidationError(FgcmFitCycleConfig.deltaAperOuterRadiusArcsec,
1205 if self.deltaAperOuterRadiusArcsec <= self.deltaAperInnerRadiusArcsec:
1206 msg = (
'deltaAperOuterRadiusArcsec must be greater than deltaAperInnerRadiusArcsec if '
1207 'deltaAper computations are turned on.')
1208 raise pexConfig.FieldValidationError(FgcmFitCycleConfig.deltaAperOuterRadiusArcsec,
1212class FgcmFitCycleTask(pipeBase.PipelineTask):
1214 Run Single fit cycle for FGCM global calibration
1217 ConfigClass = FgcmFitCycleConfig
1218 _DefaultName =
"fgcmFitCycle"
1220 def __init__(self, initInputs=None, **kwargs):
1221 super().__init__(**kwargs)
1223 def runQuantum(self, butlerQC, inputRefs, outputRefs):
1224 camera = butlerQC.get(inputRefs.camera)
1226 nCore = butlerQC.resources.num_cores
1230 handleDict[
'fgcmLookUpTable'] = butlerQC.get(inputRefs.fgcmLookUpTable)
1231 handleDict[
'fgcmVisitCatalog'] = butlerQC.get(inputRefs.fgcmVisitCatalog)
1233 if self.config.useParquetCatalogFormat:
1234 handleDict[
'fgcmStarObservations'] = butlerQC.get(inputRefs.fgcmStarObservationsParquet)
1235 handleDict[
'fgcmStarIds'] = butlerQC.get(inputRefs.fgcmStarIdsParquet)
1236 if self.config.doReferenceCalibration:
1237 handleDict[
'fgcmReferenceStars'] = butlerQC.get(inputRefs.fgcmReferenceStarsParquet)
1239 handleDict[
'fgcmStarObservations'] = butlerQC.get(inputRefs.fgcmStarObservations)
1240 handleDict[
'fgcmStarIds'] = butlerQC.get(inputRefs.fgcmStarIds)
1241 handleDict[
'fgcmStarIndices'] = butlerQC.get(inputRefs.fgcmStarIndices)
1242 if self.config.doReferenceCalibration:
1243 handleDict[
'fgcmReferenceStars'] = butlerQC.get(inputRefs.fgcmReferenceStars)
1244 if self.config.cycleNumber > 0:
1245 handleDict[
'fgcmFlaggedStars'] = butlerQC.get(inputRefs.fgcmFlaggedStarsInput)
1246 handleDict[
'fgcmFitParameters'] = butlerQC.get(inputRefs.fgcmFitParametersInput)
1248 fgcmDatasetDict =
None
1249 if self.config.doMultipleCycles:
1251 config = copy.copy(self.config)
1252 config.update(cycleNumber=0)
1253 for cycle
in range(self.config.multipleCyclesFinalCycleNumber + 1):
1254 if cycle == self.config.multipleCyclesFinalCycleNumber:
1255 config.update(isFinalCycle=
True)
1258 handleDict[
'fgcmFlaggedStars'] = fgcmDatasetDict[
'fgcmFlaggedStars']
1259 handleDict[
'fgcmFitParameters'] = fgcmDatasetDict[
'fgcmFitParameters']
1266 for outputRefName
in outputRefs.keys():
1267 if outputRefName.endswith(
"Plot")
and f
"Cycle{cycle}" in outputRefName:
1268 refs = getattr(outputRefs, outputRefName)
1269 if isinstance(refs, (tuple, list)):
1270 if "physical_filter" in refs[0].dimensions
and "detector" in refs[0].dimensions:
1272 physical_filter = ref.dataId[
"physical_filter"]
1273 detector = ref.dataId[
"detector"]
1274 handleDictKey = f
"{outputRefName}_{physical_filter}_{detector}"
1275 plotHandleDict[handleDictKey] = ref
1276 elif "physical_filter" in refs[0].dimensions:
1278 handleDictKey = f
"{outputRefName}_{ref.dataId['physical_filter']}"
1279 plotHandleDict[handleDictKey] = ref
1280 elif "band" in refs[0].dimensions:
1282 handleDictKey = f
"{outputRefName}_{ref.dataId['band']}"
1283 plotHandleDict[handleDictKey] = ref
1285 plotHandleDict[outputRefName] = refs
1287 fgcmDatasetDict, config = self._fgcmFitCycle(
1291 plotHandleDict=plotHandleDict,
1295 butlerQC.put(fgcmDatasetDict[
'fgcmFitParameters'],
1296 getattr(outputRefs, f
'fgcm_Cycle{cycle}_FitParameters'))
1297 butlerQC.put(fgcmDatasetDict[
'fgcmFlaggedStars'],
1298 getattr(outputRefs, f
'fgcm_Cycle{cycle}_FlaggedStars'))
1299 butlerQC.put(config,
1300 getattr(outputRefs, f
'fgcm_Cycle{cycle}_OutputConfig'))
1301 if self.outputZeropoints:
1302 butlerQC.put(fgcmDatasetDict[
'fgcmZeropoints'],
1303 getattr(outputRefs, f
'fgcm_Cycle{cycle}_Zeropoints'))
1304 butlerQC.put(fgcmDatasetDict[
'fgcmAtmosphereParameters'],
1305 getattr(outputRefs, f
'fgcm_Cycle{cycle}_AtmosphereParameters'))
1306 if self.outputStandards:
1307 butlerQC.put(fgcmDatasetDict[
'fgcmStandardStars'],
1308 getattr(outputRefs, f
'fgcm_Cycle{cycle}_StandardStars'))
1315 for outputRefName
in outputRefs.keys():
1316 if outputRefName.endswith(
"Plot")
and f
"Cycle{self.config.cycleNumber}" in outputRefName:
1317 refs = getattr(outputRefs, outputRefName)
1318 if isinstance(refs, (tuple, list)):
1319 if "physical_filter" in refs[0].dimensions
and "detector" in refs[0].dimensions:
1321 physical_filter = ref.dataId[
"physical_filter"]
1322 detector = ref.dataId[
"detector"]
1323 handleDictKey = f
"{outputRefName}_{physical_filter}_{detector}"
1324 plotHandleDict[handleDictKey] = ref
1325 elif "physical_filter" in refs[0].dimensions:
1327 handleDictKey = f
"{outputRefName}_{ref.dataId['physical_filter']}"
1328 plotHandleDict[handleDictKey] = ref
1329 elif "band" in refs[0].dimensions:
1331 handleDictKey = f
"{outputRefName}_{ref.dataId['band']}"
1332 plotHandleDict[handleDictKey] = ref
1334 plotHandleDict[outputRefName] = refs
1336 fgcmDatasetDict, _ = self._fgcmFitCycle(
1341 plotHandleDict=plotHandleDict,
1345 butlerQC.put(fgcmDatasetDict[
'fgcmFitParameters'], outputRefs.fgcmFitParameters)
1346 butlerQC.put(fgcmDatasetDict[
'fgcmFlaggedStars'], outputRefs.fgcmFlaggedStars)
1347 if self.outputZeropoints:
1348 butlerQC.put(fgcmDatasetDict[
'fgcmZeropoints'], outputRefs.fgcmZeropoints)
1349 butlerQC.put(fgcmDatasetDict[
'fgcmAtmosphereParameters'], outputRefs.fgcmAtmosphereParameters)
1350 if self.outputStandards:
1351 butlerQC.put(fgcmDatasetDict[
'fgcmStandardStars'], outputRefs.fgcmStandardStars)
1358 plotHandleDict=None,
1368 camera : `lsst.afw.cameraGeom.Camera`
1370 All handles are `lsst.daf.butler.DeferredDatasetHandle`
1371 handle dictionary with keys:
1373 ``"fgcmLookUpTable"``
1374 handle for the FGCM look-up table.
1375 ``"fgcmVisitCatalog"``
1376 handle for visit summary catalog.
1377 ``"fgcmStarObservations"``
1378 handle for star observation catalog.
1380 handle for star id catalog.
1381 ``"fgcmStarIndices"``
1382 handle for star index catalog.
1383 ``"fgcmReferenceStars"``
1384 handle for matched reference star catalog.
1385 ``"fgcmFlaggedStars"``
1386 handle for flagged star catalog.
1387 ``"fgcmFitParameters"``
1388 handle for fit parameter catalog.
1389 butlerQC : `lsst.pipe.base.QuantumContext`, optional
1390 Quantum context used for serializing plots.
1391 plotHandleDict : `dict` [`str`, `lsst.daf.butler.DatasetRef`], optional
1392 Dictionary of plot dataset refs, keyed by plot name.
1393 config : `lsst.pex.config.Config`, optional
1394 Configuration to use to override self.config.
1395 nCore : `int`, optional
1396 Number of cores to use during fitting.
1397 multiCycle : `bool`, optional
1398 Is this part of a multicycle run?
1402 fgcmDatasetDict : `dict`
1403 Dictionary of datasets to persist.
1405 if config
is not None:
1408 _config = self.config
1411 self.maxIter = _config.maxIterBeforeFinalCycle
1412 self.outputStandards = _config.outputStandardsBeforeFinalCycle
1413 self.outputZeropoints = _config.outputZeropointsBeforeFinalCycle
1414 self.resetFitParameters =
True
1416 if _config.isFinalCycle:
1421 self.outputStandards =
True
1422 self.outputZeropoints =
True
1423 self.resetFitParameters =
False
1425 lutCat = handleDict[
'fgcmLookUpTable'].get()
1426 fgcmLut, lutIndexVals, lutStd = translateFgcmLut(lutCat,
1427 dict(_config.physicalFilterMap))
1431 doPlots = _config.doPlots
1432 if doPlots
and multiCycle:
1433 if _config.cycleNumber < (_config.multipleCyclesFinalCycleNumber - 1) \
1434 and not _config.doPlotsBeforeFinalCycles:
1437 configDict = makeConfigDict(_config, self.log, camera,
1438 self.maxIter, self.resetFitParameters,
1439 self.outputZeropoints,
1440 lutIndexVals[0][
'FILTERNAMES'],
1445 visitCat = handleDict[
'fgcmVisitCatalog'].get()
1446 fgcmExpInfo = translateVisitCatalog(visitCat)
1449 if len(camera) == fgcmLut.nCCD:
1450 useScienceDetectors =
False
1455 useScienceDetectors =
True
1459 self.config.defaultCameraOrientation,
1460 useScienceDetectors=useScienceDetectors,
1463 noFitsDict = {
'lutIndex': lutIndexVals,
1465 'expInfo': fgcmExpInfo,
1466 'focalPlaneProjector': focalPlaneProjector}
1469 fgcmFitCycle = fgcm.FgcmFitCycle(
1472 noFitsDict=noFitsDict,
1475 plotHandleDict=plotHandleDict,
1479 if (fgcmFitCycle.initialCycle):
1481 fgcmPars = fgcm.FgcmParameters.newParsWithArrays(fgcmFitCycle.fgcmConfig,
1485 plotHandleDict=plotHandleDict)
1488 parCat = handleDict[
'fgcmFitParameters']
1490 parCat = handleDict[
'fgcmFitParameters'].get()
1491 inParInfo, inParams, inSuperStar = self._loadParameters(parCat)
1493 fgcmPars = fgcm.FgcmParameters.loadParsWithArrays(fgcmFitCycle.fgcmConfig,
1499 plotHandleDict=plotHandleDict)
1502 fgcmStars = fgcm.FgcmStars(fgcmFitCycle.fgcmConfig, butlerQC=butlerQC, plotHandleDict=plotHandleDict)
1504 starObs = handleDict[
'fgcmStarObservations'].get()
1505 starIds = handleDict[
'fgcmStarIds'].get()
1506 if not self.config.useParquetCatalogFormat:
1507 starIndices = handleDict[
'fgcmStarIndices'].get()
1512 if 'fgcmFlaggedStars' in handleDict:
1514 flaggedStars = handleDict[
'fgcmFlaggedStars']
1516 flaggedStars = handleDict[
'fgcmFlaggedStars'].get()
1517 flagId = flaggedStars[
'objId'][:]
1518 flagFlag = flaggedStars[
'objFlag'][:]
1521 elif self.config.useParquetCatalogFormat:
1527 (flagged,) = (starIds[
'obj_flag'] > 0).nonzero()
1528 flagId = starIds[
'fgcm_id'][flagged]
1529 flagFlag = starIds[
'obj_flag'][flagged]
1534 if _config.doReferenceCalibration:
1535 refStars = handleDict[
'fgcmReferenceStars'].get()
1537 refMag, refMagErr = extractReferenceMags(refStars,
1539 _config.physicalFilterMap)
1541 refId = refStars[
'fgcm_id'][:]
1551 if self.config.useParquetCatalogFormat:
1552 visitIndex = np.searchsorted(fgcmExpInfo[
'VISIT'], starObs[
'visit'])
1554 visitIndex = np.searchsorted(fgcmExpInfo[
'VISIT'], starObs[
'visit'][starIndices[
'obsIndex']])
1563 if self.config.useParquetCatalogFormat:
1566 fgcmStars.loadStars(fgcmPars,
1567 starObs[
'visit'][:],
1568 starObs[
'detector'][:],
1571 starObs[
'inst_mag'][:],
1572 starObs[
'inst_mag_err'][:],
1573 fgcmExpInfo[
'FILTERNAME'][visitIndex],
1574 starIds[
'fgcm_id'][:],
1577 starIds[
'obs_arr_index'][:],
1578 starIds[
'n_obs'][:],
1579 obsX=starObs[
'x'][:],
1580 obsY=starObs[
'y'][:],
1581 obsDeltaMagBkg=starObs[
'delta_mag_bkg'][:],
1582 obsDeltaAper=starObs[
'delta_mag_aper'][:],
1585 refMagErr=refMagErr,
1589 objIDAlternate=starIds[
'isolated_star_id'])
1594 conv = starObs[0][
'ra'].asDegrees() / float(starObs[0][
'ra'])
1596 fgcmStars.loadStars(fgcmPars,
1597 starObs[
'visit'][starIndices[
'obsIndex']],
1598 starObs[
'ccd'][starIndices[
'obsIndex']],
1599 starObs[
'ra'][starIndices[
'obsIndex']] * conv,
1600 starObs[
'dec'][starIndices[
'obsIndex']] * conv,
1601 starObs[
'instMag'][starIndices[
'obsIndex']],
1602 starObs[
'instMagErr'][starIndices[
'obsIndex']],
1603 fgcmExpInfo[
'FILTERNAME'][visitIndex],
1604 starIds[
'fgcm_id'][:],
1607 starIds[
'obsArrIndex'][:],
1609 obsX=starObs[
'x'][starIndices[
'obsIndex']],
1610 obsY=starObs[
'y'][starIndices[
'obsIndex']],
1611 obsDeltaMagBkg=starObs[
'deltaMagBkg'][starIndices[
'obsIndex']],
1612 obsDeltaAper=starObs[
'deltaMagAper'][starIndices[
'obsIndex']],
1613 psfCandidate=starObs[
'psf_candidate'][starIndices[
'obsIndex']],
1616 refMagErr=refMagErr,
1633 fgcmFitCycle.setLUT(fgcmLut)
1634 fgcmFitCycle.setStars(fgcmStars, fgcmPars)
1635 fgcmFitCycle.setPars(fgcmPars)
1638 fgcmFitCycle.finishSetup()
1647 fgcmDatasetDict = self._makeFgcmOutputDatasets(fgcmFitCycle)
1652 updatedPhotometricCutDict = {b: float(fgcmFitCycle.updatedPhotometricCut[i])
for
1653 i, b
in enumerate(_config.bands)}
1654 updatedHighCutDict = {band: float(fgcmFitCycle.updatedHighCut[i])
for
1655 i, band
in enumerate(_config.bands)}
1657 outConfig = copy.copy(_config)
1658 outConfig.update(cycleNumber=(_config.cycleNumber + 1),
1659 precomputeSuperStarInitialCycle=
False,
1660 freezeStdAtmosphere=
False,
1661 expGrayPhotometricCutDict=updatedPhotometricCutDict,
1662 expGrayHighCutDict=updatedHighCutDict)
1664 outConfig.connections.update(previousCycleNumber=str(_config.cycleNumber),
1665 cycleNumber=str(_config.cycleNumber + 1))
1668 configFileName =
'%s_cycle%02d_config.py' % (outConfig.outfileBase,
1669 outConfig.cycleNumber)
1670 outConfig.save(configFileName)
1672 if _config.isFinalCycle == 1:
1674 self.log.info(
"Everything is in place to run fgcmOutputProducts.py")
1676 self.log.info(
"Saved config for next cycle to %s" % (configFileName))
1677 self.log.info(
"Be sure to look at:")
1678 self.log.info(
" config.expGrayPhotometricCut")
1679 self.log.info(
" config.expGrayHighCut")
1680 self.log.info(
"If you are satisfied with the fit, please set:")
1681 self.log.info(
" config.isFinalCycle = True")
1683 fgcmFitCycle.freeSharedMemory()
1685 return fgcmDatasetDict, outConfig
1687 def _loadParameters(self, parCat):
1689 Load FGCM parameters from a previous fit cycle
1693 parCat : `lsst.afw.table.BaseCatalog`
1694 Parameter catalog in afw table form.
1698 inParInfo: `numpy.ndarray`
1699 Numpy array parameter information formatted for input to fgcm
1700 inParameters: `numpy.ndarray`
1701 Numpy array parameter values formatted for input to fgcm
1702 inSuperStar: `numpy.array`
1703 Superstar flat formatted for input to fgcm
1705 parLutFilterNames = np.array(parCat[0][
'lutFilterNames'].split(
','))
1706 parFitBands = np.array(parCat[0][
'fitBands'].split(
','))
1708 inParInfo = np.zeros(1, dtype=[(
'NCCD',
'i4'),
1709 (
'LUTFILTERNAMES', parLutFilterNames.dtype.str,
1710 (parLutFilterNames.size, )),
1711 (
'FITBANDS', parFitBands.dtype.str, (parFitBands.size, )),
1712 (
'LNTAUUNIT',
'f8'),
1713 (
'LNTAUSLOPEUNIT',
'f8'),
1714 (
'ALPHAUNIT',
'f8'),
1715 (
'LNPWVUNIT',
'f8'),
1716 (
'LNPWVSLOPEUNIT',
'f8'),
1717 (
'LNPWVQUADRATICUNIT',
'f8'),
1718 (
'LNPWVGLOBALUNIT',
'f8'),
1720 (
'QESYSUNIT',
'f8'),
1721 (
'FILTEROFFSETUNIT',
'f8'),
1722 (
'HASEXTERNALPWV',
'i2'),
1723 (
'HASEXTERNALTAU',
'i2')])
1724 inParInfo[
'NCCD'] = parCat[
'nCcd']
1725 inParInfo[
'LUTFILTERNAMES'][:] = parLutFilterNames
1726 inParInfo[
'FITBANDS'][:] = parFitBands
1727 inParInfo[
'HASEXTERNALPWV'] = parCat[
'hasExternalPwv']
1728 inParInfo[
'HASEXTERNALTAU'] = parCat[
'hasExternalTau']
1730 inParams = np.zeros(1, dtype=[(
'PARALPHA',
'f8', (parCat[
'parAlpha'].size, )),
1731 (
'PARO3',
'f8', (parCat[
'parO3'].size, )),
1732 (
'PARLNTAUINTERCEPT',
'f8',
1733 (parCat[
'parLnTauIntercept'].size, )),
1734 (
'PARLNTAUSLOPE',
'f8',
1735 (parCat[
'parLnTauSlope'].size, )),
1736 (
'PARLNPWVINTERCEPT',
'f8',
1737 (parCat[
'parLnPwvIntercept'].size, )),
1738 (
'PARLNPWVSLOPE',
'f8',
1739 (parCat[
'parLnPwvSlope'].size, )),
1740 (
'PARLNPWVQUADRATIC',
'f8',
1741 (parCat[
'parLnPwvQuadratic'].size, )),
1742 (
'PARQESYSINTERCEPT',
'f8',
1743 (parCat[
'parQeSysIntercept'].size, )),
1744 (
'COMPQESYSSLOPE',
'f8',
1745 (parCat[
'compQeSysSlope'].size, )),
1746 (
'PARFILTEROFFSET',
'f8',
1747 (parCat[
'parFilterOffset'].size, )),
1748 (
'PARFILTEROFFSETFITFLAG',
'i2',
1749 (parCat[
'parFilterOffsetFitFlag'].size, )),
1750 (
'PARRETRIEVEDLNPWVSCALE',
'f8'),
1751 (
'PARRETRIEVEDLNPWVOFFSET',
'f8'),
1752 (
'PARRETRIEVEDLNPWVNIGHTLYOFFSET',
'f8',
1753 (parCat[
'parRetrievedLnPwvNightlyOffset'].size, )),
1754 (
'COMPABSTHROUGHPUT',
'f8',
1755 (parCat[
'compAbsThroughput'].size, )),
1756 (
'COMPREFOFFSET',
'f8',
1757 (parCat[
'compRefOffset'].size, )),
1758 (
'COMPREFSIGMA',
'f8',
1759 (parCat[
'compRefSigma'].size, )),
1760 (
'COMPMIRRORCHROMATICITY',
'f8',
1761 (parCat[
'compMirrorChromaticity'].size, )),
1762 (
'MIRRORCHROMATICITYPIVOT',
'f8',
1763 (parCat[
'mirrorChromaticityPivot'].size, )),
1764 (
'COMPCCDCHROMATICITY',
'f8',
1765 (parCat[
'compCcdChromaticity'].size, )),
1766 (
'COMPMEDIANSEDSLOPE',
'f8',
1767 (parCat[
'compMedianSedSlope'].size, )),
1768 (
'COMPAPERCORRPIVOT',
'f8',
1769 (parCat[
'compAperCorrPivot'].size, )),
1770 (
'COMPAPERCORRSLOPE',
'f8',
1771 (parCat[
'compAperCorrSlope'].size, )),
1772 (
'COMPAPERCORRSLOPEERR',
'f8',
1773 (parCat[
'compAperCorrSlopeErr'].size, )),
1774 (
'COMPAPERCORRRANGE',
'f8',
1775 (parCat[
'compAperCorrRange'].size, )),
1776 (
'COMPMODELERREXPTIMEPIVOT',
'f8',
1777 (parCat[
'compModelErrExptimePivot'].size, )),
1778 (
'COMPMODELERRFWHMPIVOT',
'f8',
1779 (parCat[
'compModelErrFwhmPivot'].size, )),
1780 (
'COMPMODELERRSKYPIVOT',
'f8',
1781 (parCat[
'compModelErrSkyPivot'].size, )),
1782 (
'COMPMODELERRPARS',
'f8',
1783 (parCat[
'compModelErrPars'].size, )),
1784 (
'COMPEXPGRAY',
'f8',
1785 (parCat[
'compExpGray'].size, )),
1786 (
'COMPVARGRAY',
'f8',
1787 (parCat[
'compVarGray'].size, )),
1788 (
'COMPEXPDELTAMAGBKG',
'f8',
1789 (parCat[
'compExpDeltaMagBkg'].size, )),
1790 (
'COMPNGOODSTARPEREXP',
'i4',
1791 (parCat[
'compNGoodStarPerExp'].size, )),
1792 (
'COMPEXPREFOFFSET',
'f8',
1793 (parCat[
'compExpRefOffset'].size, )),
1794 (
'COMPSIGFGCM',
'f8',
1795 (parCat[
'compSigFgcm'].size, )),
1796 (
'COMPSIGMACAL',
'f8',
1797 (parCat[
'compSigmaCal'].size, )),
1798 (
'COMPRETRIEVEDLNPWV',
'f8',
1799 (parCat[
'compRetrievedLnPwv'].size, )),
1800 (
'COMPRETRIEVEDLNPWVRAW',
'f8',
1801 (parCat[
'compRetrievedLnPwvRaw'].size, )),
1802 (
'COMPRETRIEVEDLNPWVFLAG',
'i2',
1803 (parCat[
'compRetrievedLnPwvFlag'].size, )),
1804 (
'COMPRETRIEVEDTAUNIGHT',
'f8',
1805 (parCat[
'compRetrievedTauNight'].size, )),
1806 (
'COMPEPSILON',
'f8',
1807 (parCat[
'compEpsilon'].size, )),
1808 (
'COMPMEDDELTAAPER',
'f8',
1809 (parCat[
'compMedDeltaAper'].size, )),
1810 (
'COMPGLOBALEPSILON',
'f4',
1811 (parCat[
'compGlobalEpsilon'].size, )),
1812 (
'COMPEPSILONMAP',
'f4',
1813 (parCat[
'compEpsilonMap'].size, )),
1814 (
'COMPEPSILONNSTARMAP',
'i4',
1815 (parCat[
'compEpsilonNStarMap'].size, )),
1816 (
'COMPEPSILONCCDMAP',
'f4',
1817 (parCat[
'compEpsilonCcdMap'].size, )),
1818 (
'COMPEPSILONCCDNSTARMAP',
'i4',
1819 (parCat[
'compEpsilonCcdNStarMap'].size, ))])
1821 inParams[
'PARALPHA'][:] = parCat[
'parAlpha'][0, :]
1822 inParams[
'PARO3'][:] = parCat[
'parO3'][0, :]
1823 inParams[
'PARLNTAUINTERCEPT'][:] = parCat[
'parLnTauIntercept'][0, :]
1824 inParams[
'PARLNTAUSLOPE'][:] = parCat[
'parLnTauSlope'][0, :]
1825 inParams[
'PARLNPWVINTERCEPT'][:] = parCat[
'parLnPwvIntercept'][0, :]
1826 inParams[
'PARLNPWVSLOPE'][:] = parCat[
'parLnPwvSlope'][0, :]
1827 inParams[
'PARLNPWVQUADRATIC'][:] = parCat[
'parLnPwvQuadratic'][0, :]
1828 inParams[
'PARQESYSINTERCEPT'][:] = parCat[
'parQeSysIntercept'][0, :]
1829 inParams[
'COMPQESYSSLOPE'][:] = parCat[
'compQeSysSlope'][0, :]
1830 inParams[
'PARFILTEROFFSET'][:] = parCat[
'parFilterOffset'][0, :]
1831 inParams[
'PARFILTEROFFSETFITFLAG'][:] = parCat[
'parFilterOffsetFitFlag'][0, :]
1832 inParams[
'PARRETRIEVEDLNPWVSCALE'] = parCat[
'parRetrievedLnPwvScale']
1833 inParams[
'PARRETRIEVEDLNPWVOFFSET'] = parCat[
'parRetrievedLnPwvOffset']
1834 inParams[
'PARRETRIEVEDLNPWVNIGHTLYOFFSET'][:] = parCat[
'parRetrievedLnPwvNightlyOffset'][0, :]
1835 inParams[
'COMPABSTHROUGHPUT'][:] = parCat[
'compAbsThroughput'][0, :]
1836 inParams[
'COMPREFOFFSET'][:] = parCat[
'compRefOffset'][0, :]
1837 inParams[
'COMPREFSIGMA'][:] = parCat[
'compRefSigma'][0, :]
1838 inParams[
'COMPMIRRORCHROMATICITY'][:] = parCat[
'compMirrorChromaticity'][0, :]
1839 inParams[
'MIRRORCHROMATICITYPIVOT'][:] = parCat[
'mirrorChromaticityPivot'][0, :]
1840 inParams[
'COMPCCDCHROMATICITY'][:] = parCat[
'compCcdChromaticity'][0, :]
1841 inParams[
'COMPMEDIANSEDSLOPE'][:] = parCat[
'compMedianSedSlope'][0, :]
1842 inParams[
'COMPAPERCORRPIVOT'][:] = parCat[
'compAperCorrPivot'][0, :]
1843 inParams[
'COMPAPERCORRSLOPE'][:] = parCat[
'compAperCorrSlope'][0, :]
1844 inParams[
'COMPAPERCORRSLOPEERR'][:] = parCat[
'compAperCorrSlopeErr'][0, :]
1845 inParams[
'COMPAPERCORRRANGE'][:] = parCat[
'compAperCorrRange'][0, :]
1846 inParams[
'COMPMODELERREXPTIMEPIVOT'][:] = parCat[
'compModelErrExptimePivot'][0, :]
1847 inParams[
'COMPMODELERRFWHMPIVOT'][:] = parCat[
'compModelErrFwhmPivot'][0, :]
1848 inParams[
'COMPMODELERRSKYPIVOT'][:] = parCat[
'compModelErrSkyPivot'][0, :]
1849 inParams[
'COMPMODELERRPARS'][:] = parCat[
'compModelErrPars'][0, :]
1850 inParams[
'COMPEXPGRAY'][:] = parCat[
'compExpGray'][0, :]
1851 inParams[
'COMPVARGRAY'][:] = parCat[
'compVarGray'][0, :]
1852 inParams[
'COMPEXPDELTAMAGBKG'][:] = parCat[
'compExpDeltaMagBkg'][0, :]
1853 inParams[
'COMPNGOODSTARPEREXP'][:] = parCat[
'compNGoodStarPerExp'][0, :]
1854 inParams[
'COMPEXPREFOFFSET'][:] = parCat[
'compExpRefOffset'][0, :]
1855 inParams[
'COMPSIGFGCM'][:] = parCat[
'compSigFgcm'][0, :]
1856 inParams[
'COMPSIGMACAL'][:] = parCat[
'compSigmaCal'][0, :]
1857 inParams[
'COMPRETRIEVEDLNPWV'][:] = parCat[
'compRetrievedLnPwv'][0, :]
1858 inParams[
'COMPRETRIEVEDLNPWVRAW'][:] = parCat[
'compRetrievedLnPwvRaw'][0, :]
1859 inParams[
'COMPRETRIEVEDLNPWVFLAG'][:] = parCat[
'compRetrievedLnPwvFlag'][0, :]
1860 inParams[
'COMPRETRIEVEDTAUNIGHT'][:] = parCat[
'compRetrievedTauNight'][0, :]
1861 inParams[
'COMPEPSILON'][:] = parCat[
'compEpsilon'][0, :]
1862 inParams[
'COMPMEDDELTAAPER'][:] = parCat[
'compMedDeltaAper'][0, :]
1863 inParams[
'COMPGLOBALEPSILON'][:] = parCat[
'compGlobalEpsilon'][0, :]
1864 inParams[
'COMPEPSILONMAP'][:] = parCat[
'compEpsilonMap'][0, :]
1865 inParams[
'COMPEPSILONNSTARMAP'][:] = parCat[
'compEpsilonNStarMap'][0, :]
1866 inParams[
'COMPEPSILONCCDMAP'][:] = parCat[
'compEpsilonCcdMap'][0, :]
1867 inParams[
'COMPEPSILONCCDNSTARMAP'][:] = parCat[
'compEpsilonCcdNStarMap'][0, :]
1869 inSuperStar = np.zeros(parCat[
'superstarSize'][0, :], dtype=
'f8')
1870 inSuperStar[:, :, :, :] = parCat[
'superstar'][0, :].reshape(inSuperStar.shape)
1872 return (inParInfo, inParams, inSuperStar)
1874 def _makeFgcmOutputDatasets(self, fgcmFitCycle):
1876 Persist FGCM datasets through the butler.
1880 fgcmFitCycle: `lsst.fgcm.FgcmFitCycle`
1881 Fgcm Fit cycle object
1883 fgcmDatasetDict = {}
1886 parInfo, pars = fgcmFitCycle.fgcmPars.parsToArrays()
1891 lutFilterNameString = comma.join([n.decode(
'utf-8')
1892 for n
in parInfo[
'LUTFILTERNAMES'][0]])
1893 fitBandString = comma.join([n.decode(
'utf-8')
1894 for n
in parInfo[
'FITBANDS'][0]])
1896 parSchema = self._makeParSchema(parInfo, pars, fgcmFitCycle.fgcmPars.parSuperStarFlat,
1897 lutFilterNameString, fitBandString)
1898 parCat = self._makeParCatalog(parSchema, parInfo, pars,
1899 fgcmFitCycle.fgcmPars.parSuperStarFlat,
1900 lutFilterNameString, fitBandString)
1902 fgcmDatasetDict[
'fgcmFitParameters'] = parCat
1907 flagStarSchema = self._makeFlagStarSchema()
1908 flagStarStruct = fgcmFitCycle.fgcmStars.getFlagStarIndices()
1909 flagStarCat = self._makeFlagStarCat(flagStarSchema, flagStarStruct)
1911 fgcmDatasetDict[
'fgcmFlaggedStars'] = flagStarCat
1914 if self.outputZeropoints:
1915 superStarChebSize = fgcmFitCycle.fgcmZpts.zpStruct[
'FGCM_FZPT_SSTAR_CHEB'].shape[1]
1916 zptChebSize = fgcmFitCycle.fgcmZpts.zpStruct[
'FGCM_FZPT_CHEB'].shape[1]
1918 zptSchema = makeZptSchema(superStarChebSize, zptChebSize)
1919 zptCat = makeZptCat(zptSchema, fgcmFitCycle.fgcmZpts.zpStruct)
1921 fgcmDatasetDict[
'fgcmZeropoints'] = zptCat
1925 atmSchema = makeAtmSchema()
1926 atmCat = makeAtmCat(atmSchema, fgcmFitCycle.fgcmZpts.atmStruct)
1928 fgcmDatasetDict[
'fgcmAtmosphereParameters'] = atmCat
1931 if self.outputStandards:
1932 stdStruct, goodBands = fgcmFitCycle.fgcmStars.retrieveStdStarCatalog(fgcmFitCycle.fgcmPars)
1933 stdSchema = makeStdSchema(len(goodBands))
1934 stdCat = makeStdCat(stdSchema, stdStruct, goodBands)
1936 fgcmDatasetDict[
'fgcmStandardStars'] = stdCat
1938 return fgcmDatasetDict
1940 def _makeParSchema(self, parInfo, pars, parSuperStarFlat,
1941 lutFilterNameString, fitBandString):
1943 Make the parameter persistence schema
1947 parInfo: `numpy.ndarray`
1948 Parameter information returned by fgcm
1949 pars: `numpy.ndarray`
1950 Parameter values returned by fgcm
1951 parSuperStarFlat: `numpy.array`
1952 Superstar flat values returned by fgcm
1953 lutFilterNameString: `str`
1954 Combined string of all the lutFilterNames
1955 fitBandString: `str`
1956 Combined string of all the fitBands
1960 parSchema: `afwTable.schema`
1966 parSchema.addField(
'nCcd', type=np.int32, doc=
'Number of CCDs')
1967 parSchema.addField(
'lutFilterNames', type=str, doc=
'LUT Filter names in parameter file',
1968 size=len(lutFilterNameString))
1969 parSchema.addField(
'fitBands', type=str, doc=
'Bands that were fit',
1970 size=len(fitBandString))
1971 parSchema.addField(
'lnTauUnit', type=np.float64, doc=
'Step units for ln(AOD)')
1972 parSchema.addField(
'lnTauSlopeUnit', type=np.float64,
1973 doc=
'Step units for ln(AOD) slope')
1974 parSchema.addField(
'alphaUnit', type=np.float64, doc=
'Step units for alpha')
1975 parSchema.addField(
'lnPwvUnit', type=np.float64, doc=
'Step units for ln(pwv)')
1976 parSchema.addField(
'lnPwvSlopeUnit', type=np.float64,
1977 doc=
'Step units for ln(pwv) slope')
1978 parSchema.addField(
'lnPwvQuadraticUnit', type=np.float64,
1979 doc=
'Step units for ln(pwv) quadratic term')
1980 parSchema.addField(
'lnPwvGlobalUnit', type=np.float64,
1981 doc=
'Step units for global ln(pwv) parameters')
1982 parSchema.addField(
'o3Unit', type=np.float64, doc=
'Step units for O3')
1983 parSchema.addField(
'qeSysUnit', type=np.float64, doc=
'Step units for mirror gray')
1984 parSchema.addField(
'filterOffsetUnit', type=np.float64, doc=
'Step units for filter offset')
1985 parSchema.addField(
'hasExternalPwv', type=np.int32, doc=
'Parameters fit using external pwv')
1986 parSchema.addField(
'hasExternalTau', type=np.int32, doc=
'Parameters fit using external tau')
1989 parSchema.addField(
'parAlpha', type=
'ArrayD', doc=
'Alpha parameter vector',
1990 size=pars[
'PARALPHA'].size)
1991 parSchema.addField(
'parO3', type=
'ArrayD', doc=
'O3 parameter vector',
1992 size=pars[
'PARO3'].size)
1993 parSchema.addField(
'parLnTauIntercept', type=
'ArrayD',
1994 doc=
'ln(Tau) intercept parameter vector',
1995 size=pars[
'PARLNTAUINTERCEPT'].size)
1996 parSchema.addField(
'parLnTauSlope', type=
'ArrayD',
1997 doc=
'ln(Tau) slope parameter vector',
1998 size=pars[
'PARLNTAUSLOPE'].size)
1999 parSchema.addField(
'parLnPwvIntercept', type=
'ArrayD', doc=
'ln(pwv) intercept parameter vector',
2000 size=pars[
'PARLNPWVINTERCEPT'].size)
2001 parSchema.addField(
'parLnPwvSlope', type=
'ArrayD', doc=
'ln(pwv) slope parameter vector',
2002 size=pars[
'PARLNPWVSLOPE'].size)
2003 parSchema.addField(
'parLnPwvQuadratic', type=
'ArrayD', doc=
'ln(pwv) quadratic parameter vector',
2004 size=pars[
'PARLNPWVQUADRATIC'].size)
2005 parSchema.addField(
'parQeSysIntercept', type=
'ArrayD', doc=
'Mirror gray intercept parameter vector',
2006 size=pars[
'PARQESYSINTERCEPT'].size)
2007 parSchema.addField(
'compQeSysSlope', type=
'ArrayD', doc=
'Mirror gray slope parameter vector',
2008 size=pars[0][
'COMPQESYSSLOPE'].size)
2009 parSchema.addField(
'parFilterOffset', type=
'ArrayD', doc=
'Filter offset parameter vector',
2010 size=pars[
'PARFILTEROFFSET'].size)
2011 parSchema.addField(
'parFilterOffsetFitFlag', type=
'ArrayI', doc=
'Filter offset parameter fit flag',
2012 size=pars[
'PARFILTEROFFSETFITFLAG'].size)
2013 parSchema.addField(
'parRetrievedLnPwvScale', type=np.float64,
2014 doc=
'Global scale for retrieved ln(pwv)')
2015 parSchema.addField(
'parRetrievedLnPwvOffset', type=np.float64,
2016 doc=
'Global offset for retrieved ln(pwv)')
2017 parSchema.addField(
'parRetrievedLnPwvNightlyOffset', type=
'ArrayD',
2018 doc=
'Nightly offset for retrieved ln(pwv)',
2019 size=pars[
'PARRETRIEVEDLNPWVNIGHTLYOFFSET'].size)
2020 parSchema.addField(
'compAbsThroughput', type=
'ArrayD',
2021 doc=
'Absolute throughput (relative to transmission curves)',
2022 size=pars[
'COMPABSTHROUGHPUT'].size)
2023 parSchema.addField(
'compRefOffset', type=
'ArrayD',
2024 doc=
'Offset between reference stars and calibrated stars',
2025 size=pars[
'COMPREFOFFSET'].size)
2026 parSchema.addField(
'compRefSigma', type=
'ArrayD',
2027 doc=
'Width of reference star/calibrated star distribution',
2028 size=pars[
'COMPREFSIGMA'].size)
2029 parSchema.addField(
'compMirrorChromaticity', type=
'ArrayD',
2030 doc=
'Computed mirror chromaticity terms',
2031 size=pars[
'COMPMIRRORCHROMATICITY'].size)
2032 parSchema.addField(
'mirrorChromaticityPivot', type=
'ArrayD',
2033 doc=
'Mirror chromaticity pivot mjd',
2034 size=pars[
'MIRRORCHROMATICITYPIVOT'].size)
2035 parSchema.addField(
'compCcdChromaticity', type=
'ArrayD',
2036 doc=
'Computed CCD chromaticity terms',
2037 size=pars[
'COMPCCDCHROMATICITY'].size)
2038 parSchema.addField(
'compMedianSedSlope', type=
'ArrayD',
2039 doc=
'Computed median SED slope (per band)',
2040 size=pars[
'COMPMEDIANSEDSLOPE'].size)
2041 parSchema.addField(
'compAperCorrPivot', type=
'ArrayD', doc=
'Aperture correction pivot',
2042 size=pars[
'COMPAPERCORRPIVOT'].size)
2043 parSchema.addField(
'compAperCorrSlope', type=
'ArrayD', doc=
'Aperture correction slope',
2044 size=pars[
'COMPAPERCORRSLOPE'].size)
2045 parSchema.addField(
'compAperCorrSlopeErr', type=
'ArrayD', doc=
'Aperture correction slope error',
2046 size=pars[
'COMPAPERCORRSLOPEERR'].size)
2047 parSchema.addField(
'compAperCorrRange', type=
'ArrayD', doc=
'Aperture correction range',
2048 size=pars[
'COMPAPERCORRRANGE'].size)
2049 parSchema.addField(
'compModelErrExptimePivot', type=
'ArrayD', doc=
'Model error exptime pivot',
2050 size=pars[
'COMPMODELERREXPTIMEPIVOT'].size)
2051 parSchema.addField(
'compModelErrFwhmPivot', type=
'ArrayD', doc=
'Model error fwhm pivot',
2052 size=pars[
'COMPMODELERRFWHMPIVOT'].size)
2053 parSchema.addField(
'compModelErrSkyPivot', type=
'ArrayD', doc=
'Model error sky pivot',
2054 size=pars[
'COMPMODELERRSKYPIVOT'].size)
2055 parSchema.addField(
'compModelErrPars', type=
'ArrayD', doc=
'Model error parameters',
2056 size=pars[
'COMPMODELERRPARS'].size)
2057 parSchema.addField(
'compExpGray', type=
'ArrayD', doc=
'Computed exposure gray',
2058 size=pars[
'COMPEXPGRAY'].size)
2059 parSchema.addField(
'compVarGray', type=
'ArrayD', doc=
'Computed exposure variance',
2060 size=pars[
'COMPVARGRAY'].size)
2061 parSchema.addField(
'compExpDeltaMagBkg', type=
'ArrayD',
2062 doc=
'Computed exposure offset due to background',
2063 size=pars[
'COMPEXPDELTAMAGBKG'].size)
2064 parSchema.addField(
'compNGoodStarPerExp', type=
'ArrayI',
2065 doc=
'Computed number of good stars per exposure',
2066 size=pars[
'COMPNGOODSTARPEREXP'].size)
2067 parSchema.addField(
'compExpRefOffset', type=
'ArrayD',
2068 doc=
'Computed per-visit median offset between standard stars and ref stars.',
2069 size=pars[
'COMPEXPREFOFFSET'].size)
2070 parSchema.addField(
'compSigFgcm', type=
'ArrayD', doc=
'Computed sigma_fgcm (intrinsic repeatability)',
2071 size=pars[
'COMPSIGFGCM'].size)
2072 parSchema.addField(
'compSigmaCal', type=
'ArrayD', doc=
'Computed sigma_cal (systematic error floor)',
2073 size=pars[
'COMPSIGMACAL'].size)
2074 parSchema.addField(
'compRetrievedLnPwv', type=
'ArrayD', doc=
'Retrieved ln(pwv) (smoothed)',
2075 size=pars[
'COMPRETRIEVEDLNPWV'].size)
2076 parSchema.addField(
'compRetrievedLnPwvRaw', type=
'ArrayD', doc=
'Retrieved ln(pwv) (raw)',
2077 size=pars[
'COMPRETRIEVEDLNPWVRAW'].size)
2078 parSchema.addField(
'compRetrievedLnPwvFlag', type=
'ArrayI', doc=
'Retrieved ln(pwv) Flag',
2079 size=pars[
'COMPRETRIEVEDLNPWVFLAG'].size)
2080 parSchema.addField(
'compRetrievedTauNight', type=
'ArrayD', doc=
'Retrieved tau (per night)',
2081 size=pars[
'COMPRETRIEVEDTAUNIGHT'].size)
2082 parSchema.addField(
'compEpsilon', type=
'ArrayD',
2083 doc=
'Computed epsilon background offset per visit (nJy/arcsec2)',
2084 size=pars[
'COMPEPSILON'].size)
2085 parSchema.addField(
'compMedDeltaAper', type=
'ArrayD',
2086 doc=
'Median delta mag aper per visit',
2087 size=pars[
'COMPMEDDELTAAPER'].size)
2088 parSchema.addField(
'compGlobalEpsilon', type=
'ArrayD',
2089 doc=
'Computed epsilon bkg offset (global) (nJy/arcsec2)',
2090 size=pars[
'COMPGLOBALEPSILON'].size)
2091 parSchema.addField(
'compEpsilonMap', type=
'ArrayD',
2092 doc=
'Computed epsilon maps (nJy/arcsec2)',
2093 size=pars[
'COMPEPSILONMAP'].size)
2094 parSchema.addField(
'compEpsilonNStarMap', type=
'ArrayI',
2095 doc=
'Number of stars per pixel in computed epsilon maps',
2096 size=pars[
'COMPEPSILONNSTARMAP'].size)
2097 parSchema.addField(
'compEpsilonCcdMap', type=
'ArrayD',
2098 doc=
'Computed epsilon ccd maps (nJy/arcsec2)',
2099 size=pars[
'COMPEPSILONCCDMAP'].size)
2100 parSchema.addField(
'compEpsilonCcdNStarMap', type=
'ArrayI',
2101 doc=
'Number of stars per ccd bin in epsilon ccd maps',
2102 size=pars[
'COMPEPSILONCCDNSTARMAP'].size)
2103 parSchema.addField(
'epochMjdStart', type=
'ArrayD',
2104 doc=
'Epoch MJD start times',
2105 size=pars[
'EPOCHMJDSTART'].size)
2106 parSchema.addField(
'epochMjdEnd', type=
'ArrayD',
2107 doc=
'EpochMJD end times',
2108 size=pars[
'EPOCHMJDEND'].size)
2110 parSchema.addField(
'superstarSize', type=
'ArrayI', doc=
'Superstar matrix size',
2112 parSchema.addField(
'superstar', type=
'ArrayD', doc=
'Superstar matrix (flattened)',
2113 size=parSuperStarFlat.size)
2117 def _makeParCatalog(self, parSchema, parInfo, pars, parSuperStarFlat,
2118 lutFilterNameString, fitBandString):
2120 Make the FGCM parameter catalog for persistence
2124 parSchema: `lsst.afw.table.Schema`
2125 Parameter catalog schema
2126 pars: `numpy.ndarray`
2127 FGCM parameters to put into parCat
2128 parSuperStarFlat: `numpy.array`
2129 FGCM superstar flat array to put into parCat
2130 lutFilterNameString: `str`
2131 Combined string of all the lutFilterNames
2132 fitBandString: `str`
2133 Combined string of all the fitBands
2137 parCat: `afwTable.BasicCatalog`
2138 Atmosphere and instrumental model parameter catalog for persistence
2146 rec = parCat.addNew()
2149 rec[
'nCcd'] = parInfo[
'NCCD'][0]
2150 rec[
'lutFilterNames'] = lutFilterNameString
2151 rec[
'fitBands'] = fitBandString
2153 rec[
'hasExternalPwv'] = 0
2154 rec[
'hasExternalTau'] = 0
2158 scalarNames = [
'parRetrievedLnPwvScale',
'parRetrievedLnPwvOffset']
2160 arrNames = [
'parAlpha',
'parO3',
'parLnTauIntercept',
'parLnTauSlope',
2161 'parLnPwvIntercept',
'parLnPwvSlope',
'parLnPwvQuadratic',
2162 'parQeSysIntercept',
'compQeSysSlope',
2163 'parRetrievedLnPwvNightlyOffset',
'compAperCorrPivot',
2164 'parFilterOffset',
'parFilterOffsetFitFlag',
2165 'compAbsThroughput',
'compRefOffset',
'compRefSigma',
2166 'compMirrorChromaticity',
'mirrorChromaticityPivot',
'compCcdChromaticity',
2167 'compAperCorrSlope',
'compAperCorrSlopeErr',
'compAperCorrRange',
2168 'compModelErrExptimePivot',
'compModelErrFwhmPivot',
2169 'compModelErrSkyPivot',
'compModelErrPars',
2170 'compExpGray',
'compVarGray',
'compNGoodStarPerExp',
'compSigFgcm',
2171 'compSigmaCal',
'compExpDeltaMagBkg',
'compMedianSedSlope',
2172 'compRetrievedLnPwv',
'compRetrievedLnPwvRaw',
'compRetrievedLnPwvFlag',
2173 'compRetrievedTauNight',
'compEpsilon',
'compMedDeltaAper',
2174 'compGlobalEpsilon',
'compEpsilonMap',
'compEpsilonNStarMap',
2175 'compEpsilonCcdMap',
'compEpsilonCcdNStarMap',
'compExpRefOffset',
2176 'epochMjdStart',
'epochMjdEnd']
2178 for scalarName
in scalarNames:
2179 rec[scalarName] = pars[scalarName.upper()][0]
2181 for arrName
in arrNames:
2182 rec[arrName][:] = np.atleast_1d(pars[0][arrName.upper()])[:]
2185 rec[
'superstarSize'][:] = parSuperStarFlat.shape
2186 rec[
'superstar'][:] = parSuperStarFlat.ravel()
2190 def _makeFlagStarSchema(self):
2192 Make the flagged-stars schema
2196 flagStarSchema: `lsst.afw.table.Schema`
2201 flagStarSchema.addField(
'objId', type=np.int32, doc=
'FGCM object id')
2202 flagStarSchema.addField(
'objFlag', type=np.int32, doc=
'FGCM object flag')
2204 return flagStarSchema
2206 def _makeFlagStarCat(self, flagStarSchema, flagStarStruct):
2208 Make the flagged star catalog for persistence
2212 flagStarSchema: `lsst.afw.table.Schema`
2214 flagStarStruct: `numpy.ndarray`
2215 Flagged star structure from fgcm
2219 flagStarCat: `lsst.afw.table.BaseCatalog`
2220 Flagged star catalog for persistence
2224 flagStarCat.resize(flagStarStruct.size)
2226 flagStarCat[
'objId'][:] = flagStarStruct[
'OBJID']
2227 flagStarCat[
'objFlag'][:] = flagStarStruct[
'OBJFLAG']
Defines the fields and offsets for a table.