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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
# agentoxygen/hdp

## Project Overview

The Heatwave Diagnostics Package (HDP) is an open-source Python library that equips climate researchers with computationally efficient tools to quantify heatwave metrics across the parameter space of daily, gridded climate model output, particularly from large ensembles. HDP was created because existing heatwave tools (such as ehfheatwaves, heatwave3, and nctoolkit) were not designed to sample broad regions of the heatwave parameter space and struggle with the computational burden of terabyte-scale datasets. HDP addresses this gap by enabling parameter-sampling analysis and dramatically reducing the cost of computing heatwave diagnostics from increasingly large model output.

Functionally, HDP provides a complete end-to-end workflow: unit conversion and standardized measure formatting (measure.py), rolling day-of-year windowed threshold computation across arbitrary percentile levels (threshold.py), configurable heatwave definitions based on minimum duration, maximum break, and maximum sub-events (definitions.py), and the computation of group-level heatwave metrics such as frequency, duration, number, and average intensity (metric.py). These calculations are optimized through Numba for fast serial execution and leverage Xarray and Dask to scale effectively in parallel and distributed computing environments.

At a high level, the package is organized into a core computational layer (measure, threshold, and metric modules, with utilities in utils.py) and a graphics layer (graphics/), which includes plotting functions for generating summary figures that evaluate heatwave patterns spatially, temporally, and across the heatwave parameter space. Users may use these matplotlib figures as templates for custom visualizations or generate a standardized figure deck, all of which can be consolidated into a Jupyter notebook (graphics/notebook.py) for easy viewing and storage. The project also ships an llms.txt entry point to support LLM-assisted development workflows.

Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance.

## Submission Constraints (read carefully — the evaluation depends on these)

This is a **closed-book** task. The graded test suite is **hidden** and will be
injected into the workspace at evaluation time. To be scored correctly you MUST
follow these rules:

1. **Do NOT create or modify any files under the test directories** (e.g.
   `tests/`, `test/`, `testing/`, or files named `test_*.py` / `conftest.py`).
   The grader injects its own test files at those paths; any file you place
   there will collide with the injected suite and cause the whole evaluation to
   score 0. Implement **only** the library/source code — never the tests.

2. **Your package MUST be importable by the name the tests use.** The hidden
   tests `import` your package by its documented top-level name (see the
   Project Directory Structure and API Usage Guide below). Provide a valid
   `pyproject.toml` / `setup.py` / `setup.cfg` and lay out your modules so that
   `pip install -e .` succeeds and the package imports cleanly. If your package
   is not installable/importable, every test errors out and the reward is 0.

3. **Match the documented module paths and public API exactly** (names,
   signatures, and any literal error/exception strings). Internal helpers not
   listed in the API guide may be implemented however you like.

## Environment & Project Structure

- **Language**: python
- **Build system**: python
- **Test command**: `python3 -m pytest -vv -o addopts=-p no:cacheprovider hdp/tests/test_heatwave_average.py hdp/tests/test_heatwave_duration.py hdp/tests/test_heatwave_frequency.py hdp/tests/test_heatwave_number.py hdp/tests/test_index_heatwaves.py hdp/tests/test_utils.py hdp/tests/test_workflow.py`

### Project Directory Structure

```
.gitattributes
.github/workflows/draft-pdf.yml
.github/workflows/release.yml
.github/workflows/unit_tests.yml
.gitignore
.readthedocs.yaml
CITATION.cff
CONTRIBUTING.md
Dockerfile
LICENSE
README.md
docs/Makefile
docs/_static/heatwave_widget.css
docs/_static/heatwave_widget.js
docs/api.rst
docs/assets/cmip_workflow_example.png
docs/assets/example1_hw_metrics.png
docs/assets/method_figures.pptx
docs/assets/tasmax_dataarray_example.png
docs/assets/threshold_dataarray_example.png
docs/conf.py
docs/dev_guide.rst
docs/example_cmip_workflow/run_cmip_workflow.py
docs/example_heathack_workflow/HeatHack2026_HDP_example.ipynb
docs/examples.rst
docs/index.rst
docs/install.rst
docs/interactive.rst
docs/joss/ExampleFigure.png
docs/joss/paper.bib
docs/joss/paper.md
docs/joss/paper.pdf
docs/llm/README.md
docs/llm/api_map.md
docs/llm/architecture.md
docs/llm/data_model.md
docs/llm/development.md
docs/make.bat
docs/overview.rst
docs/sample_data/sample.py
docs/testing.rst
docs/user.rst
environment.yml
hdp/__init__.py
hdp/definitions.py
hdp/graphics/__init__.py
hdp/graphics/figure.py
hdp/graphics/hdp.mplstyle
hdp/graphics/notebook.py
hdp/graphics/winkel_tripel.py
hdp/measure.py
hdp/metric.py
hdp/pacl.mplstyle
hdp/threshold.py
hdp/utils.py
imgs/schematic1.png
imgs/schematic2.png
imgs/schematic3.png
imgs/schematic4.png
llms.txt
pyproject.toml
requirements.txt
```

## API Usage Guide

Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely.

### Capability: Data generation and unit conversion utilities

This capability provides the synthetic input data and the unit/provenance plumbing that downstream HDP modules consume. It has three parts: data generation (`hdp.utils`), measure unit conversion (`hdp.measure`), and figure scaffolding (`hdp.graphics.figure`). The data-generation half and the measure converters compose into the front of the package's workflow, so downstream threshold/metric functions receive well-formed, Celsius, `noleap`-calendar arrays carrying `units` and `history` attributes. `generate_base_figure` (`hdp.graphics.figure.generate_base_figure`) is listed in the verified evidence as a component of this capability, but its source lies outside the permitted files and its evidence entry carries no docstring summary, so its internal behavior is not characterized here.

**Data generation.** The three `generate_test_*` functions produce daily, `noleap`-calendar `cftime` time series. `generate_test_control_dataarray` is the root primitive: it builds a `date_range(..., freq="D", calendar="noleap", use_cftime=True)` axis and a sinusoidal seasonal cycle of the form `20 + 2*sin(2π*(phase + day_index)/365)`. The grid is split along `lat` at `grid_shape[1]//2`: the northern half uses phase `270` (peaking in summer) and the southern half phase `90`, so the two hemispheres are anti-phased. A latitude-dependent cooling `-10*|lat|/90` is broadcast over `(lon, lat)`, giving a poleward gradient. The returned array has dims `("lon", "lat", "time")`, coords `lon = linspace(-180, 180, grid_shape[0])`, `lat = linspace(-90, 90, grid_shape[1])`, name `"test_temperature_data"`, `attrs["units"] = "degC"`, and is chunked with `dict(time=-1, lat=2, lon=2)` (dask-backed). `add_noise=True` seeds `np.random` with `seed` and adds uniform `[0,1)` noise scaled by `std(values)/2` — note it seeds the global numpy RNG, not a local `Generator`.

`generate_test_warming_dataarray` wraps the control function and adds a linear trend `arange(time.size) / (365*warming_period)` broadcast over `time`, i.e. 1°C of warming per `warming_period` years. It shares the control defaults for dims, name, and units, so `control_da.name == warming_da.name` and `control_da.units == warming_da.units` (both `"degC"`). `generate_test_rh_dataarray` derives from the control array, computes `abs(base/base.max() - 0.3)`, renames to `"test_rh_data"`, and sets `units = "g/g"`; the result is bounded in `[0, 1]`.

**Unit conversion and history.** `add_history` prepends/initializes a `history` attr. On first call (no existing `history`) it writes an initialization line containing `get_version()` (from `importlib.metadata` on the `hdp_python` distribution) followed by the message; otherwise it appends. Every line is prefixed with `(YYYY-MM-DD HH:MM)` from `get_time_stamp()`. The two single-unit converters `fahrenheit_to_celsius` and `celsius_to_fahrenheit` convert a temperature `DataArray` between Fahrenheit and Celsius (per their docstrings: "Converts from temperature value from Fahrenheit to Celsius" and "...Celsius to Fahrenheit", respectively). `convert_temp_units` is described by its docstring as determining and converting temperature units to degrees Celsius; its exact unit-key mapping and mutation semantics are not captured in the deterministic evidence and are therefore not asserted here.

**Test-sensitive / non-obvious behavior.** The hidden tests exercise: `control_da.dtype == float`, dims order `("lon","lat","time")`, `time.values[0].calendar == "noleap"`, no NaNs, and a near-zero linear trend (slope `< 0.01`) for the control array, versus a strictly positive, non-zero slope for the warming array. The control trend being ~zero requires the seasonal cycle to have no secular drift — the anti-phased hemisphere construction and 20°C offset matter here. RH must satisfy `max() <= 1` and `min() >= 0`. The three default-argument arrays must have identical shape, dims, name, and units. `get_time_stamp()` and `get_version()` must both return `str`. `add_history` returns the same `ds` object after mutating `attrs`.

#### Exact API Reference

#### `hdp.graphics.figure.generate_base_figure`

- **Import Path**: `from hdp.graphics.figure import generate_base_figure`
- **Signature**:

```python
def generate_base_figure()
```

#### `hdp.measure.fahrenheit_to_celsius`

- **Import Path**: `from hdp.measure import fahrenheit_to_celsius`
- **Signature**:

```python
def fahrenheit_to_celsius(temp: xarray.DataArray) -> xarray.DataArray
```
- **Behavior**: Converts from temperature value from Fahrenheit to Celsius.

#### `hdp.measure.celsius_to_fahrenheit`

- **Import Path**: `from hdp.measure import celsius_to_fahrenheit`
- **Signature**:

```python
def celsius_to_fahrenheit(temp: xarray.DataArray) -> xarray.DataArray
```
- **Behavior**: Converts from temperature value from Celsius to Fahrenheit.

#### `hdp.measure.convert_temp_units`

- **Import Path**: `from hdp.measure import convert_temp_units`
- **Signature**:

```python
def convert_temp_units(temp_ds: xarray.DataArray) -> xarray.DataArray
```
- **Behavior**: Determines and converts temperature units to degrees Celsius.

#### `hdp.utils.add_history`

- **Import Path**: `from hdp.utils import add_history`
- **Signature**:

```python
def add_history(ds, msg)
```

#### `hdp.utils.generate_test_warming_dataarray`

- **Import Path**: `from hdp.utils import generate_test_warming_dataarray`
- **Required Test Import Paths**:
  - hdp.utils.generate_test_warming_dataarray
- **Exact Test Import Statements**:
  - import hdp.metric
- **Signature**:

```python
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)
```
- **Behavior**: Generates a synthetic warming temperature DataArray for testing.

#### `hdp.utils.generate_test_rh_dataarray`

- **Import Path**: `from hdp.utils import generate_test_rh_dataarray`
- **Required Test Import Paths**:
  - hdp.utils.generate_test_rh_dataarray
- **Exact Test Import Statements**:
  - import hdp.metric
- **Signature**:

```python
def generate_test_rh_dataarray(start_date='2000-01-01', end_date='2049-12-31', grid_shape=(2, 3))
```
- **Behavior**: Generates a synthetic relative humidity DataArray for testing.

#### `hdp.utils.generate_test_control_dataarray`

- **Import Path**: `from hdp.utils import generate_test_control_dataarray`
- **Required Test Import Paths**:
  - hdp.utils.generate_test_control_dataarray
- **Exact Test Import Statements**:
  - import hdp.metric
- **Signature**:

```python
def generate_test_control_dataarray(start_date='1700-01-01', end_date='1749-12-31', grid_shape=(2, 3), add_noise=False, seed=0)
```
- **Behavior**: Generates a synthetic control temperature DataArray with a seasonal cycle for testing.

#### `hdp.utils`

- **Import Path**: `from hdp import utils`
- **Required Test Import Paths**:
  - hdp.utils
  - hdp.utils.*
- **Exact Test Import Statements**:
  - from hdp.utils import *
  - import hdp.utils
- **Kind**: module
- **Behavior**: Module required during hidden-test collection.

#### `hdp.metric`

- **Import Path**: `from hdp import metric`
- **Required Test Import Paths**:
  - hdp.metric
- **Exact Test Import Statements**:
  - import hdp.metric
- **Kind**: module
- **Behavior**: Module required during hidden-test collection.

#### `hdp.threshold`

- **Import Path**: `from hdp import threshold`
- **Required Test Import Paths**:
  - hdp.threshold
- **Exact Test Import Statements**:
  - import hdp.threshold
- **Kind**: module
- **Behavior**: Module required during hidden-test collection.

### Capability: Heat measure formatting and heat index computation

The measure layer is the entry point that turns raw daily temperature (and optionally humidity) DataArrays into standardized HDP "measure" datasets that every downstream stage (threshold computation, metric computation) expects to consume. Its public surface is `format_standard_measures`, which accepts a list of temperature DataArrays and an optional relative-humidity DataArray, and returns a single merged `xarray.Dataset` where each variable carries the metadata contract that the rest of the package relies on.

The core workflow is: (1) validate and coerce inputs, (2) normalize temperature units to Celsius, (3) if humidity is supplied, derive a heat-index measure for each temperature measure, and (4) merge everything into one dataset with a description and history. Unit conversion is delegated to three small helpers (`kelvin_to_celsius`, `fahrenheit_to_celsius`, `celsius_to_fahrenheit`), all of which overwrite the `units` attribute and append a history note via `add_history`. Only `kelvin_to_celsius` is a true in-place mutation (it uses the augmented assignment `temp -= 273.15`); the two Fahrenheit helpers reassign `temp` to a newly computed array (`temp = (temp - 32) / 1.8` and `temp = (temp * 1.8) + 32`) rather than mutating the original DataArray in place. `convert_temp_units` dispatches among them based on the current `units` attribute; only the aliases `K`/`degK` and `F`/`degF` trigger conversion, while Celsius values (any of `C`, `degC`) pass through unchanged.

Unit validation is strict and test-sensitive. Every temperature input must carry a `units` attribute, and that value must be one of `TEMPERATURE_UNITS` (`['degC', 'degK', 'degF', 'C', 'K', 'F']`); otherwise an assertion raises with a message naming the offending variable. Humidity is similarly required to carry `units` in `['%', 'g/g']` and, if expressed as a mass fraction (`g/g`), is multiplied by 100 and relabeled `%` before use. The literal error string for a missing humidity `units` attribute is exactly `"Attribute 'units' not found in rh dataset."` (note the `rh` wording, distinct from the per-variable temperature message).

Heat index is computed only when `rh` is passed. For each temperature measure, the code converts the Celsius measure to Fahrenheit (`celsius_to_fahrenheit`), calls `apply_heat_index` with the (Fahrenheit) temperature and the (percent) humidity, then converts the result back to Celsius. `apply_heat_index` asserts that the temperature units are exactly `degF` and humidity units exactly `%` before dispatching; the actual vectorized math lives in a Numba-`vectorize`d scalar `heat_index` function implementing the National Weather Service regression (error ±1.3 °F). The Numba ufunc is invoked through `heat_index_map_wrapper`, which uses `xarray.apply_ufunc` with `dask="parallelized"`, empty input/output core dims, `output_dtypes=[np.float32]`, and `allow_rechunk: False`. Inputs are cast to `float32` before the ufunc runs.

Non-obvious contract details matter for downstream correctness. Only the raw temperature measures receive the full attribute contract: each gets `hdp_type: "measure"`, an `input_variable` name, and a `baseline_variable` name stamped onto its attributes, all set to the variable's own name. Heat-index measures do NOT carry `hdp_type` or `input_variable`, because `heat_index_map_wrapper` invokes `xarray.apply_ufunc` without `keep_attrs`, so the ufunc output drops all upstream attributes. After the ufunc returns, `apply_heat_index` renames the bare result to `"{temp_name}_hi"` (e.g. `temp_hi`) and sets only `baseline_variable` to that new name; the subsequent `fahrenheit_to_celsius` conversion adds the `units` attribute plus a history note. `format_standard_measures` always operates on deep copies and casts to `float32`, so the caller's arrays are never mutated. The final dataset merges all measures with `join="outer"`, discards per-variable attributes in favor of a single top-level `description` (embedding the HDP version) and `hdp_version`, and records an aggregation history listing every measure name. When heat index is requested, the returned dataset contains both the original temperature measure(s) and the derived heat-index measure(s), in that order.

#### Exact API Reference

#### `hdp.graphics.figure.compute_weighted_spatial_mean`

- **Import Path**: `from hdp.graphics.figure import compute_weighted_spatial_mean`
- **Signature**:

```python
def compute_weighted_spatial_mean(da)
```

#### `hdp.graphics.figure.get_metric_axis_label`

- **Import Path**: `from hdp.graphics.figure import get_metric_axis_label`
- **Signature**:

```python
def get_metric_axis_label(metric_name)
```

#### `hdp.graphics.figure.add_percentile_colorbar`

- **Import Path**: `from hdp.graphics.figure import add_percentile_colorbar`
- **Signature**:

```python
def add_percentile_colorbar(ax, percentiles)
```

#### `hdp.graphics.figure.get_metric_name`

- **Import Path**: `from hdp.graphics.figure import get_metric_name`
- **Signature**:

```python
def get_metric_name(metric_da)
```

#### `hdp.graphics.figure.get_unique_metric_names`

- **Import Path**: `from hdp.graphics.figure import get_unique_metric_names`
- **Signature**:

```python
def get_unique_metric_names(hw_ds)
```

#### `hdp.graphics.notebook.HDPNotebook`

- **Import Path**: `from hdp.graphics.notebook import HDPNotebook`
- **Signature**:

```python
class HDPNotebook:
    def create_section(self, section_name, label=None, rank=1, label_hidden=False)
    def add_markdown_cell(self, cell_data, section_name)
    def add_figure_cell(self, figure, section_name=None, alt_text='Figure')
    def set_section_label(section_name, section_label)
    def save_notebook(self, path, title=None)
```

#### `hdp.graphics.notebook.create_notebook`

- **Import Path**: `from hdp.graphics.notebook import create_notebook`
- **Required Test Import Paths**:
  - hdp.graphics.notebook.create_notebook
- **Exact Test Import Statements**:
  - from hdp.graphics.notebook import create_notebook
- **Signature**:

```python
def create_notebook(hw_ds)
```
- **Raises** (implementation must reproduce these exact messages):
  - `Missing 'hdp_type' attribute.`

#### `hdp.measure.heat_index_map_wrapper`

- **Import Path**: `from hdp.measure import heat_index_map_wrapper`
- **Signature**:

```python
def heat_index_map_wrapper(ds)
```

#### `hdp.measure.apply_heat_index`

- **Import Path**: `from hdp.measure import apply_heat_index`
- **Signature**:

```python
def apply_heat_index(temp: xarray.DataArray, rh: xarray.DataArray) -> xarray.DataArray
```
- **Behavior**: Calculates heat index from temperature and relative humidity DataArrays leveraging Dask.

#### `hdp.measure.format_standard_measures`

- **Import Path**: `from hdp.measure import format_standard_measures`
- **Required Test Import Paths**:
  - hdp.measure.format_standard_measures
- **Exact Test Import Statements**:
  - import hdp.metric
- **Signature**:

```python
def format_standard_measures(temp_datasets: list[xarray.DataArray], rh: xarray.DataArray=None) -> xarray.Dataset
```
- **Raises** (implementation must reproduce these exact messages):
  - `Attribute 'units' not found in rh dataset.`
- **Behavior**: Formats heat measure datasets (base inputs for heatwave diagnostics) for use within the HDP.

#### `hdp.threshold.compute_percentiles_wrapper`

- **Import Path**: `from hdp.threshold import compute_percentiles_wrapper`
- **Signature**:

```python
def compute_percentiles_wrapper(baseline_data, rolling_windows, percentiles)
```

#### `hdp.utils.get_time_stamp`

- **Import Path**: `from hdp.utils import get_time_stamp`
- **Signature**:

```python
def get_time_stamp()
```

#### `hdp.utils.get_version`

- **Import Path**: `from hdp.utils import get_version`
- **Signature**:

```python
def get_version()
```

#### `hdp.utils.get_func_description`

- **Import Path**: `from hdp.utils import get_func_description`
- **Signature**:

```python
def get_func_description(func)
```

#### `hdp.measure`

- **Import Path**: `from hdp import measure`
- **Required Test Import Paths**:
  - hdp.measure
- **Exact Test Import Statements**:
  - import hdp.measure
- **Kind**: module
- **Behavior**: Module required during hidden-test collection.

### Capability: Extreme heat threshold computation

## Purpose

The extreme-heat threshold capability turns baseline climate data (typically a control/warming daily time series on a lat/lon grid) into a seasonally-varying percentile threshold that later heatwave-metric code compares against. It answers: "for each day of the year, what temperature value is the P-th percentile of the historical distribution sampled in a window around that day?". The result is a Dataset keyed by `doy` and `percentile`, with spatial `lon` and `lat` coordinates, ready for `hdp.metric` to flag hot days.

## Component relationships and workflow

The public entry point is `compute_thresholds`, a thin wrapper that iterates over the variable names of a Dataset-like mapping, indexes each variable via `baseline_dataset[var_name]`, calls `compute_threshold` once per variable, and merges the resulting Datasets with `xarray.merge`. Most work happens inside `compute_threshold`.

`compute_threshold` orchestrates four distinct stages:

1. **Member flattening.** If the input has a `member` dimension (ensemble members), each member is selected, `drop_vars("member")` is applied, and members are concatenated along `time`. This is important: the final threshold has no `member` dimension; all members contribute samples to the same seasonal distribution.
2. **Window construction.** `datetimes_to_windows` (indirect helper) maps the time dimension to rolling windows of day-of-year indices. It groups every timestamp by its `dayofyr`, then for each unique day-of-year collects indices of that day plus `rolling_window_size` neighbors on either side, **wrapping circularly around the calendar year** (so late December samples borrow from early January and vice versa). The output is a 2-D integer array of shape `(n_unique_doy, (2*radius+1)*max_occurrences)`, padded with `-1` where a day-of-year occurs fewer times than the maximum.
3. **Guvectorized percentile reduction.** `compute_percentiles` is a `numba.guvectorize` ufunc with signature `(t),(d,b),(p)->(d,p)` operating on `float32` temperature input and `float64` output. For each `doy` row it gathers the windowed temperatures and applies `np.quantile` over the requested percentiles. It is applied via `compute_percentiles_wrapper`, an `xarray.apply_ufunc` call with `dask="parallelized"`, `input_core_dims=[["time"],["doy","t_index"],["percentile"]]`, `output_core_dims=[["doy","percentile"]]`, and `dask_gufunc_kwargs={"allow_rechunk": False}`.
4. **Dask block mapping.** Before reduction the data is `chunk(dict(time=-1))` and cast to `float32`. A `template` DataArray is built with `da.random.random` over the non-time dims plus `doy`/`percentile`, with the `doy` chunk forced to its full size and `percentile` to its full size. `xarray.map_blocks` then applies the wrapper lazily, with `keep_attrs` preserved from the wrapper.

## Ordering, defaults, and state

- `rolling_window_size` defaults to 7, meaning each window spans 15 day-of-year positions (7 before + center + 7 after).
- `percentiles` is coerced with `np.array(...)` and attached as a coordinate whose values equal the percentiles themselves (used later to look up a specific percentile level).
- The `doy` coordinate is always `np.arange(n_unique_doy)`, i.e. 0-based position into the sorted unique day-of-year set, NOT the literal day number. With a `noleap` calendar there are 365 unique days → `doy` spans 0..364.
- Output Dataset is named `{baseline_data.name}_threshold`. Its `lon` and `lat` coordinates are hardcoded from `threshold_da.lon.values` / `threshold_da.lat.values`; the baseline is expected to be a lat/lon grid, not an arbitrary spatial layout. `doy` carries `units="day_of_year"` plus a `baseline_calendar` attribute.

## Non-obvious / test-sensitive behavior

- **`no_season` and `fixed_value` are NOT implemented.** Both parameters are accepted and recorded into the Dataset attrs (`param_noseason`, `param_fixed_value`), but neither changes the numeric result. Passing them has no effect on the computed thresholds. Do not attempt to branch on them.
- The gufunc is compiled for `float32` input only; inputs are force-cast to `float32` regardless of their original dtype, and outputs are `float64`.
- `allow_rechunk=False` and the forced single `doy`/`percentile` chunks mean the reduction must not rechunk the `doy` axis; keep the template's chunk layout exactly as specified or Dask will error.
- Extensive metadata is written via `add_history` (from `hdp.utils`): a history line is appended (initializing history if absent), then a note about overwriting `long_name`, then a batch of threshold attributes (`baseline_variable`, `baseline_start_time`, `baseline_end_time`, `baseline_calendar`, `param_*`, and `hdp_type="threshold"`). Tests may assert on these attrs.
- `datetimes_to_windows` indexes by `dayofyr` (1-based, leap-aware). If a day-of-year appears with varying counts across years, rows are right-padded with `-1`. The `compute_percentiles` ufunc reads these `-1` sentinels verbatim as `temperatures[-1]` (NumPy wrapping), so padded slots DO contribute the last time index's temperature to the quantile rather than being skipped. In practice test fixtures use a uniform `noleap` calendar where every day-of-year occurs exactly once per year, so no padding arises; reimplementations should match this input shape rather than trying to special-case `-1`.

#### Exact API Reference

#### `hdp.graphics.figure.get_color_for_value`

- **Import Path**: `from hdp.graphics.figure import get_color_for_value`
- **Signature**:

```python
def get_color_for_value(cbar, value)
```
- **Behavior**: Get the color for a specific value from a colorbar.

#### `hdp.metric.build_doy_map`

- **Import Path**: `from hdp.metric import build_doy_map`
- **Signature**:

```python
def build_doy_map(times: np.ndarray) -> np.ndarray
```
- **Behavior**: Maps the time series index (key) to its respective day of the year (value).

#### `hdp.threshold.datetimes_to_windows`

- **Import Path**: `from hdp.threshold import datetimes_to_windows`
- **Signature**:

```python
def datetimes_to_windows(datetimes: np.ndarray, window_radius: int) -> np.ndarray
```
- **Behavior**: Generate rolling window sample of the day of year for each time index in the specified time series. Example below:

#### `hdp.threshold.compute_threshold`

- **Import Path**: `from hdp.threshold import compute_threshold`
- **Signature**:

```python
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
```
- **Behavior**: Computes percentile and, optionally, fixed value thresholds for a baseline measurements.

#### `hdp.threshold.compute_thresholds`

- **Import Path**: `from hdp.threshold import compute_thresholds`
- **Required Test Import Paths**:
  - hdp.threshold.compute_thresholds
- **Exact Test Import Statements**:
  - import hdp.metric
- **Signature**:

```python
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
```
- **Behavior**: Wrapper function for generating multiple thresholds with hdp.threshold.compute_threshold.

### Capability: Heatwave indexing and metric computation

This capability turns a heat measure (e.g. temperature or a heat index) and a matching extreme-heat threshold into the four core heatwave metrics: Heatwave Frequency (HWF), Heatwave Number (HWN), Heatwave Duration (HWD), and Heatwave Average (HWA). The computation is split into a small set of Numba-compiled kernels operating on flat 1-D time series, wrapped by Xarray/Dask layers that vectorize them over the gridded, percentile, and definition parameter space.

The heart of the pipeline is `compute_heatwave_metrics` (Numba `njit`), which performs four ordered steps per grid cell: (1) `indicate_hot_days` compares the measure against the threshold, selecting the threshold value by day-of-year via the `doy_map` (an index→day-of-year mapping built by `build_doy_map`, which is `dayofyr - 1`); (2) `index_heatwaves` labels each hot day with a non-zero event id; (3) the four metric kernels each count over `season_ranges`; (4) results are stacked into a leading `metric` axis of length 4 in the fixed order HWF, HWN, HWD, HWA (`output[0]=hwf, output[1]=hwn, output[2]=hwd, output[3]=hwa`).

`index_heatwaves` is the most test-sensitive function. It pads the input with a sentinel zero on each side, computes the diff to locate runs of hot days, then walks the run boundaries. A run opens a new event only if its length `>= min_duration`. `max_break` is the maximum gap *between* runs (gap strictly greater than `max_break` closes the current event), and `max_subs` is the maximum number of *subsequent* runs allowed to merge into the current event (the initial run is not counted toward `max_subs`). When `max_subs` is exhausted, a further run opens a new event only if it independently satisfies `min_duration`, otherwise the event closes. The returned array has length `len(hot_days_ts)` (the trailing padded element is trimmed) and uses 1-based integer event ids; `0` marks non-heatwave days.

The metric kernels each iterate over `season_ranges`, an `(n_seasons, 2)` array of `[start, end)` index pairs. HWF sums days with `hw_ts > 0`; HWN counts unique non-zero event ids via `np.unique`; HWD returns the maximum per-event length (`np.max`, 0 when no heatwave); HWA returns the mean per-event length (`np.mean`, 0 when no heatwave). `heatwave_average` computes this mean in float64 while the other three kernels produce int64. However, in `compute_heatwave_metrics` the results are stacked into `output = np.zeros((4,) + hwf.shape, dtype=nb.int64)` and `output[3] = hwa` assigns the float64 mean into an int64 slot, truncating it toward zero; the downstream `apply_ufunc` in the wrapper also declares `output_dtypes=[int]`. The HWA values actually delivered to users are therefore integer (the mean is floored/truncated), not float64. The `end` index is exclusive in HWF/HWN/HWD/HWA slicing (`hw_ts[start:end]`), but `get_range_indices` stores the index *of* the closing timestamp, so callers slice consistently with that convention.

`get_range_indices` walks a cftime time array and records the index of each season start (inclusive) and end (the index of the end timestamp). It is calendar-agnostic but wrong if the requested month/day exceed the calendar. For closed seasons the `end` index is recorded as the index where the end month/day is found, not one past it. However, when the time series ends while still searching for an end timestamp (`if not looking_for_start`), `ranges[-1, -1] = times.shape[0]` writes a one-past-the-last-valid-index (exclusive) value, and it writes it to the last row (index `num_years-1`) regardless of the current season counter `n`; this is a distinct, exclusive end-index convention applied only in the trailing incomplete-season case, and it can land on a row other than the one whose start was just recorded. `compute_hemisphere_ranges` builds two season tables—boreal `(5,1)→(10,1)` and austral `(11,1)→(4,1)`—then assigns each grid cell the north or south table based on `lat < 0`. Its leading/trailing trimming is imperfect: the loop assigns `slice_start = year_index` inside the `-1 in end_points` branch *before* `continue`, so `slice_start` ends up at the index of the LAST incomplete leading year rather than the first fully-populated year, and the subsequent slice `north_ranges[slice_start:slice_end]` therefore INCLUDES one incomplete leading year instead of trimming it (an off-by-one); the trailing side records the first incomplete year containing `-1` after the start has been identified. Its output is a DataArray with dims `(\"year\", \"end_points\", \"lat\", \"lon\")` where `end_points` holds `[\"start\", \"finish\"]` and `year` holds the sliced year integers.

`compute_individual_metrics` is the user-facing entry point. With `check_variables=True` it asserts the threshold carries `hdp_type == \"threshold\"`, that `baseline_variable` matches the measure, and that `baseline_calendar` matches `measure.time.values[0].calendar`. It builds a Dask template with dims ordered `[\"percentile\", \"definition\", <non-time measure dims>..., \"metric\", \"year\"]`, calls `xarray.map_blocks` (so the full time axis must reside in a single chunk), then splits the `metric` axis into four variables (HWF=0, HWN=1, HWD=2, HWA=3) and renames `year`→`time`, assigning cftime annual dates. `definition` coordinate values are the literal strings `\"{min_duration}-{max_break}-{max_subs}\"`. `include_threshold=True` (default) copies the threshold into the dataset under `threshold.name`. `compute_group_metrics` pairs every measure with every threshold sharing `baseline_variable`, calls `compute_individual_metrics` for each, and renames variables to `\"{measure}.{threshold}.{metric}\"` before merging; `include_threshold` defaults to `False` here so the threshold is excluded from the rename and merge.

#### Exact API Reference

#### `hdp.graphics.figure.plot_metric_parameter_comparison`

- **Import Path**: `from hdp.graphics.figure import plot_metric_parameter_comparison`
- **Signature**:

```python
def plot_metric_parameter_comparison(metric_da)
```
- **Behavior**: 4-panel plot of metric visualizing various comparisons of percentiles against the definitions.

#### `hdp.metric.get_range_indices`

- **Import Path**: `from hdp.metric import get_range_indices`
- **Signature**:

```python
def get_range_indices(times: np.ndarray, start: tuple, end: tuple) -> np.ndarray
```
- **Behavior**: Calculates the range of time indices to define each heatwave season for a given time series.

#### `hdp.metric.compute_hemisphere_ranges`

- **Import Path**: `from hdp.metric import compute_hemisphere_ranges`
- **Signature**:

```python
def compute_hemisphere_ranges(measure: xarray.DataArray) -> xarray.DataArray
```
- **Behavior**: 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).

#### `hdp.metric.compute_heatwave_metrics_wrapper`

- **Import Path**: `from hdp.metric import compute_heatwave_metrics_wrapper`
- **Signature**:

```python
def compute_heatwave_metrics_wrapper(measure, threshold, doy_map, hw_definitions)
```

#### `hdp.metric.compute_individual_metrics`

- **Import Path**: `from hdp.metric import compute_individual_metrics`
- **Signature**:

```python
def compute_individual_metrics(measure: xarray.DataArray, threshold: xarray.DataArray, hw_definitions: list, include_threshold: bool=True, check_variables: bool=True) -> xarray.Dataset
```
- **Behavior**: Computes HWN, HWF, HWD, and HWA heatwave metrics for an individual parameter configuration of measure, threshold, and definition.

#### `hdp.metric.compute_group_metrics`

- **Import Path**: `from hdp.metric import compute_group_metrics`
- **Required Test Import Paths**:
  - hdp.metric.compute_group_metrics
- **Exact Test Import Statements**:
  - import hdp.metric
- **Signature**:

```python
def compute_group_metrics(measures: xarray.Dataset, thresholds: xarray.Dataset, hw_definitions: list, include_threshold: bool=False, check_variables: bool=True) -> xarray.Dataset
```

#### `hdp.metric.heatwave_average`

- **Import Path**: `from hdp.metric import heatwave_average`
- **Required Test Import Paths**:
  - hdp.metric.heatwave_average
- **Exact Test Import Statements**:
  - from hdp.metric import heatwave_average
- **Kind**: function
- **Signature**:

```python
def heatwave_average(hw_ts: np.ndarray, season_ranges: np.ndarray) -> np.ndarray
```
- **Behavior**: Measures the average length of all heatwaves in each season of a given heatwave index time series.

#### `hdp.metric.heatwave_duration`

- **Import Path**: `from hdp.metric import heatwave_duration`
- **Required Test Import Paths**:
  - hdp.metric.heatwave_duration
- **Exact Test Import Statements**:
  - from hdp.metric import heatwave_duration
- **Kind**: function
- **Signature**:

```python
def heatwave_duration(hw_ts: np.ndarray, season_ranges: np.ndarray) -> np.ndarray
```
- **Behavior**: Measures the length of the longest heatwave in each season of a given heatwave index time series.

#### `hdp.metric.heatwave_frequency`

- **Import Path**: `from hdp.metric import heatwave_frequency`
- **Required Test Import Paths**:
  - hdp.metric.heatwave_frequency
- **Exact Test Import Statements**:
  - from hdp.metric import heatwave_frequency
- **Kind**: function
- **Signature**:

```python
def heatwave_frequency(hw_ts: np.ndarray, season_ranges: np.ndarray) -> np.ndarray
```
- **Behavior**: Measures the number of heatwave days in each season of a given heatwave index time series.

#### `hdp.metric.heatwave_number`

- **Import Path**: `from hdp.metric import heatwave_number`
- **Required Test Import Paths**:
  - hdp.metric.heatwave_number
- **Exact Test Import Statements**:
  - from hdp.metric import heatwave_number
- **Kind**: function
- **Signature**:

```python
def heatwave_number(hw_ts: np.ndarray, season_ranges: np.ndarray) -> np.ndarray
```
- **Behavior**: Measures the number of heatwaves (by event, not days) in each season of a given heatwave index time series.

#### `hdp.metric.index_heatwaves`

- **Import Path**: `from hdp.metric import index_heatwaves`
- **Required Test Import Paths**:
  - hdp.metric.index_heatwaves
- **Exact Test Import Statements**:
  - from hdp.metric import index_heatwaves
- **Kind**: function
- **Signature**:

```python
def index_heatwaves(hot_days_ts: np.ndarray, min_duration: int, max_break: int, max_subs: int) -> np.ndarray
```
- **Behavior**: Identifies the heatwaves in the timeseries using the specified heatwave definition

### Capability: Summary figure generation

# Summary Figure Generation

The summary-figure capability produces publication-style matplotlib figures that visualize heatwave metrics spatially, temporally, and across the heatwave parameter space (percentile thresholds, heatwave definitions, and ensemble members). It is the terminal step of the HDP workflow: metric `DataArray`s/Datasets produced by `metric.py` are passed here to be reduced, projected onto maps, and rendered as multi-panel figures.

The two low-level helpers are the foundation for everything else. `convert_axis_to_map(ax)` takes a plain cartesian `Axes` and returns a *new* `Axes` registered on the same figure at the same position but carrying a `WinkelTripel()` projection with `zorder=-1`. It hides the original axis spines, tick labels, and grid first, then re-adds a projected axes **behind** the existing axes so the map content sits underneath. Callers must rebind the return value (e.g. `ax = convert_axis_to_map(ax)`), because the old axes object is effectively discarded. `WinkelTripel` subclasses Cartopy's `_WarpedRectangularProjection`, sets `proj4_params=[('proj','wintri'), ...]`, uses a WGS84 globe by default, and exposes a `threshold` property returning `1e4`. `add_four_panel(figure)` builds a 2x2 `GridSpec`, returns a length-4 list of axes, and pre-populates placeholder titles/axis labels that callers later overwrite.

`plot_map(metric_da, ax, cmap="hot")` renders a filled contour over coastlines. It transposes the data so `lon` is last, wraps longitude with `add_cyclic_point`, and draws `contourf` in `PlateCarree` coordinates onto the (already projected) map axes, returning the contour artist for later colorbar attachment. It assumes `lat`/`lon` are dimension coordinate names.

The higher-level functions share a common shape: call `generate_base_figure()`, build four panels with `add_four_panel`, reduce dimension coordinates via `.mean()`/`.std()`, then decorate. `plot_metric_decadal_maps` groups time into decadal ranges via `get_decadal_ranges` (floor/ceil of first/last year to decade boundaries, then 10-year bins `(start, start+9)`), slices each with `cftime.datetime`, and produces **one figure per four decades** (`ceil(num_decades/4)`), averaging any `member`/`percentile`/`definition` dims first and appending "Ens."/"Perc."/"Def." to the panel title. `plot_metric_timeseries` and `plot_metric_parameter_comparison` both compute the latitude-weighted spatial mean with `compute_weighted_spatial_mean` (weighted by `cos(latitude)` over `lat`/`lon`), with the latter producing a 2D `pcolormesh` heatmap of definition-vs-percentile plus zonal, map, and standard-deviation panels. `plot_multi_measure_metric_comparisons` reduces a whole `Dataset` to its first four unique metric names (`get_unique_metric_names`), plots each as a line series labeled by measure (the `split('.')[0]` prefix).

Key non-obvious behaviors. First, metric names are encoded by dotted convention `{measure}.{threshold}.{metric}`; `get_metric_name` parses the third dot-separated token and raises `ValueError` if fewer than three segments are present — so variable naming is load-bearing. Second, **every** plotting function calls `plt.close(fig)` before returning the `Figure` object; tests must capture the returned figure rather than rely on `plt.gcf()`, and the style sheet is applied only inside `generate_base_figure`. Third, `add_percentile_colorbar` is defined twice in `figure.py`; the second definition (autumn colormap, ticks shifted by `+0.5`, `vmin=0, vmax=len`) is the one in effect at runtime. Colorbar label orientation uses `rotation=270` with `labelpad`, and the percentile colorbar is indexed by integer position (0, 1, ...) while displaying rounded percentile values.

Ordering and state: `convert_axis_to_map` must be applied to an axis before `plot_map` is called on it, and the returned projected axes must be rebound. The `metric_da` passed to the decadal/timeseries/parameter functions is not mutated in place except for local reassignment after dimension reductions; reductions always collapse `member` before `percentile`/`definition`, and the timeseries standard-deviation panels use `.std` across the *collapsed* dimension rather than a raw standard deviation. Datasets with an ensemble `member` dimension trigger different panel titles ("Spatial-Ens-...") than single-realization inputs.

#### Exact API Reference

#### `hdp.graphics.figure.convert_axis_to_map`

- **Import Path**: `from hdp.graphics.figure import convert_axis_to_map`
- **Signature**:

```python
def convert_axis_to_map(ax)
```

#### `hdp.graphics.figure.add_four_panel`

- **Import Path**: `from hdp.graphics.figure import add_four_panel`
- **Signature**:

```python
def add_four_panel(figure)
```

#### `hdp.graphics.figure.plot_map`

- **Import Path**: `from hdp.graphics.figure import plot_map`
- **Signature**:

```python
def plot_map(metric_da, ax, cmap='hot')
```

#### `hdp.graphics.figure.plot_multi_measure_metric_comparisons`

- **Import Path**: `from hdp.graphics.figure import plot_multi_measure_metric_comparisons`
- **Signature**:

```python
def plot_multi_measure_metric_comparisons(hw_ds)
```
- **Behavior**: 4-panel plot of time-evolution of heatwave metrics accross multiple measures.

#### `hdp.graphics.winkel_tripel.WinkelTripel`

- **Import Path**: `from hdp.graphics.winkel_tripel import WinkelTripel`
- **Signature**:

```python
class WinkelTripel:
    def threshold(self)
```
- **Behavior**: Winkel-Tripel projection implementation for Cartopy

## Detailed Implementation Nodes

### Node: Data generation and unit conversion utilities

**Constraints.**
- Time axis: `xarray.date_range(start, end, freq="D", calendar="noleap", use_cftime=True)`; dims strictly `("lon", "lat", "time")` with `lon=linspace(-180,180,grid_shape[0])`, `lat=linspace(-90,90,grid_shape[1])`, name `"test_temperature_data"`, `units="degC"`, chunked `(time=-1, lat=2, lon=2)`.
- Seasonal cycle `20 + 2*sin(2π*(phase + arange(N))/365)`, phase `270` north / `90` south split at `lat//2`; subtract `10*|lat|/90`; noise via `np.random.seed(seed)` then `random(shape)*(std/2)`.
- Warming: add `arange(N)/(365*warming_period)` over `time`; RH: `abs(base/base.max()-0.3)`, name `"test_rh_data"`, `units="g/g"`, range `[0,1]`.
- `fahrenheit_to_celsius` / `celsius_to_fahrenheit`: single-unit temperature converters between Fahrenheit and Celsius; `convert_temp_units` determines and converts temperature units to degrees Celsius (specific mapping unverified).

**Example.**
```python
import hdp.utils

control = hdp.utils.generate_test_control_dataarray(grid_shape=(2, 3))
warming = hdp.utils.generate_test_warming_dataarray(grid_shape=(2, 3))
rh = hdp.utils.generate_test_rh_dataarray(grid_shape=(2, 3))

assert control.name == warming.name == "test_temperature_data"
assert control.attrs["units"] == warming.attrs["units"] == "degC"
assert rh.attrs["units"] == "g/g"
assert rh.max() <= 1 and rh.min() >= 0
```

### Node: Heat measure formatting and heat index computation

Implement `format_standard_measures` as a pure function over deep copies: for each temperature DataArray, cast to `float32`, assert a `units` attr in `TEMPERATURE_UNITS`, stamp `hdp_type="measure"` plus `input_variable`/`baseline_variable` = the variable name, then convert to Celsius (K→C subtract 273.15, F→C `(x-32)/1.8`, C passes through). If `rh` is given, normalize `g/g`→`%` (×100), then for each measure produce a heat-index variable by F→C-round-tripping: convert to Fahrenheit, apply the Numba-vectorized `heat_index` ufunc via `xarray.apply_ufunc(dask="parallelized", output_dtypes=[np.float32], allow_rechunk=False)`, rename to `{name}_hi`, and set `baseline_variable` to that new name. Because `apply_ufunc` runs without `keep_attrs`, the heat-index output drops `hdp_type` and `input_variable`; only `baseline_variable` (plus later `units`/history) survives. Merge all measures `join="outer"`, set a top-level `description`/`hdp_version`, and append history. The `heat_index` scalar implements the NWS regression: a 0.5-weighted midpoint formula that, when the result exceeds 80, is replaced by the full 9-term polynomial with two conditional humidity/temperature adjustments.

Example:
```python
import hdp.measure, hdp.utils
t = hdp.utils.generate_test_control_dataarray(grid_shape=(2, 3)).rename("temp")
rh = hdp.utils.generate_test_rh_dataarray(grid_shape=(2, 3)).rename("rh")
ds = hdp.measure.format_standard_measures([t], rh=rh)
# ds contains 'temp' and 'temp_hi', both in degC; 'temp' has hdp_type=='measure', 'temp_hi' has only baseline_variable
```

### Node: Extreme heat threshold computation

## Functional constraints

- `compute_thresholds` takes a Dataset-like mapping (e.g. `xarray.Dataset`), not a plain list. It iterates `for var_name in baseline_dataset` and indexes `baseline_dataset[var_name]` for each variable, calling `compute_threshold` on each and merging results with `xarray.merge`. Passing a list will fail (iterating yields `DataArray` objects, then `list[DataArray]` indexing raises).
- `datetimes_to_windows(datetimes, window_radius)` returns a 2-D `int` array of shape `(n_unique_dayofyr, (2*radius+1) * max_count_per_dayofyr)`; group timestamps by `dayofyr`, gather each unique day plus `radius` neighbors on both sides, wrapping the year circularly; pad shorter rows with `-1`.
- `compute_percentiles` is a `numba.guvectorize` with signature `(t),(d,b),(p)->(d,p)`, `float32` in / `float64` out; per `doy` row, gather `temperatures[window_samples[doy]]` and write `np.quantile(doy_temps, percentiles)` to `output[doy]`.
- `compute_threshold`: flatten `member` dim by concatenation along `time`; `chunk(time=-1)` and `.astype(float32)`; build `rolling_windows` (coords `doy`,`t_index`) and `percentiles` (coord = its own values); construct a lazy `template` with `da.random.random` over non-time dims + `doy` + `percentile`, single-chunked on `doy`/`percentile`; apply via `map_blocks` + `apply_ufunc(dask="parallelized", allow_rechunk=False)`; name output var `{name}_threshold`; set `doy` units to `day_of_year`. The output Dataset hardcodes `lon` and `lat` coordinates (from `threshold_da.lon.values` / `threshold_da.lat.values`), so the baseline must be a lat/lon grid.
- `no_season` and `fixed_value` only populate `param_noseason`/`param_fixed_value` attrs; they must NOT alter computation.

## Usage example

```python
import numpy as np, xarray, hdp.threshold as t
from hdp.utils import generate_test_control_dataarray
baseline = generate_test_control_dataarray()  # dims lon,lat,time; noleap
ds = t.compute_thresholds(
    xarray.Dataset({"baseline": baseline}),
    percentiles=np.array([0.5, 0.9, 0.99]),
    rolling_window_size=7,
)
# ds["baseline_threshold"] dims: (lon, lat, doy, percentile)
print(ds["doy"].size)  # 365 for a noleap calendar
```

### Node: Heatwave indexing and metric computation

Re-implement the following invariants exactly:

- `index_heatwaves(hot_days_ts, min_duration, max_break, max_subs)` returns an int64 array of the same length as `hot_days_ts`, 1-based event ids, 0 for non-heatwave days. It must pad with a zero sentinel on both ends, use `np.diff` to find run boundaries, and enforce: new event only when a run `>= min_duration`; gap `> max_break` closes; at most `max_subs` subsequent runs merge before forcing a new (or closed) event.
- Metric kernels take `(hw_ts, season_ranges)` with `season_ranges` shape `(N,2)` of `[start, end)` index pairs. HWF = sum of `hw_ts>0`; HWN = count of unique nonzero ids; HWD = max event length; HWA = mean event length. `heatwave_average` computes HWA in float64, but `compute_heatwave_metrics` stacks results into `np.zeros((4,) + hwf.shape, dtype=nb.int64)` and assigns `output[3] = hwa`, truncating the float64 mean toward zero, so the delivered HWA is int64 (floored/truncated), not float64. Empty seasons yield 0.
- `get_range_indices` returns int `(n_years, 2)` initialized to `-1`; start index inclusive, end index = index of the end timestamp for closed seasons. When a season is still open at the end of the time array, the end index is set to `times.shape[0]` (exclusive, one past the last index) on the final row (`ranges[-1, -1]`), regardless of the current season counter.
- `compute_heatwave_metrics` stacks results in order `[HWF, HWN, HWD, HWA]` on a leading axis of length 4.
- `build_doy_map` returns `time.dayofyr - 1` per timestep.
- `compute_individual_metrics` output uses `metric` axis (0..3) later split into HWF/HWN/HWD/HWA; `year` renamed to `time`; `definition` coord = `\"{min}-{break}-{subs}\"`. The leading trim in `compute_hemisphere_ranges` is off-by-one: `slice_start` is set to the index of the last incomplete leading year, so one incomplete year remains at the start of the trimmed output.

```python
from hdp.metric import compute_individual_metrics
metrics = compute_individual_metrics(
    measure, threshold, hw_definitions=[(3, 2, 1)],
    include_threshold=True, check_variables=True,
)
# metrics[\"HWN\"]: heatwave event count per season, dims (percentile, definition, lat, lon, time)
```

### Node: Summary figure generation

# Summary Figure Generation — Implementation Constraints

- `convert_axis_to_map(ax)` returns a **new** projected axes; always rebind the return value and never reuse the original `ax` afterward.
- `WinkelTripel` sets `proj4_params` to `wintri` with a WGS84 globe default and returns `1e4` from its `threshold` property.
- `plot_map` transposes `lon` last, wraps via `add_cyclic_point`, and draws `contourf` in `PlateCarree`; returns the contour artist for colorbar attachment.
- Metric names must follow `{measure}.{threshold}.{metric}`; `get_metric_name` splits on `.` and raises `ValueError` on fewer than three tokens.
- Every figure function calls `plt.close(fig)` before returning `fig`; capture the return value, never `plt.gcf()`.
- Spatial reductions use cosine-latitude weighting (`compute_weighted_spatial_mean`).
- `add_percentile_colorbar` is defined twice; the effective version uses the `autumn` colormap with ticks shifted `+0.5` and `vmin=0, vmax=len(percentiles)`.
- Decadal maps emit `ceil(num_decades/4)` figures; reduce `member`/`percentile`/`definition` dims before slicing.

```python
from hdp.graphics import figure

# Build a projected map in one panel
f = figure.generate_base_figure()
axes = figure.add_four_panel(f)
ax = figure.convert_axis_to_map(axes[0])   # rebind the returned axes
contour = figure.plot_map(metric_da, ax)    # metric_da has lat/lon coords
cbar = f.colorbar(contour, location="bottom", anchor=(0.0, 0.0), pad=0)
fig = figure.plot_metric_timeseries(metric_da)  # returns closed Figure
```

## Install / Reconstruction Contract

Follow this contract before implementing the documented APIs:
- **Project root**: `/workspace/repo` at runtime; the submitted repository root is `.`.
- **Package/distribution name**: `HDP_python`
- **Package roots**: `.`
- **Install strategy**: `editable-install`
- **Import/entry**: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package.
- **Provision commands**:
  ```bash
  python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbic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A9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))'
programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; }
export -f programgen_pip_install
  programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel
  programgen_pip_install python3 -m pip install setuptools setuptools-scm
  (
programgen_install_report="$(mktemp)"
trap 'rm -f "$programgen_install_report"' EXIT
SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report"
python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n    metadata=item.get('"'"'metadata'"'"', {})\n    name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n    provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n    selected={'"'"''"'"'} | (provided & requested)\n    parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n    while True:\n        added=set()\n        for requirement in parsed:\n            if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n                continue\n            if canonicalize_name(requirement.name)==name:\n                if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n                    raise ValueError('"'"'local extra requires a different target distribution'"'"')\n                extras={canonicalize_name(value) for value in requirement.extras}\n                if not extras <= provided:\n                    raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n                added.update(extras - selected)\n        if not added:\n            break\n        selected.update(added)\n    for requirement in parsed:\n        if canonicalize_name(requirement.name)==name:\n            continue\n        if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n            requirement.marker=None\n            requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report"
)
  ```
- **Runtime setup**:
  ```bash
  {
    [ -e "$PWD"/README.md ] || { mkdir -p "$(dirname "$PWD"/README.md)"; : > "$PWD"/README.md; };
    SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps;
  }
  ```
- **Project root for installation**: `.`
- **Build-version environment**: `SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0`, `PDM_BUILD_SCM_VERSION=0.0.0`, `POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0`, `UV_DYNAMIC_VERSIONING_BYPASS=0.0.0`
- **Test directory**: `hdp/tests`
- **Test command**: `python3 -m pytest -vv --continue-on-collection-errors -o 'addopts=-p no:cacheprovider' hdp/tests/test_heatwave_average.py hdp/tests/test_heatwave_duration.py hdp/tests/test_heatwave_frequency.py hdp/tests/test_heatwave_number.py hdp/tests/test_index_heatwaves.py hdp/tests/test_utils.py hdp/tests/test_workflow.py`
- **Test startup**: run the exact test command above from the project root after installation; hidden tests are injected separately.