multimetricdiagram 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,47 @@
1
+ """Multimetric diagram: 5-metric alternative, that rewards realistic variance, to Taylor diagram
2
+
3
+ Metrics: total, bias, pattern, amplitude, phase.
4
+
5
+ Associated manuscript:
6
+ Codiga, Daniel L., "Improved Evaluation and Communication of Model–Observation Comparisons: The
7
+ Diagnostic Index of Agreement with Symmetry, and the Multimetric Diagram as an Alternative to the
8
+ Taylor Diagram", submitted manuscript, 2026.
9
+
10
+ Main functions
11
+ calculate_metrics()
12
+ Compute metrics from model-observation pairs (scalar or vector)
13
+ make_fig_axes()
14
+ Generate figure, main polar axes, legend container axes above
15
+ add_markerstick()
16
+ Add markerstick to polar axes, metrics for a model-observation pair
17
+ adjust_markerstick_labels()
18
+ Reposition markerstick labels to minimize overlap
19
+ add_labeledmarker_legend()
20
+ Add a marker legend, optionally with text labels on markers
21
+
22
+ See README.md for the explanation of diagram elements, the purposes of all
23
+ functions (including helper functions), usage examples, and notes about the code.
24
+
25
+ D. Codiga, with Claude agents, 11/2026
26
+ """
27
+
28
+ from importlib.metadata import version as _version
29
+
30
+ from . import alt as alt # pylint: disable=useless-import-alias # explicit re-export
31
+ from ._text import text_polar
32
+ from .axes import make_fig_axes
33
+ from .labels import adjust_markerstick_labels
34
+ from .legend import add_labeledmarker_legend
35
+ from .markerstick import add_markerstick
36
+ from .metrics import calculate_metrics
37
+
38
+ __version__ = _version("multimetricdiagram")
39
+
40
+ __all__ = [ # noqa: RUF022 (kept in workflow order)
41
+ "calculate_metrics",
42
+ "make_fig_axes",
43
+ "add_markerstick",
44
+ "adjust_markerstick_labels",
45
+ "add_labeledmarker_legend",
46
+ "text_polar",
47
+ ]
@@ -0,0 +1,18 @@
1
+ """Default style values shared by add_markerstick() and add_labeledmarker_legend()."""
2
+
3
+ MARKERSTICK_COLOR = 'r'
4
+ MARKER_SHAPE = 'o'
5
+ MARKER_SIZE = 14 # points; scatter size s = MARKER_SIZE**2
6
+ MARKER_FACECOLOR = 'none' # open (unfilled) marker
7
+ ALPHA = 0.6 # marker and stick
8
+ STICK_LINEWIDTH = 1.5
9
+ LEGEND_MARKER_EDGEWIDTH = 1.5
10
+ LABEL_FONTSIZE = 10
11
+
12
+ # label 'position' presets; offsets are gaps from the marker's edge, in multiples of fontsize;
13
+ # add_markerstick() mirrors 'beside' to ha='left', cw_offset=+0.1 when MB/SDQ < 0
14
+ LABEL_POSITION_PRESETS = {
15
+ 'outside': {'va': 'bottom', 'ha': 'center', 'out_offset': 0.1, 'cw_offset': 0},
16
+ 'inside': {'va': 'top', 'ha': 'center', 'out_offset': -0.1, 'cw_offset': 0},
17
+ 'beside': {'va': 'center', 'ha': 'right', 'out_offset': 0, 'cw_offset': -0.1},
18
+ }
@@ -0,0 +1,191 @@
1
+ """text_polar(): rotated text on polar axes (used by axes and markerstick; also public)."""
2
+
3
+ from typing import Any
4
+
5
+ import numpy as np
6
+ from matplotlib.artist import allow_rasterization
7
+ from matplotlib.font_manager import FontProperties
8
+ from matplotlib.patches import PathPatch
9
+ from matplotlib.path import Path
10
+ from matplotlib.textpath import TextPath
11
+ from matplotlib.transforms import Affine2D, Bbox, ScaledTranslation, Transform
12
+
13
+
14
+ def text_polar(
15
+ ax: Any,
16
+ theta: float,
17
+ r: float,
18
+ text: Any,
19
+ *,
20
+ color: str = 'k',
21
+ rotation: float = 0,
22
+ fontsize: float = 10,
23
+ fontweight: str = 'normal',
24
+ out_offset: float = 0,
25
+ cw_offset: float = 0,
26
+ ha: str = 'center',
27
+ va: str = 'center',
28
+ zorder: float = 2,
29
+ **kwargs,
30
+ ) -> PathPatch:
31
+ """
32
+ Draw rotated text on polar axes with precise alignment and offsets.
33
+
34
+ Drawn as a PathPatch of a TextPath, because pyplot.text() with rotation is unreliable on
35
+ polar axes.
36
+
37
+ Args:
38
+ ax: Polar axes.
39
+ theta: Angular position, radians.
40
+ r: Radial position, data units.
41
+ text: Text to draw: any object, converted with str(); None gives '' (draws nothing).
42
+ color: Text color. Default 'k'.
43
+ rotation: Rotation, degrees counterclockwise. Default 0.
44
+ fontsize: Font size, points. Default 10.
45
+ fontweight: E.g. 'normal' (default) or 'bold'.
46
+ out_offset: Shift perpendicular to the baseline, in multiples of fontsize; positive is
47
+ toward the top of the text (radially outward when rotation = theta - 90 deg, as
48
+ for markerstick labels). Default 0.
49
+ cw_offset: Shift along the baseline, in multiples of fontsize; positive is toward the
50
+ end of the text (clockwise when rotation = theta - 90 deg). Default 0.
51
+ ha: Point of the text's ink box placed at (theta, r) horizontally: 'left' edge,
52
+ 'center' (default), or 'right' edge.
53
+ va: Same, vertically: 'bottom' edge, 'center' (default), or 'top' edge.
54
+ zorder: Default 2.
55
+ **kwargs: Passed to PathPatch, e.g. alpha=0.5 (clip_on defaults to False).
56
+
57
+ Returns:
58
+ The PathPatch, for later changes, e.g. h = text_polar(...); h.set_facecolor('red').
59
+
60
+ Raises:
61
+ ValueError: ha or va is not one of the values above.
62
+ """
63
+ if ha not in ("center", "left", "right"):
64
+ raise ValueError(f"ha must be 'center', 'left', or 'right', got {ha!r}")
65
+ if va not in ("center", "bottom", "top"):
66
+ raise ValueError(f"va must be 'center', 'bottom', or 'top', got {va!r}")
67
+ clip_on = kwargs.pop('clip_on', False)
68
+ text = '' if text is None else str(text) # as matplotlib's Text.set_text()
69
+ if text:
70
+ path = TextPath((0, 0), text, size=1, prop=FontProperties(weight=fontweight))
71
+ else: # TextPath can't make an empty path; draw nothing
72
+ path = Path(np.empty((0, 2)))
73
+ patch = _PolarTextPatch(
74
+ path,
75
+ ax=ax,
76
+ theta=theta,
77
+ r=r,
78
+ rotation=rotation,
79
+ fontsize=fontsize,
80
+ out_offset=out_offset,
81
+ cw_offset=cw_offset,
82
+ ha=ha,
83
+ va=va,
84
+ lw=0,
85
+ zorder=zorder,
86
+ clip_on=clip_on,
87
+ **kwargs,
88
+ )
89
+ patch.set_color(color) # set here, not in draw(), so later color changes persist
90
+ # pylint: disable-next=protected-access,attribute-defined-outside-init
91
+ patch._text = text # e.g. for adjust_markerstick_labels()'s warning
92
+
93
+ autoscale_was_on = ax.get_autoscale_on()
94
+ ax.set_autoscale_on(False)
95
+ ax.add_patch(patch)
96
+ ax.set_autoscale_on(autoscale_was_on)
97
+
98
+ return patch
99
+
100
+
101
+ class _PolarTextPatch(PathPatch):
102
+ """
103
+ text_polar()'s patch. Its transform is recomputed at each draw, since it depends on figure
104
+ size, axes position and r-limits; an optional offset in inches is applied last.
105
+ """
106
+
107
+ def __init__(
108
+ self,
109
+ path: TextPath,
110
+ *,
111
+ ax: Any,
112
+ theta: float,
113
+ r: float,
114
+ rotation: float,
115
+ fontsize: float,
116
+ out_offset: float,
117
+ cw_offset: float,
118
+ ha: str,
119
+ va: str,
120
+ **kwargs: Any,
121
+ ) -> None:
122
+ super().__init__(path, **kwargs)
123
+ self._ax = ax
124
+ # empty text: a zero-size box at the anchor keeps the transform finite
125
+ self._bb = path.get_extents() if len(path.vertices) else Bbox.from_bounds(0, 0, 0, 0)
126
+ self._theta = theta
127
+ self._r = r
128
+ self._rotation = rotation
129
+ self._fontsize = fontsize
130
+ self._out_offset = out_offset
131
+ self._cw_offset = cw_offset
132
+ self._ha = ha
133
+ self._va = va
134
+ self._offset_inches = (0.0, 0.0)
135
+
136
+ def _polar_transform(self) -> Affine2D:
137
+ ax = self._ax
138
+ fontsize = self._fontsize
139
+ bb = self._bb
140
+ cx = bb.x0 + 0.5 * (bb.x1 - bb.x0)
141
+ cy = bb.y0 + 0.5 * (bb.y1 - bb.y0)
142
+ half_width = 0.5 * (bb.x1 - bb.x0)
143
+ half_height = 0.5 * (bb.y1 - bb.y0)
144
+ # Cartesian-data-to-display part of polar transData (equal to transData._b)
145
+ to_display = ax.transProjectionAffine + ax.transWedge + ax.transAxes
146
+ unit_px = np.hypot(*(to_display.transform((1.0, 0.0)) - to_display.transform((0.0, 0.0))))
147
+ pt_per_data = unit_px * 72.0 / ax.get_figure().dpi
148
+ scale = fontsize / pt_per_data
149
+ if self._ha == "left":
150
+ ha_shift = half_width
151
+ elif self._ha == "right":
152
+ ha_shift = -half_width
153
+ else:
154
+ ha_shift = 0.0
155
+ if self._va == "bottom":
156
+ va_shift = half_height
157
+ elif self._va == "top":
158
+ va_shift = -half_height
159
+ else:
160
+ va_shift = 0.0
161
+ x_offset = (self._cw_offset * fontsize) / pt_per_data
162
+ y_offset = (self._out_offset * fontsize) / pt_per_data
163
+ x = self._r * np.cos(self._theta)
164
+ y = self._r * np.sin(self._theta)
165
+ return (
166
+ Affine2D()
167
+ .translate(-cx + ha_shift, -cy + va_shift) # 1. center glyphs, apply ha/va (em units)
168
+ .scale(scale) # 2. scale to data units
169
+ .translate(x_offset, y_offset) # 3. shift in local text frame (data units)
170
+ .rotate_deg(self._rotation) # 4. rotate into position
171
+ .translate(x, y) # 5. move to polar location
172
+ + to_display
173
+ )
174
+
175
+ def _full_transform(self) -> Transform:
176
+ transform = self._polar_transform()
177
+ if self._offset_inches != (0.0, 0.0):
178
+ # as offset_copy(..., units='inches'): scaled by the figure dpi at draw time
179
+ dpi_scale_trans = self._ax.get_figure().dpi_scale_trans
180
+ transform = transform + ScaledTranslation(*self._offset_inches, dpi_scale_trans)
181
+ return transform
182
+
183
+ def _set_offset_inches(self, dx: float, dy: float) -> None:
184
+ """Set the extra (dx, dy) offset in inches, updating the transform immediately."""
185
+ self._offset_inches = (dx, dy)
186
+ self.set_transform(self._full_transform())
187
+
188
+ @allow_rasterization # lets set_rasterized(True) take effect
189
+ def draw(self, renderer: Any) -> None:
190
+ self.set_transform(self._full_transform())
191
+ super().draw(renderer)
@@ -0,0 +1,5 @@
1
+ """Alternative diagrams: taylor (Taylor diagram)."""
2
+
3
+ from . import taylor
4
+
5
+ __all__ = ["taylor"]
@@ -0,0 +1,61 @@
1
+ """Taylor diagram with the multimetric diagram's markersticks, labels and legend.
2
+
3
+ Each model is a marker at radius MSD/OSD and angle arccos(CC); the observations are the star at
4
+ radius 1 and CC = 1, so a marker's distance from the star is URMSD/OSD (Taylor 2001,
5
+ https://doi.org/10.1029/2000JD900719). The stick, of length |MB/OSD|, is tangent to the circle
6
+ about the star through the marker, clockwise about the star if MB > 0, so with ddof = 0 it ends
7
+ on the circle of RMSD/OSD. Gray gridlines: radials of constant CC (dotted), circles about the
8
+ origin of constant MSD/OSD (dashed), circles about the star of constant RMSD/OSD = URMSD/OSD
9
+ (solid).
10
+
11
+ Functions
12
+ calculate_metrics()
13
+ Metrics of a model-observation pair: the top-level ones plus their ratios to OSD
14
+ make_fig_axes()
15
+ Figure with the diagram's polar axes and an empty legend axes above it
16
+ add_markerstick()
17
+ Add a markerstick (marker, stick, optional labels) for one metrics dict
18
+ adjust_markerstick_labels(), add_labeledmarker_legend(), text_polar()
19
+ The top-level functions themselves
20
+
21
+ make_fig_axes() options: quadrants=None (default: 2 if any dict passed as metrics= has CC < 0,
22
+ else 1), or 1 (CC 0 to 1) or 2 (CC -1 to 1) to override; normalized=True (radii in units of
23
+ OSD, default) or False (data units: then units and osd are needed, and r_max or metrics);
24
+ r_max=None (default: fits the largest MSD in metrics=, with a labeled outer arc; else 1.5);
25
+ grid_info (gridline styles, outer arc); pad_t_b_l_r_inch (room for labels); patternonly=False
26
+ (True: axis titles without RMSD and "(marker)", for metrics from
27
+ calculate_metrics(patternonly=True), which sets MB to 0 and RMSD to its zero-bias value, so
28
+ there are no sticks).
29
+
30
+ Example:
31
+ >>> import numpy as np
32
+ >>> import multimetricdiagram as mmd
33
+ >>> taylor = mmd.alt.taylor
34
+ >>> rng = np.random.default_rng(0)
35
+ >>> obs = rng.normal(10.0, 2.0, 200)
36
+ >>> metrics = {}
37
+ >>> for name, gain, bias in [("A", 0.9, 0.3), ("B", 1.2, -0.4)]:
38
+ ... model = gain * (obs - 10) + 10 + bias + rng.normal(0, 0.8, obs.size)
39
+ ... metrics[name] = taylor.calculate_metrics(model, obs)
40
+ >>> fig, ax, ax_legend = taylor.make_fig_axes(metrics=list(metrics.values()))
41
+ >>> results = [taylor.add_markerstick(ax, m, label_info={"text": name})
42
+ ... for name, m in metrics.items()]
43
+ >>> moved = taylor.adjust_markerstick_labels(ax, results)
44
+ >>> fig.savefig("taylor.png", dpi=300)
45
+ """
46
+
47
+ from ..._text import text_polar
48
+ from ...labels import adjust_markerstick_labels
49
+ from ...legend import add_labeledmarker_legend
50
+ from .axes import make_fig_axes
51
+ from .markerstick import add_markerstick
52
+ from .metrics import calculate_metrics
53
+
54
+ __all__ = [ # noqa: RUF022 (kept in workflow order)
55
+ "calculate_metrics",
56
+ "make_fig_axes",
57
+ "add_markerstick",
58
+ "adjust_markerstick_labels",
59
+ "add_labeledmarker_legend",
60
+ "text_polar",
61
+ ]