Coverage for python / lsst / analysis / tools / actions / plot / interpolateDetectorPlot.py: 23%
81 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-05-06 09:07 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-05-06 09:07 +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 collections.abc import Mapping
28import matplotlib.pyplot as plt
29import numpy as np
30from matplotlib.figure import Figure
31from scipy.interpolate import CloughTocher2DInterpolator
33from lsst.pex.config import Field, ListField
35from ...interfaces import KeyedData, KeyedDataSchema, PlotAction, Vector
36from .plotUtils import addPlotInfo
38_LOG = logging.getLogger(__name__)
41class InterpolateDetectorMetricPlot(PlotAction):
42 """Interpolate metrics evaluated at locations across a detector.
44 The provided list of metric names and labels enables the creation of a
45 multi-panel plot, with the 2D interpolation of the input metric values
46 sampled on the given detector x and y coordinates.
47 The interpolation evaluation grid can be controlled with the margin
48 and number of grid points.
49 """
51 xAxisLabel = Field[str](doc="Label to use for the x axis.", default="x (pixel)", optional=True)
52 yAxisLabel = Field[str](doc="Label to use for the y axis.", default="y (pixel)", optional=True)
53 zAxisLabels = ListField[str](doc="Labels to use for the z axis.", optional=True)
54 metricNames = ListField[str](doc="Metrics to pull data from for interpolation", optional=False)
56 xCoordSize = Field[int]("Dimensions for X direction field to interpolate", default=4096)
57 yCoordSize = Field[int]("Dimensions for Y direction field to interpolate", default=4096)
58 nGridPoints = Field[int]("N points in the grid for the field to interpolate", default=50)
59 gridMargin = Field[int]("Grid margins for the field to interpolate", default=20)
61 def getInputSchema(self) -> KeyedDataSchema:
62 base = []
63 base.append(("x", Vector))
64 base.append(("y", Vector))
65 for metricName in self.metricNames:
66 base.append((metricName, Vector))
68 return base
70 def __call__(self, data: KeyedData, **kwargs) -> Mapping[str, Figure] | Figure:
71 return self.makePlot(data, **kwargs)
73 def makePlot(self, data: KeyedData, plotInfo: Mapping[str, str] | None = None, **kwargs) -> Figure:
74 """Makes a plot of a smooth interpolation of randomly
75 sampled metrics in the image domain.
77 Parameters
78 ----------
79 data : `KeyedData`
80 The catalog to plot the points from, the catalog needs
81 to have columns:
83 * ``"x"``
84 The x image coordinate of the input metric values
85 * ``"y"``
86 The y image coordinate of the input metric values
87 * metricNames
88 The column names of each image metric that needs to be
89 interpolated.
91 plotInfo : `dict`
92 Optional. A dictionary of information about the data being plotted
94 Returns
95 -------
96 fig : `matplotlib.figure.Figure`
97 The resulting figure.
99 Notes
100 -----
101 Uses the zAxisLabels config option to write the metric units and title
102 for each of the used panels.
103 The number of plots is determined from the number of `metricNames` in
104 the config options. The colorbar of the interpolation is included for
105 each panel, as well as a scatter plot showing the locations of the
106 metric sampling locations.
108 Examples
109 --------
110 An example of the plot produced from this code is here:
112 .. image:: /_static/analysis_tools/interpolateDetectorPlotExample.png
114 For a detailed example of how to make a plot from the command line
115 please see the
116 :ref:`getting started guide<analysis-tools-getting-started>`.
117 """
118 n_plots = len(self.metricNames)
120 # boxsize has some extra space in x axis for the colorbar
121 boxsize = (self.xCoordSize // (2**9), self.yCoordSize // (2**9) - 1)
123 if n_plots == 1:
124 fig, ax = plt.subplots(1, 1, figsize=boxsize)
125 ax.set_xlabel("X")
126 ax.set_ylabel("Y")
127 axes = np.array([ax])
128 elif n_plots <= 4:
129 n_xplots, n_yplots = n_plots, 1
130 fig, axes = plt.subplots(ncols=n_plots, nrows=1, figsize=(boxsize[0] * n_plots, boxsize[1]))
131 else:
132 # case where n_plots > 4:
133 n_xplots = 4
134 n_yplots = n_plots // 4 if n_plots % 4 == 0 else n_plots // 4 + 1
135 fig, axes = plt.subplots(
136 ncols=n_xplots,
137 nrows=n_yplots,
138 figsize=(boxsize[0] * n_xplots, boxsize[1] * n_yplots),
139 sharex=True,
140 sharey=True,
141 )
143 ytox_ratio = self.yCoordSize // self.xCoordSize
144 X = np.linspace(-self.gridMargin, self.xCoordSize + self.gridMargin, self.nGridPoints)
145 Y = np.linspace(-self.gridMargin, self.yCoordSize + self.gridMargin, self.nGridPoints * ytox_ratio)
146 meshgridX, meshgridY = np.meshgrid(X, Y) # 2D grid for interpolation
148 if self.zAxisLabels is None:
149 zAxisLabels = ["px_frac" for metricName in self.metricNames]
150 else:
151 zAxisLabels = self.zAxisLabels
153 for ax, metricName, zlabel in zip(axes.flatten(), self.metricNames, zAxisLabels):
154 dataSelector = np.isfinite(data[metricName])
155 if np.count_nonzero(dataSelector) < 4:
156 # Need at least four valid points for the interpolation.
157 ax.set_aspect("equal", "box")
158 ax.set_title(f"{metricName}[{zlabel}]")
160 continue
162 dataX = data["x"][dataSelector]
163 dataY = data["y"][dataSelector]
164 dataZ = data[metricName][dataSelector]
166 interp = CloughTocher2DInterpolator(list(zip(dataX, dataY)), dataZ)
167 Z = interp(meshgridX, meshgridY)
169 pc = ax.pcolormesh(X, Y, Z, shading="auto")
170 ax.scatter(dataX, dataY, s=10, facecolor="silver", edgecolor="black")
171 _ = fig.colorbar(pc, shrink=0.7, location="right", fraction=0.07)
172 ax.set_aspect("equal", "box")
173 ax.set_title(f"{metricName}[{zlabel}]")
175 for iax in range(axes.size - n_plots):
176 axes.flatten()[-(iax + 1)].remove()
177 # setting x axis labels for all
178 # setting only y axis labels for plots on the left of the panel
179 if n_yplots > 1:
180 for ax in axes[:, 0]:
181 ax.set_ylabel("Y")
182 for ax in axes[-1, :]:
183 ax.set_xlabel("X")
184 else:
185 axes[0].set_ylabel("Y")
186 for ax in axes:
187 ax.set_xlabel("X")
189 plt.tight_layout()
191 # add general plot info
192 if plotInfo is not None:
193 fig = addPlotInfo(fig, plotInfo)
195 return fig