utils.py
add_month_day_dims(daily_ts, monthly_ts, time_dim='time', spatial_dims=('lat', 'lon'))
Reshape daily and monthly data to have explicit month (M) and day (T) dimensions.
Here we assume maximum 31 days in a month, and invalid day entries will be padded with NaN.
Returns:
| Name | Type | Description |
|---|---|---|
daily_m |
xr.DataArray - dims: (M, T, H, W)
|
|
monthly_m |
xr.DataArray - dims: (M, H, W)
|
|
padded_days_mask |
xr.DataArray - dims: (M, T=31), bool, True where day is padded
|
|
time_features |
xr.DataArray - dims: (M, T, 2)
|
|
Source code in climanet/utils.py
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 | |
add_month_hour_dims(hourly_ts, monthly_ts, time_dim='time', spatial_dims=('lat', 'lon'))
Reshape hourly and monthly data to have explicit month (M) and hour (T) dimensions.
Here we assume maximum 31 days in a month with 24 hours per day = 744 hours maximum. Invalid hour entries will be padded with NaN.
Returns:
| Name | Type | Description |
|---|---|---|
hourly_m |
xr.DataArray - dims: (M, T=744, H, W)
|
|
monthly_m |
xr.DataArray - dims: (M, H, W)
|
|
padded_hours_mask |
xr.DataArray - dims: (M, T=744), bool, True where hour is padded
|
|
time_features |
xr.DataArray - dims: (M, T=744, 2)
|
|
Source code in climanet/utils.py
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 | |
calc_stats(arr, mean_axis=0)
Calculate mean and std along the specified axis, ignoring NaNs.
Args: arr: Input array containing NaNs to ignore. shape is (M, T, H, W) mean_axis: Axis along which to compute mean and std (default is 0 for month) Returns: mean: Mean values along the specified axis, shape (M,) std: Standard deviation along the specified axis, shape (M,)
Source code in climanet/utils.py
compute_masked_loss(pred, target, land_mask)
Compute L1 loss masked to ocean pixels only.
Source code in climanet/utils.py
configure_compute_resources(model, device, compute_threads, dataloader_num_workers)
Configure model for multi-GPU and set CPU thread usage for compute (training or prediction).
Args: model: the PyTorch model to configure device: device to run on ("cpu" or "cuda") compute_threads: number of threads to use for compute when device is CPU. If None, it will be set automatically. dataloader_num_workers: how many subprocesses to use for data loading. See torch DataLoader docs for details. Returns: The model, potentially wrapped in DataParallel if using multiple GPUs.
Source code in climanet/utils.py
data_preparation(input_data, monthly_data, time_dim='time', run_dir='.', calculate_residuals=True, is_hourly=False, save_to_zarr=False)
Prepare the data for training.
Args: input_data (xr.DataArray): The input data (daily or hourly). monthly_data (xr.DataArray): The monthly data. time_dim (str): The name of the time dimension in the data arrays. run_dir (str): Directory to save the preprocessed data. calculate_residuals (bool): Whether to calculate residuals between input and monthly data. is_hourly (bool): Whether the input data is hourly (True) or daily (False). save_to_zarr (bool): Whether to save the preprocessed data to zarr files. Returns: tuple: A tuple containing the following xarray.DataArray objects: - input_da: The reshaped input data with dimensions (M, T, H, W). - input_da_nan_mask: A boolean mask indicating NaN locations in the input data. - monthly_da: The reshaped monthly data with dimensions (M, H, W). - padded_days_mask: A boolean mask indicating padded days/hours in the input data. - time_features: A DataArray containing cyclic time features (month, day, hour).
Source code in climanet/utils.py
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 | |
data_split(data_folder, filename_pattern='*_hr_ERA5dc_masked_tos.nc', train_range=(2018, 2020), validation_range=(2021, 2021), test_range=(2022, 2022))
Split the data into training, validation, and test sets based on the provided year ranges.
Source code in climanet/utils.py
load_model(model_path, device)
Helper function to load a model from a checkpoint.
Source code in climanet/utils.py
plot_histograms(target, predictions, label='SST K', legend_labels=('Target', 'Prediction'), bins=30)
Plot histograms of target and predictions in the same figure for comparison.
Source code in climanet/utils.py
plot_loss(run_dir, list_loss_var, unit='K', figsize=(10, 5))
Plot training and validation loss from TensorBoard logs.
Args: run_dir (str | Path): Directory containing TensorBoard logs. list_loss_var (list[str]): List of loss variable names to plot. unit (str, optional): Unit of the loss values. Defaults to "K". figsize (Tuple[int, int], optional): Size of the figure. Defaults to (10, 5).
Source code in climanet/utils.py
plot_nobs_vs_err(nobs, err_baseline, err_predictions)
Plot number of observations vs error for each month.
The three inputs are expected to be xarray DataArrays with dimensions (time, lat, lon). They should share the same spatial and temporal coordinates.
Args: nobs (xr.DataArray): Number of observations per grid cell per month. Dimensions: (time, lat, lon) err_baseline (xr.DataArray): Baseline error per grid cell per month. Dimensions: (time, lat, lon) err_predictions (xr.DataArray): Prediction error per grid cell per month. Dimensions: (time, lat, lon)
Source code in climanet/utils.py
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 | |
pred_to_numpy(pred, orig_H=None, orig_W=None, land_mask=None)
pred: (B, M, H_pad,W_pad) or (B, H, W) torch tensor orig_H/W: original sizes before padding (optional) land_mask: (B, H_pad,W_pad) or (B, H,W) bool; if given, land will be set to NaN returns: (H,W) numpy array
Source code in climanet/utils.py
read_st_data(data_path='.', var_name='tos')
Read preprocessed spatio-temporal data from zarr files. Args: data_path (str): Path to the directory containing the zarr files. var_name (str): Name of the variable to read from the zarr files.
Returns: tuple: A tuple containing the following xarray.DataArray objects: - input_da - input_da_nan_mask - monthly_da - padded_days_mask - time_features
Source code in climanet/utils.py
regrid_to_boundary_centered_grid(da, roll=False)
Interpolates a DataArray from its current center-based grid onto a new grid whose coordinates are derived from user-specified boundaries.
Includes robust handling for 0-360 vs -180-180 longitude domains.
Assumes dimensions are named 'lat' and 'lon'.
Source code in climanet/utils.py
save_model(model, optimizer, run_dir, filename='best_model.pth', verbose=True)
Save model state and config to disk.
Source code in climanet/utils.py
setup_logging(log_dir)
Set up TensorBoard logging directory and writer.