Coverage for python / lsst / analysis / tools / actions / plot / interpolateDetectorPlot.py: 23%
81 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-04-15 00:23 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-04-15 00:23 +0000
1# This file is part of analysis_tools.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
21from __future__ import annotations
23__all__ = ("InterpolateDetectorMetricPlot",)
25import logging
26from typing import Mapping, Optional
28import matplotlib.pyplot as plt
29import numpy as np
30from lsst.pex.config import Field, ListField
31from matplotlib.figure import Figure
32from scipy.interpolate import CloughTocher2DInterpolator
34from ...interfaces import KeyedData, KeyedDataSchema, PlotAction, Vector
35from .plotUtils import addPlotInfo
37_LOG = logging.getLogger(__name__)
40class InterpolateDetectorMetricPlot(PlotAction):
41 """Interpolate metrics evaluated at locations across a detector.
43 The provided list of metric names and labels enables the creation of a
44 multi-panel plot, with the 2D interpolation of the input metric values
45 sampled on the given detector x and y coordinates.
46 The interpolation evaluation grid can be controlled with the margin
47 and number of grid points.
48 """
50 xAxisLabel = Field[str](doc="Label to use for the x axis.", default="x (pixel)", optional=True)
51 yAxisLabel = Field[str](doc="Label to use for the y axis.", default="y (pixel)", optional=True)
52 zAxisLabels = ListField[str](doc="Labels to use for the z axis.", optional=True)
53 metricNames = ListField[str](doc="Metrics to pull data from for interpolation", optional=False)
55 xCoordSize = Field[int]("Dimensions for X direction field to interpolate", default=4096)
56 yCoordSize = Field[int]("Dimensions for Y direction field to interpolate", default=4096)
57 nGridPoints = Field[int]("N points in the grid for the field to interpolate", default=50)
58 gridMargin = Field[int]("Grid margins for the field to interpolate", default=20)
60 def getInputSchema(self) -> KeyedDataSchema:
61 base = []
62 base.append(("x", Vector))
63 base.append(("y", Vector))
64 for metricName in self.metricNames:
65 base.append((metricName, Vector))
67 return base
69 def __call__(self, data: KeyedData, **kwargs) -> Mapping[str, Figure] | Figure:
70 return self.makePlot(data, **kwargs)
72 def makePlot(self, data: KeyedData, plotInfo: Optional[Mapping[str, str]] = None, **kwargs) -> Figure:
73 """Makes a plot of a smooth interpolation of randomly
74 sampled metrics in the image domain.
76 Parameters
77 ----------
78 data : `KeyedData`
79 The catalog to plot the points from, the catalog needs
80 to have columns:
82 * ``"x"``
83 The x image coordinate of the input metric values
84 * ``"y"``
85 The y image coordinate of the input metric values
86 * metricNames
87 The column names of each image metric that needs to be
88 interpolated.
90 plotInfo : `dict`
91 Optional. A dictionary of information about the data being plotted
93 Returns
94 -------
95 fig : `matplotlib.figure.Figure`
96 The resulting figure.
98 Notes
99 -----
100 Uses the zAxisLabels config option to write the metric units and title
101 for each of the used panels.
102 The number of plots is determined from the number of `metricNames` in
103 the config options. The colorbar of the interpolation is included for
104 each panel, as well as a scatter plot showing the locations of the
105 metric sampling locations.
107 Examples
108 --------
109 An example of the plot produced from this code is here:
111 .. image:: /_static/analysis_tools/interpolateDetectorPlotExample.png
113 For a detailed example of how to make a plot from the command line
114 please see the
115 :ref:`getting started guide<analysis-tools-getting-started>`.
116 """
117 n_plots = len(self.metricNames)
119 # boxsize has some extra space in x axis for the colorbar
120 boxsize = (self.xCoordSize // (2**9), self.yCoordSize // (2**9) - 1)
122 if n_plots == 1:
123 fig, ax = plt.subplots(1, 1, figsize=boxsize)
124 ax.set_xlabel("X")
125 ax.set_ylabel("Y")
126 axes = np.array([ax])
127 elif n_plots <= 4:
128 n_xplots, n_yplots = n_plots, 1
129 fig, axes = plt.subplots(ncols=n_plots, nrows=1, figsize=(boxsize[0] * n_plots, boxsize[1]))
130 else:
131 # case where n_plots > 4:
132 n_xplots = 4
133 n_yplots = n_plots // 4 if n_plots % 4 == 0 else n_plots // 4 + 1
134 fig, axes = plt.subplots(
135 ncols=n_xplots,
136 nrows=n_yplots,
137 figsize=(boxsize[0] * n_xplots, boxsize[1] * n_yplots),
138 sharex=True,
139 sharey=True,
140 )
142 ytox_ratio = self.yCoordSize // self.xCoordSize
143 X = np.linspace(-self.gridMargin, self.xCoordSize + self.gridMargin, self.nGridPoints)
144 Y = np.linspace(-self.gridMargin, self.yCoordSize + self.gridMargin, self.nGridPoints * ytox_ratio)
145 meshgridX, meshgridY = np.meshgrid(X, Y) # 2D grid for interpolation
147 if self.zAxisLabels is None:
148 zAxisLabels = ["px_frac" for metricName in self.metricNames]
149 else:
150 zAxisLabels = self.zAxisLabels
152 for ax, metricName, zlabel in zip(axes.flatten(), self.metricNames, zAxisLabels):
153 dataSelector = np.isfinite(data[metricName])
154 if np.count_nonzero(dataSelector) < 4:
155 # Need at least four valid points for the interpolation.
156 ax.set_aspect("equal", "box")
157 ax.set_title(metricName + "[%s]" % zlabel)
158 continue
160 dataX = data["x"][dataSelector]
161 dataY = data["y"][dataSelector]
162 dataZ = data[metricName][dataSelector]
164 interp = CloughTocher2DInterpolator(list(zip(dataX, dataY)), dataZ)
165 Z = interp(meshgridX, meshgridY)
167 pc = ax.pcolormesh(X, Y, Z, shading="auto")
168 ax.scatter(dataX, dataY, s=10, facecolor="silver", edgecolor="black")
169 _ = fig.colorbar(pc, shrink=0.7, location="right", fraction=0.07)
170 ax.set_aspect("equal", "box")
171 ax.set_title(metricName + "[%s]" % zlabel)
173 for iax in range(axes.size - n_plots):
174 axes.flatten()[-(iax + 1)].remove()
175 # setting x axis labels for all
176 # setting only y axis labels for plots on the left of the panel
177 if n_yplots > 1:
178 for ax in axes[:, 0]:
179 ax.set_ylabel("Y")
180 for ax in axes[-1, :]:
181 ax.set_xlabel("X")
182 else:
183 axes[0].set_ylabel("Y")
184 for ax in axes:
185 ax.set_xlabel("X")
187 plt.tight_layout()
189 # add general plot info
190 if plotInfo is not None:
191 fig = addPlotInfo(fig, plotInfo)
193 return fig