Download tasks/data/forward/agentoxygen__hdp.a0d206f/solution/golden.patch from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 120 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/agentoxygen__hdp.a0d206f/solution/golden.patch
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/agentoxygen__hdp.a0d206f/solution/golden.patch
-
curl -L -o golden.patch https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/agentoxygen__hdp.a0d206f/solution/golden.patch
120 kB
diff --git a/docs/_static/heatwave_widget.js b/docs/_static/heatwave_widget.js
new file mode 100644
index 0000000000000000000000000000000000000000..be9ddbd38ed3db97f5704f8b986a517b371bc3ec
--- /dev/null
+++ b/docs/_static/heatwave_widget.js
@@ -0,0 +1,367 @@
+/*
+ * Interactive Heatwave Definition Explorer
+ * ----------------------------------------
+ * Self-contained, dependency-free widget for the HDP documentation.
+ *
+ * `indexHeatwaves` below is a faithful JavaScript port of HDP's
+ * `index_heatwaves` kernel (the source of truth is hdp/metric.py).
+ * It classifies a 0/1 "hot day" timeseries into indexed heatwave events
+ * using the definition triple [min_duration, max_break, max_subs].
+ *
+ * The widget renders entirely client-side (no kernel, no network, no CDN)
+ * so it works as static HTML on ReadTheDocs and as a crash-proof live demo.
+ */
+(function () {
+ "use strict";
+
+ // ---------------------------------------------------------------------------
+ // Heatwave classification (port of hdp/metric.py :: index_heatwaves)
+ // ---------------------------------------------------------------------------
+ function indexHeatwaves(hotDays, minDuration, maxBreak, maxSubs) {
+ var n = hotDays.length;
+ // Zero-pad to n + 2 so leading/trailing events are bounded by a diff edge.
+ var ts = new Int32Array(n + 2);
+ for (var i = 0; i < n; i++) {
+ if (hotDays[i]) ts[i + 1] = 1;
+ }
+
+ // Discrete difference of the padded series.
+ var diffTs = new Int32Array(ts.length - 1);
+ for (var j = 0; j < diffTs.length; j++) {
+ diffTs[j] = ts[j + 1] - ts[j];
+ }
+
+ // Indices where the series transitions (rising = 1, falling = -1).
+ var diffIndices = [];
+ for (var k = 0; k < diffTs.length; k++) {
+ if (diffTs[k] !== 0) diffIndices.push(k);
+ }
+
+ var inHeatwave = false;
+ var currentHwIndex = 0;
+ var subEvents = 0;
+ var hwIndices = new Int32Array(diffTs.length);
+
+ for (var m = 0; m < diffIndices.length - 1; m++) {
+ var index = diffIndices[m];
+ var nextIndex = diffIndices[m + 1];
+
+ if (diffTs[index] === 1 && nextIndex - index >= minDuration && !inHeatwave) {
+ currentHwIndex += 1;
+ inHeatwave = true;
+ fill(hwIndices, index, nextIndex, currentHwIndex);
+ } else if (diffTs[index] === -1 && nextIndex - index > maxBreak) {
+ inHeatwave = false;
+ } else if (diffTs[index] === 1 && inHeatwave && subEvents < maxSubs) {
+ subEvents += 1;
+ fill(hwIndices, index, nextIndex, currentHwIndex);
+ } else if (diffTs[index] === 1 && inHeatwave && subEvents >= maxSubs) {
+ if (nextIndex - index >= minDuration) {
+ currentHwIndex += 1;
+ fill(hwIndices, index, nextIndex, currentHwIndex);
+ } else {
+ inHeatwave = false;
+ }
+ subEvents = 0;
+ }
+ }
+
+ // Drop the trailing pad cell to realign with the input length.
+ return hwIndices.subarray(0, hwIndices.length - 1);
+ }
+
+ function fill(arr, start, end, value) {
+ for (var i = start; i < end; i++) arr[i] = value;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Metrics over the slice (analogous to HWN/HWF/HWD/HWA, whole window)
+ // ---------------------------------------------------------------------------
+ function computeMetrics(hwIndex) {
+ var events = {}; // index -> day count
+ for (var i = 0; i < hwIndex.length; i++) {
+ var v = hwIndex[i];
+ if (v !== 0) events[v] = (events[v] || 0) + 1;
+ }
+ var lengths = Object.keys(events).map(function (key) {
+ return events[key];
+ });
+ var hwn = lengths.length;
+ var hwf = lengths.reduce(function (a, b) {
+ return a + b;
+ }, 0);
+ var hwd = lengths.length ? Math.max.apply(null, lengths) : 0;
+ var hwa = lengths.length ? hwf / lengths.length : 0;
+ return { HWN: hwn, HWF: hwf, HWD: hwd, HWA: hwa };
+ }
+
+ // ---------------------------------------------------------------------------
+ // Deterministic synthetic data: rise-then-fall hump + seeded noise
+ // ---------------------------------------------------------------------------
+ var N_DAYS = 30;
+
+ function mulberry32(seed) {
+ return function () {
+ seed |= 0;
+ seed = (seed + 0x6d2b79f5) | 0;
+ var t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+ }
+
+ function generateTemps(seed) {
+ var rand = mulberry32(seed);
+ var temps = new Float64Array(N_DAYS);
+ var base = 34;
+ // var amplitude = 12; // peak ~40 degC at the middle of the window
+ for (var i = 0; i < N_DAYS; i++) {
+ // Smooth hump peaking near the center of the two-week window.
+ // var hump = Math.sin((i / (N_DAYS - 1)) * Math.PI);
+ var noise = (rand() - 0.5) * 10.0; // +/- ~1.5 degC
+ temps[i] = base + noise;
+ }
+ return temps;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Canvas rendering helpers
+ // ---------------------------------------------------------------------------
+ var COLORS = {
+ notHot: "#9aa5b1",
+ hot: "#f6a623",
+ heatwave: "#d0021b",
+ line: "#2a6592",
+ threshold: "#444",
+ axis: "#888",
+ grid: "#e3e8ee"
+ };
+
+ var PAD = { left: 48, right: 16, top: 16, bottom: 28 };
+
+ function setupCanvas(canvas) {
+ var ratio = window.devicePixelRatio || 1;
+ var cssWidth = canvas.clientWidth;
+ var cssHeight = canvas.clientHeight;
+ canvas.width = Math.round(cssWidth * ratio);
+ canvas.height = Math.round(cssHeight * ratio);
+ var ctx = canvas.getContext("2d");
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
+ ctx.clearRect(0, 0, cssWidth, cssHeight);
+ return { ctx: ctx, w: cssWidth, h: cssHeight };
+ }
+
+ function xForDay(i, w) {
+ var inner = w - PAD.left - PAD.right;
+ return PAD.left + (inner * i) / (N_DAYS - 1);
+ }
+
+ function drawTempPane(canvas, temps, threshold) {
+ var s = setupCanvas(canvas);
+ var ctx = s.ctx;
+ var yMin = 24;
+ var yMax = 44;
+ var inner = s.h - PAD.top - PAD.bottom;
+ function yFor(t) {
+ return PAD.top + inner * (1 - (t - yMin) / (yMax - yMin));
+ }
+
+ // Gridlines + y-axis labels (degC).
+ ctx.strokeStyle = COLORS.grid;
+ ctx.fillStyle = COLORS.axis;
+ ctx.font = "11px sans-serif";
+ ctx.lineWidth = 1;
+ for (var t = yMin; t <= yMax; t += 5) {
+ var y = yFor(t);
+ ctx.beginPath();
+ ctx.moveTo(PAD.left, y);
+ ctx.lineTo(s.w - PAD.right, y);
+ ctx.stroke();
+ ctx.fillText(t + "°C", 8, y + 3);
+ }
+
+ // Threshold line.
+ ctx.strokeStyle = COLORS.threshold;
+ ctx.setLineDash([5, 4]);
+ ctx.beginPath();
+ ctx.moveTo(PAD.left, yFor(threshold));
+ ctx.lineTo(s.w - PAD.right, yFor(threshold));
+ ctx.stroke();
+ ctx.setLineDash([]);
+ ctx.fillStyle = COLORS.threshold;
+ ctx.fillText("threshold " + threshold.toFixed(1) + "°C", PAD.left + 4, yFor(threshold) - 5);
+
+ // Temperature line.
+ ctx.strokeStyle = COLORS.line;
+ ctx.lineWidth = 2;
+ ctx.beginPath();
+ for (var i = 0; i < N_DAYS; i++) {
+ var px = xForDay(i, s.w);
+ var py = yFor(temps[i]);
+ if (i === 0) ctx.moveTo(px, py);
+ else ctx.lineTo(px, py);
+ }
+ ctx.stroke();
+
+ // Point markers colored by hot / not-hot.
+ for (var j = 0; j < N_DAYS; j++) {
+ ctx.fillStyle = temps[j] > threshold ? COLORS.hot : COLORS.notHot;
+ ctx.beginPath();
+ ctx.arc(xForDay(j, s.w), yFor(temps[j]), 4, 0, 2 * Math.PI);
+ ctx.fill();
+ }
+
+ drawDayAxis(ctx, s);
+ }
+
+ function drawStepPane(canvas, steps) {
+ var s = setupCanvas(canvas);
+ var ctx = s.ctx;
+ var inner = s.h - PAD.top - PAD.bottom;
+ var levels = [0, 1, 2];
+ function yFor(level) {
+ return PAD.top + inner * (1 - level / 2);
+ }
+
+ // Gridlines + level labels.
+ ctx.strokeStyle = COLORS.grid;
+ ctx.fillStyle = COLORS.axis;
+ ctx.font = "11px sans-serif";
+ var labels = ["0 NH", "1 H", "2 HW"];
+ for (var l = 0; l < levels.length; l++) {
+ var y = yFor(levels[l]);
+ ctx.beginPath();
+ ctx.moveTo(PAD.left, y);
+ ctx.lineTo(s.w - PAD.right, y);
+ ctx.stroke();
+ ctx.fillText(labels[l], 4, y + 3);
+ }
+
+ // Colored bars per day.
+ var innerW = s.w - PAD.left - PAD.right;
+ var barW = (innerW / N_DAYS) * 0.7;
+ for (var i = 0; i < N_DAYS; i++) {
+ var level = steps[i];
+ var color = level === 2 ? COLORS.heatwave : level === 1 ? COLORS.hot : COLORS.notHot;
+ var cx = xForDay(i, s.w);
+ var top = yFor(level);
+ var bottom = yFor(0);
+ ctx.fillStyle = color;
+ if (level === 0) {
+ // Draw a thin marker at the baseline so "not hot" days stay visible.
+ ctx.fillRect(cx - barW / 2, bottom - 2, barW, 2);
+ } else {
+ ctx.fillRect(cx - barW / 2, top, barW, bottom - top);
+ }
+ }
+
+ drawDayAxis(ctx, s);
+ }
+
+ function drawDayAxis(ctx, s) {
+ ctx.strokeStyle = COLORS.axis;
+ ctx.fillStyle = COLORS.axis;
+ ctx.lineWidth = 1;
+ ctx.font = "11px sans-serif";
+ var y = s.h - PAD.bottom;
+ ctx.beginPath();
+ ctx.moveTo(PAD.left, y);
+ ctx.lineTo(s.w - PAD.right, y);
+ ctx.stroke();
+ for (var i = 0; i < N_DAYS; i++) {
+ var px = xForDay(i, s.w);
+ ctx.fillText(String(i + 1), px - 3, y + 16);
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // Widget wiring
+ // ---------------------------------------------------------------------------
+ function initWidget(root) {
+ var els = {
+ tempCanvas: root.querySelector("#hdp-hw-temp"),
+ stepCanvas: root.querySelector("#hdp-hw-step"),
+ threshold: root.querySelector("#hdp-hw-threshold"),
+ minDuration: root.querySelector("#hdp-hw-min-duration"),
+ maxBreak: root.querySelector("#hdp-hw-max-break"),
+ maxSubs: root.querySelector("#hdp-hw-max-subs"),
+ thresholdVal: root.querySelector("#hdp-hw-threshold-val"),
+ minDurationVal: root.querySelector("#hdp-hw-min-duration-val"),
+ maxBreakVal: root.querySelector("#hdp-hw-max-break-val"),
+ maxSubsVal: root.querySelector("#hdp-hw-max-subs-val"),
+ regenerate: root.querySelector("#hdp-hw-regenerate"),
+ metrics: root.querySelector("#hdp-hw-metrics")
+ };
+
+ var seed = 1234;
+ var temps = generateTemps(seed);
+
+ function render() {
+ var threshold = parseFloat(els.threshold.value);
+ var minDuration = parseInt(els.minDuration.value, 10);
+ var maxBreak = parseInt(els.maxBreak.value, 10);
+ var maxSubs = parseInt(els.maxSubs.value, 10);
+
+ els.thresholdVal.textContent = threshold.toFixed(1) + "°C";
+ els.minDurationVal.textContent = minDuration + " day" + (minDuration === 1 ? "" : "s");
+ els.maxBreakVal.textContent = String(maxBreak);
+ els.maxSubsVal.textContent = String(maxSubs);
+
+ var hotDays = new Int32Array(N_DAYS);
+ for (var i = 0; i < N_DAYS; i++) hotDays[i] = temps[i] > threshold ? 1 : 0;
+
+ var hwIndex = indexHeatwaves(hotDays, minDuration, maxBreak, maxSubs);
+ var steps = new Int32Array(N_DAYS);
+ for (var j = 0; j < N_DAYS; j++) {
+ steps[j] = hotDays[j] + (hwIndex[j] > 0 ? 1 : 0);
+ }
+
+ drawTempPane(els.tempCanvas, temps, threshold);
+ drawStepPane(els.stepCanvas, steps);
+
+ var m = computeMetrics(hwIndex);
+ els.metrics.innerHTML =
+ metricCell("HWN", m.HWN, "events") +
+ metricCell("HWF", m.HWF, "heatwave days") +
+ metricCell("HWD", m.HWD, "longest event, days") +
+ metricCell("HWA", m.HWA.toFixed(1), "mean event, days");
+ }
+
+ function metricCell(name, value, desc) {
+ return (
+ '<div class="hdp-hw-metric"><span class="hdp-hw-metric-name">' +
+ name +
+ '</span><span class="hdp-hw-metric-value">' +
+ value +
+ '</span><span class="hdp-hw-metric-desc">' +
+ desc +
+ "</span></div>"
+ );
+ }
+
+ [els.threshold, els.minDuration, els.maxBreak, els.maxSubs].forEach(function (slider) {
+ slider.addEventListener("input", render);
+ });
+
+ els.regenerate.addEventListener("click", function () {
+ seed = (Math.random() * 1e9) | 0;
+ temps = generateTemps(seed);
+ render();
+ });
+
+ window.addEventListener("resize", render);
+ render();
+ }
+
+ function boot() {
+ var root = document.getElementById("hdp-hw-widget");
+ if (!root) return; // No-op on pages without the widget.
+ initWidget(root);
+ }
+
+ if (document.readyState === "loading") {
+ document.addEventListener("DOMContentLoaded", boot);
+ } else {
+ boot();
+ }
+})();
diff --git a/docs/conf.py b/docs/conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..286eb8ac20003cb2dad8c7cb44bb2020fcd5232d
--- /dev/null
+++ b/docs/conf.py
@@ -0,0 +1,48 @@
+import sys
+import os
+import hdp
+from importlib.metadata import version as _get_version
+
+# Configuration file for the Sphinx documentation builder.
+#
+# For the full list of built-in configuration values, see the documentation:
+# https://www.sphinx-doc.org/en/master/usage/configuration.html
+
+# -- Project information -----------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
+
+project = 'HDP'
+copyright = '2026, Cameron Cummins'
+author = 'Cameron Cummins'
+release = _get_version('hdp_python')
+
+# -- General configuration ---------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
+
+extensions = [
+ 'sphinx.ext.duration',
+ 'sphinx.ext.autodoc',
+ 'sphinx.ext.autosummary',
+ 'sphinx.ext.viewcode',
+ 'sphinx.ext.intersphinx'
+]
+
+intersphinx_mapping = {
+ 'python': ('https://docs.python.org/3', None),
+ 'numpy': ('https://numpy.org/doc/stable', None),
+ 'xarray': ('https://docs.xarray.dev/en/stable', None),
+ 'dask': ('https://docs.dask.org/en/stable', None),
+}
+
+templates_path = ['_templates']
+exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.ipynb_checkpoints']
+
+
+
+# -- Options for HTML output -------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
+
+html_theme = 'sphinx_rtd_theme'
+html_static_path = ['_static']
+html_js_files = ['heatwave_widget.js']
+html_css_files = ['heatwave_widget.css']
diff --git a/docs/example_cmip_workflow/run_cmip_workflow.py b/docs/example_cmip_workflow/run_cmip_workflow.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc1188d344f0cc55a05105425b506f8654572524
--- /dev/null
+++ b/docs/example_cmip_workflow/run_cmip_workflow.py
@@ -0,0 +1,53 @@
+import matplotlib
+matplotlib.use('Agg') # Non-interactive backend
+
+from dask.distributed import Client, LocalCluster
+import hdp.measure
+import hdp.threshold
+import hdp.metric
+from hdp.graphics.notebook import create_notebook
+import xarray as xr
+import numpy as np
+import pandas as pd
+import s3fs
+
+
+if __name__ == "__main__":
+ aws_cmip_index = pd.read_csv("https://cmip6-pds.s3.amazonaws.com/pangeo-cmip6.csv")
+ cesm_index = aws_cmip_index.query("table_id=='day' & source_id=='CESM2'")
+ cesm_index = cesm_index[cesm_index["member_id"] == 'r4i1p1f1']
+
+ ssp370_tas_info = cesm_index.query("experiment_id=='ssp370' & variable_id=='tas'")
+ baseline_tas_info = cesm_index.query("experiment_id=='historical' & variable_id=='tas'")
+
+ cluster = LocalCluster(n_workers=6, memory_limit="16GB", threads_per_worker=2, processes=True)
+ client = Client(cluster)
+
+ fs = s3fs.S3FileSystem(anon=True)
+
+ ssp370_tas = xr.open_zarr(fs.get_mapper(ssp370_tas_info["zstore"].iloc[0]), consolidated=True)["tas"]
+ baseline_tas = xr.open_zarr(fs.get_mapper(baseline_tas_info["zstore"].iloc[0]), consolidated=True)["tas"]
+
+ ssp370_tas = ssp370_tas.chunk(dict(time=-1, lat=24, lon=18))
+ baseline_tas = baseline_tas.chunk(dict(time=-1, lat=24, lon=18)).sel(time=slice("1961-01-01", "1990-12-31"))
+
+ baseline_measures = hdp.measure.format_standard_measures(temp_datasets=[baseline_tas])
+ ssp370_measures = hdp.measure.format_standard_measures(temp_datasets=[ssp370_tas])
+
+ percentiles = np.arange(0.9, 1.0, 0.01)
+ thresholds = hdp.threshold.compute_thresholds(
+ baseline_measures,
+ percentiles
+ )
+
+ definitions = [[3,1,0], [3,1,1], [4,0,0], [4,1,1], [5,0,0], [5,1,1]]
+ metrics_dataset = hdp.metric.compute_group_metrics(ssp370_measures, thresholds, definitions)
+
+ metrics_dataset.to_zarr("cesm2_ssp370_hw_metrics.zarr", mode='w', compute=True, zarr_format=2)
+
+ metrics_dataset_disk = xr.open_zarr("cesm2_ssp370_hw_metrics.zarr")
+
+ figure_notebook = create_notebook(metrics_dataset_disk)
+ figure_notebook.save_notebook("cesm2_ssp370_hw_metrics.ipynb")
+
+ client.shutdown()
\ No newline at end of file
diff --git a/docs/sample_data/sample.py b/docs/sample_data/sample.py
new file mode 100644
index 0000000000000000000000000000000000000000..975504e5b0cac5c02b5e4b52e10390828af3825f
--- /dev/null
+++ b/docs/sample_data/sample.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+"""
+hdp.py
+
+Heatwave Diagnostics Package (HDP)
+
+Entry point for package.
+
+Developer: Cameron Cummins
+Contact: cameron.cummins@utexas.edu
+"""
+import matplotlib
+matplotlib.use('Agg') # Non-interactive backend
+
+from hdp.graphics.notebook import create_notebook
+from os.path import isdir
+import hdp.measure
+import hdp.threshold
+import hdp.metric
+import numpy as np
+import sys
+
+
+def generate_sample_data(output_dir):
+ if not isdir(output_dir):
+ raise RuntimeError(f"Output directory '{output_dir}' does not exist!")
+
+ sample_control_temp = hdp.utils.generate_test_control_dataarray(add_noise=True)
+ sample_warming_temp = hdp.utils.generate_test_warming_dataarray(add_noise=True)
+
+ baseline_measures = hdp.measure.format_standard_measures(
+ temp_datasets=[sample_control_temp]
+ )
+ test_measures = hdp.measure.format_standard_measures(
+ temp_datasets=[sample_warming_temp]
+ )
+
+ percentiles = np.arange(0.9, 1.0, 0.01)
+
+ thresholds_dataset = hdp.threshold.compute_thresholds(
+ baseline_measures,
+ percentiles
+ )
+
+ definitions = [[3,0,0], [3,1,1], [4,0,0], [4,1,1], [5,0,0], [5,1,1]]
+
+ metrics_dataset = hdp.metric.compute_group_metrics(test_measures, thresholds_dataset, definitions, include_threshold=True)
+ metrics_dataset.to_netcdf(f"{output_dir}/sample_hw_metrics.nc", mode='w')
+
+ figure_notebook = create_notebook(metrics_dataset)
+ figure_notebook.save_notebook(f"{output_dir}/sample_hw_summary_figures.ipynb")
+
+ sample_control_temp = sample_control_temp.to_dataset()
+ sample_control_temp.attrs["description"] = "Mock control temperature dataset generated by HDP for unit testing."
+ sample_control_temp.to_netcdf(f"{output_dir}/sample_control_temp.nc", mode='w')
+
+ sample_warming_temp = sample_warming_temp.to_dataset()
+ sample_warming_temp.attrs["description"] = "Mock temperature dataset with warming trend generated by HDP for unit testing."
+ sample_warming_temp.to_netcdf(f"{output_dir}/sample_warming_temp.nc", mode='w')
+
+if __name__ == "__main__":
+ print("Generating testing data and simulating a full data-to-figure workflow: ")
+ if len(sys.argv) != 2:
+ assert Exception("Please specifiy the path to output sample data and results to.")
+ generate_sample_data(sys.argv[1])
+ print("Done!")
\ No newline at end of file
diff --git a/hdp/__init__.py b/hdp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/hdp/definitions.py b/hdp/definitions.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4fa994d11176495bd0bcc4f823fec4daf3bebf9
--- /dev/null
+++ b/hdp/definitions.py
@@ -0,0 +1,4 @@
+import os
+
+PATH_ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
+PATH_MPL_STYLESHEET = f"{PATH_ROOT_DIR}/graphics/hdp.mplstyle"
\ No newline at end of file
diff --git a/hdp/graphics/__init__.py b/hdp/graphics/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/hdp/graphics/figure.py b/hdp/graphics/figure.py
new file mode 100644
index 0000000000000000000000000000000000000000..042933e459ba14dc28b7b10b2f1000778eaa42d7
--- /dev/null
+++ b/hdp/graphics/figure.py
@@ -0,0 +1,373 @@
+from matplotlib import pyplot as plt
+from matplotlib.figure import Figure
+from matplotlib.cm import ScalarMappable
+from matplotlib.colors import Normalize
+from matplotlib import cm
+from cartopy.util import add_cyclic_point
+from hdp.definitions import PATH_MPL_STYLESHEET
+from hdp.graphics.winkel_tripel import WinkelTripel
+import cartopy.crs as ccrs
+import numpy as np
+import cftime
+
+
+def compute_weighted_spatial_mean(da):
+ return da.weighted(np.cos(np.deg2rad(da.lat))).mean(dim=["lat", "lon"])
+
+
+def get_decadal_ranges(times):
+ years = [t.year for t in times]
+
+ start_year = int(np.floor(years[0] / 10)*10)
+ end_year = int(np.ceil(years[-1] / 10)*10)
+
+ decadal_ranges = []
+ for period_start_year in np.arange(start_year, end_year, 10):
+ decadal_ranges.append((int(period_start_year), int(period_start_year) + 9))
+ return decadal_ranges
+
+
+def generate_base_figure():
+ plt.style.use(PATH_MPL_STYLESHEET)
+ f = plt.figure()
+ f.suptitle("Figure Title")
+ return f
+
+
+def convert_axis_to_map(ax):
+ ax.xaxis.set_visible(False)
+ ax.yaxis.set_visible(False)
+ ax.spines['top'].set_visible(False)
+ ax.spines['right'].set_visible(False)
+ ax.spines['left'].set_visible(False)
+ ax.spines['bottom'].set_visible(False)
+ ax.grid(False)
+ return ax.figure.add_axes(ax.get_position(), frameon=True, projection=WinkelTripel(), zorder=-1)
+
+
+def add_four_panel(figure):
+ gridspec = figure.add_gridspec(2, 2)
+ ax1 = figure.add_subplot(gridspec[0, 0])
+ ax2 = figure.add_subplot(gridspec[0, 1])
+ ax3 = figure.add_subplot(gridspec[1, 0])
+ ax4 = figure.add_subplot(gridspec[1, 1])
+
+ axes = [ax1, ax2, ax3, ax4]
+
+ for index, ax in enumerate(axes):
+ ax.set_title(f"Axis {index} Title")
+ ax.set_xlabel("X Label (Units)")
+ ax.set_ylabel("Y Label (Units)")
+
+ return axes
+
+
+def get_color_for_value(cbar, value):
+ """
+ Get the color for a specific value from a colorbar.
+ """
+ cmap = cbar.mappable.get_cmap()
+ norm = cbar.mappable.norm
+ return cmap(norm(value))
+
+
+def get_metric_axis_label(metric_name):
+ if metric_name == "HWF":
+ return "Days"
+ elif metric_name == "HWD":
+ return "Days"
+ elif metric_name == "HWN":
+ return "Heatwaves"
+ elif metric_name == "HWA":
+ return "Days"
+ else:
+ return None
+
+
+def add_percentile_colorbar(ax, percentiles):
+ cmap = plt.get_cmap('Reds', len(percentiles))
+ norm = Normalize(vmin=-1, vmax=len(percentiles) - 1)
+ sm = ScalarMappable(cmap=cmap, norm=norm)
+ sm.set_array([])
+
+ cbar = plt.colorbar(sm, ax=ax, ticks=np.arange(len(percentiles)), pad=0.02)
+ cbar.set_label('Percentile', rotation=270, labelpad=8)
+ cbar.set_ticklabels(np.round(percentiles, 3))
+ return cbar
+
+
+def add_definitions_colorbar(ax, definitions):
+ cmap = plt.get_cmap('tab20', len(definitions))
+ norm = Normalize(vmin=0, vmax=len(definitions) - 1)
+ sm = ScalarMappable(cmap=cmap, norm=norm)
+ sm.set_array([])
+
+ cbar = plt.colorbar(sm, ax=ax, ticks=np.arange(len(definitions)), pad=0.02)
+ cbar.set_label('Definition', rotation=270, labelpad=8)
+ cbar.set_ticklabels(definitions)
+ return cbar
+
+
+def add_percentile_colorbar(ax, percentiles):
+ cmap = plt.get_cmap('autumn', len(percentiles))
+ norm = Normalize(vmin=0, vmax=len(percentiles))
+ sm = ScalarMappable(cmap=cmap, norm=norm)
+ sm.set_array([])
+
+ cbar = plt.colorbar(sm, ax=ax, ticks=np.arange(len(percentiles)) + 0.5, pad=0.02)
+ cbar.set_label('Percentile', rotation=270, labelpad=8)
+ cbar.set_ticklabels(np.round(percentiles, 3))
+ return cbar
+
+
+def get_metric_name(metric_da):
+ if len(metric_da.name.split(".")) >= 3:
+ return metric_da.name.split(".")[2]
+ raise ValueError(
+ f"Expected variable name '{metric_da.name}' to follow the "
+ "'{measure}.{threshold}.{metric}' naming convention."
+ )
+
+
+def get_unique_metric_names(hw_ds):
+ unique_metrics = []
+
+ for name in list(hw_ds.data_vars):
+ parsed = name.split(".")
+ if len(parsed) >= 3:
+ if parsed[2] not in unique_metrics:
+ unique_metrics.append(parsed[2])
+ return unique_metrics
+
+
+def plot_map(metric_da, ax, cmap="hot"):
+ cmap_obj = plt.get_cmap(cmap)
+ metric_da = metric_da.transpose(..., "lon")
+
+ cyclic_values, cyclic_lons = add_cyclic_point(metric_da.values, metric_da.lon.values, axis=-1)
+ ax_contour = ax.contourf(cyclic_lons, metric_da.lat.values, cyclic_values, transform=ccrs.PlateCarree(), cmap=cmap_obj)
+ ax.coastlines()
+ return ax_contour
+
+
+def plot_metric_decadal_maps(metric_da):
+ """
+ Multi-figure (4 panels per figure) plotting of decadal means for a particular metric.
+ If an ensemble, set of percentiles, or set of definitions is supplied, the average will be used.
+ Abbreviations include ensemble (ens), percentile (perc), and definition (def).
+
+ :param metric_da: DataArray of the metric (with the metric name) to plot.
+ :type metric_da: xarray.DataArray
+ :return: Matplotlib Figure of the plot with the figure title containing a list of metrics displayed.
+ :rtype: np.ndarray
+ """
+ metric_name = get_metric_name(metric_da)
+
+ prefix = ""
+ if "member" in metric_da.dims:
+ metric_da = metric_da.mean(dim="member")
+ prefix += " Ens."
+ if "percentile" in metric_da.dims:
+ metric_da = metric_da.mean(dim="percentile")
+ prefix += " Perc."
+ if "definition" in metric_da.dims:
+ metric_da = metric_da.mean(dim="definition")
+ prefix += " Def."
+
+ decadal_ranges = get_decadal_ranges(metric_da.time.values)
+ calendar = metric_da.time.values[0].calendar
+ num_figs = int(np.ceil(len(decadal_ranges) / 4))
+
+ figs = []
+
+ for f_index in range(num_figs):
+ fig = generate_base_figure()
+ fig.suptitle(metric_name)
+ axes = add_four_panel(fig)
+
+ for ax_index, ax in enumerate(axes):
+ ax.set_title(None)
+ slice_index = ax_index + f_index * len(axes)
+ if slice_index < len(decadal_ranges):
+ start_year, end_year = decadal_ranges[slice_index]
+ start_ts = cftime.datetime(start_year, 1, 1, calendar=calendar)
+ end_ts = cftime.datetime(end_year, 1, 1, calendar=calendar)
+ slice_da = metric_da.sel(time=slice(start_ts, end_ts))
+
+ if start_year != slice_da.time.values[0].year:
+ start_year = slice_da.time.values[0].year
+ if end_year != slice_da.time.values[-1].year:
+ end_year = slice_da.time.values[-1].year
+ slice_da = slice_da.mean(dim=["time"])
+
+ ax = convert_axis_to_map(ax)
+ ax_contour = plot_map(slice_da, ax)
+ ax_cbar = fig.colorbar(ax_contour, location="bottom", anchor=(0.0, 0.0), pad=0)
+ ax_cbar.set_label(f"{metric_name} ({get_metric_axis_label(metric_name)})")
+ ax.set_title(f"{start_year} to {end_year}{prefix} Mean")
+ else:
+ ax.set_axis_off()
+ plt.close(fig)
+ figs.append(fig)
+ return figs
+
+
+def plot_metric_timeseries(metric_da):
+ """
+ 4-panel plot of time-evolution of metric, spatial-ensemble mean.
+ The top two panels are means taken across thresholds and definitions while the bottom two panels show standard deviations.
+ Abbreviations include ensemble (ens), percentile (perc), definition (def), and standard deviation (std).
+
+ :param metric_da: DataArray of the metric (with the metric name) to plot.
+ :type metric_da: xarray.DataArray
+ :return: Matplotlib Figure of the plot with the figure title containing a list of metrics displayed.
+ :rtype: np.ndarray
+ """
+ fig = generate_base_figure()
+ axes = add_four_panel(fig)
+
+ spatial_mean = compute_weighted_spatial_mean(metric_da).compute()
+ metric_name = spatial_mean.name.split(".")[2]
+ years = [ts.year for ts in spatial_mean.time.values]
+
+ if "member" in spatial_mean.dims:
+ spatial_mean = spatial_mean.mean(dim="member")
+ axes[0].set_title(f"{metric_name}, Spatial-Ens-Perc. Mean")
+ axes[1].set_title(f"{metric_name}, Spatial-Ens-Def. Mean")
+ axes[2].set_title(f"{metric_name}, Spatial-Ens-Perc. Std.")
+ axes[3].set_title(f"{metric_name}, Spatial-Ens-Def. Std.")
+ else:
+ axes[0].set_title(f"{metric_name}, Spatial-Perc. Mean")
+ axes[1].set_title(f"{metric_name}, Spatial-Def. Mean")
+ axes[2].set_title(f"{metric_name}, Spatial-Perc. Std.")
+ axes[3].set_title(f"{metric_name}, Spatial-Def. Std.")
+
+ def_cbar = add_definitions_colorbar(axes[0], spatial_mean.definition.values)
+ def_cbar = add_definitions_colorbar(axes[2], spatial_mean.definition.values)
+
+ perc_cbar = add_percentile_colorbar(axes[1], spatial_mean.percentile.values)
+ perc_cbar = add_percentile_colorbar(axes[3], spatial_mean.percentile.values)
+
+ for index, definition in enumerate(spatial_mean.definition.values):
+ color = get_color_for_value(def_cbar, index)
+ axes[0].plot(years, spatial_mean.sel(definition=definition).mean(dim="percentile").values, color=color)
+ axes[2].plot(years, spatial_mean.sel(definition=definition).std(dim="percentile").values, color=color)
+
+ for index, percentile in enumerate(spatial_mean.percentile.values):
+ color = get_color_for_value(perc_cbar, index)
+ axes[1].plot(years, spatial_mean.sel(percentile=percentile).mean(dim="definition").values, color=color)
+ axes[3].plot(years, spatial_mean.sel(percentile=percentile).std(dim="definition").values, color=color)
+
+ for ax in axes:
+ ax.set_xlabel("Time (Year)")
+ ax.set_ylabel(f"{metric_name} ({get_metric_axis_label(metric_name)})", labelpad=0.005)
+ ax.set_xlim(years[0], years[-1])
+
+ fig.suptitle(spatial_mean.name)
+ plt.close(fig)
+ return fig
+
+
+def plot_metric_parameter_comparison(metric_da):
+ """
+ 4-panel plot of metric visualizing various comparisons of percentiles against the definitions.
+ If ensemble is supplied, the average is taken.
+
+ :param metric_da: DataArray of the metric (with the metric name) to plot.
+ :type metric_da: xarray.DataArray
+ :return: Matplotlib Figure of the plot with the figure title containing a list of metrics displayed.
+ :rtype: np.ndarray
+ """
+ fig = generate_base_figure()
+ axes = add_four_panel(fig)
+
+ metric_name = get_metric_name(metric_da)
+ fig.suptitle(metric_name)
+
+ if "member" in metric_da.dims:
+ metric_da = metric_da.mean(dim="member")
+
+ spatio_temporal_mean = compute_weighted_spatial_mean(metric_da).mean(dim="time")
+
+ colormesh = axes[0].pcolormesh(spatio_temporal_mean.values, cmap="hot")
+ axes[0].set_xticks(np.arange(spatio_temporal_mean.definition.size) + 0.5)
+ axes[0].set_yticks(np.arange(spatio_temporal_mean.percentile.size) + 0.5)
+ axes[0].set_xticklabels(spatio_temporal_mean.definition.values)
+ axes[0].set_yticklabels(np.round(spatio_temporal_mean.percentile.values, 3))
+ axes[0].set_xlabel("Definition")
+ axes[0].set_ylabel("Percentile")
+ cbar = fig.colorbar(colormesh, ax=axes[0], pad=0.02)
+ cbar.set_label(get_metric_axis_label(metric_name), rotation=270, labelpad=12)
+ axes[0].set_title(f"{metric_name} Spatial-Temporal Mean")
+
+ lon_def_temporal_mean = metric_da.mean(dim=["time", "lon", "definition"])
+ perc_cbar = add_percentile_colorbar(axes[1], lon_def_temporal_mean.percentile.values)
+
+ for index, percentile in enumerate(lon_def_temporal_mean.percentile.values):
+ color = get_color_for_value(perc_cbar, index)
+ axes[1].plot(lon_def_temporal_mean.lat.values, lon_def_temporal_mean.sel(percentile=percentile).values, color=color)
+ axes[1].set_xticks(np.arange(-90, 100, 30))
+ axes[1].set_xlim(-90, 90)
+ axes[1].set_ylabel(get_metric_axis_label(metric_name))
+ axes[1].set_xlabel("Latitude")
+ axes[1].set_title(f"{metric_name} Zonal-Temporal-Def. Means")
+
+ param_mean = metric_da.mean(dim=["time", "percentile", "definition"])
+ axes[2].set_title(None)
+ axes[2] = convert_axis_to_map(axes[2])
+ ax_contour = plot_map(param_mean, axes[2])
+ ax_cbar = fig.colorbar(ax_contour, location="bottom", anchor=(0.0, 0.0), pad=0)
+ ax_cbar.set_label(f"{metric_name} ({get_metric_axis_label(metric_name)})")
+ axes[2].set_title(f"{metric_name} Temporal-Def.-Perc. Mean")
+
+ param_std = metric_da.mean(dim=["time"]).std(dim=["percentile", "definition"])
+ axes[3].set_title(None)
+ axes[3] = convert_axis_to_map(axes[3])
+ ax_contour = plot_map(param_std, axes[3])
+ ax_cbar = fig.colorbar(ax_contour, location="bottom", anchor=(0.0, 0.0), pad=0)
+ ax_cbar.set_label(f"{metric_name} ({get_metric_axis_label(metric_name)})")
+ axes[3].set_title(f"{metric_name} Def.-Perc. Std. of Temporal Mean")
+
+ plt.close(fig)
+ return fig
+
+
+def plot_multi_measure_metric_comparisons(hw_ds):
+ """
+ 4-panel plot of time-evolution of heatwave metrics accross multiple measures.
+ Spatially-weighted by latitide, mean taken spatially and over both percentiles and all definitions.
+ If ensemble is used, the range of member values is shaded behind the mean line.
+ Abbreviations include percentile (perc) and definition (def).
+
+ :param metric_da: Dataset of the metrics (with the metric names) to plot.
+ :type metric_da: xarray.Dataset
+ :return: Matplotlib Figure of the plot with the figure title containing a list of metrics displayed.
+ :rtype: np.ndarray
+ """
+ fig = generate_base_figure()
+ axes = add_four_panel(fig)
+ years = [ts.year for ts in hw_ds.time.values]
+ metric_names = get_unique_metric_names(hw_ds)[:4]
+ fig.suptitle(metric_names)
+
+ for index, metric_name in enumerate(metric_names):
+ metrics = [name for name in hw_ds.data_vars if metric_name in name]
+ metrics_ds = compute_weighted_spatial_mean(hw_ds[metrics]).mean(dim=["percentile", "definition"]).compute()
+
+ axes[index].spines['top'].set_visible(False)
+ axes[index].spines['right'].set_visible(False)
+ axes[index].grid(True)
+
+ axes[index].set_xlabel("Time (Year)")
+ axes[index].set_ylabel(f"{metric_name} ({get_metric_axis_label(metric_name)})", labelpad=2)
+ axes[index].set_xlim(years[0], years[-1])
+ axes[index].set_title(f"{metric_name} Spatial-Perc-Def Mean")
+
+ for metric in metrics_ds:
+ axes[index].plot(years, metrics_ds[metric].values, label=metric.split(".")[0])
+
+ axes[index].legend()
+
+ plt.close(fig)
+ return fig
+
diff --git a/hdp/graphics/notebook.py b/hdp/graphics/notebook.py
new file mode 100644
index 0000000000000000000000000000000000000000..35b1bb999084b851743e104f3861fa64ba8e98cb
--- /dev/null
+++ b/hdp/graphics/notebook.py
@@ -0,0 +1,146 @@
+import matplotlib.pyplot as plt
+import base64
+import nbformat
+from io import BytesIO
+from datetime import datetime
+from hdp.utils import get_func_description
+from hdp.graphics.figure import *
+from tqdm.auto import tqdm
+
+
+class HDPNotebook():
+ def create_section(self, section_name, label=None, rank=1, label_hidden=False):
+ if label_hidden:
+ label = None
+ elif label is None:
+ label = section_name
+
+ self.__sections[section_name] = {
+ "cells": [],
+ "rank": rank,
+ "label": label
+ }
+
+
+ def __init__(self):
+ self.__sections = {}
+ self.__num_figs = 0
+
+
+ def add_markdown_cell(self, cell_data, section_name):
+ if section_name not in self.__sections:
+ self.create_section(section_name)
+ self.__sections[section_name]["cells"].append(nbformat.v4.new_markdown_cell(cell_data))
+
+
+ def add_figure_cell(self, figure, section_name=None, alt_text="Figure"):
+ img_buffer = BytesIO()
+ figure.savefig(img_buffer, format='png')
+ img_buffer.seek(0)
+
+ img_base64 = base64.b64encode(img_buffer.getvalue()).decode('utf-8')
+ cell_data = f''
+ img_buffer.close()
+
+ self.add_markdown_cell(cell_data=cell_data, section_name=section_name)
+ self.__num_figs += 1
+
+
+ def set_section_label(section_name, section_label):
+ self.__sections[section_name]["label"] = section_label
+
+
+ def _format_section_label(self, label):
+ return f"## {label}"
+
+
+ def save_notebook(self, path, title=None):
+ from hdp.utils import get_version, get_time_stamp
+ header_data = [
+ '# Heatwave Diagnostics Package (HDP) Standard Figure Deck\n',
+ '' if title is None else f'## Deck Title: {title}\n',
+ '\n',
+ '```\n',
+ 'Webpage: https://github.com/AgentOxygen/HDP\n',
+ f'Version: HDP {get_version()}\n',
+ f'Generation Timestamp: {get_time_stamp()}\n',
+ f'Figures Generated: {self.__num_figs}\n',
+ '```\n'
+ ]
+
+ self.create_section("header", rank=0, label_hidden=True)
+ self.add_markdown_cell(header_data, "header")
+
+ notebook_node = nbformat.v4.new_notebook()
+ ranked_cells = {}
+ for section_name in self.__sections:
+ rank = self.__sections[section_name]["rank"]
+ if rank in ranked_cells:
+ ranked_cells[rank].append(section_name)
+ else:
+ ranked_cells[rank] = [section_name]
+
+ ranks = list(ranked_cells.keys())
+ ranks.sort()
+
+ for rank in ranks:
+ for section_name in ranked_cells[rank]:
+ label = self.__sections[section_name]["label"]
+ if label is not None:
+ label_cell = nbformat.v4.new_markdown_cell(self._format_section_label(label), metadata={"jp-MarkdownHeadingCollapsed": True})
+
+ notebook_node.cells.append(label_cell)
+
+ for cell in self.__sections[section_name]["cells"]:
+ notebook_node.cells.append(cell)
+
+ with open(path, 'w') as nb_file:
+ nbformat.write(notebook_node, nb_file)
+
+
+def create_notebook(hw_ds):
+ assert "hdp_type" in hw_ds.attrs, "Missing 'hdp_type' attribute."
+
+ notebook = HDPNotebook()
+
+ if hw_ds.attrs["hdp_type"] == "measure":
+ pass
+ elif hw_ds.attrs["hdp_type"] == "threshold":
+ pass
+ elif hw_ds.attrs["hdp_type"] == "metric":
+ index = 1
+
+ section_name = f"Figures {index}"
+ notebook.create_section(section_name)
+ desc = get_func_description(plot_multi_measure_metric_comparisons)
+ notebook.add_markdown_cell(f"### Figure {index}.2 \n{desc}", section_name)
+ notebook.add_figure_cell(plot_multi_measure_metric_comparisons(hw_ds), section_name, alt_text=f"{section_name}")
+
+ index += 1
+ # This is fragile and should be improved to use metadata
+ metric_names = [name for name in list(hw_ds.data_vars) if len(name.split(".")) >= 3]
+ for metric in tqdm(metric_names, desc="Generating figures:"):
+ section_name = f"Figures {index}-{metric}"
+
+ notebook.create_section(section_name)
+ notebook.add_markdown_cell("Description of these figures.", section_name)
+
+ desc = get_func_description(plot_metric_parameter_comparison)
+ notebook.add_markdown_cell(f"### Figure {index}.1 \n{desc}", section_name)
+ notebook.add_figure_cell(plot_metric_parameter_comparison(hw_ds[metric]), section_name, alt_text=f"{section_name}")
+
+ desc = get_func_description(plot_metric_timeseries)
+ notebook.add_markdown_cell(f"### Figure {index}.2 \n{desc}", section_name)
+ notebook.add_figure_cell(plot_metric_timeseries(hw_ds[metric]), section_name, alt_text=f"{section_name}")
+
+ iindex = 3
+ for fig in plot_metric_decadal_maps(hw_ds[metric]):
+ desc = get_func_description(plot_metric_decadal_maps)
+ notebook.add_markdown_cell(f"### Figure {index}.{iindex} \n{desc}", section_name)
+ notebook.add_figure_cell(fig, section_name, alt_text=f"{section_name}")
+ iindex += 1
+ index += 1
+ else:
+ raise ValueError(f"Unexpected value for 'hdp_type' attribute, '{hw_ds.attrs["hdp_type"]}' is not 'measure', 'threshold', or 'metric'.")
+
+ return notebook
\ No newline at end of file
diff --git a/hdp/graphics/winkel_tripel.py b/hdp/graphics/winkel_tripel.py
new file mode 100644
index 0000000000000000000000000000000000000000..395f83d8aa1b536d36939a51e837dcf4ce1f27a7
--- /dev/null
+++ b/hdp/graphics/winkel_tripel.py
@@ -0,0 +1,19 @@
+import cartopy.crs as ccrs
+
+
+class WinkelTripel(ccrs._WarpedRectangularProjection):
+ """
+ Winkel-Tripel projection implementation for Cartopy
+ """
+
+ def __init__(self, central_longitude=0.0, central_latitude=0.0, globe=None):
+ globe = globe or ccrs.Globe(semimajor_axis=ccrs.WGS84_SEMIMAJOR_AXIS)
+ proj4_params = [('proj', 'wintri'),
+ ('lon_0', central_longitude),
+ ('lat_0', central_latitude)]
+
+ super(WinkelTripel, self).__init__(proj4_params, central_longitude, globe=globe)
+
+ @property
+ def threshold(self):
+ return 1e4
\ No newline at end of file
diff --git a/hdp/measure.py b/hdp/measure.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a4cf56ba25c3860ff219fb001d0e98efd9c2e4b
--- /dev/null
+++ b/hdp/measure.py
@@ -0,0 +1,203 @@
+import numpy as np
+import numba as nb
+import xarray
+from hdp.utils import add_history, get_version
+
+TEMPERATURE_UNITS = ['degC', 'degK', 'degF', 'C', 'K', 'F']
+HUMIDITY_UNITS = ["%", "g/g"]
+
+
+def kelvin_to_celsius(temp: xarray.DataArray) -> xarray.DataArray:
+ """
+ Converts from temperature value from Kelvin to Celsius.
+
+ :param temp: Temperature DataArray in degrees Kelvin
+ :type temp: xarray.DataArray
+ :return: Temperature DataArray in degrees Celsius
+ :rtype: xarray.DataArray
+ """
+ attrs = temp.attrs
+ temp -= 273.15
+ attrs["units"] = "degC"
+ temp.attrs = attrs
+ temp = add_history(temp, "HDP converted units from Kelvin to Celsius.")
+ return temp
+
+
+def fahrenheit_to_celsius(temp: xarray.DataArray) -> xarray.DataArray:
+ """
+ Converts from temperature value from Fahrenheit to Celsius.
+
+ :param temp: Temperature DataArray in degrees Fahrenheit
+ :type temp: xarray.DataArray
+ :return: Temperature DataArray in degrees Celsius
+ :rtype: xarray.DataArray
+ """
+ attrs = temp.attrs
+ temp = (temp - 32) / 1.8
+ attrs["units"] = "degC"
+ temp.attrs = attrs
+ temp = add_history(temp, "HDP converted units from Fahrenheit to Celsius.")
+ return temp
+
+
+def celsius_to_fahrenheit(temp: xarray.DataArray) -> xarray.DataArray:
+ """
+ Converts from temperature value from Celsius to Fahrenheit.
+
+ :param temp: Temperature DataArray in degrees Celsius
+ :type temp: xarray.DataArray
+ :return: Temperature DataArray in degrees Fahrenheit
+ :rtype: xarray.DataArray
+ """
+ attrs = temp.attrs
+ temp = (temp * 1.8) + 32
+ attrs["units"] = "degF"
+ temp.attrs = attrs
+ temp = add_history(temp, "HDP converted units from Celsius to Fahrenheit.")
+ return temp
+
+
+@nb.vectorize([nb.float32(nb.float32, nb.float32)])
+def heat_index(temp: float, rel_humid: float) -> float:
+ """
+ Calculates heat index from temperature and relative humidity.
+
+ This function relies on a regression of the National Weather Service heat index.
+ It has an error of +/- 1.3 degrees Fahrenheit.
+ https://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml
+
+ :param temp: Temperature value in degrees Fahrenheit
+ :type temp: float
+ :param rel_humid: Relative humidity on scale from 0 (no moisture) to 100 (fully saturated).
+ :type rel_humid: float
+ :return: Heat index value in degrees Fahrenheit
+ :rtype: float
+ """
+ hi = 0.5 * (temp + 61.0 + ((temp - 68.0)*1.2) + (rel_humid*0.094))
+ if hi > 80:
+ hi = -42.379
+ hi += 2.04901523*temp
+ hi += 10.14333127*rel_humid
+ hi += -0.22475541*temp*rel_humid
+ hi += -0.00683783*(temp**2)
+ hi += -0.05481717*(rel_humid**2)
+ hi += 0.00122874*(temp**2)*rel_humid
+ hi += 0.00085282*temp*(rel_humid**2)
+ hi += -0.00000199*((rel_humid*temp)**2)
+
+ if rel_humid < 13 and 80 <= temp <= 112:
+ hi -= ((13 - rel_humid)/4)*np.sqrt((np.abs(17 - np.abs(temp - 95))/17))
+ elif rel_humid > 85 and 80 <= temp <= 87:
+ hi += ((rel_humid - 85)/10) * ((87 - temp)/5)
+
+ return hi
+
+
+def heat_index_map_wrapper(ds):
+ hi_da = xarray.apply_ufunc(heat_index,
+ ds["temp"].astype(np.float32),
+ ds["rh"].astype(np.float32),
+ dask="parallelized",
+ input_core_dims=[[], []],
+ output_core_dims=[[]],
+ output_dtypes=[np.float32],
+ dask_gufunc_kwargs={
+ 'allow_rechunk': False
+ })
+ return hi_da
+
+
+def apply_heat_index(temp: xarray.DataArray, rh: xarray.DataArray) -> xarray.DataArray:
+ """
+ Calculates heat index from temperature and relative humidity DataArrays leveraging Dask.
+
+ :param temp: Temperature DataArray in degrees Fahrenheit
+ :type temp: xarray.DataArray
+ :param rh: Relative humidity DataArray in percentage [0-100]
+ :type rh: xarray.DataArray
+ :return: Heat index value in degrees Fahrenheit
+ :rtype: xarray.DataArray
+ """
+ assert temp.attrs["units"] == "degF"
+ assert rh.attrs["units"] == "%"
+ hi_da = heat_index_map_wrapper(
+ xarray.Dataset({
+ "temp": temp,
+ "rh": rh
+ }),
+ )
+ hi_da = hi_da.rename(f"{temp.name}_hi")
+ hi_da.attrs["baseline_variable"] = hi_da.name
+ hi_da = add_history(hi_da, f"Converted to heat index using '{rh.name}' relative humidity, renamed from '{temp.name}' to '{hi_da.name}'.")
+ return hi_da
+
+
+def convert_temp_units(temp_ds: xarray.DataArray) -> xarray.DataArray:
+ """
+ Determines and converts temperature units to degrees Celsius.
+
+ :param temp_ds: Temperature DataArray with one of the supported units
+ :type temp_ds: xarray.DataArray
+ :return: Temperature DataArray in degrees Celsius
+ :rtype: xarray.DataArray
+ """
+ if temp_ds.attrs["units"] == "K" or temp_ds.attrs["units"] == "degK":
+ temp_ds = kelvin_to_celsius(temp_ds)
+ elif temp_ds.attrs["units"] == "F" or temp_ds.attrs["units"] == "degF":
+ temp_ds = fahrenheit_to_celsius(temp_ds)
+ return temp_ds
+
+
+def format_standard_measures(temp_datasets: list[xarray.DataArray], rh: xarray.DataArray = None) -> xarray.Dataset:
+ """
+ Formats heat measure datasets (base inputs for heatwave diagnostics) for use within the HDP.
+
+ :param temp_datasets: List of input temperature DataArrays using supported units
+ :type temp_datasets: list[xarray.DataArray]
+ :param rh: (Optional) Relative humidity DataArray to compute heat index values with for each temperature DataArray.
+ :type rh: xarray.DataArray
+ :return: Dataset containing all input variables formatted and initialized for HDP analysis.
+ :rtype: xarray.Dataset
+ """
+ measures = []
+
+ for temp_ds in temp_datasets:
+ temp_ds = temp_ds.copy(deep=True).astype(np.float32)
+ assert "units" in temp_ds.attrs, f"Attribute 'units' not found in '{temp_ds.name}' dataset."
+ assert temp_ds.attrs["units"] in TEMPERATURE_UNITS, f"Units for '{temp_ds.name}' must be one of the following: {TEMPERATURE_UNITS}"
+ temp_ds.attrs |= {
+ "hdp_type": "measure",
+ "input_variable": temp_ds.name,
+ "baseline_variable": temp_ds.name
+ }
+
+ temp_ds = convert_temp_units(temp_ds)
+ measures.append(temp_ds)
+
+ if rh is not None:
+ rh = rh.copy(deep=True).astype(np.float32)
+ assert "units" in rh.attrs, "Attribute 'units' not found in rh dataset."
+ assert rh.attrs["units"] in HUMIDITY_UNITS, f"Units for rh must be one of the following: {HUMIDITY_UNITS}"
+
+ if rh.attrs["units"] == "g/g":
+ rh *= 100
+ rh.attrs["units"] = "%"
+
+ heat_index_datasets = []
+ for measure in measures:
+ ftemp_ds = celsius_to_fahrenheit(measure.copy(deep=True))
+ heat_index = apply_heat_index(ftemp_ds, rh)
+ heat_index_datasets.append(fahrenheit_to_celsius(heat_index))
+
+ for hi_ds in heat_index_datasets:
+ measures.append(hi_ds)
+
+ agg_ds = xarray.merge(measures, join="outer")
+ agg_ds.attrs = {
+ "description": f"Heat measurement dataset generated by Heatwave Diagnostics Package (HDP v{get_version()})",
+ "hdp_version": get_version(),
+ }
+ agg_ds = add_history(agg_ds, f"Dataset aggregated by HDP with measures: {[ds.name for ds in measures]}")
+
+ return agg_ds
\ No newline at end of file
diff --git a/hdp/metric.py b/hdp/metric.py
new file mode 100644
index 0000000000000000000000000000000000000000..606c88942508bc8e2edfa5e32f72077cf62bb3cd
--- /dev/null
+++ b/hdp/metric.py
@@ -0,0 +1,603 @@
+import xarray
+import numpy as np
+import cftime
+import numba as nb
+import datetime
+from os import makedirs
+from pathlib import Path
+from hdp.utils import get_version, add_history
+from tqdm.auto import tqdm
+import dask.array as da
+
+
+@nb.njit
+def index_heatwaves(hot_days_ts: np.ndarray, min_duration: int, max_break: int, max_subs: int) -> np.ndarray:
+ """
+ Identifies the heatwaves in the timeseries using the specified heatwave definition
+
+ :param hot_days_ts: Integer array of ones and zeros where ones indicates a hot day
+ :type hot_days_ts: np.ndarray
+ :param min_duration: The minimum number of hot days to constitute a heatwave event, including after breaks
+ :type min_duration: int
+ :param max_break: The maximum number of days between hot days within one heatwave event
+ :type max_break: int
+ :param max_subs: the maximum number of subsequent events allowed to be apart of the initial consecutive hot days
+ :type max_subs: int
+ :return: Timeseries where nonzero integers indicate heatwave indices for each timestep
+ :rtype: np.ndarray
+ """
+ ts = np.zeros(hot_days_ts.size + 2, dtype=nb.int64)
+ for i in range(0, hot_days_ts.size):
+ if hot_days_ts[i]:
+ ts[i + 1] = 1
+ diff_ts = np.diff(ts)
+ diff_indices = np.where(diff_ts != 0)[0]
+
+ in_heatwave = False
+ current_hw_index = 0
+ sub_events = 0
+ hw_indices = np.zeros(diff_ts.size, dtype=nb.int64)
+
+ for i in range(diff_indices.size-1):
+ index = diff_indices[i]
+ next_index = diff_indices[i+1]
+
+ if diff_ts[index] == 1 and next_index - index >= min_duration and not in_heatwave:
+ current_hw_index += 1
+ in_heatwave = True
+ hw_indices[index:next_index] = current_hw_index
+ elif diff_ts[index] == -1 and next_index - index > max_break:
+ in_heatwave = False
+ elif diff_ts[index] == 1 and in_heatwave and sub_events < max_subs:
+ sub_events += 1
+ hw_indices[index:next_index] = current_hw_index
+ elif diff_ts[index] == 1 and in_heatwave and sub_events >= max_subs:
+ if next_index - index >= min_duration:
+ current_hw_index += 1
+ hw_indices[index:next_index] = current_hw_index
+ else:
+ in_heatwave = False
+ sub_events = 0
+
+ return hw_indices[0:hw_indices.size-1]
+
+
+@nb.njit
+def heatwave_number(hw_ts: np.ndarray, season_ranges: np.ndarray) -> np.ndarray:
+ """
+ Measures the number of heatwaves (by event, not days) in each season of a given heatwave index time series.
+ Heatwave metric, commonly abbreviated as HWN.
+
+ :param hw_ts: Integer timeseries of indexed heatwave days.
+ :type hw_ts: np.ndarray
+ :param season_ranges: Range of array indices, corresponding to heatwave season, in indexed heatwave day timeseries to count.
+ :type season_ranges: np.ndarray
+ :return: Number of heatwaves per heatwave season
+ :rtype: np.ndarray
+ """
+ output = np.zeros(season_ranges.shape[0], dtype=nb.int64)
+ for y in range(season_ranges.shape[0]):
+ end_points = season_ranges[y]
+ uniques = np.unique(hw_ts[end_points[0]:end_points[1]])
+ output[y] = uniques[uniques != 0].size
+
+ return output
+
+
+@nb.njit
+def heatwave_frequency(hw_ts: np.ndarray, season_ranges: np.ndarray) -> np.ndarray:
+ """
+ Measures the number of heatwave days in each season of a given heatwave index time series.
+ Heatwave metric, commonly abbreviated as HWF.
+
+ :param hw_ts: Integer timeseries of indexed heatwave days.
+ :type hw_ts: np.ndarray
+ :param season_ranges: Range of array indices, corresponding to heatwave season, in indexed heatwave day timeseries to count.
+ :type season_ranges: np.ndarray
+ :return: Number of heatwave days per heatwave season.
+ :rtype: np.ndarray
+ """
+ output = np.zeros(season_ranges.shape[0], dtype=nb.int64)
+ for y in range(season_ranges.shape[0]):
+ end_points = season_ranges[y]
+ output[y] = np.sum(hw_ts[end_points[0]:end_points[1]] > 0, dtype=nb.int64)
+ return output
+
+
+@nb.njit
+def heatwave_duration(hw_ts: np.ndarray, season_ranges: np.ndarray) -> np.ndarray:
+ """
+ Measures the length of the longest heatwave in each season of a given heatwave index time series.
+ Heatwave metric, commonly abbreviated as HWD.
+
+ :param hw_ts: Integer timeseries of indexed heatwave days.
+ :type hw_ts: np.ndarray
+ :param season_ranges: Range of array indices, corresponding to heatwave season, in indexed heatwave day timeseries to count.
+ :type season_ranges: np.ndarray
+ :return: Length of longest heatwave per heatwave season.
+ :rtype: np.ndarray
+ """
+ output = np.zeros(season_ranges.shape[0], dtype=nb.int64)
+ for y in range(season_ranges.shape[0]):
+ end_points = season_ranges[y]
+ hw_ts_slice = hw_ts[end_points[0]:end_points[1]]
+ unique_indices = np.unique(hw_ts_slice)
+
+ if unique_indices.size == 1:
+ output[y] = 0
+ else:
+ unique_indices = unique_indices[1:]
+
+ hw_lengths = np.zeros(unique_indices.size, dtype=nb.int64)
+ for index, value in enumerate(unique_indices):
+ if value != 0:
+ for day in hw_ts_slice:
+ if day == value:
+ hw_lengths[index] += 1
+
+ output[y] = np.max(hw_lengths)
+ return output
+
+
+@nb.njit
+def heatwave_average(hw_ts: np.ndarray, season_ranges: np.ndarray) -> np.ndarray:
+ """
+ Measures the average length of all heatwaves in each season of a given heatwave index time series.
+ Heatwave metric, commonly abbreviated as HWA.
+
+ :param hw_ts: Integer timeseries of indexed heatwave days.
+ :type hw_ts: np.ndarray
+ :param season_ranges: Range of array indices, corresponding to heatwave season, in indexed heatwave day timeseries to count.
+ :type season_ranges: np.ndarray
+ :return: Average heatwave length per heatwave season.
+ :rtype: np.ndarray
+ """
+ output = np.zeros(season_ranges.shape[0], dtype=nb.float64)
+ for y in range(season_ranges.shape[0]):
+ end_points = season_ranges[y]
+ hw_ts_slice = hw_ts[end_points[0]:end_points[1]]
+ unique_indices = np.unique(hw_ts_slice)
+
+ if unique_indices.size == 1:
+ output[y] = 0
+ else:
+ unique_indices = unique_indices[1:]
+
+ hw_lengths = np.zeros(unique_indices.size, dtype=nb.int64)
+ for index, value in enumerate(unique_indices):
+ if value != 0:
+ for day in hw_ts_slice:
+ if day == value:
+ hw_lengths[index] += 1
+
+ output[y] = np.mean(hw_lengths)
+ return output
+
+
+def get_range_indices(times: np.ndarray, start: tuple, end: tuple) -> np.ndarray:
+ """
+ Calculates the range of time indices to define each heatwave season for a given time series.
+ This function is agnostic to the calendar type, but will not yield accurate results if the month and day exceed the calendar's definition.
+ The ranges of indices are then used to slice the time series into the heatwave seasons, this is faster than iterating through CFTime objects.
+
+ :param times: Array of CFTime objects corresponding to the time series to define the seasons over.
+ :type times: np.ndarray
+ :param start: Tuple of starting month integer and day integer to compare times array against.
+ :type start: tuple
+ :param end: Tuple of ending month integer and day integer to compare times array against.
+ :type end: tuple
+ :return: Range of indices in times array for each season.
+ :rtype: np.ndarray
+ """
+ num_years = times[-1].year - times[0].year + 1
+ ranges = np.zeros((num_years, 2), dtype=int) - 1
+
+ n = 0
+ looking_for_start = True
+ for t in range(times.shape[0]):
+ if looking_for_start:
+ if times[t].month == start[0] and times[t].day == start[1]:
+ looking_for_start = False
+ ranges[n, 0] = t
+ else:
+ if times[t].month == end[0] and times[t].day == end[1]:
+ looking_for_start = True
+ ranges[n, 1] = t
+ n += 1
+
+ if not looking_for_start:
+ ranges[-1, -1] = times.shape[0]
+
+ return ranges
+
+
+def compute_hemisphere_ranges(measure: xarray.DataArray) -> xarray.DataArray:
+ """
+ Computes the heatwave season ranges by time index (not the timestamp, rather the index corresponding to the timestamp) for each grid cell based on whether it is in the Northern Hemisphere (boreal summer, May 1st to October 1st) or Southern Hemisphere (austral summer, November 1st to March 1st).
+
+ :param measure: DataArray containing 'lat' and 'lon' variables corresponding to grid.
+ :type measure: xarray.DataArray
+ :return: Generates seasonal ranges by hemisphere for an arbitrary 'lat'-'lon' grid.
+ :rtype: xarray.DataArray
+ """
+ north_ranges = get_range_indices(measure.time.values, (5, 1), (10, 1))
+ south_ranges = get_range_indices(measure.time.values, (11, 1), (4, 1))
+
+ slice_start = 0
+ slice_end = north_ranges.size
+ start_indentified = False
+ for year_index, n_end_points in enumerate(north_ranges):
+ end_points = np.concatenate([n_end_points, south_ranges[year_index]])
+
+ if -1 in end_points and not start_indentified:
+ slice_start = year_index
+ continue
+ elif not start_indentified:
+ start_indentified = True
+
+ if start_indentified and -1 in end_points:
+ slice_end = year_index
+ break
+
+ north_ranges = north_ranges[slice_start:slice_end]
+ south_ranges = south_ranges[slice_start:slice_end]
+ years = np.arange(measure.time.values[0].year, measure.time.values[-1].year + 1, 1)
+ years = years[slice_start:slice_end]
+
+ ranges = np.zeros((north_ranges.shape[0], 2, measure.lat.size, measure.lon.size), dtype=int) - 1
+
+ for i in range(measure.lat.size):
+ for j in range(measure.lon.size):
+ if measure.lat.values[i] < 0:
+ ranges[:, :, i, j] = south_ranges
+ else:
+ ranges[:, :, i, j] = north_ranges
+
+
+ return xarray.DataArray(data=ranges,
+ dims=["year", "end_points", "lat", "lon"],
+ coords={
+ "year": years,
+ "end_points": ["start", "finish"],
+ "lat": measure.lat.values,
+ "lon": measure.lon.values
+ })
+
+
+def build_doy_map(times: np.ndarray) -> np.ndarray:
+ """
+ Maps the time series index (key) to its respective day of the year (value).
+
+ :param measure: Array of CFTime objects.
+ :type measure: np.ndarray
+ :return: Day of year for each timestep.
+ :rtype: np.ndarray
+ """
+ doy_map = np.zeros(times.size, dtype=int) - 1
+ for time_index, time in enumerate(times):
+ doy_map[time_index] = time.dayofyr - 1
+ return doy_map
+
+
+@nb.njit
+def indicate_hot_days(measure: np.ndarray, threshold: np.ndarray, doy_map: np.ndarray) -> np.ndarray:
+ """
+ Determines whether each time step in a heat measure exceeds the threshold.
+
+ :param measure: Heat measure to compare against the threshold.
+ :type measure: np.ndarray
+ :param threshold: Threshold for extreme heat.
+ :type threshold: np.ndarray
+ :param doy_map: Mapping from index in times array to day of year value.
+ :type doy_map: np.ndarray
+ :return: Boolean array of days in measure that exceed the threshold.
+ :rtype: np.ndarray
+ """
+ output = np.zeros(measure.shape, dtype=nb.boolean)
+ for t in range(measure.size):
+ doy = doy_map[t]
+ if measure[t] > threshold[doy]:
+ output[t] = True
+ else:
+ output[t] = False
+ return output
+
+
+@nb.njit
+def compute_heatwave_metrics(measure: np.ndarray, threshold: np.ndarray, doy_map: np.ndarray,
+ min_duration: int, max_break: int, max_subs: int,
+ season_ranges: np.ndarray) -> np.ndarray:
+ """
+ Computes HWN, HWF, HWD, and HWA metrics for a given measure, threshold, and definition. Additional parameters can be used to fine tune the analysis.
+ This is the Numba-compiled function that is parallelized with Dask and formatted into a more user-friendly format by hdp.metrics.compute_individual_metrics
+
+ :param measure: Heat measure to compare against the threshold.
+ :type measure: np.ndarray
+ :param threshold: Threshold for extreme heat.
+ :type threshold: np.ndarray
+ :param doy_map: Mapping from index in times array to day of year value.
+ :type doy_map: np.ndarray
+ :param min_duration: Minimum number of days that exceed the threshold to constitute a heatwave.
+ :type min_duration: int
+ :param max_break: Maximum number of days below the threshold that can exist in a heatwave.
+ :type max_break: int
+ :param max_subs: Maximum number of subsequent heatwaves.
+ :type max_subs: int
+ :param season_ranges:
+ :type season_ranges: np.ndarray
+ :return: Array of equal number of dimensions to measure and an additional dimension containing each heatwave metric: HWN, HWF, HWD, HWA
+ :rtype: np.ndarray
+ """
+ hot_days_ts = indicate_hot_days(measure, threshold, doy_map)
+ hw_ts = index_heatwaves(hot_days_ts, min_duration, max_break, max_subs)
+ hwf = heatwave_frequency(hw_ts, season_ranges)
+ hwn = heatwave_number(hw_ts, season_ranges)
+ hwd = heatwave_duration(hw_ts, season_ranges)
+ hwa = heatwave_average(hw_ts, season_ranges)
+
+ output = np.zeros((4,) + hwf.shape, dtype=nb.int64)
+ output[0] = hwf
+ output[1] = hwn
+ output[2] = hwd
+ output[3] = hwa
+ return output
+
+
+def compute_heatwave_metrics_wrapper(measure, threshold, doy_map, hw_definitions):
+ season_ranges = compute_hemisphere_ranges(measure)
+
+ def_coords = xarray.DataArray(
+ [f"{hw_def[0]}-{hw_def[1]}-{hw_def[2]}" for hw_def in hw_definitions],
+ dims=["definition"]
+ )
+ perc_coords = xarray.DataArray(
+ threshold.percentile.values,
+ dims=["percentile"]
+ )
+
+ perc_datasets = []
+ for perc in threshold.percentile.values:
+ def_datasets = []
+ for hw_def in hw_definitions:
+ metric_data = xarray.apply_ufunc(compute_heatwave_metrics, measure, threshold.sel(percentile=perc), doy_map,
+ hw_def[0], hw_def[1], hw_def[2],
+ season_ranges,
+ vectorize=True, dask="parallelized",
+ input_core_dims=[["time"], ["doy"], ["time"], [], [], [], ["year", "end_points"]],
+ output_core_dims=[["metric", "year"]],
+ output_dtypes=[int], dask_gufunc_kwargs=dict(output_sizes=dict(metric=4)))
+ def_datasets.append(metric_data)
+ perc_datasets.append(xarray.concat(def_datasets, dim=def_coords))
+ return xarray.concat(perc_datasets, dim=perc_coords)
+
+
+def compute_individual_metrics(measure: xarray.DataArray, threshold: xarray.DataArray, hw_definitions: list, include_threshold: bool=True, check_variables: bool=True) -> xarray.Dataset:
+ """
+ Computes HWN, HWF, HWD, and HWA heatwave metrics for an individual parameter configuration of measure, threshold, and definition.
+
+ Heatwave definitions are described by tuples of three integers in the following order:
+ 1. Minimum number of days exceeding the threshold to define the start of a heatwave
+ 2. Maximum number of days following the start of a heatwave that do not exceed the threshold and are followed by days that do exceed the threshold. In other words, the maximum "break" that a heatwave can have between the initial hot days and some number of hot days afterwards.
+ 3. Maximum number of breaks in a heatwave (can also be thought of as the maximum number of secondary events after the initial hot days).
+
+ :param measure: Formatted HDP measure DataArray
+ :type measure: xarray.DataArray
+ :param threshold: Formatted HDP threshold compatable with the given measure
+ :type threshold: xarray.DataArray
+ :param hw_definitions: Heatwave definitions to calculate metrics for. See the function description for how to generate definitions.
+ :type hw_definitions: list[tuple]
+ :param include_threshold: (Optional) Whether or not to include the threshold DataArray in the aggregated output dataset. Default is True.
+ :type include_threshold: bool
+ :param check_variables: (Optional) Whether or not to check if measure is compatable with the threshold. Default is True.
+ :type check_variables: bool
+ :return: Aggregate dataset containing all of the heatwave metrics and optional datasets.
+ :rtype: xarray.Dataset
+ """
+ if check_variables:
+ assert "hdp_type" in threshold.attrs
+ assert threshold.attrs["hdp_type"] == "threshold"
+ assert threshold.attrs["baseline_variable"] == measure.attrs["baseline_variable"]
+ assert threshold.attrs["baseline_calendar"] == measure.time.values[0].calendar
+
+ combined_history = ""
+ if "history" in measure.attrs:
+ for entry in measure.attrs["history"].split("\n"):
+ if entry != '':
+ combined_history += (f"(Measure) {entry}\n")
+ if "history" in threshold.attrs:
+ for entry in threshold.attrs["history"].split("\n"):
+ if entry != '':
+ combined_history += (f"(Threshold) {entry}\n")
+
+ season_ranges = compute_hemisphere_ranges(measure)
+
+ times = measure.time.values
+ doy_map = xarray.DataArray(
+ data=build_doy_map(times),
+ coords={"time": times}
+ )
+
+ da_dims = ["percentile", "definition"]
+ da_shape = [threshold.percentile.size, len(hw_definitions)]
+ da_chunks = [(threshold.percentile.size), (len(hw_definitions))]
+
+ for index, dim in enumerate(measure.dims):
+ if dim != "time":
+ da_dims.append(dim)
+ da_shape.append(measure.shape[index])
+ da_chunks.append(measure.chunks[index])
+
+ da_dims.extend(["metric", "year"])
+ da_shape.extend([4, season_ranges.year.size])
+ da_chunks.extend([(4), (season_ranges.year.size)])
+
+ da_coords = {**measure.coords}
+ da_coords.pop("time", None)
+ da_coords["year"] = season_ranges.year.values
+ da_coords["definition"] = [f"{hw_def[0]}-{hw_def[1]}-{hw_def[2]}" for hw_def in hw_definitions]
+ da_coords["percentile"] = threshold.percentile.values
+
+ template = xarray.DataArray(
+ da.random.random(da_shape, chunks=da_chunks),
+ dims=da_dims,
+ coords=da_coords
+ )
+
+ metric_data = xarray.map_blocks(
+ compute_heatwave_metrics_wrapper,
+ obj=measure,
+ args=[threshold, doy_map],
+ kwargs={
+ "hw_definitions": hw_definitions,
+ },
+ template=template
+ )
+
+ ds = xarray.Dataset(
+ dict(
+ HWF=metric_data.sel(metric=0),
+ HWN=metric_data.sel(metric=1),
+ HWD=metric_data.sel(metric=2),
+ HWA=metric_data.sel(metric=3)
+ )
+ )
+
+ start_ts = cftime.datetime(ds.year[0], 1, 1, calendar=measure.time.values[0].calendar)
+ end_ts = cftime.datetime(ds.year[-1], 1, 1, calendar=measure.time.values[0].calendar)
+ ds = ds.rename(dict(year="time")).assign_coords(dict(time=xarray.date_range(start_ts, end_ts, periods=ds.year.size, use_cftime=True)))
+
+ ds.attrs |= {
+ "description": f"Heatwave metric dataset generated by Heatwave Diagnostics Package (HDP v{get_version()})",
+ "hdp_version": get_version(),
+ "hdp_type": "metric"
+ }
+
+ ds["HWF"].attrs |= {
+ "units": "heatwave days",
+ "long_name": "Heatwave Frequency",
+ "description": "Number of days that fall within heatwave during a heatwave season"
+ }
+ ds["HWD"].attrs |= {
+ "units": "heatwave days",
+ "long_name": "Heatwave Duration",
+ "description": "Length of longest heatwave during a heatwave season"
+ }
+ ds["HWN"].attrs |= {
+ "units": "heatwave events",
+ "long_name": "Heatwave Number",
+ "description": "Number of distinct heatwaves during a heatwave season"
+ }
+ ds["HWA"].attrs |= {
+ "units": "heatwave events",
+ "long_name": "Heatwave Average",
+ "description": "Average length of heatwaves during a heatwave season"
+ }
+ ds["percentile"].attrs |= {
+ "range": "(0, 1)"
+ }
+ ds["definition"].attrs |= {
+ "first_number": "Minimum number of consecutively hot days",
+ "second_number": "Maximum number of break days after first wave",
+ "third_number": "Minimum number of consecutively hot days after the break"
+ }
+
+ for variable in ds:
+ ds[variable].attrs["history"] = combined_history
+ add_history(ds[variable], f"Heatwave metrics generated by HDP v{get_version()}")
+
+ if include_threshold:
+ ds[threshold.name] = threshold
+
+ return ds
+
+
+def compute_group_metrics(measures: xarray.Dataset, thresholds:xarray.Dataset, hw_definitions: list, include_threshold: bool=False, check_variables: bool=True) -> xarray.Dataset:
+ metric_sets = []
+ for measure_name in list(measures.keys()):
+ measure = measures[measure_name]
+ for threshold_name in list(thresholds.keys()):
+ threshold = thresholds[threshold_name]
+ if threshold.attrs["baseline_variable"] == measure.attrs["baseline_variable"]:
+ hw_metrics = compute_individual_metrics(measure, threshold, hw_definitions, include_threshold, check_variables)
+ var_renames = {name: f"{measure_name}.{threshold_name}.{name}" for name in list(hw_metrics.keys()) if name != threshold_name}
+ metric_sets.append(hw_metrics.rename(var_renames))
+
+ aggr_ds = xarray.merge(metric_sets)
+ aggr_ds.attrs["variable_naming_desc"] = "(heat measure).(threshold used).(heatwave metric)"
+ aggr_ds.attrs["variable_naming_delimeter"] = "."
+ return aggr_ds
+
+
+def compute_metrics_io(output_path: str,
+ measure_path: str,
+ measure_var: str,
+ threshold_path: str,
+ hw_definitions: list,
+ include_threshold: bool=False,
+ override_threshold_var: str=None,
+ overwrite: bool=False) -> None:
+ """
+ Computes heatwave metrics from path inputs instead of manually supplied xarray Datasets/DataArrays (automates reading from and writing to disk).
+ Resulting metrics are written directly to disk instead of holding in memory.
+
+ :param output_path: Path to write dataset(s) to, can be a zarr store (faster) or netCDF file (slower).
+ :type output_path: str
+ :param measure_path: Path to heat measure dataset formatted by the HDP.
+ :type measure_path: str
+ :param measure_var: Name of measure variable to use from specified dataset.
+ :type measure_var: str
+ :param threshold_path: Path to threshold dataset formatted by the HDP.
+ :type threshold_path: str
+ :param hw_definitions: Definitions to compute heatwave metrics over.
+ :type hw_definitions: list
+ :param include_threshold: (Optional) Whether or not to include the threshold dataset in the resulting output. Default is False.
+ :type include_threshold: bool
+ :param override_threshold_var: (Optional) Override threshold variable to use when computing metrics. If left unspecified, the format "threshold_{measure_var}" will be used.
+ :type override_threshold_var: str
+ :param overwrite: (Optional) Whether or not to overwrite an existing dataset at the output_path. Defaults to False.
+ :type overwrite: bool
+ :return: None
+ :rtype: None
+ """
+ output_path = Path(output_path)
+ measure_path = Path(measure_path)
+ threshold_path = Path(threshold_path)
+ check_variables = True
+
+ if override_threshold_var is None:
+ threshold_var = f"threshold_{measure_var}"
+ check_variables = False
+ else:
+ threshold_var = override_threshold_var
+
+ if output_path.exists() and not overwrite:
+ raise FileExistsError(f"Overwrite parameter set to False and file exists at '{output_path}'.")
+
+ if not output_path.parent.exists():
+ if overwrite:
+ makedirs(output_path)
+ else:
+ raise FileExistsError(f"Overwrite parameter set to False and directory '{output_path.parent}' does not exist.")
+
+ if output_path.suffix not in [".zarr", ".nc"]:
+ raise ValueError(f"File type '{output_path.suffix}' from '{output_path}' not supported.")
+
+ if measure_path.suffix == ".zarr" and measure_path.is_dir():
+ measure_data = xarray.open_zarr(measure_path)[measure_var]
+ else:
+ measure_data = xarray.open_dataset(measure_path)[measure_var]
+
+ # The heatwave indexing requires the full time axis in a single chunk (see compute_individual_metrics).
+ measure_data = measure_data.chunk(dict(time=-1))
+
+ if threshold_path.suffix == ".zarr" and threshold_path.is_dir():
+ threshold_data = xarray.open_zarr(threshold_path)[threshold_var]
+ else:
+ threshold_data = xarray.open_dataset(threshold_path)[threshold_var]
+
+ metric_ds = compute_individual_metrics(measure_data, threshold_data, hw_definitions, include_threshold=include_threshold, check_variables=check_variables)
+
+ if output_path.suffix == ".zarr":
+ metric_ds.to_zarr(output_path)
+ else:
+ metric_ds.to_netcdf(output_path)
\ No newline at end of file
diff --git a/hdp/tests/__init__.py b/hdp/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/hdp/tests/test_heatwave_average.py b/hdp/tests/test_heatwave_average.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ff6e9d4266421228a4092b27838ef864ff4d912
--- /dev/null
+++ b/hdp/tests/test_heatwave_average.py
@@ -0,0 +1,54 @@
+from hdp.metric import heatwave_average
+import numpy as np
+
+
+class TestHeatwaveAverage:
+ def test_heatwave_average_null_case(self):
+ hot_day_null = np.zeros(100, dtype=int)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_average(hot_day_null, season_range), np.array([0]))
+
+ def test_heatwave_average_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_average(hot_day_full, season_range), np.array([100]))
+
+ def test_heatwave_average_case1(self):
+ hot_day_case1 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case1.size]], dtype=int)
+ assert np.array_equal(heatwave_average(hot_day_case1, season_range), np.array([5.5]))
+
+ def test_heatwave_average_case2(self):
+ hot_day_case2 = np.array(
+ [0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 3],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case2.size]], dtype=int)
+ assert np.allclose(heatwave_average(hot_day_case2, season_range), np.array([3.333333]))
+
+ def test_heatwave_average_case3(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_average(hot_day_case3, season_range), np.array([1.75]))
+
+ def test_heatwave_average_season_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 5], [0, 10], [20, 30], [42, 50]], dtype=int)
+ assert np.array_equal(heatwave_average(hot_day_full, season_range), np.array([5, 10, 10, 8]))
+
+ def test_heatwave_average_season_case1(self):
+ hot_day_case3 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_average(hot_day_case3, season_range), np.array([6, 2.5]))
+
+ def test_heatwave_average_season_case2(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_average(hot_day_case3, season_range), np.array([1.5, 2]))
diff --git a/hdp/tests/test_heatwave_duration.py b/hdp/tests/test_heatwave_duration.py
new file mode 100644
index 0000000000000000000000000000000000000000..c865b498e17faf843db8033e61907311c1da6f67
--- /dev/null
+++ b/hdp/tests/test_heatwave_duration.py
@@ -0,0 +1,54 @@
+from hdp.metric import heatwave_duration
+import numpy as np
+
+
+class TestHeatwaveDuration:
+ def test_heatwave_duration_null_case(self):
+ hot_day_null = np.zeros(100, dtype=int)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_null, season_range), np.array([0]))
+
+ def test_heatwave_duration_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_full, season_range), np.array([100]))
+
+ def test_heatwave_duration_case1(self):
+ hot_day_case1 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case1.size]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_case1, season_range), np.array([7]))
+
+ def test_heatwave_duration_case2(self):
+ hot_day_case2 = np.array(
+ [0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 3],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case2.size]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_case2, season_range), np.array([5]))
+
+ def test_heatwave_duration_case3(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_case3, season_range), np.array([3]))
+
+ def test_heatwave_duration_season_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 5], [0, 10], [20, 30], [42, 50]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_full, season_range), np.array([5, 10, 10, 8]))
+
+ def test_heatwave_duration_season_case1(self):
+ hot_day_case3 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_case3, season_range), np.array([6, 4]))
+
+ def test_heatwave_duration_season_case2(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_case3, season_range), np.array([2, 3]))
diff --git a/hdp/tests/test_heatwave_frequency.py b/hdp/tests/test_heatwave_frequency.py
new file mode 100644
index 0000000000000000000000000000000000000000..140cb21d5ffd809eb311d79624558484ea909b1b
--- /dev/null
+++ b/hdp/tests/test_heatwave_frequency.py
@@ -0,0 +1,54 @@
+from hdp.metric import heatwave_frequency
+import numpy as np
+
+
+class TestHeatwaveFrequency:
+ def test_heatwave_frequency_null_case(self):
+ hot_day_null = np.zeros(100, dtype=int)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_null, season_range), np.array([0]))
+
+ def test_heatwave_frequency_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_full, season_range), np.array([100]))
+
+ def test_heatwave_frequency_case1(self):
+ hot_day_case1 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case1.size]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_case1, season_range), np.array([11]))
+
+ def test_heatwave_frequency_case2(self):
+ hot_day_case2 = np.array(
+ [0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 3],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case2.size]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_case2, season_range), np.array([10]))
+
+ def test_heatwave_frequency_case3(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_case3, season_range), np.array([7]))
+
+ def test_heatwave_frequency_season_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 5], [0, 10], [20, 30], [42, 50]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_full, season_range), np.array([5, 10, 10, 8]))
+
+ def test_heatwave_frequency_season_case1(self):
+ hot_day_case3 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_case3, season_range), np.array([6, 5]))
+
+ def test_heatwave_frequency_season_case2(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_case3, season_range), np.array([3, 4]))
diff --git a/hdp/tests/test_heatwave_number.py b/hdp/tests/test_heatwave_number.py
new file mode 100644
index 0000000000000000000000000000000000000000..232292ad743de7c1cb63919c2b7073dc1385981a
--- /dev/null
+++ b/hdp/tests/test_heatwave_number.py
@@ -0,0 +1,54 @@
+from hdp.metric import heatwave_number
+import numpy as np
+
+
+class TestHeatwaveNumber:
+ def test_heatwave_number_null_case(self):
+ hot_day_null = np.zeros(100, dtype=int)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_null, season_range), np.array([0]))
+
+ def test_heatwave_number_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_full, season_range), np.array([1]))
+
+ def test_heatwave_number_case1(self):
+ hot_day_case1 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case1.size]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_case1, season_range), np.array([2]))
+
+ def test_heatwave_number_case2(self):
+ hot_day_case2 = np.array(
+ [0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 3],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case2.size]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_case2, season_range), np.array([3]))
+
+ def test_heatwave_number_case3(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_case3, season_range), np.array([4]))
+
+ def test_heatwave_number_season_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 5], [0, 10], [20, 30], [42, 50]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_full, season_range), np.array([1, 1, 1, 1]))
+
+ def test_heatwave_number_season_case1(self):
+ hot_day_case3 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_case3, season_range), np.array([1, 2]))
+
+ def test_heatwave_number_season_case2(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_case3, season_range), np.array([2, 2]))
diff --git a/hdp/tests/test_index_heatwaves.py b/hdp/tests/test_index_heatwaves.py
new file mode 100644
index 0000000000000000000000000000000000000000..05ee22c1b857a137e805f4cd9421a405492c0b66
--- /dev/null
+++ b/hdp/tests/test_index_heatwaves.py
@@ -0,0 +1,41 @@
+from hdp.metric import index_heatwaves
+import numpy as np
+import pytest
+
+
+class TestIndexHeatwave:
+ def test_index_heatwaves_null_case(self):
+ hot_day_null = np.zeros(100, dtype=bool)
+ assert np.array_equal(index_heatwaves(hot_day_null, 1, 1, 1), np.zeros(hot_day_null.size))
+ assert np.array_equal(index_heatwaves(hot_day_null, 1, 0, 1), np.zeros(hot_day_null.size))
+ assert np.array_equal(index_heatwaves(hot_day_null, 0, 0, 1), np.zeros(hot_day_null.size))
+
+ def test_index_heatwaves_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ assert np.array_equal(index_heatwaves(hot_day_full, 1, 1, 1), np.ones(hot_day_full.size))
+ assert np.array_equal(index_heatwaves(hot_day_full, 1, 0, 1), np.ones(hot_day_full.size))
+ assert np.array_equal(index_heatwaves(hot_day_full, 0, 0, 1), np.ones(hot_day_full.size))
+
+ def test_index_heatwaves_case1(self):
+ hot_day_case1 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
+ dtype=bool)
+ assert np.array_equal(index_heatwaves(hot_day_case1, 1, 1, 1), [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0])
+ assert np.array_equal(index_heatwaves(hot_day_case1, 1, 0, 1), [0, 1, 1, 1, 1, 0, 2, 2, 2, 0, 0, 0, 3, 3, 3, 3, 0, 0, 0, 0])
+ assert np.array_equal(index_heatwaves(hot_day_case1, 0, 0, 1), [0, 1, 1, 1, 1, 0, 2, 2, 2, 0, 0, 0, 3, 3, 3, 3, 0, 0, 0, 0])
+
+ def test_index_heatwaves_case2(self):
+ hot_day_case2 = np.array(
+ [0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1],
+ dtype=bool)
+ assert np.array_equal(index_heatwaves(hot_day_case2, 1, 1, 1), [0, 1, 0, 1, 1, 0, 2, 2, 0, 0, 0, 0, 3, 3, 3, 3, 0, 0, 0, 4])
+ assert np.array_equal(index_heatwaves(hot_day_case2, 1, 0, 1), [0, 1, 0, 2, 2, 0, 3, 3, 0, 0, 0, 0, 4, 4, 4, 4, 0, 0, 0, 5])
+ assert np.array_equal(index_heatwaves(hot_day_case2, 0, 0, 1), [0, 1, 0, 2, 2, 0, 3, 3, 0, 0, 0, 0, 4, 4, 4, 4, 0, 0, 0, 5])
+
+ def test_index_heatwaves_case3(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
+ dtype=bool)
+ assert np.array_equal(index_heatwaves(hot_day_case3, 1, 1, 1), [0, 0, 0, 1, 1, 0, 1, 0, 2, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 0])
+ assert np.array_equal(index_heatwaves(hot_day_case3, 1, 0, 1), [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0])
+ assert np.array_equal(index_heatwaves(hot_day_case3, 0, 0, 1), [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0])
\ No newline at end of file
diff --git a/hdp/tests/test_utils.py b/hdp/tests/test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f58d24248d7bca9a2544bd0d7ab8a228696b236c
--- /dev/null
+++ b/hdp/tests/test_utils.py
@@ -0,0 +1,57 @@
+from hdp.utils import *
+import numpy as np
+from math import isclose
+from xarray import DataArray
+
+def test_get_time_stamp():
+ assert type(get_time_stamp()) is str
+
+
+def test_get_version():
+ assert type(get_version()) is str
+
+
+def test_control_dataarray():
+ control_da = generate_test_control_dataarray(grid_shape=(1,1), start_date="2000", end_date="2100")
+ assert type(control_da) is DataArray
+ var = control_da.name
+ assert control_da.attrs["units"] == "degC"
+ assert control_da.dims == ("lon", "lat", "time")
+ assert control_da.dtype == float
+ assert control_da.time.values[0].calendar == "noleap"
+ assert control_da.time.values.size >= 365
+ assert np.sum(np.isnan(control_da)) == 0
+
+ control_slope = np.polyfit(np.arange(control_da["time"].size), control_da.mean(dim=["lat", "lon"]).values, 1)[0]
+ assert np.abs(control_slope) < 0.01
+
+
+def test_warming_dataarray():
+ warming_da = generate_test_warming_dataarray(grid_shape=(1,1), start_date="2000", end_date="2100")
+ avg_da = warming_da.mean(dim=["lat", "lon"]).values
+ warm_slope = np.polyfit(np.arange(avg_da.size), avg_da, 1)[0]
+
+ assert warm_slope > 0
+ assert not isclose(warm_slope, 0)
+
+
+def test_rh_dataarray():
+ rh_da = generate_test_rh_dataarray()
+
+ assert rh_da.max() <= 1
+ assert rh_da.min() >= 0
+
+
+def test_defaults_compatibility():
+ control_da = generate_test_control_dataarray()
+ warming_da = generate_test_warming_dataarray()
+ rh_da = generate_test_rh_dataarray()
+
+ assert control_da.shape == warming_da.shape
+ assert warming_da.shape == rh_da.shape
+
+ assert control_da.dims == warming_da.dims
+ assert warming_da.dims == rh_da.dims
+
+ assert control_da.name == warming_da.name
+ assert control_da.units == warming_da.units
\ No newline at end of file
diff --git a/hdp/tests/test_workflow.py b/hdp/tests/test_workflow.py
new file mode 100644
index 0000000000000000000000000000000000000000..5750512fefd1f8bc7bb49c5f4c287b5c78cad30d
--- /dev/null
+++ b/hdp/tests/test_workflow.py
@@ -0,0 +1,99 @@
+from hdp.graphics.notebook import create_notebook
+import pytest
+import hdp.utils
+import hdp.measure
+import hdp.threshold
+import hdp.metric
+import numpy as np
+
+
+@pytest.fixture(scope="function")
+def temp_output_dir(tmp_path_factory):
+ return tmp_path_factory.mktemp("output_dir")
+
+
+def test_full_data_workflow(temp_output_dir):
+ grid_shape = (2, 3)
+
+ baseline_temp = hdp.utils.generate_test_control_dataarray(grid_shape=grid_shape).rename("temp")
+ baseline_rh = hdp.utils.generate_test_rh_dataarray(grid_shape=grid_shape).rename("rh")
+ baseline_measures = hdp.measure.format_standard_measures([baseline_temp], rh=baseline_rh)
+
+ percentiles = np.arange(0.9, 1, 0.01)
+
+ thresholds = hdp.threshold.compute_thresholds(baseline_measures, percentiles=percentiles)
+
+ test_temp = hdp.utils.generate_test_warming_dataarray(grid_shape=grid_shape).rename("temp")
+ test_rh = baseline_rh
+
+ hw_definitions = [[3,0,0], [3,1,1], [4,2,0], [4,1,3], [5,0,1], [5,1,4]]
+
+ test_measures = hdp.measure.format_standard_measures([test_temp], rh=test_rh)
+ metrics = hdp.metric.compute_group_metrics(test_measures, thresholds, hw_definitions)
+
+ metrics = metrics.compute()
+ thresholds = thresholds.compute()
+
+ assert (thresholds.percentile.values == percentiles).all()
+ assert len(thresholds.data_vars) == 2
+
+ assert metrics.definition.values[0] == "3-0-0"
+ assert metrics.definition.values[1] == "3-1-1"
+ assert metrics.definition.values[2] == "4-2-0"
+ assert metrics.definition.values[3] == "4-1-3"
+ assert metrics.definition.values[4] == "5-0-1"
+ assert metrics.definition.values[5] == "5-1-4"
+ assert (metrics.percentile.values == percentiles).all()
+
+ metric_means = metrics.mean()
+
+ assert metric_means["temp.temp_threshold.HWF"] >= metric_means["temp.temp_threshold.HWD"]
+ assert metric_means["temp.temp_threshold.HWD"] >= metric_means["temp.temp_threshold.HWA"]
+
+ for var in metrics:
+ assert metrics[var].shape == (metrics.percentile.size, metrics.definition.size, metrics.lon.size, metrics.lat.size, metrics.time.size)
+ assert metrics[var].dtype == int
+ if "HWF" in var or "HWD" in var:
+ assert metrics[var].attrs["units"] == 'heatwave days', f"Variable '{var}' has incorrect units '{metrics[var].attrs["units"]}'"
+ elif "HWN" in var or "HWA" in var:
+ assert metrics[var].attrs["units"] == 'heatwave events', f"Variable '{var}' has incorrect units '{metrics[var].attrs["units"]}'"
+ else:
+ assert False, f"Cannot determine primary heatwave metric from variable '{var}'."
+
+ figure_notebook = create_notebook(metrics)
+ figure_notebook.save_notebook(f"{temp_output_dir}/sample_hw_summary_figures.ipynb")
+
+
+def test_include_threshold(temp_output_dir):
+ grid_shape = (2, 3)
+
+ baseline_temp = hdp.utils.generate_test_control_dataarray(grid_shape=grid_shape).rename("temp")
+ test_temp = hdp.utils.generate_test_warming_dataarray(grid_shape=grid_shape).rename("temp")
+
+ baseline_measures = hdp.measure.format_standard_measures([baseline_temp])
+ test_measures = hdp.measure.format_standard_measures([test_temp])
+
+ percentiles = np.arange(0.9, 1, 0.02)
+ thresholds = hdp.threshold.compute_thresholds(baseline_measures, percentiles=percentiles)
+
+ hw_definitions = [[3, 0, 0], [3, 1, 1]]
+
+ metrics_with = hdp.metric.compute_group_metrics(test_measures, thresholds, hw_definitions, include_threshold=True).compute()
+ metrics_without = hdp.metric.compute_group_metrics(test_measures, thresholds, hw_definitions, include_threshold=False).compute()
+ thresholds = thresholds.compute()
+
+ # The threshold variable is embedded under its own name only when include_threshold=True.
+ assert "temp_threshold" in metrics_with.data_vars
+ assert "temp_threshold" not in metrics_without.data_vars
+
+ # The metric variables are unaffected by include_threshold.
+ metric_vars = [var for var in metrics_with.data_vars if var != "temp_threshold"]
+ assert set(metric_vars) == set(metrics_without.data_vars)
+
+ # The embedded threshold matches the source threshold exactly.
+ embedded = metrics_with["temp_threshold"]
+ source = thresholds["temp_threshold"]
+ assert embedded.broadcast_like(source).equals(source.broadcast_like(embedded))
+
+ figure_notebook = create_notebook(metrics_with)
+ figure_notebook.save_notebook(f"{temp_output_dir}/sample_hw_summary_figures.ipynb")
diff --git a/hdp/threshold.py b/hdp/threshold.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b33118b8f685012fc676c0736a04580857888c0
--- /dev/null
+++ b/hdp/threshold.py
@@ -0,0 +1,289 @@
+#!/usr/bin/env python
+import xarray
+import numpy as np
+import numba as nb
+from os.path import isdir
+from os import makedirs
+from pathlib import Path
+from hdp.utils import add_history, get_version
+import dask.array as da
+
+
+def datetimes_to_windows(datetimes: np.ndarray, window_radius: int) -> np.ndarray:
+ """
+ Generate rolling window sample of the day of year for each time index in the specified time series. Example below:
+
+ Day of year values for datetimes: 1 2 3 4 5 6
+ Window radius: 1
+ Result: [6 1 2], [1 2 3], [2 3 4], [3 4 5], [4 5 6], [5 6 1]
+
+
+ :param datetimes: Array of datetime objects corresponding to the dataset's time dimension
+ :type datetimes: np.ndarray
+ :param window_radius: Radius of each window
+ :type window_radius: int
+ :return: Two dimensional array where each index of the first dimension corresponds to the time dimension and the second dimension stores the indices of each window.
+ :rtype: np.ndarray
+ """
+ day_of_yr_to_index = {}
+ for index, date in enumerate(datetimes):
+ if date.dayofyr in day_of_yr_to_index.keys():
+ day_of_yr_to_index[date.dayofyr].append(index)
+ else:
+ day_of_yr_to_index[date.dayofyr] = [index]
+
+ time_index = np.zeros((len(day_of_yr_to_index), np.max([len(x) for x in day_of_yr_to_index.values()])), int) - 1
+
+ for index, day_of_yr in enumerate(day_of_yr_to_index):
+ for i in range(len(day_of_yr_to_index[day_of_yr])):
+ time_index[index, i] = day_of_yr_to_index[day_of_yr][i]
+
+ window_samples = np.zeros((len(day_of_yr_to_index), 2*window_radius+1, time_index.shape[1]), int)
+
+ for day_of_yr in range(window_samples.shape[0]):
+ for window_index in range(window_samples.shape[1]):
+ sample_index = day_of_yr + window_radius - window_index
+ if sample_index >= time_index.shape[0]:
+ sample_index = time_index.shape[0] - sample_index
+ window_samples[day_of_yr, window_index] = time_index[sample_index]
+ return window_samples.reshape((window_samples.shape[0], window_samples.shape[1]*window_samples.shape[2]))
+
+
+@nb.guvectorize(
+ [(nb.float32[:],
+ nb.int64[:, :],
+ nb.float64[:],
+ nb.float64[:, :])],
+ '(t), (d, b), (p) -> (d, p)'
+)
+def compute_percentiles(temperatures: np.ndarray, window_samples: np.ndarray, percentiles: np.ndarray, output: np.ndarray):
+ """
+ Generalized universal function that computes the temperatures for multiple percentiles using time index window samples.
+
+ :param temperatures: Dataset containing temperatures to compute percentiles from
+ :type temperatures: np.ndarray
+ :param window_samples: Array containing "windows" of indices cenetered at each day of the year
+ :type window_samples: np.ndarray
+ :param percentiles: Array of perecentiles to compute [0, 1]
+ :type percentiles: np.ndarray
+ :param output: Array to write percentiles to
+ :type output: np.ndarray
+ :return: None
+ :rtype: None
+ """
+ for doy_index in range(window_samples.shape[0]):
+ doy_temps = np.zeros(window_samples[doy_index].size)
+ for index, temperature_index in enumerate(window_samples[doy_index]):
+ doy_temps[index] = temperatures[temperature_index]
+ output[doy_index] = np.quantile(doy_temps, percentiles)
+
+
+def compute_percentiles_wrapper(baseline_data, rolling_windows, percentiles):
+ threshold_da = xarray.apply_ufunc(compute_percentiles,
+ baseline_data,
+ rolling_windows,
+ percentiles,
+ dask="parallelized",
+ input_core_dims=[["time"], ["doy", "t_index"], ["percentile"]],
+ output_core_dims=[["doy", "percentile"]],
+ keep_attrs="override",
+ dask_gufunc_kwargs={
+ 'allow_rechunk': False
+ })
+ return threshold_da
+
+
+def compute_threshold(baseline_data: xarray.DataArray, percentiles: np.ndarray, no_season: bool=False, rolling_window_size: int=7, fixed_value: float=None) -> xarray.Dataset:
+ """
+ Computes percentile and, optionally, fixed value thresholds for a baseline measurements.
+
+
+ :param baseline_data: DataArrays with baseline measurements to calculate thresholds from.
+ :type baseline_data: xarray.DataArray
+ :param percentiles: List of percentiles to calculate for each baseline.
+ :type percentiles: np.ndarray
+ :param no_season: (Optional) Instead of taking window samples at each day of year to get a seasonally-varying threshold, calculate a single percentile for the entire year. Defaults to False.
+ :type no_season: bool
+ :param rolling_window_size: (Optional) Size of rolling windows to use when calculating the percentiles. Defaults to 7.
+ :type rolling_window_size: int
+ :param fixed_value: (Optional) Value to use for fixed threshold (non-seasonally varying). Defaults to None.
+ :type fixed_value: float
+ :return: Aggregated dataset of all thresholds generated.
+ :rtype: xarray.Dataset
+ """
+ if "member" in baseline_data.dims:
+ member_datasets = []
+ for member in baseline_data.member.values:
+ member_slice = baseline_data.sel(member=member).drop_vars("member")
+ member_datasets.append(member_slice)
+ baseline_data = xarray.concat(member_datasets, dim="time")
+
+ baseline_data = baseline_data.chunk(dict(time=-1)).astype(np.float32)
+
+ percentiles = np.array(percentiles)
+
+ rolling_windows_indices = datetimes_to_windows(baseline_data.time.values, rolling_window_size)
+ rolling_windows_coords = {
+ "doy": np.arange(rolling_windows_indices.shape[0]),
+ "t_index": np.arange(rolling_windows_indices.shape[1])
+ }
+ rolling_windows = xarray.DataArray(data=rolling_windows_indices,
+ coords=rolling_windows_coords)
+
+ percentiles = xarray.DataArray(data=percentiles,
+ coords={"percentile": percentiles})
+
+ da_dims = []
+ da_shape = []
+ da_chunks = []
+
+ for index, dim in enumerate(baseline_data.dims):
+ if dim != "time":
+ da_dims.append(dim)
+ da_shape.append(baseline_data.shape[index])
+ da_chunks.append(baseline_data.chunks[index])
+
+ da_dims.extend(["doy", "percentile"])
+ da_shape.extend([rolling_windows_indices.shape[0], percentiles.values.size])
+ da_chunks.extend([(rolling_windows_indices.shape[0]), (percentiles.values.size)])
+
+
+ da_coords = {coord: baseline_data.coords[coord] for coord in baseline_data.coords if coord != "time"}
+ da_coords["doy"] = np.arange(rolling_windows_indices.shape[0])
+ da_coords["percentile"] = percentiles.values
+
+ template = xarray.DataArray(
+ da.random.random(da_shape, chunks=da_chunks),
+ dims=da_dims,
+ coords=da_coords
+ )
+
+ threshold_da = xarray.map_blocks(
+ compute_percentiles_wrapper,
+ obj=baseline_data,
+ kwargs={
+ "rolling_windows": rolling_windows,
+ "percentiles": percentiles
+ },
+ template=template
+ )
+
+ add_history(threshold_da, f"Threshold data computed by HDP v{get_version()}.\n")
+ if "long_name" in threshold_da.attrs:
+ add_history(threshold_da, f"Metadata updated: 'long_name' value '{threshold_da.attrs["long_name"]}' overwritten by HDP.\n")
+
+ threshold_da.attrs |= {
+ "long_name": f"Percentile threshold values for baseline variable '{baseline_data.name}'",
+ "baseline_variable": baseline_data.name,
+ "baseline_start_time": f"{str(baseline_data.time.values[0])}",
+ "baseline_end_time": f"{str(baseline_data.time.values[-1])}",
+ "baseline_calendar": f"{str(baseline_data.time.values[-1].calendar)}",
+ "param_percentiles": str(percentiles.values),
+ "param_noseason": str(no_season),
+ "param_rolling_window_size": str(rolling_window_size),
+ "param_fixed_value": str(fixed_value),
+ "hdp_type": "threshold"
+ }
+
+ ds = xarray.Dataset(
+ data_vars={
+ f"{baseline_data.name}_threshold": threshold_da,
+ },
+ coords=dict(
+ lon=(["lon"], threshold_da.lon.values),
+ lat=(["lat"], threshold_da.lat.values),
+ doy=np.arange(0, rolling_windows.shape[0]),
+ percentile=percentiles
+ ),
+ attrs=dict(
+ description=f"Extreme heat threshold dataset generated by Heatwave Diagnostics Package (HDP v{get_version()})",
+ hdp_version=get_version(),
+ )
+ )
+ ds["doy"].attrs = dict(units="day_of_year", baseline_calendar=str(baseline_data.time.values[0].calendar))
+ return ds
+
+
+def compute_thresholds(baseline_dataset: list[xarray.DataArray], percentiles: np.ndarray, no_season: bool=False, rolling_window_size: int=7, fixed_value: float=None) -> xarray.Dataset:
+ """
+ Wrapper function for generating multiple thresholds with hdp.threshold.compute_threshold.
+ Computes percentile and, optionally, fixed value thresholds for a list of baseline measurements.
+
+
+ :param baseline_dataset: Dataset containing baseline measurements to calculate thresholds from, where each data variable is used to compute a threshold.
+ :type baseline_dataset: xarray.Dataset
+ :param percentiles: List of percentiles to calculate for each baseline.
+ :type percentiles: np.ndarray
+ :param no_season: (Optional) Instead of taking window samples at each day of year to get a seasonally-varying threshold, calculate a single percentile for the entire year. Defaults to False.
+ :type no_season: bool
+ :param rolling_window_size: Size of rolling windows to use when calculating the percentiles.
+ :type rolling_window_size: int
+ :param fixed_value: Value to use for fixed threshold (non-seasonally varying).
+ :type fixed_value: float
+ :return: Aggregated dataset of all thresholds generated.
+ :rtype: xarray.Dataset
+ """
+ threshold_datasets = []
+ for var_name in baseline_dataset:
+ threshold_datasets.append(compute_threshold(baseline_dataset[var_name], percentiles, no_season, rolling_window_size, fixed_value))
+ return xarray.merge(threshold_datasets)
+
+
+def compute_threshold_io(baseline_path: str,
+ baseline_var: str,
+ output_path: str,
+ percentiles: np.ndarray,
+ no_season: bool=False,
+ rolling_window_size: int=7,
+ fixed_value: float=None,
+ overwrite: bool=False) -> None:
+ """
+ Computes thresholds from path inputs instead of manually supplied xarray Datasets/DataArrays (automates reading from and writing to disk).
+ Resulting threshold datasets are written directly to disk instead of holding in memory.
+
+ :param baseline_path: Path to netCDF or zarr store containing baseline measurements to compute thresholds from.
+ :type baseline_path: str
+ :param baseline_var: Variable read from the dataset at the specified path.
+ :type baseline_var: str
+ :param output_path: Path to write dataset(s) to, can be a zarr store (faster) or netCDF file (slower).
+ :type output_path: str
+ :param percentiles: List of percentiles to calculate for each baseline.
+ :type percentiles: np.ndarray
+ :param no_season: (Optional) Instead of taking window samples at each day of year to get a seasonally-varying threshold, calculate a single percentile for the entire year. Defaults to False.
+ :type no_season: bool
+ :param rolling_window_size: (Optional) Size of rolling windows to use when calculating the percentiles. Defaults to 7.
+ :type rolling_window_size: int
+ :param fixed_value: (Optional) Value to use for fixed threshold (non-seasonally varying). Defaults to None.
+ :type fixed_value: float
+ :param overwrite: (Optional) Whether or not to overwrite existing datasets at the output_path. Defaults to False
+ :type overwrite: bool
+ :return: None
+ :rtype: None
+ """
+ output_path = Path(output_path)
+ baseline_path = Path(baseline_path)
+
+ if output_path.exists() and not overwrite:
+ raise FileExistsError(f"Overwrite parameter set to False and file exists at '{output_path}'.")
+
+ if not output_path.parent.exists():
+ if overwrite:
+ makedirs(output_path)
+ else:
+ raise FileExistsError(f"Overwrite parameter set to False and directory '{output_path.parent}' does not exist.")
+
+ if output_path.suffix not in [".zarr", ".nc"]:
+ raise ValueError(f"File type '{output_path.suffix}' from '{output_path}' not supported.")
+
+ if baseline_path.suffix == ".zarr" and baseline_path.is_dir():
+ baseline_data = xarray.open_zarr(baseline_path)[baseline_var]
+ else:
+ baseline_data = xarray.open_dataset(baseline_path)[baseline_var]
+
+ baseline_data.attrs["baseline_source"] = str(baseline_path)
+ threshold_ds = compute_threshold(baseline_data, percentiles, no_season, rolling_window_size, fixed_value)
+
+ if output_path.suffix == ".zarr":
+ threshold_ds.to_zarr(output_path)
+ else:
+ threshold_ds.to_netcdf(output_path)
\ No newline at end of file
diff --git a/hdp/utils.py b/hdp/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a71b6d657d45764b2621b9be0e3539dbfb96ac30
--- /dev/null
+++ b/hdp/utils.py
@@ -0,0 +1,145 @@
+from time import time
+from importlib.metadata import version
+import numpy as np
+import dask.array as da
+import xarray
+import datetime
+import cftime
+
+
+def get_time_stamp():
+ return datetime.datetime.fromtimestamp(time()).strftime('%Y-%m-%d %H:%M')
+
+
+def add_history(ds, msg):
+ if "history" in ds.attrs:
+ ds.attrs["history"] += f"({get_time_stamp()}) {msg}\n"
+ else:
+ ds.attrs["history"] = f"({get_time_stamp()}) History metadata initialized by HDP v{get_version()}.\n"
+ ds.attrs["history"] += f"({get_time_stamp()}) {msg}\n"
+ return ds
+
+
+def get_version():
+ return version('hdp_python')
+
+
+def get_func_description(func):
+ lines = func.__doc__.split("\n")
+ desc = ""
+ for line in lines:
+ if ":param" in line:
+ break
+ line = line.strip()
+ if line != "":
+ desc += line.strip() + " "
+ return desc
+
+
+def generate_test_warming_dataarray(start_date="2000-01-01", end_date="2049-12-31", grid_shape=(2, 3), warming_period=100, add_noise=False):
+ """
+ Generates a synthetic warming temperature DataArray for testing.
+
+ Wraps :func:`generate_test_control_dataarray` and adds a linear warming trend
+ over the specified warming period (in years).
+
+ :param start_date: Start date of the time series in YYYY-MM-DD format. Defaults to "2000-01-01".
+ :type start_date: str
+ :param end_date: End date of the time series in YYYY-MM-DD format. Defaults to "2049-12-31".
+ :type end_date: str
+ :param grid_shape: Tuple of (lat, lon) grid dimensions. Defaults to (2, 3).
+ :type grid_shape: tuple
+ :param warming_period: Number of years over which 1 degree of warming is applied. Defaults to 100.
+ :type warming_period: int
+ :param add_noise: If True, adds random noise to create variance. Defaults to False.
+ :type add_noise: bool
+ :return: Synthetic warming temperature DataArray in degrees Celsius.
+ :rtype: xarray.DataArray
+ """
+ base_data = generate_test_control_dataarray(start_date=start_date, end_date=end_date, grid_shape=grid_shape, add_noise=add_noise)
+ base_data += xarray.DataArray(np.arange(base_data["time"].size) / (365*warming_period), dims=["time"], coords={"time": base_data["time"]})
+ return base_data
+
+
+def generate_test_rh_dataarray(start_date="2000-01-01", end_date="2049-12-31", grid_shape=(2, 3)):
+ """
+ Generates a synthetic relative humidity DataArray for testing.
+
+ Derived from :func:`generate_test_control_dataarray` and scaled to a relative
+ humidity range with units of g/g.
+
+ :param start_date: Start date of the time series in YYYY-MM-DD format. Defaults to "2000-01-01".
+ :type start_date: str
+ :param end_date: End date of the time series in YYYY-MM-DD format. Defaults to "2049-12-31".
+ :type end_date: str
+ :param grid_shape: Tuple of (lat, lon) grid dimensions. Defaults to (2, 3).
+ :type grid_shape: tuple
+ :return: Synthetic relative humidity DataArray with units "g/g".
+ :rtype: xarray.DataArray
+ """
+ base_data = generate_test_control_dataarray(start_date=start_date, end_date=end_date, grid_shape=grid_shape)
+ base_data = abs(base_data / base_data.max() - 0.3)
+ base_data = base_data.rename("test_rh_data")
+ base_data.attrs["units"] = 'g/g'
+ return base_data
+
+
+def generate_test_control_dataarray(start_date="1700-01-01", end_date="1749-12-31", grid_shape=(2, 3), add_noise=False, seed=0):
+ """
+ Generates a synthetic control temperature DataArray with a seasonal cycle for testing.
+
+ Produces a no-leap-calendar daily time series with a sinusoidal temperature pattern
+ and an optional latitudinal gradient. Used as the baseline (control) input in unit tests.
+
+ :param start_date: Start date of the time series in YYYY-MM-DD format. Defaults to "1700-01-01".
+ :type start_date: str
+ :param end_date: End date of the time series in YYYY-MM-DD format. Defaults to "1749-12-31".
+ :type end_date: str
+ :param grid_shape: Tuple of (lat, lon) grid dimensions. Defaults to (2, 3).
+ :type grid_shape: tuple
+ :param add_noise: If True, adds random noise to create variance across definitions and percentiles. Defaults to False.
+ :type add_noise: bool
+ :param seed: Random seed for reproducibility when add_noise is True. Defaults to 0.
+ :type seed: int
+ :return: Synthetic control temperature DataArray in degrees Celsius.
+ :rtype: xarray.DataArray
+ """
+ time_values = xarray.date_range(
+ start=start_date,
+ end=end_date,
+ freq="D",
+ calendar="noleap",
+ use_cftime=True
+ )
+ north_seasonal_ts = 20+2*np.sin(2*np.pi*((270 + np.arange(time_values.size, dtype=float)) / 365))
+ north_seasonal_vals = np.broadcast_to(north_seasonal_ts, (grid_shape[0], grid_shape[1], north_seasonal_ts.size))
+
+ south_seasonal_ts = 20+2*np.sin(2*np.pi*((90 + np.arange(time_values.size, dtype=float)) / 365))
+ south_seasonal_vals = np.broadcast_to(south_seasonal_ts, (grid_shape[0], grid_shape[1], south_seasonal_ts.size))
+
+ temperature_seasonal_vals = np.zeros((grid_shape[0], grid_shape[1], north_seasonal_ts.size))
+ temperature_seasonal_vals[:, grid_shape[1]//2:, :] = north_seasonal_vals[:, grid_shape[1]//2:, :]
+ temperature_seasonal_vals[:, :grid_shape[1]//2, :] = south_seasonal_vals[:, :grid_shape[1]//2, :]
+
+ if add_noise:
+ np.random.seed(seed)
+ temperature_seasonal_vals += np.random.random(temperature_seasonal_vals.shape)*(np.std(temperature_seasonal_vals) / 2)
+
+ lat_vals = np.linspace(-90, 90, grid_shape[1], dtype=float)
+
+ lat_grad = np.broadcast_to(np.abs(lat_vals) / 90, grid_shape)
+ temperature_seasonal_vals = temperature_seasonal_vals - 10*np.broadcast_to(lat_grad[:, :, None], temperature_seasonal_vals.shape)
+
+ return xarray.DataArray(
+ data=temperature_seasonal_vals,
+ dims=["lon", "lat", "time"],
+ coords={
+ "lon": np.linspace(-180, 180, grid_shape[0], dtype=float),
+ "lat": lat_vals,
+ "time": time_values
+ },
+ name="test_temperature_data",
+ attrs={
+ "units": "degC"
+ }
+ ).chunk(dict(time=-1, lat=2, lon=2))
\ No newline at end of file
diff --git a/docs/_static/heatwave_widget.js b/docs/_static/heatwave_widget.js
new file mode 100644
index 0000000000000000000000000000000000000000..be9ddbd38ed3db97f5704f8b986a517b371bc3ec
--- /dev/null
+++ b/docs/_static/heatwave_widget.js
+/*
+ * Interactive Heatwave Definition Explorer
+ * ----------------------------------------
+ * Self-contained, dependency-free widget for the HDP documentation.
+ *
+ * `indexHeatwaves` below is a faithful JavaScript port of HDP's
+ * `index_heatwaves` kernel (the source of truth is hdp/metric.py).
+ * It classifies a 0/1 "hot day" timeseries into indexed heatwave events
+ * using the definition triple [min_duration, max_break, max_subs].
+ *
+ * The widget renders entirely client-side (no kernel, no network, no CDN)
+ * so it works as static HTML on ReadTheDocs and as a crash-proof live demo.
+ */
+(function () {
+ "use strict";
+
+ // ---------------------------------------------------------------------------
+ // Heatwave classification (port of hdp/metric.py :: index_heatwaves)
+ // ---------------------------------------------------------------------------
+ function indexHeatwaves(hotDays, minDuration, maxBreak, maxSubs) {
+ var n = hotDays.length;
+ // Zero-pad to n + 2 so leading/trailing events are bounded by a diff edge.
+ var ts = new Int32Array(n + 2);
+ for (var i = 0; i < n; i++) {
+ if (hotDays[i]) ts[i + 1] = 1;
+ }
+
+ // Discrete difference of the padded series.
+ var diffTs = new Int32Array(ts.length - 1);
+ for (var j = 0; j < diffTs.length; j++) {
+ diffTs[j] = ts[j + 1] - ts[j];
+ }
+
+ // Indices where the series transitions (rising = 1, falling = -1).
+ var diffIndices = [];
+ for (var k = 0; k < diffTs.length; k++) {
+ if (diffTs[k] !== 0) diffIndices.push(k);
+ }
+
+ var inHeatwave = false;
+ var currentHwIndex = 0;
+ var subEvents = 0;
+ var hwIndices = new Int32Array(diffTs.length);
+
+ for (var m = 0; m < diffIndices.length - 1; m++) {
+ var index = diffIndices[m];
+ var nextIndex = diffIndices[m + 1];
+
+ if (diffTs[index] === 1 && nextIndex - index >= minDuration && !inHeatwave) {
+ currentHwIndex += 1;
+ inHeatwave = true;
+ fill(hwIndices, index, nextIndex, currentHwIndex);
+ } else if (diffTs[index] === -1 && nextIndex - index > maxBreak) {
+ inHeatwave = false;
+ } else if (diffTs[index] === 1 && inHeatwave && subEvents < maxSubs) {
+ subEvents += 1;
+ fill(hwIndices, index, nextIndex, currentHwIndex);
+ } else if (diffTs[index] === 1 && inHeatwave && subEvents >= maxSubs) {
+ if (nextIndex - index >= minDuration) {
+ currentHwIndex += 1;
+ fill(hwIndices, index, nextIndex, currentHwIndex);
+ } else {
+ inHeatwave = false;
+ }
+ subEvents = 0;
+ }
+ }
+
+ // Drop the trailing pad cell to realign with the input length.
+ return hwIndices.subarray(0, hwIndices.length - 1);
+ }
+
+ function fill(arr, start, end, value) {
+ for (var i = start; i < end; i++) arr[i] = value;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Metrics over the slice (analogous to HWN/HWF/HWD/HWA, whole window)
+ // ---------------------------------------------------------------------------
+ function computeMetrics(hwIndex) {
+ var events = {}; // index -> day count
+ for (var i = 0; i < hwIndex.length; i++) {
+ var v = hwIndex[i];
+ if (v !== 0) events[v] = (events[v] || 0) + 1;
+ }
+ var lengths = Object.keys(events).map(function (key) {
+ return events[key];
+ });
+ var hwn = lengths.length;
+ var hwf = lengths.reduce(function (a, b) {
+ return a + b;
+ }, 0);
+ var hwd = lengths.length ? Math.max.apply(null, lengths) : 0;
+ var hwa = lengths.length ? hwf / lengths.length : 0;