diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 26f5226..69e5a5e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,4 +1,4 @@ -exclude: ^docs/(gallery|assets)/ +exclude: ^(docs/(gallery|assets)/|src/nicefigs/_data/) repos: - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.15.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e85282..2f26acf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ to [Semantic Versioning](https://semver.org/). ### Added +- Maps work offline: the Natural Earth 110m and 50m coastline, land, ocean and land-border shapefiles + are bundled and used before cartopy would download them, never overriding `cartopy.config`. + `cache_natural_earth(path=None)` (also `python -m nicefigs.naturalearth`) pre-downloads every layer + including 10m; `$NICEFIGS_NATURAL_EARTH_DIR` names the folder searched and written. +- `hatch_region(..., style="dots")` stipples without a hatch outline; `hatch` defaults per style and + `edgecolor="none"` draws no outline. Gallery example `36_stippled_difference_map`. - Concept-figure primitives in `nicefigs.schematic`: `schematic_axes` (a figure of the printed size whose data units are inches), `numbered_disc`, `group_band`, `label_pair`, `grid_cells`, `folder_icon` and the colour helpers `tint`, `shade` and `soft_color`. They draw with the active diff --git a/docs/api.md b/docs/api.md index a34a04c..a5c0f69 100644 --- a/docs/api.md +++ b/docs/api.md @@ -36,6 +36,10 @@ and the [Gallery](gallery.md) for runnable examples. ::: nicefigs.maps +## `nicefigs.naturalearth` + +::: nicefigs.naturalearth + ## `nicefigs.images` ::: nicefigs.images diff --git a/docs/assets/guide/maps-stipple.png b/docs/assets/guide/maps-stipple.png new file mode 100644 index 0000000..62a9390 Binary files /dev/null and b/docs/assets/guide/maps-stipple.png differ diff --git a/docs/gallery.md b/docs/gallery.md index 43a0eff..82c8c17 100644 --- a/docs/gallery.md +++ b/docs/gallery.md @@ -490,3 +490,15 @@ from the active theme and the `NICE_COLORS`. ```python --8<-- "examples/35_schematic.py" ``` + +### 36 — Difference map with significance stippling {#stippled-difference-map} + +[`hatch_region`][nicefigs.hatch_region] with `style="dots"` stipples the cells where a +difference is significant: dots only, no hatch outline, so the diverging colours underneath +stay readable. + +![Stippled difference map](gallery/36_stippled_difference_map.png) + +```python +--8<-- "examples/36_stippled_difference_map.py" +``` diff --git a/docs/gallery/36_stippled_difference_map.png b/docs/gallery/36_stippled_difference_map.png new file mode 100644 index 0000000..0eb5250 Binary files /dev/null and b/docs/gallery/36_stippled_difference_map.png differ diff --git a/docs/guide/maps.md b/docs/guide/maps.md index 2caeef2..c71765d 100644 --- a/docs/guide/maps.md +++ b/docs/guide/maps.md @@ -245,6 +245,56 @@ nf.inset_histogram_colorbar(ax, values, cmap="inferno", bounds=(0.08, 0.55, 0.4, ![Inset histogram colorbar](../assets/guide/maps-inset-hist.png) +## Stippling significance + +[`hatch_region()`][nicefigs.hatch_region] marks the cells where a mask is set and leaves the +colours beneath visible. `style="hatch"` (default) draws diagonal lines with an outline; +`style="dots"` draws dots only, with no line along the region's edge, the usual way to +show where a difference is significant. `edgecolor` colours the marks and `hatch` overrides +the pattern: + +```python +import numpy as np + +import nicefigs as nf +from nicefigs import data + +nf.set_theme("paper") + +extent = (-12, 40, 34, 60) +lon, lat, diff = data.regional_grid(res=0.25, extent=extent) +fig, ax, _ = nf.map( + lon, lat, diff, extent=extent, projection="platecarree", + diverging=True, inset_hist=False, cbar=True, borders=True, + colorbar_label="model difference [K]", +) +nf.hatch_region( + ax, lon.ravel(), lat.ravel(), (np.abs(diff) > 0.12).ravel(), + style="dots", bin_deg=0.5, +) +``` + +![Stippled difference map](../assets/guide/maps-stipple.png) + +## Working offline + +Cartopy downloads its Natural Earth coastlines on first use, which fails without internet +(compute nodes). nicefigs bundles the 110m and 50m coastline, land, ocean and land-border +shapefiles and points cartopy at them whenever a map is drawn. Data cartopy already finds +through `cartopy.config` or `CARTOPY_DATA_DIR` is used first; the bundled data is only the +fallback before a download. For the 10m resolution, cache everything once on a machine with +internet access: + +```bash +python -m nicefigs.naturalearth /path/to/natural_earth # or nicefigs.cache_natural_earth(path) +export NICEFIGS_NATURAL_EARTH_DIR=/path/to/natural_earth # on the offline machine +``` + +`NICEFIGS_NATURAL_EARTH_DIR` is searched after cartopy's own directories and before the +bundled data, and is the default target of +[`cache_natural_earth()`][nicefigs.naturalearth.cache_natural_earth]. The Natural Earth data is in the +public domain. + ## Ternary maps For a three-part composition per point, such as land-use fractions, diff --git a/examples/36_stippled_difference_map.py b/examples/36_stippled_difference_map.py new file mode 100644 index 0000000..1dab217 --- /dev/null +++ b/examples/36_stippled_difference_map.py @@ -0,0 +1,39 @@ +"""Difference map with significance stippling. + +A diverging regional difference map; ``hatch_region(..., style="dots")`` stipples the +cells where the difference is significant, with dots only and no outline, so the colours +underneath stay readable. +""" + +import numpy as np + +import nicefigs as nf +from nicefigs import data + + +def make(): + nf.set_theme("paper") + lon, lat, diff = data.regional_grid(res=0.25, extent=(-12, 40, 34, 60)) + significant = np.abs(diff) > 0.12 + fig, ax, _ = nf.map( + lon, + lat, + diff, + extent=(-12, 40, 34, 60), + projection="platecarree", + diverging=True, + inset_hist=False, + cbar=True, + borders=True, + colorbar_label="model difference [K]", + title="Difference, stippled where significant", + ) + nf.hatch_region(ax, lon.ravel(), lat.ravel(), significant.ravel(), style="dots", bin_deg=0.5) + return fig + + +if __name__ == "__main__": + import matplotlib + + matplotlib.use("Agg") + nf.save(make(), "36_stippled_difference_map", formats=("png", "pdf")) diff --git a/src/nicefigs/__init__.py b/src/nicefigs/__init__.py index 9712d43..a5c846f 100644 --- a/src/nicefigs/__init__.py +++ b/src/nicefigs/__init__.py @@ -57,6 +57,7 @@ scatter_map, tri_map, ) +from .naturalearth import cache_natural_earth from .palettes import ( CATEGORICAL, CUSTOM_CMAPS, @@ -281,6 +282,7 @@ "cross_section", "cross_section_panels", "profile", + "cache_natural_earth", "hatch_region", "taylor", "hovmoller", diff --git a/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.cpg b/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.cpg new file mode 100644 index 0000000..3ad133c --- /dev/null +++ b/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.cpg @@ -0,0 +1 @@ +UTF-8 \ No newline at end of file diff --git a/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.dbf b/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.dbf new file mode 100644 index 0000000..39ebad5 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.dbf differ diff --git a/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.prj b/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.prj new file mode 100644 index 0000000..b13a717 --- /dev/null +++ b/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.prj @@ -0,0 +1 @@ +GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.017453292519943295]] \ No newline at end of file diff --git a/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.shp b/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.shp new file mode 100644 index 0000000..0537422 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.shp differ diff --git a/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.shx b/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.shx new file mode 100644 index 0000000..763719e Binary files /dev/null and b/src/nicefigs/_data/natural_earth/cultural/ne_110m_admin_0_boundary_lines_land.shx differ diff --git a/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.cpg b/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.cpg new file mode 100644 index 0000000..3ad133c --- /dev/null +++ b/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.cpg @@ -0,0 +1 @@ +UTF-8 \ No newline at end of file diff --git a/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.dbf b/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.dbf new file mode 100644 index 0000000..fb5f801 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.dbf differ diff --git a/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.prj b/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.prj new file mode 100644 index 0000000..b13a717 --- /dev/null +++ b/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.prj @@ -0,0 +1 @@ +GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.017453292519943295]] \ No newline at end of file diff --git a/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.shp b/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.shp new file mode 100644 index 0000000..03820b6 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.shp differ diff --git a/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.shx b/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.shx new file mode 100644 index 0000000..2ce054b Binary files /dev/null and b/src/nicefigs/_data/natural_earth/cultural/ne_50m_admin_0_boundary_lines_land.shx differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_110m_coastline.dbf b/src/nicefigs/_data/natural_earth/physical/ne_110m_coastline.dbf new file mode 100644 index 0000000..d89c673 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_110m_coastline.dbf differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_110m_coastline.shp b/src/nicefigs/_data/natural_earth/physical/ne_110m_coastline.shp new file mode 100644 index 0000000..fc3f939 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_110m_coastline.shp differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_110m_coastline.shx b/src/nicefigs/_data/natural_earth/physical/ne_110m_coastline.shx new file mode 100644 index 0000000..49cc085 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_110m_coastline.shx differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_110m_land.cpg b/src/nicefigs/_data/natural_earth/physical/ne_110m_land.cpg new file mode 100644 index 0000000..3ad133c --- /dev/null +++ b/src/nicefigs/_data/natural_earth/physical/ne_110m_land.cpg @@ -0,0 +1 @@ +UTF-8 \ No newline at end of file diff --git a/src/nicefigs/_data/natural_earth/physical/ne_110m_land.dbf b/src/nicefigs/_data/natural_earth/physical/ne_110m_land.dbf new file mode 100644 index 0000000..f0ee147 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_110m_land.dbf differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_110m_land.prj b/src/nicefigs/_data/natural_earth/physical/ne_110m_land.prj new file mode 100644 index 0000000..b13a717 --- /dev/null +++ b/src/nicefigs/_data/natural_earth/physical/ne_110m_land.prj @@ -0,0 +1 @@ +GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.017453292519943295]] \ No newline at end of file diff --git a/src/nicefigs/_data/natural_earth/physical/ne_110m_land.shp b/src/nicefigs/_data/natural_earth/physical/ne_110m_land.shp new file mode 100644 index 0000000..69ce127 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_110m_land.shp differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_110m_land.shx b/src/nicefigs/_data/natural_earth/physical/ne_110m_land.shx new file mode 100644 index 0000000..0c82e83 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_110m_land.shx differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.cpg b/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.cpg new file mode 100644 index 0000000..3ad133c --- /dev/null +++ b/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.cpg @@ -0,0 +1 @@ +UTF-8 \ No newline at end of file diff --git a/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.dbf b/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.dbf new file mode 100644 index 0000000..41b0b77 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.dbf differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.prj b/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.prj new file mode 100644 index 0000000..b13a717 --- /dev/null +++ b/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.prj @@ -0,0 +1 @@ +GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.017453292519943295]] \ No newline at end of file diff --git a/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.shp b/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.shp new file mode 100644 index 0000000..953e7a1 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.shp differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.shx b/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.shx new file mode 100644 index 0000000..b665c27 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_110m_ocean.shx differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_50m_coastline.dbf b/src/nicefigs/_data/natural_earth/physical/ne_50m_coastline.dbf new file mode 100644 index 0000000..e98c7d4 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_50m_coastline.dbf differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_50m_coastline.shp b/src/nicefigs/_data/natural_earth/physical/ne_50m_coastline.shp new file mode 100644 index 0000000..3e2890d Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_50m_coastline.shp differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_50m_coastline.shx b/src/nicefigs/_data/natural_earth/physical/ne_50m_coastline.shx new file mode 100644 index 0000000..235eb40 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_50m_coastline.shx differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_50m_land.cpg b/src/nicefigs/_data/natural_earth/physical/ne_50m_land.cpg new file mode 100644 index 0000000..3ad133c --- /dev/null +++ b/src/nicefigs/_data/natural_earth/physical/ne_50m_land.cpg @@ -0,0 +1 @@ +UTF-8 \ No newline at end of file diff --git a/src/nicefigs/_data/natural_earth/physical/ne_50m_land.dbf b/src/nicefigs/_data/natural_earth/physical/ne_50m_land.dbf new file mode 100644 index 0000000..2dc4732 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_50m_land.dbf differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_50m_land.prj b/src/nicefigs/_data/natural_earth/physical/ne_50m_land.prj new file mode 100644 index 0000000..a30c00a --- /dev/null +++ b/src/nicefigs/_data/natural_earth/physical/ne_50m_land.prj @@ -0,0 +1 @@ +GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]] \ No newline at end of file diff --git a/src/nicefigs/_data/natural_earth/physical/ne_50m_land.shp b/src/nicefigs/_data/natural_earth/physical/ne_50m_land.shp new file mode 100644 index 0000000..75ce6d9 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_50m_land.shp differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_50m_land.shx b/src/nicefigs/_data/natural_earth/physical/ne_50m_land.shx new file mode 100644 index 0000000..8a145a5 Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_50m_land.shx differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.cpg b/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.cpg new file mode 100644 index 0000000..3ad133c --- /dev/null +++ b/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.cpg @@ -0,0 +1 @@ +UTF-8 \ No newline at end of file diff --git a/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.dbf b/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.dbf new file mode 100644 index 0000000..3c93d9d Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.dbf differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.prj b/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.prj new file mode 100644 index 0000000..a30c00a --- /dev/null +++ b/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.prj @@ -0,0 +1 @@ +GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]] \ No newline at end of file diff --git a/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.shp b/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.shp new file mode 100644 index 0000000..964c3df Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.shp differ diff --git a/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.shx b/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.shx new file mode 100644 index 0000000..32f350f Binary files /dev/null and b/src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.shx differ diff --git a/src/nicefigs/maps.py b/src/nicefigs/maps.py index 389f4a9..604a765 100644 --- a/src/nicefigs/maps.py +++ b/src/nicefigs/maps.py @@ -53,6 +53,9 @@ def _try_cartopy() -> ModuleType | None: try: import cartopy.crs as ccrs + from .naturalearth import use_offline_natural_earth + + use_offline_natural_earth() return ccrs except ImportError: return None @@ -150,6 +153,10 @@ def draw_background( return import cartopy.feature as cfeature + from .naturalearth import use_offline_natural_earth + + use_offline_natural_earth() + def _rasterize(artist: Any) -> None: if artist is not None and hasattr(artist, "set_rasterized"): artist.set_rasterized(True) @@ -209,6 +216,9 @@ def _land_mask(nx: int, ny: int, bin_deg: float, resolution: str) -> np.ndarray from shapely.prepared import prep except ImportError: return None + from .naturalearth import use_offline_natural_earth + + use_offline_natural_earth() shp = natural_earth(resolution=resolution, category="physical", name="land") land = prep(unary_union(list(Reader(shp).geometries()))) lon_c = -180.0 + bin_deg * (np.arange(nx) + 0.5) @@ -278,6 +288,9 @@ def _bin_values( return lon_edges, lat_edges, np.ma.masked_invalid(grid) +_HATCH_STYLES = {"hatch": "////", "dots": "..."} + + def hatch_region( ax: Axes, lon: ArrayLike, @@ -285,32 +298,42 @@ def hatch_region( mask: ArrayLike, *, ccrs: ModuleType | None = None, - hatch: str = "////", + style: str = "hatch", + hatch: str | None = None, edgecolor: str = "#333333", linewidth: float = 0.5, bin_deg: float = 2.0, threshold: float = 0.5, ) -> QuadContourSet: - """Hatch the region where a per-point mask is set, leaving the colours beneath visible. + """Hatch or stipple the region where a per-point mask is set, leaving the colours beneath visible. The mask is bin-averaged onto a ``bin_deg`` grid and cells at or above - ``threshold`` are hatched without fill. + ``threshold`` are marked without fill. ``style="dots"`` gives significance + stippling: dots only, with no line along the region's outline. Args: ax: Map axes. lon: Point longitudes in degrees east. lat: Point latitudes in degrees north. mask: Per-point boolean or fraction, same shape as ``lon``. - ccrs: The ``cartopy.crs`` module when ``ax`` is projected, else ``None``. - hatch: Matplotlib hatch pattern. - edgecolor: Hatch colour. - linewidth: Hatch line width in points. + ccrs: The ``cartopy.crs`` module; detected from ``ax`` if ``None``. + style: ``"hatch"`` (diagonal lines, outlined) or ``"dots"`` (dots, never outlined). + hatch: Matplotlib hatch pattern; defaults to ``"////"`` for ``"hatch"`` and ``"..."`` + for ``"dots"``. + edgecolor: Colour of the hatch marks. ``"none"`` draws no outline and takes the mark + colour from ``rcParams["hatch.color"]``. + linewidth: Hatch line and outline width in points. bin_deg: Grid cell size in degrees. threshold: Minimum cell-mean mask value that is hatched. Returns: The contour set drawing the hatch. """ + if style not in _HATCH_STYLES: + raise ValueError(f"style must be one of {sorted(_HATCH_STYLES)}, got {style!r}") + if hatch is None: + hatch = _HATCH_STYLES[style] + outline = style == "hatch" and edgecolor != "none" lon = np.asarray(lon, dtype=float) lat = np.asarray(lat, dtype=float) m = np.asarray(mask, dtype=float) @@ -318,15 +341,20 @@ def hatch_region( lon_c = 0.5 * (lon_e[:-1] + lon_e[1:]) lat_c = 0.5 * (lat_e[:-1] + lat_e[1:]) filled = np.ma.filled(grid, 0.0) + if ccrs is None and hasattr(ax, "projection"): + ccrs = _try_cartopy() kw = {} if ccrs is not None: kw["transform"] = ccrs.PlateCarree() - cs = ax.contourf(lon_c, lat_c, filled, levels=[threshold, 1e9], colors="none", hatches=[hatch], **kw) + # Without an outline matplotlib colours hatch marks from rcParams, read at creation. + rc = {} if edgecolor == "none" else {"hatch.color": edgecolor} + with plt.rc_context(rc): + cs = ax.contourf(lon_c, lat_c, filled, levels=[threshold, 1e9], colors="none", hatches=[hatch], **kw) # matplotlib < 3.8 exposes per-level ``.collections``; later the ContourSet is the collection. targets = getattr(cs, "collections", None) or [cs] for coll in targets: - coll.set_edgecolor(edgecolor) - coll.set_linewidth(linewidth) + coll.set_edgecolor(edgecolor if outline else "none") + coll.set_linewidth(linewidth if outline else 0.0) return cs diff --git a/src/nicefigs/naturalearth.py b/src/nicefigs/naturalearth.py new file mode 100644 index 0000000..7cb40dd --- /dev/null +++ b/src/nicefigs/naturalearth.py @@ -0,0 +1,128 @@ +"""Offline Natural Earth data for the map functions. + +nicefigs bundles the Natural Earth 110m and 50m coastline, land, ocean and land-border +shapefiles (public domain, naturalearthdata.com) so maps render without internet access, +e.g. on compute nodes. Cartopy looks up data in this order, and nicefigs adds its own +sources only as the last step before a download: + +1. ``cartopy.config["pre_existing_data_dir"]`` (``$CARTOPY_DATA_DIR``) and cartopy's + download cache, exactly as without nicefigs; +2. the folder in ``$NICEFIGS_NATURAL_EARTH_DIR``, laid out like cartopy's data dir + (``/shapefiles/natural_earth/physical/ne_10m_land.shp``, ...); +3. the data bundled with nicefigs (110m and 50m); +4. a download. + +The 10m resolution is not bundled; fetch it once with :func:`cache_natural_earth` or +``python -m nicefigs.naturalearth``. +""" + +from __future__ import annotations + +import argparse +import os +from collections.abc import Sequence +from pathlib import Path +from typing import Any + +ENV_VAR = "NICEFIGS_NATURAL_EARTH_DIR" +"""Environment variable naming a Natural Earth folder searched before the bundled data +and used as the default target of :func:`cache_natural_earth`.""" + +#: ``(category, name)`` of every Natural Earth layer the map functions draw. +LAYERS: tuple[tuple[str, str], ...] = ( + ("physical", "coastline"), + ("physical", "land"), + ("physical", "ocean"), + ("cultural", "admin_0_boundary_lines_land"), +) +RESOLUTIONS: tuple[str, ...] = ("110m", "50m", "10m") + +_BUNDLED = Path(__file__).parent / "_data" + + +def _search_dirs() -> list[Path]: + """Folders searched for a missing shapefile, in order.""" + dirs = [] + if os.environ.get(ENV_VAR): + dirs.append(Path(os.environ[ENV_VAR]).expanduser() / "shapefiles") + dirs.append(_BUNDLED) + return dirs + + +def use_offline_natural_earth() -> None: + """Make cartopy fall back to local Natural Earth data before it downloads. + + Idempotent and called by the map functions. Files cartopy already finds through its + own configuration are never replaced. + """ + from cartopy import config + + downloader = config["downloaders"].get(("shapefiles", "natural_earth")) + if downloader is None or getattr(downloader, "_nicefigs_offline", False): + return + download = downloader.acquire_resource + + def acquire_resource(target_path: Any, format_dict: dict[str, Any]) -> Any: + rel = Path("natural_earth") / format_dict["category"] + rel = rel / f"ne_{format_dict['resolution']}_{format_dict['name']}.shp" + for root in _search_dirs(): + candidate = root / rel + if candidate.exists(): + return candidate + return download(target_path, format_dict) + + downloader.acquire_resource = acquire_resource + downloader._nicefigs_offline = True + + +def cache_natural_earth( + path: str | os.PathLike[str] | None = None, resolutions: Sequence[str] = RESOLUTIONS +) -> Path: + """Download every Natural Earth layer nicefigs may draw, so maps work offline later. + + Run once on a machine with internet access. Layers already present are not fetched + again. + + Args: + path: Target folder, laid out like cartopy's data dir. Defaults to + ``$NICEFIGS_NATURAL_EARTH_DIR``, else cartopy's own data dir + (``cartopy.config["data_dir"]``). Point ``$NICEFIGS_NATURAL_EARTH_DIR`` (or + ``$CARTOPY_DATA_DIR``) at it on the offline machine. + resolutions: Subset of ``"110m"``, ``"50m"``, ``"10m"``. + + Returns: + The folder the data was cached in. + """ + import cartopy + from cartopy.io.shapereader import natural_earth + + unknown = set(resolutions) - set(RESOLUTIONS) + if unknown: + raise ValueError(f"unknown resolutions {sorted(unknown)}; choose from {RESOLUTIONS}") + if path is None: + path = os.environ.get(ENV_VAR) or cartopy.config["data_dir"] + target = Path(path).expanduser() + old = cartopy.config["data_dir"] + cartopy.config["data_dir"] = target + try: + for resolution in resolutions: + for category, name in LAYERS: + natural_earth(resolution=resolution, category=category, name=name) + finally: + cartopy.config["data_dir"] = old + return target + + +def main(argv: Sequence[str] | None = None) -> None: + """Command line entry: ``python -m nicefigs.naturalearth [PATH] [-r 50m 10m]``.""" + parser = argparse.ArgumentParser(description=cache_natural_earth.__doc__.split("\n\n")[0]) + parser.add_argument( + "path", nargs="?", default=None, help=f"target folder (default: ${ENV_VAR} or cartopy's)" + ) + parser.add_argument("-r", "--resolutions", nargs="+", default=list(RESOLUTIONS), choices=RESOLUTIONS) + args = parser.parse_args(argv) + print(cache_natural_earth(args.path, args.resolutions)) + + +if __name__ == "__main__": + main() diff --git a/tests/test_naturalearth.py b/tests/test_naturalearth.py new file mode 100644 index 0000000..fcd5244 --- /dev/null +++ b/tests/test_naturalearth.py @@ -0,0 +1,119 @@ +"""Maps must render from bundled Natural Earth data with the network blocked.""" + +from __future__ import annotations + +import shutil +import urllib.request + +import matplotlib.pyplot as plt +import numpy as np +import pytest + +import nicefigs as nf +from nicefigs import maps, naturalearth + +cartopy = pytest.importorskip("cartopy") +pytest.importorskip("shapely") + + +@pytest.fixture +def offline(monkeypatch, tmp_path): + """Empty cartopy caches and every download attempt raising, as on a compute node.""" + + def _blocked(*args, **kwargs): + raise urllib.error.URLError("network blocked") + + monkeypatch.setattr(urllib.request, "urlopen", _blocked) + monkeypatch.setitem(cartopy.config, "data_dir", tmp_path / "cartopy") + monkeypatch.setitem(cartopy.config, "pre_existing_data_dir", tmp_path / "none") + monkeypatch.delenv(naturalearth.ENV_VAR, raising=False) + maps._land_mask.cache_clear() + downloader = cartopy.config["downloaders"][("shapefiles", "natural_earth")] + monkeypatch.setattr(downloader, "_urlopen", _blocked, raising=False) + return tmp_path + + +@pytest.mark.parametrize("resolution", ["110m", "50m"]) +def test_map_features_render_offline(offline, resolution): + lon, lat, v = nf.data.global_points(n=500) + fig, ax, _ = nf.map(lon, lat, v, inset_hist=False) + nf.draw_background(ax, maps._try_cartopy(), ocean=True, borders=True, resolution=resolution) + fig.canvas.draw() + assert len(ax.collections) > 0 + plt.close(fig) + + +def test_clip_ocean_land_mask_offline(offline): + mask = maps._land_mask(36, 18, 10.0, "110m") + assert mask is not None and 0.1 < mask.mean() < 0.5 + + +def test_explicit_cartopy_dir_wins(offline): + src = naturalearth._BUNDLED / "natural_earth" / "physical" + dst = offline / "mine" / "shapefiles" / "natural_earth" / "physical" + dst.mkdir(parents=True) + for f in src.glob("ne_110m_land.*"): + shutil.copy(f, dst) + cartopy.config["pre_existing_data_dir"] = offline / "mine" + maps._try_cartopy() + from cartopy.io.shapereader import natural_earth + + path = natural_earth(resolution="110m", category="physical", name="land") + assert offline / "mine" in path.parents + + +def test_env_dir_beats_bundled_for_missing_resolution(offline, monkeypatch): + dst = offline / "ne" / "shapefiles" / "natural_earth" / "physical" + dst.mkdir(parents=True) + src = naturalearth._BUNDLED / "natural_earth" / "physical" + for f in src.glob("ne_110m_land.*"): + shutil.copy(f, dst / f.name.replace("110m", "10m")) + monkeypatch.setenv(naturalearth.ENV_VAR, str(offline / "ne")) + maps._try_cartopy() + from cartopy.io.shapereader import natural_earth + + assert offline / "ne" in natural_earth(resolution="10m", category="physical", name="land").parents + + +def test_cache_natural_earth_requests_every_layer(offline, monkeypatch): + import cartopy.io.shapereader as sr + + seen = [] + monkeypatch.setattr(sr, "natural_earth", lambda **kw: seen.append(kw)) + out = nf.cache_natural_earth(offline / "cache", resolutions=["10m"]) + assert out == offline / "cache" + assert {(k["category"], k["name"]) for k in seen} == set(naturalearth.LAYERS) + assert {k["resolution"] for k in seen} == {"10m"} + assert cartopy.config["data_dir"] == offline / "cartopy" # restored + with pytest.raises(ValueError): + nf.cache_natural_earth(offline, resolutions=["5m"]) + + +def _stipple(style, **kw): + lon, lat, v = nf.data.global_points(n=1500) + fig, ax, _ = nf.map(lon, lat, v, inset_hist=False) + cs = nf.hatch_region( + ax, lon, lat, (np.abs(lat) < 30).astype(float), ccrs=maps._try_cartopy(), bin_deg=6, style=style, **kw + ) + return fig, cs + + +def test_hatch_region_dots_have_no_outline(): + fig, cs = _stipple("dots", edgecolor="#cc0000") + assert list(cs.hatches) == ["..."] + assert cs.get_linewidth()[0] == 0.0 + assert len(cs.get_edgecolor()) == 0 or cs.get_edgecolor()[0][3] == 0.0 + fig.canvas.draw() + plt.close(fig) + + +def test_hatch_region_default_style_unchanged(): + fig, cs = _stipple("hatch") + assert list(cs.hatches) == ["////"] + assert cs.get_linewidth()[0] == 0.5 + plt.close(fig) + + +def test_hatch_region_rejects_unknown_style(): + with pytest.raises(ValueError, match="style"): + _stipple("stripes")