LSSTApplications  19.0.0-14-gb0260a2+72efe9b372,20.0.0+7927753e06,20.0.0+8829bf0056,20.0.0+995114c5d2,20.0.0+b6f4b2abd1,20.0.0+bddc4f4cbe,20.0.0-1-g253301a+8829bf0056,20.0.0-1-g2b7511a+0d71a2d77f,20.0.0-1-g5b95a8c+7461dd0434,20.0.0-12-g321c96ea+23efe4bbff,20.0.0-16-gfab17e72e+fdf35455f6,20.0.0-2-g0070d88+ba3ffc8f0b,20.0.0-2-g4dae9ad+ee58a624b3,20.0.0-2-g61b8584+5d3db074ba,20.0.0-2-gb780d76+d529cf1a41,20.0.0-2-ged6426c+226a441f5f,20.0.0-2-gf072044+8829bf0056,20.0.0-2-gf1f7952+ee58a624b3,20.0.0-20-geae50cf+e37fec0aee,20.0.0-25-g3dcad98+544a109665,20.0.0-25-g5eafb0f+ee58a624b3,20.0.0-27-g64178ef+f1f297b00a,20.0.0-3-g4cc78c6+e0676b0dc8,20.0.0-3-g8f21e14+4fd2c12c9a,20.0.0-3-gbd60e8c+187b78b4b8,20.0.0-3-gbecbe05+48431fa087,20.0.0-38-ge4adf513+a12e1f8e37,20.0.0-4-g97dc21a+544a109665,20.0.0-4-gb4befbc+087873070b,20.0.0-4-gf910f65+5d3db074ba,20.0.0-5-gdfe0fee+199202a608,20.0.0-5-gfbfe500+d529cf1a41,20.0.0-6-g64f541c+d529cf1a41,20.0.0-6-g9a5b7a1+a1cd37312e,20.0.0-68-ga3f3dda+5fca18c6a4,20.0.0-9-g4aef684+e18322736b,w.2020.45
LSSTDataManagementBasePackage
interactive.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 # Copyright 2008-2013 LSST Corporation.
4 #
5 # This product includes software developed by the
6 # LSST Project (http://www.lsst.org/).
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the LSST License Statement and
19 # the GNU General Public License along with this program. If not,
20 # see <http://www.lsstcorp.org/LegalNotices/>.
21 #
22 
23 import numpy
24 
25 import lsst.pipe.base
26 import lsst.pex.config
28 import lsst.afw.image
31 
32 from ..measureCcd import MeasureCcdTask
33 from ..measureCoadd import MeasureCoaddTask
34 from ..measureMulti import MeasureMultiTask
35 from .. import modelfitLib
36 
37 from .densityPlot import CrossPointsLayer, DensityPlot, HistogramLayer, SurfaceLayer
38 from .modelFitAdapters import OptimizerDataAdapter, OptimizerTrackLayer, SamplingDataAdapter
39 from .optimizerDisplay import OptimizerDisplay
40 
41 __all__ = ("Interactive", )
42 
43 
45  """Interactive analysis helper class
46 
47  This class manages a butler, calexp, modelfits catalog, and an instance
48  of a Measure*Task, allowing individual objects to be re-fit and plotted.
49  """
50 
51  def __init__(self, root, tag=None, config=None, dataId=None, mode="ccd"):
52  """Construct an interactive analysis object.
53 
54  @param[in] rerun Output directory, relative to $S13_DATA_DIR/output.
55  measureCcd.py (or measureCoadd.py if mode='coadd') must
56  have been run (possibly with prepOnly=True) previously
57  with this output directory.
58  @param[in] tag Tag associated with the run; see BaseMeasureConfig.tag.
59  If None, config must not be (and config.tag will be used).
60  @param[in] config ConfigClass instance; if None, it will be loaded from disk.
61  @param[in] dataId Butler data ID of the image to analyze.
62  @param[in] mode One of "ccd", "coadd", or "multi", indicating whether
63  to use MeasureCcdTask, MeasureCoaddTask, or MeasureMultiTask.
64  """
65  self.mode = mode.lower()
67  TaskClass = None
68  configName = None
69  if self.mode == "ccd":
70  if dataId is None:
71  dataId = dict(visit=100, raft="2,2", sensor="1,1")
72  self.dataRef = self.butler.dataRef("calexp", dataId=dataId)
73  configName = "measureCcd_config"
74  TaskClass = MeasureCcdTask
75  elif self.mode == "coadd":
76  if dataId is None:
77  dataId = dict(tract=0, patch="2,2", filter="i")
78  self.dataRef = self.butler.dataRef("deepCoadd_calexp", dataId=dataId)
79  configName = "deep_measureCoadd_config"
80  TaskClass = MeasureCoaddTask
81  elif self.mode.startswith("multi"):
82  if dataId is None:
83  dataId = dict(tract=0, patch="2,2", filter="i")
84  self.dataRef = self.butler.dataRef("deepCoadd_calexp", dataId=dataId)
85  configName = "deep_measureMulti_config"
86  TaskClass = MeasureMultiTask
87  if config is None:
88  config = self.butler.get(configName, tag=tag, immediate=True)
89  config.previous = tag
90  if tag is None:
91  if config is None:
92  raise ValueError("tag and config arguments cannot both be None")
93  tag = config.tag
94  else:
95  config.tag = "intermediate"
96  self.task = TaskClass(config=config, butler=self.butler)
97  self.inputs = self.task.readInputs(self.dataRef)
98 
99  def fit(self, outRecord):
100  """Re-fit the object indicated by the given record sequential index or source ID,
101  returning the record.
102  """
103  likelihood = self.task.makeLikelihood(self.inputs, outRecord)
104  self.task.fitter.run(likelihood, outRecord)
105  return outRecord
106 
107  def plotDistribution(self, *records):
108  """Plot a representation of the posterior distribution from a ModelFitRecord.
109  """
110  import matplotlib
111  recordId = records[0].getId()
112  figure = matplotlib.pyplot.figure(recordId, figsize=(10, 10))
113  data = {}
114  layers = {}
115  for record in records:
116  assert record.getId() == recordId
117  if modelfitLib.MarginalSamplingInterpreter.cast(record.getInterpreter()):
118  data["marginal"] = SamplingDataAdapter(record)
119  layers["marginal.samples"] = HistogramLayer("direct")
120  layers["marginal.proposal"] = SurfaceLayer("direct")
121  elif modelfitLib.DirectSamplingInterpreter.cast(record.getInterpreter()):
122  data["direct"] = SamplingDataAdapter(record)
123  layers["direct.samples"] = HistogramLayer("direct")
124  layers["direct.proposal"] = SurfaceLayer("direct")
125  elif modelfitLib.OptimizerInterpreter.cast(record.getInterpreter()):
126  data["optimizer"] = OptimizerDataAdapter(record)
127  layers["optimizer.track"] = OptimizerTrackLayer("optimizer")
128  layers["optimizer.pdf"] = SurfaceLayer("optimizer",
129  kwds1d=dict(color='g'),
130  kwds2d=dict(cmap=matplotlib.cm.Greens))
131  layers["optimizer.points"] = CrossPointsLayer("optimizer")
132  else:
133  raise ValueError("Unknown or missing interpreter")
134  p = DensityPlot(figure, **data)
135  p.layers.update(layers)
136  p.draw()
137  return p
138 
139  def displayOptimizer(self, record, **kwds):
140  likelihood = self.task.makeLikelihood(self.inputs, record)
141  objective = modelfitLib.OptimizerObjective.makeFromLikelihood(likelihood, self.task.prior)
142  return OptimizerDisplay(record.getSamples(), self.task.model, objective)
143 
144  def displayResiduals(self, record, nonlinear="fit", amplitudes="fit", doApplyWeights=False):
145  """Display the data postage stamp along with the model image and residuals in ds9.
146 
147  @param[in] record ModelFitRecord defining the object to display
148  @param[in] nonlinear Vector of nonlinear parameters, or a string prefix (see below)
149  @param[in] amplitudes Vector of linear parameters, or a string prefix (see below)
150  @param[in] doApplyWeights Whether to show the weighted images used directly in the fit
151  or the original unweighted data.
152 
153  String prefixes are used to extract the parameters from the record. Usually the following
154  are available:
155  fit ------- use record.get("fit.*"); the best-fit parameters
156  initial --- use record.get("initial.*"); the initial parameters
157  """
158  likelihood = self.task.makeLikelihood(self.inputs, record)
159 
160  if isinstance(nonlinear, str):
161  nonlinear = record.get(nonlinear + ".nonlinear")
162  else:
163  assert nonlinear.shape == (likelihood.getNonlinearDim(),)
164 
165  matrix = numpy.zeros((likelihood.getAmplitudeDim(), likelihood.getDataDim()),
166  dtype=modelfitLib.Pixel).transpose()
167  likelihood.computeModelMatrix(matrix, nonlinear, doApplyWeights)
168 
169  if isinstance(amplitudes, str):
170  amplitudes = record.get(amplitudes + ".amplitudes")
171  else:
172  assert amplitudes.shape == (likelihood.getAmplitudeDim(),)
173 
174  bbox = record.getFootprint().getBBox()
175  bbox.grow(2)
176  flatModel = numpy.zeros(likelihood.getDataDim(), dtype=modelfitLib.Pixel)
177  flatModel[:] = numpy.dot(matrix, amplitudes)
178 
179  imgData = lsst.afw.image.MaskedImageF(self.inputs.exposure.getMaskedImage(), bbox,
180  lsst.afw.image.PARENT, True)
181  bitmask = imgData.getMask().addMaskPlane("FIT_REGION")
182  regionMask = lsst.afw.image.MaskU(bbox)
183  lsst.afw.detection.setMaskFromFootprint(regionMask, record.getFootprint(), bitmask)
184  dataMask = imgData.getMask()
185  dataMask |= regionMask
186  if doApplyWeights:
187  imgData.getImage().set(0.0)
188  imgData.getVariance().set(0.0)
189  flatData = likelihood.getData()
190  lsst.afw.detection.expandArray(record.getFootprint(), flatData, imgData.getImage().getArray(),
191  imgData.getXY0())
192  imgModel = lsst.afw.image.MaskedImageF(lsst.afw.image.ImageF(bbox), regionMask)
193  lsst.afw.detection.expandArray(record.getFootprint(), flatModel, imgModel.getImage().getArray(),
194  imgModel.getXY0())
195  imgResiduals = lsst.afw.image.MaskedImageF(imgData, True)
196  imgResiduals -= imgModel
198  mosaic.setMode("x")
199  mosaic.append(imgData, "data")
200  mosaic.append(imgModel, "model")
201  mosaic.append(imgResiduals, "data-model")
202  grid = mosaic.makeMosaic()
lsst::afw::image
Backwards-compatibility support for depersisting the old Calib (FluxMag0/FluxMag0Err) objects.
Definition: imageAlgorithm.dox:1
lsst::afw.display.ds9
Definition: ds9.py:1
lsst::meas::modelfit.display.densityPlot.SurfaceLayer
Definition: densityPlot.py:172
lsst::meas::modelfit.display.interactive.Interactive.mode
mode
Definition: interactive.py:65
lsst::meas::modelfit.display.interactive.Interactive.task
task
Definition: interactive.py:96
lsst::meas::modelfit.display.interactive.Interactive.displayResiduals
def displayResiduals(self, record, nonlinear="fit", amplitudes="fit", doApplyWeights=False)
Definition: interactive.py:144
lsst::afw.display.ds9.mtv
def mtv(data, frame=None, title="", wcs=None, *args, **kwargs)
Definition: ds9.py:93
lsst::meas::modelfit.display.interactive.Interactive
Definition: interactive.py:44
lsst::meas::modelfit.display.interactive.Interactive.displayOptimizer
def displayOptimizer(self, record, **kwds)
Definition: interactive.py:139
lsst::meas::modelfit.display.interactive.Interactive.fit
def fit(self, outRecord)
Definition: interactive.py:99
lsst::meas::modelfit.display.modelFitAdapters.SamplingDataAdapter
Definition: modelFitAdapters.py:60
lsst::daf::persistence.butler.Butler
Definition: butler.py:321
lsst::meas::modelfit.display.interactive.Interactive.inputs
inputs
Definition: interactive.py:97
lsst::afw::geom::ellipses
Definition: Axes.h:42
lsst.pex.config
Definition: __init__.py:1
lsst::meas::modelfit.display.interactive.Interactive.dataRef
dataRef
Definition: interactive.py:72
lsst::meas::modelfit.display.densityPlot.HistogramLayer
Definition: densityPlot.py:63
lsst::meas::modelfit.display.modelFitAdapters.OptimizerTrackLayer
Definition: modelFitAdapters.py:77
lsst::meas::modelfit.display.interactive.Interactive.butler
butler
Definition: interactive.py:66
lsst::meas::modelfit.display.optimizerDisplay.OptimizerDisplay
Definition: optimizerDisplay.py:71
lsst::meas::modelfit.display.densityPlot.DensityPlot
Definition: densityPlot.py:268
lsst::meas::modelfit.display.densityPlot.CrossPointsLayer
Definition: densityPlot.py:231
lsst::meas::modelfit.display.interactive.Interactive.__init__
def __init__(self, root, tag=None, config=None, dataId=None, mode="ccd")
Definition: interactive.py:51
lsst::meas::modelfit.display.interactive.Interactive.plotDistribution
def plotDistribution(self, *records)
Definition: interactive.py:107
lsst::afw.display.ds9.setMaskTransparency
def setMaskTransparency(name, frame=None)
Definition: ds9.py:81
lsst::meas::modelfit.display.modelFitAdapters.OptimizerDataAdapter
Definition: modelFitAdapters.py:110
lsst::daf::persistence
Definition: Utils.h:50
lsst.pipe.base
Definition: __init__.py:1
set
daf::base::PropertySet * set
Definition: fits.cc:912
lsst::afw.display.utils.Mosaic
Definition: utils.py:71