Skip to content

Single-Timestamp Downscaler

s3lst_ds.downscaling.piecewise_downscaling.PiecewiseDownscaler

Bases: BaseEstimator, RegressorMixin

A downscaling model that employs a scale-invariance-based approach with residual correction, considering an estimator for each timestamp - uniquely trained with and inferring for a single timestamp. For each timestamp, the fine target is estimated by a DownscalerEstimator (trained on coarse data of that same timestamp) from fine predictors and masks and corrected with the finely-resampled residual associated with the prediction of coarse target from coarse predictors and masks.

Attributes:

Name Type Description
base_model Regressor

The general (i.e. non-pixel-wise) base model to be fitted with coarse data. Each estimator is to have a copy of this base model trained with the data of the respective timestamp.

cols_X list or ndarray

The names of the predictor columns to regard.

cols_mask (list or ndarray, optional)

The names of the mask columns to regard.

scale {"standardize", "min_max_normalize", None}, default="standardize"

The scaling method to apply to numerical predictors: - "standardize": to standardize the numerical predictors (zero mean and unit variance); - "min_max_normalize": to min-max normalize the numerical predictors (to the range [0, 1]); - None: to regard the numerical predictors raw (no scaling).

encode {"one_hot", "dummy", None}, default="dummy"

The encoding method to apply to the categorical predictors: - "one_hot": to one-hot encode the categorical predictors; - "dummy": to dummy encode the categorical predictors (one-hot encoding with the first component dropped); - None: to regard the categorical predictors raw (no encoding).

Note that dummy encoding is usually considered in place of one-hot to avoid multicollinearity problems (one may show that a component of a one-hot encoding vector is fully determined by all the other components making it redundant).

lasso_sel bool, default=False

Whether to use a Lasso regression for selecting the scaled-encoded cols_X predictors downstream of the preprocessor. Lasso selection is such that solely the input predictors associated with coefficients of the fitted Lasso regression model having absolute values larger than 1e-5 are selected. Note that the non-encoded cols_X predictors are regardlessly considered downstream of the preprocessor.

lasso_alpha float, default=1.0

The regularization strength of the Lasso regression model used for selecting the scaled-encoded cols_X predictors downstream of the preprocessor. Such regularization strength is the multiplying constant of the weight vector L1-norm (sum of the absolute values of the components) in the Lasso regression objective function. The larger the value, the stronger the regularization. Note that this parameter only takes effect if lasso_sel is True.

estimators dict[Timestamp, DownscalerEstimator]

The preprocessing and regression pipelines keyed by timestamp. The items of the dictionary are set in fitting.

max_workers int, default=1

Number of simultaneous multiple processes to consider in training, prediction and scoring with the special cases: - 1 or None: no multiprocessing is considered; - -1: all processors are used; - -k: all processors except k-1 are used.

logger RichLogger

A rich logger for showing progress of the prediction/scoring.

show_progress bool, default=True

True to display the downscaling progress.

Methods:

Name Description
__init__
fit

Fit an estimator (preprocessing transformers and the general base model) to

get_estimator
predict

Predict fine target for multiple images using predict_single() for each one,

predict_coarse

Predict coarse target for multiple images.

predict_single

Predict fine target from fine predictors and masks (X_and_mask_fine).

save

Write the instance to path with joblib.

score

Predict fine target and score for multiple images individually (if aggregate

score_coarse

Predict coarse target and score for multiple images individually (if aggregate

score_single

Predict fine target and score the prediction.

Source code in src/s3lst_ds/downscaling/piecewise_downscaling.py
  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
 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
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
class PiecewiseDownscaler(BaseEstimator, RegressorMixin):
    """

    A downscaling model that employs a scale-invariance-based approach with residual
    correction, considering an estimator for each timestamp - uniquely trained with and
    inferring for a single timestamp. For each timestamp, the fine target is estimated
    by a `DownscalerEstimator` (trained on coarse data of that same timestamp) from fine
    predictors and masks and corrected with the finely-resampled residual associated
    with the prediction of coarse target from coarse predictors and masks.

    Attributes
    ----------

    base_model : Regressor
        The general (i.e. non-pixel-wise) base model to be fitted with coarse data. Each
        estimator is to have a copy of this base model trained with the data of the
        respective timestamp.

    cols_X : list or np.ndarray
        The names of the predictor columns to regard.

    cols_mask : list or np.ndarray, optional
        The names of the mask columns to regard.

    scale : {"standardize", "min_max_normalize", None}, default="standardize"
        The scaling method to apply to numerical predictors:
            - `"standardize"`: to standardize the numerical predictors (zero mean and
            unit variance);
            - `"min_max_normalize"`: to min-max normalize the numerical predictors (to
            the range `[0, 1]`);
            - `None`: to regard the numerical predictors raw (no scaling).

    encode : {"one_hot", "dummy", None}, default="dummy"
        The encoding method to apply to the categorical predictors:
            - `"one_hot"`: to one-hot encode the categorical predictors;
            - `"dummy"`: to dummy encode the categorical predictors (one-hot encoding
            with the first component dropped);
            - `None`: to regard the categorical predictors raw (no encoding).

        Note that dummy encoding is usually considered in place of one-hot to avoid
        multicollinearity problems (one may show that a component of a one-hot encoding
        vector is fully determined by all the other components making it redundant).

    lasso_sel : bool, default=False
        Whether to use a Lasso regression for selecting the scaled-encoded `cols_X`
        predictors downstream of the preprocessor. Lasso selection is such that solely
        the input predictors associated with coefficients of the fitted Lasso regression
        model having absolute values larger than 1e-5 are selected. Note that the
        non-encoded `cols_X` predictors are regardlessly considered downstream of the
        preprocessor.

    lasso_alpha : float, default=1.0
        The regularization strength of the Lasso regression model used for selecting the
        scaled-encoded `cols_X` predictors downstream of the preprocessor. Such
        regularization strength is the multiplying constant of the weight vector L1-norm
        (sum of the absolute values of the components) in the Lasso regression objective
        function. The larger the value, the stronger the regularization. Note that this
        parameter only takes effect if `lasso_sel` is `True`.

    estimators : dict[pd.Timestamp, estimation.DownscalerEstimator]
        The preprocessing and regression pipelines keyed by timestamp. The items of the
        dictionary are set in fitting.

    max_workers : int, default=1
        Number of simultaneous multiple processes to consider in training, prediction
        and scoring with the special cases:
            - `1` or `None`: no multiprocessing is considered;
            - `-1`: all processors are used;
            - `-k`: all processors except k-1 are used.

    logger : RichLogger
        A rich logger for showing progress of the prediction/scoring.

    show_progress : bool, default=True
        `True` to display the downscaling progress.
    """

    def __init__(
        self,
        base_model: Regressor,
        cols_X: list | np.ndarray,
        cols_mask: list | np.ndarray | None = None,
        scale: Literal["standardize", "min_max_normalize"] | None = "standardize",
        encode: Literal["one_hot", "dummy"] | None = "dummy",
        lasso_sel: bool = False,
        lasso_alpha: float = 1.0,
        max_workers: int = 1,
        logger: RichLogger | None = None,
        show_progress: bool = True,
    ) -> None:

        super().__init__()
        # NOTE: attribute `is_fitted_` is set to `True` after fitting to let `sklearn`
        # know that the instance is already fitted.
        self.is_fitted_ = False
        self.base_model = base_model
        self.cols_X = cols_X
        self._cols_mask = cols_mask if cols_mask is not None else []
        self.scale = scale  # type: ignore
        self.encode = encode
        self.lasso_sel = lasso_sel
        self.lasso_alpha = lasso_alpha
        self.max_workers = max_workers
        self.logger = logger
        self.show_progress = show_progress
        self.estimators = {}

    @property
    def cols_mask(self) -> list | np.ndarray:
        return self._cols_mask

    @property
    def max_workers(self) -> int:
        return self._max_workers

    @cols_mask.setter
    def cols_mask(self, value: list | np.ndarray | None) -> None:
        self._cols_mask = value if value is not None else []
        for estimator in self.estimators.values():
            estimator.cols_mask = self._cols_mask

    @max_workers.setter
    def max_workers(self, value: int) -> None:
        self._max_workers = parse_n_jobs(value)

    def get_estimator(self) -> DownscalerEstimator:
        estimator = DownscalerEstimator(
            base_model=copy.deepcopy(self.base_model),
            cols_X=self.cols_X,
            cols_mask=self.cols_mask,
            scale=self.scale,  # type: ignore
            encode=self.encode,  # type: ignore
            lasso_sel=self.lasso_sel,
            lasso_alpha=self.lasso_alpha,
        )
        return estimator

    def fit(
        self,
        X_and_mask_coarse: dict[pd.Timestamp, np.ndarray | pd.DataFrame],
        y_coarse: dict[pd.Timestamp, np.ndarray | pd.Series],
        sample_weight: dict[pd.Timestamp, np.ndarray | pd.Series] | None = None,
    ) -> Self:
        """
        Fit an estimator (preprocessing transformers and the general base model) to
        training coarse data for each timestamp.

        Parameters
        ----------

        X_and_mask_coarse : dict[pd.Timestamp, np.ndarray or pd.DataFrame]
            The training coarse predictors and masks, keyed by timestamp.

        y_coarse : dict[pd.Timestamp, np.ndarray or pd.Series]
            The training coarse target, keyed by timestamp.

        sample_weight : dict[pd.Timestamp, np.ndarray or pd.Series] or None, default=None
            Weights of the samples in the cost function of the model, keyed by
            timestamp.

        Returns
        -------

        self : PiecewiseDownscaler
            The fitted instance itself.

        """

        if self.logger is not None:
            self.logger.info("Fitting estimators...")

        # Transform parameters valued as None into dictionaries with None values (one
        # per image)
        sample_weight = (
            sample_weight
            if sample_weight is not None
            else dict.fromkeys(X_and_mask_coarse.keys(), None)  # type: ignore
        )

        # Define progress bar
        pbar = (
            tqdm(
                # Prefix for the progressbar
                bar_format=f"{'':9}" + "{l_bar}{bar}{r_bar}",
                desc=f"{'':8}",
                total=len(X_and_mask_coarse.keys()),  # type: ignore
                unit="timestamp",
                position=0,
                leave=True,  # Keep progress on the screen after completion.
                options={"console": self.logger.console},
            )
            if self.show_progress is True and self.logger is not None
            else None
        )

        # Fit estimators
        if self.max_workers != 1:
            with ProcessPoolExecutor(max_workers=self.max_workers) as executor:
                # List of placeholders for the eventual result of a computation
                futures = {
                    # NOTE: Using executor.submit() can be safely used as key of
                    # dictionary since executor.submit() returns a Future object
                    # (https://docs.python.org/3/library/asyncio-future.html#future-object)
                    # and all of these objects are unique and hashable.
                    executor.submit(
                        self.get_estimator().fit,
                        X_and_mask_coarse[timestamp],
                        y_coarse[timestamp],
                        sample_weight=sample_weight[timestamp],  # type: ignore
                    ): timestamp
                    for timestamp in X_and_mask_coarse  # type: ignore
                }

                for future in as_completed(futures):
                    # Add result to dictionary of results
                    timestamp = futures[future]
                    self.estimators[timestamp] = future.result()

                    # Update progress bar with one more count per completed process
                    if pbar is not None:
                        pbar.update()

            # Make dictionary of estimators to be ordered as input X_and_mask_coarse
            # NOTE: multiprocessing may output results in a different order.
            self.estimators = {
                timestamp: self.estimators[timestamp] for timestamp in X_and_mask_coarse
            }

        else:
            for timestamp in X_and_mask_coarse:  # noqa: PLC0206
                self.estimators[timestamp] = self.get_estimator().fit(
                    X_and_mask_coarse[timestamp],
                    y_coarse[timestamp],
                    sample_weight=sample_weight[timestamp],  # type: ignore
                )

                # Update progress bar with one more count per completed process
                if pbar is not None:
                    pbar.update()

        # At the end close progress bar
        if pbar is not None:
            pbar.close()

        # NOTE: attribute `is_fitted_` must be set to `True` to let `sklearn` know that
        # the instance is already fitted.
        self.is_fitted_ = True

        return self

    def predict_single(
        self,
        timestamp: pd.Timestamp,
        X_and_mask_fine: np.ndarray | pd.DataFrame,
        correct: bool = True,
        X_and_mask_coarse: np.ndarray | pd.DataFrame | None = None,
        y_coarse: np.ndarray | pd.Series | None = None,
        coords_coarse: xr.Coordinates | None = None,
        coords_fine: xr.Coordinates | None = None,
        gridded: bool = True,
        dims: tuple | None = None,
        attrs: dict | None = None,
        path_out: Path | None = None,
    ) -> np.ndarray | xr.DataArray | None:
        """
        Predict fine target from fine predictors and masks (`X_and_mask_fine`).
        Additionally, if `correct` is set to `True`, correct prediction with
        finely-resampled residuals associated with the prediction of coarse target from
        coarse predictors and masks (`X_and_mask_coarse`). Note that to compute such
        residuals, the "true" coarse target (`y_coarse`) and the coarse and fine grid
        coordinates (`coords_coarse` and `coords_fine`) must be also issued.

        Note that this method only predicts for a single image. To predict for multiple
        images, use `predict()`.

        Parameters
        ----------

        timestamp : pd.Timestamp
            Timestamp associated with the data.

        X_and_mask_fine : np.ndarray or pd.DataFrame
            Fine predictors and masks.

        correct : bool, default=True
            Whether to correct the predicted fine target (from fine predictors and
            masks, `X_and_mask_fine`) using the finely-resampled residual for the
            prediction of the coarse target (from coarse predictors and masks,
            `X_and_mask_coarse`).

        X_and_mask_coarse : np.ndarray or pd.DataFrame or None, default=None
            Coarse predictors and masks. It must be issued if `correct` is `True`.

        y_coarse : np.ndarray or pd.Series or None, default=None
            The "true" coarse target. It must be issued if `correct` is `True`.

        coords_coarse : xarray.core.coordinates.Coordinates or None, default=None
            The coordinates of the coarse mesh. It must be issued if `correct` is
            `True`.

        coords_fine : xarray.core.coordinates.Coordinates or None, default=None
            The coordinates of the fine mesh. It must be issued if `correct` or
            `gridded` are `True`.

        gridded : bool, default=True
            Whether to return the predicted fine target in grid form (as an
            `xr.DataArray`) or flattened form (as a `pd.Series`).

        dims : tuple or None, default=None
            Labels for the dimensions of the predicted target if it is returned in grid
            form. If not issued, it is set to ("lat", "lon") by default.

        attrs : dict or None, default=None
            Attributes to set in the predicted target if it is returned in grid form. If
            not issued, it is set to:
                {
                    "standard_name": "land_surface_temperature",
                    "long_name": "Land surface temperature",
                    "units": "K",
                }

        path_out : Path or None, default=None
            The output path of the file for the predicted image. If not issued, the
            predicted target is instead returned.

        Returns
        -------

        y_fine_pred : np.ndarray or xr.DataArray or None
            Predicted fine target in flattened form (as a `np.ndarray`, if `gridded` is
            `False`) or grid form (as an `xr.DataArray` if `gridded` is `True`). If
            `path_out` is issued, the prediction is written to file and `None` is
            instead returned.

        """

        # Parse dims and attrs parameters
        dims = dims if dims is not None else ("lat", "lon")
        attrs = (
            attrs
            if attrs is not None
            else {
                "standard_name": "land_surface_temperature",
                "long_name": "Land surface temperature",
                "units": "K",
            }
        )

        # Raise error if residual correction is to be performed but required parameters
        # are missing
        if correct is True and any(
            elem is None
            for elem in [X_and_mask_coarse, y_coarse, coords_coarse, coords_fine]
        ):
            raise TypeError(
                "Parameters 'X_and_mask_coarse', 'y_coarse', 'coords_coarse' and"
                " 'coords_fine' must also be issued to perform residual"
                " correction."
            )

        # Raise error if the predicted target is wanted in grid form (not in ravelled
        # one) but required parameters are missing
        if gridded is True and coords_fine is None:
            raise TypeError(
                "Parameter 'coords_fine' must also be issued to make predicted"
                " target gridded."
            )

        # Convert true coarse target to a pandas Series if it is not already and
        # residual correction is considered (such condition would require usage of the
        # true coarse target)
        if not isinstance(y_coarse, pd.Series) and correct is True:
            y_coarse = pd.Series(y_coarse)

        # Predict fine target from fine predictors and masks using the the preprocessor
        # and the base model
        y_fine_pred = pd.Series(self.estimators[timestamp].predict(X_and_mask_fine))

        # If gridded prediction or residual correction are wanted, transform the
        # predicted fine target into grid form
        # NOTE: residual correction involves reprojection of the coarse residual into
        # the fine grid. The grid of the gridded predicted fine target may be used as
        # target of the matching reprojection.
        if gridded is True or correct is True:
            # Get shape of the fine grid
            shape_fine = tuple(reversed(list(coords_fine.sizes.values())))  # type: ignore

            # Convert flat predicted fine target into gridded format
            y_fine_pred = xr.DataArray(
                data=y_fine_pred.values.reshape(shape_fine),  # type: ignore
                coords=coords_fine,
                dims=("y", "x"),
                name="LST",
            )

        # If residual correction is wanted, correct the prediction using
        # finely resampled residuals associated with the prediction of the coarse target
        if correct is True:
            # Predict coarse target from coarse predictors and masks
            y_coarse_pred = pd.Series(
                self.estimators[timestamp].predict(X_and_mask_coarse)
            )

            # Compute respective residuals
            res_coarse = y_coarse - y_coarse_pred  # type: ignore

            # Get shape of the coarse grid
            shape_coarse = tuple(reversed(list(coords_coarse.sizes.values())))  # type: ignore

            # Express the residuals in the coarse grid
            res_coarse = xr.DataArray(
                data=res_coarse.values.reshape(shape_coarse),  # type: ignore
                coords=coords_coarse,
                dims=("y", "x"),
                name="LST",
            )

            # Refine the residuals by reprojecting then to the fine grid
            res_coarse_refined = selective_reproject_match(
                data_src=res_coarse,
                data_target=y_fine_pred,  # type: ignore
            )

            # Correct the fine target
            y_fine_pred = y_fine_pred + res_coarse_refined

            # If ravelled (flat) predicted fine target is wanted, ravel it
            if gridded is False:
                y_fine_pred = y_fine_pred.values.ravel()  # type: ignore

        # In case of gridded prediction, set type, time coordinate, NODATA value,
        # dimension labels and attributes of the data
        if gridded is True:
            # Set data type
            y_fine_pred = y_fine_pred.astype("float32")

            # Set time coordinate
            # WARNING: it is herein assumed that the timestamp is in the UTC timezone.
            y_fine_pred = y_fine_pred.expand_dims(  # type: ignore
                dim={"time": [timestamp.tz_localize("UTC")]}
            )

            # Write NODATA value
            y_fine_pred.rio.write_nodata(  # type: ignore
                input_nodata=-999,
                encoded=True,
                inplace=True,
            )

            # Set dimension labels
            if dims is not None:
                y_fine_pred = y_fine_pred.rename({"y": dims[0], "x": dims[1]})

            # Set attributes
            if attrs is not None:
                y_fine_pred.attrs = attrs  # type: ignore
                y_fine_pred["time"].attrs = {
                    "axis": "T",
                    "standard_name": "time",
                    "long_name": "Start sensing time of the satellite acquisition",
                }

        # If writing to file, write the predicted fine target
        if path_out is not None:
            # Create output directory if it does not exist
            path_out.parent.mkdir(  # type: ignore
                parents=True,
                exist_ok=True,
            )

            # Write to file
            if gridded is False:
                path_out = path_out.with_suffix(".csv")
                np.savetxt(fname=path_out, X=y_fine_pred)  # type: ignore
            else:
                # NOTE: rioxarray `to_raster()` cannot handle writing to NetCDF files,
                # but `to_netcdf()` can.
                if path_out.suffix == ".nc":
                    # NetCDF cannot handle pd.Timestamp type. Time will be converted to
                    # seconds since 1972-01-01 00:00:00 UTC, as in accordance with CF
                    # conventions
                    # NOTE: see https://cf-convention.github.io/Data/cf-conventions/cf-conventions-1.13/cf-conventions.pdf#page=42
                    y_fine_pred["time"] = (
                        y_fine_pred["time"] - pd.Timestamp("1972-01-01 00:00:00Z")
                    ).dt.total_seconds()  # type: ignore
                    y_fine_pred["time"].attrs = {  # type: ignore
                        "standard_name": "time",
                        "long_name": "Time",
                        "axis": "T",
                        "units": "seconds since 1972-1-1 00:00:00Z",
                        "calendar": "proleptic_gregorian",
                    }

                    y_fine_pred.to_netcdf(path_out)  # type: ignore
                else:
                    # In the case of no suffix, `to_raster()` considers GeoTIFF.
                    if path_out.suffix in [""]:
                        path_out = path_out.with_suffix(".tif")

                    y_fine_pred.rio.to_raster(path_out)  # type: ignore

            # Set y_fine_pred to None to return None at the end of the function
            y_fine_pred = None

        return y_fine_pred  # type: ignore

    def predict(
        self,
        X_and_mask_fine: dict[pd.Timestamp, np.ndarray | pd.DataFrame],
        correct: bool = True,
        X_and_mask_coarse: dict[pd.Timestamp, np.ndarray | pd.DataFrame] | None = None,
        y_coarse: dict[pd.Timestamp, np.ndarray | pd.Series] | None = None,
        coords_coarse: dict[pd.Timestamp, xr.Coordinates] | None = None,
        coords_fine: dict[pd.Timestamp, xr.Coordinates] | None = None,
        gridded: bool = True,
        dims: tuple | None = None,
        attrs: dict | None = None,
        path_out: dict[pd.Timestamp, Path] | None = None,
        *,
        _log: bool = True,
    ) -> dict[pd.Timestamp, np.ndarray | xr.DataArray] | None:
        """
        Predict fine target for multiple images using `predict_single()` for each one,
        keyed by timestamp.

        Parameters
        ----------

        X_and_mask_fine : dict[pd.Timestamp, np.ndarray or pd.DataFrame]
            Fine predictors and masks for each image, keyed by timestamp.

        correct : bool, default=True
            Whether to correct the predicted fine target for each image (from fine
            predictors and masks, `X_and_mask_fine`) using the finely-resampled residual
            for the prediction of the coarse target (from coarse predictors and masks,
            `X_and_mask_coarse`).

        X_and_mask_coarse : dict[pd.Timestamp, np.ndarray or pd.DataFrame] or None, default=None
            Coarse predictors and masks for each image, keyed by timestamp. It must be
            issued if `correct` is `True`.

        y_coarse : dict[pd.Timestamp, np.ndarray or pd.Series] or None, default=None
            The "true" coarse target, keyed by timestamp. It must be issued if `correct`
            is `True`.

        coords_coarse : dict[pd.Timestamp, xarray.core.coordinates.Coordinates] or None, default=None
            The coordinates of the coarse mesh for each image, keyed by timestamp. It
            must be issued if `correct` is `True`.

        coords_fine : dict[pd.Timestamp, xarray.core.coordinates.Coordinates] or None, default=None
            The coordinates of the fine mesh for each image, keyed by timestamp. It must
            be issued if `correct` or `gridded` are `True`.

        gridded : bool, default=True
            Whether to return the predicted fine target for each image in grid form (as
            an `xr.DataArray`) or in flattened form (as a `pd.Series`).

        dims : tuple or None, default=None
            Labels for the dimensions of the predicted target if it is returned in grid
            form. If not issued, it is set to ("y", "x") by default.

        attrs : dict or None, default=None
            Attributes to set in the predicted target if it is returned in grid form. If
            not issued, it is set as in accordance with the CF conventions
            (https://cf-convention.github.io/Data/cf-conventions/cf-conventions-1.13/cf-conventions.pdf#temperature-units):
                {
                    "standard_name": "land_surface_temperature", "long_name": "Land
                    surface temperature", "units": "K",
                }

        path_out : dict[pd.Timestamp, Path] or None, default=None
            The output path of the file for each predicted image, keyed by timestamp. If
            not issued, the predicted target is instead returned.

        _log : bool, default=True
            Whether to log messages into terminal.

        Returns
        -------

        y_fine_pred : dict[pd.Timestamp, np.ndarray or xr.DataArray] or None
            Predicted fine target for each image in flattened form (as a `np.ndarray`,
            if `gridded` is `False`) or grid form (as an `xr.DataArray` if `gridded` is
            `True`), keyed by timestamp. If `path_out` is issued, the predictions are
            written to files and `None` is instead returned.

        """
        if self.logger is not None and _log is True:
            self.logger.info("Predicting target...")

        # Transform parameters valued as None into dictionaries with None values (one
        # per image)
        X_and_mask_coarse = (
            X_and_mask_coarse
            if X_and_mask_coarse is not None
            else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
        )
        y_coarse = (
            y_coarse
            if y_coarse is not None
            else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
        )
        coords_coarse = (
            coords_coarse
            if coords_coarse is not None
            else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
        )
        coords_fine = (
            coords_fine
            if coords_fine is not None
            else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
        )
        path_out = (
            path_out
            if path_out is not None
            else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
        )

        # Define progress bar
        pbar = (
            tqdm(
                # Prefix for the progressbar
                bar_format=f"{'':9}" + "{l_bar}{bar}{r_bar}",
                desc=f"{'':8}",
                total=len(X_and_mask_fine.keys()),  # type: ignore
                unit="timestamp",
                position=0,
                leave=True,  # Keep progress on the screen after completion.
                options={"console": self.logger.console},
            )
            if self.show_progress is True and self.logger is not None
            else None
        )

        # Predict fine raw targets as a dictionary
        y_fine_pred = {}
        if self.max_workers != 1:
            with ProcessPoolExecutor(max_workers=self.max_workers) as executor:
                # List of placeholders for the eventual result of a computation
                futures = {
                    # NOTE: Using executor.submit() can be safely used as key of
                    # dictionary since executor.submit() returns a Future object
                    # (https://docs.python.org/3/library/asyncio-future.html#future-object)
                    # and all of these objects are unique and hashable.
                    executor.submit(
                        self.predict_single,
                        timestamp=timestamp,
                        X_and_mask_fine=X_and_mask_fine[timestamp],
                        correct=correct,
                        X_and_mask_coarse=X_and_mask_coarse[timestamp],  # type: ignore
                        y_coarse=y_coarse[timestamp],  # type: ignore
                        coords_coarse=coords_coarse[timestamp],  # type: ignore
                        coords_fine=coords_fine[timestamp],  # type: ignore
                        gridded=gridded,
                        dims=dims,
                        attrs=attrs,
                        path_out=path_out[timestamp],  # type: ignore
                    ): timestamp
                    for timestamp in X_and_mask_fine  # type: ignore
                }

                for future in as_completed(futures):
                    # Add result to dictionary of results
                    timestamp = futures[future]
                    y_fine_pred[timestamp] = future.result()

                    # Update progress bar with one more count per completed process
                    if pbar is not None:
                        pbar.update()

            # Make dictionary of predictions be ordered as input X_and_mask_fine
            # NOTE: multiprocessing may output results in a different order.
            y_fine_pred = {
                timestamp: y_fine_pred[timestamp]
                for timestamp in X_and_mask_fine  # type: ignore
            }

        else:
            for timestamp in X_and_mask_fine:  # noqa: PLC0206
                y_fine_pred[timestamp] = self.predict_single(
                    timestamp=timestamp,
                    X_and_mask_fine=X_and_mask_fine[timestamp],
                    correct=correct,
                    X_and_mask_coarse=X_and_mask_coarse[timestamp],  # type: ignore
                    y_coarse=y_coarse[timestamp],  # type: ignore
                    coords_coarse=coords_coarse[timestamp],  # type: ignore
                    coords_fine=coords_fine[timestamp],  # type: ignore
                    gridded=gridded,
                    dims=dims,
                    attrs=attrs,
                    path_out=path_out[timestamp],  # type: ignore
                )

                # Update progress bar with one more count per completed process
                if pbar is not None:
                    pbar.update()

        # At the end close progress bar
        if pbar is not None:
            pbar.close()

        # Convert y_fine_pred to None if it any of their values was written to files.
        if None not in path_out.values():  # type: ignore
            y_fine_pred = None

        return y_fine_pred  # type: ignore

    def predict_coarse(
        self,
        X_and_mask_coarse: dict[pd.Timestamp, np.ndarray | pd.DataFrame],
        coords_coarse: dict[pd.Timestamp, xr.Coordinates] | None = None,
        gridded: bool = True,
        dims: tuple | None = None,
        attrs: dict | None = None,
        path_out: dict[pd.Timestamp, Path] | None = None,
    ) -> dict[pd.Timestamp, np.ndarray | xr.DataArray] | None:
        """
        Predict coarse target for multiple images.

        Parameters
        ----------

        X_and_mask_coarse : dict[pd.Timestamp, np.ndarray or pd.DataFrame]
            Coarse predictors and masks for each image, keyed by timestamp.

        coords_coarse : dict[pd.Timestamp, xarray.core.coordinates.Coordinates] or None, default=None
            The coordinates of the coarse mesh for each image, keyed by timestamp. It
            must be issued if `gridded` is `True`.

        gridded : bool, default=True
            Whether to return the predicted coarse target for each image in grid form
            (as an `xr.DataArray`) or in flattened form (as a `pd.Series`).

        dims : tuple or None, default=None
            Labels for the dimensions of the predicted target if it is returned in grid
            form. If not issued, it is set to ("y", "x") by default.

        attrs : dict or None, default=None
            Attributes to set in the predicted target if it is returned in grid form. If
            not issued, it is set as in accordance with the CF conventions
            (https://cf-convention.github.io/Data/cf-conventions/cf-conventions-1.13/cf-conventions.pdf#temperature-units):
                {
                    "standard_name": "land_surface_temperature", "long_name": "Land
                    surface temperature", "units": "K",
                }

        path_out : Path or list[Path] or dict[Any, Path] or None, default=None
            The output path of the file for each predicted image. If not issued, the
            predicted target is instead returned.

        Returns
        -------

        y_coarse_pred : dict[pd.Timestamp, np.ndarray or xr.DataArray] or None
            Predicted coarse target for each image in flattened form (as a `np.ndarray`,
            if `gridded` is `False`) or grid form (as an `xr.DataArray` if `gridded` is
            `True`), keyed by timestamp. If `path_out` is issued, the prediction is
            written to file and `None` is instead returned.
        """

        y_coarse_pred = self.predict(
            X_and_mask_fine=X_and_mask_coarse,
            correct=False,
            coords_fine=coords_coarse,
            gridded=gridded,
            dims=dims,
            attrs=attrs,
            path_out=path_out,
        )

        return y_coarse_pred

    def score_single(
        self,
        timestamp: pd.Timestamp,
        X_and_mask_fine: np.ndarray | pd.DataFrame,
        y_fine: np.ndarray | pd.Series,
        correct: bool = True,
        calibrate: bool = False,
        X_and_mask_coarse: np.ndarray | pd.DataFrame | None = None,
        y_coarse: np.ndarray | pd.Series | None = None,
        coords_coarse: xr.Coordinates | None = None,
        coords_fine: xr.Coordinates | None = None,
        scorers: list[str] | None = None,
        sample_weight: np.ndarray | pd.Series | None = None,
    ) -> dict[str, float]:
        """
        Predict fine target and score the prediction.

        Note that this method only predicts and scores for a single image. To predict
        and score for multiple images, use `score()`.

        Parameters
        ----------

        timestamp : pd.Timestamp
            Timestamp associated with the data.

        X_and_mask_fine : np.ndarray or pd.DataFrame
            Fine predictors and masks.

        y_fine : np.ndarray or pd.Series
            The "true" fine target.

        correct : bool, default=True
            Whether to correct the predicted fine target (from fine predictors and
            masks, `X_and_mask_fine`) using the finely-resampled residual for the
            prediction of the coarse target (from coarse predictors and masks,
            `X_and_mask_coarse`).

        calibrate : bool, default=False
            Whether to calibrate the predicted fine target with the coarse validation
            target. This is done by offsetting and scaling the predicted fine target
            with the transform that makes the coarse true target (`y_coarse`) have the
            same mean and standard deviation as the validation coarse one (coarsened
            `y_fine`). Such transformation is an attempt to account for discrepancies
            between source and validation platforms at a common coarse grid from the
            computed scores.

        X_and_mask_coarse : np.ndarray or pd.DataFrame or None, default=None
            Coarse predictors and masks. It must be issued if `correct` is `True`.

        y_coarse : np.ndarray or pd.Series or None, default=None
            The "true" coarse target.  It must be issued if `correct` or `calibrate` are
            `True`.

        coords_coarse : xarray.core.coordinates.Coordinates or None, default=None
            The coordinates of the coarse mesh. It must be issued if `correct` or
            `calibrate` are `True`.

        coords_fine : xarray.core.coordinates.Coordinates or None, default=None
            The coordinates of the fine mesh. It must be issued if `correct` or
            `calibrate` are `True`.

        scorers : list[str], default=["r2", "r2_oos", "rmse", "rmse_delta", "mae", "mae_delta", "mbe"]
            Aliases of the scorers to consider.

        sample_weight : np.ndarray or pd.Series or None, default=None
            Weight of each sample in the score.

        Returns
        -------

        score : dict[str, float]
            Prediction scores.
        """

        # Define default value for scorers argument
        if scorers is None:
            scorers = ["r2", "r2_oos", "rmse", "rmse_delta", "mae", "mae_delta", "mbe"]

        # If y_fine is a Series, reset its indexes. The analogous follows for
        # sample_weight. This is required, since indexes of y_fine, y_fine_pred and
        # y_fine_dummy_pred and sample_weight should match when combining them into a
        # single DataFrame afterwards.
        if isinstance(y_fine, pd.Series):
            y_fine = y_fine.reset_index(drop=True)
        if isinstance(sample_weight, pd.Series):
            sample_weight = sample_weight.reset_index(drop=True)

        # Predict fine target
        y_fine_pred = pd.Series(
            self.predict_single(
                timestamp=timestamp,
                X_and_mask_fine=X_and_mask_fine,
                correct=correct,
                X_and_mask_coarse=X_and_mask_coarse,
                y_coarse=y_coarse,
                coords_coarse=coords_coarse,
                coords_fine=coords_fine,
                gridded=False,
            )  # type: ignore
        )

        # Predict fine target from predictors using the dummy mean model
        # NOTE: this is required for computing out-of-sample coefficient of
        # determination
        y_fine_dummy_pred = (
            self.estimators[timestamp]
            .pipeline.named_steps["regressor"]
            .dummy_mean_model.predict(X_and_mask_fine)
        )

        # Calibrate the fine targets predicted by downscaler and dummy mean model with
        # the transform that would make the coarse true target have the same mean and
        # standard deviation as the coarsened fine validation one.
        if calibrate is True:
            # Express coarse true target in its grid
            shape_coarse = tuple(reversed(list(coords_coarse.sizes.values())))  # type: ignore
            y_coarse_grid = xr.DataArray(
                data=(
                    y_coarse.values if isinstance(y_coarse, pd.Series) else y_coarse
                ).reshape(  # type: ignore
                    shape_coarse  # type: ignore
                ),
                coords=coords_coarse,
                dims=("y", "x"),
                name="LST",
            )

            # Express fine validation target in its grid
            shape_fine = tuple(reversed(list(coords_fine.sizes.values())))  # type: ignore
            y_fine_grid = xr.DataArray(
                data=(
                    y_fine.values if isinstance(y_fine, pd.Series) else y_fine
                ).reshape(  # type: ignore
                    shape_fine  # type: ignore
                ),
                coords=coords_fine,
                dims=("y", "x"),
                name="LST",
            )

            # Reproject fine validation target to coarse grid
            y_fine_coarse = selective_reproject_match(
                data_src=y_fine_grid,
                data_target=y_coarse_grid,  # type: ignore
            )

            # Calibrate fine target predicted by downscaler
            # NOTE: https://math.stackexchange.com/a/2943606/209790
            y_fine_pred = (
                y_fine_coarse.mean().item()  # type: ignore
                + y_fine_coarse.std().item()  # type: ignore
                / y_coarse.std()  # type: ignore
                * (y_fine_pred - y_coarse.mean())  # type: ignore
            )

            # Calibrate fine target predicted by dummy mean model
            y_fine_dummy_pred = (
                y_fine_coarse.mean().item()  # type: ignore
                + y_fine_coarse.std().item()  # type: ignore
                / y_coarse.std()  # type: ignore
                * (y_fine_dummy_pred - y_coarse.mean())  # type: ignore
            )

        # Combine the true and predicted targets into a same DataFrame (so that all
        # records containing any nan may be later dropped and the prediction score
        # afterwards computed)
        data = pd.DataFrame(
            data={
                "y_true": y_fine,
                "y_pred": y_fine_pred,
                "y_dummy_pred": y_fine_dummy_pred,
                **(
                    {
                        "sample_weight": sample_weight,
                    }
                    if sample_weight is not None
                    else {}
                ),
            }
        )

        # Drop nan
        data = data.dropna()

        # Compute prediction score
        score = {
            # Coefficient of determination
            "r2": r2(
                y_true=data["y_true"],
                y_pred=data["y_pred"],
                sample_weight=(
                    data["sample_weight"] if sample_weight is not None else None
                ),
            ),
            # Out-of-sample coefficient of determination
            # [NOTE: this is such that it uses a dummy mean model (simply the arithmetic
            # mean of the masked inference coarse targets) as reference.]
            "r2_oos": r2_oos(
                y_true=data["y_true"],
                y_pred=data["y_pred"],
                y_dummy_pred=data["y_dummy_pred"],
                sample_weight=(
                    data["sample_weight"] if sample_weight is not None else None
                ),
            ),
            # Root mean squared error
            "rmse": rmse(
                y_true=data["y_true"],
                y_pred=data["y_pred"],
                sample_weight=(
                    data["sample_weight"] if sample_weight is not None else None
                ),
            ),
            # Root mean squared error of the standardized target (using true target
            # statistics)
            "rmse_delta": rmse_delta(
                y_true=data["y_true"],
                y_pred=data["y_pred"],
                sample_weight=(
                    data["sample_weight"] if sample_weight is not None else None
                ),
            ),
            # Mean absolute error
            "mae": mae(
                y_true=data["y_true"],
                y_pred=data["y_pred"],
                sample_weight=(
                    data["sample_weight"] if sample_weight is not None else None
                ),
            ),
            # Mean absolute error of the standardized target (using true
            # target statistics)
            "mae_delta": mae_delta(
                y_true=data["y_true"],
                y_pred=data["y_pred"],
                sample_weight=(
                    data["sample_weight"] if sample_weight is not None else None
                ),
            ),
            # Mean bias error
            "mbe": mbe(
                y_true=data["y_true"],
                y_pred=data["y_pred"],
                sample_weight=(
                    data["sample_weight"] if sample_weight is not None else None
                ),
            ),
        }

        # Select solely scores of interest
        score = {
            scorer: score_i for scorer, score_i in score.items() if scorer in scorers
        }

        return score

    def score(
        self,
        X_and_mask_fine: dict[pd.Timestamp, np.ndarray | pd.DataFrame],
        y_fine: dict[pd.Timestamp, np.ndarray | pd.Series],
        correct: bool = True,
        calibrate: bool = False,
        X_and_mask_coarse: dict[pd.Timestamp, np.ndarray | pd.DataFrame] | None = None,
        y_coarse: dict[pd.Timestamp, np.ndarray | pd.Series] | None = None,
        coords_coarse: dict[pd.Timestamp, xr.Coordinates] | None = None,
        coords_fine: dict[pd.Timestamp, xr.Coordinates] | None = None,
        aggregate: bool = False,
        scorers: list[str] | None = None,
        sample_weight: dict[pd.Timestamp, np.ndarray | pd.Series] | None = None,
    ) -> dict[str, float] | dict[pd.Timestamp, dict[str, float]]:
        """
        Predict fine target and score for multiple images individually (if `aggregate`
        is set to `False`) or combined (if `aggregate` is set to `True`).

        Parameters
        ----------

        X_and_mask_fine : dict[pd.Timestamp, np.ndarray or pd.DataFrame]
            Fine predictors and masks, keyed by timestamp.

        y_fine : dict[pd.Timestamp, np.ndarray or pd.Series]
            The "true" fine target, keyed by timestamp.

        correct : bool, default=True
            Whether to correct the predicted fine target (from fine predictors and
            masks, `X_and_mask_fine`) using the finely-resampled residual for the
            prediction of the coarse target (from coarse predictors and masks,
            `X_and_mask_coarse`).

        calibrate : bool, default=False
            Whether to calibrate the predicted fine target with the coarse validation
            target for each timestamp. This is done by offsetting and scaling the
            predicted fine target with the transform that makes the coarse true target
            (`y_coarse`) have the same mean and standard deviation as the validation
            coarse one (coarsened `y_fine`) for each timestamp. Such transformation is
            an attempt to account for discrepancies between source and validation
            platforms at a common coarse grid from the computed scores.

        X_and_mask_coarse : dict[pd.Timestamp, np.ndarray or pd.DataFrame] or None, default=None
            Coarse predictors and masks, keyed by timestamp. It must be issued if
            `correct` is `True`.

        y_coarse : dict[pd.Timestamp, np.ndarray or pd.Series] or None, default=None
            The "true" coarse target, keyed by timestamp. It must be issued if `correct`
            or `calibrate` are `True`.

        coords_coarse : dict[pd.Timestamp, xarray.core.coordinates.Coordinates] or None, default=None
            The coordinates of the coarse mesh for each image, keyed by timestamp. It
            must be issued if `correct` or `calibrate` are `True`.

        coords_fine : dict[pd.Timestamp, xarray.core.coordinates.Coordinates] or None, default=None
            The coordinates of the fine mesh for each image, keyed by timestamp. It must
            be issued if `correct` or `calibrate` are `True`.

        aggregate : bool, default=False
            Whether to compute scores for images individually (`False`) or combined
            (`True`).

        scorers : list[str], default=["r2", "r2_oos", "rmse", "rmse_delta", "mae", "mae_delta", "mbe"]
            Aliases of the scorers to consider.

        sample_weight : dict[pd.Timestamp, np.ndarray or pd.Series] None, default=None
            Weights of the samples in the score, keyed by timestamp.

        Returns
        -------

        score : dict[str, float] or dict[pd.Timestamp, dict[str, float]]
            Prediction scores for each image (if `aggregate` is set to `False`) or all
            of them combined (if `aggregate` is set to `True`).
        """

        if self.logger is not None:
            self.logger.info("Predicting target and scoring...")

        # Define default value for scorers argument
        if scorers is None:
            scorers = ["r2", "r2_oos", "rmse", "rmse_delta", "mae", "mae_delta", "mbe"]

        # Transform parameters valued as None into dictionaries with None values (one
        # per image)
        X_and_mask_coarse = (
            X_and_mask_coarse
            if X_and_mask_coarse is not None
            else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
        )
        y_coarse = (
            y_coarse
            if y_coarse is not None
            else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
        )
        coords_coarse = (
            coords_coarse
            if coords_coarse is not None
            else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
        )
        coords_fine = (
            coords_fine
            if coords_fine is not None
            else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
        )
        sample_weight = (
            sample_weight
            if sample_weight is not None
            else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
        )

        # If parameter "aggregate" is False, score for each timestamp individually
        if aggregate is False:
            # Define progress bar
            pbar = (
                tqdm(
                    # Prefix for the progressbar
                    bar_format=f"{'':9}" + "{l_bar}{bar}{r_bar}",
                    desc=f"{'':8}",
                    total=len(X_and_mask_fine.keys()),  # type: ignore
                    unit="timestamp",
                    position=0,
                    leave=True,  # Keep progress on the screen after completion.
                    options={"console": self.logger.console},
                )
                if self.show_progress is True and self.logger is not None
                else None
            )

            # Predict scores as a dictionary
            score = {}
            if self.max_workers != 1:
                with ProcessPoolExecutor(max_workers=self.max_workers) as executor:
                    # List of placeholders for the eventual result of a computation
                    futures = {
                        # NOTE: Using executor.submit() can be safely used as key of
                        # dictionary since executor.submit() returns a Future object
                        # (https://docs.python.org/3/library/asyncio-future.html#future-object)
                        # and all of these objects are unique and hashable.
                        executor.submit(
                            self.score_single,
                            timestamp=timestamp,
                            X_and_mask_fine=X_and_mask_fine[timestamp],
                            y_fine=y_fine[timestamp],
                            correct=correct,
                            calibrate=calibrate,
                            X_and_mask_coarse=X_and_mask_coarse[timestamp],  # type: ignore
                            y_coarse=y_coarse[timestamp],  # type: ignore
                            coords_coarse=coords_coarse[timestamp],  # type: ignore
                            coords_fine=coords_fine[timestamp],  # type: ignore
                            scorers=scorers,
                            sample_weight=sample_weight[timestamp],  # type: ignore
                        ): timestamp
                        for timestamp in X_and_mask_fine  # type: ignore
                    }

                    for future in as_completed(futures):
                        # Add result to dictionary of results
                        timestamp = futures[future]
                        score[timestamp] = future.result()

                        # Update progress bar with one more count per completed process
                        if pbar is not None:
                            pbar.update()

                # Make dictionary of scores be ordered as input X_and_mask_fine
                # NOTE: multiprocessing may output results in a different order.
                score = {timestamp: score[timestamp] for timestamp in X_and_mask_fine}  # type: ignore

            else:
                for timestamp in X_and_mask_fine:  # noqa: PLC0206
                    score[timestamp] = self.score_single(
                        timestamp=timestamp,
                        X_and_mask_fine=X_and_mask_fine[timestamp],
                        y_fine=y_fine[timestamp],
                        correct=correct,
                        calibrate=calibrate,
                        X_and_mask_coarse=X_and_mask_coarse[timestamp],  # type: ignore
                        y_coarse=y_coarse[timestamp],  # type: ignore
                        coords_coarse=coords_coarse[timestamp],  # type: ignore
                        coords_fine=coords_fine[timestamp],  # type: ignore
                        scorers=scorers,
                        sample_weight=sample_weight[timestamp],  # type: ignore
                    )
                    # Update progress bar with one more count per completed process
                    if pbar is not None:
                        pbar.update()

            # At the end close progress bar
            if pbar is not None:
                pbar.close()

        # If parameter "aggregate" is True, score for the combined data
        else:
            # Convert true fine target for each image to pandas Series if it is not
            # already.
            y_fine = {
                timestamp: (
                    pd.Series(y_fine[timestamp])
                    if not isinstance(y_fine[timestamp], pd.Series)
                    else y_fine[timestamp]
                )
                for timestamp in X_and_mask_fine
            }

            # Get statistics of true fine target for each image (to use them later to
            # compute RMSE of the standardized target)
            y_fine_mean = {
                timestamp: y_fine[timestamp].mean() for timestamp in X_and_mask_fine
            }
            y_fine_std = {
                timestamp: y_fine[timestamp].std() for timestamp in X_and_mask_fine
            }

            # Compute standardized true fine target for each image (using true fine
            # target statistics)
            y_fine_delta = {
                timestamp: (
                    y_fine[timestamp] - y_fine_mean[timestamp]  # type: ignore
                )
                / y_fine_std[timestamp]
                for timestamp in X_and_mask_fine
            }

            # Predict fine target for each image
            y_fine_pred = {
                key: pd.Series(value)  # type: ignore
                for key, value in self.predict(
                    X_and_mask_fine=X_and_mask_fine,
                    correct=correct,
                    X_and_mask_coarse=X_and_mask_coarse,  # type: ignore
                    y_coarse=y_coarse,
                    coords_coarse=coords_coarse,
                    coords_fine=coords_fine,
                    gridded=False,
                    _log=False,
                ).items()  # type: ignore
            }

            # Predict fine target for each image using the dummy mean model
            # NOTE: this is required for computing out-of-sample coefficient of
            # determination.
            y_fine_dummy_pred = {
                timestamp: pd.Series(
                    self.estimators[timestamp]
                    .pipeline.named_steps["regressor"]
                    .dummy_mean_model.predict(X_and_mask_fine[timestamp])
                )
                for timestamp in X_and_mask_fine
            }

            # Calibrate the fine targets predicted by downscaler and dummy mean model
            # with the transform that would make the coarse true target have the same
            # mean and standard deviation as the coarsened fine validation one.
            if calibrate is True:
                # Express coarse true target in its grid
                shape_coarse = {
                    timestamp: tuple(
                        reversed(list(coords_coarse[timestamp].sizes.values()))  # type: ignore
                    )  # type: ignore
                    for timestamp in X_and_mask_fine
                }
                y_coarse_grid = {
                    timestamp: xr.DataArray(
                        data=(
                            y_coarse[timestamp].values  # type: ignore
                            if isinstance(y_coarse[timestamp], pd.Series)  # type: ignore
                            else y_coarse[timestamp]  # type: ignore
                        ).reshape(  # type: ignore
                            shape_coarse[timestamp]  # type: ignore
                        ),
                        coords=coords_coarse[timestamp],  # type: ignore
                        dims=("y", "x"),
                        name="LST",
                    )
                    for timestamp in X_and_mask_fine
                }

                # Express fine validation target in its  grid
                shape_fine = {
                    timestamp: tuple(
                        reversed(list(coords_fine[timestamp].sizes.values()))  # type: ignore
                    )  # type: ignore
                    for timestamp in X_and_mask_fine
                }  # type: ignore
                y_fine_grid = {
                    timestamp: xr.DataArray(
                        data=(
                            y_fine[timestamp].values  # type: ignore
                            if isinstance(y_fine[timestamp], pd.Series)  # type: ignore
                            else y_fine[timestamp]
                        ).reshape(  # type: ignore
                            shape_fine[timestamp]  # type: ignore
                        ),
                        coords=coords_fine[timestamp],  # type: ignore
                        dims=("y", "x"),
                        name="LST",
                    )
                    for timestamp in X_and_mask_fine
                }

                # Reproject fine validation target to coarse grid
                y_fine_coarse = {
                    timestamp: selective_reproject_match(
                        data_src=y_fine_grid[timestamp],  # type: ignore
                        data_target=y_coarse_grid[timestamp],  # type: ignore
                    )
                    for timestamp in X_and_mask_fine  # type: ignore
                }

                # Calibrate fine target predicted by downscaler
                # NOTE: https://math.stackexchange.com/a/2943606/209790
                y_fine_pred = {
                    timestamp: (
                        y_fine_coarse[timestamp].mean().item()  # type: ignore
                        + y_fine_coarse[timestamp].std().item()  # type: ignore
                        / y_coarse[timestamp].std()  # type: ignore
                        * (y_fine_pred[timestamp] - y_coarse[timestamp].mean())  # type: ignore
                    )
                    for timestamp in X_and_mask_fine  # type: ignore
                }

                # Calibrate fine target predicted by dummy mean model
                y_fine_dummy_pred = {
                    timestamp: (
                        y_fine_coarse[timestamp].mean().item()  # type: ignore
                        + y_fine_coarse[timestamp].std().item()  # type: ignore
                        / y_coarse[timestamp].std()  # type: ignore
                        * (y_fine_dummy_pred[timestamp] - y_coarse[timestamp].mean())  # type: ignore
                    )
                    for timestamp in X_and_mask_fine  # type: ignore
                }

            # Compute standardized predicted fine target for each image (using true fine
            # raw target statistics)
            y_fine_pred_delta = {
                timestamp: (y_fine_pred[timestamp] - y_fine_mean[timestamp])
                / y_fine_std[timestamp]
                for timestamp in X_and_mask_fine  # type: ignore
            }

            # Combine variables of all timestamps
            y_fine = pd.concat(y_fine, ignore_index=True)  # type: ignore
            y_fine_pred = pd.concat(y_fine_pred, ignore_index=True)  # type: ignore
            y_fine_dummy_pred = pd.concat(y_fine_dummy_pred, ignore_index=True)  # type: ignore
            y_fine_delta = pd.concat(y_fine_delta, ignore_index=True)  # type: ignore
            y_fine_pred_delta = pd.concat(y_fine_pred_delta, ignore_index=True)  # type: ignore
            sample_weight = (
                pd.concat(sample_weight, ignore_index=True)  # type: ignore
                if not any(value is None for value in sample_weight.values())  # type: ignore
                else None
            )

            # Combine the true and predicted targets into a common DataFrame (so
            # that all records containing any nan may be later dropped and the
            # prediction score afterwards computed)
            data = pd.DataFrame(
                data={
                    "y_true": y_fine,
                    "y_pred": y_fine_pred,
                    "y_dummy_pred": y_fine_dummy_pred,
                    "y_true_delta": y_fine_delta,
                    "y_pred_delta": y_fine_pred_delta,
                    **(
                        {
                            "sample_weight": sample_weight,
                        }
                        if sample_weight is not None
                        else {}
                    ),
                }
            )

            # Drop nan
            data = data.dropna()

            # Compute prediction score
            score = {
                # Coefficient of determination
                "r2": r2(
                    y_true=data["y_true"],
                    y_pred=data["y_pred"],
                    sample_weight=(
                        data["sample_weight"] if sample_weight is not None else None
                    ),
                ),
                # Out-of-sample coefficient of determination
                # [NOTE: this is such that it uses a dummy mean model (simply the
                # arithmetic mean of the masked inference coarse targets) as
                # reference.]
                "r2_oos": r2_oos(
                    y_true=data["y_true"],
                    y_pred=data["y_pred"],
                    y_dummy_pred=data["y_dummy_pred"],
                    sample_weight=(
                        data["sample_weight"] if sample_weight is not None else None
                    ),
                ),
                # Root mean squared error
                "rmse": rmse(
                    y_true=data["y_true"],
                    y_pred=data["y_pred"],
                    sample_weight=(
                        data["sample_weight"] if sample_weight is not None else None
                    ),
                ),
                # Root mean squared error of the standardized target (using true
                # target statistics)
                "rmse_delta": rmse(
                    y_true=data["y_true_delta"],
                    y_pred=data["y_pred_delta"],
                    sample_weight=(
                        data["sample_weight"] if sample_weight is not None else None
                    ),
                ),
                # Mean absolute error
                "mae": mae(
                    y_true=data["y_true"],
                    y_pred=data["y_pred"],
                    sample_weight=(
                        data["sample_weight"] if sample_weight is not None else None
                    ),
                ),
                # Mean absolute error of the standardized target (using true
                # target statistics)
                "mae_delta": mae(
                    y_true=data["y_true_delta"],
                    y_pred=data["y_pred_delta"],
                    sample_weight=(
                        data["sample_weight"] if sample_weight is not None else None
                    ),
                ),
                # Mean bias error
                "mbe": mbe(
                    y_true=data["y_true"],
                    y_pred=data["y_pred"],
                    sample_weight=(
                        data["sample_weight"] if sample_weight is not None else None
                    ),
                ),
            }

            # Select solely scores of interest
            score = {
                scorer: score_i
                for scorer, score_i in score.items()
                if scorer in scorers
            }

        return score

    def score_coarse(
        self,
        X_and_mask_coarse: dict[pd.Timestamp, np.ndarray | pd.DataFrame],
        y_coarse: dict[pd.Timestamp, np.ndarray | pd.Series],
        aggregate: bool = False,
        scorers: list[str] | None = None,
        sample_weight: dict[pd.Timestamp, np.ndarray | pd.Series] | None = None,
    ) -> dict[str, float] | dict[pd.Timestamp, dict[str, float]]:
        """
        Predict coarse target and score for multiple images individually (if `aggregate`
        is set to `False`) or combined (if `aggregate` is set to `True`).

        Parameters
        ----------

        X_and_mask_coarse : dict[pd.Timestamp, np.ndarray | pd.DataFrame]
            Coarse predictors and masks, keyed by timestamp.

        y_coarse : dict[pd.Timestamp, np.ndarray | pd.Series]
            The "true" coarse target, keyed by timestamp.

        aggregate : bool, default=False
            Whether to compute scores for images individually (`False`) or combined
            (`True`).

        scorers : list[str], default=["r2", "r2_oos", "rmse", "rmse_delta", "mae", "mae_delta", "mbe"]
            Aliases of the scorers to consider.

        sample_weight : dict[pd.Timestamp, np.ndarray or pd.Series] None, default=None
            Weights of the samples in the score, keyed by timestamp.

        Returns
        -------

        score : dict[str, float] or dict[pd.Timestamp, dict[str, float]]
            Prediction scores for each image (if `aggregate` is set to `False`) or all
            of them combined (if `aggregate` is set to `True`)
        """

        score = self.score(
            X_and_mask_fine=X_and_mask_coarse,
            y_fine=y_coarse,
            correct=False,
            aggregate=aggregate,
            scorers=scorers,
            sample_weight=sample_weight,
        )

        return score

    def save(self, path: Path) -> None:
        """
        Write the instance to `path` with `joblib`.

        Parameters
        ----------
        path : Path
            Path to write the instance to.
        """

        joblib.dump(value=self, filename=path)

base_model instance-attribute

base_model = base_model

cols_X instance-attribute

cols_X = cols_X

cols_mask property writable

cols_mask: list | ndarray

encode instance-attribute

encode = encode

estimators instance-attribute

estimators = {}

is_fitted_ instance-attribute

is_fitted_ = False

lasso_alpha instance-attribute

lasso_alpha = lasso_alpha

lasso_sel instance-attribute

lasso_sel = lasso_sel

logger instance-attribute

logger = logger

max_workers property writable

max_workers: int

scale instance-attribute

scale = scale

show_progress instance-attribute

show_progress = show_progress

__init__

__init__(
    base_model: Regressor,
    cols_X: list | ndarray,
    cols_mask: list | ndarray | None = None,
    scale: Literal["standardize", "min_max_normalize"] | None = "standardize",
    encode: Literal["one_hot", "dummy"] | None = "dummy",
    lasso_sel: bool = False,
    lasso_alpha: float = 1.0,
    max_workers: int = 1,
    logger: RichLogger | None = None,
    show_progress: bool = True,
) -> None
Source code in src/s3lst_ds/downscaling/piecewise_downscaling.py
def __init__(
    self,
    base_model: Regressor,
    cols_X: list | np.ndarray,
    cols_mask: list | np.ndarray | None = None,
    scale: Literal["standardize", "min_max_normalize"] | None = "standardize",
    encode: Literal["one_hot", "dummy"] | None = "dummy",
    lasso_sel: bool = False,
    lasso_alpha: float = 1.0,
    max_workers: int = 1,
    logger: RichLogger | None = None,
    show_progress: bool = True,
) -> None:

    super().__init__()
    # NOTE: attribute `is_fitted_` is set to `True` after fitting to let `sklearn`
    # know that the instance is already fitted.
    self.is_fitted_ = False
    self.base_model = base_model
    self.cols_X = cols_X
    self._cols_mask = cols_mask if cols_mask is not None else []
    self.scale = scale  # type: ignore
    self.encode = encode
    self.lasso_sel = lasso_sel
    self.lasso_alpha = lasso_alpha
    self.max_workers = max_workers
    self.logger = logger
    self.show_progress = show_progress
    self.estimators = {}

fit

fit(
    X_and_mask_coarse: dict[Timestamp, ndarray | DataFrame],
    y_coarse: dict[Timestamp, ndarray | Series],
    sample_weight: dict[Timestamp, ndarray | Series] | None = None,
) -> Self

Fit an estimator (preprocessing transformers and the general base model) to training coarse data for each timestamp.

Parameters:

Name Type Description Default
X_and_mask_coarse dict[Timestamp, ndarray or DataFrame]

The training coarse predictors and masks, keyed by timestamp.

required
y_coarse dict[Timestamp, ndarray or Series]

The training coarse target, keyed by timestamp.

required
sample_weight dict[Timestamp, ndarray or Series] or None

Weights of the samples in the cost function of the model, keyed by timestamp.

None

Returns:

Name Type Description
self PiecewiseDownscaler

The fitted instance itself.

Source code in src/s3lst_ds/downscaling/piecewise_downscaling.py
def fit(
    self,
    X_and_mask_coarse: dict[pd.Timestamp, np.ndarray | pd.DataFrame],
    y_coarse: dict[pd.Timestamp, np.ndarray | pd.Series],
    sample_weight: dict[pd.Timestamp, np.ndarray | pd.Series] | None = None,
) -> Self:
    """
    Fit an estimator (preprocessing transformers and the general base model) to
    training coarse data for each timestamp.

    Parameters
    ----------

    X_and_mask_coarse : dict[pd.Timestamp, np.ndarray or pd.DataFrame]
        The training coarse predictors and masks, keyed by timestamp.

    y_coarse : dict[pd.Timestamp, np.ndarray or pd.Series]
        The training coarse target, keyed by timestamp.

    sample_weight : dict[pd.Timestamp, np.ndarray or pd.Series] or None, default=None
        Weights of the samples in the cost function of the model, keyed by
        timestamp.

    Returns
    -------

    self : PiecewiseDownscaler
        The fitted instance itself.

    """

    if self.logger is not None:
        self.logger.info("Fitting estimators...")

    # Transform parameters valued as None into dictionaries with None values (one
    # per image)
    sample_weight = (
        sample_weight
        if sample_weight is not None
        else dict.fromkeys(X_and_mask_coarse.keys(), None)  # type: ignore
    )

    # Define progress bar
    pbar = (
        tqdm(
            # Prefix for the progressbar
            bar_format=f"{'':9}" + "{l_bar}{bar}{r_bar}",
            desc=f"{'':8}",
            total=len(X_and_mask_coarse.keys()),  # type: ignore
            unit="timestamp",
            position=0,
            leave=True,  # Keep progress on the screen after completion.
            options={"console": self.logger.console},
        )
        if self.show_progress is True and self.logger is not None
        else None
    )

    # Fit estimators
    if self.max_workers != 1:
        with ProcessPoolExecutor(max_workers=self.max_workers) as executor:
            # List of placeholders for the eventual result of a computation
            futures = {
                # NOTE: Using executor.submit() can be safely used as key of
                # dictionary since executor.submit() returns a Future object
                # (https://docs.python.org/3/library/asyncio-future.html#future-object)
                # and all of these objects are unique and hashable.
                executor.submit(
                    self.get_estimator().fit,
                    X_and_mask_coarse[timestamp],
                    y_coarse[timestamp],
                    sample_weight=sample_weight[timestamp],  # type: ignore
                ): timestamp
                for timestamp in X_and_mask_coarse  # type: ignore
            }

            for future in as_completed(futures):
                # Add result to dictionary of results
                timestamp = futures[future]
                self.estimators[timestamp] = future.result()

                # Update progress bar with one more count per completed process
                if pbar is not None:
                    pbar.update()

        # Make dictionary of estimators to be ordered as input X_and_mask_coarse
        # NOTE: multiprocessing may output results in a different order.
        self.estimators = {
            timestamp: self.estimators[timestamp] for timestamp in X_and_mask_coarse
        }

    else:
        for timestamp in X_and_mask_coarse:  # noqa: PLC0206
            self.estimators[timestamp] = self.get_estimator().fit(
                X_and_mask_coarse[timestamp],
                y_coarse[timestamp],
                sample_weight=sample_weight[timestamp],  # type: ignore
            )

            # Update progress bar with one more count per completed process
            if pbar is not None:
                pbar.update()

    # At the end close progress bar
    if pbar is not None:
        pbar.close()

    # NOTE: attribute `is_fitted_` must be set to `True` to let `sklearn` know that
    # the instance is already fitted.
    self.is_fitted_ = True

    return self

get_estimator

get_estimator() -> DownscalerEstimator
Source code in src/s3lst_ds/downscaling/piecewise_downscaling.py
def get_estimator(self) -> DownscalerEstimator:
    estimator = DownscalerEstimator(
        base_model=copy.deepcopy(self.base_model),
        cols_X=self.cols_X,
        cols_mask=self.cols_mask,
        scale=self.scale,  # type: ignore
        encode=self.encode,  # type: ignore
        lasso_sel=self.lasso_sel,
        lasso_alpha=self.lasso_alpha,
    )
    return estimator

predict

predict(
    X_and_mask_fine: dict[Timestamp, ndarray | DataFrame],
    correct: bool = True,
    X_and_mask_coarse: dict[Timestamp, ndarray | DataFrame] | None = None,
    y_coarse: dict[Timestamp, ndarray | Series] | None = None,
    coords_coarse: dict[Timestamp, Coordinates] | None = None,
    coords_fine: dict[Timestamp, Coordinates] | None = None,
    gridded: bool = True,
    dims: tuple | None = None,
    attrs: dict | None = None,
    path_out: dict[Timestamp, Path] | None = None,
    *,
    _log: bool = True,
) -> dict[Timestamp, ndarray | DataArray] | None

Predict fine target for multiple images using predict_single() for each one, keyed by timestamp.

Parameters:

Name Type Description Default
X_and_mask_fine dict[Timestamp, ndarray or DataFrame]

Fine predictors and masks for each image, keyed by timestamp.

required
correct bool

Whether to correct the predicted fine target for each image (from fine predictors and masks, X_and_mask_fine) using the finely-resampled residual for the prediction of the coarse target (from coarse predictors and masks, X_and_mask_coarse).

True
X_and_mask_coarse dict[Timestamp, ndarray or DataFrame] or None

Coarse predictors and masks for each image, keyed by timestamp. It must be issued if correct is True.

None
y_coarse dict[Timestamp, ndarray or Series] or None

The "true" coarse target, keyed by timestamp. It must be issued if correct is True.

None
coords_coarse dict[Timestamp, Coordinates] or None

The coordinates of the coarse mesh for each image, keyed by timestamp. It must be issued if correct is True.

None
coords_fine dict[Timestamp, Coordinates] or None

The coordinates of the fine mesh for each image, keyed by timestamp. It must be issued if correct or gridded are True.

None
gridded bool

Whether to return the predicted fine target for each image in grid form (as an xr.DataArray) or in flattened form (as a pd.Series).

True
dims tuple or None

Labels for the dimensions of the predicted target if it is returned in grid form. If not issued, it is set to ("y", "x") by default.

None
attrs dict or None

Attributes to set in the predicted target if it is returned in grid form. If not issued, it is set as in accordance with the CF conventions (https://cf-convention.github.io/Data/cf-conventions/cf-conventions-1.13/cf-conventions.pdf#temperature-units): { "standard_name": "land_surface_temperature", "long_name": "Land surface temperature", "units": "K", }

None
path_out dict[Timestamp, Path] or None

The output path of the file for each predicted image, keyed by timestamp. If not issued, the predicted target is instead returned.

None
_log bool

Whether to log messages into terminal.

True

Returns:

Name Type Description
y_fine_pred dict[Timestamp, ndarray or DataArray] or None

Predicted fine target for each image in flattened form (as a np.ndarray, if gridded is False) or grid form (as an xr.DataArray if gridded is True), keyed by timestamp. If path_out is issued, the predictions are written to files and None is instead returned.

Source code in src/s3lst_ds/downscaling/piecewise_downscaling.py
def predict(
    self,
    X_and_mask_fine: dict[pd.Timestamp, np.ndarray | pd.DataFrame],
    correct: bool = True,
    X_and_mask_coarse: dict[pd.Timestamp, np.ndarray | pd.DataFrame] | None = None,
    y_coarse: dict[pd.Timestamp, np.ndarray | pd.Series] | None = None,
    coords_coarse: dict[pd.Timestamp, xr.Coordinates] | None = None,
    coords_fine: dict[pd.Timestamp, xr.Coordinates] | None = None,
    gridded: bool = True,
    dims: tuple | None = None,
    attrs: dict | None = None,
    path_out: dict[pd.Timestamp, Path] | None = None,
    *,
    _log: bool = True,
) -> dict[pd.Timestamp, np.ndarray | xr.DataArray] | None:
    """
    Predict fine target for multiple images using `predict_single()` for each one,
    keyed by timestamp.

    Parameters
    ----------

    X_and_mask_fine : dict[pd.Timestamp, np.ndarray or pd.DataFrame]
        Fine predictors and masks for each image, keyed by timestamp.

    correct : bool, default=True
        Whether to correct the predicted fine target for each image (from fine
        predictors and masks, `X_and_mask_fine`) using the finely-resampled residual
        for the prediction of the coarse target (from coarse predictors and masks,
        `X_and_mask_coarse`).

    X_and_mask_coarse : dict[pd.Timestamp, np.ndarray or pd.DataFrame] or None, default=None
        Coarse predictors and masks for each image, keyed by timestamp. It must be
        issued if `correct` is `True`.

    y_coarse : dict[pd.Timestamp, np.ndarray or pd.Series] or None, default=None
        The "true" coarse target, keyed by timestamp. It must be issued if `correct`
        is `True`.

    coords_coarse : dict[pd.Timestamp, xarray.core.coordinates.Coordinates] or None, default=None
        The coordinates of the coarse mesh for each image, keyed by timestamp. It
        must be issued if `correct` is `True`.

    coords_fine : dict[pd.Timestamp, xarray.core.coordinates.Coordinates] or None, default=None
        The coordinates of the fine mesh for each image, keyed by timestamp. It must
        be issued if `correct` or `gridded` are `True`.

    gridded : bool, default=True
        Whether to return the predicted fine target for each image in grid form (as
        an `xr.DataArray`) or in flattened form (as a `pd.Series`).

    dims : tuple or None, default=None
        Labels for the dimensions of the predicted target if it is returned in grid
        form. If not issued, it is set to ("y", "x") by default.

    attrs : dict or None, default=None
        Attributes to set in the predicted target if it is returned in grid form. If
        not issued, it is set as in accordance with the CF conventions
        (https://cf-convention.github.io/Data/cf-conventions/cf-conventions-1.13/cf-conventions.pdf#temperature-units):
            {
                "standard_name": "land_surface_temperature", "long_name": "Land
                surface temperature", "units": "K",
            }

    path_out : dict[pd.Timestamp, Path] or None, default=None
        The output path of the file for each predicted image, keyed by timestamp. If
        not issued, the predicted target is instead returned.

    _log : bool, default=True
        Whether to log messages into terminal.

    Returns
    -------

    y_fine_pred : dict[pd.Timestamp, np.ndarray or xr.DataArray] or None
        Predicted fine target for each image in flattened form (as a `np.ndarray`,
        if `gridded` is `False`) or grid form (as an `xr.DataArray` if `gridded` is
        `True`), keyed by timestamp. If `path_out` is issued, the predictions are
        written to files and `None` is instead returned.

    """
    if self.logger is not None and _log is True:
        self.logger.info("Predicting target...")

    # Transform parameters valued as None into dictionaries with None values (one
    # per image)
    X_and_mask_coarse = (
        X_and_mask_coarse
        if X_and_mask_coarse is not None
        else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
    )
    y_coarse = (
        y_coarse
        if y_coarse is not None
        else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
    )
    coords_coarse = (
        coords_coarse
        if coords_coarse is not None
        else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
    )
    coords_fine = (
        coords_fine
        if coords_fine is not None
        else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
    )
    path_out = (
        path_out
        if path_out is not None
        else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
    )

    # Define progress bar
    pbar = (
        tqdm(
            # Prefix for the progressbar
            bar_format=f"{'':9}" + "{l_bar}{bar}{r_bar}",
            desc=f"{'':8}",
            total=len(X_and_mask_fine.keys()),  # type: ignore
            unit="timestamp",
            position=0,
            leave=True,  # Keep progress on the screen after completion.
            options={"console": self.logger.console},
        )
        if self.show_progress is True and self.logger is not None
        else None
    )

    # Predict fine raw targets as a dictionary
    y_fine_pred = {}
    if self.max_workers != 1:
        with ProcessPoolExecutor(max_workers=self.max_workers) as executor:
            # List of placeholders for the eventual result of a computation
            futures = {
                # NOTE: Using executor.submit() can be safely used as key of
                # dictionary since executor.submit() returns a Future object
                # (https://docs.python.org/3/library/asyncio-future.html#future-object)
                # and all of these objects are unique and hashable.
                executor.submit(
                    self.predict_single,
                    timestamp=timestamp,
                    X_and_mask_fine=X_and_mask_fine[timestamp],
                    correct=correct,
                    X_and_mask_coarse=X_and_mask_coarse[timestamp],  # type: ignore
                    y_coarse=y_coarse[timestamp],  # type: ignore
                    coords_coarse=coords_coarse[timestamp],  # type: ignore
                    coords_fine=coords_fine[timestamp],  # type: ignore
                    gridded=gridded,
                    dims=dims,
                    attrs=attrs,
                    path_out=path_out[timestamp],  # type: ignore
                ): timestamp
                for timestamp in X_and_mask_fine  # type: ignore
            }

            for future in as_completed(futures):
                # Add result to dictionary of results
                timestamp = futures[future]
                y_fine_pred[timestamp] = future.result()

                # Update progress bar with one more count per completed process
                if pbar is not None:
                    pbar.update()

        # Make dictionary of predictions be ordered as input X_and_mask_fine
        # NOTE: multiprocessing may output results in a different order.
        y_fine_pred = {
            timestamp: y_fine_pred[timestamp]
            for timestamp in X_and_mask_fine  # type: ignore
        }

    else:
        for timestamp in X_and_mask_fine:  # noqa: PLC0206
            y_fine_pred[timestamp] = self.predict_single(
                timestamp=timestamp,
                X_and_mask_fine=X_and_mask_fine[timestamp],
                correct=correct,
                X_and_mask_coarse=X_and_mask_coarse[timestamp],  # type: ignore
                y_coarse=y_coarse[timestamp],  # type: ignore
                coords_coarse=coords_coarse[timestamp],  # type: ignore
                coords_fine=coords_fine[timestamp],  # type: ignore
                gridded=gridded,
                dims=dims,
                attrs=attrs,
                path_out=path_out[timestamp],  # type: ignore
            )

            # Update progress bar with one more count per completed process
            if pbar is not None:
                pbar.update()

    # At the end close progress bar
    if pbar is not None:
        pbar.close()

    # Convert y_fine_pred to None if it any of their values was written to files.
    if None not in path_out.values():  # type: ignore
        y_fine_pred = None

    return y_fine_pred  # type: ignore

predict_coarse

predict_coarse(
    X_and_mask_coarse: dict[Timestamp, ndarray | DataFrame],
    coords_coarse: dict[Timestamp, Coordinates] | None = None,
    gridded: bool = True,
    dims: tuple | None = None,
    attrs: dict | None = None,
    path_out: dict[Timestamp, Path] | None = None,
) -> dict[Timestamp, ndarray | DataArray] | None

Predict coarse target for multiple images.

Parameters:

Name Type Description Default
X_and_mask_coarse dict[Timestamp, ndarray or DataFrame]

Coarse predictors and masks for each image, keyed by timestamp.

required
coords_coarse dict[Timestamp, Coordinates] or None

The coordinates of the coarse mesh for each image, keyed by timestamp. It must be issued if gridded is True.

None
gridded bool

Whether to return the predicted coarse target for each image in grid form (as an xr.DataArray) or in flattened form (as a pd.Series).

True
dims tuple or None

Labels for the dimensions of the predicted target if it is returned in grid form. If not issued, it is set to ("y", "x") by default.

None
attrs dict or None

Attributes to set in the predicted target if it is returned in grid form. If not issued, it is set as in accordance with the CF conventions (https://cf-convention.github.io/Data/cf-conventions/cf-conventions-1.13/cf-conventions.pdf#temperature-units): { "standard_name": "land_surface_temperature", "long_name": "Land surface temperature", "units": "K", }

None
path_out Path or list[Path] or dict[Any, Path] or None

The output path of the file for each predicted image. If not issued, the predicted target is instead returned.

None

Returns:

Name Type Description
y_coarse_pred dict[Timestamp, ndarray or DataArray] or None

Predicted coarse target for each image in flattened form (as a np.ndarray, if gridded is False) or grid form (as an xr.DataArray if gridded is True), keyed by timestamp. If path_out is issued, the prediction is written to file and None is instead returned.

Source code in src/s3lst_ds/downscaling/piecewise_downscaling.py
def predict_coarse(
    self,
    X_and_mask_coarse: dict[pd.Timestamp, np.ndarray | pd.DataFrame],
    coords_coarse: dict[pd.Timestamp, xr.Coordinates] | None = None,
    gridded: bool = True,
    dims: tuple | None = None,
    attrs: dict | None = None,
    path_out: dict[pd.Timestamp, Path] | None = None,
) -> dict[pd.Timestamp, np.ndarray | xr.DataArray] | None:
    """
    Predict coarse target for multiple images.

    Parameters
    ----------

    X_and_mask_coarse : dict[pd.Timestamp, np.ndarray or pd.DataFrame]
        Coarse predictors and masks for each image, keyed by timestamp.

    coords_coarse : dict[pd.Timestamp, xarray.core.coordinates.Coordinates] or None, default=None
        The coordinates of the coarse mesh for each image, keyed by timestamp. It
        must be issued if `gridded` is `True`.

    gridded : bool, default=True
        Whether to return the predicted coarse target for each image in grid form
        (as an `xr.DataArray`) or in flattened form (as a `pd.Series`).

    dims : tuple or None, default=None
        Labels for the dimensions of the predicted target if it is returned in grid
        form. If not issued, it is set to ("y", "x") by default.

    attrs : dict or None, default=None
        Attributes to set in the predicted target if it is returned in grid form. If
        not issued, it is set as in accordance with the CF conventions
        (https://cf-convention.github.io/Data/cf-conventions/cf-conventions-1.13/cf-conventions.pdf#temperature-units):
            {
                "standard_name": "land_surface_temperature", "long_name": "Land
                surface temperature", "units": "K",
            }

    path_out : Path or list[Path] or dict[Any, Path] or None, default=None
        The output path of the file for each predicted image. If not issued, the
        predicted target is instead returned.

    Returns
    -------

    y_coarse_pred : dict[pd.Timestamp, np.ndarray or xr.DataArray] or None
        Predicted coarse target for each image in flattened form (as a `np.ndarray`,
        if `gridded` is `False`) or grid form (as an `xr.DataArray` if `gridded` is
        `True`), keyed by timestamp. If `path_out` is issued, the prediction is
        written to file and `None` is instead returned.
    """

    y_coarse_pred = self.predict(
        X_and_mask_fine=X_and_mask_coarse,
        correct=False,
        coords_fine=coords_coarse,
        gridded=gridded,
        dims=dims,
        attrs=attrs,
        path_out=path_out,
    )

    return y_coarse_pred

predict_single

predict_single(
    timestamp: Timestamp,
    X_and_mask_fine: ndarray | DataFrame,
    correct: bool = True,
    X_and_mask_coarse: ndarray | DataFrame | None = None,
    y_coarse: ndarray | Series | None = None,
    coords_coarse: Coordinates | None = None,
    coords_fine: Coordinates | None = None,
    gridded: bool = True,
    dims: tuple | None = None,
    attrs: dict | None = None,
    path_out: Path | None = None,
) -> ndarray | DataArray | None

Predict fine target from fine predictors and masks (X_and_mask_fine). Additionally, if correct is set to True, correct prediction with finely-resampled residuals associated with the prediction of coarse target from coarse predictors and masks (X_and_mask_coarse). Note that to compute such residuals, the "true" coarse target (y_coarse) and the coarse and fine grid coordinates (coords_coarse and coords_fine) must be also issued.

Note that this method only predicts for a single image. To predict for multiple images, use predict().

Parameters:

Name Type Description Default
timestamp Timestamp

Timestamp associated with the data.

required
X_and_mask_fine ndarray or DataFrame

Fine predictors and masks.

required
correct bool

Whether to correct the predicted fine target (from fine predictors and masks, X_and_mask_fine) using the finely-resampled residual for the prediction of the coarse target (from coarse predictors and masks, X_and_mask_coarse).

True
X_and_mask_coarse ndarray or DataFrame or None

Coarse predictors and masks. It must be issued if correct is True.

None
y_coarse ndarray or Series or None

The "true" coarse target. It must be issued if correct is True.

None
coords_coarse Coordinates or None

The coordinates of the coarse mesh. It must be issued if correct is True.

None
coords_fine Coordinates or None

The coordinates of the fine mesh. It must be issued if correct or gridded are True.

None
gridded bool

Whether to return the predicted fine target in grid form (as an xr.DataArray) or flattened form (as a pd.Series).

True
dims tuple or None

Labels for the dimensions of the predicted target if it is returned in grid form. If not issued, it is set to ("lat", "lon") by default.

None
attrs dict or None

Attributes to set in the predicted target if it is returned in grid form. If not issued, it is set to: { "standard_name": "land_surface_temperature", "long_name": "Land surface temperature", "units": "K", }

None
path_out Path or None

The output path of the file for the predicted image. If not issued, the predicted target is instead returned.

None

Returns:

Name Type Description
y_fine_pred ndarray or DataArray or None

Predicted fine target in flattened form (as a np.ndarray, if gridded is False) or grid form (as an xr.DataArray if gridded is True). If path_out is issued, the prediction is written to file and None is instead returned.

Source code in src/s3lst_ds/downscaling/piecewise_downscaling.py
def predict_single(
    self,
    timestamp: pd.Timestamp,
    X_and_mask_fine: np.ndarray | pd.DataFrame,
    correct: bool = True,
    X_and_mask_coarse: np.ndarray | pd.DataFrame | None = None,
    y_coarse: np.ndarray | pd.Series | None = None,
    coords_coarse: xr.Coordinates | None = None,
    coords_fine: xr.Coordinates | None = None,
    gridded: bool = True,
    dims: tuple | None = None,
    attrs: dict | None = None,
    path_out: Path | None = None,
) -> np.ndarray | xr.DataArray | None:
    """
    Predict fine target from fine predictors and masks (`X_and_mask_fine`).
    Additionally, if `correct` is set to `True`, correct prediction with
    finely-resampled residuals associated with the prediction of coarse target from
    coarse predictors and masks (`X_and_mask_coarse`). Note that to compute such
    residuals, the "true" coarse target (`y_coarse`) and the coarse and fine grid
    coordinates (`coords_coarse` and `coords_fine`) must be also issued.

    Note that this method only predicts for a single image. To predict for multiple
    images, use `predict()`.

    Parameters
    ----------

    timestamp : pd.Timestamp
        Timestamp associated with the data.

    X_and_mask_fine : np.ndarray or pd.DataFrame
        Fine predictors and masks.

    correct : bool, default=True
        Whether to correct the predicted fine target (from fine predictors and
        masks, `X_and_mask_fine`) using the finely-resampled residual for the
        prediction of the coarse target (from coarse predictors and masks,
        `X_and_mask_coarse`).

    X_and_mask_coarse : np.ndarray or pd.DataFrame or None, default=None
        Coarse predictors and masks. It must be issued if `correct` is `True`.

    y_coarse : np.ndarray or pd.Series or None, default=None
        The "true" coarse target. It must be issued if `correct` is `True`.

    coords_coarse : xarray.core.coordinates.Coordinates or None, default=None
        The coordinates of the coarse mesh. It must be issued if `correct` is
        `True`.

    coords_fine : xarray.core.coordinates.Coordinates or None, default=None
        The coordinates of the fine mesh. It must be issued if `correct` or
        `gridded` are `True`.

    gridded : bool, default=True
        Whether to return the predicted fine target in grid form (as an
        `xr.DataArray`) or flattened form (as a `pd.Series`).

    dims : tuple or None, default=None
        Labels for the dimensions of the predicted target if it is returned in grid
        form. If not issued, it is set to ("lat", "lon") by default.

    attrs : dict or None, default=None
        Attributes to set in the predicted target if it is returned in grid form. If
        not issued, it is set to:
            {
                "standard_name": "land_surface_temperature",
                "long_name": "Land surface temperature",
                "units": "K",
            }

    path_out : Path or None, default=None
        The output path of the file for the predicted image. If not issued, the
        predicted target is instead returned.

    Returns
    -------

    y_fine_pred : np.ndarray or xr.DataArray or None
        Predicted fine target in flattened form (as a `np.ndarray`, if `gridded` is
        `False`) or grid form (as an `xr.DataArray` if `gridded` is `True`). If
        `path_out` is issued, the prediction is written to file and `None` is
        instead returned.

    """

    # Parse dims and attrs parameters
    dims = dims if dims is not None else ("lat", "lon")
    attrs = (
        attrs
        if attrs is not None
        else {
            "standard_name": "land_surface_temperature",
            "long_name": "Land surface temperature",
            "units": "K",
        }
    )

    # Raise error if residual correction is to be performed but required parameters
    # are missing
    if correct is True and any(
        elem is None
        for elem in [X_and_mask_coarse, y_coarse, coords_coarse, coords_fine]
    ):
        raise TypeError(
            "Parameters 'X_and_mask_coarse', 'y_coarse', 'coords_coarse' and"
            " 'coords_fine' must also be issued to perform residual"
            " correction."
        )

    # Raise error if the predicted target is wanted in grid form (not in ravelled
    # one) but required parameters are missing
    if gridded is True and coords_fine is None:
        raise TypeError(
            "Parameter 'coords_fine' must also be issued to make predicted"
            " target gridded."
        )

    # Convert true coarse target to a pandas Series if it is not already and
    # residual correction is considered (such condition would require usage of the
    # true coarse target)
    if not isinstance(y_coarse, pd.Series) and correct is True:
        y_coarse = pd.Series(y_coarse)

    # Predict fine target from fine predictors and masks using the the preprocessor
    # and the base model
    y_fine_pred = pd.Series(self.estimators[timestamp].predict(X_and_mask_fine))

    # If gridded prediction or residual correction are wanted, transform the
    # predicted fine target into grid form
    # NOTE: residual correction involves reprojection of the coarse residual into
    # the fine grid. The grid of the gridded predicted fine target may be used as
    # target of the matching reprojection.
    if gridded is True or correct is True:
        # Get shape of the fine grid
        shape_fine = tuple(reversed(list(coords_fine.sizes.values())))  # type: ignore

        # Convert flat predicted fine target into gridded format
        y_fine_pred = xr.DataArray(
            data=y_fine_pred.values.reshape(shape_fine),  # type: ignore
            coords=coords_fine,
            dims=("y", "x"),
            name="LST",
        )

    # If residual correction is wanted, correct the prediction using
    # finely resampled residuals associated with the prediction of the coarse target
    if correct is True:
        # Predict coarse target from coarse predictors and masks
        y_coarse_pred = pd.Series(
            self.estimators[timestamp].predict(X_and_mask_coarse)
        )

        # Compute respective residuals
        res_coarse = y_coarse - y_coarse_pred  # type: ignore

        # Get shape of the coarse grid
        shape_coarse = tuple(reversed(list(coords_coarse.sizes.values())))  # type: ignore

        # Express the residuals in the coarse grid
        res_coarse = xr.DataArray(
            data=res_coarse.values.reshape(shape_coarse),  # type: ignore
            coords=coords_coarse,
            dims=("y", "x"),
            name="LST",
        )

        # Refine the residuals by reprojecting then to the fine grid
        res_coarse_refined = selective_reproject_match(
            data_src=res_coarse,
            data_target=y_fine_pred,  # type: ignore
        )

        # Correct the fine target
        y_fine_pred = y_fine_pred + res_coarse_refined

        # If ravelled (flat) predicted fine target is wanted, ravel it
        if gridded is False:
            y_fine_pred = y_fine_pred.values.ravel()  # type: ignore

    # In case of gridded prediction, set type, time coordinate, NODATA value,
    # dimension labels and attributes of the data
    if gridded is True:
        # Set data type
        y_fine_pred = y_fine_pred.astype("float32")

        # Set time coordinate
        # WARNING: it is herein assumed that the timestamp is in the UTC timezone.
        y_fine_pred = y_fine_pred.expand_dims(  # type: ignore
            dim={"time": [timestamp.tz_localize("UTC")]}
        )

        # Write NODATA value
        y_fine_pred.rio.write_nodata(  # type: ignore
            input_nodata=-999,
            encoded=True,
            inplace=True,
        )

        # Set dimension labels
        if dims is not None:
            y_fine_pred = y_fine_pred.rename({"y": dims[0], "x": dims[1]})

        # Set attributes
        if attrs is not None:
            y_fine_pred.attrs = attrs  # type: ignore
            y_fine_pred["time"].attrs = {
                "axis": "T",
                "standard_name": "time",
                "long_name": "Start sensing time of the satellite acquisition",
            }

    # If writing to file, write the predicted fine target
    if path_out is not None:
        # Create output directory if it does not exist
        path_out.parent.mkdir(  # type: ignore
            parents=True,
            exist_ok=True,
        )

        # Write to file
        if gridded is False:
            path_out = path_out.with_suffix(".csv")
            np.savetxt(fname=path_out, X=y_fine_pred)  # type: ignore
        else:
            # NOTE: rioxarray `to_raster()` cannot handle writing to NetCDF files,
            # but `to_netcdf()` can.
            if path_out.suffix == ".nc":
                # NetCDF cannot handle pd.Timestamp type. Time will be converted to
                # seconds since 1972-01-01 00:00:00 UTC, as in accordance with CF
                # conventions
                # NOTE: see https://cf-convention.github.io/Data/cf-conventions/cf-conventions-1.13/cf-conventions.pdf#page=42
                y_fine_pred["time"] = (
                    y_fine_pred["time"] - pd.Timestamp("1972-01-01 00:00:00Z")
                ).dt.total_seconds()  # type: ignore
                y_fine_pred["time"].attrs = {  # type: ignore
                    "standard_name": "time",
                    "long_name": "Time",
                    "axis": "T",
                    "units": "seconds since 1972-1-1 00:00:00Z",
                    "calendar": "proleptic_gregorian",
                }

                y_fine_pred.to_netcdf(path_out)  # type: ignore
            else:
                # In the case of no suffix, `to_raster()` considers GeoTIFF.
                if path_out.suffix in [""]:
                    path_out = path_out.with_suffix(".tif")

                y_fine_pred.rio.to_raster(path_out)  # type: ignore

        # Set y_fine_pred to None to return None at the end of the function
        y_fine_pred = None

    return y_fine_pred  # type: ignore

save

save(path: Path) -> None

Write the instance to path with joblib.

Parameters:

Name Type Description Default
path Path

Path to write the instance to.

required
Source code in src/s3lst_ds/downscaling/piecewise_downscaling.py
def save(self, path: Path) -> None:
    """
    Write the instance to `path` with `joblib`.

    Parameters
    ----------
    path : Path
        Path to write the instance to.
    """

    joblib.dump(value=self, filename=path)

score

score(
    X_and_mask_fine: dict[Timestamp, ndarray | DataFrame],
    y_fine: dict[Timestamp, ndarray | Series],
    correct: bool = True,
    calibrate: bool = False,
    X_and_mask_coarse: dict[Timestamp, ndarray | DataFrame] | None = None,
    y_coarse: dict[Timestamp, ndarray | Series] | None = None,
    coords_coarse: dict[Timestamp, Coordinates] | None = None,
    coords_fine: dict[Timestamp, Coordinates] | None = None,
    aggregate: bool = False,
    scorers: list[str] | None = None,
    sample_weight: dict[Timestamp, ndarray | Series] | None = None,
) -> dict[str, float] | dict[Timestamp, dict[str, float]]

Predict fine target and score for multiple images individually (if aggregate is set to False) or combined (if aggregate is set to True).

Parameters:

Name Type Description Default
X_and_mask_fine dict[Timestamp, ndarray or DataFrame]

Fine predictors and masks, keyed by timestamp.

required
y_fine dict[Timestamp, ndarray or Series]

The "true" fine target, keyed by timestamp.

required
correct bool

Whether to correct the predicted fine target (from fine predictors and masks, X_and_mask_fine) using the finely-resampled residual for the prediction of the coarse target (from coarse predictors and masks, X_and_mask_coarse).

True
calibrate bool

Whether to calibrate the predicted fine target with the coarse validation target for each timestamp. This is done by offsetting and scaling the predicted fine target with the transform that makes the coarse true target (y_coarse) have the same mean and standard deviation as the validation coarse one (coarsened y_fine) for each timestamp. Such transformation is an attempt to account for discrepancies between source and validation platforms at a common coarse grid from the computed scores.

False
X_and_mask_coarse dict[Timestamp, ndarray or DataFrame] or None

Coarse predictors and masks, keyed by timestamp. It must be issued if correct is True.

None
y_coarse dict[Timestamp, ndarray or Series] or None

The "true" coarse target, keyed by timestamp. It must be issued if correct or calibrate are True.

None
coords_coarse dict[Timestamp, Coordinates] or None

The coordinates of the coarse mesh for each image, keyed by timestamp. It must be issued if correct or calibrate are True.

None
coords_fine dict[Timestamp, Coordinates] or None

The coordinates of the fine mesh for each image, keyed by timestamp. It must be issued if correct or calibrate are True.

None
aggregate bool

Whether to compute scores for images individually (False) or combined (True).

False
scorers list[str]

Aliases of the scorers to consider.

["r2", "r2_oos", "rmse", "rmse_delta", "mae", "mae_delta", "mbe"]
sample_weight dict[pd.Timestamp, np.ndarray or pd.Series] None

Weights of the samples in the score, keyed by timestamp.

None

Returns:

Name Type Description
score dict[str, float] or dict[Timestamp, dict[str, float]]

Prediction scores for each image (if aggregate is set to False) or all of them combined (if aggregate is set to True).

Source code in src/s3lst_ds/downscaling/piecewise_downscaling.py
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
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
def score(
    self,
    X_and_mask_fine: dict[pd.Timestamp, np.ndarray | pd.DataFrame],
    y_fine: dict[pd.Timestamp, np.ndarray | pd.Series],
    correct: bool = True,
    calibrate: bool = False,
    X_and_mask_coarse: dict[pd.Timestamp, np.ndarray | pd.DataFrame] | None = None,
    y_coarse: dict[pd.Timestamp, np.ndarray | pd.Series] | None = None,
    coords_coarse: dict[pd.Timestamp, xr.Coordinates] | None = None,
    coords_fine: dict[pd.Timestamp, xr.Coordinates] | None = None,
    aggregate: bool = False,
    scorers: list[str] | None = None,
    sample_weight: dict[pd.Timestamp, np.ndarray | pd.Series] | None = None,
) -> dict[str, float] | dict[pd.Timestamp, dict[str, float]]:
    """
    Predict fine target and score for multiple images individually (if `aggregate`
    is set to `False`) or combined (if `aggregate` is set to `True`).

    Parameters
    ----------

    X_and_mask_fine : dict[pd.Timestamp, np.ndarray or pd.DataFrame]
        Fine predictors and masks, keyed by timestamp.

    y_fine : dict[pd.Timestamp, np.ndarray or pd.Series]
        The "true" fine target, keyed by timestamp.

    correct : bool, default=True
        Whether to correct the predicted fine target (from fine predictors and
        masks, `X_and_mask_fine`) using the finely-resampled residual for the
        prediction of the coarse target (from coarse predictors and masks,
        `X_and_mask_coarse`).

    calibrate : bool, default=False
        Whether to calibrate the predicted fine target with the coarse validation
        target for each timestamp. This is done by offsetting and scaling the
        predicted fine target with the transform that makes the coarse true target
        (`y_coarse`) have the same mean and standard deviation as the validation
        coarse one (coarsened `y_fine`) for each timestamp. Such transformation is
        an attempt to account for discrepancies between source and validation
        platforms at a common coarse grid from the computed scores.

    X_and_mask_coarse : dict[pd.Timestamp, np.ndarray or pd.DataFrame] or None, default=None
        Coarse predictors and masks, keyed by timestamp. It must be issued if
        `correct` is `True`.

    y_coarse : dict[pd.Timestamp, np.ndarray or pd.Series] or None, default=None
        The "true" coarse target, keyed by timestamp. It must be issued if `correct`
        or `calibrate` are `True`.

    coords_coarse : dict[pd.Timestamp, xarray.core.coordinates.Coordinates] or None, default=None
        The coordinates of the coarse mesh for each image, keyed by timestamp. It
        must be issued if `correct` or `calibrate` are `True`.

    coords_fine : dict[pd.Timestamp, xarray.core.coordinates.Coordinates] or None, default=None
        The coordinates of the fine mesh for each image, keyed by timestamp. It must
        be issued if `correct` or `calibrate` are `True`.

    aggregate : bool, default=False
        Whether to compute scores for images individually (`False`) or combined
        (`True`).

    scorers : list[str], default=["r2", "r2_oos", "rmse", "rmse_delta", "mae", "mae_delta", "mbe"]
        Aliases of the scorers to consider.

    sample_weight : dict[pd.Timestamp, np.ndarray or pd.Series] None, default=None
        Weights of the samples in the score, keyed by timestamp.

    Returns
    -------

    score : dict[str, float] or dict[pd.Timestamp, dict[str, float]]
        Prediction scores for each image (if `aggregate` is set to `False`) or all
        of them combined (if `aggregate` is set to `True`).
    """

    if self.logger is not None:
        self.logger.info("Predicting target and scoring...")

    # Define default value for scorers argument
    if scorers is None:
        scorers = ["r2", "r2_oos", "rmse", "rmse_delta", "mae", "mae_delta", "mbe"]

    # Transform parameters valued as None into dictionaries with None values (one
    # per image)
    X_and_mask_coarse = (
        X_and_mask_coarse
        if X_and_mask_coarse is not None
        else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
    )
    y_coarse = (
        y_coarse
        if y_coarse is not None
        else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
    )
    coords_coarse = (
        coords_coarse
        if coords_coarse is not None
        else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
    )
    coords_fine = (
        coords_fine
        if coords_fine is not None
        else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
    )
    sample_weight = (
        sample_weight
        if sample_weight is not None
        else dict.fromkeys(X_and_mask_fine.keys(), None)  # type: ignore
    )

    # If parameter "aggregate" is False, score for each timestamp individually
    if aggregate is False:
        # Define progress bar
        pbar = (
            tqdm(
                # Prefix for the progressbar
                bar_format=f"{'':9}" + "{l_bar}{bar}{r_bar}",
                desc=f"{'':8}",
                total=len(X_and_mask_fine.keys()),  # type: ignore
                unit="timestamp",
                position=0,
                leave=True,  # Keep progress on the screen after completion.
                options={"console": self.logger.console},
            )
            if self.show_progress is True and self.logger is not None
            else None
        )

        # Predict scores as a dictionary
        score = {}
        if self.max_workers != 1:
            with ProcessPoolExecutor(max_workers=self.max_workers) as executor:
                # List of placeholders for the eventual result of a computation
                futures = {
                    # NOTE: Using executor.submit() can be safely used as key of
                    # dictionary since executor.submit() returns a Future object
                    # (https://docs.python.org/3/library/asyncio-future.html#future-object)
                    # and all of these objects are unique and hashable.
                    executor.submit(
                        self.score_single,
                        timestamp=timestamp,
                        X_and_mask_fine=X_and_mask_fine[timestamp],
                        y_fine=y_fine[timestamp],
                        correct=correct,
                        calibrate=calibrate,
                        X_and_mask_coarse=X_and_mask_coarse[timestamp],  # type: ignore
                        y_coarse=y_coarse[timestamp],  # type: ignore
                        coords_coarse=coords_coarse[timestamp],  # type: ignore
                        coords_fine=coords_fine[timestamp],  # type: ignore
                        scorers=scorers,
                        sample_weight=sample_weight[timestamp],  # type: ignore
                    ): timestamp
                    for timestamp in X_and_mask_fine  # type: ignore
                }

                for future in as_completed(futures):
                    # Add result to dictionary of results
                    timestamp = futures[future]
                    score[timestamp] = future.result()

                    # Update progress bar with one more count per completed process
                    if pbar is not None:
                        pbar.update()

            # Make dictionary of scores be ordered as input X_and_mask_fine
            # NOTE: multiprocessing may output results in a different order.
            score = {timestamp: score[timestamp] for timestamp in X_and_mask_fine}  # type: ignore

        else:
            for timestamp in X_and_mask_fine:  # noqa: PLC0206
                score[timestamp] = self.score_single(
                    timestamp=timestamp,
                    X_and_mask_fine=X_and_mask_fine[timestamp],
                    y_fine=y_fine[timestamp],
                    correct=correct,
                    calibrate=calibrate,
                    X_and_mask_coarse=X_and_mask_coarse[timestamp],  # type: ignore
                    y_coarse=y_coarse[timestamp],  # type: ignore
                    coords_coarse=coords_coarse[timestamp],  # type: ignore
                    coords_fine=coords_fine[timestamp],  # type: ignore
                    scorers=scorers,
                    sample_weight=sample_weight[timestamp],  # type: ignore
                )
                # Update progress bar with one more count per completed process
                if pbar is not None:
                    pbar.update()

        # At the end close progress bar
        if pbar is not None:
            pbar.close()

    # If parameter "aggregate" is True, score for the combined data
    else:
        # Convert true fine target for each image to pandas Series if it is not
        # already.
        y_fine = {
            timestamp: (
                pd.Series(y_fine[timestamp])
                if not isinstance(y_fine[timestamp], pd.Series)
                else y_fine[timestamp]
            )
            for timestamp in X_and_mask_fine
        }

        # Get statistics of true fine target for each image (to use them later to
        # compute RMSE of the standardized target)
        y_fine_mean = {
            timestamp: y_fine[timestamp].mean() for timestamp in X_and_mask_fine
        }
        y_fine_std = {
            timestamp: y_fine[timestamp].std() for timestamp in X_and_mask_fine
        }

        # Compute standardized true fine target for each image (using true fine
        # target statistics)
        y_fine_delta = {
            timestamp: (
                y_fine[timestamp] - y_fine_mean[timestamp]  # type: ignore
            )
            / y_fine_std[timestamp]
            for timestamp in X_and_mask_fine
        }

        # Predict fine target for each image
        y_fine_pred = {
            key: pd.Series(value)  # type: ignore
            for key, value in self.predict(
                X_and_mask_fine=X_and_mask_fine,
                correct=correct,
                X_and_mask_coarse=X_and_mask_coarse,  # type: ignore
                y_coarse=y_coarse,
                coords_coarse=coords_coarse,
                coords_fine=coords_fine,
                gridded=False,
                _log=False,
            ).items()  # type: ignore
        }

        # Predict fine target for each image using the dummy mean model
        # NOTE: this is required for computing out-of-sample coefficient of
        # determination.
        y_fine_dummy_pred = {
            timestamp: pd.Series(
                self.estimators[timestamp]
                .pipeline.named_steps["regressor"]
                .dummy_mean_model.predict(X_and_mask_fine[timestamp])
            )
            for timestamp in X_and_mask_fine
        }

        # Calibrate the fine targets predicted by downscaler and dummy mean model
        # with the transform that would make the coarse true target have the same
        # mean and standard deviation as the coarsened fine validation one.
        if calibrate is True:
            # Express coarse true target in its grid
            shape_coarse = {
                timestamp: tuple(
                    reversed(list(coords_coarse[timestamp].sizes.values()))  # type: ignore
                )  # type: ignore
                for timestamp in X_and_mask_fine
            }
            y_coarse_grid = {
                timestamp: xr.DataArray(
                    data=(
                        y_coarse[timestamp].values  # type: ignore
                        if isinstance(y_coarse[timestamp], pd.Series)  # type: ignore
                        else y_coarse[timestamp]  # type: ignore
                    ).reshape(  # type: ignore
                        shape_coarse[timestamp]  # type: ignore
                    ),
                    coords=coords_coarse[timestamp],  # type: ignore
                    dims=("y", "x"),
                    name="LST",
                )
                for timestamp in X_and_mask_fine
            }

            # Express fine validation target in its  grid
            shape_fine = {
                timestamp: tuple(
                    reversed(list(coords_fine[timestamp].sizes.values()))  # type: ignore
                )  # type: ignore
                for timestamp in X_and_mask_fine
            }  # type: ignore
            y_fine_grid = {
                timestamp: xr.DataArray(
                    data=(
                        y_fine[timestamp].values  # type: ignore
                        if isinstance(y_fine[timestamp], pd.Series)  # type: ignore
                        else y_fine[timestamp]
                    ).reshape(  # type: ignore
                        shape_fine[timestamp]  # type: ignore
                    ),
                    coords=coords_fine[timestamp],  # type: ignore
                    dims=("y", "x"),
                    name="LST",
                )
                for timestamp in X_and_mask_fine
            }

            # Reproject fine validation target to coarse grid
            y_fine_coarse = {
                timestamp: selective_reproject_match(
                    data_src=y_fine_grid[timestamp],  # type: ignore
                    data_target=y_coarse_grid[timestamp],  # type: ignore
                )
                for timestamp in X_and_mask_fine  # type: ignore
            }

            # Calibrate fine target predicted by downscaler
            # NOTE: https://math.stackexchange.com/a/2943606/209790
            y_fine_pred = {
                timestamp: (
                    y_fine_coarse[timestamp].mean().item()  # type: ignore
                    + y_fine_coarse[timestamp].std().item()  # type: ignore
                    / y_coarse[timestamp].std()  # type: ignore
                    * (y_fine_pred[timestamp] - y_coarse[timestamp].mean())  # type: ignore
                )
                for timestamp in X_and_mask_fine  # type: ignore
            }

            # Calibrate fine target predicted by dummy mean model
            y_fine_dummy_pred = {
                timestamp: (
                    y_fine_coarse[timestamp].mean().item()  # type: ignore
                    + y_fine_coarse[timestamp].std().item()  # type: ignore
                    / y_coarse[timestamp].std()  # type: ignore
                    * (y_fine_dummy_pred[timestamp] - y_coarse[timestamp].mean())  # type: ignore
                )
                for timestamp in X_and_mask_fine  # type: ignore
            }

        # Compute standardized predicted fine target for each image (using true fine
        # raw target statistics)
        y_fine_pred_delta = {
            timestamp: (y_fine_pred[timestamp] - y_fine_mean[timestamp])
            / y_fine_std[timestamp]
            for timestamp in X_and_mask_fine  # type: ignore
        }

        # Combine variables of all timestamps
        y_fine = pd.concat(y_fine, ignore_index=True)  # type: ignore
        y_fine_pred = pd.concat(y_fine_pred, ignore_index=True)  # type: ignore
        y_fine_dummy_pred = pd.concat(y_fine_dummy_pred, ignore_index=True)  # type: ignore
        y_fine_delta = pd.concat(y_fine_delta, ignore_index=True)  # type: ignore
        y_fine_pred_delta = pd.concat(y_fine_pred_delta, ignore_index=True)  # type: ignore
        sample_weight = (
            pd.concat(sample_weight, ignore_index=True)  # type: ignore
            if not any(value is None for value in sample_weight.values())  # type: ignore
            else None
        )

        # Combine the true and predicted targets into a common DataFrame (so
        # that all records containing any nan may be later dropped and the
        # prediction score afterwards computed)
        data = pd.DataFrame(
            data={
                "y_true": y_fine,
                "y_pred": y_fine_pred,
                "y_dummy_pred": y_fine_dummy_pred,
                "y_true_delta": y_fine_delta,
                "y_pred_delta": y_fine_pred_delta,
                **(
                    {
                        "sample_weight": sample_weight,
                    }
                    if sample_weight is not None
                    else {}
                ),
            }
        )

        # Drop nan
        data = data.dropna()

        # Compute prediction score
        score = {
            # Coefficient of determination
            "r2": r2(
                y_true=data["y_true"],
                y_pred=data["y_pred"],
                sample_weight=(
                    data["sample_weight"] if sample_weight is not None else None
                ),
            ),
            # Out-of-sample coefficient of determination
            # [NOTE: this is such that it uses a dummy mean model (simply the
            # arithmetic mean of the masked inference coarse targets) as
            # reference.]
            "r2_oos": r2_oos(
                y_true=data["y_true"],
                y_pred=data["y_pred"],
                y_dummy_pred=data["y_dummy_pred"],
                sample_weight=(
                    data["sample_weight"] if sample_weight is not None else None
                ),
            ),
            # Root mean squared error
            "rmse": rmse(
                y_true=data["y_true"],
                y_pred=data["y_pred"],
                sample_weight=(
                    data["sample_weight"] if sample_weight is not None else None
                ),
            ),
            # Root mean squared error of the standardized target (using true
            # target statistics)
            "rmse_delta": rmse(
                y_true=data["y_true_delta"],
                y_pred=data["y_pred_delta"],
                sample_weight=(
                    data["sample_weight"] if sample_weight is not None else None
                ),
            ),
            # Mean absolute error
            "mae": mae(
                y_true=data["y_true"],
                y_pred=data["y_pred"],
                sample_weight=(
                    data["sample_weight"] if sample_weight is not None else None
                ),
            ),
            # Mean absolute error of the standardized target (using true
            # target statistics)
            "mae_delta": mae(
                y_true=data["y_true_delta"],
                y_pred=data["y_pred_delta"],
                sample_weight=(
                    data["sample_weight"] if sample_weight is not None else None
                ),
            ),
            # Mean bias error
            "mbe": mbe(
                y_true=data["y_true"],
                y_pred=data["y_pred"],
                sample_weight=(
                    data["sample_weight"] if sample_weight is not None else None
                ),
            ),
        }

        # Select solely scores of interest
        score = {
            scorer: score_i
            for scorer, score_i in score.items()
            if scorer in scorers
        }

    return score

score_coarse

score_coarse(
    X_and_mask_coarse: dict[Timestamp, ndarray | DataFrame],
    y_coarse: dict[Timestamp, ndarray | Series],
    aggregate: bool = False,
    scorers: list[str] | None = None,
    sample_weight: dict[Timestamp, ndarray | Series] | None = None,
) -> dict[str, float] | dict[Timestamp, dict[str, float]]

Predict coarse target and score for multiple images individually (if aggregate is set to False) or combined (if aggregate is set to True).

Parameters:

Name Type Description Default
X_and_mask_coarse dict[Timestamp, ndarray | DataFrame]

Coarse predictors and masks, keyed by timestamp.

required
y_coarse dict[Timestamp, ndarray | Series]

The "true" coarse target, keyed by timestamp.

required
aggregate bool

Whether to compute scores for images individually (False) or combined (True).

False
scorers list[str]

Aliases of the scorers to consider.

["r2", "r2_oos", "rmse", "rmse_delta", "mae", "mae_delta", "mbe"]
sample_weight dict[pd.Timestamp, np.ndarray or pd.Series] None

Weights of the samples in the score, keyed by timestamp.

None

Returns:

Name Type Description
score dict[str, float] or dict[Timestamp, dict[str, float]]

Prediction scores for each image (if aggregate is set to False) or all of them combined (if aggregate is set to True)

Source code in src/s3lst_ds/downscaling/piecewise_downscaling.py
def score_coarse(
    self,
    X_and_mask_coarse: dict[pd.Timestamp, np.ndarray | pd.DataFrame],
    y_coarse: dict[pd.Timestamp, np.ndarray | pd.Series],
    aggregate: bool = False,
    scorers: list[str] | None = None,
    sample_weight: dict[pd.Timestamp, np.ndarray | pd.Series] | None = None,
) -> dict[str, float] | dict[pd.Timestamp, dict[str, float]]:
    """
    Predict coarse target and score for multiple images individually (if `aggregate`
    is set to `False`) or combined (if `aggregate` is set to `True`).

    Parameters
    ----------

    X_and_mask_coarse : dict[pd.Timestamp, np.ndarray | pd.DataFrame]
        Coarse predictors and masks, keyed by timestamp.

    y_coarse : dict[pd.Timestamp, np.ndarray | pd.Series]
        The "true" coarse target, keyed by timestamp.

    aggregate : bool, default=False
        Whether to compute scores for images individually (`False`) or combined
        (`True`).

    scorers : list[str], default=["r2", "r2_oos", "rmse", "rmse_delta", "mae", "mae_delta", "mbe"]
        Aliases of the scorers to consider.

    sample_weight : dict[pd.Timestamp, np.ndarray or pd.Series] None, default=None
        Weights of the samples in the score, keyed by timestamp.

    Returns
    -------

    score : dict[str, float] or dict[pd.Timestamp, dict[str, float]]
        Prediction scores for each image (if `aggregate` is set to `False`) or all
        of them combined (if `aggregate` is set to `True`)
    """

    score = self.score(
        X_and_mask_fine=X_and_mask_coarse,
        y_fine=y_coarse,
        correct=False,
        aggregate=aggregate,
        scorers=scorers,
        sample_weight=sample_weight,
    )

    return score

score_single

score_single(
    timestamp: Timestamp,
    X_and_mask_fine: ndarray | DataFrame,
    y_fine: ndarray | Series,
    correct: bool = True,
    calibrate: bool = False,
    X_and_mask_coarse: ndarray | DataFrame | None = None,
    y_coarse: ndarray | Series | None = None,
    coords_coarse: Coordinates | None = None,
    coords_fine: Coordinates | None = None,
    scorers: list[str] | None = None,
    sample_weight: ndarray | Series | None = None,
) -> dict[str, float]

Predict fine target and score the prediction.

Note that this method only predicts and scores for a single image. To predict and score for multiple images, use score().

Parameters:

Name Type Description Default
timestamp Timestamp

Timestamp associated with the data.

required
X_and_mask_fine ndarray or DataFrame

Fine predictors and masks.

required
y_fine ndarray or Series

The "true" fine target.

required
correct bool

Whether to correct the predicted fine target (from fine predictors and masks, X_and_mask_fine) using the finely-resampled residual for the prediction of the coarse target (from coarse predictors and masks, X_and_mask_coarse).

True
calibrate bool

Whether to calibrate the predicted fine target with the coarse validation target. This is done by offsetting and scaling the predicted fine target with the transform that makes the coarse true target (y_coarse) have the same mean and standard deviation as the validation coarse one (coarsened y_fine). Such transformation is an attempt to account for discrepancies between source and validation platforms at a common coarse grid from the computed scores.

False
X_and_mask_coarse ndarray or DataFrame or None

Coarse predictors and masks. It must be issued if correct is True.

None
y_coarse ndarray or Series or None

The "true" coarse target. It must be issued if correct or calibrate are True.

None
coords_coarse Coordinates or None

The coordinates of the coarse mesh. It must be issued if correct or calibrate are True.

None
coords_fine Coordinates or None

The coordinates of the fine mesh. It must be issued if correct or calibrate are True.

None
scorers list[str]

Aliases of the scorers to consider.

["r2", "r2_oos", "rmse", "rmse_delta", "mae", "mae_delta", "mbe"]
sample_weight ndarray or Series or None

Weight of each sample in the score.

None

Returns:

Name Type Description
score dict[str, float]

Prediction scores.

Source code in src/s3lst_ds/downscaling/piecewise_downscaling.py
def score_single(
    self,
    timestamp: pd.Timestamp,
    X_and_mask_fine: np.ndarray | pd.DataFrame,
    y_fine: np.ndarray | pd.Series,
    correct: bool = True,
    calibrate: bool = False,
    X_and_mask_coarse: np.ndarray | pd.DataFrame | None = None,
    y_coarse: np.ndarray | pd.Series | None = None,
    coords_coarse: xr.Coordinates | None = None,
    coords_fine: xr.Coordinates | None = None,
    scorers: list[str] | None = None,
    sample_weight: np.ndarray | pd.Series | None = None,
) -> dict[str, float]:
    """
    Predict fine target and score the prediction.

    Note that this method only predicts and scores for a single image. To predict
    and score for multiple images, use `score()`.

    Parameters
    ----------

    timestamp : pd.Timestamp
        Timestamp associated with the data.

    X_and_mask_fine : np.ndarray or pd.DataFrame
        Fine predictors and masks.

    y_fine : np.ndarray or pd.Series
        The "true" fine target.

    correct : bool, default=True
        Whether to correct the predicted fine target (from fine predictors and
        masks, `X_and_mask_fine`) using the finely-resampled residual for the
        prediction of the coarse target (from coarse predictors and masks,
        `X_and_mask_coarse`).

    calibrate : bool, default=False
        Whether to calibrate the predicted fine target with the coarse validation
        target. This is done by offsetting and scaling the predicted fine target
        with the transform that makes the coarse true target (`y_coarse`) have the
        same mean and standard deviation as the validation coarse one (coarsened
        `y_fine`). Such transformation is an attempt to account for discrepancies
        between source and validation platforms at a common coarse grid from the
        computed scores.

    X_and_mask_coarse : np.ndarray or pd.DataFrame or None, default=None
        Coarse predictors and masks. It must be issued if `correct` is `True`.

    y_coarse : np.ndarray or pd.Series or None, default=None
        The "true" coarse target.  It must be issued if `correct` or `calibrate` are
        `True`.

    coords_coarse : xarray.core.coordinates.Coordinates or None, default=None
        The coordinates of the coarse mesh. It must be issued if `correct` or
        `calibrate` are `True`.

    coords_fine : xarray.core.coordinates.Coordinates or None, default=None
        The coordinates of the fine mesh. It must be issued if `correct` or
        `calibrate` are `True`.

    scorers : list[str], default=["r2", "r2_oos", "rmse", "rmse_delta", "mae", "mae_delta", "mbe"]
        Aliases of the scorers to consider.

    sample_weight : np.ndarray or pd.Series or None, default=None
        Weight of each sample in the score.

    Returns
    -------

    score : dict[str, float]
        Prediction scores.
    """

    # Define default value for scorers argument
    if scorers is None:
        scorers = ["r2", "r2_oos", "rmse", "rmse_delta", "mae", "mae_delta", "mbe"]

    # If y_fine is a Series, reset its indexes. The analogous follows for
    # sample_weight. This is required, since indexes of y_fine, y_fine_pred and
    # y_fine_dummy_pred and sample_weight should match when combining them into a
    # single DataFrame afterwards.
    if isinstance(y_fine, pd.Series):
        y_fine = y_fine.reset_index(drop=True)
    if isinstance(sample_weight, pd.Series):
        sample_weight = sample_weight.reset_index(drop=True)

    # Predict fine target
    y_fine_pred = pd.Series(
        self.predict_single(
            timestamp=timestamp,
            X_and_mask_fine=X_and_mask_fine,
            correct=correct,
            X_and_mask_coarse=X_and_mask_coarse,
            y_coarse=y_coarse,
            coords_coarse=coords_coarse,
            coords_fine=coords_fine,
            gridded=False,
        )  # type: ignore
    )

    # Predict fine target from predictors using the dummy mean model
    # NOTE: this is required for computing out-of-sample coefficient of
    # determination
    y_fine_dummy_pred = (
        self.estimators[timestamp]
        .pipeline.named_steps["regressor"]
        .dummy_mean_model.predict(X_and_mask_fine)
    )

    # Calibrate the fine targets predicted by downscaler and dummy mean model with
    # the transform that would make the coarse true target have the same mean and
    # standard deviation as the coarsened fine validation one.
    if calibrate is True:
        # Express coarse true target in its grid
        shape_coarse = tuple(reversed(list(coords_coarse.sizes.values())))  # type: ignore
        y_coarse_grid = xr.DataArray(
            data=(
                y_coarse.values if isinstance(y_coarse, pd.Series) else y_coarse
            ).reshape(  # type: ignore
                shape_coarse  # type: ignore
            ),
            coords=coords_coarse,
            dims=("y", "x"),
            name="LST",
        )

        # Express fine validation target in its grid
        shape_fine = tuple(reversed(list(coords_fine.sizes.values())))  # type: ignore
        y_fine_grid = xr.DataArray(
            data=(
                y_fine.values if isinstance(y_fine, pd.Series) else y_fine
            ).reshape(  # type: ignore
                shape_fine  # type: ignore
            ),
            coords=coords_fine,
            dims=("y", "x"),
            name="LST",
        )

        # Reproject fine validation target to coarse grid
        y_fine_coarse = selective_reproject_match(
            data_src=y_fine_grid,
            data_target=y_coarse_grid,  # type: ignore
        )

        # Calibrate fine target predicted by downscaler
        # NOTE: https://math.stackexchange.com/a/2943606/209790
        y_fine_pred = (
            y_fine_coarse.mean().item()  # type: ignore
            + y_fine_coarse.std().item()  # type: ignore
            / y_coarse.std()  # type: ignore
            * (y_fine_pred - y_coarse.mean())  # type: ignore
        )

        # Calibrate fine target predicted by dummy mean model
        y_fine_dummy_pred = (
            y_fine_coarse.mean().item()  # type: ignore
            + y_fine_coarse.std().item()  # type: ignore
            / y_coarse.std()  # type: ignore
            * (y_fine_dummy_pred - y_coarse.mean())  # type: ignore
        )

    # Combine the true and predicted targets into a same DataFrame (so that all
    # records containing any nan may be later dropped and the prediction score
    # afterwards computed)
    data = pd.DataFrame(
        data={
            "y_true": y_fine,
            "y_pred": y_fine_pred,
            "y_dummy_pred": y_fine_dummy_pred,
            **(
                {
                    "sample_weight": sample_weight,
                }
                if sample_weight is not None
                else {}
            ),
        }
    )

    # Drop nan
    data = data.dropna()

    # Compute prediction score
    score = {
        # Coefficient of determination
        "r2": r2(
            y_true=data["y_true"],
            y_pred=data["y_pred"],
            sample_weight=(
                data["sample_weight"] if sample_weight is not None else None
            ),
        ),
        # Out-of-sample coefficient of determination
        # [NOTE: this is such that it uses a dummy mean model (simply the arithmetic
        # mean of the masked inference coarse targets) as reference.]
        "r2_oos": r2_oos(
            y_true=data["y_true"],
            y_pred=data["y_pred"],
            y_dummy_pred=data["y_dummy_pred"],
            sample_weight=(
                data["sample_weight"] if sample_weight is not None else None
            ),
        ),
        # Root mean squared error
        "rmse": rmse(
            y_true=data["y_true"],
            y_pred=data["y_pred"],
            sample_weight=(
                data["sample_weight"] if sample_weight is not None else None
            ),
        ),
        # Root mean squared error of the standardized target (using true target
        # statistics)
        "rmse_delta": rmse_delta(
            y_true=data["y_true"],
            y_pred=data["y_pred"],
            sample_weight=(
                data["sample_weight"] if sample_weight is not None else None
            ),
        ),
        # Mean absolute error
        "mae": mae(
            y_true=data["y_true"],
            y_pred=data["y_pred"],
            sample_weight=(
                data["sample_weight"] if sample_weight is not None else None
            ),
        ),
        # Mean absolute error of the standardized target (using true
        # target statistics)
        "mae_delta": mae_delta(
            y_true=data["y_true"],
            y_pred=data["y_pred"],
            sample_weight=(
                data["sample_weight"] if sample_weight is not None else None
            ),
        ),
        # Mean bias error
        "mbe": mbe(
            y_true=data["y_true"],
            y_pred=data["y_pred"],
            sample_weight=(
                data["sample_weight"] if sample_weight is not None else None
            ),
        ),
    }

    # Select solely scores of interest
    score = {
        scorer: score_i for scorer, score_i in score.items() if scorer in scorers
    }

    return score