eofigs 0.2.0__tar.gz → 0.2.2__tar.gz

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.
Files changed (62) hide show
  1. {eofigs-0.2.0 → eofigs-0.2.2}/CHANGELOG.md +55 -0
  2. {eofigs-0.2.0 → eofigs-0.2.2}/CITATION.cff +2 -2
  3. {eofigs-0.2.0 → eofigs-0.2.2}/PKG-INFO +5 -5
  4. {eofigs-0.2.0 → eofigs-0.2.2}/README.md +3 -3
  5. {eofigs-0.2.0 → eofigs-0.2.2}/pyproject.toml +1 -1
  6. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/__init__.py +1 -1
  7. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/check.py +28 -2
  8. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/events.py +1 -0
  9. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/styling.py +78 -2
  10. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/trends.py +52 -7
  11. eofigs-0.2.2/tests/baseline/test_accuracy_scatter_density_image.png +0 -0
  12. eofigs-0.2.2/tests/baseline/test_accuracy_scatter_groups_image.png +0 -0
  13. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_check.py +20 -0
  14. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_style.py +70 -2
  15. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_trends.py +49 -0
  16. eofigs-0.2.2/tests/test_zenodo_draft.py +75 -0
  17. eofigs-0.2.0/tests/baseline/test_accuracy_scatter_density_image.png +0 -0
  18. eofigs-0.2.0/tests/baseline/test_accuracy_scatter_groups_image.png +0 -0
  19. {eofigs-0.2.0 → eofigs-0.2.2}/.gitignore +0 -0
  20. {eofigs-0.2.0 → eofigs-0.2.2}/LICENSE +0 -0
  21. {eofigs-0.2.0 → eofigs-0.2.2}/conftest.py +0 -0
  22. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/_colour.py +0 -0
  23. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/_countries.py +0 -0
  24. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/_presets.py +0 -0
  25. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/accuracy.py +0 -0
  26. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/data/journals.json +0 -0
  27. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/data/ne_110m_countries.geojson +0 -0
  28. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/data/variables.json +0 -0
  29. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/export.py +0 -0
  30. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/figures.py +0 -0
  31. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/maps.py +0 -0
  32. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/palettes.py +0 -0
  33. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/py.typed +0 -0
  34. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/raster.py +0 -0
  35. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/stats.py +0 -0
  36. {eofigs-0.2.0 → eofigs-0.2.2}/src/eofigs/variables.py +0 -0
  37. {eofigs-0.2.0 → eofigs-0.2.2}/tests/baseline/test_event_composite_image.png +0 -0
  38. {eofigs-0.2.0 → eofigs-0.2.2}/tests/baseline/test_event_composite_two_phases_image.png +0 -0
  39. {eofigs-0.2.0 → eofigs-0.2.2}/tests/baseline/test_north_arrow_and_scale_bar_image.png +0 -0
  40. {eofigs-0.2.0 → eofigs-0.2.2}/tests/baseline/test_study_area_map_inside_image.png +0 -0
  41. {eofigs-0.2.0 → eofigs-0.2.2}/tests/baseline/test_study_area_map_side_image.png +0 -0
  42. {eofigs-0.2.0 → eofigs-0.2.2}/tests/baseline/test_trend_map_dots_image.png +0 -0
  43. {eofigs-0.2.0 → eofigs-0.2.2}/tests/baseline/test_trend_map_hatch_image.png +0 -0
  44. {eofigs-0.2.0 → eofigs-0.2.2}/tests/baseline/test_trend_map_profile_image.png +0 -0
  45. {eofigs-0.2.0 → eofigs-0.2.2}/tests/conftest.py +0 -0
  46. {eofigs-0.2.0 → eofigs-0.2.2}/tests/geo_helpers.py +0 -0
  47. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_accuracy.py +0 -0
  48. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_colour.py +0 -0
  49. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_docs_presets.py +0 -0
  50. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_docs_variables.py +0 -0
  51. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_events.py +0 -0
  52. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_export.py +0 -0
  53. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_figures.py +0 -0
  54. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_glyphs.py +0 -0
  55. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_house_style.py +0 -0
  56. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_import.py +0 -0
  57. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_map_images.py +0 -0
  58. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_maps.py +0 -0
  59. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_presets.py +0 -0
  60. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_raster.py +0 -0
  61. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_stats.py +0 -0
  62. {eofigs-0.2.0 → eofigs-0.2.2}/tests/test_variables.py +0 -0
@@ -7,6 +7,58 @@ Entries marked **Affects existing figures: re-render.** change figure output (wh
7
7
  the statistics, the layout) or caption text: figures made with an earlier version should be
8
8
  drawn again.
9
9
 
10
+ ## [Unreleased]
11
+
12
+ ## [0.2.2] - 2026-12-04
13
+
14
+ Patch release that requires cmcrameri below 2.0, the colour maps eofigs was checked
15
+ against. Support for cmcrameri 2.0 follows.
16
+
17
+ ### Changed
18
+
19
+ - eofigs requires cmcrameri below 2.0 (`cmcrameri>=1.9,<2`). cmcrameri 2.0 (December 2026)
20
+ adds colour maps and changes some colours, which eofigs has not been checked against yet;
21
+ support follows ([#45](https://github.com/kmkamilkhel/eofigs/issues/45)). The same cap is in
22
+ the development environment, the container image and the installation guide.
23
+ - The citation page and the README give the version DOI of 0.2.1
24
+ (10.5281/zenodo.24241081).
25
+ - cmcrameri now comes from conda-forge in the development environment and in the installation
26
+ guide: the conda-forge build 1.10 (build 1) reports its version correctly.
27
+
28
+ ## [0.2.1] - 2026-11-15
29
+
30
+ Patch release with two fixes found in real use: readable colour-bar ticks for small
31
+ trends, and mathtext in the text font without font notices.
32
+
33
+ ### Fixed
34
+
35
+ - `trend_map` and `event_composite`: colour-bar limits below 0.01 are written as a power
36
+ of ten times a short number, with the factor in the colour-bar label (for example
37
+ "NIRv trend (10⁻³ decade⁻¹)" with ticks −5 to 5; the latitude profile uses the same
38
+ factor). If neighbouring tick labels still touch at the printed size, the colour bar
39
+ drops to three ticks. The caption keeps the true values; the record gives the factor as
40
+ `colourbar_scale` (#37). Re-render trend maps and event composites whose colour-bar
41
+ limits are below 0.01, or whose colour-bar tick labels overlapped. The first now show a
42
+ power-of-ten factor in the label; the second show three ticks instead of five. Other
43
+ figures do not need to be drawn again. **Affects existing figures: re-render.**
44
+ - `set_style` sets mathtext to the chosen text font and weight (`mathtext.fontset`
45
+ "custom", with `rm`, `it`, `bf`, `sf` and `cal` mapped to the text font), so units,
46
+ subscripts and symbols match the text. With `bold=True`, matplotlib no longer prints
47
+ "findfont: Failed to find font weight bold" notices for its built-in mathtext fallback
48
+ fonts; notices about any other font, including a missing font you asked for, are kept
49
+ (#38).
50
+
51
+ ### Added
52
+
53
+ - `check_figure` warns when the tick labels of a colour bar touch or overlap (#37).
54
+
55
+ ### Changed
56
+
57
+ - Units and subscripts are now set in the text font and weight; glyphs may shift
58
+ slightly. No change to what figures show (#38).
59
+ - The citation page and the README give the version DOI of 0.2.0
60
+ (10.5281/zenodo.24143866).
61
+
10
62
  ## [0.2.0] - 2026-11-11
11
63
 
12
64
  Statistical tests behind the significance marks: false discovery rate control and the
@@ -224,6 +276,9 @@ figures: study area map, trend map, event composite and accuracy scatter.
224
276
  - Code of conduct (Contributor Covenant 2.1), issue templates, pull request template.
225
277
  - Citation file validation and coverage total in continuous integration.
226
278
 
279
+ [Unreleased]: https://github.com/kmkamilkhel/eofigs/compare/v0.2.2...HEAD
280
+ [0.2.2]: https://github.com/kmkamilkhel/eofigs/compare/v0.2.1...v0.2.2
281
+ [0.2.1]: https://github.com/kmkamilkhel/eofigs/compare/v0.2.0...v0.2.1
227
282
  [0.2.0]: https://github.com/kmkamilkhel/eofigs/compare/v0.1.1...v0.2.0
228
283
  [0.1.1]: https://github.com/kmkamilkhel/eofigs/compare/v0.1.0...v0.1.1
229
284
  [0.1.0]: https://github.com/kmkamilkhel/eofigs/releases/tag/v0.1.0
@@ -2,8 +2,8 @@ cff-version: 1.2.0
2
2
  message: "If you use this software, please cite it using these metadata."
3
3
  title: "eofigs: analysis-aware, publication-ready figures for Earth observation research"
4
4
  type: software
5
- version: 0.2.0
6
- date-released: "2026-11-11"
5
+ version: 0.2.2
6
+ date-released: "2026-12-04"
7
7
  doi: 10.5281/zenodo.24053760
8
8
  abstract: >-
9
9
  eofigs turns Earth observation analysis outputs (rasters, time series and validation
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: eofigs
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Analysis-aware, publication-ready figures for Earth observation research.
5
5
  Project-URL: Homepage, https://kmkamilkhel.github.io/eofigs/
6
6
  Project-URL: Documentation, https://kmkamilkhel.github.io/eofigs/
@@ -26,7 +26,7 @@ Classifier: Topic :: Scientific/Engineering :: Visualization
26
26
  Classifier: Typing :: Typed
27
27
  Requires-Python: >=3.11
28
28
  Requires-Dist: cartopy>=0.23
29
- Requires-Dist: cmcrameri>=1.9
29
+ Requires-Dist: cmcrameri<2,>=1.9
30
30
  Requires-Dist: geopandas>=1.0
31
31
  Requires-Dist: matplotlib-scalebar>=0.8
32
32
  Requires-Dist: matplotlib>=3.9
@@ -136,11 +136,11 @@ More in the [quickstart](https://kmkamilkhel.github.io/eofigs/quickstart/) and t
136
136
  ## Run with Docker
137
137
 
138
138
  A container image with eofigs and its geospatial stack (cartopy, rioxarray, geopandas, fonts)
139
- is published on GitHub Container Registry for each release (`0.2.0`, `latest`; `dev` follows
139
+ is published on GitHub Container Registry for each release (`0.2.2`, `latest`; `dev` follows
140
140
  the main branch):
141
141
 
142
142
  ```bash
143
- docker run --rm -v "$PWD":/work ghcr.io/kmkamilkhel/eofigs:0.2.0 python script.py
143
+ docker run --rm -v "$PWD":/work ghcr.io/kmkamilkhel/eofigs:0.2.2 python script.py
144
144
  ```
145
145
 
146
146
  ## Roadmap
@@ -183,7 +183,7 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) and the [Code of Conduct](CODE_OF_CONDUCT
183
183
 
184
184
  If you use eofigs, please cite it. The software is archived on Zenodo:
185
185
  [doi:10.5281/zenodo.24053760](https://doi.org/10.5281/zenodo.24053760) covers all versions, and each release
186
- has its own DOI (v0.1.1: [doi:10.5281/zenodo.24084780](https://doi.org/10.5281/zenodo.24084780)). The metadata are in
186
+ has its own DOI (v0.2.1: [doi:10.5281/zenodo.24241081](https://doi.org/10.5281/zenodo.24241081)). The metadata are in
187
187
  [CITATION.cff](CITATION.cff); the
188
188
  [citation page](https://kmkamilkhel.github.io/eofigs/citation/) has APA and BibTeX entries.
189
189
 
@@ -67,11 +67,11 @@ More in the [quickstart](https://kmkamilkhel.github.io/eofigs/quickstart/) and t
67
67
  ## Run with Docker
68
68
 
69
69
  A container image with eofigs and its geospatial stack (cartopy, rioxarray, geopandas, fonts)
70
- is published on GitHub Container Registry for each release (`0.2.0`, `latest`; `dev` follows
70
+ is published on GitHub Container Registry for each release (`0.2.2`, `latest`; `dev` follows
71
71
  the main branch):
72
72
 
73
73
  ```bash
74
- docker run --rm -v "$PWD":/work ghcr.io/kmkamilkhel/eofigs:0.2.0 python script.py
74
+ docker run --rm -v "$PWD":/work ghcr.io/kmkamilkhel/eofigs:0.2.2 python script.py
75
75
  ```
76
76
 
77
77
  ## Roadmap
@@ -114,7 +114,7 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) and the [Code of Conduct](CODE_OF_CONDUCT
114
114
 
115
115
  If you use eofigs, please cite it. The software is archived on Zenodo:
116
116
  [doi:10.5281/zenodo.24053760](https://doi.org/10.5281/zenodo.24053760) covers all versions, and each release
117
- has its own DOI (v0.1.1: [doi:10.5281/zenodo.24084780](https://doi.org/10.5281/zenodo.24084780)). The metadata are in
117
+ has its own DOI (v0.2.1: [doi:10.5281/zenodo.24241081](https://doi.org/10.5281/zenodo.24241081)). The metadata are in
118
118
  [CITATION.cff](CITATION.cff); the
119
119
  [citation page](https://kmkamilkhel.github.io/eofigs/citation/) has APA and BibTeX entries.
120
120
 
@@ -42,7 +42,7 @@ dependencies = [
42
42
  "scipy>=1.11",
43
43
  "matplotlib>=3.9",
44
44
  "cartopy>=0.23",
45
- "cmcrameri>=1.9",
45
+ "cmcrameri>=1.9,<2",
46
46
  "matplotlib-scalebar>=0.8",
47
47
  "rioxarray>=0.15",
48
48
  "geopandas>=1.0",
@@ -20,7 +20,7 @@ from eofigs.styling import label_panels, new_figure, set_style, style, tidy_axes
20
20
  from eofigs.trends import trend_map
21
21
  from eofigs.variables import Variable, register_variable, variable
22
22
 
23
- __version__ = "0.2.0"
23
+ __version__ = "0.2.2"
24
24
 
25
25
  __all__ = [
26
26
  "CheckReport",
@@ -30,7 +30,7 @@ from eofigs._colour import (
30
30
  to_srgb,
31
31
  )
32
32
  from eofigs._presets import MM_PER_INCH, Journal, check_art, get_journal
33
- from eofigs.styling import current_journal, current_max_ticks
33
+ from eofigs.styling import current_journal, current_max_ticks, tick_labels_overlap
34
34
 
35
35
  Status = Literal["pass", "warn", "fail"]
36
36
 
@@ -101,7 +101,7 @@ def check_figure(
101
101
  For a live figure the checks are: printed size, resolution, smallest font size,
102
102
  fonts in use, colour-blind safety of categorical colours, colour maps, and, when a
103
103
  tick limit is set with ``set_style(max_ticks=...)``, the number of tick labels per
104
- axis. For
104
+ axis; colour bars are checked for touching or overlapping tick labels. For
105
105
  files: size and resolution (raster files), size and embedded fonts (PDF).
106
106
 
107
107
  Parameters
@@ -248,9 +248,35 @@ def _check_live(
248
248
  results.append(overlay)
249
249
  if max_ticks is not None:
250
250
  results.append(_tick_result(fig, max_ticks))
251
+ bars = _colourbar_tick_result(fig)
252
+ if bars is not None:
253
+ results.append(bars)
251
254
  return results
252
255
 
253
256
 
257
+ def _colourbar_tick_result(fig: Figure) -> CheckResult | None:
258
+ """Warn when the tick labels of a colour bar touch or overlap (figure already drawn)."""
259
+ bars = [
260
+ ax for ax in fig.axes if getattr(ax, "_colorbar", None) is not None and ax.get_visible()
261
+ ]
262
+ if not bars:
263
+ return None
264
+ crowded = []
265
+ for ax in bars:
266
+ which = "x" if ax._colorbar.orientation == "horizontal" else "y"
267
+ if tick_labels_overlap(ax, which, draw=False):
268
+ label = ax._colorbar.ax.get_xlabel() if which == "x" else ax._colorbar.ax.get_ylabel()
269
+ crowded.append(label.strip() or f"axes {fig.axes.index(ax) + 1}")
270
+ if crowded:
271
+ return CheckResult(
272
+ "colour-bar ticks",
273
+ "warn",
274
+ f"Colour-bar tick labels overlap: {', '.join(crowded[:4])}. Use fewer ticks, or "
275
+ "scale the values and put the factor in the label (as trend_map does).",
276
+ )
277
+ return CheckResult("colour-bar ticks", "pass", "Colour-bar tick labels do not overlap.")
278
+
279
+
254
280
  def _font_size_result(texts: list[Text], preset: Journal) -> CheckResult:
255
281
  if not texts:
256
282
  return CheckResult("font size", "pass", "No text in the figure.")
@@ -781,6 +781,7 @@ def _draw(
781
781
  "phase_steps": steps,
782
782
  "limits": limit,
783
783
  "limits_rule": rule,
784
+ "colourbar_scale": trends.tick_scale(limit),
784
785
  "extend": extend,
785
786
  "clipped_percent": round(clipped, 2),
786
787
  "excluded_percent": round(100.0 * float(excluded.sum()) / max(int(footprint.sum()), 1), 2),
@@ -2,7 +2,10 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import itertools
6
+ import logging
5
7
  import math
8
+ import re
6
9
  import string
7
10
  import warnings
8
11
  from collections.abc import Iterator, Sequence
@@ -77,6 +80,55 @@ def _resolve_font(font: str | None, default_family: str) -> tuple[str, str]:
77
80
  return "DejaVu Sans", "sans-serif" # always shipped with matplotlib
78
81
 
79
82
 
83
+ def _fc_escape(name: str) -> str:
84
+ """Escape a family name for a fontconfig pattern ("-" and ":" are separators there)."""
85
+ return re.sub(r"([-:\\])", r"\\\1", name)
86
+
87
+
88
+ def _mathtext_params(name: str, family: str, bold: bool) -> dict[str, Any]:
89
+ """Mathtext in the text font and weight: units, subscripts and symbols match the text.
90
+
91
+ Glyphs the text font lacks come from STIX (serif) or STIX Sans (sans-serif).
92
+ """
93
+ font = _fc_escape(name)
94
+ weight = ":bold" if bold else ""
95
+ return {
96
+ "mathtext.fontset": "custom",
97
+ "mathtext.rm": f"{font}{weight}",
98
+ "mathtext.sf": f"{font}{weight}",
99
+ "mathtext.it": f"{font}:italic{weight}",
100
+ "mathtext.bf": f"{font}:bold",
101
+ "mathtext.cal": f"{font}{weight}", # the default "cursive" has no bold face on macOS
102
+ "mathtext.default": "regular",
103
+ "mathtext.fallback": "stix" if family == "serif" else "stixsans",
104
+ }
105
+
106
+
107
+ #: Fonts matplotlib loads for mathtext fallbacks and large delimiters; none has a bold face.
108
+ _MATH_FALLBACK = re.compile(
109
+ r"Failed to find font weight \w+ for "
110
+ r"(cm\w+|STIX\w*|DejaVu Sans Display|DejaVu Sans Mono|DejaVu Serif Display)"
111
+ )
112
+
113
+
114
+ class _MathFallbackFilter(logging.Filter):
115
+ """Drop findfont notices about the bold weight of mathtext fallback fonts.
116
+
117
+ With bold text, matplotlib asks for the bold face of every font it loads for mathtext
118
+ (Computer Modern, STIX size fonts), which do not have one; it then uses the regular
119
+ face. The notices are expected and carry no information for the figure.
120
+ """
121
+
122
+ def filter(self, record: logging.LogRecord) -> bool:
123
+ return not _MATH_FALLBACK.search(record.getMessage())
124
+
125
+
126
+ def _quiet_math_fallback_lookups() -> None:
127
+ log = logging.getLogger("matplotlib.font_manager")
128
+ if not any(isinstance(f, _MathFallbackFilter) for f in log.filters):
129
+ log.addFilter(_MathFallbackFilter())
130
+
131
+
80
132
  def set_style(
81
133
  journal: str | None = "elsevier",
82
134
  font: str | None = None,
@@ -156,6 +208,7 @@ def set_style(
156
208
  small = max(size - 1, preset.min_font_pt)
157
209
  weight = "bold" if bold else "normal"
158
210
 
211
+ _quiet_math_fallback_lookups()
159
212
  mpl.rcParams.update(
160
213
  {
161
214
  "font.family": [name],
@@ -172,8 +225,7 @@ def set_style(
172
225
  "legend.fontsize": small,
173
226
  "legend.title_fontsize": size,
174
227
  "legend.frameon": False,
175
- "mathtext.fontset": "stix" if family == "serif" else "dejavusans",
176
- "mathtext.default": "regular",
228
+ **_mathtext_params(name, family, bold),
177
229
  "axes.unicode_minus": True,
178
230
  "axes.prop_cycle": cycler(color=list(OKABE_ITO)),
179
231
  "image.cmap": "cmc.batlow",
@@ -450,6 +502,30 @@ def tidy_axes(*items: Any, max_ticks: int | None = None) -> None:
450
502
  tidy_axes(*np.ravel(np.asarray(item, dtype=object)), max_ticks=max_ticks)
451
503
 
452
504
 
505
+ def tick_labels_overlap(ax: Axes, which: str = "x", gap_pt: float = 1.5, draw: bool = True) -> bool:
506
+ """Return True when neighbouring rendered tick labels of an axis touch or overlap.
507
+
508
+ With ``draw=True`` the figure is drawn once (without output) to place the labels;
509
+ ``gap_pt`` is the smallest free space required between two labels.
510
+ """
511
+ root = ax.figure
512
+ root = getattr(root, "figure", None) or root # the top figure for a subfigure
513
+ if draw:
514
+ root.draw_without_rendering()
515
+ renderer = root.canvas.get_renderer()
516
+ axis = ax.xaxis if which == "x" else ax.yaxis
517
+ boxes = [t.get_window_extent(renderer) for t in axis.get_ticklabels()
518
+ if t.get_visible() and t.get_text().strip()] # fmt: skip
519
+ if len(boxes) < 2:
520
+ return False
521
+ gap = renderer.points_to_pixels(gap_pt)
522
+ if which == "x":
523
+ boxes.sort(key=lambda b: b.x0)
524
+ return any(a.x1 + gap > b.x0 for a, b in itertools.pairwise(boxes))
525
+ boxes.sort(key=lambda b: b.y0)
526
+ return any(a.y1 + gap > b.y0 for a, b in itertools.pairwise(boxes))
527
+
528
+
453
529
  def round_ticks(low: float, high: float, min_n: int = 4, max_n: int = 5) -> np.ndarray:
454
530
  """Round tick values between ``low`` and ``high``: ``min_n`` to ``max_n`` if possible.
455
531
 
@@ -21,7 +21,7 @@ from eofigs import maps
21
21
  from eofigs._colour import NO_DATA_COLOUR, SECONDARY_COLOUR, TEXT_COLOUR
22
22
  from eofigs._presets import get_journal, resolve_width
23
23
  from eofigs.stats import fdr_mask
24
- from eofigs.styling import _STATE, label_panels, round_ticks
24
+ from eofigs.styling import _STATE, label_panels, round_ticks, tick_labels_overlap
25
25
  from eofigs.variables import Variable
26
26
  from eofigs.variables import variable as lookup_variable
27
27
 
@@ -313,6 +313,7 @@ def trend_map(
313
313
  "crs": crs.to_string(),
314
314
  "limits": limit,
315
315
  "limits_rule": rule,
316
+ "colourbar_scale": tick_scale(limit),
316
317
  "extend": extend,
317
318
  **stats,
318
319
  "fdr": fdr_record,
@@ -763,15 +764,57 @@ def _draw_colourbar(holder, ax, lay, image, var, extend):
763
764
  rect = (x / lay.fig_w, y / lay.fig_h, w / lay.fig_w, h / lay.fig_h)
764
765
  bar = holder.colorbar(image, cax=holder.add_axes(rect), orientation="horizontal",
765
766
  extend=extend) # fmt: skip
766
- bar.set_label(var.short_label, size=mpl.rcParams["font.size"])
767
+ limit = float(image.norm.vmax)
768
+ exponent = tick_scale(limit)
769
+ factor = 10.0**exponent
770
+ bar.set_label(scaled_label(var, exponent), size=mpl.rcParams["font.size"])
767
771
  bar.ax.tick_params(labelsize=small, width=0.6, length=2.5)
768
772
  bar.outline.set_linewidth(0.6)
769
- bar.set_ticks(diverging_ticks(image.norm.vmax, _STATE.get("max_ticks") or 5))
770
- bar.formatter = FuncFormatter(lambda value, _: tick_label(value))
773
+ bar.formatter = FuncFormatter(lambda value, _: tick_label(value / factor))
774
+ bar.set_ticks(diverging_ticks(limit / factor, _STATE.get("max_ticks") or 5) * factor)
771
775
  bar.update_ticks()
776
+ if tick_labels_overlap(bar.ax, "x"): # still crowded: three round ticks around zero
777
+ bar.set_ticks(diverging_ticks(limit / factor, 3) * factor)
778
+ bar.update_ticks()
779
+ bar.ax._eofigs_tick_scale = exponent
772
780
  return bar
773
781
 
774
782
 
783
+ #: Colour-bar limits below this are written as a power of ten times a short number, with the
784
+ #: factor in the label ("NDVI trend (10⁻³ yr⁻¹)", ticks −5 to 5), so the tick labels stay short.
785
+ SCALE_BELOW = 0.01
786
+
787
+
788
+ def tick_scale(limit: float) -> int:
789
+ """Power of ten that brings a small colour-bar limit into the range 1-10, else 0.
790
+
791
+ Examples
792
+ --------
793
+ >>> from eofigs.trends import tick_scale
794
+ >>> tick_scale(0.08), tick_scale(0.008), tick_scale(0.001), tick_scale(0.0006)
795
+ (0, -3, -3, -4)
796
+ """
797
+ if not np.isfinite(limit) or limit <= 0 or limit >= SCALE_BELOW:
798
+ return 0
799
+ return int(np.floor(np.log10(limit) + 1e-9))
800
+
801
+
802
+ def scaled_label(var: Variable, exponent: int) -> str:
803
+ """Short label with a power-of-ten factor before the units ("NIRv trend (10$^{-3}$ yr$^{-1}$)").
804
+
805
+ Examples
806
+ --------
807
+ >>> from eofigs.trends import scaled_label
808
+ >>> from eofigs.variables import variable
809
+ >>> scaled_label(variable("ndvi").trend(), -3)
810
+ 'NDVI trend (10$^{-3}$ decade$^{-1}$)'
811
+ """
812
+ if exponent == 0:
813
+ return var.short_label
814
+ units = f"10$^{{{exponent}}}$" + (f" {var.units}" if var.units else "")
815
+ return f"{var.symbol} ({units})"
816
+
817
+
775
818
  def tick_label(value: float) -> str:
776
819
  """Shortest exact label for a tick value, "0" for zero and a true minus sign.
777
820
 
@@ -888,11 +931,13 @@ def _draw_profile(holder, ax, lay, shown, crs, extent, limit, var, small):
888
931
  prof.yaxis.tick_right()
889
932
  prof.tick_params(labelsize=small, width=0.6, length=2.5)
890
933
  prof.grid(axis="y", color=SECONDARY_COLOUR, linewidth=0.3, alpha=0.6, linestyle=(0, (2, 2)))
891
- prof.set_xlabel(f"Median {var.short_label}", size=mpl.rcParams["font.size"])
934
+ exponent = tick_scale(limit) # same power-of-ten factor as the colour bar
935
+ factor = 10.0**exponent
936
+ prof.set_xlabel(f"Median {scaled_label(var, exponent)}", size=mpl.rcParams["font.size"])
892
937
  for spine in prof.spines.values():
893
938
  spine.set_linewidth(0.6)
894
- prof.set_xticks(diverging_ticks(limit, _STATE.get("max_ticks") or 5))
895
- prof.xaxis.set_major_formatter(FuncFormatter(lambda value, _: tick_label(value)))
939
+ prof.set_xticks(diverging_ticks(limit / factor, _STATE.get("max_ticks") or 5) * factor)
940
+ prof.xaxis.set_major_formatter(FuncFormatter(lambda value, _: tick_label(value / factor)))
896
941
  return prof, {"step_deg": round(float(step), 4), "bands": int(len(centres)),
897
942
  "min_pixels": PROFILE_MIN_PIXELS} # fmt: skip
898
943
 
@@ -343,3 +343,23 @@ def test_fill_between_envelopes_are_not_categorical_classes(sans_font):
343
343
  ax.add_patch(Rectangle((0, 0), 0.1, 0.1, color="#B8BDBD"))
344
344
  names = [r.name for r in eofigs.check_figure(fig).warnings]
345
345
  assert "colour-blind safety" in names
346
+
347
+
348
+ def test_overlapping_colour_bar_ticks_warn(sans_font):
349
+ fig, ax = _figure(sans_font)
350
+ image = ax.imshow(np.linspace(-0.01, 0.01, 100).reshape(10, 10), cmap="RdBu_r")
351
+ bar = fig.colorbar(image, ax=ax, orientation="horizontal")
352
+ bar.set_ticks(np.linspace(-0.01, 0.01, 11))
353
+ bar.ax.xaxis.set_major_formatter(mpl.ticker.FuncFormatter(lambda v, _: f"{v:.4f}"))
354
+ report = eofigs.check_figure(fig)
355
+ (result,) = [r for r in report.results if r.name == "colour-bar ticks"]
356
+ assert result.status == "warn"
357
+ bar.set_ticks([-0.01, 0, 0.01])
358
+ (result,) = [r for r in eofigs.check_figure(fig).results if r.name == "colour-bar ticks"]
359
+ assert result.status == "pass"
360
+
361
+
362
+ def test_no_colour_bar_no_colour_bar_check(sans_font):
363
+ fig, ax = _figure(sans_font)
364
+ ax.plot([0, 1], [0, 1])
365
+ assert "colour-bar ticks" not in {r.name for r in eofigs.check_figure(fig).results}
@@ -1,6 +1,8 @@
1
+ import logging
1
2
  import warnings
2
3
 
3
4
  import matplotlib as mpl
5
+ import matplotlib.pyplot as plt
4
6
  import pytest
5
7
 
6
8
  import eofigs
@@ -16,7 +18,8 @@ def test_set_style_applies_journal_settings(sans_font):
16
18
  assert rc["xtick.labelsize"] == 8 # never below the journal minimum
17
19
  assert rc["pdf.fonttype"] == 42
18
20
  assert rc["savefig.dpi"] == 600
19
- assert rc["mathtext.fontset"] == "dejavusans"
21
+ assert rc["mathtext.fontset"] == "custom"
22
+ assert rc["mathtext.rm"] == sans_font
20
23
  assert [c.upper() for c in rc["axes.prop_cycle"].by_key()["color"]] == list(OKABE_ITO)
21
24
  assert style_module.current_journal() == "springer"
22
25
 
@@ -32,10 +35,75 @@ def test_serif_uses_stix_mathtext():
32
35
  with warnings.catch_warnings():
33
36
  warnings.simplefilter("ignore", UserWarning) # Times New Roman may be missing
34
37
  eofigs.set_style("elsevier", font="serif")
35
- assert mpl.rcParams["mathtext.fontset"] == "stix"
38
+ assert mpl.rcParams["mathtext.fontset"] == "custom"
39
+ assert mpl.rcParams["mathtext.fallback"] == "stix"
36
40
  assert style_module._STATE["font_family"] == "serif"
37
41
 
38
42
 
43
+ def test_mathtext_uses_the_text_font_and_weight(sans_font):
44
+ eofigs.set_style("custom", font=sans_font, bold=True)
45
+ assert mpl.rcParams["mathtext.fontset"] == "custom"
46
+ assert mpl.rcParams["mathtext.rm"] == f"{sans_font}:bold"
47
+ assert mpl.rcParams["mathtext.it"] == f"{sans_font}:italic:bold"
48
+ assert mpl.rcParams["mathtext.fallback"] == "stixsans"
49
+ assert mpl.rcParams["mathtext.cal"] == f"{sans_font}:bold"
50
+ eofigs.set_style("custom", font=sans_font)
51
+ assert mpl.rcParams["mathtext.rm"] == sans_font
52
+ assert style_module._fc_escape("Source-Sans:3") == r"Source\-Sans\:3"
53
+
54
+
55
+ def test_bold_mathtext_prints_no_font_warnings(sans_font, caplog):
56
+ from matplotlib import font_manager, mathtext
57
+
58
+ # clear the font and mathtext caches so the fallback fonts are looked up again
59
+ font_manager.fontManager._findfont_cached.cache_clear()
60
+ parse_cache = getattr(mathtext.MathTextParser, "_parse_cached", None)
61
+ if parse_cache is not None:
62
+ parse_cache.cache_clear()
63
+ with eofigs.style("custom", font=sans_font, bold=True):
64
+ fig, ax = eofigs.new_figure("single", height_mm=40)
65
+ ax.set_xlabel(r"NIR$_{v}$ trend (10$^{-3}$ decade$^{-1}$) $\alpha$ km$^{2}$")
66
+ with caplog.at_level(logging.DEBUG, logger="matplotlib.font_manager"):
67
+ fig.canvas.draw()
68
+ findfont = [r.getMessage() for r in caplog.records if "Failed to find font" in r.getMessage()]
69
+ assert findfont == []
70
+ plt.close(fig)
71
+
72
+
73
+ def test_missing_user_font_still_warns(sans_font, caplog):
74
+ # eofigs's own warning when the requested text font is not installed
75
+ with pytest.warns(UserWarning, match="NoSuchFont"):
76
+ eofigs.set_style("custom", font="NoSuchFont", bold=True)
77
+ # matplotlib's notice for a missing family requested directly is not filtered
78
+ fig, ax = eofigs.new_figure("single", height_mm=40)
79
+ ax.text(0.5, 0.5, "label", fontfamily="NoSuchFont")
80
+ with caplog.at_level(logging.WARNING, logger="matplotlib.font_manager"):
81
+ fig.canvas.draw()
82
+ assert any("NoSuchFont" in r.getMessage() for r in caplog.records)
83
+ plt.close(fig)
84
+ eofigs.set_style(None)
85
+
86
+
87
+ def test_filter_drops_only_builtin_math_fallback_notices():
88
+ keep = style_module._MathFallbackFilter().filter
89
+
90
+ def record(message):
91
+ return logging.LogRecord(
92
+ "matplotlib.font_manager", logging.WARNING, "", 0, message, None, None
93
+ )
94
+
95
+ for name in ("cmex10", "cmmi10", "STIXSizeFiveSym", "STIXGeneral", "DejaVu Sans Display"):
96
+ assert not keep(
97
+ record(f"findfont: Failed to find font weight bold for {name}, now using 400.")
98
+ )
99
+ for message in (
100
+ "findfont: Failed to find font weight bold for NoSuchFont, now using 400.",
101
+ "findfont: Failed to find font weight bold for Arial Narrow, now using 400.",
102
+ "findfont: Font family 'NoSuchFont' not found.",
103
+ ):
104
+ assert keep(record(message))
105
+
106
+
39
107
  def test_set_style_none_restores_previous_settings(sans_font):
40
108
  before = mpl.rcParams["font.size"]
41
109
  eofigs.set_style("frontiers", font=sans_font, base_size=11)
@@ -747,3 +747,52 @@ def test_monthly_data_without_seasonal_warns_and_annual_does_not(custom_style):
747
747
  slope = _grid(np.full((8, 8), 0.01))
748
748
  with pytest.raises(ValueError, match="seasonal applies to data="):
749
749
  eofigs.trend_map(slope=slope, variable="ndvi", seasonal="month")
750
+
751
+
752
+ def _limit_grid(limit):
753
+ return _grid(np.linspace(-limit, limit, 60)[None, :].repeat(60, 0))
754
+
755
+
756
+ def _colour_bar(fig):
757
+ return [a for a in fig.axes if getattr(a, "_colorbar", None) is not None][0]
758
+
759
+
760
+ def test_small_limits_are_scaled_into_the_label(sans_font):
761
+ with eofigs.style("custom", font=sans_font, bold=True):
762
+ fig = eofigs.trend_map(slope=_limit_grid(0.006), variable="nirv", exclude=None,
763
+ width="single", limits=0.006) # fmt: skip
764
+ fig.canvas.draw()
765
+ bar = _colour_bar(fig)
766
+ assert "10$^{-3}$" in bar.get_xlabel()
767
+ assert [t.get_text() for t in bar.get_xticklabels()] == ["−5", "−2.5", "0", "2.5", "5"]
768
+ assert fig.eofigs_layout["colourbar_scale"] == -3
769
+ assert "±0.006" in fig.eofigs_layout["caption"] # the caption keeps the true values
770
+ report = eofigs.check_figure(fig)
771
+ (result,) = [r for r in report.results if r.name == "colour-bar ticks"]
772
+ assert result.status == "pass"
773
+
774
+
775
+ def test_crowded_colour_bar_ticks_are_thinned(sans_font):
776
+ with eofigs.style("custom", font=sans_font, bold=True):
777
+ crowded = eofigs.trend_map(slope=_limit_grid(0.0375), variable="nirv", exclude=None,
778
+ width="single", limits=0.0375) # fmt: skip
779
+ roomy = eofigs.trend_map(slope=_limit_grid(0.08), variable="nirv", exclude=None,
780
+ width="single", limits=0.08) # fmt: skip
781
+ for fig in (crowded, roomy):
782
+ fig.canvas.draw()
783
+ assert fig.eofigs_layout["colourbar_scale"] == 0
784
+ assert len(_colour_bar(crowded).get_xticks()) == 3
785
+ assert len(_colour_bar(roomy).get_xticks()) == 5
786
+ assert not trends.tick_labels_overlap(_colour_bar(crowded), "x")
787
+
788
+
789
+ def test_profile_axis_uses_the_colour_bar_scale(custom_style):
790
+ lat = np.linspace(35.9, 34.5, 141)
791
+ lon = np.linspace(72.0, 72.8, 81)
792
+ values = np.repeat(((lat - 35.2) / 300)[:, None], lon.size, axis=1) # about ±0.002
793
+ da = xr.DataArray(values, dims=("y", "x"), coords={"y": lat, "x": lon}).rio.write_crs(4326)
794
+ fig = eofigs.trend_map(slope=da, variable="ndvi", latitude_profile=True, width="double")
795
+ fig.canvas.draw()
796
+ prof = [a for a in fig.axes if a.get_xlabel().startswith("Median")][0]
797
+ assert "10$^{-3}$" in prof.get_xlabel()
798
+ assert all(len(t.get_text()) <= 4 for t in prof.get_xticklabels())
@@ -0,0 +1,75 @@
1
+ """The Zenodo draft script (.github/scripts/zenodo_draft.py): retries after HTTP 5xx answers."""
2
+
3
+ import importlib.util
4
+ import io
5
+ import urllib.error
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+ SCRIPT = Path(__file__).resolve().parents[1] / ".github" / "scripts" / "zenodo_draft.py"
11
+
12
+
13
+ @pytest.fixture
14
+ def zd():
15
+ spec = importlib.util.spec_from_file_location("zenodo_draft", SCRIPT)
16
+ module = importlib.util.module_from_spec(spec)
17
+ spec.loader.exec_module(module)
18
+ return module
19
+
20
+
21
+ class _Response(io.BytesIO):
22
+ def __enter__(self):
23
+ return self
24
+
25
+ def __exit__(self, *exc):
26
+ return False
27
+
28
+
29
+ def _server(monkeypatch, answers):
30
+ """Make urlopen answer with ``answers`` in turn: an HTTP code (an error) or a body (success)."""
31
+ seen = []
32
+
33
+ def urlopen(request, timeout=None):
34
+ seen.append(request.get_method())
35
+ answer = answers[len(seen) - 1]
36
+ if isinstance(answer, int):
37
+ fp = io.BytesIO(b'{"message": "error"}')
38
+ raise urllib.error.HTTPError(request.full_url, answer, "error", {}, fp)
39
+ return _Response(answer)
40
+
41
+ monkeypatch.setattr("urllib.request.urlopen", urlopen)
42
+ return seen
43
+
44
+
45
+ def test_a_5xx_answer_is_retried_with_doubling_waits(zd, monkeypatch, capsys):
46
+ seen = _server(monkeypatch, [500, 502, b'{"id": 1}'])
47
+ waits = []
48
+ out = zd.call("DELETE", "https://zenodo.test/api/x", "token", sleep=waits.append)
49
+ assert out == {"id": 1}
50
+ assert seen == ["DELETE"] * 3
51
+ assert waits == [zd.BACKOFF, 2 * zd.BACKOFF]
52
+ assert "retry 1 of 4" in capsys.readouterr().out
53
+
54
+
55
+ def test_retries_stop_after_the_limit(zd, monkeypatch):
56
+ seen = _server(monkeypatch, [503] * 10)
57
+ waits = []
58
+ with pytest.raises(zd.ZenodoError, match="HTTP 503"):
59
+ zd.call("GET", "https://zenodo.test/api/x", retries=3, backoff=1.0, sleep=waits.append)
60
+ assert len(seen) == 4
61
+ assert waits == [1.0, 2.0, 4.0]
62
+
63
+
64
+ def test_a_4xx_answer_is_not_retried(zd, monkeypatch):
65
+ seen = _server(monkeypatch, [400, b"{}"])
66
+ with pytest.raises(zd.ZenodoError, match="HTTP 400"):
67
+ zd.call("PUT", "https://zenodo.test/api/x", body={"a": 1}, sleep=lambda s: None)
68
+ assert seen == ["PUT"]
69
+
70
+
71
+ def test_post_is_never_repeated(zd, monkeypatch):
72
+ seen = _server(monkeypatch, [500, b"{}"])
73
+ with pytest.raises(zd.ZenodoError, match="HTTP 500"):
74
+ zd.call("POST", "https://zenodo.test/api/x", sleep=lambda s: None)
75
+ assert seen == ["POST"]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes