28 import astropy.units
as u
33 import lsst.pipe.base
as pipeBase
39 from lsst.obs.base
import Instrument
40 from lsst.pipe.tasks.colorterms
import ColortermLibrary
41 from lsst.verify
import Job, Measurement
44 ReferenceObjectLoader)
47 from .dataIds
import PerTractCcdDataIdContainer
52 __all__ = [
"JointcalConfig",
"JointcalRunner",
"JointcalTask"]
54 Photometry = collections.namedtuple(
'Photometry', (
'fit',
'model'))
55 Astrometry = collections.namedtuple(
'Astrometry', (
'fit',
'model',
'sky_to_tan_projection'))
60 meas = Measurement(job.metrics[name], value)
61 job.measurements.insert(meas)
65 """Subclass of TaskRunner for jointcalTask (gen2)
67 jointcalTask.runDataRef() takes a number of arguments, one of which is a list of dataRefs
68 extracted from the command line (whereas most CmdLineTasks' runDataRef methods take
69 single dataRef, are are called repeatedly). This class transforms the processed
70 arguments generated by the ArgumentParser into the arguments expected by
71 Jointcal.runDataRef().
73 See pipeBase.TaskRunner for more information.
79 Return a list of tuples per tract, each containing (dataRefs, kwargs).
81 Jointcal operates on lists of dataRefs simultaneously.
83 kwargs[
'butler'] = parsedCmd.butler
87 for ref
in parsedCmd.id.refList:
88 refListDict.setdefault(ref.dataId[
"tract"], []).append(ref)
90 result = [(refListDict[tract], kwargs)
for tract
in sorted(refListDict.keys())]
98 Arguments for Task.runDataRef()
103 if self.doReturnResults is False:
105 - ``exitStatus``: 0 if the task completed successfully, 1 otherwise.
107 if self.doReturnResults is True:
109 - ``result``: the result of calling jointcal.runDataRef()
110 - ``exitStatus``: 0 if the task completed successfully, 1 otherwise.
115 dataRefList, kwargs = args
116 butler = kwargs.pop(
'butler')
117 task = self.TaskClass(config=self.config, log=self.log, butler=butler)
120 result = task.runDataRef(dataRefList, **kwargs)
121 exitStatus = result.exitStatus
122 job_path = butler.get(
'verify_job_filename')
123 result.job.write(job_path[0])
124 except Exception
as e:
129 eName = type(e).__name__
130 tract = dataRefList[0].dataId[
'tract']
131 task.log.fatal(
"Failed processing tract %s, %s: %s", tract, eName, e)
134 kwargs[
'butler'] = butler
135 if self.doReturnResults:
136 return pipeBase.Struct(result=result, exitStatus=exitStatus)
138 return pipeBase.Struct(exitStatus=exitStatus)
142 """Lookup function that asserts/hopes that a static calibration dataset
143 exists in a particular collection, since this task can't provide a single
144 date/time to use to search for one properly.
146 This is mostly useful for the ``camera`` dataset, in cases where the task's
147 quantum dimensions do *not* include something temporal, like ``exposure``
152 datasetType : `lsst.daf.butler.DatasetType`
153 Type of dataset being searched for.
154 registry : `lsst.daf.butler.Registry`
155 Data repository registry to search.
156 quantumDataId : `lsst.daf.butler.DataCoordinate`
157 Data ID of the quantum this camera should match.
158 collections : `Iterable` [ `str` ]
159 Collections that should be searched - but this lookup function works
160 by ignoring this in favor of a more-or-less hard-coded value.
164 refs : `Iterator` [ `lsst.daf.butler.DatasetRef` ]
165 Iterator over dataset references; should have only one element.
169 This implementation duplicates one in fgcmcal, and is at least quite
170 similar to another in cp_pipe. This duplicate has the most documentation.
171 Fixing this is DM-29661.
173 instrument = Instrument.fromName(quantumDataId[
"instrument"], registry)
174 unboundedCollection = instrument.makeUnboundedCalibrationRunName()
175 return registry.queryDatasets(datasetType,
176 dataId=quantumDataId,
177 collections=[unboundedCollection],
182 """Lookup function that finds all refcats for all visits that overlap a
183 tract, rather than just the refcats that directly overlap the tract.
187 datasetType : `lsst.daf.butler.DatasetType`
188 Type of dataset being searched for.
189 registry : `lsst.daf.butler.Registry`
190 Data repository registry to search.
191 quantumDataId : `lsst.daf.butler.DataCoordinate`
192 Data ID of the quantum; expected to be something we can use as a
193 constraint to query for overlapping visits.
194 collections : `Iterable` [ `str` ]
195 Collections to search.
199 refs : `Iterator` [ `lsst.daf.butler.DatasetRef` ]
200 Iterator over refcat references.
209 for visit_data_id
in set(registry.queryDataIds(
"visit", dataId=quantumDataId).expanded()):
211 registry.queryDatasets(
213 collections=collections,
214 dataId=visit_data_id,
222 dimensions=(
"skymap",
"tract",
"instrument",
"physical_filter")):
223 """Middleware input/output connections for jointcal data."""
224 inputCamera = pipeBase.connectionTypes.PrerequisiteInput(
225 doc=
"The camera instrument that took these observations.",
227 storageClass=
"Camera",
228 dimensions=(
"instrument",),
230 lookupFunction=lookupStaticCalibrations,
232 inputSourceTableVisit = pipeBase.connectionTypes.Input(
233 doc=
"Source table in parquet format, per visit",
234 name=
"sourceTable_visit",
235 storageClass=
"DataFrame",
236 dimensions=(
"instrument",
"visit"),
240 inputVisitSummary = pipeBase.connectionTypes.Input(
241 doc=(
"Per-visit consolidated exposure metadata built from calexps. "
242 "These catalogs use detector id for the id and must be sorted for "
243 "fast lookups of a detector."),
245 storageClass=
"ExposureCatalog",
246 dimensions=(
"instrument",
"visit"),
250 astrometryRefCat = pipeBase.connectionTypes.PrerequisiteInput(
251 doc=
"The astrometry reference catalog to match to loaded input catalog sources.",
252 name=
"gaia_dr2_20200414",
253 storageClass=
"SimpleCatalog",
254 dimensions=(
"skypix",),
257 lookupFunction=lookupVisitRefCats,
259 photometryRefCat = pipeBase.connectionTypes.PrerequisiteInput(
260 doc=
"The photometry reference catalog to match to loaded input catalog sources.",
261 name=
"ps1_pv3_3pi_20170110",
262 storageClass=
"SimpleCatalog",
263 dimensions=(
"skypix",),
266 lookupFunction=lookupVisitRefCats,
269 outputWcs = pipeBase.connectionTypes.Output(
270 doc=(
"Per-tract, per-visit world coordinate systems derived from the fitted model."
271 " These catalogs only contain entries for detectors with an output, and use"
272 " the detector id for the catalog id, sorted on id for fast lookups of a detector."),
273 name=
"jointcalSkyWcsCatalog",
274 storageClass=
"ExposureCatalog",
275 dimensions=(
"instrument",
"visit",
"skymap",
"tract"),
278 outputPhotoCalib = pipeBase.connectionTypes.Output(
279 doc=(
"Per-tract, per-visit photometric calibrations derived from the fitted model."
280 " These catalogs only contain entries for detectors with an output, and use"
281 " the detector id for the catalog id, sorted on id for fast lookups of a detector."),
282 name=
"jointcalPhotoCalibCatalog",
283 storageClass=
"ExposureCatalog",
284 dimensions=(
"instrument",
"visit",
"skymap",
"tract"),
292 for name
in (
"astrometry",
"photometry"):
293 vars()[f
"{name}_matched_fittedStars"] = pipeBase.connectionTypes.Output(
294 doc=f
"The number of cross-matched fittedStars for {name}",
295 name=f
"metricvalue_jointcal_{name}_matched_fittedStars",
296 storageClass=
"MetricValue",
297 dimensions=(
"skymap",
"tract",
"instrument",
"physical_filter"),
299 vars()[f
"{name}_collected_refStars"] = pipeBase.connectionTypes.Output(
300 doc=f
"The number of {name} reference stars drawn from the reference catalog, before matching.",
301 name=f
"metricvalue_jointcal_{name}_collected_refStars",
302 storageClass=
"MetricValue",
303 dimensions=(
"skymap",
"tract",
"instrument",
"physical_filter"),
305 vars()[f
"{name}_prepared_refStars"] = pipeBase.connectionTypes.Output(
306 doc=f
"The number of {name} reference stars matched to fittedStars.",
307 name=f
"metricvalue_jointcal_{name}_prepared_refStars",
308 storageClass=
"MetricValue",
309 dimensions=(
"skymap",
"tract",
"instrument",
"physical_filter"),
311 vars()[f
"{name}_prepared_fittedStars"] = pipeBase.connectionTypes.Output(
312 doc=f
"The number of cross-matched fittedStars after cleanup, for {name}.",
313 name=f
"metricvalue_jointcal_{name}_prepared_fittedStars",
314 storageClass=
"MetricValue",
315 dimensions=(
"skymap",
"tract",
"instrument",
"physical_filter"),
317 vars()[f
"{name}_prepared_ccdImages"] = pipeBase.connectionTypes.Output(
318 doc=f
"The number of ccdImages that will be fit for {name}, after cleanup.",
319 name=f
"metricvalue_jointcal_{name}_prepared_ccdImages",
320 storageClass=
"MetricValue",
321 dimensions=(
"skymap",
"tract",
"instrument",
"physical_filter"),
323 vars()[f
"{name}_final_chi2"] = pipeBase.connectionTypes.Output(
324 doc=f
"The final chi2 of the {name} fit.",
325 name=f
"metricvalue_jointcal_{name}_final_chi2",
326 storageClass=
"MetricValue",
327 dimensions=(
"skymap",
"tract",
"instrument",
"physical_filter"),
329 vars()[f
"{name}_final_ndof"] = pipeBase.connectionTypes.Output(
330 doc=f
"The number of degrees of freedom of the fitted {name}.",
331 name=f
"metricvalue_jointcal_{name}_final_ndof",
332 storageClass=
"MetricValue",
333 dimensions=(
"skymap",
"tract",
"instrument",
"physical_filter"),
344 if not config.doAstrometry:
345 self.prerequisiteInputs.remove(
"astrometryRefCat")
346 self.outputs.remove(
"outputWcs")
347 for key
in list(self.outputs):
348 if "metricvalue_jointcal_astrometry" in key:
349 self.outputs.remove(key)
350 if not config.doPhotometry:
351 self.prerequisiteInputs.remove(
"photometryRefCat")
352 self.outputs.remove(
"outputPhotoCalib")
353 for key
in list(self.outputs):
354 if "metricvalue_jointcal_photometry" in key:
355 self.outputs.remove(key)
359 pipelineConnections=JointcalTaskConnections):
360 """Configuration for JointcalTask"""
362 doAstrometry = pexConfig.Field(
363 doc=
"Fit astrometry and write the fitted result.",
367 doPhotometry = pexConfig.Field(
368 doc=
"Fit photometry and write the fitted result.",
372 coaddName = pexConfig.Field(
373 doc=
"Type of coadd, typically deep or goodSeeing",
378 sourceFluxType = pexConfig.Field(
380 doc=
"Source flux field to use in source selection and to get fluxes from the catalog.",
383 positionErrorPedestal = pexConfig.Field(
384 doc=
"Systematic term to apply to the measured position error (pixels)",
388 photometryErrorPedestal = pexConfig.Field(
389 doc=
"Systematic term to apply to the measured error on flux or magnitude as a "
390 "fraction of source flux or magnitude delta (e.g. 0.05 is 5% of flux or +50 millimag).",
395 matchCut = pexConfig.Field(
396 doc=
"Matching radius between fitted and reference stars (arcseconds)",
400 minMeasurements = pexConfig.Field(
401 doc=
"Minimum number of associated measured stars for a fitted star to be included in the fit",
405 minMeasuredStarsPerCcd = pexConfig.Field(
406 doc=
"Minimum number of measuredStars per ccdImage before printing warnings",
410 minRefStarsPerCcd = pexConfig.Field(
411 doc=
"Minimum number of measuredStars per ccdImage before printing warnings",
415 allowLineSearch = pexConfig.Field(
416 doc=
"Allow a line search during minimization, if it is reasonable for the model"
417 " (models with a significant non-linear component, e.g. constrainedPhotometry).",
421 astrometrySimpleOrder = pexConfig.Field(
422 doc=
"Polynomial order for fitting the simple astrometry model.",
426 astrometryChipOrder = pexConfig.Field(
427 doc=
"Order of the per-chip transform for the constrained astrometry model.",
431 astrometryVisitOrder = pexConfig.Field(
432 doc=
"Order of the per-visit transform for the constrained astrometry model.",
436 useInputWcs = pexConfig.Field(
437 doc=
"Use the input calexp WCSs to initialize a SimpleAstrometryModel.",
441 astrometryModel = pexConfig.ChoiceField(
442 doc=
"Type of model to fit to astrometry",
444 default=
"constrained",
445 allowed={
"simple":
"One polynomial per ccd",
446 "constrained":
"One polynomial per ccd, and one polynomial per visit"}
448 photometryModel = pexConfig.ChoiceField(
449 doc=
"Type of model to fit to photometry",
451 default=
"constrainedMagnitude",
452 allowed={
"simpleFlux":
"One constant zeropoint per ccd and visit, fitting in flux space.",
453 "constrainedFlux":
"Constrained zeropoint per ccd, and one polynomial per visit,"
454 " fitting in flux space.",
455 "simpleMagnitude":
"One constant zeropoint per ccd and visit,"
456 " fitting in magnitude space.",
457 "constrainedMagnitude":
"Constrained zeropoint per ccd, and one polynomial per visit,"
458 " fitting in magnitude space.",
461 applyColorTerms = pexConfig.Field(
462 doc=
"Apply photometric color terms to reference stars?"
463 "Requires that colorterms be set to a ColortermLibrary",
467 colorterms = pexConfig.ConfigField(
468 doc=
"Library of photometric reference catalog name to color term dict.",
469 dtype=ColortermLibrary,
471 photometryVisitOrder = pexConfig.Field(
472 doc=
"Order of the per-visit polynomial transform for the constrained photometry model.",
476 photometryDoRankUpdate = pexConfig.Field(
477 doc=(
"Do the rank update step during minimization. "
478 "Skipping this can help deal with models that are too non-linear."),
482 astrometryDoRankUpdate = pexConfig.Field(
483 doc=(
"Do the rank update step during minimization (should not change the astrometry fit). "
484 "Skipping this can help deal with models that are too non-linear."),
488 outlierRejectSigma = pexConfig.Field(
489 doc=
"How many sigma to reject outliers at during minimization.",
493 astrometryOutlierRelativeTolerance = pexConfig.Field(
494 doc=(
"Convergence tolerance for outlier rejection threshold when fitting astrometry. Iterations will "
495 "stop when the fractional change in the chi2 cut level is below this value. If tolerance is set "
496 "to zero, iterations will continue until there are no more outliers. We suggest a value of 0.002"
497 "as a balance between a shorter minimization runtime and achieving a final fitted model that is"
498 "close to the solution found when removing all outliers."),
502 maxPhotometrySteps = pexConfig.Field(
503 doc=
"Maximum number of minimize iterations to take when fitting photometry.",
507 maxAstrometrySteps = pexConfig.Field(
508 doc=
"Maximum number of minimize iterations to take when fitting astrometry.",
512 astrometryRefObjLoader = pexConfig.ConfigurableField(
513 target=LoadIndexedReferenceObjectsTask,
514 doc=
"Reference object loader for astrometric fit",
516 photometryRefObjLoader = pexConfig.ConfigurableField(
517 target=LoadIndexedReferenceObjectsTask,
518 doc=
"Reference object loader for photometric fit",
520 sourceSelector = sourceSelectorRegistry.makeField(
521 doc=
"How to select sources for cross-matching",
524 astrometryReferenceSelector = pexConfig.ConfigurableField(
525 target=ReferenceSourceSelectorTask,
526 doc=
"How to down-select the loaded astrometry reference catalog.",
528 photometryReferenceSelector = pexConfig.ConfigurableField(
529 target=ReferenceSourceSelectorTask,
530 doc=
"How to down-select the loaded photometry reference catalog.",
532 astrometryReferenceErr = pexConfig.Field(
533 doc=(
"Uncertainty on reference catalog coordinates [mas] to use in place of the `coord_*Err` fields. "
534 "If None, then raise an exception if the reference catalog is missing coordinate errors. "
535 "If specified, overrides any existing `coord_*Err` values."),
542 writeInitMatrix = pexConfig.Field(
544 doc=(
"Write the pre/post-initialization Hessian and gradient to text files, for debugging. "
545 "Output files will be written to `config.debugOutputPath` and will "
546 "be of the form 'astrometry_[pre|post]init-TRACT-FILTER-mat.txt'. "
547 "Note that these files are the dense versions of the matrix, and so may be very large."),
550 writeChi2FilesInitialFinal = pexConfig.Field(
552 doc=(
"Write .csv files containing the contributions to chi2 for the initialization and final fit. "
553 "Output files will be written to `config.debugOutputPath` and will "
554 "be of the form `astrometry_[initial|final]_chi2-TRACT-FILTER."),
557 writeChi2FilesOuterLoop = pexConfig.Field(
559 doc=(
"Write .csv files containing the contributions to chi2 for the outer fit loop. "
560 "Output files will be written to `config.debugOutputPath` and will "
561 "be of the form `astrometry_init-NN_chi2-TRACT-FILTER`."),
564 writeInitialModel = pexConfig.Field(
566 doc=(
"Write the pre-initialization model to text files, for debugging. "
567 "Output files will be written to `config.debugOutputPath` and will be "
568 "of the form `initial_astrometry_model-TRACT_FILTER.txt`."),
571 debugOutputPath = pexConfig.Field(
574 doc=(
"Path to write debug output files to. Used by "
575 "`writeInitialModel`, `writeChi2Files*`, `writeInitMatrix`.")
577 detailedProfile = pexConfig.Field(
580 doc=
"Output separate profiling information for different parts of jointcal, e.g. data read, fitting"
586 msg =
"applyColorTerms=True requires the `colorterms` field be set to a ColortermLibrary."
587 raise pexConfig.FieldValidationError(JointcalConfig.colorterms, self, msg)
589 msg = (
"Only doing astrometry, but Colorterms are not applied for astrometry;"
590 "applyColorTerms=True will be ignored.")
591 lsst.log.warning(msg)
599 self.
sourceSelectorsourceSelector[
'science'].doSignalToNoise =
True
602 self.
sourceSelectorsourceSelector[
'science'].signalToNoise.minimum = 10.
604 fluxField = f
"slot_{self.sourceFluxType}Flux_instFlux"
605 self.
sourceSelectorsourceSelector[
'science'].signalToNoise.fluxField = fluxField
606 self.
sourceSelectorsourceSelector[
'science'].signalToNoise.errField = fluxField +
"Err"
612 badFlags = [
'base_PixelFlags_flag_edge',
'base_PixelFlags_flag_saturated',
613 'base_PixelFlags_flag_interpolatedCenter',
'base_SdssCentroid_flag',
614 'base_PsfFlux_flag',
'base_PixelFlags_flag_suspectCenter']
626 """Write model to outfile."""
627 with open(filename,
"w")
as file:
628 file.write(repr(model))
629 log.info(
"Wrote %s to file: %s", model, filename)
632 @dataclasses.dataclass
634 """The input data jointcal needs for each detector/visit."""
636 """The visit identifier of this exposure."""
638 """The catalog derived from this exposure."""
640 """The VisitInfo of this exposure."""
642 """The detector of this exposure."""
644 """The photometric calibration of this exposure."""
646 """The WCS of this exposure."""
648 """The bounding box of this exposure."""
650 """The filter of this exposure."""
654 """Astrometricly and photometricly calibrate across multiple visits of the
659 butler : `lsst.daf.persistence.Butler`
660 The butler is passed to the refObjLoader constructor in case it is
661 needed. Ignored if the refObjLoader argument provides a loader directly.
662 Used to initialize the astrometry and photometry refObjLoaders.
663 initInputs : `dict`, optional
664 Dictionary used to initialize PipelineTasks (empty for jointcal).
667 ConfigClass = JointcalConfig
668 RunnerClass = JointcalRunner
669 _DefaultName =
"jointcal"
671 def __init__(self, butler=None, initInputs=None, **kwargs):
673 self.makeSubtask(
"sourceSelector")
674 if self.config.doAstrometry:
675 if initInputs
is None:
677 self.makeSubtask(
'astrometryRefObjLoader', butler=butler)
678 self.makeSubtask(
"astrometryReferenceSelector")
681 if self.config.doPhotometry:
682 if initInputs
is None:
684 self.makeSubtask(
'photometryRefObjLoader', butler=butler)
685 self.makeSubtask(
"photometryReferenceSelector")
690 self.
jobjob = Job.load_metrics_package(subset=
'jointcal')
695 inputs = butlerQC.get(inputRefs)
697 tract = butlerQC.quantum.dataId[
'tract']
698 if self.config.doAstrometry:
700 dataIds=[ref.datasetRef.dataId
701 for ref
in inputRefs.astrometryRefCat],
702 refCats=inputs.pop(
'astrometryRefCat'),
703 config=self.config.astrometryRefObjLoader,
705 if self.config.doPhotometry:
707 dataIds=[ref.datasetRef.dataId
708 for ref
in inputRefs.photometryRefCat],
709 refCats=inputs.pop(
'photometryRefCat'),
710 config=self.config.photometryRefObjLoader,
712 outputs = self.
runrun(**inputs, tract=tract)
713 self.
_put_metrics_put_metrics(butlerQC, outputs.job, outputRefs)
714 if self.config.doAstrometry:
715 self.
_put_output_put_output(butlerQC, outputs.outputWcs, outputRefs.outputWcs,
716 inputs[
'inputCamera'],
"setWcs")
717 if self.config.doPhotometry:
718 self.
_put_output_put_output(butlerQC, outputs.outputPhotoCalib, outputRefs.outputPhotoCalib,
719 inputs[
'inputCamera'],
"setPhotoCalib")
721 def _put_metrics(self, butlerQC, job, outputRefs):
722 """Persist all measured metrics stored in a job.
726 butlerQC : `lsst.pipe.base.ButlerQuantumContext`
727 A butler which is specialized to operate in the context of a
728 `lsst.daf.butler.Quantum`; This is the input to `runQuantum`.
729 job : `lsst.verify.job.Job`
730 Measurements of metrics to persist.
731 outputRefs : `list` [`lsst.pipe.base.connectionTypes.OutputQuantizedConnection`]
732 The DatasetRefs to persist the data to.
734 for key
in job.measurements.keys():
735 butlerQC.put(job.measurements[key], getattr(outputRefs, key.fqn.replace(
'jointcal.',
'')))
737 def _put_output(self, butlerQC, outputs, outputRefs, camera, setter):
738 """Persist the output datasets to their appropriate datarefs.
742 butlerQC : `lsst.pipe.base.ButlerQuantumContext`
743 A butler which is specialized to operate in the context of a
744 `lsst.daf.butler.Quantum`; This is the input to `runQuantum`.
745 outputs : `dict` [`tuple`, `lsst.afw.geom.SkyWcs`] or
746 `dict` [`tuple, `lsst.afw.image.PhotoCalib`]
747 The fitted objects to persist.
748 outputRefs : `list` [`lsst.pipe.base.connectionTypes.OutputQuantizedConnection`]
749 The DatasetRefs to persist the data to.
750 camera : `lsst.afw.cameraGeom.Camera`
751 The camera for this instrument, to get detector ids from.
753 The method to call on the ExposureCatalog to set each output.
756 schema.addField(
'visit', type=
'I', doc=
'Visit number')
758 def new_catalog(visit, size):
759 """Return an catalog ready to be filled with appropriate output."""
762 catalog[
'visit'] = visit
764 metadata.add(
"COMMENT",
"Catalog id is detector id, sorted.")
765 metadata.add(
"COMMENT",
"Only detectors with data have entries.")
769 detectors_per_visit = collections.defaultdict(int)
772 detectors_per_visit[key[0]] += 1
774 for ref
in outputRefs:
775 visit = ref.dataId[
'visit']
776 catalog = new_catalog(visit, detectors_per_visit[visit])
779 for detector
in camera:
780 detectorId = detector.getId()
781 key = (ref.dataId[
'visit'], detectorId)
782 if key
not in outputs:
784 self.log.debug(
"No %s output for detector %s in visit %s",
785 setter[3:], detectorId, visit)
788 catalog[i].setId(detectorId)
789 getattr(catalog[i], setter)(outputs[key])
793 butlerQC.put(catalog, ref)
794 self.log.info(
"Wrote %s detectors to %s", i, ref)
796 def run(self, inputSourceTableVisit, inputVisitSummary, inputCamera, tract=None):
802 sourceFluxField =
"flux"
806 oldWcsList, bands = self.
_load_data_load_data(inputSourceTableVisit,
812 boundingCircle, center, radius, defaultFilter, epoch = self.
_prep_sky_prep_sky(associations, bands)
814 if self.config.doAstrometry:
818 referenceSelector=self.astrometryReferenceSelector,
822 astrometry_output = self.
_make_output_make_output(associations.getCcdImageList(),
826 astrometry_output =
None
828 if self.config.doPhotometry:
832 referenceSelector=self.photometryReferenceSelector,
836 reject_bad_fluxes=
True)
837 photometry_output = self.
_make_output_make_output(associations.getCcdImageList(),
841 photometry_output =
None
843 return pipeBase.Struct(outputWcs=astrometry_output,
844 outputPhotoCalib=photometry_output,
849 def _make_schema_table(self):
850 """Return an afw SourceTable to use as a base for creating the
851 SourceCatalog to insert values from the dataFrame into.
855 table : `lsst.afw.table.SourceTable`
856 Table with schema and slots to use to make SourceCatalogs.
859 schema.addField(
"centroid_x",
"D")
860 schema.addField(
"centroid_y",
"D")
861 schema.addField(
"centroid_xErr",
"F")
862 schema.addField(
"centroid_yErr",
"F")
863 schema.addField(
"shape_xx",
"D")
864 schema.addField(
"shape_yy",
"D")
865 schema.addField(
"shape_xy",
"D")
866 schema.addField(
"flux_instFlux",
"D")
867 schema.addField(
"flux_instFluxErr",
"D")
869 table.defineCentroid(
"centroid")
870 table.defineShape(
"shape")
873 def _extract_detector_catalog_from_visit_catalog(self, table, visitCatalog, detectorId,
874 detectorColumn, ixxColumns):
875 """Return an afw SourceCatalog extracted from a visit-level dataframe,
876 limited to just one detector.
880 table : `lsst.afw.table.SourceTable`
881 Table factory to use to make the SourceCatalog that will be
882 populated with data from ``visitCatalog``.
883 visitCatalog : `pandas.DataFrame`
884 DataFrame to extract a detector catalog from.
886 Numeric id of the detector to extract from ``visitCatalog``.
887 detectorColumn : `str`
888 Name of the detector column in the catalog.
889 ixxColumns : `list` [`str`]
890 Names of the ixx/iyy/ixy columns in the catalog.
894 catalog : `lsst.afw.table.SourceCatalog`
895 Detector-level catalog extracted from ``visitCatalog``.
898 mapping = {
'x':
'centroid_x',
900 'xErr':
'centroid_xErr',
901 'yErr':
'centroid_yErr',
902 ixxColumns[0]:
'shape_xx',
903 ixxColumns[1]:
'shape_yy',
904 ixxColumns[2]:
'shape_xy',
905 f
'{self.config.sourceFluxType}_instFlux':
'flux_instFlux',
906 f
'{self.config.sourceFluxType}_instFluxErr':
'flux_instFluxErr',
910 matched = visitCatalog[detectorColumn] == detectorId
911 catalog.resize(sum(matched))
912 view = visitCatalog.loc[matched]
913 catalog[
'id'] = view.index
914 for dfCol, afwCol
in mapping.items():
915 catalog[afwCol] = view[dfCol]
917 self.log.debug(
"%d sources selected in visit %d detector %d",
919 view[
'visit'].iloc[0],
923 def _load_data(self, inputSourceTableVisit, inputVisitSummary, associations,
924 jointcalControl, camera):
925 """Read the data that jointcal needs to run. (Gen3 version)
927 Modifies ``associations`` in-place with the loaded data.
931 inputSourceTableVisit : `list` [`lsst.daf.butler.DeferredDatasetHandle`]
932 References to visit-level DataFrames to load the catalog data from.
933 inputVisitSummary : `list` [`lsst.daf.butler.DeferredDatasetHandle`]
934 Visit-level exposure summary catalog with metadata.
935 associations : `lsst.jointcal.Associations`
936 Object to add the loaded data to by constructing new CcdImages.
937 jointcalControl : `jointcal.JointcalControl`
938 Control object for C++ associations management.
939 camera : `lsst.afw.cameraGeom.Camera`
940 Camera object for detector geometry.
944 oldWcsList: `list` [`lsst.afw.geom.SkyWcs`]
945 The original WCS of the input data, to aid in writing tests.
946 bands : `list` [`str`]
947 The filter bands of each input dataset.
951 load_cat_prof_file =
'jointcal_load_data.prof' if self.config.detailedProfile
else ''
952 with pipeBase.cmdLineTask.profile(load_cat_prof_file):
955 catalogMap = {ref.dataId[
'visit']: i
for i, ref
in enumerate(inputSourceTableVisit)}
956 detectorDict = {detector.getId(): detector
for detector
in camera}
960 for visitSummaryRef
in inputVisitSummary:
961 visitSummary = visitSummaryRef.get()
963 dataRef = inputSourceTableVisit[catalogMap[visitSummaryRef.dataId[
'visit']]]
965 inColumns = dataRef.get(component=
'columns')
967 visitCatalog = dataRef.get(parameters={
'columns': columns})
969 selected = self.sourceSelector.
run(visitCatalog)
972 detectors = {id: index
for index, id
in enumerate(visitSummary[
'id'])}
973 for id, index
in detectors.items():
975 detColumn, ixxColumns)
976 data = self.
_make_one_input_data_make_one_input_data(visitSummary[index], catalog, detectorDict)
977 result = self.
_build_ccdImage_build_ccdImage(data, associations, jointcalControl)
978 if result
is not None:
979 oldWcsList.append(result.wcs)
981 filters.append(data.filter)
982 if len(filters) == 0:
983 raise RuntimeError(
"No data to process: did source selector remove all sources?")
984 filters = collections.Counter(filters)
986 return oldWcsList, filters
988 def _make_one_input_data(self, visitRecord, catalog, detectorDict):
989 """Return a data structure for this detector+visit."""
992 visitInfo=visitRecord.getVisitInfo(),
993 detector=detectorDict[visitRecord.getId()],
994 photoCalib=visitRecord.getPhotoCalib(),
995 wcs=visitRecord.getWcs(),
996 bbox=visitRecord.getBBox(),
1000 physical=visitRecord[
'physical_filter']))
1002 def _get_sourceTable_visit_columns(self, inColumns):
1004 Get the sourceTable_visit columns from the config.
1009 List of columns available in the sourceTable_visit
1014 List of columns to read from sourceTable_visit.
1015 detectorColumn : `str`
1016 Name of the detector column.
1018 Name of the ixx/iyy/ixy columns.
1020 if 'detector' in inColumns:
1022 detectorColumn =
'detector'
1025 detectorColumn =
'ccd'
1027 columns = [
'visit', detectorColumn,
1028 'sourceId',
'x',
'xErr',
'y',
'yErr',
1029 self.config.sourceFluxType +
'_instFlux', self.config.sourceFluxType +
'_instFluxErr']
1031 if 'ixx' in inColumns:
1033 ixxColumns = [
'ixx',
'iyy',
'ixy']
1036 ixxColumns = [
'Ixx',
'Iyy',
'Ixy']
1037 columns.extend(ixxColumns)
1039 if self.sourceSelector.config.doFlags:
1040 columns.extend(self.sourceSelector.config.flags.bad)
1041 if self.sourceSelector.config.doUnresolved:
1042 columns.append(self.sourceSelector.config.unresolved.name)
1043 if self.sourceSelector.config.doIsolated:
1044 columns.append(self.sourceSelector.config.isolated.parentName)
1045 columns.append(self.sourceSelector.config.isolated.nChildName)
1047 return columns, detectorColumn, ixxColumns
1052 def _getMetadataName(self):
1056 def _makeArgumentParser(cls):
1057 """Create an argument parser"""
1058 parser = pipeBase.ArgumentParser(name=cls.
_DefaultName_DefaultName)
1059 parser.add_id_argument(
"--id",
"calexp", help=
"data ID, e.g. --id visit=6789 ccd=0..9",
1060 ContainerClass=PerTractCcdDataIdContainer)
1063 def _build_ccdImage(self, data, associations, jointcalControl):
1065 Extract the necessary things from this catalog+metadata to add a new
1070 data : `JointcalInputData`
1071 The loaded input data.
1072 associations : `lsst.jointcal.Associations`
1073 Object to add the info to, to construct a new CcdImage
1074 jointcalControl : `jointcal.JointcalControl`
1075 Control object for associations management
1079 namedtuple or `None`
1081 The TAN WCS of this image, read from the calexp
1082 (`lsst.afw.geom.SkyWcs`).
1084 A key to identify this dataRef by its visit and ccd ids
1087 if there are no sources in the loaded catalog.
1089 if len(data.catalog) == 0:
1090 self.log.warning(
"No sources selected in visit %s ccd %s", data.visit, data.detector.getId())
1093 associations.createCcdImage(data.catalog,
1097 data.filter.physicalLabel,
1101 data.detector.getId(),
1104 Result = collections.namedtuple(
'Result_from_build_CcdImage', (
'wcs',
'key'))
1105 Key = collections.namedtuple(
'Key', (
'visit',
'ccd'))
1106 return Result(data.wcs, Key(data.visit, data.detector.getId()))
1108 def _readDataId(self, butler, dataId):
1109 """Read all of the data for one dataId from the butler. (gen2 version)"""
1111 if "visit" in dataId.keys():
1112 visit = dataId[
"visit"]
1114 visit = butler.getButler().queryMetadata(
"calexp", (
"visit"), butler.dataId)[0]
1115 detector = butler.get(
'calexp_detector', dataId=dataId)
1117 catalog = butler.get(
'src',
1118 flags=lsst.afw.table.SOURCE_IO_NO_FOOTPRINTS,
1120 goodSrc = self.sourceSelector.
run(catalog)
1121 self.log.debug(
"%d sources selected in visit %d detector %d",
1122 len(goodSrc.sourceCat),
1126 catalog=goodSrc.sourceCat,
1127 visitInfo=butler.get(
'calexp_visitInfo', dataId=dataId),
1129 photoCalib=butler.get(
'calexp_photoCalib', dataId=dataId),
1130 wcs=butler.get(
'calexp_wcs', dataId=dataId),
1131 bbox=butler.get(
'calexp_bbox', dataId=dataId),
1132 filter=butler.get(
'calexp_filterLabel', dataId=dataId))
1134 def loadData(self, dataRefs, associations, jointcalControl):
1135 """Read the data that jointcal needs to run. (Gen2 version)"""
1136 visit_ccd_to_dataRef = {}
1139 load_cat_prof_file =
'jointcal_loadData.prof' if self.config.detailedProfile
else ''
1140 with pipeBase.cmdLineTask.profile(load_cat_prof_file):
1142 camera = dataRefs[0].get(
'camera', immediate=
True)
1144 for dataRef
in dataRefs:
1145 data = self.
_readDataId_readDataId(dataRef.getButler(), dataRef.dataId)
1146 result = self.
_build_ccdImage_build_ccdImage(data, associations, jointcalControl)
1149 oldWcsList.append(result.wcs)
1150 visit_ccd_to_dataRef[result.key] = dataRef
1151 filters.append(data.filter)
1152 if len(filters) == 0:
1153 raise RuntimeError(
"No data to process: did source selector remove all sources?")
1154 filters = collections.Counter(filters)
1156 return oldWcsList, filters, visit_ccd_to_dataRef
1158 def _getDebugPath(self, filename):
1159 """Constructs a path to filename using the configured debug path.
1161 return os.path.join(self.config.debugOutputPath, filename)
1163 def _prep_sky(self, associations, filters):
1164 """Prepare on-sky and other data that must be computed after data has
1167 associations.computeCommonTangentPoint()
1169 boundingCircle = associations.computeBoundingCircle()
1171 radius =
lsst.geom.Angle(boundingCircle.getOpeningAngle().asRadians(), lsst.geom.radians)
1173 self.log.info(f
"Data has center={center} with radius={radius.asDegrees()} degrees.")
1176 defaultFilter = filters.most_common(1)[0][0]
1177 self.log.debug(
"Using '%s' filter for reference flux", defaultFilter.physicalLabel)
1181 associations.setEpoch(epoch.jyear)
1183 return boundingCircle, center, radius, defaultFilter, epoch
1185 @pipeBase.timeMethod
1188 Jointly calibrate the astrometry and photometry across a set of images.
1190 NOTE: this is for gen2 middleware only.
1194 dataRefs : `list` of `lsst.daf.persistence.ButlerDataRef`
1195 List of data references to the exposures to be fit.
1199 result : `lsst.pipe.base.Struct`
1200 Struct of metadata from the fit, containing:
1203 The provided data references that were fit (with updated WCSs)
1205 The original WCS from each dataRef
1207 Dictionary of internally-computed metrics for testing/validation.
1209 if len(dataRefs) == 0:
1210 raise ValueError(
'Need a non-empty list of data references!')
1214 sourceFluxField =
"slot_%sFlux" % (self.config.sourceFluxType,)
1218 oldWcsList, filters, visit_ccd_to_dataRef = self.
loadDataloadData(dataRefs,
1222 boundingCircle, center, radius, defaultFilter, epoch = self.
_prep_sky_prep_sky(associations, filters)
1224 tract = dataRefs[0].dataId[
'tract']
1226 if self.config.doAstrometry:
1230 referenceSelector=self.astrometryReferenceSelector,
1238 if self.config.doPhotometry:
1242 referenceSelector=self.photometryReferenceSelector,
1246 reject_bad_fluxes=
True)
1251 return pipeBase.Struct(dataRefs=dataRefs,
1252 oldWcsList=oldWcsList,
1256 defaultFilter=defaultFilter,
1258 exitStatus=exitStatus)
1260 def _get_refcat_coordinate_error_override(self, refCat, name):
1261 """Check whether we should override the refcat coordinate errors, and
1262 return the overridden error if necessary.
1266 refCat : `lsst.afw.table.SimpleCatalog`
1267 The reference catalog to check for a ``coord_raErr`` field.
1269 Whether we are doing "astrometry" or "photometry".
1273 refCoordErr : `float`
1274 The refcat coordinate error to use, or NaN if we are not overriding
1279 lsst.pex.config.FieldValidationError
1280 Raised if the refcat does not contain coordinate errors and
1281 ``config.astrometryReferenceErr`` is not set.
1285 if name.lower() ==
"photometry":
1286 if 'coord_raErr' not in refCat.schema:
1291 if self.config.astrometryReferenceErr
is None and 'coord_raErr' not in refCat.schema:
1292 msg = (
"Reference catalog does not contain coordinate errors, "
1293 "and config.astrometryReferenceErr not supplied.")
1294 raise pexConfig.FieldValidationError(JointcalConfig.astrometryReferenceErr,
1298 if self.config.astrometryReferenceErr
is not None and 'coord_raErr' in refCat.schema:
1299 self.log.warning(
"Overriding reference catalog coordinate errors with %f/coordinate [mas]",
1300 self.config.astrometryReferenceErr)
1302 if self.config.astrometryReferenceErr
is None:
1305 return self.config.astrometryReferenceErr
1307 def _compute_proper_motion_epoch(self, ccdImageList):
1308 """Return the proper motion correction epoch of the provided images.
1312 ccdImageList : `list` [`lsst.jointcal.CcdImage`]
1313 The images to compute the appropriate epoch for.
1317 epoch : `astropy.time.Time`
1318 The date to use for proper motion corrections.
1320 return astropy.time.Time(np.mean([ccdImage.getEpoch()
for ccdImage
in ccdImageList]),
1324 def _do_load_refcat_and_fit(self, associations, defaultFilter, center, radius,
1325 tract="", match_cut=3.0,
1326 reject_bad_fluxes=False, *,
1327 name="", refObjLoader=None, referenceSelector=None,
1328 fit_function=None, epoch=None):
1329 """Load reference catalog, perform the fit, and return the result.
1333 associations : `lsst.jointcal.Associations`
1334 The star/reference star associations to fit.
1335 defaultFilter : `lsst.afw.image.FilterLabel`
1336 filter to load from reference catalog.
1337 center : `lsst.geom.SpherePoint`
1338 ICRS center of field to load from reference catalog.
1339 radius : `lsst.geom.Angle`
1340 On-sky radius to load from reference catalog.
1342 Name of thing being fit: "astrometry" or "photometry".
1343 refObjLoader : `lsst.meas.algorithms.LoadReferenceObjectsTask`
1344 Reference object loader to use to load a reference catalog.
1345 referenceSelector : `lsst.meas.algorithms.ReferenceSourceSelectorTask`
1346 Selector to use to pick objects from the loaded reference catalog.
1347 fit_function : callable
1348 Function to call to perform fit (takes Associations object).
1349 tract : `str`, optional
1350 Name of tract currently being fit.
1351 match_cut : `float`, optional
1352 Radius in arcseconds to find cross-catalog matches to during
1353 associations.associateCatalogs.
1354 reject_bad_fluxes : `bool`, optional
1355 Reject refCat sources with NaN/inf flux or NaN/0 fluxErr.
1356 epoch : `astropy.time.Time`, optional
1357 Epoch to which to correct refcat proper motion and parallax,
1358 or `None` to not apply such corrections.
1362 result : `Photometry` or `Astrometry`
1363 Result of `fit_function()`
1365 self.log.info(
"====== Now processing %s...", name)
1368 associations.associateCatalogs(match_cut)
1370 associations.fittedStarListSize())
1372 applyColorterms =
False if name.lower() ==
"astrometry" else self.config.applyColorTerms
1374 center, radius, defaultFilter,
1375 applyColorterms=applyColorterms,
1379 associations.collectRefStars(refCat,
1380 self.config.matchCut*lsst.geom.arcseconds,
1382 refCoordinateErr=refCoordErr,
1383 rejectBadFluxes=reject_bad_fluxes)
1385 associations.refStarListSize())
1387 associations.prepareFittedStars(self.config.minMeasurements)
1391 associations.nFittedStarsWithAssociatedRefStar())
1393 associations.fittedStarListSize())
1395 associations.nCcdImagesValidForFit())
1397 load_cat_prof_file =
'jointcal_fit_%s.prof'%name
if self.config.detailedProfile
else ''
1398 dataName =
"{}_{}".format(tract, defaultFilter.physicalLabel)
1399 with pipeBase.cmdLineTask.profile(load_cat_prof_file):
1400 result = fit_function(associations, dataName)
1403 if self.config.writeChi2FilesInitialFinal:
1404 baseName = self.
_getDebugPath_getDebugPath(f
"{name}_final_chi2-{dataName}")
1405 result.fit.saveChi2Contributions(baseName+
"{type}")
1406 self.log.info(
"Wrote chi2 contributions files: %s", baseName)
1410 def _load_reference_catalog(self, refObjLoader, referenceSelector, center, radius, filterLabel,
1411 applyColorterms=False, epoch=None):
1412 """Load the necessary reference catalog sources, convert fluxes to
1413 correct units, and apply color term corrections if requested.
1417 refObjLoader : `lsst.meas.algorithms.LoadReferenceObjectsTask`
1418 The reference catalog loader to use to get the data.
1419 referenceSelector : `lsst.meas.algorithms.ReferenceSourceSelectorTask`
1420 Source selector to apply to loaded reference catalog.
1421 center : `lsst.geom.SpherePoint`
1422 The center around which to load sources.
1423 radius : `lsst.geom.Angle`
1424 The radius around ``center`` to load sources in.
1425 filterLabel : `lsst.afw.image.FilterLabel`
1426 The camera filter to load fluxes for.
1427 applyColorterms : `bool`
1428 Apply colorterm corrections to the refcat for ``filterName``?
1429 epoch : `astropy.time.Time`, optional
1430 Epoch to which to correct refcat proper motion and parallax,
1431 or `None` to not apply such corrections.
1435 refCat : `lsst.afw.table.SimpleCatalog`
1436 The loaded reference catalog.
1438 The name of the reference catalog flux field appropriate for ``filterName``.
1440 skyCircle = refObjLoader.loadSkyCircle(center,
1442 filterLabel.bandLabel,
1445 selected = referenceSelector.run(skyCircle.refCat)
1447 if not selected.sourceCat.isContiguous():
1448 refCat = selected.sourceCat.copy(deep=
True)
1450 refCat = selected.sourceCat
1453 refCatName = refObjLoader.ref_dataset_name
1454 self.log.info(
"Applying color terms for physical filter=%r reference catalog=%s",
1455 filterLabel.physicalLabel, refCatName)
1456 colorterm = self.config.colorterms.getColorterm(filterLabel.physicalLabel,
1460 refMag, refMagErr = colorterm.getCorrectedMagnitudes(refCat)
1461 refCat[skyCircle.fluxField] = u.Magnitude(refMag, u.ABmag).to_value(u.nJy)
1463 refCat[skyCircle.fluxField+
'Err'] = fluxErrFromABMagErr(refMagErr, refMag) * 1e9
1465 return refCat, skyCircle.fluxField
1467 def _check_star_lists(self, associations, name):
1469 if associations.nCcdImagesValidForFit() == 0:
1470 raise RuntimeError(
'No images in the ccdImageList!')
1471 if associations.fittedStarListSize() == 0:
1472 raise RuntimeError(
'No stars in the {} fittedStarList!'.format(name))
1473 if associations.refStarListSize() == 0:
1474 raise RuntimeError(
'No stars in the {} reference star list!'.format(name))
1476 def _logChi2AndValidate(self, associations, fit, model, chi2Label, writeChi2Name=None):
1477 """Compute chi2, log it, validate the model, and return chi2.
1481 associations : `lsst.jointcal.Associations`
1482 The star/reference star associations to fit.
1483 fit : `lsst.jointcal.FitterBase`
1484 The fitter to use for minimization.
1485 model : `lsst.jointcal.Model`
1486 The model being fit.
1488 Label to describe the chi2 (e.g. "Initialized", "Final").
1489 writeChi2Name : `str`, optional
1490 Filename prefix to write the chi2 contributions to.
1491 Do not supply an extension: an appropriate one will be added.
1495 chi2: `lsst.jointcal.Chi2Accumulator`
1496 The chi2 object for the current fitter and model.
1501 Raised if chi2 is infinite or NaN.
1503 Raised if the model is not valid.
1505 if writeChi2Name
is not None:
1507 fit.saveChi2Contributions(fullpath+
"{type}")
1508 self.log.info(
"Wrote chi2 contributions files: %s", fullpath)
1510 chi2 = fit.computeChi2()
1511 self.log.info(
"%s %s", chi2Label, chi2)
1513 if not np.isfinite(chi2.chi2):
1514 raise FloatingPointError(f
'{chi2Label} chi2 is invalid: {chi2}')
1515 if not model.validate(associations.getCcdImageList(), chi2.ndof):
1516 raise ValueError(
"Model is not valid: check log messages for warnings.")
1519 def _fit_photometry(self, associations, dataName=None):
1521 Fit the photometric data.
1525 associations : `lsst.jointcal.Associations`
1526 The star/reference star associations to fit.
1528 Name of the data being processed (e.g. "1234_HSC-Y"), for
1529 identifying debugging files.
1533 fit_result : `namedtuple`
1534 fit : `lsst.jointcal.PhotometryFit`
1535 The photometric fitter used to perform the fit.
1536 model : `lsst.jointcal.PhotometryModel`
1537 The photometric model that was fit.
1539 self.log.info(
"=== Starting photometric fitting...")
1542 if self.config.photometryModel ==
"constrainedFlux":
1545 visitOrder=self.config.photometryVisitOrder,
1546 errorPedestal=self.config.photometryErrorPedestal)
1548 doLineSearch = self.config.allowLineSearch
1549 elif self.config.photometryModel ==
"constrainedMagnitude":
1552 visitOrder=self.config.photometryVisitOrder,
1553 errorPedestal=self.config.photometryErrorPedestal)
1555 doLineSearch = self.config.allowLineSearch
1556 elif self.config.photometryModel ==
"simpleFlux":
1558 errorPedestal=self.config.photometryErrorPedestal)
1559 doLineSearch =
False
1560 elif self.config.photometryModel ==
"simpleMagnitude":
1562 errorPedestal=self.config.photometryErrorPedestal)
1563 doLineSearch =
False
1568 if self.config.writeChi2FilesInitialFinal:
1569 baseName = f
"photometry_initial_chi2-{dataName}"
1572 if self.config.writeInitialModel:
1573 fullpath = self.
_getDebugPath_getDebugPath(f
"initial_photometry_model-{dataName}.txt")
1575 self.
_logChi2AndValidate_logChi2AndValidate(associations, fit, model,
"Initialized", writeChi2Name=baseName)
1577 def getChi2Name(whatToFit):
1578 if self.config.writeChi2FilesOuterLoop:
1579 return f
"photometry_init-%s_chi2-{dataName}" % whatToFit
1585 if self.config.writeInitMatrix:
1586 dumpMatrixFile = self.
_getDebugPath_getDebugPath(f
"photometry_preinit-{dataName}")
1589 if self.config.photometryModel.startswith(
"constrained"):
1592 fit.minimize(
"ModelVisit", dumpMatrixFile=dumpMatrixFile)
1593 self.
_logChi2AndValidate_logChi2AndValidate(associations, fit, model,
"Initialize ModelVisit",
1594 writeChi2Name=getChi2Name(
"ModelVisit"))
1597 fit.minimize(
"Model", doLineSearch=doLineSearch, dumpMatrixFile=dumpMatrixFile)
1599 writeChi2Name=getChi2Name(
"Model"))
1601 fit.minimize(
"Fluxes")
1602 self.
_logChi2AndValidate_logChi2AndValidate(associations, fit, model,
"Initialize Fluxes",
1603 writeChi2Name=getChi2Name(
"Fluxes"))
1605 fit.minimize(
"Model Fluxes", doLineSearch=doLineSearch)
1606 self.
_logChi2AndValidate_logChi2AndValidate(associations, fit, model,
"Initialize ModelFluxes",
1607 writeChi2Name=getChi2Name(
"ModelFluxes"))
1609 model.freezeErrorTransform()
1610 self.log.debug(
"Photometry error scales are frozen.")
1614 self.config.maxPhotometrySteps,
1617 doRankUpdate=self.config.photometryDoRankUpdate,
1618 doLineSearch=doLineSearch,
1625 def _fit_astrometry(self, associations, dataName=None):
1627 Fit the astrometric data.
1631 associations : `lsst.jointcal.Associations`
1632 The star/reference star associations to fit.
1634 Name of the data being processed (e.g. "1234_HSC-Y"), for
1635 identifying debugging files.
1639 fit_result : `namedtuple`
1640 fit : `lsst.jointcal.AstrometryFit`
1641 The astrometric fitter used to perform the fit.
1642 model : `lsst.jointcal.AstrometryModel`
1643 The astrometric model that was fit.
1644 sky_to_tan_projection : `lsst.jointcal.ProjectionHandler`
1645 The model for the sky to tangent plane projection that was used in the fit.
1648 self.log.info(
"=== Starting astrometric fitting...")
1650 associations.deprojectFittedStars()
1657 if self.config.astrometryModel ==
"constrained":
1659 sky_to_tan_projection,
1660 chipOrder=self.config.astrometryChipOrder,
1661 visitOrder=self.config.astrometryVisitOrder)
1662 elif self.config.astrometryModel ==
"simple":
1664 sky_to_tan_projection,
1665 self.config.useInputWcs,
1667 order=self.config.astrometrySimpleOrder)
1672 if self.config.writeChi2FilesInitialFinal:
1673 baseName = f
"astrometry_initial_chi2-{dataName}"
1676 if self.config.writeInitialModel:
1677 fullpath = self.
_getDebugPath_getDebugPath(f
"initial_astrometry_model-{dataName}.txt")
1679 self.
_logChi2AndValidate_logChi2AndValidate(associations, fit, model,
"Initial", writeChi2Name=baseName)
1681 def getChi2Name(whatToFit):
1682 if self.config.writeChi2FilesOuterLoop:
1683 return f
"astrometry_init-%s_chi2-{dataName}" % whatToFit
1687 if self.config.writeInitMatrix:
1688 dumpMatrixFile = self.
_getDebugPath_getDebugPath(f
"astrometry_preinit-{dataName}")
1693 if self.config.astrometryModel ==
"constrained":
1694 fit.minimize(
"DistortionsVisit", dumpMatrixFile=dumpMatrixFile)
1695 self.
_logChi2AndValidate_logChi2AndValidate(associations, fit, model,
"Initialize DistortionsVisit",
1696 writeChi2Name=getChi2Name(
"DistortionsVisit"))
1699 fit.minimize(
"Distortions", dumpMatrixFile=dumpMatrixFile)
1700 self.
_logChi2AndValidate_logChi2AndValidate(associations, fit, model,
"Initialize Distortions",
1701 writeChi2Name=getChi2Name(
"Distortions"))
1703 fit.minimize(
"Positions")
1704 self.
_logChi2AndValidate_logChi2AndValidate(associations, fit, model,
"Initialize Positions",
1705 writeChi2Name=getChi2Name(
"Positions"))
1707 fit.minimize(
"Distortions Positions")
1708 self.
_logChi2AndValidate_logChi2AndValidate(associations, fit, model,
"Initialize DistortionsPositions",
1709 writeChi2Name=getChi2Name(
"DistortionsPositions"))
1713 self.config.maxAstrometrySteps,
1715 "Distortions Positions",
1716 sigmaRelativeTolerance=self.config.astrometryOutlierRelativeTolerance,
1717 doRankUpdate=self.config.astrometryDoRankUpdate,
1723 return Astrometry(fit, model, sky_to_tan_projection)
1725 def _check_stars(self, associations):
1726 """Count measured and reference stars per ccd and warn/log them."""
1727 for ccdImage
in associations.getCcdImageList():
1728 nMeasuredStars, nRefStars = ccdImage.countStars()
1729 self.log.debug(
"ccdImage %s has %s measured and %s reference stars",
1730 ccdImage.getName(), nMeasuredStars, nRefStars)
1731 if nMeasuredStars < self.config.minMeasuredStarsPerCcd:
1732 self.log.warning(
"ccdImage %s has only %s measuredStars (desired %s)",
1733 ccdImage.getName(), nMeasuredStars, self.config.minMeasuredStarsPerCcd)
1734 if nRefStars < self.config.minRefStarsPerCcd:
1735 self.log.warning(
"ccdImage %s has only %s RefStars (desired %s)",
1736 ccdImage.getName(), nRefStars, self.config.minRefStarsPerCcd)
1738 def _iterate_fit(self, associations, fitter, max_steps, name, whatToFit,
1740 sigmaRelativeTolerance=0,
1742 doLineSearch=False):
1743 """Run fitter.minimize up to max_steps times, returning the final chi2.
1747 associations : `lsst.jointcal.Associations`
1748 The star/reference star associations to fit.
1749 fitter : `lsst.jointcal.FitterBase`
1750 The fitter to use for minimization.
1752 Maximum number of steps to run outlier rejection before declaring
1753 convergence failure.
1754 name : {'photometry' or 'astrometry'}
1755 What type of data are we fitting (for logs and debugging files).
1757 Passed to ``fitter.minimize()`` to define the parameters to fit.
1758 dataName : `str`, optional
1759 Descriptive name for this dataset (e.g. tract and filter),
1761 sigmaRelativeTolerance : `float`, optional
1762 Convergence tolerance for the fractional change in the chi2 cut
1763 level for determining outliers. If set to zero, iterations will
1764 continue until there are no outliers.
1765 doRankUpdate : `bool`, optional
1766 Do an Eigen rank update during minimization, or recompute the full
1767 matrix and gradient?
1768 doLineSearch : `bool`, optional
1769 Do a line search for the optimum step during minimization?
1773 chi2: `lsst.jointcal.Chi2Statistic`
1774 The final chi2 after the fit converges, or is forced to end.
1779 Raised if the fitter fails with a non-finite value.
1781 Raised if the fitter fails for some other reason;
1782 log messages will provide further details.
1784 if self.config.writeInitMatrix:
1785 dumpMatrixFile = self.
_getDebugPath_getDebugPath(f
"{name}_postinit-{dataName}")
1789 oldChi2.chi2 = float(
"inf")
1790 for i
in range(max_steps):
1791 if self.config.writeChi2FilesOuterLoop:
1792 writeChi2Name = f
"{name}_iterate_{i}_chi2-{dataName}"
1794 writeChi2Name =
None
1795 result = fitter.minimize(whatToFit,
1796 self.config.outlierRejectSigma,
1797 sigmaRelativeTolerance=sigmaRelativeTolerance,
1798 doRankUpdate=doRankUpdate,
1799 doLineSearch=doLineSearch,
1800 dumpMatrixFile=dumpMatrixFile)
1802 chi2 = self.
_logChi2AndValidate_logChi2AndValidate(associations, fitter, fitter.getModel(),
1803 f
"Fit iteration {i}", writeChi2Name=writeChi2Name)
1805 if result == MinimizeResult.Converged:
1807 self.log.debug(
"fit has converged - no more outliers - redo minimization "
1808 "one more time in case we have lost accuracy in rank update.")
1810 result = fitter.minimize(whatToFit, self.config.outlierRejectSigma,
1811 sigmaRelativeTolerance=sigmaRelativeTolerance)
1812 chi2 = self.
_logChi2AndValidate_logChi2AndValidate(associations, fitter, fitter.getModel(),
"Fit completed")
1815 if chi2.chi2/chi2.ndof >= 4.0:
1816 self.log.error(
"Potentially bad fit: High chi-squared/ndof.")
1819 elif result == MinimizeResult.Chi2Increased:
1820 self.log.warning(
"Still some outliers remaining but chi2 increased - retry")
1822 chi2Ratio = chi2.chi2 / oldChi2.chi2
1824 self.log.warning(
'Significant chi2 increase by a factor of %.4g / %.4g = %.4g',
1825 chi2.chi2, oldChi2.chi2, chi2Ratio)
1832 msg = (
"Large chi2 increase between steps: fit likely cannot converge."
1833 " Try setting one or more of the `writeChi2*` config fields and looking"
1834 " at how individual star chi2-values evolve during the fit.")
1835 raise RuntimeError(msg)
1837 elif result == MinimizeResult.NonFinite:
1838 filename = self.
_getDebugPath_getDebugPath(
"{}_failure-nonfinite_chi2-{}.csv".format(name, dataName))
1840 fitter.saveChi2Contributions(filename+
"{type}")
1841 msg =
"Nonfinite value in chi2 minimization, cannot complete fit. Dumped star tables to: {}"
1842 raise FloatingPointError(msg.format(filename))
1843 elif result == MinimizeResult.Failed:
1844 raise RuntimeError(
"Chi2 minimization failure, cannot complete fit.")
1846 raise RuntimeError(
"Unxepected return code from minimize().")
1848 self.log.error(
"%s failed to converge after %d steps"%(name, max_steps))
1852 def _make_output(self, ccdImageList, model, func):
1853 """Return the internal jointcal models converted to the afw
1854 structures that will be saved to disk.
1858 ccdImageList : `lsst.jointcal.CcdImageList`
1859 The list of CcdImages to get the output for.
1860 model : `lsst.jointcal.AstrometryModel` or `lsst.jointcal.PhotometryModel`
1861 The internal jointcal model to convert for each `lsst.jointcal.CcdImage`.
1863 The name of the function to call on ``model`` to get the converted
1864 structure. Must accept an `lsst.jointcal.CcdImage`.
1868 output : `dict` [`tuple`, `lsst.jointcal.AstrometryModel`] or
1869 `dict` [`tuple`, `lsst.jointcal.PhotometryModel`]
1870 The data to be saved, keyed on (visit, detector).
1873 for ccdImage
in ccdImageList:
1874 ccd = ccdImage.ccdId
1875 visit = ccdImage.visit
1876 self.log.debug(
"%s for visit: %d, ccd: %d", func, visit, ccd)
1877 output[(visit, ccd)] = getattr(model, func)(ccdImage)
1880 def _write_astrometry_results(self, associations, model, visit_ccd_to_dataRef):
1882 Write the fitted astrometric results to a new 'jointcal_wcs' dataRef.
1886 associations : `lsst.jointcal.Associations`
1887 The star/reference star associations to fit.
1888 model : `lsst.jointcal.AstrometryModel`
1889 The astrometric model that was fit.
1890 visit_ccd_to_dataRef : `dict` of Key: `lsst.daf.persistence.ButlerDataRef`
1891 Dict of ccdImage identifiers to dataRefs that were fit.
1893 ccdImageList = associations.getCcdImageList()
1894 output = self.
_make_output_make_output(ccdImageList, model,
"makeSkyWcs")
1895 for key, skyWcs
in output.items():
1896 dataRef = visit_ccd_to_dataRef[key]
1898 dataRef.put(skyWcs,
'jointcal_wcs')
1899 except pexExceptions.Exception
as e:
1900 self.log.fatal(
'Failed to write updated Wcs: %s', str(e))
1903 def _write_photometry_results(self, associations, model, visit_ccd_to_dataRef):
1905 Write the fitted photometric results to a new 'jointcal_photoCalib' dataRef.
1909 associations : `lsst.jointcal.Associations`
1910 The star/reference star associations to fit.
1911 model : `lsst.jointcal.PhotometryModel`
1912 The photoometric model that was fit.
1913 visit_ccd_to_dataRef : `dict` of Key: `lsst.daf.persistence.ButlerDataRef`
1914 Dict of ccdImage identifiers to dataRefs that were fit.
1917 ccdImageList = associations.getCcdImageList()
1918 output = self.
_make_output_make_output(ccdImageList, model,
"toPhotoCalib")
1919 for key, photoCalib
in output.items():
1920 dataRef = visit_ccd_to_dataRef[key]
1922 dataRef.put(photoCalib,
'jointcal_photoCalib')
1923 except pexExceptions.Exception
as e:
1924 self.log.fatal(
'Failed to write updated PhotoCalib: %s', str(e))
static Schema makeMinimalSchema()
static std::shared_ptr< SourceTable > make(Schema const &schema, std::shared_ptr< IdFactory > const &idFactory)
static Schema makeMinimalSchema()
The class that implements the relations between MeasuredStar and FittedStar.
Class that handles the astrometric least squares problem.
Simple structure to accumulate chi2 and ndof.
A multi-component model, fitting mappings for sensors and visits simultaneously.
A projection handler in which all CCDs from the same visit have the same tangent point.
Class that handles the photometric least squares problem.
A model where there is one independent transform per CcdImage.
def getTargetList(parsedCmd, **kwargs)
def __init__(self, *config=None)
def _load_data(self, inputSourceTableVisit, inputVisitSummary, associations, jointcalControl, camera)
def _compute_proper_motion_epoch(self, ccdImageList)
def _get_refcat_coordinate_error_override(self, refCat, name)
def _getDebugPath(self, filename)
def _check_star_lists(self, associations, name)
def _make_one_input_data(self, visitRecord, catalog, detectorDict)
def _iterate_fit(self, associations, fitter, max_steps, name, whatToFit, dataName="", sigmaRelativeTolerance=0, doRankUpdate=True, doLineSearch=False)
def _write_astrometry_results(self, associations, model, visit_ccd_to_dataRef)
def _check_stars(self, associations)
def _prep_sky(self, associations, filters)
def _readDataId(self, butler, dataId)
def runQuantum(self, butlerQC, inputRefs, outputRefs)
def _do_load_refcat_and_fit(self, associations, defaultFilter, center, radius, tract="", match_cut=3.0, reject_bad_fluxes=False, *name="", refObjLoader=None, referenceSelector=None, fit_function=None, epoch=None)
def _put_metrics(self, butlerQC, job, outputRefs)
def _build_ccdImage(self, data, associations, jointcalControl)
def runDataRef(self, dataRefs)
def __init__(self, butler=None, initInputs=None, **kwargs)
def _make_schema_table(self)
def _get_sourceTable_visit_columns(self, inColumns)
def run(self, inputSourceTableVisit, inputVisitSummary, inputCamera, tract=None)
def _fit_photometry(self, associations, dataName=None)
def _write_photometry_results(self, associations, model, visit_ccd_to_dataRef)
def _logChi2AndValidate(self, associations, fit, model, chi2Label, writeChi2Name=None)
def _extract_detector_catalog_from_visit_catalog(self, table, visitCatalog, detectorId, detectorColumn, ixxColumns)
def _make_output(self, ccdImageList, model, func)
def _put_output(self, butlerQC, outputs, outputRefs, camera, setter)
def _load_reference_catalog(self, refObjLoader, referenceSelector, center, radius, filterLabel, applyColorterms=False, epoch=None)
def _fit_astrometry(self, associations, dataName=None)
def loadData(self, dataRefs, associations, jointcalControl)
def lookupStaticCalibrations(datasetType, registry, quantumDataId, collections)
def add_measurement(job, name, value)
def lookupVisitRefCats(datasetType, registry, quantumDataId, collections)
def writeModel(model, filename, log)