climate_data
Climate Data
This package contains modules for extracting, processing, harmonizing, and downscaling climate data. It sources historical climate data from the European Centre for Medium-Range Weather Forecasts (ECMWF) ERA5 dataset and future climate data from the Coupled Model Intercomparison Project Phase 6 (CMIP6).
aggregate
hierarchy
Runner for the collate stage of the climate aggregates pipeline.
This module provides functions to collate block-level datasets into measure-level datasets. The compilation process: 1. Loads raw results from all blocks for a given hierarchy, measure, and scenario 2. Aggregates the data up the location hierarchy 3. Produces views for subset hierarchies 4. Saves the results as measure-level datasets
hierarchy(agg_version: str, hierarchy: list[str], agg_measure: list[str], agg_scenario: list[str], population_model_dir: str, output_dir: str, queue: str, dry_run: bool) -> None
Collate block-level datasets into measure-level datasets.
This command: 1. Identifies which combinations of hierarchy, measure, and scenario need compilation 2. Creates parallel jobs to collate each combination 3. Runs the jobs using jobmon
Source code in src/climate_data/aggregate/hierarchy.py
hierarchy_main(agg_version: str, hierarchy: str, measure: str, scenario: str, population_model_dir: str, output_dir: str, *, progress_bar: bool = False) -> None
Collate block-level datasets into measure/scenario-level datasets.
This function: 1. Loads all block-level datasets for a given hierarchy, measure, and scenario 2. Combines them into a single dataset 3. Aggregates the data up the location hierarchy 4. Produces views for subset hierarchies 5. Saves the results as measure-level datasets
Parameters
agg_version The version identifier hierarchy The full aggregation hierarchy to process measure The climate measure to process scenario The climate scenario to process population_model_dir Path to the population model directory output_dir Path to save results progress_bar Whether to show a progress bar
Source code in src/climate_data/aggregate/hierarchy.py
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 | |
hierarchy_task(agg_version: str, hierarchy: str, agg_measure: str, agg_scenario: str, population_model_dir: str, output_dir: str, *, progress_bar: bool) -> None
Collate block-level datasets into measure-level datasets.
This command collates results for a specific hierarchy, measure, and scenario.
Source code in src/climate_data/aggregate/hierarchy.py
pixel
utils
aggregate_climate_to_hierarchy(data: pd.DataFrame, hierarchy: pd.DataFrame) -> pd.DataFrame
Create all aggregate climate values for a given hierarchy from most-detailed data.
Parameters
data The most-detailed climate data to aggregate. hierarchy The hierarchy to aggregate the data to.
Returns
pd.DataFrame The climate data with values for all levels of the hierarchy.
Source code in src/climate_data/aggregate/utils.py
blocks_with_shapefile_intersections(hierarchy: str, pm_data: PopulationModelData, modeling_frame: gpd.GeoDataFrame | None = None) -> set[str]
Return the block_keys whose footprint intersects the hierarchy's raking shapes.
Blocks whose (dissolved) modeling-frame geometry intersects no raking polygon
contribute only empty rows to the sum/sum aggregation, so the pipeline can skip
them. The shapefile lookup is delegated to
PopulationModelData.load_raking_shapes, which routes to the right file for
whichever hierarchy is in use.
.. note::
This uses the block *geometry* vs the full shape set, whereas the production
emptiness gate in ``build_location_masks`` uses the raster *bounding box* vs
bbox-filtered shapes. Equivalence was validated empirically for ``lsae_1285``
(bit-for-bit identical output) but is frame/hierarchy-dependent — re-validate
if the modeling frame or a hierarchy's shapes change.
Parameters
hierarchy
The full aggregation hierarchy whose raking shapes gate the blocks.
pm_data
PopulationModelData used to load the raking shapes (and the modeling frame
when one is not supplied).
modeling_frame
Optional pre-loaded modeling frame. Loaded via
pm_data.load_modeling_frame() when None; pass the already-loaded
frame to avoid a redundant re-read.
Returns
set[str] The block_keys with at least one intersecting raking polygon.
Raises
ValueError If no block intersects any raking shape while blocks exist — a likely CRS/shapefile misconfiguration that would otherwise silently skip everything.
Source code in src/climate_data/aggregate/utils.py
build_bounds_map(raster_template: rt.RasterArray, shape_values: list[tuple[Polygon | MultiPolygon, int]]) -> dict[int, tuple[slice, slice]]
Build a map of location IDs to buffered slices of the raster template.
Parameters
raster_template The raster template to build the bounds map for. shape_values A list of tuples where the first element is a shapely Polygon or MultiPolygon in the CRS of the raster template and the second element is the location ID of the shape.
Returns
dict[int, tuple[slice, slice]] A dictionary mapping location IDs to a tuple of slices representing the bounds of the location in the raster template. The slices are buffered by 10 pixels to ensure that the entire shape is included in the mask.
Source code in src/climate_data/aggregate/utils.py
build_location_masks(hierarchy: str, block_key: str, pm_data: PopulationModelData) -> tuple[dict[str, slice], dict[int, tuple[slice, slice, npt.NDArray[np.bool_]]], npt.NDArray[np.uint32]]
Build location masks for each location in the hierarchy.
Parameters
hierarchy The name of the hierarchy to build location masks for. Must be one of of the keys of the HIERARCHY_MAP constant. pm_data PopulationModelData object to load the population model data.
Returns
tuple[dict[str, slice], dict[int, tuple[slice, slice, npt.NDArray[np.bool_]]], npt.NDArray[np.uint32]] A three-tuple of: - climate_slice: a dict mapping "longitude"/"latitude" to slices bounding the location block, for subsetting climate rasters before processing (downstream operations scale with the number of pixels in the mask). - bounds_map: a dict mapping each location ID to (row_slice, col_slice, mask), where mask is a boolean array selecting that location's pixels within the sliced window. - location_mask: a 2D uint32 array where each location ID is written as a unique integer value.
Source code in src/climate_data/aggregate/utils.py
get_bbox(raster: rt.RasterArray, crs: str | None = None) -> shapely.Polygon
Get the bounding box of a raster array.
Parameters
raster The raster array to get the bounding box of. crs The CRS to return the bounding box in. If None, the bounding box is returned in the CRS of the raster.
Returns
shapely.Polybon The bounding box of the raster in the CRS specified by the crs parameter.
Source code in src/climate_data/aggregate/utils.py
cli
cdrun() -> None
cli_options
Climate Data CLI Options
This module provides a set of CLI options for extracting climate data from the ERA5 and CMIP6 datasets. These options are used to specify the data to extract, such as the year, month, variable, and dataset. It also provides global variables representing the full space of valid values for these options.
resolve_run_mode_root(param_name: str, value: str, run_mode: str, *, aggregate: bool = False) -> str
Resolve a directory option to the run-mode root unless the user overrode it.
--run-mode selects the storage-root profile; an explicitly-passed
--<param> still wins (detected via click's parameter source).
Source code in src/climate_data/cli_options.py
with_agg_measure(*, allow_all: bool = False) -> Callable[[Callable[P, T]], Callable[P, T]]
Add aggregation measure option to a command.
Source code in src/climate_data/cli_options.py
with_agg_scenario(*, allow_all: bool = False) -> Callable[[Callable[P, T]], Callable[P, T]]
Add aggregation scenario option to a command.
Source code in src/climate_data/cli_options.py
with_agg_version() -> Callable[[Callable[P, T]], Callable[P, T]]
Add aggregation version option to a command.
with_block_key(*, allow_all: bool = False) -> Callable[[Callable[P, T]], Callable[P, T]]
Add block key option to a command.
Source code in src/climate_data/cli_options.py
with_concurrency_limit(*, default: int | None = None) -> Callable[[Callable[P, T]], Callable[P, T]]
Add the jobmon concurrency-limit option to a command.
Pass default to throttle a runner out of the box; leaving it unset means
the option defaults to None, which run_parallel_maybe_dry_run drops
so jobmon applies its own default (10000, effectively unthrottled).
Source code in src/climate_data/cli_options.py
with_debias_method() -> Callable[[Callable[P, T]], Callable[P, T]]
Add the option selecting the Jensen de-bias applied to a multiplicative anomaly.
Source code in src/climate_data/cli_options.py
with_dry_day_rule() -> Callable[[Callable[P, T]], Callable[P, T]]
Add the option selecting how days the driving model reports as dry are treated.
Source code in src/climate_data/cli_options.py
with_dry_run() -> Callable[[Callable[P, T]], Callable[P, T]]
Add dry-run flag to a command.
Source code in src/climate_data/cli_options.py
with_hierarchy(choices: Collection[str] = cdc.HIERARCHY_MAP, *, allow_all: bool = False, default: str | None = None) -> Callable[[Callable[P, T]], Callable[P, T]]
Add hierarchy option to a command.
Pass default to give the (single-value) option a default; this builds
the option directly since with_choice always supplies its own default.
Source code in src/climate_data/cli_options.py
with_location_id() -> Callable[[Callable[P, T]], Callable[P, T]]
Add location ID option to a command.
with_run_mode() -> Callable[[Callable[P, T]], Callable[P, T]]
Add the run-mode option selecting the storage-root profile.
Source code in src/climate_data/cli_options.py
with_year(years: Collection[str], *, allow_all: bool = False) -> Callable[[Callable[P, T]], Callable[P, T]]
Create a CLI option for selecting a year.
Source code in src/climate_data/cli_options.py
constants
aggregate_root(run_mode: str) -> Path
Aggregation working directory for the given run mode.
Source code in src/climate_data/constants.py
model_root(run_mode: str) -> Path
Downscaling working directory for the given run mode.
Source code in src/climate_data/constants.py
data
Climate Data Management
This module provides a class for managing the climate data used in the project. It includes methods for loading and saving data, as well as for accessing the various directories where data is stored. This abstraction allows for easy access to the data and ensures that all data is stored in a consistent and organized manner. It also provides a central location for managing the data, which makes it easier to update and maintain the path structure of the data as needed.
This module generally does not load or process data itself, though some exceptions are made for metadata which is generally loaded and cached on disk.
The main classes are: - PopulationModelData: Handles data from the gridded population modeling pipeline. This includes population estimates and projections as well as the location hierarchies for the population data. This class provides read-only access to the data. - ClimateData: Handles gridded climate data from the climate downscaling pipeline. This includes climate data for different scenarios and measures. This class provides read and write access to the data. - ClimateAggregateData: Handles the output data structure for climate aggregates. This includes raw results at the block level, final results at the measure level, and versioned results for different pipeline versions. This class provides both read and write access to the data.
ClimateAggregateData
Manages the output data structure for climate aggregates.
This class manages the file organization and paths for: 1. Reading and writing raw results at block level 2. Reading and writing final results at measure and scenario level 3. Versioning of results
Source code in src/climate_data/data.py
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 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 | |
logs: Path
property
Get the directory for log files.
root: Path
property
Get the root directory for model data.
__init__(root: str | Path = cdc.AGGREGATE_ROOT, *, read_only: bool = False) -> None
Initialize the climate aggregate data manager.
Parameters
root
Path to the model root directory
read_only
If True, do not create the root or logs directories. Use this for
path construction and reads (including dry runs), so merely building a
manager never writes to shared storage.
Source code in src/climate_data/data.py
compiled_person_days_path(subset_hierarchy: str, scenario: str, gcm_member: str) -> Path
Path to a compiled (hierarchy-aggregated) person-days file.
Source code in src/climate_data/data.py
diagnostics_root(version: str, hierarchy: str) -> Path
Get the path to the diagnostics directory.
Parameters
version The version identifier
Returns
Path The path to the diagnostics directory
Source code in src/climate_data/data.py
load_person_days(block_key: str, scenario: str, gcm_member: str) -> pd.DataFrame
Load a raw per-block person-days file.
load_population(version: str, hierarchy: str, location_id: int | None = None) -> pd.DataFrame
Load population data for a specific hierarchy and optionally location.
Parameters
version The version identifier hierarchy The location hierarchy location_id If provided, load only data for this location
Returns
pd.DataFrame The population data
Source code in src/climate_data/data.py
load_raw_results(version: str, hierarchy: str, block_key: str, draw: str, measure: str | None = None, scenario: str | None = None) -> pd.DataFrame
Load raw results for a specific hierarchy, block, and draw.
Parameters
version The version identifier hierarchy The location hierarchy block_key The block key draw The draw of the climate data to load (e.g. "000") measure If provided, filter results to only include this measure scenario If provided, filter results to only include this scenario
Returns
pd.DataFrame The raw results
Source code in src/climate_data/data.py
load_results(version: str, hierarchy: str, scenario: str, measure: str, location_id: int | None = None) -> pd.DataFrame
Load final results for a specific scenario and measure.
Parameters
version The version identifier hierarchy The location hierarchy scenario The climate scenario measure The climate measure location_id If provided, load only data for this location
Returns
pd.DataFrame The results
Source code in src/climate_data/data.py
log_dir(step_name: str) -> Path
Get the directory for logs from a specific pipeline step.
Parameters
step_name The name of the pipeline step
Returns
Path The directory for step-specific logs
Source code in src/climate_data/data.py
person_days_path(block_key: str, scenario: str, gcm_member: str) -> Path
Path to a raw per-block person-days file.
Different GBD vintages (gbd_2021/2023/2025, which have different location
sets) are kept apart by the versioned root (<output_dir>/<hierarchy>,
e.g. .../aggregates/gbd_2023), mirroring the aggregate stage's
version_root convention -- not by a segment in this path. The special
runners build that root by appending hierarchy to output_dir.
Source code in src/climate_data/data.py
population_path(version: str, hierarchy: str) -> Path
Get the path to population data for a specific hierarchy.
Parameters
version The version identifier hierarchy The location hierarchy
Returns
Path The path to the population data file
Source code in src/climate_data/data.py
raw_results_path(version: str, hierarchy: str, block_key: str, draw: str) -> Path
Get the path to raw results for a specific hierarchy, block, and draw.
Parameters
version The version identifier hierarchy The location hierarchy block_key The block key draw The draw of the climate data (e.g. "000")
Returns
Path The path to the raw results file
Source code in src/climate_data/data.py
raw_results_root(version: str) -> Path
Get the directory for raw results (block-level).
Parameters
version The version identifier
Returns
Path The directory for raw results
Source code in src/climate_data/data.py
results_path(version: str, hierarchy: str, scenario: str, measure: str) -> Path
Get the path to final results for a specific scenario and measure.
Parameters
version The version identifier hierarchy The location hierarchy scenario The climate scenario measure The climate measure
Returns
Path The path to the results file
Source code in src/climate_data/data.py
results_root(version: str) -> Path
Get the directory for final results (measure-level).
Parameters
version The version identifier
Returns
Path The directory for final results
Source code in src/climate_data/data.py
save_population(df: pd.DataFrame, version: str, hierarchy: str) -> None
Save population data for a specific hierarchy.
Parameters
df The population data to save version The version identifier hierarchy The location hierarchy
Source code in src/climate_data/data.py
save_raw_results(df: pd.DataFrame, version: str, hierarchy: str, block_key: str, draw: str) -> None
Save raw results for a specific hierarchy, block, and draw.
Parameters
df The results to save version The version identifier hierarchy The location hierarchy block_key The block key draw The draw of the climate data to save (e.g. "000")
Source code in src/climate_data/data.py
save_results(df: pd.DataFrame, version: str, hierarchy: str, scenario: str, measure: str) -> None
Save final results for a specific scenario and measure.
Parameters
df The results to save version The version identifier hierarchy The location hierarchy scenario The climate scenario measure The climate measure
Source code in src/climate_data/data.py
version_root(version: str) -> Path
Get the root directory for a specific version.
Parameters
version The version identifier
Returns
Path The directory for version-specific data
Source code in src/climate_data/data.py
ClimateData
Class for managing the climate data used in the project.
Source code in src/climate_data/data.py
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 | |
combine_raw_annual(paths: list[Path]) -> xr.Dataset
staticmethod
Open and combine raw annual .nc files into one dataset, sorted by year.
draw_results_path(scenario: str, measure: str, draw: str) -> Path
Get the path to annual results for a specific scenario, measure, and draw.
Parameters
scenario The climate scenario (e.g. "ssp126") measure The climate measure (e.g. "mean_temperature") draw The draw of the climate data to load (e.g. "000")
Returns
Path The path to the results file
Source code in src/climate_data/data.py
load_draw_results(scenario: str, measure: str, draw: str) -> xr.Dataset
Load annual climate results for a specific scenario, measure, and draw.
Parameters
scenario The climate scenario (e.g. "ssp126") measure The climate measure (e.g. "mean_temperature") draw The draw of the climate data to load (e.g. "000")
Returns
xr.Dataset The climate data in xarray format
Source code in src/climate_data/data.py
load_raw_annual_mfdataset(scenario: str, variable: str, gcm_member: str | None = None) -> xr.Dataset
Glob and combine all raw annual results for a scenario/variable.
Pass gcm_member to restrict to a single member's files; otherwise every
.nc under the scenario/variable directory is combined.
Source code in src/climate_data/data.py
PopulationModelData
Handles population data and location hierarchies.
This class manages: 1. Population projections at different time points 2. Location hierarchies (GBD, LSAE, etc.) 3. Spatial data for aggregation
The population data is used as weights when aggregating climate data to different location hierarchies.
Source code in src/climate_data/data.py
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 | |
model_spec_path: Path
property
Get the path to the model specification file.
raking_data: Path
property
Get the directory containing data used to rake the population estimates.
Raking enforces admin-level consistency between gridded population data and GBD/FHS population estimates. We'll use these same hierarchies to aggregate the climate data.
results: Path
property
Get the directory containing current model results.
root: Path
property
Get the root directory for population model data.
__init__(root: str | Path = cdc.POPULATION_MODEL_ROOT) -> None
Initialize the population model data manager.
Parameters
root : str | Path Path to the population model root directory
Source code in src/climate_data/data.py
load_lsae_mapping_shapes(admin_level: int) -> gpd.GeoDataFrame
Load the LSAE mapping shapes for a given admin level.
Parameters
admin_level The admin level to load (0, 1, or 2)
Returns
gpd.GeoDataFrame The LSAE mapping shapes for the given admin level
Source code in src/climate_data/data.py
load_model_spec() -> dict[str, Any]
Load the model specification file.
Returns
dict The model specification containing paths and parameters
Source code in src/climate_data/data.py
load_modeling_frame() -> gpd.GeoDataFrame
Load the modeling frame containing spatial information.
The modeling frame is a subdivision of the world into equal-area blocks. Each block is assigned a unique key that is used to parallelize pipeline steps in both population modeling and in this pipeline's aggregation step.
Returns
gpd.GeoDataFrame The modeling frame with spatial information and block keys
Source code in src/climate_data/data.py
load_raking_shapes(full_aggregation_hierarchy: str, bounds: tuple[float, float, float, float] | None = None) -> gpd.GeoDataFrame
Load shapes for a full aggregation hierarchy within given bounds.
Parameters
full_aggregation_hierarchy
The full aggregation hierarchy to load (e.g. "gbd_2021")
bounds
The bounds to load (xmin, ymin, xmax, ymax). None (the default)
loads all shapes for the hierarchy.
Returns
gpd.GeoDataFrame The shapes for the given hierarchy and bounds
Source code in src/climate_data/data.py
load_results(time_point: str, block_key: str) -> rt.RasterArray
Load population results for a specific time point and block.
Parameters
time_point The time point to load (e.g. "2020q1") block_key The block key to load (e.g. "B-0021X-0003Y")
Returns
rt.RasterArray The population raster data
Source code in src/climate_data/data.py
load_subset_hierarchy(subset_hierarchy: str) -> pd.DataFrame
Load a subset location hierarchy.
The subset hierarchy might be equal to the full aggregation hierarchy, but it might also be a subset of the full aggregation hierarchy. These hierarchies are used to provide different views of aggregated climate data.
Parameters
subset_hierarchy The administrative hierarchy to load (e.g. "gbd_2021")
Returns
pd.DataFrame The hierarchy data with parent-child relationships
Source code in src/climate_data/data.py
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 | |
gcm_member_id(source: str, variant: str) -> str
The <source>_<variant> key identifying one CMIP6 ensemble member.
Both halves are load-bearing. A CMIP6 member_id is only unique within a source --
r1i1p1f1 is shared by 24 of the 22 extracted sources in ssp126 and 30 in ssp585 --
so a filename keyed on the variant alone collides across models. Defined once here
because extract_cmip6_main writes these paths and ClimateData.get_gcms reads them;
when they disagreed, the extract wrote pr_ssp126_r1i1p1f1.nc for every source, each
overwriting the last, and the generate stage looked for a name nothing had written.
Source code in src/climate_data/data.py
save_parquet(df: pd.DataFrame, output_path: str | Path) -> None
Save a pandas DataFrame to a file with standard parameters.
Parameters
df The DataFrame to save. output_path The path to save the DataFrame to.
Source code in src/climate_data/data.py
save_raster(raster: rt.RasterArray, output_path: str | Path, num_cores: int = 1, **kwargs: Any) -> None
Save a raster to a file with standard parameters.
Parameters
raster The raster to save. output_path The path to save the raster to. num_cores The number of cores to use for compression.
Source code in src/climate_data/data.py
save_raster_to_cog(raster: rt.RasterArray, output_path: str | Path, num_cores: int = 1, resampling: str = 'nearest') -> None
Save a raster to a COG file.
A COG file is a cloud-optimized GeoTIFF that is optimized for use in cloud storage systems. This function saves the raster to a COG file with the specified resampling method.
Parameters
raster The raster to save. output_path The path to save the raster to. num_cores The number of cores to use for compression. resampling The resampling method to use when building the overviews.
Source code in src/climate_data/data.py
save_xarray(ds: xr.Dataset, output_path: str | Path, encoding_kwargs: dict[str, Any]) -> None
Save an xarray dataset to a file with standard parameters.
Parameters
ds The dataset to save. output_path The path to save the dataset to. encoding_kwargs The encoding parameters to use when saving the dataset.
Source code in src/climate_data/data.py
diagnostics
utils
get_locations_depth_first(hierarchy: pd.DataFrame) -> list[int]
Return location ids sorted by a depth first search of the hierarchy.
Locations at the same level are sorted alphabetically by name.
Source code in src/climate_data/diagnostics/utils.py
extract
Climate Data Extraction
This module contains pipelines for extracting climate data from various sources.
cmip6
CMIP6 Data Extraction
check_encoding_covers(data_min: float, data_max: float, offset: float, scale: float, variable: str, dtype: str = 'int16') -> None
Refuse to write values the declared encoding cannot represent.
Packing to a 16-bit integer rounds (value - offset) / scale, and anything outside
the type's range wraps modulo 65536. to_netcdf does this silently, so the corruption
is invisible until someone plots the result and finds negative rainfall. pr shipped
with scale_factor=1e-9 for two years -- a 2.83 mm/day ceiling -- and produced 295
files in which 26.4% of sampled cells were wrong and 12.4% were negative.
Raising here makes the next such mistake a failed extract rather than a corrupt archive. An unsigned dtype also makes a negative value an error rather than a wrap, which for a flux like precipitation is the honest outcome.
Source code in src/climate_data/extract/cmip6.py
extract_cmip6(cmip6_source: list[str], cmip6_experiment: list[str], cmip6_variable: list[str], output_dir: str, queue: str, overwrite: bool, dry_run: bool) -> None
Extract CMIP6 data.
Extracts CMIP6 data for the given source, experiment, and variable. We use the
the table at https://www.nature.com/articles/s41597-023-02549-6/tables/3 to determine
which CMIP6 source_ids to include. See ClimateData.load_koppen_geiger_model_inclusion
to load and examine this table. The extraction criteria does not completely
capture model inclusion criteria as it does not account for the year range avaialable
in the data. This determiniation is made when we proccess the data in later steps.
Fans out one job per ensemble member rather than one per (source, experiment). The
member counts are wildly uneven -- MIROC6 has 50 pr members where most sources have
one -- so grouping them made three jobs carry fifty times the work of a typical one.
More importantly, extract_cmip6_main re-raises on failure, so a member the encoding
guard rejects used to abandon every member behind it in the same job. One job per
member contains that to the member that failed, and makes a resumed run skip the
members already written instead of redoing whole groups.
The member space is not a cartesian product -- not every source publishes every
variant for every experiment -- so it is enumerated from the metadata and passed as
flat_node_args.
Source code in src/climate_data/extract/cmip6.py
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 | |
load_cmip_data(zarr_path: str) -> xr.Dataset
Loads a CMIP6 dataset from a zarr path.
Source code in src/climate_data/extract/cmip6.py
select_members(meta: pd.DataFrame, cmip6_source: str, cmip6_experiment: str, cmip6_variable: str, gcm_member: str | None = None) -> dict[str, str]
The {member_id: zstore} this job should extract.
With gcm_member given, narrows to that one ensemble member so the runner can put
each member in its own job. Shared with the runner, which enumerates the same space
to build its task list -- if these two disagreed, the runner would submit jobs whose
member does not exist and they would silently extract nothing.
Source code in src/climate_data/extract/cmip6.py
elevation
extract_elevation(model_name: str, output_dir: str, queue: str, dry_run: bool) -> None
Download elevation data from Open Topography.
Source code in src/climate_data/extract/elevation.py
extract_elevation_task(model_name: str, lat_start: int, lon_start: int, output_dir: str) -> None
Download elevation data from Open Topography.
Source code in src/climate_data/extract/elevation.py
era5
ERA5 Data Extraction
check_extract_year_floor(years: Sequence[str], *, allow_pre_floor: bool) -> None
Refuse a run that reaches below cdc.EXTRACT_YEAR_FLOOR unless asked to.
build_task_lists treats a missing output file as work to do, so after ERF's Sep2026
deletion every pre-1980 extract looks like a gap. The runner's --year defaults to
ALL, which means the bare invocation would refill 3,238 files and silently undo the
reclamation -- days of Copernicus queue to recover from. Guarding the outcome rather
than the default also catches an explicitly typed --year ALL.
Source code in src/climate_data/extract/era5.py
variables_for_full_expansion(era5_variables: Sequence[str]) -> list[str]
Drop never-read variables when the whole variable set was requested.
--era5-variable ALL resolves to every declared variable, so the default invocation
downloads and stores surface_pressure for every month of every year although no
stage opens it. Naming a variable explicitly still extracts it; this only narrows the
meaning of "all" to "all the ones we use".
Source code in src/climate_data/extract/era5.py
generate
historical_daily
drop_noncore_coords(ds: xr.Dataset) -> xr.Dataset
Drop coordinates the older and newer CDS extract formats disagree about.
Extracts pulled through the newer CDS API carry number (ensemble member) and
expver ('0001' final ERA5, '0005' preliminary ERA5T) alongside the grid coords;
older extracts carry neither, and are packed int16 rather than float32. xr.concat
refuses to join datasets whose coordinates differ, so a look-ahead that crosses from
an old extract into a new one has to be normalised first.
Which era a file belongs to tracks its download date, not its data year: surveying
the archive, valid_time covers 1950-1989 and 2024 while time covers 1990-2023. So
there are two seams, not the single 2023/2024 one this used to describe -- 1989->1990
crosses new format into old, 2023->2024 crosses old into new -- and the 1950-2023
regeneration passed through both.
Source code in src/climate_data/generate/historical_daily.py
load_variable_with_lookahead(cdata: ClimateData, variable: str, year: str, month: str, dataset: str) -> xr.Dataset
Load a month's hourly data plus the one sample that closes its final day.
Accumulation windows are stamped by their end, so the last day of a month is closed by the next month's first sample -- for December, by the next year's January. That single extra sample completes the final bin without opening a new one.
Raises if the look-ahead file is absent rather than degrading to the incomplete
23-hour window, which should stop the run rather than quietly shorten one day.
Checked before loading the target month so the run fails fast. Note this reaches one
year past the history range -- regenerating the last history year needs the following
January -- which is why the extract tasks span cdc.EXTRACT_YEARS rather than
cdc.HISTORY_YEARS.
Source code in src/climate_data/generate/historical_daily.py
trim_to_month(ds: xr.Dataset, year: str, month: int) -> xr.Dataset
Drop collapsed bins that fall outside the target month.
The interval-aware collapse labels its first bin with the previous month's last day, since that bin holds that day's closing sample. Left in place, every month contributes a duplicate date at its seam.
Source code in src/climate_data/generate/historical_daily.py
scenario_annual
bounded_source_variables(target_variable: str, anomaly_scheme: str) -> list[str]
Source variables of target_variable that anomaly_scheme cannot bias-correct.
Value-bounded variables are floored and clipped to cdc.VALUE_BOUNDS instead of being
stabilised, so they run under cdc.BOUNDED_VARIABLE_SCHEMES only; see
check_bounded_variable_scheme for why the other schemes are refused. The bounds are
keyed on the daily variable, so the annual target has to be resolved through its
sources the same way the de-bias check is.
Source code in src/climate_data/generate/scenario_annual.py
forecast_jobs_for_anomaly_scheme(to_run: list[tuple[str, str, str, str]], anomaly_scheme: str) -> list[tuple[str, str, str, str]]
Drop forecast jobs whose variable the anomaly scheme cannot be applied to.
Filtered per job rather than per variable because the historical scenario never
reaches generate_scenario_daily_main -- it reads the daily results off disk -- so
the scheme does not constrain it, and an additive variable is perfectly runnable
there. Only the forecast scenarios pass through compute_anomaly.
Two classes are dropped, and they are not mirror images. Additive variables run under
the stabilised monthly scheme and no other. Value-bounded variables are the reverse:
they run under cdc.BOUNDED_VARIABLE_SCHEMES only, which means they have to be dropped
under the default scheme too -- this stage calls generate_scenario_daily_main in
memory, so a bounded forecast job reaches check_bounded_variable_scheme and raises in
the worker after being scheduled. That is the failure the daily launcher's filter
already prevents.
A filter that removed every job is a usage error rather than an empty run, because the caller asked for work that cannot be done and an empty fan-out looks like success.
Source code in src/climate_data/generate/scenario_annual.py
scenario_daily
apply_dry_day_rule(anomaly: xr.Dataset, target: xr.Dataset, dry_day_rule: str) -> xr.Dataset
Stop the eps offset from manufacturing rain on days the model reports as dry.
The multiplicative anomaly (T + eps)/(R + eps) is strictly positive even when the
model reports no rain at all, so a rainless model day still receives
E_ref(month) * a(d) > 0 of the ERA5 climatology. Worse, eps dominates the
numerator for such a day, so every rainless day in a cell-month gets the identical
anomaly 1/(R_m + eps) -- a flat positive floor rather than a dry spell. Wherever that
floor clears the 0.1 mm/day wet-day threshold the pipeline reports a wet day that neither
ERA5 nor the GCM has, which is what makes precipitation_days step at the boundary.
preserve zeroes the anomaly on those days and rescales the surviving days of the same
cell-month so the month's summed anomaly is unchanged. Because that sum is preserved per
GCM cell and interpolate_to_target_latlon is linear, the monthly -- and therefore the
annual -- total on the target grid is untouched to floating point. Only the distribution
across days moves. That is deliberate: this is a shape fix, exactly orthogonal to the
Jensen de-bias, which is a level fix that leaves the shape alone. The two commute, because
the de-bias scales a whole month uniformly and this rescale is scale-invariant.
A cell-month the model reports dry on every day has nothing to renormalise onto. Those are left exactly as they are rather than zeroed. Zeroing them is the variant that was measured and rejected: it loses up to 1.2% of the population-weighted annual total across the 1-3% of cell-months that are all-dry. Keeping them is what makes this rule total-preserving, and it is the whole difference between the two.
Source code in src/climate_data/generate/scenario_daily.py
apply_value_bounds(ds: xr.Dataset, bounds: tuple[float, float]) -> xr.Dataset
Clip every data variable to bounds (inclusive); NaN stays NaN.
Source code in src/climate_data/generate/scenario_daily.py
check_bounded_variable_scheme(target_variable: str, anomaly_scheme: str) -> None
Refuse a stabilised or yearly anomaly scheme for a value-bounded variable.
A bounded variable (relative humidity) has its raw inputs clipped to
cdc.VALUE_BOUNDS before the ratio is formed, so the floor already does the job of
the +1 / tapered eps in the eps-bearing schemes -- applying both would stabilise twice
and shift the ratio away from the construction that was evaluated. The yearly family
drops the monthly anchor that evaluation was made on. Called from the worker and, via
variables_for_anomaly_scheme, from the launcher, so --target-variable all under
the default scheme skips the variable with a message instead of queueing doomed jobs.
Source code in src/climate_data/generate/scenario_daily.py
check_debias_variable(target_variable: str, debias_method: str, dry_day_rule: str = 'none') -> None
Refuse a correction for a variable it has not been validated against.
Called from the launchers as well as from the worker, so that --target-variable all
fails in a second rather than after submitting thousands of doomed jobs.
Source code in src/climate_data/generate/scenario_daily.py
check_scheme_compatibility(anomaly_scheme: str, anomaly_type: str, debias_method: str, dry_day_rule: str) -> None
Reject combinations of the two correction axes that cannot both apply.
debias_method and dry_day_rule correct the (T + eps) / (R + eps) construction.
Both monthly (constant eps) and monthly-taper (tapered eps) use it, so both accept
them. The yearly and monthly-ratio families have no eps for those corrections to act
on, so asking for either against them is a mistake rather than a no-op -- and silently
ignoring the request would produce a file whose attrs claim a correction that was
never applied.
Source code in src/climate_data/generate/scenario_daily.py
compute_anomaly(reference: xr.Dataset, target: xr.Dataset, anomaly_type: str, *, debias_method: str, dry_day_rule: str, anomaly_scheme: str = cdc.ANOMALY_SCHEME_MONTHLY, eps_floor: float = cdc.DEFAULT_EPS_FLOOR, anomaly_cap: float | None = cdc.DEFAULT_ANOMALY_CAP) -> xr.Dataset
The forecast anomaly, optionally capped.
A thin wrapper so the ceiling applies to every scheme without threading it through each one: the scheme dispatch below has several return points, and duplicating the clip at each is how one of them ends up missing it.
Applied on the GCM grid, BEFORE interpolate_to_target_latlon. Capping afterwards
would leave a blown-up cell already smeared across its neighbours by the regrid.
The cap bounds each cell's multiplier at the granularity the scheme anchors at -- annual for the yearly family, per calendar month for the monthly family -- and rescales the daily series to meet it.
It cannot be an elementwise clip. anomaly carries the target's daily date
dimension, because the denominator is a reference-window mean with no date dim and
the division broadcasts. Clipping elementwise bounds every day at anomaly_cap
times the cell's reference mean, and against an annual denominator that ceiling sits
inside the ordinary distribution of daily rainfall: a cell averaging 2 mm/day is cut
at 40 mm/day, an unremarkable tropical wet day. The daily-over-annual ratio also
carries the seasonal cycle, so such a clip bites hardest where seasonality is
strongest rather than where the pathology is.
Measured on yearly-delta ssp126 before this change, an elementwise clip at 20
altered 20.5% of land pixels in 2083 and 15.5% in 2050; 82% of those had an annual
anomaly at or below 2 -- cells projecting essentially no change -- and the global
total moved -19.1% and -1.1% respectively.
Rescaling instead leaves any cell at or below the ceiling bit-identical to uncapped, brings a cell above it exactly to the ceiling, and preserves within-period shape so a wet day stays proportionally a wet day.
The cap still only removes precipitation -- it cannot conserve, and whatever it removes is gone from the total. That is intended: the values it removes are ones no cell's observed climatology supports. But it means a cap moves the level, so it must be chosen on evidence rather than set defensively.
Source code in src/climate_data/generate/scenario_daily.py
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 | |
jensen_debias_factor(reference: xr.Dataset, reference_monthly: xr.Dataset, debias_method: str, eps: xr.Dataset | float = 1.0) -> xr.Dataset
The factor to divide a multiplicative anomaly by, per month and per GCM cell.
The anomaly is (T + 1) / (R + 1) with R a monthly mean over only five reference
years. 1/(R + 1) is convex, so by Jensen's inequality the anomaly averages above 1 even
when the target year is drawn from the same distribution as the reference period -- a level
bias on every forecast year. This returns an estimate of that inflation.
loo -- leave-one-out. For each held-out reference year, form the multiplier of that
year against the mean of the other years and average over the folds. Between reference
years there is no climate signal, so an unbiased estimator would return 1; the excess is
the bias, measured from the data with no series expansion. The held-out denominator
averages n-1 years while the pipeline averages n, and the bias goes as 1/n, so
the excess is rescaled by (n-1)/n.
This is provably >= 1: with u_y = T_y + 1 and S = sum_y u_y the held-out
denominator is (S - u_y)/(n-1), so each fold is (n-1)*u_y/(S - u_y), convex in
u_y, and Jensen gives mean_y >= f(S/n) = 1 with equality iff every reference year
is identical. So dividing by it can only shrink the anomaly, never inflate it -- which is
what makes the effect on a threshold count such as precipitation_days sign-definite.
analytic -- the second-order expansion 1 + Var(Rbar)/(R + 1)^2. Cheaper to reason
about but it is a truncated series, and the neglected terms matter exactly where the
correction is largest (near-zero R, where eps dominates the denominator). Kept for
comparison; loo is the estimator this was built for.
reference_monthly is the pipeline's own denominator, passed in rather than recomputed so
the analytic form squares precisely the value the anomaly divides by.
Source code in src/climate_data/generate/scenario_daily.py
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 | |
load_and_shift_longitude_and_correct_time(member_path: str | Path, year: str) -> xr.Dataset
Put a member's year onto the real Gregorian calendar, day by day.
The conversion is by DATE, never by value. interp_calendar used to resample onto the
target axis by linear interpolation, so whenever the source calendar's year length
differed from the target's -- a noleap member in a leap year -- every target day
became a blend of two source days. convert_calendar maps each source day onto its own
date instead and leaves 29 February missing; the reindex holds the output axis to
exactly this year's days whatever the source calendar, and interpolate_na fills the
gap from the nearest real day.
Every variable comes through here, not just precipitation, but what the blending cost
depends on the field. Temperature is smooth, so blending barely moves it and the
threshold measures it feeds -- days_over_30C, the suitability maps -- were knocked
either way and largely cancelled in the spatial mean. Precipitation is spiky and mostly
zero against a 0.1 mm cut sitting on the floor, so smearing a wet day onto its dry
neighbours could only push them UP over the line, never below it. That one-way ratchet
is why precipitation_days took a coherent ~13.5 d per noleap member in all 19 leap
years 2024-2096 while everything else came out as cancelling noise. (CLIMATE-35)
No align_on is passed: it only takes effect when a 360_day calendar is involved,
and no member in the extracts uses one. If that changes, align_on needs a deliberate
choice rather than xarray's default.
Source code in src/climate_data/generate/scenario_daily.py
variables_for_anomaly_scheme(target_variables: list[str], anomaly_scheme: str, anomaly_types: dict[str, str]) -> list[str]
Drop target variables the anomaly scheme cannot be applied to.
The yearly schemes are defined for multiplicative variables only -- compute_anomaly
raises for anything else -- while --target-variable defaults to ALL. Without this
filter the default invocation of a yearly scheme submits additive jobs that are
certain to fail, and they fail only after being scheduled and retried.
Skipped variables are named rather than dropped quietly, and selecting nothing but additive variables is an error rather than an empty run.
Source code in src/climate_data/generate/scenario_daily.py
utils
annual_mean_from_monthly(ds: xr.Dataset) -> xr.Dataset
Day-weighted annual mean of a 12-month climatology.
Weights are bound by month label, not position, so a permuted month coordinate still weights correctly; anything other than a full 1..12 coordinate is rejected rather than misweighted.
Source code in src/climate_data/generate/utils.py
buck_vapor_pressure(temperature_c: xr.Dataset) -> xr.Dataset
Approximate vapor pressure of water.
https://en.wikipedia.org/wiki/Arden_Buck_equation https://journals.ametsoc.org/view/journals/apme/20/12/1520-0450_1981_020_1527_nefcvp_2_0_co_2.xml
Parameters
temperature_c Temperature in Celsius
Returns
xr.Dataset Vapor pressure in hPa
Source code in src/climate_data/generate/utils.py
daily_accumulation_last(ds: xr.Dataset) -> xr.Dataset
Collapse a within-day cumulative variable to its daily total.
For ERA5-Land total_precipitation, which accumulates since 00Z, the day's total is
the window's closing sample, so last reads it directly. Prefer this to a maximum:
the two agree only while the window rises monotonically, and int16 packing can make
it tick down in its final step, in which case the maximum is an earlier,
quantisation-inflated sample. Measured over 741,270 land day-pixels, last matched
the true close for 100.0000% against 99.9864% for max.
Note resample emits a regular axis with NaN for empty bins, unlike groupby, which
emits observed groups only. Callers must trim the partial bins at each end.
skipna=False because the default steps back past an absent closing sample to hour
23, reintroducing the incomplete window this function exists to eliminate. NaN is the
honest answer for a window that never closed. It is not, however, a detectable one:
generate_historical_daily_main fills ERA5-Land NaNs from the interpolated
single-level field -- that is how ocean pixels are supplied -- so such a pixel carries
a complete 0.25 degree value rather than a truncated 0.1 degree one, and never reaches
validate_output. Preferring the coarse-but-whole value is the point; detecting the
substitution would need a separate check against the sea mask.
Source code in src/climate_data/generate/utils.py
daily_accumulation_sum(ds: xr.Dataset) -> xr.Dataset
Collapse a variable of per-hour increments to its daily total.
For ERA5 single-levels, "accumulations are over the hour ending at the validity
date/time", so the increments sum. The same interval convention applies as for
daily_accumulation_last, so the two stay on a common date axis -- they are merged
downstream in generate_historical_daily_main.
Source code in src/climate_data/generate/utils.py
identity(ds: xr.Dataset) -> xr.Dataset
interpolate_to_target_latlon(ds: xr.Dataset, method: str = 'nearest', target_lon: xr.DataArray = cdc.TARGET_LONGITUDE, target_lat: xr.DataArray = cdc.TARGET_LATITUDE) -> xr.Dataset
Interpolate a dataset to a target latitude and longitude grid.
Parameters
ds Dataset to interpolate method Interpolation method target_lon Target longitude grid target_lat Target latitude grid
Returns
xr.Dataset Interpolated dataset
Source code in src/climate_data/generate/utils.py
kelvin_to_celsius(temperature_k: xr.Dataset) -> xr.Dataset
Convert temperature from Kelvin to Celsius
Parameters
temperature_k Temperature in Kelvin
Returns
xr.Dataset Temperature in Celsius
Source code in src/climate_data/generate/utils.py
meter_to_millimeter(rainfall_m: xr.Dataset) -> xr.Dataset
Convert rainfall from meters to millimeters
Parameters
rainfall_m Rainfall in meters
Returns
xr.Dataset Rainfall in millimeters
Source code in src/climate_data/generate/utils.py
parse_reference_years(reference_years: str) -> slice
Turn a START-END year string (inclusive, four-digit years) into a date slice.
Source code in src/climate_data/generate/utils.py
precipitation_flux_to_rainfall(precipitation_flux: xr.Dataset) -> xr.Dataset
Convert precipitation flux to rainfall
Parameters
precipitation_flux Precipitation flux in kg m-2 s-1
Returns
xr.Dataset Rainfall in mm/day
Source code in src/climate_data/generate/utils.py
rh_percent(temperature_c: xr.Dataset, dewpoint_temperature_c: xr.Dataset) -> xr.Dataset
Calculate relative humidity from temperature and dewpoint temperature.
Parameters
temperature_c Temperature in Celsius dewpoint_temperature_c Dewpoint temperature in Celsius
Returns
xr.Dataset Relative humidity as a percentage
Source code in src/climate_data/generate/utils.py
scale_wind_speed_height(wind_speed_10m: xr.Dataset) -> xr.Dataset
Scaling wind speed from a height of 10 meters to a height of 2 meters
Reference: Bröde et al. (2012) https://doi.org/10.1007/s00484-011-0454-1
Parameters
wind_speed_10m The 10m wind speed [m/s]. May be signed (ie a velocity component)
Returns
xr.DataSet The 2m wind speed [m/s]. May be signed (ie a velocity component)
Source code in src/climate_data/generate/utils.py
vector_magnitude(x: xr.Dataset, y: xr.Dataset) -> xr.Dataset
jobmon_utils
Helpers for working with jobmon in the Climate Data CLI.
The main entrypoint is run_parallel_maybe_dry_run which mirrors
rra_tools.jobmon.run_parallel but adds a dry_run flag.
When dry_run is True, this helper:
* Expands flat_node_args or node_args into per-job CLI argument sets.
* Builds sbatch-like preview commands using the supplied task resources.
* Prints a short summary plus representative example commands.
* Returns a dummy success status without touching jobmon or the scheduler.
When dry_run is False, it simply delegates to
jobmon.run_parallel with identical semantics.
run_parallel_maybe_dry_run(*, runner: str, task_name: str, task_resources: Mapping[str, Any], flat_node_args: tuple[Sequence[str], Sequence[Sequence[Any]]] | None = None, node_args: Mapping[str, Sequence[Any]] | None = None, task_args: Mapping[str, Any] | None = None, log_root: str | Path | None = None, max_attempts: int | None = None, concurrency_limit: int | None = None, dry_run: bool) -> Any
Wrapper around jobmon.run_parallel with optional dry-run behavior.
Parameters
runner
The executable used for tasks, e.g. "cdtask" or "cdtask aggregate".
task_name
A short, human-readable name for the job group.
task_resources
Resource profile for the tasks (queue, cores, memory, runtime, project, ...).
flat_node_args
Tuple of (argument names, rows) describing per-node CLI arguments.
node_args
Mapping from argument name to a sequence of values; all combinations are used.
task_args
Shared CLI arguments that are the same for all nodes.
log_root
Optional log directory passed through to jobmon.
max_attempts
Maximum number of attempts; passed through to jobmon. Defaults to None
to match jobmon.run_parallel (jobmon then applies its own default).
dry_run
If True, only print sbatch-like previews instead of submitting.
Source code in src/climate_data/jobmon_utils.py
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 | |
special
download_era5_uncertainty
ERA5 Uncertainty Download (CLIMATE-22 gap-fill)
Downloads whole-year ERA5 reanalysis and ensemble_spread 2m temperature
files from the Copernicus CDS, matching the layout Katrin Burkart produced by
hand in /ihme/erf/ERA5/katrin_download_20240208/ for 2022/2023:
era5_{product_type}_{variable}_{year}.nc (one file per whole year)
This fills the 2024/2025 gap that GBD temperature PAF work depends on. It is a
standalone gap-fill: the ensemble_spread product is not (yet) consumed by
the rest of this repo's pipeline, which only uses reanalysis mean temperature.
Notes / gotchas baked in below:
* The ensemble products only exist on reanalysis-era5-single-levels (0.25°
HRES / ~0.5° EDA), never on reanalysis-era5-land.
* Both products are pulled 3-hourly to match the canonical GBD download and
Katrin's 2022/2023 files. ensemble_spread (the EDA) is only 3-hourly;
reanalysis (HRES) is subsampled from hourly to the same 3-hourly axis.
* Credentials come from the caller's ~/.cdsapirc (cdsapi.Client() with
no args), so no dependency on the shared per-user copernicus.yaml keyring
(which does not carry every user).
download_era5_uncertainty(era5_variable: str, output_dir: str, queue: str, dry_run: bool) -> None
Download 2024/2025 ERA5 reanalysis + ensemble_spread (CLIMATE-22 gap-fill).
Source code in src/climate_data/special/download_era5_uncertainty.py
download_era5_uncertainty_task(year: str, product_type: str, era5_variable: str, output_dir: str) -> None
Download one whole-year ERA5 file (single year, single product type).
Source code in src/climate_data/special/download_era5_uncertainty.py
temperature_person_days
temperature_person_days_main(block_key: str, gcm_member: str, scenario: str, hierarchy: str, population_model_root: str, climate_data_root: str, output_dir: str, *, progress_bar: bool = False) -> None
Bin population into (temperature x temperature-zone) person-days per year.
The year span is derived from the temperature_zone actually on disk (not a
hardcoded range): for the historical scenario this is the ERA5-only product
spanning EXPOSURE_START_YEAR through the last year present (1990-2025 as
delivered); for a forecast scenario, daily temperature is ERA5 before
FORECAST_START_YEAR and the GCM scenario from then on, binned against that
scenario's own zone. A year whose daily or population input is missing fails loudly
rather than being skipped, so a gap in a product that must be square cannot slip
through silently.
Source code in src/climate_data/special/temperature_person_days.py
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 | |
temperature_zone
generate_temperature_zone_main(gcm_member: str, scenario: str, output_dir: str | Path) -> None
Generate the temperature zone for a given scenario and gcm member.
Parameters
gcm_member
The gcm member to generate the temperature zone for.
scenario
The scenario to generate the temperature zone for. Pass historical
(with gcm_member="era5") to build a pure-ERA5 zone from the raw
historical annual mean temperature rather than the compiled
historical+forecast series; the output then spans EXPOSURE_START_YEAR
through the last historical year present on disk.
output_dir
The directory to save the temperature zone to (root for this run mode).
Source code in src/climate_data/special/temperature_zone.py
utils
aggregate_to_hierarchy(data: pd.DataFrame, hierarchy: pd.DataFrame) -> pd.DataFrame
Create all aggregate climate values for a given hierarchy from most-detailed data.
Parameters
data The most-detailed climate data to aggregate. hierarchy The hierarchy to aggregate the data to.
Returns
pd.DataFrame The climate data with values for all levels of the hierarchy.
Source code in src/climate_data/special/utils.py
utils
Climate Data Utilities
Utility functions for working with climate data.
make_raster_template(x_min: int | float, y_min: int | float, stride: int | float, resolution: int | float, crs: str = 'EPSG:4326') -> rt.RasterArray
Create a raster template with the specified dimensions and resolution.
A raster template is a RasterArray with a specified extent, resolution, and CRS. The data values are initialized to zero. This function is useful for creating a template to use when resampling another raster to a common grid.
Parameters
x_min The minimum x-coordinate of the raster. y_min The minimum y-coordinate of the raster. stride The length of one side of the raster in the x and y directions measured in the units of the provided coordinate reference system. resolution The resolution of the raster in the units of the provided coordinate reference system. crs The coordinate reference system of the generated raster.
Returns
rt.RasterArray A raster template with the specified dimensions and resolution.
Source code in src/climate_data/utils.py
to_raster(ds: xr.DataArray, no_data_value: float | int, lat_col: str = 'lat', lon_col: str = 'lon', crs: str = 'EPSG:4326') -> rt.RasterArray
Convert an xarray DataArray to a RasterArray.
Parameters
ds The xarray DataArray to convert. no_data_value The value to use for missing data. This should be consistent with the dtype of the data. lat_col The name of the latitude coordinate in the dataset. lon_col The name of the longitude coordinate in the dataset. crs The coordinate reference system of the data.
Returns
rt.RasterArray The RasterArray representation of the input data.