Source code for energy_analysis.degradation.gallery

"""Recompute the attributed degradation gallery from small annual stress tables."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import xarray as xr
from matplotlib.colors import BoundaryNorm, ListedColormap
from shapely.geometry import shape

from energy_data_retrieval.storage import sha256_file
from energy_methods.country_boundaries import polygons
from energy_methods.degradation import DegradationParameters
from energy_methods.degradation_mapping import RATE_VARIABLES, STRESS_UNITS, map_degradation

TITLES = ("Hydrolysis", "Photodegradation", "Thermomechanical", "Combined rate")






[docs] def load_degradation_example(directory: Path) -> tuple[xr.Dataset, xr.Dataset, dict[str, Any]]: """Verify small fixtures, recompute rates and check against the archived run. Returns annual inputs, recalculated rates, and source/calibration metadata. Rates are %/year under the named scenario; missing grid cells remain missing. """ metadata = json.loads((directory / "degradation_provenance.json").read_text()) if metadata.get("format_version") != 1: raise ValueError("Unsupported degradation fixture format") for name, expected in metadata["files"].items(): if Path(name).name != name or sha256_file(directory / name) != expected: raise ValueError(f"Degradation fixture checksum mismatch: {name}") if sha256_file(directory / "climate_world_boundaries.geojson") != metadata["boundaries_sha256"]: raise ValueError("Degradation boundary checksum mismatch") table = pd.read_csv(directory / "degradation_stresses.csv") if table.duplicated(["year", "lat", "lon"]).any(): raise ValueError("Duplicate annual stress coordinates") annual = table.set_index(["year", "lat", "lon"]).to_xarray() annual.attrs = metadata["stress_metadata"] for name, units in STRESS_UNITS.items(): annual[name].attrs["units"] = units parameters = DegradationParameters( **json.loads((directory / "degradation_parameters.json").read_text()) ) result = map_degradation(annual, parameters, aggregation="mean_stress") reference = ( pd.read_csv(directory / "degradation_reference.csv").set_index(["lat", "lon"]).to_xarray() ) result, reference = xr.align(result, reference, join="exact") for name in (*RATE_VARIABLES, "valid_year_count", "rate_class"): if not np.allclose(result[name], reference[name], rtol=1e-10, atol=1e-12, equal_nan=True): raise ValueError(f"Recalculation differs from archived study: {name}") result["land_mask"] = reference.land_mask result.attrs.update(metadata["result_metadata"]) return annual, result, metadata
[docs] def plot_degradation_maps( rates: xr.Dataset, boundaries: Path, *, categorical: bool = False ) -> plt.Figure: """Plot mechanism rates or the classified total on the supplied regular grid. Colored rectangles are sample-centred footprints, not land polygons or an interpolation to the coast. Gray footprints mark incomplete land samples. """ fig, axes = ( plt.subplots(1, 1, figsize=(13, 6), layout="constrained") if categorical else (plt.subplots(2, 2, figsize=(15, 9), layout="constrained")) ) document = json.loads(boundaries.read_text()) step = float(rates.attrs["grid_step_degrees"]) x = np.r_[rates.lon.values - step / 2, float(rates.lon[-1]) + step / 2] y = np.r_[rates.lat.values - step / 2, float(rates.lat[-1]) + step / 2] selected = ( [("rate_class", "Combined rate categories")] if categorical else list(zip(RATE_VARIABLES, TITLES, strict=True)) ) for ax, (name, title) in zip(np.asarray(axes).ravel(), selected, strict=True): ax.set_facecolor("#eef3f7") missing = (rates.land_mask == 1) & rates.total_rate.isnull() ax.pcolormesh( x, y, np.ma.masked_where(~missing.values, np.ones(missing.shape)), cmap=ListedColormap(["#747d86"]), shading="flat", ) if categorical: colors = plt.get_cmap("YlOrRd")(np.linspace(0.15, 0.95, 8)) cmap = ListedColormap(colors) mesh = ax.pcolormesh( x, y, rates[name].where(rates[name] > 0), cmap=cmap, norm=BoundaryNorm(np.arange(0.5, 9.5), 8), shading="flat", ) bar = fig.colorbar(mesh, ax=ax, orientation="horizontal", pad=0.09, ticks=range(1, 9)) labels = json.loads(rates.rate_class.attrs["class_labels"]) bar.ax.set_xticklabels([labels[str(i)] for i in range(1, 9)]) else: mesh = ax.pcolormesh( x, y, rates[name], cmap="YlOrRd", vmin=0, vmax=max(float(rates[name].max()), 1e-12), shading="flat", ) bar = fig.colorbar(mesh, ax=ax, orientation="horizontal", pad=0.09, shrink=0.9) bar.set_label("Scenario degradation rate (%/year)") for feature in document["features"]: for part in polygons(shape(feature["geometry"])): xy = np.asarray(part.exterior.coords) ax.plot(xy[:, 0], xy[:, 1], color="#526575", linewidth=0.4) ax.set( xlim=(-180, 180), ylim=(max(-90, y[0]), min(90, y[-1])), xlabel="Longitude (°)", ylabel="Latitude (°)", title=title, ) ax.grid(alpha=0.15) valid = int(rates.total_rate.notnull().sum()) land = int(rates.land_mask.sum()) fig.suptitle( f"Climate degradation scenario | {rates.attrs['baseline_start_year']}-" f"{rates.attrs['baseline_end_year']}\n" f"{step:g}° sampling · {valid}/{land} complete land centres · gray = missing · " + ("0.2%/year classes" if categorical else "each mechanism has its own color scale"), fontsize=14, ) return fig