Coverage for python / lsst / analysis / tools / actions / plot / quiverPlot.py: 33%
60 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__ = ("QuiverPlot",)
25import logging
26from typing import Mapping, Optional
28import matplotlib.pyplot as plt
29import numpy as np
30from lsst.pex.config import Field
31from matplotlib.figure import Figure
33from ...interfaces import KeyedData, KeyedDataSchema, PlotAction, Scalar, Vector
34from .plotUtils import addPlotInfo
36_LOG = logging.getLogger(__name__)
39class QuiverPlot(PlotAction):
40 """Plots vectors on the detector focal plane.
42 Given the posisions on the detector in x and y, the quiver
43 plot draws arrows of length `length` and angle `angle`.
44 The quiver key label `qKeyLabel` and size `qKeySize` can be also set
45 up to show reference vector length. In a similar manner as in
46 interpolateDetectorPlot the size of the
47 """
49 xAxisLabel = Field[str](doc="Label to use for the x axis.", default="x (pixel)", optional=True)
50 yAxisLabel = Field[str](doc="Label to use for the y axis.", default="y (pixel)", optional=True)
51 zAxisLabel = Field[str](doc="Label to use for the arrows.", optional=True)
52 qKeyLabel = Field[str](doc="Label to use for the optional quiver Key", optional=True)
53 qKeySize = Field[float](doc="Size of the vector to use for the optional quiver Key", optional=True)
54 xCoordSize = Field[int]("Dimensions for X detector axis", default=4096)
55 yCoordSize = Field[int]("Dimensions for Y detector axis", default=4096)
57 def getInputSchema(self, **kwargs) -> KeyedDataSchema:
58 base = []
59 base.append(("x", Vector))
60 base.append(("y", Vector))
61 base.append(("angle", Vector))
62 base.append(("length", Vector))
64 return base
66 def _validateInput(self, data: KeyedData, **kwargs) -> None:
67 """NOTE currently can only check that something is not a Scalar, not
68 check that the data is consistent with Vector
69 """
70 needed = self.getInputSchema(**kwargs)
71 if remainder := {key.format(**kwargs) for key, _ in needed} - {
72 key.format(**kwargs) for key in data.keys()
73 }:
74 raise ValueError(f"Task needs keys {remainder} but they were not found in input")
75 for name, typ in needed:
76 isScalar = issubclass((colType := type(data[name.format(**kwargs)])), Scalar)
77 if isScalar and typ != Scalar:
78 raise ValueError(f"Data keyed by {name} has type {colType} but action requires type {typ}")
80 def __call__(self, data: KeyedData, **kwargs) -> Mapping[str, Figure] | Figure:
81 self._validateInput(data, **kwargs)
82 return self.makePlot(data, **kwargs)
84 def makePlot(self, data: KeyedData, plotInfo: Optional[Mapping[str, str]] = None, **kwargs) -> Figure:
86 quiverConf = {
87 "pivot": "mid",
88 "color": "blue",
89 "width": 0.004,
90 }
92 dataSelector = np.isfinite(data["angle"]) & np.isfinite(data["length"])
93 dataX = data["x"][dataSelector]
94 dataY = data["y"][dataSelector]
95 dataA = data["angle"][dataSelector]
96 dataL = data["length"][dataSelector]
98 U = dataL * np.cos(dataA)
99 V = dataL * np.sin(dataA)
101 fig = plt.figure(dpi=300)
102 ax = fig.add_subplot(111)
104 q = ax.quiver(dataX, dataY, U, V, **quiverConf)
105 if hasattr(self, "qKeyLabel") and hasattr(self, "qKeySize"):
106 ax.quiverkey(q, 0.5, 0.9, self.qKeySize, self.qKeyLabel, labelpos="E", coordinates="figure")
108 ax.set_xlim(-10, self.xCoordSize + 10)
109 ax.set_ylim(-10, self.yCoordSize + 10)
110 ax.set_xlabel(self.xAxisLabel)
111 ax.set_ylabel(self.yAxisLabel)
112 ax.set_aspect("equal", "box")
114 plt.subplots_adjust(wspace=0.0, hspace=0.0, right=0.85)
116 # add general plot info
117 if plotInfo is not None:
118 fig = addPlotInfo(fig, plotInfo)
120 return fig