Skip to content

EarthLens#

The unified entry point (facade) for all data sources.

earthlens.earthlens.EarthLens #

Facade that routes a download to the requested backend.

The class-level :attr:DataSources mapping resolves a string key ("chc", "amazon-s3", "ecmwf", or "gee" / its alias "google-earth-engine") to the concrete :class:AbstractDataSource subclass that owns the request shape, authentication, and post-processing for that provider. Each backend's SDK is an optional dependency, so :attr:DataSources is a :class:_LazyRegistry: indexing it imports the backend on demand and rewrites a missing SDK into a friendly ImportError naming the extra to install (e.g. pip install earthlens[ecmwf]).

Attributes:

Name Type Description
DataSources

Class-level lazy registry of registered backends. Keys are the user-facing names accepted by data_source; values resolve at access time to the corresponding subclasses of :class:earthlens.base.AbstractDataSource.

datasource

Instance attribute set by :meth:__init__ — holds the concrete backend that :meth:download routes to.

Examples:

  • Inspect the registered backends:

    >>> from earthlens.earthlens import EarthLens
    >>> sorted(EarthLens.DataSources)  # doctest: +NORMALIZE_WHITESPACE
    ['admin', 'admin-boundaries', 'airnow', 'alaska-satellite-facility',
     'amazon-s3', 'argo', 'argo-floats', 'argopy', 'asf', 'bathymetry',
     'bdc', 'brazil-data-cube', 'cdse', 'chc', 'chirps', 'climate-indices',
     'climate-projections', 'climate_indices', 'cmems', 'cmip6',
     'cop-dem', 'copernicus-dem', 'dea',
     'deafrica', 'dem', 'digital-earth-africa', 'digital-earth-australia',
     'drought', 'earth-search', 'earthdata', 'ecmwf', 'edo',
     'eea-aq', 'elevation', 'erddap', 'etopo', 'eumetsat', 'fdsn', 'firms', 'g-portal',
     'gbif', 'gdacs', 'gdo', 'gebco', 'gee', 'geoboundaries',
     'gfw', 'ghs', 'ghsl', 'glaciers', 'glims',
     'global-forest-watch', 'global-solar-atlas',
     'global-wind-atlas', 'goes', 'google-earth-engine', 'gsa', 'gwa',
     'hdx', 'himawari', 'human-settlement', 'inform', 'insar', 'ioos',
     'isric', 'iucn', 'jaxa', 'jaxa-earth', 'landsat',
     'national-water-model', 'natural-earth', 'nexrad', 'nrel',
     'nsrdb', 'nwis', 'nwm', 'nwp', 'obis', 'ohsome', 'openaq',
     'openeo', 'openstreetmap', 'osm', 'overpass', 'overture',
     'pangeo-cmip6', 'planetary-computer', 'protected-planet', 'ptree',
     'pvgis', 'radar',
     'redlist', 'rgi', 'risk-indicators', 'sensor-community',
     'sentinel-hub',
     'sentinelhub', 'soilgrids', 'solar-pv', 'solar-wind-atlas',
     'stac', 'teleconnections', 'thinkhazard', 'tiger',
     'tropycal', 'usdm', 'usgs-landsat', 'usgs-nwis',
     'usgs-water', 'veda', 'wdpa', 'wgms',
     'wind-toolkit', 'world-pop', 'worldpop']
    
    - Asking for an unknown backend raises ValueError:

    >>> from earthlens.earthlens import EarthLens
    >>> EarthLens(  # doctest: +ELLIPSIS
    ...     variables=[], data_source="not-a-real-source"
    ... )
    Traceback (most recent call last):
        ...
    ValueError: 'not-a-real-source' is not a supported data source. ...
    
See Also

:class:earthlens.chc.CHIRPS: CHIRPS rainfall over FTP. :class:earthlens.s3.S3: AWS Open-Data datasets over public S3 (ERA5, Sentinel-2, GOES, Copernicus DEM, ESA WorldCover) + an arbitrary-bucket passthrough. :class:earthlens.asf.ASF: Alaska Satellite Facility SAR search and InSAR baseline stack() via asf_search; reuses NASA Earthdata Login auth from :class:earthlens.earthdata.EarthdataAuth. Keys "asf" / "alaska-satellite-facility" / "insar". :class:earthlens.cmems.CMEMS: Copernicus Marine ocean datasets via copernicusmarine. :class:earthlens.earthdata.Earthdata: NASA EOSDIS granules across 9 DAACs via earthaccess + CMR; the first backend whose OUTPUT_KIND is per-dataset (raster / vector / tabular), not fixed. :class:earthlens.ecmwf.ECMWF: ERA5 via the Copernicus Climate Data Store (cdsapi). :class:earthlens.eumetsat.EUMETSAT: EUMETSAT Data Store products (MTG / MSG / Metop / Sentinel-3/-5P/-6 mirrors) via eumdac; per-collection OUTPUT_KIND; key "eumetsat". :class:earthlens.fdsn.FDSN: seismic events from the FDSN networks (USGS / EMSC / INGV / EarthScope / ISC / GeoNet) via obspy; the first vector-output backend. :class:earthlens.gee.GEE: imagery from Google Earth Engine (earthengine-api); keys "gee" / "google-earth-engine". :class:earthlens.gdacs.GDACS: GDACS multi-hazard disaster alerts (public feed, no credentials); key "gdacs". :class:earthlens.openaq.OpenAQ: ground-station air-quality measurements from OpenAQ v3 (tabular DataFrame). :class:earthlens.openeo.OpenEO: server-side openEO process graphs (defaults to CDSE openEO); raster output, aggregate= is a native aggregate_temporal_period node; key "openeo". :class:earthlens.sentinel_hub.SentinelHub: server-side Sentinel Hub render on CDSE (Process / Async / Batch raster, Statistical / Batch-Statistical tabular); mixed output, evalscript-driven; keys "sentinel-hub" / "sentinelhub". :class:earthlens.tropycal.TropicalCyclone: tropical-cyclone best tracks via tropycal (vector output); key "tropycal". :class:earthlens.firms.FIRMS: NASA FIRMS active-fire detections (MODIS / VIIRS) as a vector FeatureCollection; free MAP_KEY, no extra; key "firms". :class:earthlens.nwm.NWM: NOAA National Water Model hydrologic output — per-reach streamflow (chrtout, tabular) and gridded land surface (ldasout, raster) — fetched whole from the anonymous noaa-nwm-pds bucket; tabular subsetting + the retrospective Zarr read via pyramids LabeledDataset. Keys "nwm" / "national-water-model". :class:earthlens.cmip6.CMIP6: Raw CMIP6 climate projections — the full model x scenario x variable x member archive as analysis-ready Zarr on the open Pangeo gs://cmip6 bucket. A facet tuple (source_id / experiment_id / variable_id / table_id) resolves to the store(s) and pyramids writes a bbox/time NetCDF subset (raster); anonymous, no extra. Keys "cmip6" / "pangeo-cmip6" / "climate-projections". :class:earthlens.goes.GOES: NOAA GOES-R ABI geostationary imagery fetched whole (raw NetCDF granules, raster) from the anonymous noaa-goes19 / noaa-goes18 / noaa-goes16 buckets by satellite / product / domain / scan-time window; rides the [s3] extra (unsigned boto3), no auth, decode is downstream (pyramids / satpy); key "goes". :class:earthlens.hdx.HDX: Humanitarian Data Exchange resources via CKAN (hdx-python-api); the first mixed-output backend (downloads CSV / GeoTIFF / GeoPackage / … files as-is); public, no credentials; key "hdx". :class:earthlens.overture.Overture: Overture Maps Foundation GeoParquet (buildings / places / transportation / divisions) over public S3 via overturemaps; vector FeatureCollection output with a per-row license_id column (and an ODbL LicenseWarning); no credentials; key "overture". :class:earthlens.nwp.NWP: open numerical-weather-prediction forecasts (NOAA NODD / ECMWF Open Data / DWD) on a forecast (cycle, step) axis, returned as bbox-cropped COGs; key "nwp". :class:earthlens.radar.Radar: NEXRAD Level-II radar volumes assembled from the real-time chunk feed (vector inventory); keys "radar" / "nexrad". :class:earthlens.usgs_water.USGSWater: USGS NWIS / Water Data per-site water observations (discharge, gage height, water quality, …) via dataretrieval as a tabular DataFrame; optional API_USGS_PAT, anonymous works; keys "usgs-water" / "usgs-nwis" / "nwis". :class:earthlens.ghsl.GHSL: JRC Global Human Settlement Layer (population / built-up / settlement-model grids + R2025A WUP projections) over open HTTPS, reprojected / mosaicked / cropped to the AOI via pyramids as raster GeoTIFFs (one per product × epoch; aggregate= reduces across epochs); no credentials; keys "ghsl" / "ghs" / "human-settlement". :class:earthlens.glaciers.Glaciers: glacier outlines / fluctuations over three open sources — RGI 7.0 per-region outlines (UNESCO IHP-WINS) and GLIMS WFS time-series outlines as vector FeatureCollections clipped to the AOI, and the WGMS Fluctuations of Glaciers (mass balance / front variation / state) as a tabular DataFrame; per-instance OUTPUT_KIND, aggregate= rejected; no credentials; keys "glaciers" / "rgi" / "glims" / "wgms". :class:earthlens.worldpop.WorldPop: WorldPop open population data hub (CC-BY-4.0, no credentials) — per-country / global gridded population, density, age/sex, births, projections; mosaic + crop to the AOI via pyramids with a tidy age/sex table for demographic products; mixed output; keys "worldpop" / "world-pop". :class:earthlens.gbif.GBIF: GBIF species occurrences via pygbif (anonymous); vector occurrence-point FeatureCollection; key "gbif". :class:earthlens.obis.OBIS: OBIS marine occurrences via pyobis (anonymous); vector occurrence-point FeatureCollection; key "obis". :class:earthlens.drought.Drought: Drought-indicator backend over three live services — US Drought Monitor (vector polygons via GeoJSON), Copernicus EDO/GDO (raster via the Copernicus drought GetCoverage REST endpoint), and CSIC SPEIbase (raster via NetCDF). Per-instance OUTPUT_KIND. No SDK extra. Four discoverability keys ("drought" / "usdm" / "edo" / "gdo") all resolve to the same backend; all require an explicit dataset= kwarg. :class:earthlens.wdpa.WDPA: Protected Planet (WDPA) protected-area polygons via the direct v4 REST API (?token=); vector polygon FeatureCollection; keys "wdpa" / "protected-planet". :class:earthlens.iucn.IUCN: IUCN Red List v4 assessments via the direct REST shim (Bearer token); tabular DataFrame (always a CC-BY-NC LicenseWarning); keys "iucn" / "redlist". :class:earthlens.argo.ARGO: Argo autonomous-float ocean profiles (temperature / salinity / pressure, plus BGC parameters) via argopy as a tabular long-format DataFrame; region / float: / profile: selectors, open data (no auth); keys "argo" / "argo-floats" / "argopy". :class:earthlens.osm.OSM: OpenStreetMap features over two public, keyless protocols — overpy (Overpass, current-state) + ohsome (OSM history / analytics) — as a vector FeatureCollection with an ODbL LicenseWarning; named-query catalog (overpass:hospitals, ohsome:buildings) + raw query= / filter= override; keys "osm" / "openstreetmap" / "overpass" / "ohsome".

Source code in src/earthlens/earthlens.py
 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
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
class EarthLens:
    """Facade that routes a download to the requested backend.

    The class-level :attr:`DataSources` mapping resolves a string key
    (`"chc"`, `"amazon-s3"`, `"ecmwf"`, or `"gee"` / its alias
    `"google-earth-engine"`) to the concrete
    :class:`AbstractDataSource` subclass that owns the request shape,
    authentication, and post-processing for that provider. Each
    backend's SDK is an optional dependency, so :attr:`DataSources`
    is a :class:`_LazyRegistry`: indexing it imports the backend on
    demand and rewrites a missing SDK into a friendly
    `ImportError` naming the extra to install
    (e.g. `pip install earthlens[ecmwf]`).

    Attributes:
        DataSources: Class-level lazy registry of registered backends.
            Keys are the user-facing names accepted by `data_source`;
            values resolve at access time to the corresponding
            subclasses of
            :class:`earthlens.base.AbstractDataSource`.
        datasource: Instance attribute set by :meth:`__init__` —
            holds the concrete backend that :meth:`download` routes to.

    Examples:
        - Inspect the registered backends:

            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> sorted(EarthLens.DataSources)  # doctest: +NORMALIZE_WHITESPACE
            ['admin', 'admin-boundaries', 'airnow', 'alaska-satellite-facility',
             'amazon-s3', 'argo', 'argo-floats', 'argopy', 'asf', 'bathymetry',
             'bdc', 'brazil-data-cube', 'cdse', 'chc', 'chirps', 'climate-indices',
             'climate-projections', 'climate_indices', 'cmems', 'cmip6',
             'cop-dem', 'copernicus-dem', 'dea',
             'deafrica', 'dem', 'digital-earth-africa', 'digital-earth-australia',
             'drought', 'earth-search', 'earthdata', 'ecmwf', 'edo',
             'eea-aq', 'elevation', 'erddap', 'etopo', 'eumetsat', 'fdsn', 'firms', 'g-portal',
             'gbif', 'gdacs', 'gdo', 'gebco', 'gee', 'geoboundaries',
             'gfw', 'ghs', 'ghsl', 'glaciers', 'glims',
             'global-forest-watch', 'global-solar-atlas',
             'global-wind-atlas', 'goes', 'google-earth-engine', 'gsa', 'gwa',
             'hdx', 'himawari', 'human-settlement', 'inform', 'insar', 'ioos',
             'isric', 'iucn', 'jaxa', 'jaxa-earth', 'landsat',
             'national-water-model', 'natural-earth', 'nexrad', 'nrel',
             'nsrdb', 'nwis', 'nwm', 'nwp', 'obis', 'ohsome', 'openaq',
             'openeo', 'openstreetmap', 'osm', 'overpass', 'overture',
             'pangeo-cmip6', 'planetary-computer', 'protected-planet', 'ptree',
             'pvgis', 'radar',
             'redlist', 'rgi', 'risk-indicators', 'sensor-community',
             'sentinel-hub',
             'sentinelhub', 'soilgrids', 'solar-pv', 'solar-wind-atlas',
             'stac', 'teleconnections', 'thinkhazard', 'tiger',
             'tropycal', 'usdm', 'usgs-landsat', 'usgs-nwis',
             'usgs-water', 'veda', 'wdpa', 'wgms',
             'wind-toolkit', 'world-pop', 'worldpop']

            ```
        - Asking for an unknown backend raises `ValueError`:

            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> EarthLens(  # doctest: +ELLIPSIS
            ...     variables=[], data_source="not-a-real-source"
            ... )
            Traceback (most recent call last):
                ...
            ValueError: 'not-a-real-source' is not a supported data source. ...

            ```

    See Also:
        :class:`earthlens.chc.CHIRPS`: CHIRPS rainfall over FTP.
        :class:`earthlens.s3.S3`: AWS Open-Data datasets over public S3
            (ERA5, Sentinel-2, GOES, Copernicus DEM, ESA WorldCover) +
            an arbitrary-bucket passthrough.
        :class:`earthlens.asf.ASF`: Alaska Satellite Facility SAR
            search and InSAR baseline `stack()` via `asf_search`;
            reuses NASA Earthdata Login auth from
            :class:`earthlens.earthdata.EarthdataAuth`. Keys
            `"asf"` / `"alaska-satellite-facility"` / `"insar"`.
        :class:`earthlens.cmems.CMEMS`: Copernicus Marine ocean
            datasets via `copernicusmarine`.
        :class:`earthlens.earthdata.Earthdata`: NASA EOSDIS granules
            across 9 DAACs via `earthaccess` + CMR; the first backend
            whose `OUTPUT_KIND` is per-dataset (raster / vector /
            tabular), not fixed.
        :class:`earthlens.ecmwf.ECMWF`: ERA5 via the Copernicus
            Climate Data Store (cdsapi).
        :class:`earthlens.eumetsat.EUMETSAT`: EUMETSAT Data Store
            products (MTG / MSG / Metop / Sentinel-3/-5P/-6 mirrors)
            via `eumdac`; per-collection `OUTPUT_KIND`; key `"eumetsat"`.
        :class:`earthlens.fdsn.FDSN`: seismic events from the FDSN
            networks (USGS / EMSC / INGV / EarthScope / ISC / GeoNet)
            via `obspy`; the first `vector`-output backend.
        :class:`earthlens.gee.GEE`: imagery from Google Earth Engine
            (`earthengine-api`); keys `"gee"` / `"google-earth-engine"`.
        :class:`earthlens.gdacs.GDACS`: GDACS multi-hazard disaster
            alerts (public feed, no credentials); key `"gdacs"`.
        :class:`earthlens.openaq.OpenAQ`: ground-station air-quality
            measurements from OpenAQ v3 (tabular `DataFrame`).
        :class:`earthlens.openeo.OpenEO`: server-side openEO process graphs
            (defaults to CDSE openEO); `raster` output, `aggregate=` is a
            native `aggregate_temporal_period` node; key `"openeo"`.
        :class:`earthlens.sentinel_hub.SentinelHub`: server-side Sentinel
            Hub render on CDSE (Process / Async / Batch raster, Statistical /
            Batch-Statistical tabular); `mixed` output, evalscript-driven;
            keys `"sentinel-hub"` / `"sentinelhub"`.
        :class:`earthlens.tropycal.TropicalCyclone`: tropical-cyclone
            best tracks via `tropycal` (`vector` output); key
            `"tropycal"`.
        :class:`earthlens.firms.FIRMS`: NASA FIRMS active-fire
            detections (MODIS / VIIRS) as a `vector` FeatureCollection;
            free `MAP_KEY`, no extra; key `"firms"`.
        :class:`earthlens.nwm.NWM`: NOAA National Water Model hydrologic
            output — per-reach streamflow (`chrtout`, `tabular`) and
            gridded land surface (`ldasout`, `raster`) — fetched whole
            from the anonymous `noaa-nwm-pds` bucket; tabular subsetting +
            the retrospective Zarr read via pyramids `LabeledDataset`. Keys
            `"nwm"` / `"national-water-model"`.
        :class:`earthlens.cmip6.CMIP6`: Raw CMIP6 climate projections — the
            full `model x scenario x variable x member` archive as
            analysis-ready Zarr on the open Pangeo `gs://cmip6` bucket. A
            facet tuple (`source_id` / `experiment_id` / `variable_id` /
            `table_id`) resolves to the store(s) and pyramids writes a
            bbox/time NetCDF subset (`raster`); anonymous, no extra. Keys
            `"cmip6"` / `"pangeo-cmip6"` / `"climate-projections"`.
        :class:`earthlens.goes.GOES`: NOAA GOES-R ABI geostationary imagery
            fetched whole (raw NetCDF granules, `raster`) from the anonymous
            `noaa-goes19` / `noaa-goes18` / `noaa-goes16` buckets by
            satellite / product / domain / scan-time window; rides the `[s3]`
            extra (unsigned boto3), no auth, decode is downstream
            (pyramids / satpy); key `"goes"`.
        :class:`earthlens.hdx.HDX`: Humanitarian Data Exchange resources
            via CKAN (`hdx-python-api`); the first `mixed`-output
            backend (downloads CSV / GeoTIFF / GeoPackage / … files
            as-is); public, no credentials; key `"hdx"`.
        :class:`earthlens.overture.Overture`: Overture Maps Foundation
            GeoParquet (buildings / places / transportation / divisions)
            over public S3 via `overturemaps`; `vector` FeatureCollection
            output with a per-row `license_id` column (and an ODbL
            `LicenseWarning`); no credentials; key `"overture"`.
        :class:`earthlens.nwp.NWP`: open numerical-weather-prediction
            forecasts (NOAA NODD / ECMWF Open Data / DWD) on a forecast
            `(cycle, step)` axis, returned as bbox-cropped COGs; key
            `"nwp"`.
        :class:`earthlens.radar.Radar`: NEXRAD Level-II radar volumes
            assembled from the real-time chunk feed (`vector` inventory);
            keys `"radar"` / `"nexrad"`.
        :class:`earthlens.usgs_water.USGSWater`: USGS NWIS / Water Data
            per-site water observations (discharge, gage height,
            water quality, …) via `dataretrieval` as a `tabular`
            `DataFrame`; optional `API_USGS_PAT`, anonymous works; keys
            `"usgs-water"` / `"usgs-nwis"` / `"nwis"`.
        :class:`earthlens.ghsl.GHSL`: JRC Global Human Settlement Layer
            (population / built-up / settlement-model grids + R2025A WUP
            projections) over open HTTPS, reprojected / mosaicked / cropped
            to the AOI via `pyramids` as `raster` GeoTIFFs (one per
            product × epoch; `aggregate=` reduces across epochs); no
            credentials; keys `"ghsl"` / `"ghs"` / `"human-settlement"`.
        :class:`earthlens.glaciers.Glaciers`: glacier outlines / fluctuations
            over three open sources — RGI 7.0 per-region outlines (UNESCO
            IHP-WINS) and GLIMS WFS time-series outlines as `vector`
            `FeatureCollection`s clipped to the AOI, and the WGMS Fluctuations
            of Glaciers (mass balance / front variation / state) as a
            `tabular` `DataFrame`; per-instance `OUTPUT_KIND`, `aggregate=`
            rejected; no credentials; keys `"glaciers"` / `"rgi"` / `"glims"`
            / `"wgms"`.
        :class:`earthlens.worldpop.WorldPop`: WorldPop open population data
            hub (CC-BY-4.0, no credentials) — per-country / global gridded
            population, density, age/sex, births, projections; mosaic +
            crop to the AOI via `pyramids` with a tidy age/sex table for
            demographic products; `mixed` output; keys `"worldpop"` /
            `"world-pop"`.
        :class:`earthlens.gbif.GBIF`: GBIF species occurrences via
            `pygbif` (anonymous); `vector` occurrence-point
            FeatureCollection; key `"gbif"`.
        :class:`earthlens.obis.OBIS`: OBIS marine occurrences via
            `pyobis` (anonymous); `vector` occurrence-point
            FeatureCollection; key `"obis"`.
        :class:`earthlens.drought.Drought`: Drought-indicator backend over
            three live services — US Drought Monitor (vector polygons via
            GeoJSON), Copernicus EDO/GDO (raster via the Copernicus drought
            `GetCoverage` REST endpoint), and CSIC SPEIbase (raster via
            NetCDF). Per-instance `OUTPUT_KIND`. No SDK extra. Four
            discoverability keys (`"drought"` / `"usdm"` / `"edo"` /
            `"gdo"`) all resolve to the same backend; all require an
            explicit `dataset=` kwarg.
        :class:`earthlens.wdpa.WDPA`: Protected Planet (WDPA)
            protected-area polygons via the direct v4 REST API
            (`?token=`); `vector` polygon FeatureCollection; keys
            `"wdpa"` / `"protected-planet"`.
        :class:`earthlens.iucn.IUCN`: IUCN Red List v4 assessments via
            the direct REST shim (Bearer token); `tabular` `DataFrame`
            (always a CC-BY-NC `LicenseWarning`); keys `"iucn"` /
            `"redlist"`.
        :class:`earthlens.argo.ARGO`: Argo autonomous-float ocean
            profiles (temperature / salinity / pressure, plus BGC
            parameters) via `argopy` as a `tabular` long-format
            `DataFrame`; region / `float:` / `profile:` selectors, open
            data (no auth); keys `"argo"` / `"argo-floats"` / `"argopy"`.
        :class:`earthlens.osm.OSM`: OpenStreetMap features over two public,
            keyless protocols — `overpy` (Overpass, current-state) +
            `ohsome` (OSM history / analytics) — as a `vector`
            FeatureCollection with an ODbL `LicenseWarning`; named-query
            catalog (`overpass:hospitals`, `ohsome:buildings`) + raw
            `query=` / `filter=` override; keys `"osm"` /
            `"openstreetmap"` / `"overpass"` / `"ohsome"`.

    """

    DataSources = _LazyRegistry(
        {
            "chc": ("earthlens.chc", "CHIRPS", "", {}),
            # Back-compat alias: the package was originally named after
            # its best-known dataset (CHIRPS), then generalised to cover
            # the full Climate Hazards Center catalog. The `"chirps"`
            # key is kept for callers that still use it.
            "chirps": ("earthlens.chc", "CHIRPS", "", {}),
            "amazon-s3": ("earthlens.s3", "S3", "s3", {}),
            # Alaska Satellite Facility SAR search + InSAR baseline `stack()`
            # via `asf_search`. Reuses NASA Earthdata Login from
            # `earthlens.earthdata` — no second credential system. Aliases
            # `"alaska-satellite-facility"` / `"insar"`.
            "asf": ("earthlens.asf", "ASF", "asf", {}),
            "alaska-satellite-facility": ("earthlens.asf", "ASF", "asf", {}),
            "insar": ("earthlens.asf", "ASF", "asf", {}),
            "cmems": ("earthlens.cmems", "CMEMS", "cmems", {}),
            # Raw CMIP6 archive (full model x scenario x variable x member
            # matrix) as analysis-ready Zarr on the open Pangeo `gs://cmip6`
            # bucket. Anonymous (no auth); reads via pyramids (GDAL /vsigs/),
            # so no per-backend SDK — the `cmip6` extra is empty. Aliases
            # `"pangeo-cmip6"` / `"climate-projections"`.
            "cmip6": ("earthlens.cmip6", "CMIP6", "", {}),
            "pangeo-cmip6": ("earthlens.cmip6", "CMIP6", "", {}),
            "climate-projections": ("earthlens.cmip6", "CMIP6", "", {}),
            "earthdata": ("earthlens.earthdata", "Earthdata", "earthdata", {}),
            "ecmwf": ("earthlens.ecmwf", "ECMWF", "ecmwf", {}),
            "eumetsat": ("earthlens.eumetsat", "EUMETSAT", "eumetsat", {}),
            "fdsn": ("earthlens.fdsn", "FDSN", "fdsn", {}),
            "gee": ("earthlens.gee", "GEE", "gee", {}),
            "google-earth-engine": ("earthlens.gee", "GEE", "gee", {}),
            # NOAA GOES-R ABI imagery (anonymous noaa-goes19/18/16 buckets);
            # rides the [s3] extra (unsigned boto3). Raw NetCDF granules out
            # (raster); decode is downstream (pyramids / satpy).
            "goes": ("earthlens.goes", "GOES", "s3", {}),
            # GDACS is a public feed (requests only), so no extra to hint.
            "gdacs": ("earthlens.gdacs", "GDACS", "", {}),
            "hdx": ("earthlens.hdx", "HDX", "hdx", {}),
            "openaq": ("earthlens.openaq", "OpenAQ", "openaq", {}),
            # Ground-obs air-quality trio completing OpenAQ's coverage, all
            # tabular (DataFrame). airnow (US/Canada EPA, /aq/data/ bbox REST)
            # and sensor-community (crowdsourced archive CSV) are core
            # (requests + pandas); eea-aq wraps airbase behind the [eea_aq]
            # extra.
            "airnow": ("earthlens.airnow", "AirNow", "", {}),
            "eea-aq": ("earthlens.eea_aq", "EEA_AQ", "eea_aq", {}),
            "sensor-community": (
                "earthlens.sensor_community",
                "SensorCommunity",
                "",
                {},
            ),
            # openEO server-side processing (defaults to CDSE openEO). Builds a
            # process graph the backend executes; returns the written paths.
            "openeo": ("earthlens.openeo", "OpenEO", "openeo", {}),
            # Sentinel Hub server-side render on CDSE. Builds a bbox/geometry +
            # evalscript request the server renders; returns written GeoTIFF
            # paths (raster planes) or table paths / S3 URIs (tabular / batch).
            # `OUTPUT_KIND="mixed"`. The `"sentinelhub"` alias matches the SDK
            # spelling.
            "sentinel-hub": (
                "earthlens.sentinel_hub",
                "SentinelHub",
                "sentinel-hub",
                {},
            ),
            "sentinelhub": (
                "earthlens.sentinel_hub",
                "SentinelHub",
                "sentinel-hub",
                {},
            ),
            # Overture Maps GeoParquet over public S3 (no creds). Vector
            # FeatureCollection output with a per-row license_id column.
            "overture": ("earthlens.overture", "Overture", "overture", {}),
            # JRC Global Human Settlement Layer (open HTTPS, attribution-only).
            # Download-and-localise raster: tiles/whole-globe .zip -> pyramids
            # reproject/mosaic/crop. No extra SDK (requests + pyramids are core),
            # so no extra to hint. Aliases "ghs" / "human-settlement".
            "ghsl": ("earthlens.ghsl", "GHSL", "", {}),
            "ghs": ("earthlens.ghsl", "GHSL", "", {}),
            "human-settlement": ("earthlens.ghsl", "GHSL", "", {}),
            "tropycal": ("earthlens.tropycal", "TropicalCyclone", "tropycal", {}),
            # FIRMS needs a free MAP_KEY but no SDK (requests + pandas
            # are core), so like GDACS there is no extra to hint.
            "firms": ("earthlens.firms", "FIRMS", "", {}),
            # NOAA National Water Model (anonymous noaa-nwm-pds bucket); the
            # [nwm] extra pulls boto3. Alias "national-water-model".
            "nwm": ("earthlens.nwm", "NWM", "nwm", {}),
            "national-water-model": ("earthlens.nwm", "NWM", "nwm", {}),
            # Open NWP forecasts (NOAA NODD / ECMWF Open Data / DWD); the
            # [nwp] extra pulls herbie-data + ecmwf-opendata.
            "nwp": ("earthlens.nwp", "NWP", "nwp", {}),
            # NEXRAD Level-II radar (anonymous chunk bucket); alias "nexrad".
            "radar": ("earthlens.radar", "Radar", "radar", {}),
            "nexrad": ("earthlens.radar", "Radar", "radar", {}),
            # One unified STAC backend over several endpoints. The bare
            # `"stac"` key leaves the endpoint to be inferred from the
            # requested collection; the three endpoint aliases pre-bind
            # `endpoint=` so `data_source="cdse"` needs no extra kwarg.
            "stac": ("earthlens.stac", "STAC", "stac", {}),
            "planetary-computer": (
                "earthlens.stac",
                "STAC",
                "stac",
                {"endpoint": "planetary-computer"},
            ),
            "earth-search": (
                "earthlens.stac",
                "STAC",
                "stac",
                {"endpoint": "earth-search"},
            ),
            "cdse": ("earthlens.stac", "STAC", "stac", {"endpoint": "cdse"}),
            # Digital Earth Africa STAC (anonymous, af-south-1) — WOfS, FC,
            # crop mask, Landsat/Sentinel-2 ARD, GeoMedian, Copernicus DEM.
            "deafrica": ("earthlens.stac", "STAC", "stac", {"endpoint": "deafrica"}),
            "digital-earth-africa": (
                "earthlens.stac",
                "STAC",
                "stac",
                {"endpoint": "deafrica"},
            ),
            # Digital Earth Australia STAC (anonymous, ap-southeast-2) —
            # Landsat / Sentinel-2 NBART ARD, WOfS, FC, GeoMedian, Intertidal,
            # mangrove cover, SRTM DEM.
            "dea": ("earthlens.stac", "STAC", "stac", {"endpoint": "dea"}),
            "digital-earth-australia": (
                "earthlens.stac",
                "STAC",
                "stac",
                {"endpoint": "dea"},
            ),
            # NASA VEDA STAC (anonymous, us-west-2) — NASA-curated derived
            # products: Black Marble HD nightlights, CMIP6 climate, NLDAS-3,
            # fire/disaster-damage, HLS NDVI, EPA emissions.
            "veda": ("earthlens.stac", "STAC", "stac", {"endpoint": "veda"}),
            # USGS LandsatLook (the authoritative Landsat C2 STAC; SR/ST/L1
            # split into separate collections, requester-pays on
            # s3://usgs-landsat, us-west-2). Alias 'landsat' for convenience.
            "usgs-landsat": (
                "earthlens.stac",
                "STAC",
                "stac",
                {"endpoint": "usgs-landsat"},
            ),
            "landsat": (
                "earthlens.stac",
                "STAC",
                "stac",
                {"endpoint": "usgs-landsat"},
            ),
            # INPE Brazil Data Cube (BDC) STAC v1 — anonymous, the only global
            # source of CBERS-4/4A and AMAZONIA-1. Alias 'brazil-data-cube'.
            "bdc": ("earthlens.stac", "STAC", "stac", {"endpoint": "bdc"}),
            "brazil-data-cube": (
                "earthlens.stac",
                "STAC",
                "stac",
                {"endpoint": "bdc"},
            ),
            # USGS NWIS / Water Data (dataretrieval). Tabular DataFrame of
            # per-site water observations; anonymous access works. The
            # "usgs-nwis" / "nwis" aliases point at the same backend.
            "usgs-water": ("earthlens.usgs_water", "USGSWater", "usgs-water", {}),
            "usgs-nwis": ("earthlens.usgs_water", "USGSWater", "usgs-water", {}),
            "nwis": ("earthlens.usgs_water", "USGSWater", "usgs-water", {}),
            # WorldPop open population data hub (CC-BY-4.0, no creds). Mosaic +
            # crop per-country GeoTIFFs to the AOI; demographic products also
            # emit a tidy age/sex table. `OUTPUT_KIND="mixed"`. Alias
            # "world-pop". The default REST path needs no extra SDK.
            "worldpop": ("earthlens.worldpop", "WorldPop", "worldpop", {}),
            "world-pop": ("earthlens.worldpop", "WorldPop", "worldpop", {}),
            # Biodiversity cluster. GBIF / OBIS are anonymous occurrence search
            # (vector FeatureCollection of points); WDPA returns protected-area
            # polygons (token, ?token= query param); IUCN returns Red List
            # assessments (tabular DataFrame, Bearer token). GBIF/OBIS need the
            # pygbif/pyobis extra; WDPA/IUCN use core requests (no extra).
            "gbif": ("earthlens.gbif", "GBIF", "gbif", {}),
            "obis": ("earthlens.obis", "OBIS", "obis", {}),
            "wdpa": ("earthlens.wdpa", "WDPA", "", {}),
            "protected-planet": ("earthlens.wdpa", "WDPA", "", {}),
            "iucn": ("earthlens.iucn", "IUCN", "", {}),
            "redlist": ("earthlens.iucn", "IUCN", "", {}),
            # JAXA archive over three protocols: authless `jaxa-earth`
            # (STAC + COG via the official jaxa.earth API), credentialed
            # `gportal` (G-Portal SFTP via the community gportal SDK), and
            # credentialed `ptree` (Himawari-8/9 HSD via plain FTP with
            # stdlib ftplib). Per-dataset routing — the catalog's
            # `protocol:` field picks the branch. `OUTPUT_KIND="raster"`.
            "jaxa": ("earthlens.jaxa", "JAXA", "jaxa", {}),
            "jaxa-earth": ("earthlens.jaxa", "JAXA", "jaxa", {}),
            "g-portal": ("earthlens.jaxa", "JAXA", "jaxa", {}),
            # ptree / himawari are unambiguously the stdlib-`ftplib`
            # branch, so their `extras` slot is empty — a failed import
            # here won't misdirect a user to `pip install
            # earthlens[jaxa]` for a branch that never needed it.
            "ptree": ("earthlens.jaxa", "JAXA", "", {}),
            "himawari": ("earthlens.jaxa", "JAXA", "", {}),
            # Argo autonomous-float ocean profiles via the `argopy` SDK
            # (open data, no auth). `OUTPUT_KIND="tabular"` — a long-format
            # DataFrame of profiles. The `"argo"` key is canonical; the
            # `"argo-floats"` / `"argopy"` aliases collapse to it.
            "argo": ("earthlens.argo", "ARGO", "argo", {}),
            "argo-floats": ("earthlens.argo", "ARGO", "argo", {}),
            "argopy": ("earthlens.argo", "ARGO", "argo", {}),
            # Generic ERDDAP client — one backend for many public ERDDAP
            # servers (NOAA CoastWatch / CRW, NCEI, …). `dataset=<id>`
            # picks a curated row; its `protocol` sets the per-instance
            # OUTPUT_KIND (griddap -> raster, tabledap -> tabular). Alias
            # "ioos".
            "erddap": ("earthlens.erddap", "ERDDAP", "erddap", {}),
            "ioos": ("earthlens.erddap", "ERDDAP", "erddap", {}),
            # Global topography / bathymetry DEMs (GEBCO 2020 + ETOPO1
            # ice/bedrock) subset via NOAA ERDDAP griddap -> pyramids ->
            # GeoTIFF. Open data (requests + pyramids are core), so no extra
            # to hint. Aliases "gebco" / "etopo" — pass dataset= to pick the
            # DEM (e.g. dataset="gebco_2020" / "etopo1_ice" / "etopo1_bedrock").
            "bathymetry": ("earthlens.bathymetry", "Bathymetry", "", {}),
            "gebco": ("earthlens.bathymetry", "Bathymetry", "", {}),
            "etopo": ("earthlens.bathymetry", "Bathymetry", "", {}),
            # Global Solar Atlas + Global Wind Atlas climatology layers,
            # bbox-subset to GeoTIFF. Open data / CC-BY-4.0 (requests +
            # pyramids are core), so no extra to hint. The wind layers are
            # read windowed over /vsicurl; the solar layers download once and
            # crop locally. Aliases "global-solar-atlas" / "global-wind-atlas"
            # / "gsa" / "gwa" — pass variables=[...] to pick layers (e.g.
            # variables=["ghi", "wind_100m"]).
            "solar-wind-atlas": (
                "earthlens.solar_wind_atlas",
                "SolarWindAtlas",
                "",
                {},
            ),
            "global-solar-atlas": (
                "earthlens.solar_wind_atlas",
                "SolarWindAtlas",
                "",
                {},
            ),
            "global-wind-atlas": (
                "earthlens.solar_wind_atlas",
                "SolarWindAtlas",
                "",
                {},
            ),
            "gsa": ("earthlens.solar_wind_atlas", "SolarWindAtlas", "", {}),
            "gwa": ("earthlens.solar_wind_atlas", "SolarWindAtlas", "", {}),
            # JRC PVGIS solar-radiation / PV time series over the keyless
            # REST API. Per-coordinate hourly DataFrame (tabular); a point
            # or a bbox sampled to a point grid. variables=["seriescalc"]
            # (hourly radiation / PV power) or ["tmy"]. No extra SDK (core
            # requests + pandas). Alias "solar-pv".
            "pvgis": ("earthlens.pvgis", "PVGIS", "", {}),
            "solar-pv": ("earthlens.pvgis", "PVGIS", "", {}),
            # Monthly climate / teleconnection indices (ENSO/ONI, NAO, AO,
            # PDO, AMO, SOI, PNA, ...) from NOAA PSL + KNMI Climate Explorer
            # ASCII series -> long-format DataFrame. Open data (requests +
            # pandas are core), so no extra to hint. Aliases "climate_indices"
            # / "teleconnections". Global scalar series: spatial args are
            # ignored and aggregate= is rejected.
            "climate-indices": ("earthlens.climate_indices", "ClimateIndices", "", {}),
            "climate_indices": ("earthlens.climate_indices", "ClimateIndices", "", {}),
            "teleconnections": ("earthlens.climate_indices", "ClimateIndices", "", {}),
            # NREL NSRDB (solar) + WIND Toolkit (wind) resource time series over
            # the keyed REST CSV download API. Per-coordinate hourly DataFrame
            # (tabular); a point or a bbox sampled to a point grid. Requires a
            # free NREL api_key + email (NREL_API_KEY / NREL_EMAIL), forwarded
            # via **backend_kwargs. No extra SDK (core requests + pandas). The
            # "nsrdb" / "wind-toolkit" aliases pre-bind product=; pick a product
            # directly with product="nsrdb-psm3" / "nsrdb-tmy" / "wtk".
            "nrel": ("earthlens.nrel", "NREL", "", {}),
            "nsrdb": ("earthlens.nrel", "NREL", "", {"product": "nsrdb-psm3"}),
            "wind-toolkit": ("earthlens.nrel", "NREL", "", {"product": "wtk"}),
            # Country/admin-indexed risk indicators over three sources — GFDRR
            # ThinkHazard! + INFORM Risk (JRC) (both public) + the Global Forest
            # Watch Data API (needs GFW_API_KEY). Per-instance OUTPUT_KIND
            # (tabular -> DataFrame, vector -> FeatureCollection); pass
            # country=<ISO3> (or admin_code=) and, for gfw, api_key=. No extra
            # SDK (core requests + pandas + pyramids). Aliases "thinkhazard" /
            # "inform" / "gfw" / "global-forest-watch".
            "risk-indicators": (
                "earthlens.risk_indicators",
                "RiskIndicators",
                "",
                {},
            ),
            "thinkhazard": ("earthlens.risk_indicators", "RiskIndicators", "", {}),
            "inform": ("earthlens.risk_indicators", "RiskIndicators", "", {}),
            "gfw": ("earthlens.risk_indicators", "RiskIndicators", "", {}),
            "global-forest-watch": (
                "earthlens.risk_indicators",
                "RiskIndicators",
                "",
                {},
            ),
            # Glacier outlines / fluctuations over three open sources — RGI 7.0
            # per-region outlines (UNESCO IHP-WINS) + GLIMS WFS time-series
            # outlines + WGMS Fluctuations of Glaciers (tabular). Per-instance
            # OUTPUT_KIND (vector -> FeatureCollection for rgi/glims, tabular ->
            # DataFrame for wgms); pass a bbox (lat_lim/lon_lim or aoi=) for
            # rgi/glims, or region= / glacier_id= / glacier_name= for wgms. No
            # extra SDK (core requests + pandas + pyramids); no auth. Aliases
            # "rgi" / "glims" / "wgms".
            "glaciers": ("earthlens.glaciers", "Glaciers", "", {}),
            "rgi": ("earthlens.glaciers", "Glaciers", "", {}),
            "glims": ("earthlens.glaciers", "Glaciers", "", {}),
            "wgms": ("earthlens.glaciers", "Glaciers", "", {}),
            # OpenStreetMap features over two public, keyless protocols — overpy
            # (Overpass, current-state) + ohsome (OSM history/analytics). Vector
            # FeatureCollection output with an ODbL LicenseWarning. The [osm]
            # extra pulls overpy + ohsome (imported lazily). Aliases
            # "openstreetmap" / "overpass" / "ohsome".
            "osm": ("earthlens.osm", "OSM", "osm", {}),
            "openstreetmap": ("earthlens.osm", "OSM", "osm", {}),
            "overpass": ("earthlens.osm", "OSM", "osm", {}),
            "ohsome": ("earthlens.osm", "OSM", "osm", {}),
            # Administrative-boundary polygons from four public sources —
            # geoBoundaries (per-country ADM0-5), CGAZ (seamless global ADM0/1/2),
            # Natural Earth (cultural admin), US Census TIGER/Line (states /
            # counties / tracts / nation); GADM omitted for license. Vector
            # FeatureCollection output (EPSG:4326); no extra SDK (core requests +
            # pyramids), all four public. Pass the dataset via variables=
            # ["geoboundaries:adm1"] plus its selector (country=<ISO3> /
            # scale= / year= / state=). Aliases "admin-boundaries" /
            # "geoboundaries" / "natural-earth" / "tiger".
            "admin": ("earthlens.admin", "AdminBoundaries", "", {}),
            "admin-boundaries": ("earthlens.admin", "AdminBoundaries", "", {}),
            "geoboundaries": ("earthlens.admin", "AdminBoundaries", "", {}),
            "natural-earth": ("earthlens.admin", "AdminBoundaries", "", {}),
            "tiger": ("earthlens.admin", "AdminBoundaries", "", {}),
            # ISRIC SoilGrids 2.0 — global 250 m soil properties (clay, sand,
            # silt, cfvo, phh2o, cec, nitrogen, soc, ocd, ocs, bdod) subset
            # server-side over OGC WCS at maps.isric.org and written as GeoTIFF
            # (OUTPUT_KIND="raster"; aggregate= rejected — static, no time axis).
            # No extra SDK — the WCS transport is pyramids' Dataset.from_wcs;
            # open, CC-BY 4.0, no auth. Alias "isric".
            "soilgrids": ("earthlens.soilgrids", "SoilGrids", "", {}),
            "isric": ("earthlens.soilgrids", "SoilGrids", "", {}),
            # Copernicus DEM (GLO-30 / GLO-90) over the anonymous AWS Open
            # Data buckets — the account-free path to a global DEM. Reuses
            # the [s3] unsigned-boto3 substrate; no new SDK. Aliases
            # "copernicus-dem" / "cop-dem" / "elevation".
            "dem": ("earthlens.dem", "DEM", "s3", {}),
            "copernicus-dem": ("earthlens.dem", "DEM", "s3", {}),
            "cop-dem": ("earthlens.dem", "DEM", "s3", {}),
            "elevation": ("earthlens.dem", "DEM", "s3", {}),
            # Drought-indicator backend over three live public services:
            # USDM (vector GeoJSON polygon classes), Copernicus EDO/GDO (raster
            # via the Copernicus drought GetCoverage REST endpoint —
            # TIME + SELECTED_TIMESCALE custom params, not a conformant WCS),
            # and CSIC SPEIbase (raster NetCDF). Per-instance OUTPUT_KIND from
            # the resolved `dataset=` row. No SDK extra (requests + pyramids are
            # core). The four keys (`drought` / `usdm` / `edo` / `gdo`) are
            # discoverability aliases — all four resolve to the same backend
            # and all four require an explicit `dataset=` kwarg (e.g.
            # `EarthLens("usdm", dataset="usdm", ...)`,
            # `EarthLens("edo", dataset="edo-spaST", ...)`). No alias pre-binds
            # the dataset: pre-bound aliases collide with the facade's own
            # `dataset=` plumbing (TypeError: multiple values) and only work for
            # exactly one of the catalog rows, so they trade a tiny ergonomic
            # win for two foot-guns.
            "drought": ("earthlens.drought", "Drought", "", {}),
            "usdm": ("earthlens.drought", "Drought", "", {}),
            "edo": ("earthlens.drought", "Drought", "", {}),
            "gdo": ("earthlens.drought", "Drought", "", {}),
        }
    )

    def __init__(
        self,
        data_source: str = "chc",
        variables: dict[str, list[str]] | list[str] | None = None,
        temporal_resolution: str = "daily",
        start: str | datetime | date | None = None,
        end: str | datetime | date | None = None,
        path: Path | str | None = None,
        lat_lim: list[float] | None = None,
        lon_lim: list[float] | None = None,
        fmt: str = "%Y-%m-%d",
        aoi: Any = None,
        buffer: float | None = None,
        dataset: str | None = None,
        cadence: str | None = None,
        time: Any = None,
        **backend_kwargs: object,
    ):
        """Resolve the backend and construct it with the user's parameters.

        Validates `data_source` against :attr:`DataSources`, fills in
        whole-Earth defaults for missing `lat_lim` / `lon_lim`, and
        instantiates the concrete backend bound to `self.datasource`.

        Args:
            data_source: Backend key. One of the registered keys in
                :attr:`DataSources` — `"chc"` (alias `"chirps"`),
                `"climate-indices"` (aliases `"climate_indices"` /
                `"teleconnections"`),
                `"amazon-s3"`, `"asf"` (aliases
                `"alaska-satellite-facility"` / `"insar"`),
                `"cmems"`, `"earthdata"`, `"ecmwf"`,
                `"eumetsat"`, `"fdsn"`, `"firms"`, `"gdacs"`, `"gee"`
                (alias `"google-earth-engine"`), `"ghsl"` (aliases
                `"ghs"` / `"human-settlement"`), `"glaciers"` (aliases
                `"rgi"` / `"glims"` / `"wgms"`), `"hdx"`,
                `"nrel"` (aliases `"nsrdb"` / `"wind-toolkit"`), `"nwp"`,
                `"openaq"`, `"openeo"`, `"overture"`, `"radar"` (alias
                `"nexrad"`), `"sentinel-hub"` (alias `"sentinelhub"`),
                `"pvgis"` (alias `"solar-pv"`),
                `"stac"` (with endpoint aliases `"planetary-computer"` /
                `"earth-search"` / `"cdse"`), `"tropycal"`,
                `"usgs-water"` (aliases `"usgs-nwis"` / `"nwis"`),
                `"worldpop"` (alias `"world-pop"`), `"argo"` (aliases
                `"argo-floats"` / `"argopy"`), or `"admin"` (aliases
                `"admin-boundaries"` / `"geoboundaries"` /
                `"natural-earth"` / `"tiger"`). See
                `sorted(EarthLens.DataSources)` for the live list.
                Defaults to `"chc"`.
            temporal_resolution: The download cadence — `"daily"` or
                `"monthly"` for most backends; the GEE backend also accepts
                `"raw"` and `"yearly"`. Prefer the `cadence=` alias for the
                download-cadence backends (CHIRPS / S3 / ECMWF / GEE). The
                concrete backend may accept a narrower
                set; check its `temporal_resolution` handling. Note the
                meaning is backend-specific:

                * a **download-loop cadence** that spaces the per-step
                  requests — CHIRPS, S3, ECMWF, GEE;
                * an **advisory label** only — NWP (the real cadence
                  comes from each model's metadata);
                * a **server-side rollup selector** — OpenAQ (picks the
                  measurements vs. hourly/daily endpoint);
                * a **service selector** — USGS Water (sub-daily maps to
                  the instantaneous service);
                * **ignored / forced to `"all"`** for the snapshot
                  backends with no per-step time axis — Overture,
                  Tropycal, FDSN, FIRMS, GDACS, Radar.

                For the first (download-cadence) group, `cadence` is the
                clearer spelling. Defaults to `"daily"`.
            cadence: Clearer alias for `temporal_resolution` in its
                download-cadence role (CHIRPS / S3 / ECMWF / GEE). When
                given, it overrides `temporal_resolution`. Defaults to
                `None`.
            start: Inclusive start date. A string (parsed with `fmt`,
                falling back to ISO-8601), or a `datetime` / `date` /
                `pandas.Timestamp` object. Defaults to `None`.
            end: Inclusive end date, same accepted types as `start`.
                Defaults to `None`.
            time: A single time range, the ergonomic alternative to the
                `start` / `end` pair (STAC `"a/b"` / earthaccess `(a, b)`
                idiom). Accepts a `"start/end"` string, a `(start, end)`
                2-sequence, a `slice`, or a single date (an instant). Splits
                into `start` / `end`; both bounds are required (an
                open-ended interval such as `"2020-01-01/"` raises), and
                passing it together with `start` / `end` raises
                `ValueError`. Defaults to `None`.
            path: Output directory. Created by the backend if it does
                not exist. When omitted (`None`), defaults to
                `./earthlens-data/<data_source>/` rather than the current
                working directory; pass `path=""` to opt into the CWD.
            dataset: Explicit dataset / collection key, the ergonomic
                alternative to keying it into `variables`. When given
                with a plain `variables` list, the facade composes the
                backend's request for you — the S3 backend receives it
                as a native `dataset` argument, and the dataset-keyed
                backends (ECMWF, GEE, CHC, …) receive the composed
                `{dataset: variables}` dict. Passing `dataset` together
                with a dict `variables` raises `ValueError` for the
                dataset-keyed backends. Defaults to `None` (the legacy
                nested-dict `variables` call is unchanged).
            variables: Backend-specific variable specification.
                Shape depends on the backend:

                * ECMWF: `dict[str, list[str]]` mapping CDS dataset
                  short name to a list of variable codes drawn from
                  that dataset, e.g.
                  `{"reanalysis-era5-single-levels": ["2m-temperature"]}`.
                * GEE: `dict[str, list[str]]` mapping an Earth Engine
                  asset id to a list of band ids, e.g.
                  `{"UCSB-CHG/CHIRPS/DAILY": ["precipitation"]}`.
                * CHIRPS: either `list[str]` of variable codes
                  (legacy — auto-routed to the `"global-daily"` /
                  `"global-monthly"` dataset key via
                  `temporal_resolution`), or `dict[str, list[str]]`
                  mapping a CHIRPS catalog dataset key (e.g.
                  `"africa-pentad"`, `"chirps-v3-global-monthly"`)
                  to a list of variable codes drawn from that
                  dataset, e.g. `{"africa-monthly": ["precipitation"]}`.
                  See `Catalog().list_datasets()` for the curated
                  dataset keys.
                * S3 / ERA5: `list[str]` of variable codes from the
                  S3 backend's catalog.

                Defaults to `None`.
            lat_lim: Legacy latitude pair `[lat_min, lat_max]` — prefer the
                single `aoi=` channel, which also accepts a bbox. Defaults to
                :data:`DEFAULT_LATITUDE_LIMIT` (whole Earth). Mutually
                exclusive with `aoi`.
            lon_lim: Legacy longitude pair `[lon_min, lon_max]` — prefer the
                single `aoi=` channel. Defaults to
                :data:`DEFAULT_LONGITUDE_LIMIT` (whole Earth). Mutually
                exclusive with `aoi`.
            fmt: `strptime` format tried first when `start` / `end` are
                strings; a non-matching string falls back to an ISO-8601
                parse, and `datetime` / `date` objects ignore it. An
                optional override rather than a requirement. Defaults to
                `"%Y-%m-%d"`.
            aoi: A single area-of-interest, the ergonomic alternative to
                the `lat_lim` / `lon_lim` pair. Accepts a bbox
                `[min_lon, min_lat, max_lon, max_lat]` (GeoJSON W, S, E,
                N order), a bbox mapping, a `(lon, lat)` point (with
                `buffer`), a shapely geometry, any `__geo_interface__`
                object, a GeoJSON geometry / Feature, a WKT string, or a
                `GeoDataFrame` / `GeoSeries`. Reduced to `lat_lim` /
                `lon_lim` by :func:`earthlens.base.spatial.normalize_aoi`.
                Passing both `aoi` and `lat_lim` / `lon_lim` raises
                `ValueError`. Defaults to `None`.
            buffer: Half-width in degrees applied to a `(lon, lat)` point
                `aoi` to grow it into a square box. Only valid together
                with a point `aoi`. Defaults to `None`.
            **backend_kwargs: Extra keyword arguments forwarded
                verbatim to the chosen backend's constructor — for
                backend-specific options the facade does not name
                explicitly (e.g. ECMWF's `skip_constraints`, or GEE's
                `scale` / `crs` / `reducer` / `export_via` /
                `drive_folder` / `gcs_bucket` / `region`). Credentials are
                not constructor kwargs: backends that defer auth take them
                on `authenticate()` instead (e.g. GEE's `service_account`
                / `service_key` / `project`), so forwarding those through
                the facade raises `TypeError`. A kwarg the backend does
                not accept is its `TypeError`, not the facade's.

        Raises:
            ValueError: If `data_source` is not a key of
                :attr:`DataSources`, if both `aoi` and
                `lat_lim` / `lon_lim` are given, if `buffer` is given
                without a point `aoi`, or if `aoi` is malformed.
            AuthenticationError: For backends that defer auth
                (ECMWF, GEE, STAC, CMEMS, …) the network handshake is
                lazy, so an auth failure surfaces on the first
                `authenticate()` / `download()` / `search()`, not at
                construction. GEE resolves and opens its Earth Engine
                connection lazily too: its *offline* precondition (no
                `service_account` + `service_key` / `project` and no
                matching environment variable) and its actual Earth
                Engine errors (invalid key, unregistered project) all
                surface on first use, not here.
            ImportError: If the chosen backend's optional SDK is not
                installed (e.g. `data_source="gee"` without
                `pip install earthlens[gee]`).

        Examples:
            - The DataSources registry resolves the backend class
              before construction. Inspect what each key points to:

                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> EarthLens.DataSources["chc"].__name__
                'CHIRPS'
                >>> EarthLens.DataSources["chirps"].__name__  # alias
                'CHIRPS'
                >>> EarthLens.DataSources["ecmwf"].__name__
                'ECMWF'
                >>> EarthLens.DataSources["gee"].__name__
                'GEE'

                ```
            - An unknown `data_source` is rejected before any backend
              code runs:

                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> EarthLens(  # doctest: +ELLIPSIS
                ...     variables=[], data_source="bogus"
                ... )
                Traceback (most recent call last):
                    ...
                ValueError: 'bogus' is not a supported data source. ...

                ```
            - Construct an ECMWF-backed facade. Marked
              `# doctest: +SKIP` because it builds a real
              :class:`cdsapi.Client`, which requires
              `~/.cdsapirc`:

                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> earthlens = EarthLens(  # doctest: +SKIP
                ...     data_source="ecmwf",
                ...     temporal_resolution="daily",
                ...     start="2022-01-01",
                ...     end="2022-01-01",
                ...     variables={
                ...         "reanalysis-era5-single-levels": ["2m-temperature"],
                ...     },
                ...     lat_lim=[4.0, 5.0],
                ...     lon_lim=[-75.0, -74.0],
                ...     path="examples/data/era5",
                ... )

                ```

        See Also:
            :meth:`download`: Triggers the actual retrieval.
        """
        # Back-compat for the legacy positional order
        # `EarthLens(variables, data_source, ...)`. `data_source` is now
        # the first positional; a caller who passed `variables` first sends
        # a list / dict where a source key (a `str`) is expected, so detect
        # that and swap, with a deprecation warning. Runs before
        # `_check_source` so the (now-correct) key is the one validated.
        if not isinstance(data_source, str):
            warnings.warn(
                "EarthLens(variables, data_source, ...) is deprecated; pass "
                "data_source first: EarthLens(data_source, variables=...).",
                DeprecationWarning,
                stacklevel=2,
            )
            data_source, variables = (
                variables if isinstance(variables, str) else "chc",
                data_source,
            )
        self._check_source(data_source)

        # Most backends take a `variables` (or `dataset`) request axis. A few —
        # currently only CMIP6 — address their data purely by facet keywords
        # (`variable_id=`, `source_id=`, ...) and declare no `variables`
        # parameter; those neither require nor accept `variables=`/`dataset=`.
        # A backend is treated as facet-only *only* when its constructor
        # explicitly declares neither `variables` nor a catch-all `**kwargs`
        # (a `MagicMock` test double, or any pass-through signature, keeps the
        # historical variables-required behaviour).
        backend_cls = self.DataSources[data_source]
        backend_params = inspect.signature(backend_cls.__init__).parameters
        has_var_keyword = any(
            p.kind is inspect.Parameter.VAR_KEYWORD for p in backend_params.values()
        )
        requires_variables = "variables" in backend_params or has_var_keyword
        if requires_variables:
            if variables is None and dataset is None:
                raise ValueError(
                    "variables= is required (or pass dataset= for a "
                    "dataset-keyed backend), e.g. "
                    "EarthLens('chc', variables=['precipitation'])."
                )
        elif variables is not None or dataset is not None:
            raise ValueError(
                f"the {data_source!r} backend addresses its data by facet "
                "keyword arguments (e.g. variable_id=, source_id=), not "
                "variables=/dataset=."
            )

        # `cadence=` is the clearer alias for the download-cadence role of
        # `temporal_resolution`; when given it simply overrides it.
        if cadence is not None:
            temporal_resolution = cadence

        # A single `time=` range supersedes the separate `start` / `end`
        # pair (STAC `"a/b"` / earthaccess `(a, b)` idiom). Split it into
        # the `start` / `end` the backend already consumes.
        if time is not None:
            if start is not None or end is not None:
                raise ValueError("pass either time= or start=/end=, not both")
            start, end = split_time(time)
            # An open-ended interval (`"2020-01-01/"`) would leave a `None`
            # bound that the backend silently expands to "now" — a surprise
            # multi-year span. Require both bounds explicitly.
            if start is None or end is None:
                raise ValueError(
                    "time= needs both bounds; got an open-ended interval. "
                    "Pass an explicit start and end (e.g. "
                    "time='2020-01-01/2020-01-31')."
                )

        # A single `aoi=` supersedes the legacy `lat_lim` / `lon_lim`
        # pair. It accepts a bbox, a point (+ `buffer`), a shapely /
        # GeoJSON / WKT geometry, or a GeoDataFrame, and is reduced to
        # the `[min, max]` pairs every backend already consumes. A backend
        # that declares its own richer `aoi` parameter (e.g. WorldPop's
        # ISO3 / bbox / GeoDataFrame) instead receives `aoi` verbatim and
        # interprets it itself.
        clip_geometry = None
        if aoi is not None and "aoi" in backend_params:
            if buffer is not None:
                raise ValueError(
                    f"buffer= is not supported by the {data_source!r} backend, "
                    "which interprets aoi= itself"
                )
            backend_kwargs = {**backend_kwargs, "aoi": aoi}
        elif aoi is not None:
            if lat_lim is not None or lon_lim is not None:
                raise ValueError("pass either aoi= or lat_lim=/lon_lim=, not both")
            lat_lim, lon_lim, clip_geometry = resolve_aoi(aoi, buffer=buffer)
        elif buffer is not None:
            raise ValueError(
                "buffer= only applies to a point aoi=(lon, lat); pass aoi= too"
            )

        if lat_lim is None:
            lat_lim = DEFAULT_LATITUDE_LIMIT
        if lon_lim is None:
            lon_lim = DEFAULT_LONGITUDE_LIMIT

        # An omitted `path` makes earthlens manage the location: `download()`
        # persists to a named per-source subdirectory (`./earthlens-data/<source>/`)
        # rather than scattering files into the cwd, while `load()` (which only
        # needs the in-memory object) redirects to a throwaway temp dir and
        # removes the empty default afterwards. An explicit `path=""` still means
        # the CWD (a deliberate choice).
        self._explicit_path = path is not None
        if path is None:
            path = Path("earthlens-data") / data_source
            logger.info(
                f"No `path` given; download() writes {data_source!r} output under "
                f"{path}/ (load() uses a temp dir)."
            )

        # Per-key defaults (e.g. the STAC endpoint aliases pre-bind
        # `endpoint=`) are merged *under* the user's kwargs, so an
        # explicit value always wins.
        merged_kwargs = {
            **self.DataSources.default_kwargs(data_source),
            **backend_kwargs,
        }

        # Reject an unknown backend kwarg here, with a did-you-mean, rather
        # than letting it surface as a raw TypeError from deep in the
        # backend constructor.
        self._check_backend_kwargs(data_source, backend_params, merged_kwargs)

        # `dataset=` + a plain `variables` list is resolved into the
        # shape each backend wants — a native `dataset` kwarg for the S3
        # backend, or the legacy `{dataset: variables}` dict for the
        # dataset-keyed backends. With `dataset=None` this is a no-op.
        from earthlens.base._requests import normalize_dataset_variables

        request_kwargs = (
            normalize_dataset_variables(backend_cls, dataset, variables)
            if requires_variables
            else {}
        )

        self.datasource = backend_cls(
            start=start,
            end=end,
            lat_lim=lat_lim,
            lon_lim=lon_lim,
            temporal_resolution=temporal_resolution,
            path=path,
            fmt=fmt,
            **request_kwargs,
            **merged_kwargs,
        )
        # A polygon `aoi=` records its mask on the backend's spatial extent
        # so raster backends clip the fetched bbox to the exact shape.
        if clip_geometry is not None:
            self.datasource._attach_clip_geometry(clip_geometry)

    @classmethod
    def _check_source(cls, data_source: str) -> None:
        """Validate `data_source` against the registry, with a did-you-mean hint.

        Args:
            data_source: The backend key to validate.

        Raises:
            ValueError: If `data_source` is not a registered key. The
                message names the closest registered key (via `difflib`)
                and lists the known keys.
        """
        if data_source not in cls.DataSources:
            close = difflib.get_close_matches(data_source, list(cls.DataSources), n=1)
            hint = f" Did you mean {close[0]!r}?" if close else ""
            raise ValueError(
                f"{data_source!r} is not a supported data source. "
                f"Known: {sorted(cls.DataSources)}.{hint}"
            )

    #: Constructor parameter names the facade owns and supplies itself.
    #: Everything else a backend declares is a backend-specific option,
    #: surfaced by :meth:`options_for` and accepted as a kwarg.
    _FACADE_PARAMS = frozenset(
        {
            "self",
            "start",
            "end",
            "variables",
            "dataset",
            "lat_lim",
            "lon_lim",
            "temporal_resolution",
            "path",
            "fmt",
            "aoi",
            "buffer",
        }
    )

    @classmethod
    def options_for(cls, data_source: str) -> list[str]:
        """List a backend's extra constructor options.

        The backend-specific keyword arguments a backend accepts beyond
        the facade's own parameters — the discoverable surface for
        `**backend_kwargs` (e.g. GEE's `scale` / `crs` / `service_account`,
        ECMWF's `skip_constraints`).

        Args:
            data_source: A registered backend key.

        Returns:
            The sorted backend-specific option names.

        Raises:
            ValueError: If `data_source` is not a registered key.

        Examples:
            - GEE exposes its export knobs as options:
                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> options = EarthLens.options_for("gee")
                >>> "scale" in options and "crs" in options
                True

                ```
        """
        cls._check_source(data_source)
        params = inspect.signature(cls.DataSources[data_source].__init__).parameters
        return sorted(
            name
            for name, parameter in params.items()
            if name not in cls._FACADE_PARAMS
            and parameter.kind not in (parameter.VAR_KEYWORD, parameter.VAR_POSITIONAL)
        )

    @classmethod
    def _check_backend_kwargs(
        cls, data_source: str, backend_params: Any, kwargs: dict[str, object]
    ) -> None:
        """Reject an unexpected backend kwarg with a did-you-mean hint.

        Args:
            data_source: The backend key (for the error message).
            backend_params: The backend `__init__` parameters mapping.
            kwargs: The merged backend kwargs about to be forwarded.

        Raises:
            TypeError: If a key in `kwargs` is not an accepted backend
                parameter (skipped when the backend declares `**kwargs`).
        """
        if any(p.kind == p.VAR_KEYWORD for p in backend_params.values()):
            return
        accepted = {name for name in backend_params if name != "self"}
        for name in kwargs:
            if name not in accepted:
                close = difflib.get_close_matches(name, sorted(accepted), n=1)
                hint = f" Did you mean {close[0]!r}?" if close else ""
                raise TypeError(
                    f"the {data_source!r} backend got an unexpected keyword "
                    f"argument {name!r}.{hint} Backend options: "
                    f"{cls.options_for(data_source)}."
                )

    @classmethod
    def catalog(cls, data_source: str) -> AbstractCatalog:
        """Return the dataset / variable catalog for a backend.

        The catalogs hold the curated dataset and variable metadata
        (cadence, extent, bands) each backend ships, so they are the
        natural place to discover valid `dataset=` / `variables=` values
        without constructing the backend or hitting the network.

        Args:
            data_source: A registered backend key (see
                `sorted(EarthLens.DataSources)`).

        Returns:
            The backend's `Catalog` instance, loaded from its bundled
            data.

        Raises:
            ValueError: If `data_source` is not a registered key.
            ImportError: If the backend's optional SDK is required to
                import its module and is not installed.
            NotImplementedError: If the backend ships no catalog.

        Examples:
            - The CHC catalog exposes its curated datasets:
                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> catalog = EarthLens.catalog("chc")
                >>> len(catalog) > 0
                True

                ```
        """
        cls._check_source(data_source)
        module_name, extras = next(
            (mod, extra)
            for key, mod, extra in cls.DataSources.entries()
            if key == data_source
        )
        try:
            module = importlib.import_module(module_name)
        except ImportError as exc:
            hint = f" Install with `pip install earthlens[{extras}]`." if extras else ""
            raise ImportError(
                f"Backend {data_source!r} catalog is unavailable — its "
                f"runtime dependency is not installed.{hint}"
            ) from exc
        catalog_cls = getattr(module, "Catalog", None)
        if catalog_cls is None:
            raise NotImplementedError(
                f"the {data_source!r} backend ships no catalog to query"
            )
        return catalog_cls()

    @classmethod
    def list_datasets(cls, data_source: str) -> list[str]:
        """List a backend's curated dataset keys.

        Args:
            data_source: A registered backend key.

        Returns:
            The sorted curated dataset keys — the values accepted by
            `dataset=` (and `describe_dataset`).

        Raises:
            ValueError: If `data_source` is not a registered key.

        Examples:
            - CHC ships a curated dataset for African monthly rainfall:
                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> "africa-monthly" in EarthLens.list_datasets("chc")
                True

                ```
        """
        return sorted(cls.catalog(data_source).datasets)

    @classmethod
    def describe_dataset(cls, data_source: str, key: str) -> Any:
        """Return the catalog record for one dataset.

        Args:
            data_source: A registered backend key.
            key: A curated dataset key (see :meth:`list_datasets`).

        Returns:
            The backend-specific dataset record (carries the dataset's
            variables / bands, cadence, and extent).

        Raises:
            ValueError: If `data_source` is unknown, or `key` is not a
                curated dataset (the message suggests the closest key).

        Examples:
            - Inspect a CHC dataset's declared variables:
                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> dataset = EarthLens.describe_dataset("chc", "africa-monthly")
                >>> bool(dataset.variables)
                True

                ```
            - An unknown key is rejected with a did-you-mean hint:
                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> EarthLens.describe_dataset(  # doctest: +ELLIPSIS
                ...     "chc", "africa-month"
                ... )
                Traceback (most recent call last):
                    ...
                ValueError: 'africa-month' is not in the ...

                ```
        """
        return cls.catalog(data_source).get_dataset(key)

    @classmethod
    def guess_dataset(cls, data_source: str, text: str) -> list[str]:
        """Search a backend's datasets by free text.

        A discovery aid in the spirit of eodag's `guess_product_type`:
        case-insensitive substring matches first (capped), falling back
        to `difflib` fuzzy matches when nothing contains `text`. Searches
        the full `available_datasets` universe plus the curated keys.

        Args:
            data_source: A registered backend key.
            text: The free-text fragment to search for.

        Returns:
            Matching dataset keys, best matches first (may be empty).

        Raises:
            ValueError: If `data_source` is not a registered key.

        Examples:
            - Find the CHC monthly datasets:
                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> "africa-monthly" in EarthLens.guess_dataset("chc", "monthly")
                True

                ```
        """
        cat = cls.catalog(data_source)
        pool = sorted(set(cat.available_datasets) | set(cat.datasets))
        lowered = text.lower()
        hits = [name for name in pool if lowered in name.lower()]
        if hits:
            return hits[:20]
        return difflib.get_close_matches(text, pool, n=10, cutoff=0.3)

    def __getattr__(self, name: str) -> Any:
        """Delegate an unknown attribute to the bound backend.

        Python calls this only when normal lookup misses, so the facade's
        own attributes and methods always take precedence. It lets the
        facade transparently expose a backend's *own* surface without
        forcing it onto every backend — e.g.
        `EarthLens(data_source="nwm", ...)._feature_ids()` forwards to the
        NWM backend, while the same call on a CHIRPS-backed facade raises
        `AttributeError` (CHIRPS has no such method).

        Args:
            name: The attribute being looked up.

        Returns:
            The corresponding attribute of `self.datasource`.

        Raises:
            AttributeError: If `name` is a dunder, the backend is not yet
                bound (mid-construction), or the backend lacks `name`.

        Examples:
            - A backend-specific helper is reachable through the facade
              (live; skipped here):
                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> el = EarthLens(  # doctest: +SKIP
                ...     data_source="nwm",
                ...     dataset="chrtout",
                ...     variables=["streamflow"],
                ...     start="2024-01-01", end="2024-01-01",
                ... )
                >>> el._feature_ids()  # doctest: +SKIP

                ```
        """
        if name.startswith("__") and name.endswith("__"):
            raise AttributeError(name)
        datasource = self.__dict__.get("datasource")
        if datasource is None:
            raise AttributeError(
                f"{type(self).__name__!r} object has no attribute {name!r}"
            )
        return getattr(datasource, name)

    def __dir__(self) -> list[str]:
        """Include the bound backend's attributes for tab-completion."""
        own = set(super().__dir__())
        datasource = self.__dict__.get("datasource")
        if datasource is not None:
            own |= set(dir(datasource))
        return sorted(own)

    def authenticate(self, **credentials: Any) -> EarthLens:
        """Eagerly authenticate the bound backend; raise on failure.

        The explicit, fail-fast counterpart to the lazy authentication
        that otherwise happens on the first :meth:`download` / `search`.
        Delegates to
        :meth:`earthlens.base.AbstractDataSource.authenticate` — opening
        the network client or running the credential step — and is a
        no-op for credential-free backends. Lets callers separate "do I
        have valid credentials?" from the download itself, e.g. wrap only
        `authenticate()` in a `try/except AuthenticationError`.

        Any keyword arguments are forwarded verbatim to the backend's
        `authenticate`, so a backend that takes its credential there
        receives it — e.g. FIRMS accepts `api_key=` (falling back to the
        `FIRMS_MAP_KEY` environment variable when omitted). Passing a
        credential a backend does not accept raises `TypeError`.

        Args:
            **credentials: Backend-specific credential keywords forwarded
                to the bound backend's `authenticate` (e.g. FIRMS's
                `api_key`). Empty for credential-free or env-resolved
                backends.

        Returns:
            The facade, so it chains:
            `EarthLens(...).authenticate().download()`.

        Raises:
            AuthenticationError: If the backend cannot authenticate.

        Examples:
            - Verify credentials up front, then download (live; skipped
              here):
                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> EarthLens(  # doctest: +SKIP
                ...     data_source="ecmwf",
                ...     dataset="reanalysis-era5-single-levels",
                ...     variables=["2m-temperature"],
                ...     start="2022-01-01", end="2022-01-01",
                ... ).authenticate().download()

                ```
            - Pass a FIRMS key explicitly at the auth step (live;
              skipped here):
                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> EarthLens(  # doctest: +SKIP
                ...     data_source="firms",
                ...     variables=["VIIRS_SNPP_NRT"],
                ...     start="2024-08-01", end="2024-08-01",
                ...     lat_lim=[33.0, 35.0], lon_lim=[-119.0, -117.0],
                ... ).authenticate(api_key="…").download()

                ```
        """
        self.datasource.authenticate(**credentials)
        return self

    def search(self) -> list[RemoteProduct]:
        """List the products this request matches, without downloading them.

        The cheap, dry-run half of the search→fetch split: it queries the
        backend's catalog and returns one
        :class:`~earthlens.base.RemoteProduct` per item that
        :meth:`download` would fetch, so you can inspect or filter the
        result first.

        Returns:
            One :class:`~earthlens.base.RemoteProduct` per matching item;
            the empty list when nothing matches.

        Raises:
            NotImplementedError: If the bound backend keeps the legacy
                `_api`-only flow (CHIRPS, S3, ECMWF, GEE) and exposes no
                searchable product list — call :meth:`download` directly.

        Examples:
            - Preview a STAC search without fetching any bytes (live;
              skipped here):
                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> products = EarthLens(  # doctest: +SKIP
                ...     data_source="earth-search",
                ...     dataset="sentinel-2-l2a",
                ...     variables=["red"],
                ...     start="2024-01-01", end="2024-01-31",
                ...     aoi=[-75.0, 4.0, -74.0, 5.0],
                ... ).search()

                ```
        """
        try:
            return self.datasource._search()
        except NotImplementedError as exc:
            raise NotImplementedError(
                f"the {type(self.datasource).__name__} backend does not "
                f"support search()/preview()/count(); call download() instead."
            ) from exc

    def count(self) -> int:
        """Return how many products this request matches, without downloading.

        Uses the backend's :meth:`~earthlens.base.AbstractDataSource._count`
        hook, which a backend with a cheap server-side total overrides;
        otherwise it counts a :meth:`search`.

        Returns:
            The number of matching products.

        Raises:
            NotImplementedError: If the bound backend exposes no
                searchable product list (see :meth:`search`).
        """
        try:
            return self.datasource._count()
        except NotImplementedError as exc:
            raise NotImplementedError(
                f"the {type(self.datasource).__name__} backend does not "
                f"support search()/preview()/count(); call download() instead."
            ) from exc

    def preview(self, n: int = 10) -> list[dict[str, Any]]:
        """Return the first `n` matching products as plain dicts.

        A notebook-friendly view over :meth:`search`: each product is
        flattened to `{"id": ..., "href": ..., **metadata}` for quick
        tabular display before committing to a download.

        Args:
            n: Maximum number of products to return. Defaults to 10.

        Returns:
            Up to `n` dicts, each carrying the product `id`, `href`, and
            its backend-specific metadata.

        Raises:
            NotImplementedError: If the bound backend exposes no
                searchable product list (see :meth:`search`).
        """
        return [
            {"id": product.id, "href": product.href, **product.metadata}
            for product in self.search()[:n]
        ]

    def download(
        self,
        progress_bar: bool = True,
        aggregate: AggregationConfig | None = None,
        *args: object,
        **kwargs: object,
    ) -> Any:
        """Delegate the download to the bound backend.

        Forwards every argument verbatim to `self.datasource.download`.
        Each backend's `download` accepts its own backend-specific
        keyword arguments (for example, CHIRPS supports `cores` for
        parallel FTP retrieval), so unrecognised kwargs propagate
        through.

        Args:
            progress_bar: Whether the backend should print a per-date
                progress bar during the loop. Defaults to `True`.
            aggregate: Optional :class:`earthlens.aggregate.AggregationConfig`.
                Forwarded to backends whose `OUTPUT_KIND` is
                `"raster"` or `"mixed"` — the two shapes for which
                a gridded reduction is well-defined. Backends
                declaring `"vector"` or `"tabular"` reject a
                non-`None` `aggregate` with `NotImplementedError`
                before the backend's `download` is called (the
                aggregator has no meaningful semantics on
                `GeoDataFrame` / `DataFrame` rows). A backend
                without an explicit `OUTPUT_KIND` attribute is
                treated as `"raster"` for back-compatibility.
            *args: Forwarded positionally to `backend.download`.
            **kwargs: Forwarded as keywords to `backend.download`.

        Returns:
            Whatever the bound backend's `download` returns. The shape
            tracks the backend's `OUTPUT_KIND`:

            * `"raster"` / `"mixed"` file-writers — the list of written
              paths (`list[Path]`); GEE may also return export
              destination strings / `TaskInfo` for async exports.
            * `"vector"` — an in-memory `FeatureCollection` (e.g. FDSN,
              FIRMS, GDACS); radar returns a `GeoDataFrame`.
            * `"tabular"` — a `pandas.DataFrame` (e.g. OpenAQ,
              USGS Water).

            The legacy CHIRPS / ECMWF backends return their written
            `list[Path]` and also leave the files on disk under `path`.

        Raises:
            AuthenticationError: When the ECMWF backend cannot
                authenticate against CDS (typically a missing
                `~/.cdsapirc`). See
                :class:`earthlens.ecmwf.AuthenticationError`.
            KeyError: When any backend receives an unknown variable
                code that the catalog cannot resolve.
            NotImplementedError: When `aggregate=` is not `None` and
                the bound backend's `OUTPUT_KIND` is `"vector"` or
                `"tabular"`. The aggregator only handles gridded
                raster outputs; vector / tabular backends emit
                `GeoDataFrame` / `DataFrame` rows that have no
                meaningful gridded reduction.

        Examples:
            - End-to-end CHIRPS download. Marked `# doctest: +SKIP`
              because it makes a live FTP connection:

                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> earthlens = EarthLens(  # doctest: +SKIP
                ...     data_source="chc",
                ...     start="2009-01-01",
                ...     end="2009-01-02",
                ...     variables=["precipitation"],
                ...     lat_lim=[4.19, 4.64],
                ...     lon_lim=[-75.65, -74.73],
                ...     path="examples/data/chirps",
                ... )
                >>> earthlens.download()  # doctest: +SKIP

                ```
            - ECMWF download via the facade. Marked
              `# doctest: +SKIP` because CDS requires
              `~/.cdsapirc` and the request blocks for minutes
              while the queue serves it:

                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> earthlens = EarthLens(  # doctest: +SKIP
                ...     data_source="ecmwf",
                ...     start="2022-01-01",
                ...     end="2022-01-01",
                ...     variables={
                ...         "reanalysis-era5-single-levels": ["2m-temperature"],
                ...     },
                ...     lat_lim=[4.0, 5.0],
                ...     lon_lim=[-75.0, -74.0],
                ...     path="examples/data/era5",
                ... )
                >>> earthlens.download()  # doctest: +SKIP

                ```

        See Also:
            :meth:`earthlens.chc.CHIRPS.download`: CHIRPS
                backend implementation, including the `cores=`
                keyword for parallel retrieval.
            :meth:`earthlens.s3.S3.download`: S3/ERA5 backend
                implementation.
            :meth:`earthlens.ecmwf.ECMWF.download`: ECMWF/CDS
                backend implementation.
            :meth:`earthlens.gee.GEE.download`: Google Earth Engine
                backend implementation (`export_via`, the 32768-px
                synchronous cap).
        """
        return self._dispatch_download(
            *args, progress_bar=progress_bar, aggregate=aggregate, **kwargs
        )

    def _redirect_output_to_tempdir(self) -> None:
        """Point the backend output at a throwaway temp dir for an in-memory load.

        Called by :meth:`load` when `path` was omitted: `load` only needs the
        in-memory object, so the incidental files go to a fresh temp directory
        instead of the persistent `./earthlens-data/<source>/` default — and the
        default directory is removed if construction left it empty, so a
        load-and-plot run never leaves files in the working tree. Creating the
        temp dir here (not at construction) means a construct-only or
        download-only run allocates no temp directory.
        """
        default_dir = getattr(self.datasource, "root_dir", None)
        tmp = Path(tempfile.mkdtemp(prefix="earthlens-load-"))
        self.datasource.root_dir = tmp
        self.datasource.path = tmp
        if default_dir is not None and default_dir != tmp:
            try:
                if default_dir.is_dir() and not any(default_dir.iterdir()):
                    default_dir.rmdir()
            except OSError:
                pass

    def _dispatch_download(
        self,
        *args: object,
        progress_bar: bool = True,
        aggregate: AggregationConfig | None = None,
        **kwargs: object,
    ) -> Any:
        """Run the `aggregate=` guard, then forward to the backend's `download`.

        The shared fetch path behind :meth:`download` (which first redirects an
        omitted `path` to the persistent directory) and :meth:`load` (which
        keeps the throwaway temp directory). Rejects a non-`None` `aggregate`
        for a non-raster backend before the backend is called.

        Args:
            *args: Forwarded positionally to `backend.download`.
            progress_bar: Whether the backend prints its progress bar.
            aggregate: Optional aggregation config; only valid for `"raster"` /
                `"mixed"` backends.
            **kwargs: Forwarded as keywords to `backend.download`.

        Returns:
            Whatever the bound backend's `download` returns.

        Raises:
            NotImplementedError: If `aggregate` is not `None` and the backend's
                `OUTPUT_KIND` is `"vector"` or `"tabular"`.
        """
        if aggregate is not None:
            output_kind = getattr(self.datasource, "OUTPUT_KIND", "raster")
            if output_kind not in {"raster", "mixed"}:
                raise NotImplementedError(
                    f"aggregate= is not supported for "
                    f"{type(self.datasource).__name__} backends "
                    f"(OUTPUT_KIND={output_kind!r}). The aggregator only "
                    f"handles gridded raster outputs; vector / tabular "
                    f"backends emit GeoDataFrames or DataFrames that do "
                    f"not have a meaningful gridded reduction."
                )
            kwargs["aggregate"] = aggregate

        return self.datasource.download(*args, progress_bar=progress_bar, **kwargs)

    def load(self, *args: object, **kwargs: object) -> Any:
        """Download and return the data in memory instead of only on disk.

        The lazy-stack convenience: runs :meth:`download` and hands back the
        fetched data as the project's **native pyramids objects** rather than
        leaving the caller to re-open files. Raster outputs are read into a
        `pyramids.Dataset` / `NetCDF` (a `.nc` path becomes a `NetCDF`, every
        other raster a `Dataset`); a non-raster output a backend already
        returns in memory (a `FeatureCollection` / `GeoDataFrame` /
        `DataFrame`) is passed through unchanged, as are non-raster file paths
        (e.g. a `.csv` table from a mixed backend). The files are still written
        to `path` — `load` adds the in-memory handle on top.

        When `path` was omitted, `load` writes to a throwaway temp directory
        (not the persistent `./earthlens-data/<source>/` that `download` uses),
        so a load-and-plot run never leaves files in the working tree — there is
        no need to pass `path=tempfile.mkdtemp()` yourself. Each returned raster
        is detached into an in-memory copy and the temp directory is removed
        immediately, so repeated `load()` calls — e.g. a per-year loop — do not
        accumulate gigabytes under the system temp dir. (Because the data is
        copied into memory, a `path=`-less `load` of a very large raster reads it
        fully into RAM; pass `path=` to keep the lazy, file-backed objects.)

        `xarray` is intentionally not the return type: a returned
        `pyramids.Dataset` / `NetCDF` already exposes `.to_xarray()` for callers
        who want the climate-stack interop, so EarthLens stays free of an
        xarray dependency.

        Args:
            *args: Forwarded positionally to :meth:`download`.
            **kwargs: Forwarded as keywords to :meth:`download`.

        Returns:
            For a raster / mixed backend, a list with each written raster read
            into a `pyramids.Dataset` / `NetCDF` (non-raster entries left as
            their `Path`); for a vector / tabular backend, the in-memory
            `FeatureCollection` / `GeoDataFrame` / `DataFrame` `download`
            returned.

        Examples:
            - Load CHIRPS precipitation into pyramids `Dataset` objects
              (live; skipped here):
                ```python
                >>> from earthlens.earthlens import EarthLens
                >>> rasters = EarthLens(  # doctest: +SKIP
                ...     "chc", variables=["precipitation"],
                ...     start="2020-01-01", end="2020-01-02", aoi=[-75, 4, -74, 5],
                ... ).load()
                >>> rasters[0].read_array()  # doctest: +SKIP

                ```
        """
        if self._explicit_path:
            return _load_result(self._dispatch_download(*args, **kwargs))
        self._redirect_output_to_tempdir()
        temp_dir = self.datasource.path
        result = _load_result(self._dispatch_download(*args, **kwargs))
        return _detach_and_cleanup(temp_dir, result)

__dir__() #

Include the bound backend's attributes for tab-completion.

Source code in src/earthlens/earthlens.py
def __dir__(self) -> list[str]:
    """Include the bound backend's attributes for tab-completion."""
    own = set(super().__dir__())
    datasource = self.__dict__.get("datasource")
    if datasource is not None:
        own |= set(dir(datasource))
    return sorted(own)

__getattr__(name) #

Delegate an unknown attribute to the bound backend.

Python calls this only when normal lookup misses, so the facade's own attributes and methods always take precedence. It lets the facade transparently expose a backend's own surface without forcing it onto every backend — e.g. EarthLens(data_source="nwm", ...)._feature_ids() forwards to the NWM backend, while the same call on a CHIRPS-backed facade raises AttributeError (CHIRPS has no such method).

Parameters:

Name Type Description Default
name str

The attribute being looked up.

required

Returns:

Type Description
Any

The corresponding attribute of self.datasource.

Raises:

Type Description
AttributeError

If name is a dunder, the backend is not yet bound (mid-construction), or the backend lacks name.

Examples:

  • A backend-specific helper is reachable through the facade (live; skipped here):
    >>> from earthlens.earthlens import EarthLens
    >>> el = EarthLens(  # doctest: +SKIP
    ...     data_source="nwm",
    ...     dataset="chrtout",
    ...     variables=["streamflow"],
    ...     start="2024-01-01", end="2024-01-01",
    ... )
    >>> el._feature_ids()  # doctest: +SKIP
    
Source code in src/earthlens/earthlens.py
def __getattr__(self, name: str) -> Any:
    """Delegate an unknown attribute to the bound backend.

    Python calls this only when normal lookup misses, so the facade's
    own attributes and methods always take precedence. It lets the
    facade transparently expose a backend's *own* surface without
    forcing it onto every backend — e.g.
    `EarthLens(data_source="nwm", ...)._feature_ids()` forwards to the
    NWM backend, while the same call on a CHIRPS-backed facade raises
    `AttributeError` (CHIRPS has no such method).

    Args:
        name: The attribute being looked up.

    Returns:
        The corresponding attribute of `self.datasource`.

    Raises:
        AttributeError: If `name` is a dunder, the backend is not yet
            bound (mid-construction), or the backend lacks `name`.

    Examples:
        - A backend-specific helper is reachable through the facade
          (live; skipped here):
            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> el = EarthLens(  # doctest: +SKIP
            ...     data_source="nwm",
            ...     dataset="chrtout",
            ...     variables=["streamflow"],
            ...     start="2024-01-01", end="2024-01-01",
            ... )
            >>> el._feature_ids()  # doctest: +SKIP

            ```
    """
    if name.startswith("__") and name.endswith("__"):
        raise AttributeError(name)
    datasource = self.__dict__.get("datasource")
    if datasource is None:
        raise AttributeError(
            f"{type(self).__name__!r} object has no attribute {name!r}"
        )
    return getattr(datasource, name)

__init__(data_source='chc', variables=None, temporal_resolution='daily', start=None, end=None, path=None, lat_lim=None, lon_lim=None, fmt='%Y-%m-%d', aoi=None, buffer=None, dataset=None, cadence=None, time=None, **backend_kwargs) #

Resolve the backend and construct it with the user's parameters.

Validates data_source against :attr:DataSources, fills in whole-Earth defaults for missing lat_lim / lon_lim, and instantiates the concrete backend bound to self.datasource.

Parameters:

Name Type Description Default
data_source str

Backend key. One of the registered keys in :attr:DataSources"chc" (alias "chirps"), "climate-indices" (aliases "climate_indices" / "teleconnections"), "amazon-s3", "asf" (aliases "alaska-satellite-facility" / "insar"), "cmems", "earthdata", "ecmwf", "eumetsat", "fdsn", "firms", "gdacs", "gee" (alias "google-earth-engine"), "ghsl" (aliases "ghs" / "human-settlement"), "glaciers" (aliases "rgi" / "glims" / "wgms"), "hdx", "nrel" (aliases "nsrdb" / "wind-toolkit"), "nwp", "openaq", "openeo", "overture", "radar" (alias "nexrad"), "sentinel-hub" (alias "sentinelhub"), "pvgis" (alias "solar-pv"), "stac" (with endpoint aliases "planetary-computer" / "earth-search" / "cdse"), "tropycal", "usgs-water" (aliases "usgs-nwis" / "nwis"), "worldpop" (alias "world-pop"), "argo" (aliases "argo-floats" / "argopy"), or "admin" (aliases "admin-boundaries" / "geoboundaries" / "natural-earth" / "tiger"). See sorted(EarthLens.DataSources) for the live list. Defaults to "chc".

'chc'
temporal_resolution str

The download cadence — "daily" or "monthly" for most backends; the GEE backend also accepts "raw" and "yearly". Prefer the cadence= alias for the download-cadence backends (CHIRPS / S3 / ECMWF / GEE). The concrete backend may accept a narrower set; check its temporal_resolution handling. Note the meaning is backend-specific:

  • a download-loop cadence that spaces the per-step requests — CHIRPS, S3, ECMWF, GEE;
  • an advisory label only — NWP (the real cadence comes from each model's metadata);
  • a server-side rollup selector — OpenAQ (picks the measurements vs. hourly/daily endpoint);
  • a service selector — USGS Water (sub-daily maps to the instantaneous service);
  • ignored / forced to "all" for the snapshot backends with no per-step time axis — Overture, Tropycal, FDSN, FIRMS, GDACS, Radar.

For the first (download-cadence) group, cadence is the clearer spelling. Defaults to "daily".

'daily'
cadence str | None

Clearer alias for temporal_resolution in its download-cadence role (CHIRPS / S3 / ECMWF / GEE). When given, it overrides temporal_resolution. Defaults to None.

None
start str | datetime | date | None

Inclusive start date. A string (parsed with fmt, falling back to ISO-8601), or a datetime / date / pandas.Timestamp object. Defaults to None.

None
end str | datetime | date | None

Inclusive end date, same accepted types as start. Defaults to None.

None
time Any

A single time range, the ergonomic alternative to the start / end pair (STAC "a/b" / earthaccess (a, b) idiom). Accepts a "start/end" string, a (start, end) 2-sequence, a slice, or a single date (an instant). Splits into start / end; both bounds are required (an open-ended interval such as "2020-01-01/" raises), and passing it together with start / end raises ValueError. Defaults to None.

None
path Path | str | None

Output directory. Created by the backend if it does not exist. When omitted (None), defaults to ./earthlens-data/<data_source>/ rather than the current working directory; pass path="" to opt into the CWD.

None
dataset str | None

Explicit dataset / collection key, the ergonomic alternative to keying it into variables. When given with a plain variables list, the facade composes the backend's request for you — the S3 backend receives it as a native dataset argument, and the dataset-keyed backends (ECMWF, GEE, CHC, …) receive the composed {dataset: variables} dict. Passing dataset together with a dict variables raises ValueError for the dataset-keyed backends. Defaults to None (the legacy nested-dict variables call is unchanged).

None
variables dict[str, list[str]] | list[str] | None

Backend-specific variable specification. Shape depends on the backend:

  • ECMWF: dict[str, list[str]] mapping CDS dataset short name to a list of variable codes drawn from that dataset, e.g. {"reanalysis-era5-single-levels": ["2m-temperature"]}.
  • GEE: dict[str, list[str]] mapping an Earth Engine asset id to a list of band ids, e.g. {"UCSB-CHG/CHIRPS/DAILY": ["precipitation"]}.
  • CHIRPS: either list[str] of variable codes (legacy — auto-routed to the "global-daily" / "global-monthly" dataset key via temporal_resolution), or dict[str, list[str]] mapping a CHIRPS catalog dataset key (e.g. "africa-pentad", "chirps-v3-global-monthly") to a list of variable codes drawn from that dataset, e.g. {"africa-monthly": ["precipitation"]}. See Catalog().list_datasets() for the curated dataset keys.
  • S3 / ERA5: list[str] of variable codes from the S3 backend's catalog.

Defaults to None.

None
lat_lim list[float] | None

Legacy latitude pair [lat_min, lat_max] — prefer the single aoi= channel, which also accepts a bbox. Defaults to :data:DEFAULT_LATITUDE_LIMIT (whole Earth). Mutually exclusive with aoi.

None
lon_lim list[float] | None

Legacy longitude pair [lon_min, lon_max] — prefer the single aoi= channel. Defaults to :data:DEFAULT_LONGITUDE_LIMIT (whole Earth). Mutually exclusive with aoi.

None
fmt str

strptime format tried first when start / end are strings; a non-matching string falls back to an ISO-8601 parse, and datetime / date objects ignore it. An optional override rather than a requirement. Defaults to "%Y-%m-%d".

'%Y-%m-%d'
aoi Any

A single area-of-interest, the ergonomic alternative to the lat_lim / lon_lim pair. Accepts a bbox [min_lon, min_lat, max_lon, max_lat] (GeoJSON W, S, E, N order), a bbox mapping, a (lon, lat) point (with buffer), a shapely geometry, any __geo_interface__ object, a GeoJSON geometry / Feature, a WKT string, or a GeoDataFrame / GeoSeries. Reduced to lat_lim / lon_lim by :func:earthlens.base.spatial.normalize_aoi. Passing both aoi and lat_lim / lon_lim raises ValueError. Defaults to None.

None
buffer float | None

Half-width in degrees applied to a (lon, lat) point aoi to grow it into a square box. Only valid together with a point aoi. Defaults to None.

None
**backend_kwargs object

Extra keyword arguments forwarded verbatim to the chosen backend's constructor — for backend-specific options the facade does not name explicitly (e.g. ECMWF's skip_constraints, or GEE's scale / crs / reducer / export_via / drive_folder / gcs_bucket / region). Credentials are not constructor kwargs: backends that defer auth take them on authenticate() instead (e.g. GEE's service_account / service_key / project), so forwarding those through the facade raises TypeError. A kwarg the backend does not accept is its TypeError, not the facade's.

{}

Raises:

Type Description
ValueError

If data_source is not a key of :attr:DataSources, if both aoi and lat_lim / lon_lim are given, if buffer is given without a point aoi, or if aoi is malformed.

AuthenticationError

For backends that defer auth (ECMWF, GEE, STAC, CMEMS, …) the network handshake is lazy, so an auth failure surfaces on the first authenticate() / download() / search(), not at construction. GEE resolves and opens its Earth Engine connection lazily too: its offline precondition (no service_account + service_key / project and no matching environment variable) and its actual Earth Engine errors (invalid key, unregistered project) all surface on first use, not here.

ImportError

If the chosen backend's optional SDK is not installed (e.g. data_source="gee" without pip install earthlens[gee]).

Examples:

  • The DataSources registry resolves the backend class before construction. Inspect what each key points to:

    >>> from earthlens.earthlens import EarthLens
    >>> EarthLens.DataSources["chc"].__name__
    'CHIRPS'
    >>> EarthLens.DataSources["chirps"].__name__  # alias
    'CHIRPS'
    >>> EarthLens.DataSources["ecmwf"].__name__
    'ECMWF'
    >>> EarthLens.DataSources["gee"].__name__
    'GEE'
    
    - An unknown data_source is rejected before any backend code runs:

    >>> from earthlens.earthlens import EarthLens
    >>> EarthLens(  # doctest: +ELLIPSIS
    ...     variables=[], data_source="bogus"
    ... )
    Traceback (most recent call last):
        ...
    ValueError: 'bogus' is not a supported data source. ...
    
    - Construct an ECMWF-backed facade. Marked # doctest: +SKIP because it builds a real :class:cdsapi.Client, which requires ~/.cdsapirc:

    >>> from earthlens.earthlens import EarthLens
    >>> earthlens = EarthLens(  # doctest: +SKIP
    ...     data_source="ecmwf",
    ...     temporal_resolution="daily",
    ...     start="2022-01-01",
    ...     end="2022-01-01",
    ...     variables={
    ...         "reanalysis-era5-single-levels": ["2m-temperature"],
    ...     },
    ...     lat_lim=[4.0, 5.0],
    ...     lon_lim=[-75.0, -74.0],
    ...     path="examples/data/era5",
    ... )
    
See Also

:meth:download: Triggers the actual retrieval.

Source code in src/earthlens/earthlens.py
 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
def __init__(
    self,
    data_source: str = "chc",
    variables: dict[str, list[str]] | list[str] | None = None,
    temporal_resolution: str = "daily",
    start: str | datetime | date | None = None,
    end: str | datetime | date | None = None,
    path: Path | str | None = None,
    lat_lim: list[float] | None = None,
    lon_lim: list[float] | None = None,
    fmt: str = "%Y-%m-%d",
    aoi: Any = None,
    buffer: float | None = None,
    dataset: str | None = None,
    cadence: str | None = None,
    time: Any = None,
    **backend_kwargs: object,
):
    """Resolve the backend and construct it with the user's parameters.

    Validates `data_source` against :attr:`DataSources`, fills in
    whole-Earth defaults for missing `lat_lim` / `lon_lim`, and
    instantiates the concrete backend bound to `self.datasource`.

    Args:
        data_source: Backend key. One of the registered keys in
            :attr:`DataSources` — `"chc"` (alias `"chirps"`),
            `"climate-indices"` (aliases `"climate_indices"` /
            `"teleconnections"`),
            `"amazon-s3"`, `"asf"` (aliases
            `"alaska-satellite-facility"` / `"insar"`),
            `"cmems"`, `"earthdata"`, `"ecmwf"`,
            `"eumetsat"`, `"fdsn"`, `"firms"`, `"gdacs"`, `"gee"`
            (alias `"google-earth-engine"`), `"ghsl"` (aliases
            `"ghs"` / `"human-settlement"`), `"glaciers"` (aliases
            `"rgi"` / `"glims"` / `"wgms"`), `"hdx"`,
            `"nrel"` (aliases `"nsrdb"` / `"wind-toolkit"`), `"nwp"`,
            `"openaq"`, `"openeo"`, `"overture"`, `"radar"` (alias
            `"nexrad"`), `"sentinel-hub"` (alias `"sentinelhub"`),
            `"pvgis"` (alias `"solar-pv"`),
            `"stac"` (with endpoint aliases `"planetary-computer"` /
            `"earth-search"` / `"cdse"`), `"tropycal"`,
            `"usgs-water"` (aliases `"usgs-nwis"` / `"nwis"`),
            `"worldpop"` (alias `"world-pop"`), `"argo"` (aliases
            `"argo-floats"` / `"argopy"`), or `"admin"` (aliases
            `"admin-boundaries"` / `"geoboundaries"` /
            `"natural-earth"` / `"tiger"`). See
            `sorted(EarthLens.DataSources)` for the live list.
            Defaults to `"chc"`.
        temporal_resolution: The download cadence — `"daily"` or
            `"monthly"` for most backends; the GEE backend also accepts
            `"raw"` and `"yearly"`. Prefer the `cadence=` alias for the
            download-cadence backends (CHIRPS / S3 / ECMWF / GEE). The
            concrete backend may accept a narrower
            set; check its `temporal_resolution` handling. Note the
            meaning is backend-specific:

            * a **download-loop cadence** that spaces the per-step
              requests — CHIRPS, S3, ECMWF, GEE;
            * an **advisory label** only — NWP (the real cadence
              comes from each model's metadata);
            * a **server-side rollup selector** — OpenAQ (picks the
              measurements vs. hourly/daily endpoint);
            * a **service selector** — USGS Water (sub-daily maps to
              the instantaneous service);
            * **ignored / forced to `"all"`** for the snapshot
              backends with no per-step time axis — Overture,
              Tropycal, FDSN, FIRMS, GDACS, Radar.

            For the first (download-cadence) group, `cadence` is the
            clearer spelling. Defaults to `"daily"`.
        cadence: Clearer alias for `temporal_resolution` in its
            download-cadence role (CHIRPS / S3 / ECMWF / GEE). When
            given, it overrides `temporal_resolution`. Defaults to
            `None`.
        start: Inclusive start date. A string (parsed with `fmt`,
            falling back to ISO-8601), or a `datetime` / `date` /
            `pandas.Timestamp` object. Defaults to `None`.
        end: Inclusive end date, same accepted types as `start`.
            Defaults to `None`.
        time: A single time range, the ergonomic alternative to the
            `start` / `end` pair (STAC `"a/b"` / earthaccess `(a, b)`
            idiom). Accepts a `"start/end"` string, a `(start, end)`
            2-sequence, a `slice`, or a single date (an instant). Splits
            into `start` / `end`; both bounds are required (an
            open-ended interval such as `"2020-01-01/"` raises), and
            passing it together with `start` / `end` raises
            `ValueError`. Defaults to `None`.
        path: Output directory. Created by the backend if it does
            not exist. When omitted (`None`), defaults to
            `./earthlens-data/<data_source>/` rather than the current
            working directory; pass `path=""` to opt into the CWD.
        dataset: Explicit dataset / collection key, the ergonomic
            alternative to keying it into `variables`. When given
            with a plain `variables` list, the facade composes the
            backend's request for you — the S3 backend receives it
            as a native `dataset` argument, and the dataset-keyed
            backends (ECMWF, GEE, CHC, …) receive the composed
            `{dataset: variables}` dict. Passing `dataset` together
            with a dict `variables` raises `ValueError` for the
            dataset-keyed backends. Defaults to `None` (the legacy
            nested-dict `variables` call is unchanged).
        variables: Backend-specific variable specification.
            Shape depends on the backend:

            * ECMWF: `dict[str, list[str]]` mapping CDS dataset
              short name to a list of variable codes drawn from
              that dataset, e.g.
              `{"reanalysis-era5-single-levels": ["2m-temperature"]}`.
            * GEE: `dict[str, list[str]]` mapping an Earth Engine
              asset id to a list of band ids, e.g.
              `{"UCSB-CHG/CHIRPS/DAILY": ["precipitation"]}`.
            * CHIRPS: either `list[str]` of variable codes
              (legacy — auto-routed to the `"global-daily"` /
              `"global-monthly"` dataset key via
              `temporal_resolution`), or `dict[str, list[str]]`
              mapping a CHIRPS catalog dataset key (e.g.
              `"africa-pentad"`, `"chirps-v3-global-monthly"`)
              to a list of variable codes drawn from that
              dataset, e.g. `{"africa-monthly": ["precipitation"]}`.
              See `Catalog().list_datasets()` for the curated
              dataset keys.
            * S3 / ERA5: `list[str]` of variable codes from the
              S3 backend's catalog.

            Defaults to `None`.
        lat_lim: Legacy latitude pair `[lat_min, lat_max]` — prefer the
            single `aoi=` channel, which also accepts a bbox. Defaults to
            :data:`DEFAULT_LATITUDE_LIMIT` (whole Earth). Mutually
            exclusive with `aoi`.
        lon_lim: Legacy longitude pair `[lon_min, lon_max]` — prefer the
            single `aoi=` channel. Defaults to
            :data:`DEFAULT_LONGITUDE_LIMIT` (whole Earth). Mutually
            exclusive with `aoi`.
        fmt: `strptime` format tried first when `start` / `end` are
            strings; a non-matching string falls back to an ISO-8601
            parse, and `datetime` / `date` objects ignore it. An
            optional override rather than a requirement. Defaults to
            `"%Y-%m-%d"`.
        aoi: A single area-of-interest, the ergonomic alternative to
            the `lat_lim` / `lon_lim` pair. Accepts a bbox
            `[min_lon, min_lat, max_lon, max_lat]` (GeoJSON W, S, E,
            N order), a bbox mapping, a `(lon, lat)` point (with
            `buffer`), a shapely geometry, any `__geo_interface__`
            object, a GeoJSON geometry / Feature, a WKT string, or a
            `GeoDataFrame` / `GeoSeries`. Reduced to `lat_lim` /
            `lon_lim` by :func:`earthlens.base.spatial.normalize_aoi`.
            Passing both `aoi` and `lat_lim` / `lon_lim` raises
            `ValueError`. Defaults to `None`.
        buffer: Half-width in degrees applied to a `(lon, lat)` point
            `aoi` to grow it into a square box. Only valid together
            with a point `aoi`. Defaults to `None`.
        **backend_kwargs: Extra keyword arguments forwarded
            verbatim to the chosen backend's constructor — for
            backend-specific options the facade does not name
            explicitly (e.g. ECMWF's `skip_constraints`, or GEE's
            `scale` / `crs` / `reducer` / `export_via` /
            `drive_folder` / `gcs_bucket` / `region`). Credentials are
            not constructor kwargs: backends that defer auth take them
            on `authenticate()` instead (e.g. GEE's `service_account`
            / `service_key` / `project`), so forwarding those through
            the facade raises `TypeError`. A kwarg the backend does
            not accept is its `TypeError`, not the facade's.

    Raises:
        ValueError: If `data_source` is not a key of
            :attr:`DataSources`, if both `aoi` and
            `lat_lim` / `lon_lim` are given, if `buffer` is given
            without a point `aoi`, or if `aoi` is malformed.
        AuthenticationError: For backends that defer auth
            (ECMWF, GEE, STAC, CMEMS, …) the network handshake is
            lazy, so an auth failure surfaces on the first
            `authenticate()` / `download()` / `search()`, not at
            construction. GEE resolves and opens its Earth Engine
            connection lazily too: its *offline* precondition (no
            `service_account` + `service_key` / `project` and no
            matching environment variable) and its actual Earth
            Engine errors (invalid key, unregistered project) all
            surface on first use, not here.
        ImportError: If the chosen backend's optional SDK is not
            installed (e.g. `data_source="gee"` without
            `pip install earthlens[gee]`).

    Examples:
        - The DataSources registry resolves the backend class
          before construction. Inspect what each key points to:

            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> EarthLens.DataSources["chc"].__name__
            'CHIRPS'
            >>> EarthLens.DataSources["chirps"].__name__  # alias
            'CHIRPS'
            >>> EarthLens.DataSources["ecmwf"].__name__
            'ECMWF'
            >>> EarthLens.DataSources["gee"].__name__
            'GEE'

            ```
        - An unknown `data_source` is rejected before any backend
          code runs:

            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> EarthLens(  # doctest: +ELLIPSIS
            ...     variables=[], data_source="bogus"
            ... )
            Traceback (most recent call last):
                ...
            ValueError: 'bogus' is not a supported data source. ...

            ```
        - Construct an ECMWF-backed facade. Marked
          `# doctest: +SKIP` because it builds a real
          :class:`cdsapi.Client`, which requires
          `~/.cdsapirc`:

            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> earthlens = EarthLens(  # doctest: +SKIP
            ...     data_source="ecmwf",
            ...     temporal_resolution="daily",
            ...     start="2022-01-01",
            ...     end="2022-01-01",
            ...     variables={
            ...         "reanalysis-era5-single-levels": ["2m-temperature"],
            ...     },
            ...     lat_lim=[4.0, 5.0],
            ...     lon_lim=[-75.0, -74.0],
            ...     path="examples/data/era5",
            ... )

            ```

    See Also:
        :meth:`download`: Triggers the actual retrieval.
    """
    # Back-compat for the legacy positional order
    # `EarthLens(variables, data_source, ...)`. `data_source` is now
    # the first positional; a caller who passed `variables` first sends
    # a list / dict where a source key (a `str`) is expected, so detect
    # that and swap, with a deprecation warning. Runs before
    # `_check_source` so the (now-correct) key is the one validated.
    if not isinstance(data_source, str):
        warnings.warn(
            "EarthLens(variables, data_source, ...) is deprecated; pass "
            "data_source first: EarthLens(data_source, variables=...).",
            DeprecationWarning,
            stacklevel=2,
        )
        data_source, variables = (
            variables if isinstance(variables, str) else "chc",
            data_source,
        )
    self._check_source(data_source)

    # Most backends take a `variables` (or `dataset`) request axis. A few —
    # currently only CMIP6 — address their data purely by facet keywords
    # (`variable_id=`, `source_id=`, ...) and declare no `variables`
    # parameter; those neither require nor accept `variables=`/`dataset=`.
    # A backend is treated as facet-only *only* when its constructor
    # explicitly declares neither `variables` nor a catch-all `**kwargs`
    # (a `MagicMock` test double, or any pass-through signature, keeps the
    # historical variables-required behaviour).
    backend_cls = self.DataSources[data_source]
    backend_params = inspect.signature(backend_cls.__init__).parameters
    has_var_keyword = any(
        p.kind is inspect.Parameter.VAR_KEYWORD for p in backend_params.values()
    )
    requires_variables = "variables" in backend_params or has_var_keyword
    if requires_variables:
        if variables is None and dataset is None:
            raise ValueError(
                "variables= is required (or pass dataset= for a "
                "dataset-keyed backend), e.g. "
                "EarthLens('chc', variables=['precipitation'])."
            )
    elif variables is not None or dataset is not None:
        raise ValueError(
            f"the {data_source!r} backend addresses its data by facet "
            "keyword arguments (e.g. variable_id=, source_id=), not "
            "variables=/dataset=."
        )

    # `cadence=` is the clearer alias for the download-cadence role of
    # `temporal_resolution`; when given it simply overrides it.
    if cadence is not None:
        temporal_resolution = cadence

    # A single `time=` range supersedes the separate `start` / `end`
    # pair (STAC `"a/b"` / earthaccess `(a, b)` idiom). Split it into
    # the `start` / `end` the backend already consumes.
    if time is not None:
        if start is not None or end is not None:
            raise ValueError("pass either time= or start=/end=, not both")
        start, end = split_time(time)
        # An open-ended interval (`"2020-01-01/"`) would leave a `None`
        # bound that the backend silently expands to "now" — a surprise
        # multi-year span. Require both bounds explicitly.
        if start is None or end is None:
            raise ValueError(
                "time= needs both bounds; got an open-ended interval. "
                "Pass an explicit start and end (e.g. "
                "time='2020-01-01/2020-01-31')."
            )

    # A single `aoi=` supersedes the legacy `lat_lim` / `lon_lim`
    # pair. It accepts a bbox, a point (+ `buffer`), a shapely /
    # GeoJSON / WKT geometry, or a GeoDataFrame, and is reduced to
    # the `[min, max]` pairs every backend already consumes. A backend
    # that declares its own richer `aoi` parameter (e.g. WorldPop's
    # ISO3 / bbox / GeoDataFrame) instead receives `aoi` verbatim and
    # interprets it itself.
    clip_geometry = None
    if aoi is not None and "aoi" in backend_params:
        if buffer is not None:
            raise ValueError(
                f"buffer= is not supported by the {data_source!r} backend, "
                "which interprets aoi= itself"
            )
        backend_kwargs = {**backend_kwargs, "aoi": aoi}
    elif aoi is not None:
        if lat_lim is not None or lon_lim is not None:
            raise ValueError("pass either aoi= or lat_lim=/lon_lim=, not both")
        lat_lim, lon_lim, clip_geometry = resolve_aoi(aoi, buffer=buffer)
    elif buffer is not None:
        raise ValueError(
            "buffer= only applies to a point aoi=(lon, lat); pass aoi= too"
        )

    if lat_lim is None:
        lat_lim = DEFAULT_LATITUDE_LIMIT
    if lon_lim is None:
        lon_lim = DEFAULT_LONGITUDE_LIMIT

    # An omitted `path` makes earthlens manage the location: `download()`
    # persists to a named per-source subdirectory (`./earthlens-data/<source>/`)
    # rather than scattering files into the cwd, while `load()` (which only
    # needs the in-memory object) redirects to a throwaway temp dir and
    # removes the empty default afterwards. An explicit `path=""` still means
    # the CWD (a deliberate choice).
    self._explicit_path = path is not None
    if path is None:
        path = Path("earthlens-data") / data_source
        logger.info(
            f"No `path` given; download() writes {data_source!r} output under "
            f"{path}/ (load() uses a temp dir)."
        )

    # Per-key defaults (e.g. the STAC endpoint aliases pre-bind
    # `endpoint=`) are merged *under* the user's kwargs, so an
    # explicit value always wins.
    merged_kwargs = {
        **self.DataSources.default_kwargs(data_source),
        **backend_kwargs,
    }

    # Reject an unknown backend kwarg here, with a did-you-mean, rather
    # than letting it surface as a raw TypeError from deep in the
    # backend constructor.
    self._check_backend_kwargs(data_source, backend_params, merged_kwargs)

    # `dataset=` + a plain `variables` list is resolved into the
    # shape each backend wants — a native `dataset` kwarg for the S3
    # backend, or the legacy `{dataset: variables}` dict for the
    # dataset-keyed backends. With `dataset=None` this is a no-op.
    from earthlens.base._requests import normalize_dataset_variables

    request_kwargs = (
        normalize_dataset_variables(backend_cls, dataset, variables)
        if requires_variables
        else {}
    )

    self.datasource = backend_cls(
        start=start,
        end=end,
        lat_lim=lat_lim,
        lon_lim=lon_lim,
        temporal_resolution=temporal_resolution,
        path=path,
        fmt=fmt,
        **request_kwargs,
        **merged_kwargs,
    )
    # A polygon `aoi=` records its mask on the backend's spatial extent
    # so raster backends clip the fetched bbox to the exact shape.
    if clip_geometry is not None:
        self.datasource._attach_clip_geometry(clip_geometry)

authenticate(**credentials) #

Eagerly authenticate the bound backend; raise on failure.

The explicit, fail-fast counterpart to the lazy authentication that otherwise happens on the first :meth:download / search. Delegates to :meth:earthlens.base.AbstractDataSource.authenticate — opening the network client or running the credential step — and is a no-op for credential-free backends. Lets callers separate "do I have valid credentials?" from the download itself, e.g. wrap only authenticate() in a try/except AuthenticationError.

Any keyword arguments are forwarded verbatim to the backend's authenticate, so a backend that takes its credential there receives it — e.g. FIRMS accepts api_key= (falling back to the FIRMS_MAP_KEY environment variable when omitted). Passing a credential a backend does not accept raises TypeError.

Parameters:

Name Type Description Default
**credentials Any

Backend-specific credential keywords forwarded to the bound backend's authenticate (e.g. FIRMS's api_key). Empty for credential-free or env-resolved backends.

{}

Returns:

Type Description
EarthLens

The facade, so it chains:

EarthLens

EarthLens(...).authenticate().download().

Raises:

Type Description
AuthenticationError

If the backend cannot authenticate.

Examples:

  • Verify credentials up front, then download (live; skipped here):
    >>> from earthlens.earthlens import EarthLens
    >>> EarthLens(  # doctest: +SKIP
    ...     data_source="ecmwf",
    ...     dataset="reanalysis-era5-single-levels",
    ...     variables=["2m-temperature"],
    ...     start="2022-01-01", end="2022-01-01",
    ... ).authenticate().download()
    
  • Pass a FIRMS key explicitly at the auth step (live; skipped here):
    >>> from earthlens.earthlens import EarthLens
    >>> EarthLens(  # doctest: +SKIP
    ...     data_source="firms",
    ...     variables=["VIIRS_SNPP_NRT"],
    ...     start="2024-08-01", end="2024-08-01",
    ...     lat_lim=[33.0, 35.0], lon_lim=[-119.0, -117.0],
    ... ).authenticate(api_key="…").download()
    
Source code in src/earthlens/earthlens.py
def authenticate(self, **credentials: Any) -> EarthLens:
    """Eagerly authenticate the bound backend; raise on failure.

    The explicit, fail-fast counterpart to the lazy authentication
    that otherwise happens on the first :meth:`download` / `search`.
    Delegates to
    :meth:`earthlens.base.AbstractDataSource.authenticate` — opening
    the network client or running the credential step — and is a
    no-op for credential-free backends. Lets callers separate "do I
    have valid credentials?" from the download itself, e.g. wrap only
    `authenticate()` in a `try/except AuthenticationError`.

    Any keyword arguments are forwarded verbatim to the backend's
    `authenticate`, so a backend that takes its credential there
    receives it — e.g. FIRMS accepts `api_key=` (falling back to the
    `FIRMS_MAP_KEY` environment variable when omitted). Passing a
    credential a backend does not accept raises `TypeError`.

    Args:
        **credentials: Backend-specific credential keywords forwarded
            to the bound backend's `authenticate` (e.g. FIRMS's
            `api_key`). Empty for credential-free or env-resolved
            backends.

    Returns:
        The facade, so it chains:
        `EarthLens(...).authenticate().download()`.

    Raises:
        AuthenticationError: If the backend cannot authenticate.

    Examples:
        - Verify credentials up front, then download (live; skipped
          here):
            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> EarthLens(  # doctest: +SKIP
            ...     data_source="ecmwf",
            ...     dataset="reanalysis-era5-single-levels",
            ...     variables=["2m-temperature"],
            ...     start="2022-01-01", end="2022-01-01",
            ... ).authenticate().download()

            ```
        - Pass a FIRMS key explicitly at the auth step (live;
          skipped here):
            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> EarthLens(  # doctest: +SKIP
            ...     data_source="firms",
            ...     variables=["VIIRS_SNPP_NRT"],
            ...     start="2024-08-01", end="2024-08-01",
            ...     lat_lim=[33.0, 35.0], lon_lim=[-119.0, -117.0],
            ... ).authenticate(api_key="…").download()

            ```
    """
    self.datasource.authenticate(**credentials)
    return self

catalog(data_source) classmethod #

Return the dataset / variable catalog for a backend.

The catalogs hold the curated dataset and variable metadata (cadence, extent, bands) each backend ships, so they are the natural place to discover valid dataset= / variables= values without constructing the backend or hitting the network.

Parameters:

Name Type Description Default
data_source str

A registered backend key (see sorted(EarthLens.DataSources)).

required

Returns:

Type Description
AbstractCatalog

The backend's Catalog instance, loaded from its bundled

AbstractCatalog

data.

Raises:

Type Description
ValueError

If data_source is not a registered key.

ImportError

If the backend's optional SDK is required to import its module and is not installed.

NotImplementedError

If the backend ships no catalog.

Examples:

  • The CHC catalog exposes its curated datasets:
    >>> from earthlens.earthlens import EarthLens
    >>> catalog = EarthLens.catalog("chc")
    >>> len(catalog) > 0
    True
    
Source code in src/earthlens/earthlens.py
@classmethod
def catalog(cls, data_source: str) -> AbstractCatalog:
    """Return the dataset / variable catalog for a backend.

    The catalogs hold the curated dataset and variable metadata
    (cadence, extent, bands) each backend ships, so they are the
    natural place to discover valid `dataset=` / `variables=` values
    without constructing the backend or hitting the network.

    Args:
        data_source: A registered backend key (see
            `sorted(EarthLens.DataSources)`).

    Returns:
        The backend's `Catalog` instance, loaded from its bundled
        data.

    Raises:
        ValueError: If `data_source` is not a registered key.
        ImportError: If the backend's optional SDK is required to
            import its module and is not installed.
        NotImplementedError: If the backend ships no catalog.

    Examples:
        - The CHC catalog exposes its curated datasets:
            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> catalog = EarthLens.catalog("chc")
            >>> len(catalog) > 0
            True

            ```
    """
    cls._check_source(data_source)
    module_name, extras = next(
        (mod, extra)
        for key, mod, extra in cls.DataSources.entries()
        if key == data_source
    )
    try:
        module = importlib.import_module(module_name)
    except ImportError as exc:
        hint = f" Install with `pip install earthlens[{extras}]`." if extras else ""
        raise ImportError(
            f"Backend {data_source!r} catalog is unavailable — its "
            f"runtime dependency is not installed.{hint}"
        ) from exc
    catalog_cls = getattr(module, "Catalog", None)
    if catalog_cls is None:
        raise NotImplementedError(
            f"the {data_source!r} backend ships no catalog to query"
        )
    return catalog_cls()

count() #

Return how many products this request matches, without downloading.

Uses the backend's :meth:~earthlens.base.AbstractDataSource._count hook, which a backend with a cheap server-side total overrides; otherwise it counts a :meth:search.

Returns:

Type Description
int

The number of matching products.

Raises:

Type Description
NotImplementedError

If the bound backend exposes no searchable product list (see :meth:search).

Source code in src/earthlens/earthlens.py
def count(self) -> int:
    """Return how many products this request matches, without downloading.

    Uses the backend's :meth:`~earthlens.base.AbstractDataSource._count`
    hook, which a backend with a cheap server-side total overrides;
    otherwise it counts a :meth:`search`.

    Returns:
        The number of matching products.

    Raises:
        NotImplementedError: If the bound backend exposes no
            searchable product list (see :meth:`search`).
    """
    try:
        return self.datasource._count()
    except NotImplementedError as exc:
        raise NotImplementedError(
            f"the {type(self.datasource).__name__} backend does not "
            f"support search()/preview()/count(); call download() instead."
        ) from exc

describe_dataset(data_source, key) classmethod #

Return the catalog record for one dataset.

Parameters:

Name Type Description Default
data_source str

A registered backend key.

required
key str

A curated dataset key (see :meth:list_datasets).

required

Returns:

Type Description
Any

The backend-specific dataset record (carries the dataset's

Any

variables / bands, cadence, and extent).

Raises:

Type Description
ValueError

If data_source is unknown, or key is not a curated dataset (the message suggests the closest key).

Examples:

  • Inspect a CHC dataset's declared variables:
    >>> from earthlens.earthlens import EarthLens
    >>> dataset = EarthLens.describe_dataset("chc", "africa-monthly")
    >>> bool(dataset.variables)
    True
    
  • An unknown key is rejected with a did-you-mean hint:
    >>> from earthlens.earthlens import EarthLens
    >>> EarthLens.describe_dataset(  # doctest: +ELLIPSIS
    ...     "chc", "africa-month"
    ... )
    Traceback (most recent call last):
        ...
    ValueError: 'africa-month' is not in the ...
    
Source code in src/earthlens/earthlens.py
@classmethod
def describe_dataset(cls, data_source: str, key: str) -> Any:
    """Return the catalog record for one dataset.

    Args:
        data_source: A registered backend key.
        key: A curated dataset key (see :meth:`list_datasets`).

    Returns:
        The backend-specific dataset record (carries the dataset's
        variables / bands, cadence, and extent).

    Raises:
        ValueError: If `data_source` is unknown, or `key` is not a
            curated dataset (the message suggests the closest key).

    Examples:
        - Inspect a CHC dataset's declared variables:
            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> dataset = EarthLens.describe_dataset("chc", "africa-monthly")
            >>> bool(dataset.variables)
            True

            ```
        - An unknown key is rejected with a did-you-mean hint:
            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> EarthLens.describe_dataset(  # doctest: +ELLIPSIS
            ...     "chc", "africa-month"
            ... )
            Traceback (most recent call last):
                ...
            ValueError: 'africa-month' is not in the ...

            ```
    """
    return cls.catalog(data_source).get_dataset(key)

download(progress_bar=True, aggregate=None, *args, **kwargs) #

Delegate the download to the bound backend.

Forwards every argument verbatim to self.datasource.download. Each backend's download accepts its own backend-specific keyword arguments (for example, CHIRPS supports cores for parallel FTP retrieval), so unrecognised kwargs propagate through.

Parameters:

Name Type Description Default
progress_bar bool

Whether the backend should print a per-date progress bar during the loop. Defaults to True.

True
aggregate AggregationConfig | None

Optional :class:earthlens.aggregate.AggregationConfig. Forwarded to backends whose OUTPUT_KIND is "raster" or "mixed" — the two shapes for which a gridded reduction is well-defined. Backends declaring "vector" or "tabular" reject a non-None aggregate with NotImplementedError before the backend's download is called (the aggregator has no meaningful semantics on GeoDataFrame / DataFrame rows). A backend without an explicit OUTPUT_KIND attribute is treated as "raster" for back-compatibility.

None
*args object

Forwarded positionally to backend.download.

()
**kwargs object

Forwarded as keywords to backend.download.

{}

Returns:

Type Description
Any

Whatever the bound backend's download returns. The shape

Any

tracks the backend's OUTPUT_KIND:

Any
  • "raster" / "mixed" file-writers — the list of written paths (list[Path]); GEE may also return export destination strings / TaskInfo for async exports.
Any
  • "vector" — an in-memory FeatureCollection (e.g. FDSN, FIRMS, GDACS); radar returns a GeoDataFrame.
Any
  • "tabular" — a pandas.DataFrame (e.g. OpenAQ, USGS Water).
Any

The legacy CHIRPS / ECMWF backends return their written

Any

list[Path] and also leave the files on disk under path.

Raises:

Type Description
AuthenticationError

When the ECMWF backend cannot authenticate against CDS (typically a missing ~/.cdsapirc). See :class:earthlens.ecmwf.AuthenticationError.

KeyError

When any backend receives an unknown variable code that the catalog cannot resolve.

NotImplementedError

When aggregate= is not None and the bound backend's OUTPUT_KIND is "vector" or "tabular". The aggregator only handles gridded raster outputs; vector / tabular backends emit GeoDataFrame / DataFrame rows that have no meaningful gridded reduction.

Examples:

  • End-to-end CHIRPS download. Marked # doctest: +SKIP because it makes a live FTP connection:

    >>> from earthlens.earthlens import EarthLens
    >>> earthlens = EarthLens(  # doctest: +SKIP
    ...     data_source="chc",
    ...     start="2009-01-01",
    ...     end="2009-01-02",
    ...     variables=["precipitation"],
    ...     lat_lim=[4.19, 4.64],
    ...     lon_lim=[-75.65, -74.73],
    ...     path="examples/data/chirps",
    ... )
    >>> earthlens.download()  # doctest: +SKIP
    
    - ECMWF download via the facade. Marked # doctest: +SKIP because CDS requires ~/.cdsapirc and the request blocks for minutes while the queue serves it:

    >>> from earthlens.earthlens import EarthLens
    >>> earthlens = EarthLens(  # doctest: +SKIP
    ...     data_source="ecmwf",
    ...     start="2022-01-01",
    ...     end="2022-01-01",
    ...     variables={
    ...         "reanalysis-era5-single-levels": ["2m-temperature"],
    ...     },
    ...     lat_lim=[4.0, 5.0],
    ...     lon_lim=[-75.0, -74.0],
    ...     path="examples/data/era5",
    ... )
    >>> earthlens.download()  # doctest: +SKIP
    
See Also

:meth:earthlens.chc.CHIRPS.download: CHIRPS backend implementation, including the cores= keyword for parallel retrieval. :meth:earthlens.s3.S3.download: S3/ERA5 backend implementation. :meth:earthlens.ecmwf.ECMWF.download: ECMWF/CDS backend implementation. :meth:earthlens.gee.GEE.download: Google Earth Engine backend implementation (export_via, the 32768-px synchronous cap).

Source code in src/earthlens/earthlens.py
def download(
    self,
    progress_bar: bool = True,
    aggregate: AggregationConfig | None = None,
    *args: object,
    **kwargs: object,
) -> Any:
    """Delegate the download to the bound backend.

    Forwards every argument verbatim to `self.datasource.download`.
    Each backend's `download` accepts its own backend-specific
    keyword arguments (for example, CHIRPS supports `cores` for
    parallel FTP retrieval), so unrecognised kwargs propagate
    through.

    Args:
        progress_bar: Whether the backend should print a per-date
            progress bar during the loop. Defaults to `True`.
        aggregate: Optional :class:`earthlens.aggregate.AggregationConfig`.
            Forwarded to backends whose `OUTPUT_KIND` is
            `"raster"` or `"mixed"` — the two shapes for which
            a gridded reduction is well-defined. Backends
            declaring `"vector"` or `"tabular"` reject a
            non-`None` `aggregate` with `NotImplementedError`
            before the backend's `download` is called (the
            aggregator has no meaningful semantics on
            `GeoDataFrame` / `DataFrame` rows). A backend
            without an explicit `OUTPUT_KIND` attribute is
            treated as `"raster"` for back-compatibility.
        *args: Forwarded positionally to `backend.download`.
        **kwargs: Forwarded as keywords to `backend.download`.

    Returns:
        Whatever the bound backend's `download` returns. The shape
        tracks the backend's `OUTPUT_KIND`:

        * `"raster"` / `"mixed"` file-writers — the list of written
          paths (`list[Path]`); GEE may also return export
          destination strings / `TaskInfo` for async exports.
        * `"vector"` — an in-memory `FeatureCollection` (e.g. FDSN,
          FIRMS, GDACS); radar returns a `GeoDataFrame`.
        * `"tabular"` — a `pandas.DataFrame` (e.g. OpenAQ,
          USGS Water).

        The legacy CHIRPS / ECMWF backends return their written
        `list[Path]` and also leave the files on disk under `path`.

    Raises:
        AuthenticationError: When the ECMWF backend cannot
            authenticate against CDS (typically a missing
            `~/.cdsapirc`). See
            :class:`earthlens.ecmwf.AuthenticationError`.
        KeyError: When any backend receives an unknown variable
            code that the catalog cannot resolve.
        NotImplementedError: When `aggregate=` is not `None` and
            the bound backend's `OUTPUT_KIND` is `"vector"` or
            `"tabular"`. The aggregator only handles gridded
            raster outputs; vector / tabular backends emit
            `GeoDataFrame` / `DataFrame` rows that have no
            meaningful gridded reduction.

    Examples:
        - End-to-end CHIRPS download. Marked `# doctest: +SKIP`
          because it makes a live FTP connection:

            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> earthlens = EarthLens(  # doctest: +SKIP
            ...     data_source="chc",
            ...     start="2009-01-01",
            ...     end="2009-01-02",
            ...     variables=["precipitation"],
            ...     lat_lim=[4.19, 4.64],
            ...     lon_lim=[-75.65, -74.73],
            ...     path="examples/data/chirps",
            ... )
            >>> earthlens.download()  # doctest: +SKIP

            ```
        - ECMWF download via the facade. Marked
          `# doctest: +SKIP` because CDS requires
          `~/.cdsapirc` and the request blocks for minutes
          while the queue serves it:

            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> earthlens = EarthLens(  # doctest: +SKIP
            ...     data_source="ecmwf",
            ...     start="2022-01-01",
            ...     end="2022-01-01",
            ...     variables={
            ...         "reanalysis-era5-single-levels": ["2m-temperature"],
            ...     },
            ...     lat_lim=[4.0, 5.0],
            ...     lon_lim=[-75.0, -74.0],
            ...     path="examples/data/era5",
            ... )
            >>> earthlens.download()  # doctest: +SKIP

            ```

    See Also:
        :meth:`earthlens.chc.CHIRPS.download`: CHIRPS
            backend implementation, including the `cores=`
            keyword for parallel retrieval.
        :meth:`earthlens.s3.S3.download`: S3/ERA5 backend
            implementation.
        :meth:`earthlens.ecmwf.ECMWF.download`: ECMWF/CDS
            backend implementation.
        :meth:`earthlens.gee.GEE.download`: Google Earth Engine
            backend implementation (`export_via`, the 32768-px
            synchronous cap).
    """
    return self._dispatch_download(
        *args, progress_bar=progress_bar, aggregate=aggregate, **kwargs
    )

guess_dataset(data_source, text) classmethod #

Search a backend's datasets by free text.

A discovery aid in the spirit of eodag's guess_product_type: case-insensitive substring matches first (capped), falling back to difflib fuzzy matches when nothing contains text. Searches the full available_datasets universe plus the curated keys.

Parameters:

Name Type Description Default
data_source str

A registered backend key.

required
text str

The free-text fragment to search for.

required

Returns:

Type Description
list[str]

Matching dataset keys, best matches first (may be empty).

Raises:

Type Description
ValueError

If data_source is not a registered key.

Examples:

  • Find the CHC monthly datasets:
    >>> from earthlens.earthlens import EarthLens
    >>> "africa-monthly" in EarthLens.guess_dataset("chc", "monthly")
    True
    
Source code in src/earthlens/earthlens.py
@classmethod
def guess_dataset(cls, data_source: str, text: str) -> list[str]:
    """Search a backend's datasets by free text.

    A discovery aid in the spirit of eodag's `guess_product_type`:
    case-insensitive substring matches first (capped), falling back
    to `difflib` fuzzy matches when nothing contains `text`. Searches
    the full `available_datasets` universe plus the curated keys.

    Args:
        data_source: A registered backend key.
        text: The free-text fragment to search for.

    Returns:
        Matching dataset keys, best matches first (may be empty).

    Raises:
        ValueError: If `data_source` is not a registered key.

    Examples:
        - Find the CHC monthly datasets:
            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> "africa-monthly" in EarthLens.guess_dataset("chc", "monthly")
            True

            ```
    """
    cat = cls.catalog(data_source)
    pool = sorted(set(cat.available_datasets) | set(cat.datasets))
    lowered = text.lower()
    hits = [name for name in pool if lowered in name.lower()]
    if hits:
        return hits[:20]
    return difflib.get_close_matches(text, pool, n=10, cutoff=0.3)

list_datasets(data_source) classmethod #

List a backend's curated dataset keys.

Parameters:

Name Type Description Default
data_source str

A registered backend key.

required

Returns:

Type Description
list[str]

The sorted curated dataset keys — the values accepted by

list[str]

dataset= (and describe_dataset).

Raises:

Type Description
ValueError

If data_source is not a registered key.

Examples:

  • CHC ships a curated dataset for African monthly rainfall:
    >>> from earthlens.earthlens import EarthLens
    >>> "africa-monthly" in EarthLens.list_datasets("chc")
    True
    
Source code in src/earthlens/earthlens.py
@classmethod
def list_datasets(cls, data_source: str) -> list[str]:
    """List a backend's curated dataset keys.

    Args:
        data_source: A registered backend key.

    Returns:
        The sorted curated dataset keys — the values accepted by
        `dataset=` (and `describe_dataset`).

    Raises:
        ValueError: If `data_source` is not a registered key.

    Examples:
        - CHC ships a curated dataset for African monthly rainfall:
            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> "africa-monthly" in EarthLens.list_datasets("chc")
            True

            ```
    """
    return sorted(cls.catalog(data_source).datasets)

load(*args, **kwargs) #

Download and return the data in memory instead of only on disk.

The lazy-stack convenience: runs :meth:download and hands back the fetched data as the project's native pyramids objects rather than leaving the caller to re-open files. Raster outputs are read into a pyramids.Dataset / NetCDF (a .nc path becomes a NetCDF, every other raster a Dataset); a non-raster output a backend already returns in memory (a FeatureCollection / GeoDataFrame / DataFrame) is passed through unchanged, as are non-raster file paths (e.g. a .csv table from a mixed backend). The files are still written to pathload adds the in-memory handle on top.

When path was omitted, load writes to a throwaway temp directory (not the persistent ./earthlens-data/<source>/ that download uses), so a load-and-plot run never leaves files in the working tree — there is no need to pass path=tempfile.mkdtemp() yourself. Each returned raster is detached into an in-memory copy and the temp directory is removed immediately, so repeated load() calls — e.g. a per-year loop — do not accumulate gigabytes under the system temp dir. (Because the data is copied into memory, a path=-less load of a very large raster reads it fully into RAM; pass path= to keep the lazy, file-backed objects.)

xarray is intentionally not the return type: a returned pyramids.Dataset / NetCDF already exposes .to_xarray() for callers who want the climate-stack interop, so EarthLens stays free of an xarray dependency.

Parameters:

Name Type Description Default
*args object

Forwarded positionally to :meth:download.

()
**kwargs object

Forwarded as keywords to :meth:download.

{}

Returns:

Type Description
Any

For a raster / mixed backend, a list with each written raster read

Any

into a pyramids.Dataset / NetCDF (non-raster entries left as

Any

their Path); for a vector / tabular backend, the in-memory

Any

FeatureCollection / GeoDataFrame / DataFrame download

Any

returned.

Examples:

  • Load CHIRPS precipitation into pyramids Dataset objects (live; skipped here):
    >>> from earthlens.earthlens import EarthLens
    >>> rasters = EarthLens(  # doctest: +SKIP
    ...     "chc", variables=["precipitation"],
    ...     start="2020-01-01", end="2020-01-02", aoi=[-75, 4, -74, 5],
    ... ).load()
    >>> rasters[0].read_array()  # doctest: +SKIP
    
Source code in src/earthlens/earthlens.py
def load(self, *args: object, **kwargs: object) -> Any:
    """Download and return the data in memory instead of only on disk.

    The lazy-stack convenience: runs :meth:`download` and hands back the
    fetched data as the project's **native pyramids objects** rather than
    leaving the caller to re-open files. Raster outputs are read into a
    `pyramids.Dataset` / `NetCDF` (a `.nc` path becomes a `NetCDF`, every
    other raster a `Dataset`); a non-raster output a backend already
    returns in memory (a `FeatureCollection` / `GeoDataFrame` /
    `DataFrame`) is passed through unchanged, as are non-raster file paths
    (e.g. a `.csv` table from a mixed backend). The files are still written
    to `path` — `load` adds the in-memory handle on top.

    When `path` was omitted, `load` writes to a throwaway temp directory
    (not the persistent `./earthlens-data/<source>/` that `download` uses),
    so a load-and-plot run never leaves files in the working tree — there is
    no need to pass `path=tempfile.mkdtemp()` yourself. Each returned raster
    is detached into an in-memory copy and the temp directory is removed
    immediately, so repeated `load()` calls — e.g. a per-year loop — do not
    accumulate gigabytes under the system temp dir. (Because the data is
    copied into memory, a `path=`-less `load` of a very large raster reads it
    fully into RAM; pass `path=` to keep the lazy, file-backed objects.)

    `xarray` is intentionally not the return type: a returned
    `pyramids.Dataset` / `NetCDF` already exposes `.to_xarray()` for callers
    who want the climate-stack interop, so EarthLens stays free of an
    xarray dependency.

    Args:
        *args: Forwarded positionally to :meth:`download`.
        **kwargs: Forwarded as keywords to :meth:`download`.

    Returns:
        For a raster / mixed backend, a list with each written raster read
        into a `pyramids.Dataset` / `NetCDF` (non-raster entries left as
        their `Path`); for a vector / tabular backend, the in-memory
        `FeatureCollection` / `GeoDataFrame` / `DataFrame` `download`
        returned.

    Examples:
        - Load CHIRPS precipitation into pyramids `Dataset` objects
          (live; skipped here):
            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> rasters = EarthLens(  # doctest: +SKIP
            ...     "chc", variables=["precipitation"],
            ...     start="2020-01-01", end="2020-01-02", aoi=[-75, 4, -74, 5],
            ... ).load()
            >>> rasters[0].read_array()  # doctest: +SKIP

            ```
    """
    if self._explicit_path:
        return _load_result(self._dispatch_download(*args, **kwargs))
    self._redirect_output_to_tempdir()
    temp_dir = self.datasource.path
    result = _load_result(self._dispatch_download(*args, **kwargs))
    return _detach_and_cleanup(temp_dir, result)

options_for(data_source) classmethod #

List a backend's extra constructor options.

The backend-specific keyword arguments a backend accepts beyond the facade's own parameters — the discoverable surface for **backend_kwargs (e.g. GEE's scale / crs / service_account, ECMWF's skip_constraints).

Parameters:

Name Type Description Default
data_source str

A registered backend key.

required

Returns:

Type Description
list[str]

The sorted backend-specific option names.

Raises:

Type Description
ValueError

If data_source is not a registered key.

Examples:

  • GEE exposes its export knobs as options:
    >>> from earthlens.earthlens import EarthLens
    >>> options = EarthLens.options_for("gee")
    >>> "scale" in options and "crs" in options
    True
    
Source code in src/earthlens/earthlens.py
@classmethod
def options_for(cls, data_source: str) -> list[str]:
    """List a backend's extra constructor options.

    The backend-specific keyword arguments a backend accepts beyond
    the facade's own parameters — the discoverable surface for
    `**backend_kwargs` (e.g. GEE's `scale` / `crs` / `service_account`,
    ECMWF's `skip_constraints`).

    Args:
        data_source: A registered backend key.

    Returns:
        The sorted backend-specific option names.

    Raises:
        ValueError: If `data_source` is not a registered key.

    Examples:
        - GEE exposes its export knobs as options:
            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> options = EarthLens.options_for("gee")
            >>> "scale" in options and "crs" in options
            True

            ```
    """
    cls._check_source(data_source)
    params = inspect.signature(cls.DataSources[data_source].__init__).parameters
    return sorted(
        name
        for name, parameter in params.items()
        if name not in cls._FACADE_PARAMS
        and parameter.kind not in (parameter.VAR_KEYWORD, parameter.VAR_POSITIONAL)
    )

preview(n=10) #

Return the first n matching products as plain dicts.

A notebook-friendly view over :meth:search: each product is flattened to {"id": ..., "href": ..., **metadata} for quick tabular display before committing to a download.

Parameters:

Name Type Description Default
n int

Maximum number of products to return. Defaults to 10.

10

Returns:

Type Description
list[dict[str, Any]]

Up to n dicts, each carrying the product id, href, and

list[dict[str, Any]]

its backend-specific metadata.

Raises:

Type Description
NotImplementedError

If the bound backend exposes no searchable product list (see :meth:search).

Source code in src/earthlens/earthlens.py
def preview(self, n: int = 10) -> list[dict[str, Any]]:
    """Return the first `n` matching products as plain dicts.

    A notebook-friendly view over :meth:`search`: each product is
    flattened to `{"id": ..., "href": ..., **metadata}` for quick
    tabular display before committing to a download.

    Args:
        n: Maximum number of products to return. Defaults to 10.

    Returns:
        Up to `n` dicts, each carrying the product `id`, `href`, and
        its backend-specific metadata.

    Raises:
        NotImplementedError: If the bound backend exposes no
            searchable product list (see :meth:`search`).
    """
    return [
        {"id": product.id, "href": product.href, **product.metadata}
        for product in self.search()[:n]
    ]

search() #

List the products this request matches, without downloading them.

The cheap, dry-run half of the search→fetch split: it queries the backend's catalog and returns one :class:~earthlens.base.RemoteProduct per item that :meth:download would fetch, so you can inspect or filter the result first.

Returns:

Name Type Description
One list[RemoteProduct]

class:~earthlens.base.RemoteProduct per matching item;

list[RemoteProduct]

the empty list when nothing matches.

Raises:

Type Description
NotImplementedError

If the bound backend keeps the legacy _api-only flow (CHIRPS, S3, ECMWF, GEE) and exposes no searchable product list — call :meth:download directly.

Examples:

  • Preview a STAC search without fetching any bytes (live; skipped here):
    >>> from earthlens.earthlens import EarthLens
    >>> products = EarthLens(  # doctest: +SKIP
    ...     data_source="earth-search",
    ...     dataset="sentinel-2-l2a",
    ...     variables=["red"],
    ...     start="2024-01-01", end="2024-01-31",
    ...     aoi=[-75.0, 4.0, -74.0, 5.0],
    ... ).search()
    
Source code in src/earthlens/earthlens.py
def search(self) -> list[RemoteProduct]:
    """List the products this request matches, without downloading them.

    The cheap, dry-run half of the search→fetch split: it queries the
    backend's catalog and returns one
    :class:`~earthlens.base.RemoteProduct` per item that
    :meth:`download` would fetch, so you can inspect or filter the
    result first.

    Returns:
        One :class:`~earthlens.base.RemoteProduct` per matching item;
        the empty list when nothing matches.

    Raises:
        NotImplementedError: If the bound backend keeps the legacy
            `_api`-only flow (CHIRPS, S3, ECMWF, GEE) and exposes no
            searchable product list — call :meth:`download` directly.

    Examples:
        - Preview a STAC search without fetching any bytes (live;
          skipped here):
            ```python
            >>> from earthlens.earthlens import EarthLens
            >>> products = EarthLens(  # doctest: +SKIP
            ...     data_source="earth-search",
            ...     dataset="sentinel-2-l2a",
            ...     variables=["red"],
            ...     start="2024-01-01", end="2024-01-31",
            ...     aoi=[-75.0, 4.0, -74.0, 5.0],
            ... ).search()

            ```
    """
    try:
        return self.datasource._search()
    except NotImplementedError as exc:
        raise NotImplementedError(
            f"the {type(self.datasource).__name__} backend does not "
            f"support search()/preview()/count(); call download() instead."
        ) from exc