Skip to content

WorldPop — API reference#

WorldPop open population data hub source subpackage — earthlens.worldpop. Background, usage, the available product/sub-alias matrix, and the optional WorldPopPy path are covered under the other pages in this section; this page is the rendered API.

earthlens.worldpop #

WorldPop backend — open population data hub over anonymous HTTPS.

earthlens.worldpop wraps the WorldPop open population data hub (hub.worldpop.org): global gridded population counts, density, age/sex structures, births, pregnancies, dependency ratios, urban change, built-settlement growth, and forward projections — per country (ISO3) and as global mosaics, at 100 m / 1 km, in constrained and unconstrained variants. A request is an AOI (ISO3 / bbox / GeoDataFrame) + time window + a list of WorldPop product aliases; the backend queries the WorldPop REST API for the matching GeoTIFF URLs, downloads them over anonymous HTTPS, and uses pyramids to mosaic + crop to the AOI — writing population GeoTIFFs and, for demographic products, a tidy age/sex table. OUTPUT_KIND="mixed".

The provider is open + CC-BY-4.0, so WorldPopAuth is a no-op kept for conformance with the package's AbstractAuth shape. The default REST path needs only the core dependencies; the optional WorldPopPy path imports worldpoppy lazily (consuming only its file cache, never its xarray return), so the package imports without the [worldpop] extra.

AuthenticationError #

Bases: Exception

Raised when a backend cannot establish an authenticated session.

Subclasses re-raise this with backend-specific context (missing ~/.cdsapirc, unregistered Earth Engine project, expired CDSE token, missing Earthdata Login). Every backend's auth class catches the underlying SDK / HTTP exception and wraps it with an actionable message — never propagates a raw cdsapi.api.Exception or ee.EEException to the user.

The class is intentionally a flat Exception subclass and not ConnectionError because half the failure modes are not network errors (no credentials at all, malformed key file, misconfigured project IAM). Callers should catch AuthenticationError directly rather than its causes.

Examples:

  • The error preserves its constructor message:
    >>> from earthlens.base import AuthenticationError
    >>> exc = AuthenticationError("missing ~/.cdsapirc")
    >>> str(exc)
    'missing ~/.cdsapirc'
    
  • Catch every backend's auth failure with one clause:
    >>> from earthlens.base import AuthenticationError
    >>> try:
    ...     raise AuthenticationError("token expired")
    ... except AuthenticationError as exc:
    ...     handled = str(exc)
    >>> handled
    'token expired'
    
Source code in src/earthlens/base/auth.py
class AuthenticationError(Exception):
    """Raised when a backend cannot establish an authenticated session.

    Subclasses re-raise this with backend-specific context (missing
    `~/.cdsapirc`, unregistered Earth Engine project, expired CDSE
    token, missing Earthdata Login). Every backend's auth class
    catches the underlying SDK / HTTP exception and wraps it with
    an actionable message — never propagates a raw
    `cdsapi.api.Exception` or `ee.EEException` to the user.

    The class is intentionally a flat `Exception` subclass and not
    `ConnectionError` because half the failure modes are not
    network errors (no credentials at all, malformed key file,
    misconfigured project IAM). Callers should catch
    `AuthenticationError` directly rather than its causes.

    Examples:
        - The error preserves its constructor message:
            ```python
            >>> from earthlens.base import AuthenticationError
            >>> exc = AuthenticationError("missing ~/.cdsapirc")
            >>> str(exc)
            'missing ~/.cdsapirc'

            ```
        - Catch every backend's auth failure with one clause:
            ```python
            >>> from earthlens.base import AuthenticationError
            >>> try:
            ...     raise AuthenticationError("token expired")
            ... except AuthenticationError as exc:
            ...     handled = str(exc)
            >>> handled
            'token expired'

            ```
    """

Catalog #

Bases: AbstractCatalog

Product / sub-alias availability catalog for the WorldPop backend.

Reads the bundled worldpop_data_catalog.yaml and exposes its products: block as a map of Product rows keyed by canonical alias under the inherited datasets field (giving cat["pop"], "pop" in cat, len(cat), and the did-you-mean error for free). Instantiate with no arguments (Catalog()); model_post_init loads and validates the YAML.

Attributes:

Name Type Description
datasets dict[str, Product]

Map from canonical product alias to its Product row.

available_datasets list[str]

Every curated product alias, sorted.

Source code in src/earthlens/worldpop/catalog.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
class Catalog(AbstractCatalog):
    """Product / sub-alias availability catalog for the WorldPop backend.

    Reads the bundled `worldpop_data_catalog.yaml` and exposes its
    `products:` block as a map of `Product` rows keyed by canonical alias
    under the inherited `datasets` field (giving `cat["pop"]`, `"pop" in
    cat`, `len(cat)`, and the did-you-mean error for free). Instantiate
    with no arguments (`Catalog()`); `model_post_init` loads and validates
    the YAML.

    Attributes:
        datasets: Map from canonical product alias to its `Product` row.
        available_datasets: Every curated product alias, sorted.
    """

    _catalog_kind: str = "WorldPop product catalog"
    #: Plural noun for the did-you-mean message ("Known products: …"); the
    #: shared AbstractCatalog reads this (its entries are products, not
    #: "datasets").
    _entry_noun: str = "products"

    datasets: dict[str, Product] = Field(default_factory=dict)

    def model_post_init(self, __context: Any) -> None:
        """Auto-load the bundled catalog when no products were supplied.

        `Catalog()` with no args reads `CATALOG_PATH`; passing
        `datasets=...` skips the disk read (used in tests).

        Raises:
            ValueError: Propagated from `load` when the YAML is missing,
                empty, or has a malformed product row.
        """
        if not self.datasets:
            self.datasets = dict(_load_products(CATALOG_PATH))
        if not self.available_datasets:
            self.available_datasets = sorted(self.datasets)
        self._index_aliases()

    def _index_aliases(self) -> None:
        """Build the alias → canonical-alias lookup from the loaded rows."""
        index: dict[str, str] = {}
        for alias, product in self.datasets.items():
            index[alias.lower()] = alias
            for friendly in product.friendly:
                index[friendly.lower()] = alias
        object.__setattr__(self, "_alias_index", index)

    @classmethod
    def load(cls, catalog_path: Path | None = None) -> Catalog:
        """Read the WorldPop product catalog from disk.

        Args:
            catalog_path: Path to the catalog YAML. Defaults to the
                module-level `CATALOG_PATH`.

        Returns:
            A fully-populated `Catalog` with `datasets` and the
            `available_datasets` index set.

        Raises:
            ValueError: If the file has no `products:` block, or a row
                fails `Product` validation.
        """
        catalog_path = catalog_path if catalog_path is not None else CATALOG_PATH
        products = _load_products(catalog_path)
        return cls(datasets=dict(products), available_datasets=sorted(products))

    def get_catalog(self) -> dict[str, Product]:
        """Return the product map (satisfies the abstract contract)."""
        return self.datasets

    def get(self, alias: str) -> Product:
        """Return the `Product` for a canonical alias, did-you-mean on miss.

        Args:
            alias: A canonical product alias (`"pop"`).

        Returns:
            Product: The matching row.

        Raises:
            ValueError: If `alias` is not a curated product.
        """
        return self.get_dataset(alias)

    def resolve(self, key: str) -> str:
        """Resolve a product key or friendly alias to its canonical alias.

        Args:
            key: A canonical alias (`"pop"`) or a friendly alias
                (`"population"`, case-insensitive).

        Returns:
            str: The canonical product alias.

        Raises:
            ValueError: If `key` matches no product or alias; the message
                lists the known products with a did-you-mean hint.

        Examples:
            - A friendly alias and a canonical key both resolve:
                ```python
                >>> from earthlens.worldpop import Catalog
                >>> cat = Catalog()
                >>> cat.resolve("population")
                'pop'
                >>> cat.resolve("pop")
                'pop'

                ```
        """
        index: dict[str, str] = getattr(self, "_alias_index", {})
        canonical = index.get(key.lower())
        if canonical is not None:
            return canonical
        close = difflib.get_close_matches(key.lower(), index, n=1)
        hint = f" Did you mean {index[close[0]]!r}?" if close else ""
        raise ValueError(
            f"{key!r} is not a known WorldPop product or alias. "
            f"Known products: {sorted(self.datasets)}.{hint}"
        )

    def available_products(self) -> list[str]:
        """Return the curated product aliases, sorted."""
        return sorted(self.datasets)

    def pick_subalias(
        self,
        product: str,
        *,
        constrained: bool = False,
        unadjusted: bool = True,
        resolution: str = "100m",
        scope: str = "countries",
        generation: str = "R2021",
        level: str = "national",
    ) -> str:
        """Resolve the selector kwargs to a single REST sub-alias id.

        A product with exactly one sub-alias (`births`, `urban_change`, …)
        returns it directly — the selector kwargs do not apply, since there
        is only one variant. As a guard against a silently-ignored request,
        a `resolution` that differs from the sole sub-alias's resolution
        emits a `UserWarning` (the other selectors are product-intrinsic for
        single-variant products and are not warned on). Otherwise the kwargs
        must match one sub-alias's
        `(constrained, unadjusted, resolution, scope, generation, level)`
        tuple exactly.

        Args:
            product: A product key or alias (resolved first).
            constrained: Settlement-masked variant (`True`) vs
                unconstrained (`False`).
            unadjusted: Raw (`True`) vs UN-adjusted (`False`).
            resolution: `"100m"` or `"1km"`.
            scope: `"countries"` or `"global"`.
            generation: One of `GENERATIONS`.
            level: `"national"` or `"subnational"` (only `pwd` differs).

        Returns:
            str: The matching sub-alias id (e.g. `"wpgp"`).

        Raises:
            ValueError: If no sub-alias matches the selector; the message
                lists the product's available sub-alias tuples.

        Examples:
            - The classic unconstrained 100 m country series resolves to `wpgp`:
                ```python
                >>> from earthlens.worldpop import Catalog
                >>> Catalog().pick_subalias("pop")
                'wpgp'

                ```
        """
        code = self.resolve(product)
        row = self.datasets[code]
        if len(row.subaliases) == 1:
            only = row.subaliases[0]
            if resolution != only.resolution:
                warnings.warn(
                    f"{code!r} offers only the {only.resolution!r} sub-alias "
                    f"{only.id!r}; the requested resolution={resolution!r} is "
                    "ignored.",
                    UserWarning,
                    stacklevel=2,
                )
            return only.id
        want = (constrained, unadjusted, resolution, scope, generation, level)
        for sub in row.subaliases:
            if sub.selector() == want:
                return sub.id
        options = "\n".join(
            f"  - id={s.id!r} constrained={s.constrained} "
            f"unadjusted={s.unadjusted} resolution={s.resolution!r} "
            f"scope={s.scope!r} generation={s.generation!r} level={s.level!r}"
            for s in row.subaliases
        )
        raise ValueError(
            f"{code!r} has no variant for constrained={constrained}, "
            f"unadjusted={unadjusted}, resolution={resolution!r}, scope={scope!r}, "
            f"generation={generation!r}, level={level!r}. "
            f"Available sub-aliases:\n{options}"
        )

    def subalias(self, product: str, subalias_id: str) -> SubAlias:
        """Return the `SubAlias` row of a product by its REST id.

        Args:
            product: A product key or alias (resolved first).
            subalias_id: A sub-alias id belonging to that product.

        Returns:
            SubAlias: The matching sub-alias row.

        Raises:
            ValueError: If `product` is unknown or has no such sub-alias.

        Examples:
            - Look up a sub-alias and read its scope / resolution:
                ```python
                >>> from earthlens.worldpop import Catalog
                >>> sub = Catalog().subalias("pop", "wpgp")
                >>> sub.scope
                'countries'
                >>> sub.resolution
                '100m'

                ```
        """
        code = self.resolve(product)
        for sub in self.datasets[code].subaliases:
            if sub.id == subalias_id:
                return sub
        raise ValueError(
            f"{code!r} has no sub-alias {subalias_id!r}; "
            f"have {[s.id for s in self.datasets[code].subaliases]}."
        )

    def validate(
        self,
        product: str,
        *,
        constrained: bool = False,
        unadjusted: bool = True,
        resolution: str = "100m",
        scope: str = "countries",
        generation: str = "R2021",
        level: str = "national",
        year: int | None = None,
    ) -> tuple[str, str]:
        """Validate a full request and return `(product, subalias_id)`.

        Resolves the product, picks the sub-alias from the selectors, and —
        when `year` is given — checks the sub-alias offers it.

        Args:
            product: A product key or alias.
            constrained: See `pick_subalias`.
            unadjusted: See `pick_subalias`.
            resolution: See `pick_subalias`.
            scope: See `pick_subalias`.
            generation: See `pick_subalias`.
            level: See `pick_subalias`.
            year: Optional year to check against the sub-alias's `years`.

        Returns:
            tuple[str, str]: The canonical `(product, subalias_id)`.

        Raises:
            ValueError: If the selector matches no sub-alias, or `year` is
                outside the sub-alias's available years.
        """
        code = self.resolve(product)
        subalias_id = self.pick_subalias(
            code,
            constrained=constrained,
            unadjusted=unadjusted,
            resolution=resolution,
            scope=scope,
            generation=generation,
            level=level,
        )
        if year is not None:
            sub = next(s for s in self.datasets[code].subaliases if s.id == subalias_id)
            years = sub.years_set()
            if year not in years:
                raise ValueError(
                    f"{code}/{subalias_id} does not offer year {year}; "
                    f"available years: {sorted(years)}."
                )
        return code, subalias_id

    def describe(self, product: str) -> dict[str, Any]:
        """Return a structured introspection record for a product.

        Mirrors `earthlens.ecmwf.Catalog.describe` / the tropycal catalog: a
        runtime "what does product X expose?" helper a CLI / notebook can
        dump without walking the YAML.

        Args:
            product: A product key or friendly alias (resolved first).

        Returns:
            dict[str, Any]: Keys `product` (canonical alias), `friendly`,
            `kind`, `demographic`, `unit`, and `subaliases` (a list of
            per-variant dicts with `id` / `constrained` / `unadjusted` /
            `resolution` / `scope` / `generation` / `level` / `years`).

        Raises:
            ValueError: If `product` is not a curated product.

        Examples:
            - Describe the population product at a glance:
                ```python
                >>> from earthlens.worldpop import Catalog
                >>> info = Catalog().describe("population")
                >>> info["product"]
                'pop'
                >>> info["kind"]
                'raster'
                >>> info["subaliases"][0]["id"]
                'wpgp'

                ```
        """
        code = self.resolve(product)
        row = self.datasets[code]
        return {
            "product": code,
            "friendly": list(row.friendly),
            "kind": row.kind,
            "demographic": row.demographic,
            "unit": row.unit,
            "description": row.description,
            "endpoint": row.endpoint(),
            "subaliases": [
                {
                    "id": sub.id,
                    "constrained": sub.constrained,
                    "unadjusted": sub.unadjusted,
                    "resolution": sub.resolution,
                    "scope": sub.scope,
                    "generation": sub.generation,
                    "level": sub.level,
                    "years": sub.years,
                }
                for sub in row.subaliases
            ],
        }

    def health(self) -> dict[str, list[str]]:
        """Report structural hygiene issues across the loaded catalog.

        Mirrors `earthlens.ecmwf.Catalog.health` / `earthlens.gee.Catalog.health`:
        returns a mapping `check_name -> sorted list of offenders`. An empty
        list means the check passes. Schema-level invariants (duplicate keys,
        unknown fields) are already enforced at load time — these are the
        residual data-quality checks the pydantic schema cannot express.

        Checks reported:

        * `product_without_subaliases` — products carrying zero sub-aliases.
        * `demographic_not_mixed` — products flagged `demographic` whose
          `kind` is not `"mixed"`.
        * `subalias_unknown_generation` — `"<product>:<id>"` whose
          `generation` is not in `GENERATIONS`.
        * `subalias_bad_years` — `"<product>:<id>"` whose `years` spec does
          not parse.

        Returns:
            dict[str, list[str]]: The per-check offender lists.

        Examples:
            - The bundled catalog is clean:
                ```python
                >>> from earthlens.worldpop import Catalog
                >>> Catalog().health()
                {'product_without_subaliases': [], 'demographic_not_mixed': [], 'subalias_unknown_generation': [], 'subalias_bad_years': []}

                ```
        """
        no_subaliases: list[str] = []
        demographic_not_mixed: list[str] = []
        unknown_generation: list[str] = []
        bad_years: list[str] = []
        for alias, product in self.datasets.items():
            if not product.subaliases:
                no_subaliases.append(alias)
            if product.demographic and product.kind != "mixed":
                demographic_not_mixed.append(alias)
            for sub in product.subaliases:
                if sub.generation not in GENERATIONS:
                    unknown_generation.append(f"{alias}:{sub.id}")
                try:
                    sub.years_set()
                except ValueError:
                    bad_years.append(f"{alias}:{sub.id}")
        return {
            "product_without_subaliases": sorted(no_subaliases),
            "demographic_not_mixed": sorted(demographic_not_mixed),
            "subalias_unknown_generation": sorted(unknown_generation),
            "subalias_bad_years": sorted(bad_years),
        }

available_products() #

Return the curated product aliases, sorted.

Source code in src/earthlens/worldpop/catalog.py
def available_products(self) -> list[str]:
    """Return the curated product aliases, sorted."""
    return sorted(self.datasets)

describe(product) #

Return a structured introspection record for a product.

Mirrors earthlens.ecmwf.Catalog.describe / the tropycal catalog: a runtime "what does product X expose?" helper a CLI / notebook can dump without walking the YAML.

Parameters:

Name Type Description Default
product str

A product key or friendly alias (resolved first).

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Keys product (canonical alias), friendly,

dict[str, Any]

kind, demographic, unit, and subaliases (a list of

dict[str, Any]

per-variant dicts with id / constrained / unadjusted /

dict[str, Any]

resolution / scope / generation / level / years).

Raises:

Type Description
ValueError

If product is not a curated product.

Examples:

  • Describe the population product at a glance:
    >>> from earthlens.worldpop import Catalog
    >>> info = Catalog().describe("population")
    >>> info["product"]
    'pop'
    >>> info["kind"]
    'raster'
    >>> info["subaliases"][0]["id"]
    'wpgp'
    
Source code in src/earthlens/worldpop/catalog.py
def describe(self, product: str) -> dict[str, Any]:
    """Return a structured introspection record for a product.

    Mirrors `earthlens.ecmwf.Catalog.describe` / the tropycal catalog: a
    runtime "what does product X expose?" helper a CLI / notebook can
    dump without walking the YAML.

    Args:
        product: A product key or friendly alias (resolved first).

    Returns:
        dict[str, Any]: Keys `product` (canonical alias), `friendly`,
        `kind`, `demographic`, `unit`, and `subaliases` (a list of
        per-variant dicts with `id` / `constrained` / `unadjusted` /
        `resolution` / `scope` / `generation` / `level` / `years`).

    Raises:
        ValueError: If `product` is not a curated product.

    Examples:
        - Describe the population product at a glance:
            ```python
            >>> from earthlens.worldpop import Catalog
            >>> info = Catalog().describe("population")
            >>> info["product"]
            'pop'
            >>> info["kind"]
            'raster'
            >>> info["subaliases"][0]["id"]
            'wpgp'

            ```
    """
    code = self.resolve(product)
    row = self.datasets[code]
    return {
        "product": code,
        "friendly": list(row.friendly),
        "kind": row.kind,
        "demographic": row.demographic,
        "unit": row.unit,
        "description": row.description,
        "endpoint": row.endpoint(),
        "subaliases": [
            {
                "id": sub.id,
                "constrained": sub.constrained,
                "unadjusted": sub.unadjusted,
                "resolution": sub.resolution,
                "scope": sub.scope,
                "generation": sub.generation,
                "level": sub.level,
                "years": sub.years,
            }
            for sub in row.subaliases
        ],
    }

get(alias) #

Return the Product for a canonical alias, did-you-mean on miss.

Parameters:

Name Type Description Default
alias str

A canonical product alias ("pop").

required

Returns:

Name Type Description
Product Product

The matching row.

Raises:

Type Description
ValueError

If alias is not a curated product.

Source code in src/earthlens/worldpop/catalog.py
def get(self, alias: str) -> Product:
    """Return the `Product` for a canonical alias, did-you-mean on miss.

    Args:
        alias: A canonical product alias (`"pop"`).

    Returns:
        Product: The matching row.

    Raises:
        ValueError: If `alias` is not a curated product.
    """
    return self.get_dataset(alias)

get_catalog() #

Return the product map (satisfies the abstract contract).

Source code in src/earthlens/worldpop/catalog.py
def get_catalog(self) -> dict[str, Product]:
    """Return the product map (satisfies the abstract contract)."""
    return self.datasets

health() #

Report structural hygiene issues across the loaded catalog.

Mirrors earthlens.ecmwf.Catalog.health / earthlens.gee.Catalog.health: returns a mapping check_name -> sorted list of offenders. An empty list means the check passes. Schema-level invariants (duplicate keys, unknown fields) are already enforced at load time — these are the residual data-quality checks the pydantic schema cannot express.

Checks reported:

  • product_without_subaliases — products carrying zero sub-aliases.
  • demographic_not_mixed — products flagged demographic whose kind is not "mixed".
  • subalias_unknown_generation"<product>:<id>" whose generation is not in GENERATIONS.
  • subalias_bad_years"<product>:<id>" whose years spec does not parse.

Returns:

Type Description
dict[str, list[str]]

dict[str, list[str]]: The per-check offender lists.

Examples:

  • The bundled catalog is clean:
    >>> from earthlens.worldpop import Catalog
    >>> Catalog().health()
    {'product_without_subaliases': [], 'demographic_not_mixed': [], 'subalias_unknown_generation': [], 'subalias_bad_years': []}
    
Source code in src/earthlens/worldpop/catalog.py
def health(self) -> dict[str, list[str]]:
    """Report structural hygiene issues across the loaded catalog.

    Mirrors `earthlens.ecmwf.Catalog.health` / `earthlens.gee.Catalog.health`:
    returns a mapping `check_name -> sorted list of offenders`. An empty
    list means the check passes. Schema-level invariants (duplicate keys,
    unknown fields) are already enforced at load time — these are the
    residual data-quality checks the pydantic schema cannot express.

    Checks reported:

    * `product_without_subaliases` — products carrying zero sub-aliases.
    * `demographic_not_mixed` — products flagged `demographic` whose
      `kind` is not `"mixed"`.
    * `subalias_unknown_generation` — `"<product>:<id>"` whose
      `generation` is not in `GENERATIONS`.
    * `subalias_bad_years` — `"<product>:<id>"` whose `years` spec does
      not parse.

    Returns:
        dict[str, list[str]]: The per-check offender lists.

    Examples:
        - The bundled catalog is clean:
            ```python
            >>> from earthlens.worldpop import Catalog
            >>> Catalog().health()
            {'product_without_subaliases': [], 'demographic_not_mixed': [], 'subalias_unknown_generation': [], 'subalias_bad_years': []}

            ```
    """
    no_subaliases: list[str] = []
    demographic_not_mixed: list[str] = []
    unknown_generation: list[str] = []
    bad_years: list[str] = []
    for alias, product in self.datasets.items():
        if not product.subaliases:
            no_subaliases.append(alias)
        if product.demographic and product.kind != "mixed":
            demographic_not_mixed.append(alias)
        for sub in product.subaliases:
            if sub.generation not in GENERATIONS:
                unknown_generation.append(f"{alias}:{sub.id}")
            try:
                sub.years_set()
            except ValueError:
                bad_years.append(f"{alias}:{sub.id}")
    return {
        "product_without_subaliases": sorted(no_subaliases),
        "demographic_not_mixed": sorted(demographic_not_mixed),
        "subalias_unknown_generation": sorted(unknown_generation),
        "subalias_bad_years": sorted(bad_years),
    }

load(catalog_path=None) classmethod #

Read the WorldPop product catalog from disk.

Parameters:

Name Type Description Default
catalog_path Path | None

Path to the catalog YAML. Defaults to the module-level CATALOG_PATH.

None

Returns:

Type Description
Catalog

A fully-populated Catalog with datasets and the

Catalog

available_datasets index set.

Raises:

Type Description
ValueError

If the file has no products: block, or a row fails Product validation.

Source code in src/earthlens/worldpop/catalog.py
@classmethod
def load(cls, catalog_path: Path | None = None) -> Catalog:
    """Read the WorldPop product catalog from disk.

    Args:
        catalog_path: Path to the catalog YAML. Defaults to the
            module-level `CATALOG_PATH`.

    Returns:
        A fully-populated `Catalog` with `datasets` and the
        `available_datasets` index set.

    Raises:
        ValueError: If the file has no `products:` block, or a row
            fails `Product` validation.
    """
    catalog_path = catalog_path if catalog_path is not None else CATALOG_PATH
    products = _load_products(catalog_path)
    return cls(datasets=dict(products), available_datasets=sorted(products))

model_post_init(__context) #

Auto-load the bundled catalog when no products were supplied.

Catalog() with no args reads CATALOG_PATH; passing datasets=... skips the disk read (used in tests).

Raises:

Type Description
ValueError

Propagated from load when the YAML is missing, empty, or has a malformed product row.

Source code in src/earthlens/worldpop/catalog.py
def model_post_init(self, __context: Any) -> None:
    """Auto-load the bundled catalog when no products were supplied.

    `Catalog()` with no args reads `CATALOG_PATH`; passing
    `datasets=...` skips the disk read (used in tests).

    Raises:
        ValueError: Propagated from `load` when the YAML is missing,
            empty, or has a malformed product row.
    """
    if not self.datasets:
        self.datasets = dict(_load_products(CATALOG_PATH))
    if not self.available_datasets:
        self.available_datasets = sorted(self.datasets)
    self._index_aliases()

pick_subalias(product, *, constrained=False, unadjusted=True, resolution='100m', scope='countries', generation='R2021', level='national') #

Resolve the selector kwargs to a single REST sub-alias id.

A product with exactly one sub-alias (births, urban_change, …) returns it directly — the selector kwargs do not apply, since there is only one variant. As a guard against a silently-ignored request, a resolution that differs from the sole sub-alias's resolution emits a UserWarning (the other selectors are product-intrinsic for single-variant products and are not warned on). Otherwise the kwargs must match one sub-alias's (constrained, unadjusted, resolution, scope, generation, level) tuple exactly.

Parameters:

Name Type Description Default
product str

A product key or alias (resolved first).

required
constrained bool

Settlement-masked variant (True) vs unconstrained (False).

False
unadjusted bool

Raw (True) vs UN-adjusted (False).

True
resolution str

"100m" or "1km".

'100m'
scope str

"countries" or "global".

'countries'
generation str

One of GENERATIONS.

'R2021'
level str

"national" or "subnational" (only pwd differs).

'national'

Returns:

Name Type Description
str str

The matching sub-alias id (e.g. "wpgp").

Raises:

Type Description
ValueError

If no sub-alias matches the selector; the message lists the product's available sub-alias tuples.

Examples:

  • The classic unconstrained 100 m country series resolves to wpgp:
    >>> from earthlens.worldpop import Catalog
    >>> Catalog().pick_subalias("pop")
    'wpgp'
    
Source code in src/earthlens/worldpop/catalog.py
def pick_subalias(
    self,
    product: str,
    *,
    constrained: bool = False,
    unadjusted: bool = True,
    resolution: str = "100m",
    scope: str = "countries",
    generation: str = "R2021",
    level: str = "national",
) -> str:
    """Resolve the selector kwargs to a single REST sub-alias id.

    A product with exactly one sub-alias (`births`, `urban_change`, …)
    returns it directly — the selector kwargs do not apply, since there
    is only one variant. As a guard against a silently-ignored request,
    a `resolution` that differs from the sole sub-alias's resolution
    emits a `UserWarning` (the other selectors are product-intrinsic for
    single-variant products and are not warned on). Otherwise the kwargs
    must match one sub-alias's
    `(constrained, unadjusted, resolution, scope, generation, level)`
    tuple exactly.

    Args:
        product: A product key or alias (resolved first).
        constrained: Settlement-masked variant (`True`) vs
            unconstrained (`False`).
        unadjusted: Raw (`True`) vs UN-adjusted (`False`).
        resolution: `"100m"` or `"1km"`.
        scope: `"countries"` or `"global"`.
        generation: One of `GENERATIONS`.
        level: `"national"` or `"subnational"` (only `pwd` differs).

    Returns:
        str: The matching sub-alias id (e.g. `"wpgp"`).

    Raises:
        ValueError: If no sub-alias matches the selector; the message
            lists the product's available sub-alias tuples.

    Examples:
        - The classic unconstrained 100 m country series resolves to `wpgp`:
            ```python
            >>> from earthlens.worldpop import Catalog
            >>> Catalog().pick_subalias("pop")
            'wpgp'

            ```
    """
    code = self.resolve(product)
    row = self.datasets[code]
    if len(row.subaliases) == 1:
        only = row.subaliases[0]
        if resolution != only.resolution:
            warnings.warn(
                f"{code!r} offers only the {only.resolution!r} sub-alias "
                f"{only.id!r}; the requested resolution={resolution!r} is "
                "ignored.",
                UserWarning,
                stacklevel=2,
            )
        return only.id
    want = (constrained, unadjusted, resolution, scope, generation, level)
    for sub in row.subaliases:
        if sub.selector() == want:
            return sub.id
    options = "\n".join(
        f"  - id={s.id!r} constrained={s.constrained} "
        f"unadjusted={s.unadjusted} resolution={s.resolution!r} "
        f"scope={s.scope!r} generation={s.generation!r} level={s.level!r}"
        for s in row.subaliases
    )
    raise ValueError(
        f"{code!r} has no variant for constrained={constrained}, "
        f"unadjusted={unadjusted}, resolution={resolution!r}, scope={scope!r}, "
        f"generation={generation!r}, level={level!r}. "
        f"Available sub-aliases:\n{options}"
    )

resolve(key) #

Resolve a product key or friendly alias to its canonical alias.

Parameters:

Name Type Description Default
key str

A canonical alias ("pop") or a friendly alias ("population", case-insensitive).

required

Returns:

Name Type Description
str str

The canonical product alias.

Raises:

Type Description
ValueError

If key matches no product or alias; the message lists the known products with a did-you-mean hint.

Examples:

  • A friendly alias and a canonical key both resolve:
    >>> from earthlens.worldpop import Catalog
    >>> cat = Catalog()
    >>> cat.resolve("population")
    'pop'
    >>> cat.resolve("pop")
    'pop'
    
Source code in src/earthlens/worldpop/catalog.py
def resolve(self, key: str) -> str:
    """Resolve a product key or friendly alias to its canonical alias.

    Args:
        key: A canonical alias (`"pop"`) or a friendly alias
            (`"population"`, case-insensitive).

    Returns:
        str: The canonical product alias.

    Raises:
        ValueError: If `key` matches no product or alias; the message
            lists the known products with a did-you-mean hint.

    Examples:
        - A friendly alias and a canonical key both resolve:
            ```python
            >>> from earthlens.worldpop import Catalog
            >>> cat = Catalog()
            >>> cat.resolve("population")
            'pop'
            >>> cat.resolve("pop")
            'pop'

            ```
    """
    index: dict[str, str] = getattr(self, "_alias_index", {})
    canonical = index.get(key.lower())
    if canonical is not None:
        return canonical
    close = difflib.get_close_matches(key.lower(), index, n=1)
    hint = f" Did you mean {index[close[0]]!r}?" if close else ""
    raise ValueError(
        f"{key!r} is not a known WorldPop product or alias. "
        f"Known products: {sorted(self.datasets)}.{hint}"
    )

subalias(product, subalias_id) #

Return the SubAlias row of a product by its REST id.

Parameters:

Name Type Description Default
product str

A product key or alias (resolved first).

required
subalias_id str

A sub-alias id belonging to that product.

required

Returns:

Name Type Description
SubAlias SubAlias

The matching sub-alias row.

Raises:

Type Description
ValueError

If product is unknown or has no such sub-alias.

Examples:

  • Look up a sub-alias and read its scope / resolution:
    >>> from earthlens.worldpop import Catalog
    >>> sub = Catalog().subalias("pop", "wpgp")
    >>> sub.scope
    'countries'
    >>> sub.resolution
    '100m'
    
Source code in src/earthlens/worldpop/catalog.py
def subalias(self, product: str, subalias_id: str) -> SubAlias:
    """Return the `SubAlias` row of a product by its REST id.

    Args:
        product: A product key or alias (resolved first).
        subalias_id: A sub-alias id belonging to that product.

    Returns:
        SubAlias: The matching sub-alias row.

    Raises:
        ValueError: If `product` is unknown or has no such sub-alias.

    Examples:
        - Look up a sub-alias and read its scope / resolution:
            ```python
            >>> from earthlens.worldpop import Catalog
            >>> sub = Catalog().subalias("pop", "wpgp")
            >>> sub.scope
            'countries'
            >>> sub.resolution
            '100m'

            ```
    """
    code = self.resolve(product)
    for sub in self.datasets[code].subaliases:
        if sub.id == subalias_id:
            return sub
    raise ValueError(
        f"{code!r} has no sub-alias {subalias_id!r}; "
        f"have {[s.id for s in self.datasets[code].subaliases]}."
    )

validate(product, *, constrained=False, unadjusted=True, resolution='100m', scope='countries', generation='R2021', level='national', year=None) #

Validate a full request and return (product, subalias_id).

Resolves the product, picks the sub-alias from the selectors, and — when year is given — checks the sub-alias offers it.

Parameters:

Name Type Description Default
product str

A product key or alias.

required
constrained bool

See pick_subalias.

False
unadjusted bool

See pick_subalias.

True
resolution str

See pick_subalias.

'100m'
scope str

See pick_subalias.

'countries'
generation str

See pick_subalias.

'R2021'
level str

See pick_subalias.

'national'
year int | None

Optional year to check against the sub-alias's years.

None

Returns:

Type Description
tuple[str, str]

tuple[str, str]: The canonical (product, subalias_id).

Raises:

Type Description
ValueError

If the selector matches no sub-alias, or year is outside the sub-alias's available years.

Source code in src/earthlens/worldpop/catalog.py
def validate(
    self,
    product: str,
    *,
    constrained: bool = False,
    unadjusted: bool = True,
    resolution: str = "100m",
    scope: str = "countries",
    generation: str = "R2021",
    level: str = "national",
    year: int | None = None,
) -> tuple[str, str]:
    """Validate a full request and return `(product, subalias_id)`.

    Resolves the product, picks the sub-alias from the selectors, and —
    when `year` is given — checks the sub-alias offers it.

    Args:
        product: A product key or alias.
        constrained: See `pick_subalias`.
        unadjusted: See `pick_subalias`.
        resolution: See `pick_subalias`.
        scope: See `pick_subalias`.
        generation: See `pick_subalias`.
        level: See `pick_subalias`.
        year: Optional year to check against the sub-alias's `years`.

    Returns:
        tuple[str, str]: The canonical `(product, subalias_id)`.

    Raises:
        ValueError: If the selector matches no sub-alias, or `year` is
            outside the sub-alias's available years.
    """
    code = self.resolve(product)
    subalias_id = self.pick_subalias(
        code,
        constrained=constrained,
        unadjusted=unadjusted,
        resolution=resolution,
        scope=scope,
        generation=generation,
        level=level,
    )
    if year is not None:
        sub = next(s for s in self.datasets[code].subaliases if s.id == subalias_id)
        years = sub.years_set()
        if year not in years:
            raise ValueError(
                f"{code}/{subalias_id} does not offer year {year}; "
                f"available years: {sorted(years)}."
            )
    return code, subalias_id

Product #

Bases: BaseModel

One curated WorldPop product family (a top-level REST alias).

Attributes:

Name Type Description
alias str

Canonical product alias ("pop", "age_structures"); set from the YAML mapping key by the loader.

friendly list[str]

Friendly names that also resolve to this product (["population", "population_counts"]).

kind str

"raster" (gridded only) or "mixed" (gridded and a tabular demographic breakdown).

demographic bool

Whether the product ships per-cohort age/sex rasters that earthlens tabularises (only age_structures in practice).

unit str

Human-readable unit of the values ("people/pixel").

worldpoppy_id str | None

The matching WorldPopPy product id for the optional api="worldpoppy" path, or None if unmapped.

rest_alias str

The top-level REST alias to query when it differs from the catalog key. Empty (the default) means "use the key". The covariate products set this to "covariates" (they are sub-aliases of the shared covariates endpoint).

description str

Human-readable description of the product (the hub's title), shown in docs / describe.

subaliases list[SubAlias]

The concrete variants this product offers.

Source code in src/earthlens/worldpop/catalog.py
class Product(BaseModel):
    """One curated WorldPop product family (a top-level REST alias).

    Attributes:
        alias: Canonical product alias (`"pop"`, `"age_structures"`); set
            from the YAML mapping key by the loader.
        friendly: Friendly names that also resolve to this product
            (`["population", "population_counts"]`).
        kind: `"raster"` (gridded only) or `"mixed"` (gridded **and** a
            tabular demographic breakdown).
        demographic: Whether the product ships per-cohort age/sex rasters
            that earthlens tabularises (only `age_structures` in practice).
        unit: Human-readable unit of the values (`"people/pixel"`).
        worldpoppy_id: The matching WorldPopPy product id for the optional
            `api="worldpoppy"` path, or `None` if unmapped.
        rest_alias: The top-level REST alias to query when it differs from
            the catalog key. Empty (the default) means "use the key". The
            covariate products set this to `"covariates"` (they are
            sub-aliases of the shared `covariates` endpoint).
        description: Human-readable description of the product (the hub's
            title), shown in docs / `describe`.
        subaliases: The concrete variants this product offers.
    """

    model_config = ConfigDict(frozen=True, extra="forbid")

    alias: str = ""
    friendly: list[str] = Field(default_factory=list)
    kind: str = "raster"
    demographic: bool = False
    unit: str = ""
    worldpoppy_id: str | None = None
    rest_alias: str = ""
    description: str = ""
    subaliases: list[SubAlias] = Field(default_factory=list)

    def endpoint(self) -> str:
        """Return the REST alias to query (`rest_alias` or the product key)."""
        return self.rest_alias or self.alias

    def selectors(self) -> list[tuple[bool, bool, str, str, str, str]]:
        """Return every sub-alias selector tuple (for did-you-mean listings)."""
        return [s.selector() for s in self.subaliases]

endpoint() #

Return the REST alias to query (rest_alias or the product key).

Source code in src/earthlens/worldpop/catalog.py
def endpoint(self) -> str:
    """Return the REST alias to query (`rest_alias` or the product key)."""
    return self.rest_alias or self.alias

selectors() #

Return every sub-alias selector tuple (for did-you-mean listings).

Source code in src/earthlens/worldpop/catalog.py
def selectors(self) -> list[tuple[bool, bool, str, str, str, str]]:
    """Return every sub-alias selector tuple (for did-you-mean listings)."""
    return [s.selector() for s in self.subaliases]

SubAlias #

Bases: BaseModel

One concrete WorldPop variant under a product alias.

Maps the selector tuple (constrained, unadjusted, resolution, scope, generation) to a REST sub-alias id and the years it offers. The tuple is unique within a product, so Catalog.pick_subalias can resolve a request to exactly one sub-alias.

Attributes:

Name Type Description
id str

The real REST sub-alias id ("wpgp", "cic2020_100m", "G2_CN_POP_R25A_100m", …) — the {subalias} path segment.

constrained bool

Whether this is the settlement-masked constrained variant (True) or the unconstrained variant (False).

unadjusted bool

True for the raw variant; False for the UN-adjusted variant. WorldPop's "UN adjusted" sub-aliases set this False, the plain ones True. Defaults to True.

resolution str

Pixel size — "100m" or "1km".

scope str

"countries" (per-ISO3 rasters) or "global" (a single global mosaic).

generation str

The product generation ("R2021", "R2024B", "R2025A", "2024").

level str

Aggregation level for products that publish both (pwd): "national" or "subnational". "national" for every other product.

archive str

The archive format the product is distributed in, or "" for plain per-year GeoTIFFs. "7z" (dependency_ratios, per-continent) and "zip" (future_pop, per-SSP) products are downloaded as an archive and extracted before cropping; "zip" (multi-GB) additionally requires the allow_large_archive opt-in.

years str

The years this sub-alias offers, as a single year ("2020") or an inclusive range ("2000-2020").

Source code in src/earthlens/worldpop/catalog.py
class SubAlias(BaseModel):
    """One concrete WorldPop variant under a product alias.

    Maps the selector tuple `(constrained, unadjusted, resolution, scope,
    generation)` to a REST sub-alias `id` and the years it offers. The tuple
    is unique within a product, so `Catalog.pick_subalias` can resolve a
    request to exactly one sub-alias.

    Attributes:
        id: The real REST sub-alias id (`"wpgp"`, `"cic2020_100m"`,
            `"G2_CN_POP_R25A_100m"`, …) — the `{subalias}` path segment.
        constrained: Whether this is the settlement-masked *constrained*
            variant (`True`) or the *unconstrained* variant (`False`).
        unadjusted: `True` for the raw variant; `False` for the
            UN-adjusted variant. WorldPop's "UN adjusted" sub-aliases set
            this `False`, the plain ones `True`. Defaults to `True`.
        resolution: Pixel size — `"100m"` or `"1km"`.
        scope: `"countries"` (per-ISO3 rasters) or `"global"` (a single
            global mosaic).
        generation: The product generation (`"R2021"`, `"R2024B"`,
            `"R2025A"`, `"2024"`).
        level: Aggregation level for products that publish both
            (`pwd`): `"national"` or `"subnational"`. `"national"` for
            every other product.
        archive: The archive format the product is distributed in, or `""`
            for plain per-year GeoTIFFs. `"7z"` (`dependency_ratios`,
            per-continent) and `"zip"` (`future_pop`, per-SSP) products are
            downloaded as an archive and extracted before cropping; `"zip"`
            (multi-GB) additionally requires the `allow_large_archive` opt-in.
        years: The years this sub-alias offers, as a single year
            (`"2020"`) or an inclusive range (`"2000-2020"`).
    """

    model_config = ConfigDict(frozen=True, extra="forbid")

    id: str
    constrained: bool = False
    unadjusted: bool = True
    resolution: str = "100m"
    scope: str = "countries"
    generation: str = "R2021"
    level: str = "national"
    archive: str = ""
    years: str = "2000-2020"

    def years_set(self) -> set[int]:
        """Return the set of years this sub-alias offers (parsed from `years`)."""
        return _years_set(self.years)

    def selector(self) -> tuple[bool, bool, str, str, str, str]:
        """Return the selector key.

        The key is `(constrained, unadjusted, resolution, scope, generation,
        level)` — unique within a product.
        """
        return (
            self.constrained,
            self.unadjusted,
            self.resolution,
            self.scope,
            self.generation,
            self.level,
        )

selector() #

Return the selector key.

The key is (constrained, unadjusted, resolution, scope, generation, level) — unique within a product.

Source code in src/earthlens/worldpop/catalog.py
def selector(self) -> tuple[bool, bool, str, str, str, str]:
    """Return the selector key.

    The key is `(constrained, unadjusted, resolution, scope, generation,
    level)` — unique within a product.
    """
    return (
        self.constrained,
        self.unadjusted,
        self.resolution,
        self.scope,
        self.generation,
        self.level,
    )

years_set() #

Return the set of years this sub-alias offers (parsed from years).

Source code in src/earthlens/worldpop/catalog.py
def years_set(self) -> set[int]:
    """Return the set of years this sub-alias offers (parsed from `years`)."""
    return _years_set(self.years)

WorldPop #

Bases: AbstractDataSource

Download WorldPop population + demographic products, localised via pyramids.

Attributes:

Name Type Description
OUTPUT_KIND OutputKind

Fixed "mixed" — population products yield GeoTIFFs and demographic products (age_structures) additionally yield a tidy age/sex table, so the facade forwards aggregate=.

Source code in src/earthlens/worldpop/backend.py
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
class WorldPop(AbstractDataSource):
    """Download WorldPop population + demographic products, localised via pyramids.

    Attributes:
        OUTPUT_KIND: Fixed `"mixed"` — population products yield GeoTIFFs
            and demographic products (`age_structures`) additionally yield a
            tidy age/sex table, so the facade forwards `aggregate=`.
    """

    OUTPUT_KIND: OutputKind = "mixed"

    def __init__(
        self,
        start: str,
        end: str,
        variables: list[str],
        lat_lim: list[float],
        lon_lim: list[float],
        temporal_resolution: str = "yearly",
        path: Path | str = "",
        fmt: str = "%Y-%m-%d",
        *,
        aoi: str | list[str] | list[float] | object | None = None,
        constrained: bool = False,
        unadjusted: bool = True,
        resolution: str = "100m",
        scope: str = "countries",
        generation: str = "R2021",
        level: str = "national",
        year: int | None = None,
        years: list[int] | None = None,
        crs: str = "EPSG:4326",
        api: str = "rest",
        ssp: str = "SSP2",
        allow_large_archive: bool = False,
        catalog: Catalog | None = None,
    ):
        """Initialise a WorldPop backend instance.

        Resolves and statically validates every requested product +
        sub-alias selector against the catalog **before** the parent
        constructor runs (the parent calls `_initialize` first). The AOI is
        resolved to a set of ISO3 codes here too, since `_initialize`
        receives no bbox.

        Args:
            start: Inclusive start of the date window (parsed with `fmt`);
                its year selects the first WorldPop year in range.
            end: Inclusive end of the date window.
            variables: WorldPop product keys — canonical (`"pop"`) or
                friendly aliases (`"population"`, `"age_sex"`, …).
            lat_lim: `[lat_min, lat_max]` in degrees.
            lon_lim: `[lon_min, lon_max]` in degrees.
            temporal_resolution: Advisory label only (WorldPop years are
                annual points); accepted for facade parity. Defaults to
                `"yearly"`.
            path: Output directory. Created by the parent class.
            fmt: `strptime` format for `start` / `end`.
            aoi: Explicit AOI — an ISO3 string, a list of ISO3 strings, a
                `[w, s, e, n]` bbox, or a `GeoDataFrame`. `None` (default)
                derives the ISO3 set from `lat_lim` / `lon_lim`.
            constrained: Settlement-masked *constrained* variant (`True`)
                vs *unconstrained* (`False`, default).
            unadjusted: Raw variant (`True`, default → `wpgp`) vs the
                UN-adjusted variant (`False` → `wpgpunadj`).
            resolution: `"100m"` (default) or `"1km"`.
            scope: `"countries"` (per-ISO3, default) or `"global"` (the
                global mosaic, where the product offers one).
            generation: Product generation — `"R2021"` (default, the
                classic 2000–2020 line) or a Global-2 line (`"R2025A"`, …).
            level: `"national"` (default) or `"subnational"` — only the
                population-weighted-density (`pwd`) product offers both.
            year: A single year to fetch (overrides the date window).
            years: An explicit list of years (overrides the date window
                and `year`).
            crs: Output CRS as an EPSG string / code (default
                `"EPSG:4326"` — WorldPop's native CRS, so no reproject).
            api: Access path — `"rest"` (default; direct REST + pyramids,
                no optional SDK) or `"worldpoppy"` (the optional SDK via its
                file cache).
            ssp: SSP scenario for the `future_pop` `.zip` archives
                (`"SSP1"`…`"SSP5"`; default `"SSP2"`). Ignored by other
                products.
            allow_large_archive: Opt-in required to download the multi-GB
                `future_pop` per-SSP `.zip` archives (~4 GB each). Defaults
                to `False`.
            catalog: Optional pre-built `Catalog` (tests inject a faked
                one); defaults to the bundled catalog.

        Raises:
            ValueError: When `variables` is empty, a product / alias is
                unknown, the selector tuple matches no sub-alias, or
                `resolution` / `scope` / `generation` / `api` is malformed.
            ImportError: When `api="worldpoppy"` but the `[worldpop]` extra
                is not installed.
        """
        if not variables:
            raise ValueError(
                "WorldPop requires a non-empty `variables` list of product keys, "
                'e.g. ["pop"] or ["population"].'
            )
        if api not in _API_MODES:
            raise ValueError(f"api must be one of {sorted(_API_MODES)}; got {api!r}.")
        if resolution not in _RESOLUTIONS:
            raise ValueError(
                f"resolution must be one of {sorted(_RESOLUTIONS)}; got {resolution!r}."
            )
        if scope not in _SCOPES:
            raise ValueError(f"scope must be one of {sorted(_SCOPES)}; got {scope!r}.")
        if level not in _LEVELS:
            raise ValueError(f"level must be one of {sorted(_LEVELS)}; got {level!r}.")
        if generation not in GENERATIONS:
            raise ValueError(
                f"generation must be one of {list(GENERATIONS)}; got {generation!r}."
            )
        if api == "worldpoppy":
            _require_worldpoppy()

        self._catalog = catalog if catalog is not None else Catalog()
        self._constrained = constrained
        self._unadjusted = unadjusted
        self._resolution = resolution
        self._scope = scope
        self._generation = generation
        self._level = level
        self._year_arg = year
        self._years_arg = years
        self._crs = crs
        self._output_epsg = epsg_int(crs)
        self._api_mode = api
        self._ssp = ssp
        self._allow_large_archive = allow_large_archive
        self._auth = WorldPopAuth()
        self._aggregate_cfg = None
        self._show_progress = True

        # Resolve + statically validate (product + selector → sub-alias) up
        # front; year validation happens once the year list is derived.
        self._products: list[str] = [self._catalog.resolve(v) for v in variables]
        self._subalias_ids: dict[str, str] = {
            product: self._catalog.pick_subalias(
                product,
                constrained=constrained,
                unadjusted=unadjusted,
                resolution=resolution,
                scope=scope,
                generation=generation,
                level=level,
            )
            for product in self._products
        }
        self._guard_unsupported()
        self._iso3s: list[str] = self._resolve_aoi(aoi, lat_lim, lon_lim)

        super().__init__(
            start=start,
            end=end,
            variables=variables,
            temporal_resolution=temporal_resolution,
            lat_lim=lat_lim,
            lon_lim=lon_lim,
            fmt=fmt,
            path=path,
        )

        # A polygon AOI (a GeoDataFrame / geometry, not an ISO3 code or
        # bbox) masks the fetched country mosaics to the exact shape; the
        # ISO3 set above already selected which countries to fetch.
        if aoi is not None and (
            hasattr(aoi, "total_bounds") or hasattr(aoi, "__geo_interface__")
        ):
            _, _, geometry = resolve_aoi(aoi)
            if geometry is not None:
                self._attach_clip_geometry(geometry)

    def _guard_unsupported(self) -> None:
        """Gate the multi-GB `.zip` archive products behind an explicit opt-in.

        Per-country / global-mosaic GeoTIFF products and the small `.7z`
        per-continent products (`dependency_ratios`) are fetched directly.
        The `future_pop` SSP `.zip` bundles are **~4 GB each** (×5 scenarios),
        so they require `allow_large_archive=True` to avoid a multi-GB
        surprise download.

        Raises:
            NotImplementedError: If a `.zip` archive product is requested
                without `allow_large_archive=True`.
        """
        for product, subalias_id in self._subalias_ids.items():
            sub = self._catalog.subalias(product, subalias_id)
            if sub.archive == "zip" and not self._allow_large_archive:
                raise NotImplementedError(
                    f"WorldPop {product!r} ({subalias_id!r}) ships as ~4 GB per-SSP "
                    ".zip archives (×5 scenarios). Pass allow_large_archive=True "
                    "(and an ssp=, e.g. ssp='SSP2') to opt into the large download."
                )

    def _resolve_aoi(
        self,
        aoi: str | list[str] | list[float] | object | None,
        lat_lim: list[float],
        lon_lim: list[float],
    ) -> list[str]:
        """Resolve the AOI to a sorted list of ISO3 country codes.

        Args:
            aoi: An ISO3 string, a list of ISO3 strings, a `[w, s, e, n]`
                bbox, a `GeoDataFrame`, or `None` (derive from the bbox).
            lat_lim: `[lat_min, lat_max]` used when `aoi` is `None`.
            lon_lim: `[lon_min, lon_max]` used when `aoi` is `None`.

        Returns:
            list[str]: The intersecting / requested ISO3 codes, sorted.
        """
        if isinstance(aoi, str):
            return [normalise_iso3(aoi)]
        if isinstance(aoi, list) and aoi and isinstance(aoi[0], str):
            return sorted({normalise_iso3(code) for code in aoi})
        if isinstance(aoi, list) and len(aoi) == 4 and isinstance(aoi[0], (int, float)):
            bbox = [float(x) for x in aoi]
        elif aoi is not None and hasattr(aoi, "total_bounds"):  # a GeoDataFrame
            crs = getattr(aoi, "crs", None)
            if crs is not None and crs.to_epsg() != 4326:
                aoi = aoi.to_crs(4326)
            bbox = [float(x) for x in aoi.total_bounds]
        else:
            bbox = [lon_lim[0], lat_lim[0], lon_lim[1], lat_lim[1]]
        return iso3_for_bbox(bbox, load_iso3_bbox())

    def _initialize(self):
        """Configure the (no-op) auth; no network client is created.

        Returns:
            None: WorldPop is open + anonymous, so the parent binds no
                `self.client`.
        """
        self._auth.configure()
        return None

    def _create_grid(self, lat_lim: list, lon_lim: list) -> SpatialExtent:
        """Wrap the user bbox into a `SpatialExtent`.

        Args:
            lat_lim: `[lat_min, lat_max]` in degrees.
            lon_lim: `[lon_min, lon_max]` in degrees.

        Returns:
            SpatialExtent: Validated, frozen bbox (WGS84).
        """
        return SpatialExtent.from_pairs(lat_lim=lat_lim, lon_lim=lon_lim)

    def _check_input_dates(
        self,
        start: str,
        end: str,
        temporal_resolution: str,
        fmt: str,
    ) -> TemporalExtent:
        """Parse the date window into a `TemporalExtent`.

        The window's years select the WorldPop years in range; the
        per-year expansion happens in `_years`.

        Args:
            start: Inclusive start of the window.
            end: Inclusive end of the window.
            temporal_resolution: Advisory label (ignored).
            fmt: `strptime` format applied to `start` / `end`.

        Returns:
            TemporalExtent: Frozen model with the parsed bounds.

        Raises:
            ValueError: If `start` parses to a date later than `end`.
        """
        start_dt = dt.datetime.strptime(start, fmt)
        end_dt = dt.datetime.strptime(end, fmt)
        dates = pd.date_range(start_dt, end_dt, freq="YS")
        return TemporalExtent(
            start_date=start_dt,
            end_date=end_dt,
            resolution="YS",
            dates=dates,
        )

    def _years(self) -> list[int]:
        """Return the explicit years to fetch (from `years` / `year` / window).

        Returns:
            list[int]: Sorted, de-duplicated years. `years=` wins, then
                `year=`, else every year spanned by `start`/`end`.
        """
        if self._years_arg is not None:
            return sorted({int(y) for y in self._years_arg})
        if self._year_arg is not None:
            return [int(self._year_arg)]
        return sorted({d.year for d in self.time.dates})

    def _search(self) -> list[RemoteProduct]:
        """Plan the download — one `RemoteProduct` per `(product, iso3, year, file)`.

        Queries the REST API once per `(product, iso3)` (records carry every
        year) and filters client-side to the requested years. For
        demographic products each year yields many cohort files; for plain
        population products, one.

        Returns:
            list[RemoteProduct]: One item per GeoTIFF URL to download, each
                carrying `product` / `iso3` / `year` / `demographic` /
                `subalias` metadata.
        """
        out: list[RemoteProduct] = []
        years = self._years()
        if self._api_mode == "worldpoppy":
            # The WorldPopPy SDK resolves files itself; the plan is just the
            # (product, iso3, year) cross-product (no REST query, no URLs).
            for product in self._products:
                demographic = self._catalog.get(product).demographic
                for iso3 in self._iso3s:
                    for year in years:
                        out.append(
                            RemoteProduct(
                                id=f"{product}_{iso3}_{year}",
                                href=None,
                                metadata={
                                    "product": product,
                                    "iso3": iso3,
                                    "year": year,
                                    "demographic": demographic,
                                },
                            )
                        )
            return out
        for product in self._products:
            subalias_id = self._subalias_ids[product]
            demographic = self._catalog.get(product).demographic
            if self._catalog.subalias(product, subalias_id).scope == "global":
                out.extend(self._plan_global(product, subalias_id, demographic, years))
            else:
                out.extend(
                    self._plan_countries(product, subalias_id, demographic, years)
                )
        return out

    def _plan_countries(
        self, product: str, subalias_id: str, demographic: bool, years: list[int]
    ) -> list[RemoteProduct]:
        """Plan per-country downloads for one product (records once per ISO3).

        Covariate layers are **undated** (one record, `popyear` is `None`),
        so they are planned once per ISO3 with the year read from the
        filename rather than looped over the requested years.
        """
        endpoint = self._catalog.get(product).endpoint()
        out: list[RemoteProduct] = []
        for iso3 in self._iso3s:
            records = rest_records(endpoint, subalias_id, iso3)
            undated = not any(rec.get("popyear") for rec in records)
            for year in [None] if undated else years:
                for url in files_for_year(records, year):
                    resolved_year = year if year is not None else _year_in(url)
                    out.append(
                        RemoteProduct(
                            id=f"{product}_{iso3}_{resolved_year}_{Path(url).stem}",
                            href=url,
                            metadata={
                                "product": product,
                                "iso3": iso3,
                                "year": resolved_year,
                                "subalias": subalias_id,
                                "demographic": demographic,
                            },
                        )
                    )
        return out

    def _plan_global(
        self, product: str, subalias_id: str, demographic: bool, years: list[int]
    ) -> list[RemoteProduct]:
        """Plan global-mosaic downloads for one product (no ISO3; `?id=` detail).

        A global mosaic is one whole-world GeoTIFF per year (or one per
        age/sex cohort), downloaded once and cropped to the AOI bbox by the
        localise step — there is no per-country mosaic.
        """
        out: list[RemoteProduct] = []
        for year in years:
            for url in global_files_for_year(product, subalias_id, year):
                out.append(
                    RemoteProduct(
                        id=f"{product}_global_{year}_{Path(url).stem}",
                        href=url,
                        metadata={
                            "product": product,
                            "iso3": "global",
                            "year": year,
                            "subalias": subalias_id,
                            "demographic": demographic,
                        },
                    )
                )
        return out

    def _raw_dir(self) -> Path:
        """Return (creating) the directory raw per-country downloads land in."""
        raw = self.root_dir / _RAW_DIRNAME
        raw.mkdir(parents=True, exist_ok=True)
        return raw

    def _http_get(self, url: str, dest: Path) -> Path:
        """Download `url` to `dest`, skipping when the file already exists.

        Transient connection / timeout errors are retried up to
        `_MAX_RETRIES` with exponential backoff; an HTTP status error (e.g.
        404) propagates immediately without retry.

        Args:
            url: The GeoTIFF URL.
            dest: Local destination path.

        Returns:
            Path: `dest`.

        Raises:
            requests.HTTPError: On a non-2xx response (the URL is named).
            requests.ConnectionError | requests.Timeout: If every retry of a
                transient network error is exhausted.
        """
        if dest.exists() and dest.stat().st_size > 0:
            return dest
        http = HttpClient(
            session=_RequestsGet(),
            retry_on_exceptions=(requests.ConnectionError, requests.Timeout),
            status_forcelist=(),
            max_retries=_MAX_RETRIES - 1,
            backoff_factor=_BACKOFF_BASE,
            max_backoff=None,
            timeout=_HTTP_TIMEOUT,
            sleep=lambda seconds: time.sleep(seconds),
        )
        resp = http.get(url)
        dest.write_bytes(resp.content)
        return dest

    def _group_for_mosaic(
        self, products: list[RemoteProduct]
    ) -> dict[
        tuple[str, int, tuple[str, int] | None], list[tuple[Path, RemoteProduct]]
    ]:
        """Download every product and group the files for mosaicking.

        Groups by `(product, year, cohort)` so multi-country requests merge
        correctly and `age_structures` keeps each age/sex cohort separate.

        Args:
            products: The `_search` result.

        Returns:
            A mapping `(product, year, cohort) -> [(local_path, product), …]`.
        """
        raw = self._raw_dir()
        paths = Parallel(n_jobs=_DOWNLOAD_JOBS, prefer="threads")(
            delayed(self._http_get)(rp.href, raw / Path(rp.href).name)
            for rp in products
        )
        groups: dict[
            tuple[str, int, tuple[str, int] | None], list[tuple[Path, RemoteProduct]]
        ] = {}
        for path, rp in zip(paths, products):
            key = (rp.metadata["product"], rp.metadata["year"], cohort_of(rp.href))
            groups.setdefault(key, []).append((path, rp))
        return groups

    def _fetch(self, products: list[RemoteProduct]) -> list[Path]:
        """Download, localise, tabularise demographics, and optionally aggregate.

        Downloads (idempotently, in parallel), mosaics + crops each
        `(product, year, cohort)` group to the AOI, writes a tidy age/sex
        table for demographic products, and — when `aggregate=` was passed
        to `download` — reduces the per-year rasters across years.

        Args:
            products: The `_search` result.

        Returns:
            list[Path]: The written GeoTIFF and table paths (the reduced
                per-window rasters replace the per-year rasters when
                `aggregate=` is set; tables are always included).
        """
        if self._api_mode == "worldpoppy":
            return self._fetch_via_worldpoppy(products)
        return self._finish(self._group_for_mosaic(products))

    def _finish(
        self,
        groups: dict[
            tuple[str, int, tuple[str, int] | None], list[tuple[Path, RemoteProduct]]
        ],
    ) -> list[Path]:
        """Localise each group, write demographic tables, and optionally aggregate.

        Shared tail of both the REST and WorldPopPy fetch paths.

        Args:
            groups: The `(product, year, cohort) -> [(path, product), …]`
                map of downloaded / cached per-country tiles.

        Returns:
            list[Path]: The written GeoTIFF + table paths (reduced
                per-window rasters replace per-year rasters when
                `aggregate=` is set).
        """
        localised: dict[tuple[str, int, tuple[str, int] | None], Path] = {
            key: self._localise(group) for key, group in groups.items()
        }
        tables = self._write_demographic_tables(localised)
        if self._aggregate_cfg is not None:
            rasters = self._aggregate_years(localised, self._aggregate_cfg)
        else:
            rasters = list(localised.values())
        self._sweep_intermediates()
        return rasters + tables

    def _sweep_intermediates(self) -> None:
        """Best-effort removal of leftover `*_merged.tif` mosaics.

        `_localise` deletes each intermediate inline, but on Windows the GDAL
        handle may still be open at that point. Once the per-`_localise`
        datasets are out of scope, a `gc.collect()` releases the handles, so
        this final sweep clears any that survived. Failures are ignored — the
        files live in the hidden raw cache dir and are harmless.
        """
        import gc

        gc.collect()
        raw = self._raw_dir()
        # _localise writes the intermediate with a leading dot, so match both.
        leftovers = list(raw.glob("*_merged.tif")) + list(raw.glob(".*_merged.tif"))
        for leftover in leftovers:
            try:
                leftover.unlink()
            except OSError:
                pass

    def _write_demographic_tables(
        self, localised: dict[tuple[str, int, tuple[str, int] | None], Path]
    ) -> list[Path]:
        """Write a tidy age/sex table per `(product, year)` for demographic products.

        For each cohort raster of a demographic product (`age_structures`),
        the AOI population total is summed and emitted as one tidy row
        `{aoi, year, sex, age_low, population}`; the rows for a
        `(product, year)` are written to `{product}_{year}.csv` alongside
        the per-cohort GeoTIFFs.

        Args:
            localised: The `(product, year, cohort) -> output_path` map.

        Returns:
            list[Path]: The written table paths (empty if no demographic
                product was requested).
        """
        rows_by_table: dict[tuple[str, int], list[dict[str, object]]] = {}
        aoi_label = "+".join(self._iso3s) if self._iso3s else "aoi"
        for (product, year, cohort), path in localised.items():
            if cohort is None or not self._catalog.get(product).demographic:
                continue
            sex, age_low = cohort
            rows_by_table.setdefault((product, year), []).append(
                {
                    "aoi": aoi_label,
                    "year": year,
                    "sex": sex,
                    "age_low": age_low,
                    "population": _zonal_sum(path),
                }
            )
        out: list[Path] = []
        for (product, year), rows in rows_by_table.items():
            frame = pd.DataFrame(rows).sort_values(["sex", "age_low"])
            target = Path(self.path) / f"{product}_{year}.csv"
            frame.to_csv(target, index=False)
            out.append(target)
        return out

    def _aggregate_years(
        self,
        localised: dict[tuple[str, int, tuple[str, int] | None], Path],
        cfg,
    ) -> list[Path]:
        """Reduce the per-year rasters across years, bucketed by `cfg.freq`.

        Groups the localised rasters by `(product, cohort)`, buckets their
        years by the pandas offset `cfg.freq`, reduces each bucket with
        `cfg.op` (`auto` → `mean` for population), and writes one GeoTIFF
        per window.

        Args:
            localised: The `(product, year, cohort) -> output_path` map.
            cfg: An `earthlens.aggregate.AggregationConfig`.

        Returns:
            list[Path]: One reduced GeoTIFF per `(product, cohort, window)`.
        """
        from pyramids.dataset import Dataset

        op = "mean" if cfg.op == "auto" else cfg.op
        by_series: dict[tuple[str, tuple[str, int] | None], dict[int, Path]] = {}
        for (product, year, cohort), path in localised.items():
            by_series.setdefault((product, cohort), {})[year] = path

        out: list[Path] = []
        for (product, cohort), year_paths in by_series.items():
            years = sorted(year_paths)
            index = pd.to_datetime([f"{y}-01-01" for y in years])
            series = pd.Series(years, index=index)
            for window_label, bucket in series.groupby(pd.Grouper(freq=cfg.freq)):
                bucket_years = list(bucket.values)
                if not bucket_years:
                    continue
                template = Dataset.read_file(str(year_paths[bucket_years[0]]))
                stack = np.stack(
                    [
                        _masked_array(Dataset.read_file(str(year_paths[y])))
                        for y in bucket_years
                    ]
                )
                with warnings.catch_warnings():
                    # All-no-data cells reduce to NaN; that is expected for
                    # ocean / outside-AOI pixels, so silence the empty-slice
                    # RuntimeWarning numpy emits for them.
                    warnings.simplefilter("ignore", RuntimeWarning)
                    reduced = _REDUCERS[op](stack, axis=0)
                tag = f"_{cohort[0]}_{cohort[1]}" if cohort else ""
                target = (
                    Path(self.path)
                    / f"{product}{tag}_{cfg.freq}_{window_label:%Y%m%d}_{op}.tif"
                )
                Dataset.create_from_array(
                    arr=reduced, geo=template.geotransform, epsg=template.epsg
                ).to_file(str(target))
                out.append(target)
        return out

    def _fetch_via_worldpoppy(self, products: list[RemoteProduct]) -> list[Path]:
        """Fetch via the optional WorldPopPy SDK — through its file cache only.

        Calls `wp_raster(..., download_dry_run=True)` to populate the SDK's
        on-disk cache, **discards the returned `xarray.DataArray`** (CLAUDE.md
        forbids importing xarray in `src/`), then reads the cached GeoTIFFs
        from `get_cache_dir()` and runs them through the same localise /
        table / aggregate tail as the REST path.

        Args:
            products: The `_search` plan (one item per product / iso3 /
                year); used to bound which cached files are consumed.

        Returns:
            list[Path]: The written GeoTIFF + table paths.

        Raises:
            ValueError: If a requested product has no `worldpoppy_id`.
        """
        from worldpoppy import get_cache_dir, wp_raster

        years = self._years()
        cache = Path(get_cache_dir())
        groups: dict[
            tuple[str, int, tuple[str, int] | None], list[tuple[Path, RemoteProduct]]
        ] = {}
        for product in self._products:
            wp_id = self._catalog.get(product).worldpoppy_id
            if not wp_id:
                raise ValueError(
                    f"{product!r} has no worldpoppy_id mapping; use api='rest'."
                )
            demographic = self._catalog.get(product).demographic
            # Snapshot the cache around each call so the files this product
            # produced are attributed to it by provenance, not by filename
            # convention. If the product was already fully cached (no new
            # files), fall back to demographic-vs-cohort matching across the
            # cache for this product.
            before = set(cache.rglob("*.tif"))
            wp_raster(
                product_name=wp_id,
                aoi=self._iso3s,
                years=years,
                download_dry_run=True,  # the returned xarray.DataArray is discarded
            )
            produced = set(cache.rglob("*.tif")) - before
            if not produced:
                produced = set(cache.rglob("*.tif"))
            for tif in sorted(produced):
                match = re.search(r"_(\d{4})\.tif$", tif.name)
                if match is None:
                    continue
                year = int(match.group(1))
                iso3 = tif.name[:3].upper()
                cohort = cohort_of(tif.name)
                if iso3 not in self._iso3s or year not in years:
                    continue
                if demographic != (cohort is not None):
                    continue
                rp = RemoteProduct(
                    id=f"{product}_{iso3}_{year}_{tif.stem}",
                    href=str(tif),
                    metadata={
                        "product": product,
                        "iso3": iso3,
                        "year": year,
                        "demographic": demographic,
                    },
                )
                groups.setdefault((product, year, cohort), []).append((tif, rp))
        return self._finish(groups)

    def _localise(self, group: list[tuple[Path, RemoteProduct]]) -> Path:
        """Mosaic the per-country GeoTIFFs of one group + crop to the AOI.

        WorldPop is WGS84 (EPSG:4326) natively, so no reproject happens
        unless `crs != 4326`. The crop bbox is always WGS84 regardless of
        the output CRS (pyramids reprojects the bbox).

        Args:
            group: `[(local_path, product), …]` for one `(product, year,
                cohort)` — the per-country tiles to merge.

        Returns:
            Path: The written AOI-cropped GeoTIFF under `self.path`.
        """
        from pyramids.dataset import Dataset
        from pyramids.dataset.merge import merge_rasters

        tifs = [str(path) for path, _ in group]
        rp = group[0][1]
        product = rp.metadata["product"]
        year = rp.metadata["year"]
        dst_crs = self._output_epsg if self._output_epsg != 4326 else None

        work = self._raw_dir() / f".{product}_{year}_{Path(rp.href).stem}_merged.tif"
        merge_rasters(
            tifs,
            str(work),
            method="last",
            dst_crs=dst_crs,
            no_data_value=_WORLDPOP_NODATA,
        )
        dataset = Dataset.read_file(str(work))
        cropped = crop_to_aoi(
            dataset,
            self.space,
            bbox=[
                self.space.west,
                self.space.south,
                self.space.east,
                self.space.north,
            ],
            touch=True,
        )
        cohort = cohort_of(rp.href)
        tag = f"_{cohort[0]}_{cohort[1]}" if cohort else ""
        target = Path(self.path) / f"{product}_{year}{tag}_{self._resolution}.tif"
        cropped.to_file(str(target))
        # Best-effort cleanup of the intermediate mosaic; on Windows the GDAL
        # handle may still hold it open, in which case it stays in the raw
        # cache dir (harmless — a distinct name per group).
        try:
            work.unlink(missing_ok=True)
        except OSError:
            pass
        return target

    def _archive_products(self) -> list[str]:
        """Return the requested products whose sub-alias is archive-distributed."""
        return [
            product
            for product in self._products
            if self._catalog.subalias(product, self._subalias_ids[product]).archive
        ]

    def _dispatch(self) -> list[Path]:
        """Route the request to the archive path or the GeoTIFF search/fetch.

        Archive products (`.7z` / `.zip`) and plain GeoTIFF products cannot
        be combined in one request — they take different fetch paths.

        Raises:
            ValueError: If the request mixes archive and GeoTIFF products.
        """
        archive = self._archive_products()
        if archive and len(archive) != len(self._products):
            raise ValueError(
                "WorldPop cannot mix archive products "
                f"({archive}) with GeoTIFF products in one request; fetch them "
                "separately."
            )
        if archive:
            return self._fetch_archive()
        return self._api_via_search_fetch()

    def _api(self) -> list[Path]:
        """Dispatch the request (archive path or GeoTIFF search/fetch)."""
        return self._dispatch()

    def download(self, progress_bar: bool = True, aggregate=None) -> list[Path]:
        """Fetch the requested products as AOI-cropped GeoTIFFs (+ tables).

        Args:
            progress_bar: Whether per-download progress is shown.
            aggregate: Optional `earthlens.aggregate.AggregationConfig`;
                reduces the per-year raster stack across years. It reduces
                the **rasters** only — for demographic products the per-cohort
                age/sex tables are still written per year (the table column is
                not aggregated). Ignored by the archive products.

        Returns:
            list[Path]: The written GeoTIFF / table paths.
        """
        self._show_progress = progress_bar
        self._aggregate_cfg = aggregate
        return self._dispatch()

    def _fetch_archive(self) -> list[Path]:
        """Fetch archive products (`.7z` / `.zip`): download, extract, crop.

        `dependency_ratios` ships one small `.7z` per continent (the AOI's
        continent is resolved); `future_pop` ships one ~4 GB `.zip` per SSP
        scenario (`ssp=`). Each archive's GeoTIFF members are extracted and
        cropped to the AOI bbox.

        Returns:
            list[Path]: One cropped GeoTIFF per extracted archive member
                (year-filtered for the per-year `.zip` products).
        """
        out: list[Path] = []
        bbox = [self.space.west, self.space.south, self.space.east, self.space.north]
        for product in self._products:
            subalias_id = self._subalias_ids[product]
            fmt = self._catalog.subalias(product, subalias_id).archive
            for url in self._archive_urls(product, subalias_id, fmt, bbox):
                local = self._http_get(url, self._raw_dir() / Path(url).name)
                extract_dir = self._raw_dir() / f".{product}_{Path(url).stem}_extract"
                members = extract_geotiffs(local, fmt, extract_dir)
                for tif in self._select_archive_members(members, fmt):
                    out.append(self._crop_archive_member(tif, product, bbox))
        return out

    def _archive_urls(
        self, product: str, subalias_id: str, fmt: str, bbox: list[float]
    ) -> list[str]:
        """Resolve the archive download URL(s) for one archive product.

        `.7z` (`dependency_ratios`) is per-continent — the AOI's continent
        selects the record; `.zip` (`future_pop`) is per-SSP — `self._ssp`
        selects the archive.

        Raises:
            ValueError: If no record / archive matches the continent or SSP.
        """
        records = global_records(product, subalias_id)
        if fmt == "7z":
            continent = continent_for_bbox(bbox)
            record = next(
                (r for r in records if continent.lower() in r.get("title", "").lower()),
                None,
            )
            if record is None:
                titles = [r.get("title") for r in records]
                raise ValueError(
                    f"WorldPop {product!r} has no {continent!r} archive; "
                    f"available: {titles}."
                )
            return record_archive_files(product, subalias_id, record["id"], "7z")
        # zip (future_pop): a single record whose files are the per-SSP archives.
        urls = record_archive_files(product, subalias_id, records[0]["id"], "zip")
        wanted = [u for u in urls if self._ssp.lower() in Path(u).name.lower()]
        if not wanted:
            names = [Path(u).name for u in urls]
            raise ValueError(
                f"WorldPop {product!r} has no {self._ssp!r} archive; available: {names}."
            )
        return wanted

    def _select_archive_members(self, members: list[Path], fmt: str) -> list[Path]:
        """Filter extracted GeoTIFFs — by requested year for the per-year `.zip`.

        The `.7z` continent products are a single year (all members kept); the
        `.zip` SSP projections are per-year, so keep only members whose
        filename carries one of the requested years.
        """
        if fmt != "zip":
            return members
        wanted_years = {str(y) for y in self._years()}
        selected = [
            m for m in members if set(re.findall(r"(\d{4})", m.stem)) & wanted_years
        ]
        return selected or members

    def _crop_archive_member(self, tif: Path, product: str, bbox: list[float]) -> Path:
        """Crop one extracted GeoTIFF to the AOI bbox (reproject if `crs != 4326`)."""
        from pyramids.dataset import Dataset

        dataset = Dataset.read_file(str(tif))
        cropped = crop_to_aoi(dataset, self.space, bbox=bbox, touch=True)
        if self._output_epsg != 4326:
            cropped = cropped.to_crs(self._output_epsg)
        target = Path(self.path) / f"{product}_{tif.stem}_{self._resolution}.tif"
        cropped.to_file(str(target))
        return target

__init__(start, end, variables, lat_lim, lon_lim, temporal_resolution='yearly', path='', fmt='%Y-%m-%d', *, aoi=None, constrained=False, unadjusted=True, resolution='100m', scope='countries', generation='R2021', level='national', year=None, years=None, crs='EPSG:4326', api='rest', ssp='SSP2', allow_large_archive=False, catalog=None) #

Initialise a WorldPop backend instance.

Resolves and statically validates every requested product + sub-alias selector against the catalog before the parent constructor runs (the parent calls _initialize first). The AOI is resolved to a set of ISO3 codes here too, since _initialize receives no bbox.

Parameters:

Name Type Description Default
start str

Inclusive start of the date window (parsed with fmt); its year selects the first WorldPop year in range.

required
end str

Inclusive end of the date window.

required
variables list[str]

WorldPop product keys — canonical ("pop") or friendly aliases ("population", "age_sex", …).

required
lat_lim list[float]

[lat_min, lat_max] in degrees.

required
lon_lim list[float]

[lon_min, lon_max] in degrees.

required
temporal_resolution str

Advisory label only (WorldPop years are annual points); accepted for facade parity. Defaults to "yearly".

'yearly'
path Path | str

Output directory. Created by the parent class.

''
fmt str

strptime format for start / end.

'%Y-%m-%d'
aoi str | list[str] | list[float] | object | None

Explicit AOI — an ISO3 string, a list of ISO3 strings, a [w, s, e, n] bbox, or a GeoDataFrame. None (default) derives the ISO3 set from lat_lim / lon_lim.

None
constrained bool

Settlement-masked constrained variant (True) vs unconstrained (False, default).

False
unadjusted bool

Raw variant (True, default → wpgp) vs the UN-adjusted variant (Falsewpgpunadj).

True
resolution str

"100m" (default) or "1km".

'100m'
scope str

"countries" (per-ISO3, default) or "global" (the global mosaic, where the product offers one).

'countries'
generation str

Product generation — "R2021" (default, the classic 2000–2020 line) or a Global-2 line ("R2025A", …).

'R2021'
level str

"national" (default) or "subnational" — only the population-weighted-density (pwd) product offers both.

'national'
year int | None

A single year to fetch (overrides the date window).

None
years list[int] | None

An explicit list of years (overrides the date window and year).

None
crs str

Output CRS as an EPSG string / code (default "EPSG:4326" — WorldPop's native CRS, so no reproject).

'EPSG:4326'
api str

Access path — "rest" (default; direct REST + pyramids, no optional SDK) or "worldpoppy" (the optional SDK via its file cache).

'rest'
ssp str

SSP scenario for the future_pop .zip archives ("SSP1""SSP5"; default "SSP2"). Ignored by other products.

'SSP2'
allow_large_archive bool

Opt-in required to download the multi-GB future_pop per-SSP .zip archives (~4 GB each). Defaults to False.

False
catalog Catalog | None

Optional pre-built Catalog (tests inject a faked one); defaults to the bundled catalog.

None

Raises:

Type Description
ValueError

When variables is empty, a product / alias is unknown, the selector tuple matches no sub-alias, or resolution / scope / generation / api is malformed.

ImportError

When api="worldpoppy" but the [worldpop] extra is not installed.

Source code in src/earthlens/worldpop/backend.py
def __init__(
    self,
    start: str,
    end: str,
    variables: list[str],
    lat_lim: list[float],
    lon_lim: list[float],
    temporal_resolution: str = "yearly",
    path: Path | str = "",
    fmt: str = "%Y-%m-%d",
    *,
    aoi: str | list[str] | list[float] | object | None = None,
    constrained: bool = False,
    unadjusted: bool = True,
    resolution: str = "100m",
    scope: str = "countries",
    generation: str = "R2021",
    level: str = "national",
    year: int | None = None,
    years: list[int] | None = None,
    crs: str = "EPSG:4326",
    api: str = "rest",
    ssp: str = "SSP2",
    allow_large_archive: bool = False,
    catalog: Catalog | None = None,
):
    """Initialise a WorldPop backend instance.

    Resolves and statically validates every requested product +
    sub-alias selector against the catalog **before** the parent
    constructor runs (the parent calls `_initialize` first). The AOI is
    resolved to a set of ISO3 codes here too, since `_initialize`
    receives no bbox.

    Args:
        start: Inclusive start of the date window (parsed with `fmt`);
            its year selects the first WorldPop year in range.
        end: Inclusive end of the date window.
        variables: WorldPop product keys — canonical (`"pop"`) or
            friendly aliases (`"population"`, `"age_sex"`, …).
        lat_lim: `[lat_min, lat_max]` in degrees.
        lon_lim: `[lon_min, lon_max]` in degrees.
        temporal_resolution: Advisory label only (WorldPop years are
            annual points); accepted for facade parity. Defaults to
            `"yearly"`.
        path: Output directory. Created by the parent class.
        fmt: `strptime` format for `start` / `end`.
        aoi: Explicit AOI — an ISO3 string, a list of ISO3 strings, a
            `[w, s, e, n]` bbox, or a `GeoDataFrame`. `None` (default)
            derives the ISO3 set from `lat_lim` / `lon_lim`.
        constrained: Settlement-masked *constrained* variant (`True`)
            vs *unconstrained* (`False`, default).
        unadjusted: Raw variant (`True`, default → `wpgp`) vs the
            UN-adjusted variant (`False` → `wpgpunadj`).
        resolution: `"100m"` (default) or `"1km"`.
        scope: `"countries"` (per-ISO3, default) or `"global"` (the
            global mosaic, where the product offers one).
        generation: Product generation — `"R2021"` (default, the
            classic 2000–2020 line) or a Global-2 line (`"R2025A"`, …).
        level: `"national"` (default) or `"subnational"` — only the
            population-weighted-density (`pwd`) product offers both.
        year: A single year to fetch (overrides the date window).
        years: An explicit list of years (overrides the date window
            and `year`).
        crs: Output CRS as an EPSG string / code (default
            `"EPSG:4326"` — WorldPop's native CRS, so no reproject).
        api: Access path — `"rest"` (default; direct REST + pyramids,
            no optional SDK) or `"worldpoppy"` (the optional SDK via its
            file cache).
        ssp: SSP scenario for the `future_pop` `.zip` archives
            (`"SSP1"`…`"SSP5"`; default `"SSP2"`). Ignored by other
            products.
        allow_large_archive: Opt-in required to download the multi-GB
            `future_pop` per-SSP `.zip` archives (~4 GB each). Defaults
            to `False`.
        catalog: Optional pre-built `Catalog` (tests inject a faked
            one); defaults to the bundled catalog.

    Raises:
        ValueError: When `variables` is empty, a product / alias is
            unknown, the selector tuple matches no sub-alias, or
            `resolution` / `scope` / `generation` / `api` is malformed.
        ImportError: When `api="worldpoppy"` but the `[worldpop]` extra
            is not installed.
    """
    if not variables:
        raise ValueError(
            "WorldPop requires a non-empty `variables` list of product keys, "
            'e.g. ["pop"] or ["population"].'
        )
    if api not in _API_MODES:
        raise ValueError(f"api must be one of {sorted(_API_MODES)}; got {api!r}.")
    if resolution not in _RESOLUTIONS:
        raise ValueError(
            f"resolution must be one of {sorted(_RESOLUTIONS)}; got {resolution!r}."
        )
    if scope not in _SCOPES:
        raise ValueError(f"scope must be one of {sorted(_SCOPES)}; got {scope!r}.")
    if level not in _LEVELS:
        raise ValueError(f"level must be one of {sorted(_LEVELS)}; got {level!r}.")
    if generation not in GENERATIONS:
        raise ValueError(
            f"generation must be one of {list(GENERATIONS)}; got {generation!r}."
        )
    if api == "worldpoppy":
        _require_worldpoppy()

    self._catalog = catalog if catalog is not None else Catalog()
    self._constrained = constrained
    self._unadjusted = unadjusted
    self._resolution = resolution
    self._scope = scope
    self._generation = generation
    self._level = level
    self._year_arg = year
    self._years_arg = years
    self._crs = crs
    self._output_epsg = epsg_int(crs)
    self._api_mode = api
    self._ssp = ssp
    self._allow_large_archive = allow_large_archive
    self._auth = WorldPopAuth()
    self._aggregate_cfg = None
    self._show_progress = True

    # Resolve + statically validate (product + selector → sub-alias) up
    # front; year validation happens once the year list is derived.
    self._products: list[str] = [self._catalog.resolve(v) for v in variables]
    self._subalias_ids: dict[str, str] = {
        product: self._catalog.pick_subalias(
            product,
            constrained=constrained,
            unadjusted=unadjusted,
            resolution=resolution,
            scope=scope,
            generation=generation,
            level=level,
        )
        for product in self._products
    }
    self._guard_unsupported()
    self._iso3s: list[str] = self._resolve_aoi(aoi, lat_lim, lon_lim)

    super().__init__(
        start=start,
        end=end,
        variables=variables,
        temporal_resolution=temporal_resolution,
        lat_lim=lat_lim,
        lon_lim=lon_lim,
        fmt=fmt,
        path=path,
    )

    # A polygon AOI (a GeoDataFrame / geometry, not an ISO3 code or
    # bbox) masks the fetched country mosaics to the exact shape; the
    # ISO3 set above already selected which countries to fetch.
    if aoi is not None and (
        hasattr(aoi, "total_bounds") or hasattr(aoi, "__geo_interface__")
    ):
        _, _, geometry = resolve_aoi(aoi)
        if geometry is not None:
            self._attach_clip_geometry(geometry)

download(progress_bar=True, aggregate=None) #

Fetch the requested products as AOI-cropped GeoTIFFs (+ tables).

Parameters:

Name Type Description Default
progress_bar bool

Whether per-download progress is shown.

True
aggregate

Optional earthlens.aggregate.AggregationConfig; reduces the per-year raster stack across years. It reduces the rasters only — for demographic products the per-cohort age/sex tables are still written per year (the table column is not aggregated). Ignored by the archive products.

None

Returns:

Type Description
list[Path]

list[Path]: The written GeoTIFF / table paths.

Source code in src/earthlens/worldpop/backend.py
def download(self, progress_bar: bool = True, aggregate=None) -> list[Path]:
    """Fetch the requested products as AOI-cropped GeoTIFFs (+ tables).

    Args:
        progress_bar: Whether per-download progress is shown.
        aggregate: Optional `earthlens.aggregate.AggregationConfig`;
            reduces the per-year raster stack across years. It reduces
            the **rasters** only — for demographic products the per-cohort
            age/sex tables are still written per year (the table column is
            not aggregated). Ignored by the archive products.

    Returns:
        list[Path]: The written GeoTIFF / table paths.
    """
    self._show_progress = progress_bar
    self._aggregate_cfg = aggregate
    return self._dispatch()

WorldPopAuth #

Bases: AbstractAuth[WorldPopCredentials]

No-op auth for the open, attribution-only WorldPop data.

Kept for conformance with the AbstractAuth shape the other backends follow; WorldPop reads no credentials. configure() flips an internal flag and is_authenticated() is always True, so the context-manager form (with WorldPopAuth() as auth: ...) works like any other backend's.

Examples:

  • It is always authenticated, with nothing to configure:
    >>> from earthlens.worldpop import WorldPopAuth
    >>> auth = WorldPopAuth()
    >>> auth.is_authenticated()
    True
    >>> auth.configure()  # idempotent no-op
    >>> auth.is_authenticated()
    True
    
Source code in src/earthlens/worldpop/auth.py
class WorldPopAuth(AbstractAuth[WorldPopCredentials]):
    """No-op auth for the open, attribution-only WorldPop data.

    Kept for conformance with the `AbstractAuth` shape the other
    backends follow; WorldPop reads no credentials. `configure()`
    flips an internal flag and `is_authenticated()` is always
    `True`, so the context-manager form (`with WorldPopAuth() as
    auth: ...`) works like any other backend's.

    Examples:
        - It is always authenticated, with nothing to configure:
            ```python
            >>> from earthlens.worldpop import WorldPopAuth
            >>> auth = WorldPopAuth()
            >>> auth.is_authenticated()
            True
            >>> auth.configure()  # idempotent no-op
            >>> auth.is_authenticated()
            True

            ```
    """

    def __init__(self, credentials: WorldPopCredentials | None = None) -> None:
        """Store the (empty) credentials; default to a fresh `WorldPopCredentials`.

        Args:
            credentials: Optional empty credentials object. Defaults to a
                fresh `WorldPopCredentials()` since WorldPop needs no
                secrets.
        """
        super().__init__(
            credentials if credentials is not None else WorldPopCredentials()
        )
        self._configured = False

    def configure(self) -> None:
        """No-op setup — WorldPop is open + attribution-only (nothing to do)."""
        self._configured = True

    def is_authenticated(self) -> bool:
        """Return `True` — open data needs no credentials."""
        return True

__init__(credentials=None) #

Store the (empty) credentials; default to a fresh WorldPopCredentials.

Parameters:

Name Type Description Default
credentials WorldPopCredentials | None

Optional empty credentials object. Defaults to a fresh WorldPopCredentials() since WorldPop needs no secrets.

None
Source code in src/earthlens/worldpop/auth.py
def __init__(self, credentials: WorldPopCredentials | None = None) -> None:
    """Store the (empty) credentials; default to a fresh `WorldPopCredentials`.

    Args:
        credentials: Optional empty credentials object. Defaults to a
            fresh `WorldPopCredentials()` since WorldPop needs no
            secrets.
    """
    super().__init__(
        credentials if credentials is not None else WorldPopCredentials()
    )
    self._configured = False

configure() #

No-op setup — WorldPop is open + attribution-only (nothing to do).

Source code in src/earthlens/worldpop/auth.py
def configure(self) -> None:
    """No-op setup — WorldPop is open + attribution-only (nothing to do)."""
    self._configured = True

is_authenticated() #

Return True — open data needs no credentials.

Source code in src/earthlens/worldpop/auth.py
def is_authenticated(self) -> bool:
    """Return `True` — open data needs no credentials."""
    return True

WorldPopCredentials #

Bases: BaseModel

Empty credentials value object for the open WorldPop backend.

WorldPop needs no secrets; this exists only to satisfy the earthlens.base.auth.AbstractAuth generic contract that every backend's auth class binds a pydantic.BaseModel credentials type. It carries no fields.

Examples:

  • Construct the empty credentials:
    >>> from earthlens.worldpop import WorldPopCredentials
    >>> WorldPopCredentials()
    WorldPopCredentials()
    
Source code in src/earthlens/worldpop/auth.py
class WorldPopCredentials(BaseModel, frozen=True):
    """Empty credentials value object for the open WorldPop backend.

    WorldPop needs no secrets; this exists only to satisfy the
    `earthlens.base.auth.AbstractAuth` generic contract that every
    backend's auth class binds a `pydantic.BaseModel` credentials
    type. It carries no fields.

    Examples:
        - Construct the empty credentials:
            ```python
            >>> from earthlens.worldpop import WorldPopCredentials
            >>> WorldPopCredentials()
            WorldPopCredentials()

            ```
    """

clear_catalog_cache() #

Empty the module-level product parse cache.

Useful in tests that rewrite the catalog on disk and want to force a re-parse. Production callers do not need this — the cache key includes st_mtime_ns, so any real file mutation invalidates the entry on its own.

Source code in src/earthlens/worldpop/catalog.py
def clear_catalog_cache() -> None:
    """Empty the module-level product parse cache.

    Useful in tests that rewrite the catalog on disk and want to force a
    re-parse. Production callers do not need this — the cache key includes
    `st_mtime_ns`, so any real file mutation invalidates the entry on its
    own.
    """
    _CATALOG_CACHE.clear()

earthlens.worldpop.backend #

WorldPop backend — open population data hub over anonymous HTTPS.

WorldPop is a download-and-localise backend (OUTPUT_KIND="mixed"). A request is an AOI (ISO3 / bbox / GeoDataFrame) + time window + a list of WorldPop product aliases (variables=["pop", ...], canonical or friendly) plus constrained / unadjusted / resolution / scope / generation / year(s) / crs / api selectors. The backend resolves each product to a concrete REST sub-alias against the bundled catalog, queries the WorldPop REST API for the matching per-country GeoTIFF URLs, downloads them over anonymous HTTPS, and uses pyramids to mosaic + crop (and reproject only when crs != 4326) — writing population GeoTIFFs and, for demographic products (age_structures), per-cohort rasters plus a tidy age/sex table.

The provider is open, CC-BY-4.0 — no credentials (see earthlens.worldpop.auth). The default api="rest" path needs only the core dependencies (requests + pyramids); the optional api="worldpoppy" path imports worldpoppy lazily and consumes only its file cache (never its xarray return), so the package imports without the [worldpop] extra.

WorldPop #

Bases: AbstractDataSource

Download WorldPop population + demographic products, localised via pyramids.

Attributes:

Name Type Description
OUTPUT_KIND OutputKind

Fixed "mixed" — population products yield GeoTIFFs and demographic products (age_structures) additionally yield a tidy age/sex table, so the facade forwards aggregate=.

Source code in src/earthlens/worldpop/backend.py
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
class WorldPop(AbstractDataSource):
    """Download WorldPop population + demographic products, localised via pyramids.

    Attributes:
        OUTPUT_KIND: Fixed `"mixed"` — population products yield GeoTIFFs
            and demographic products (`age_structures`) additionally yield a
            tidy age/sex table, so the facade forwards `aggregate=`.
    """

    OUTPUT_KIND: OutputKind = "mixed"

    def __init__(
        self,
        start: str,
        end: str,
        variables: list[str],
        lat_lim: list[float],
        lon_lim: list[float],
        temporal_resolution: str = "yearly",
        path: Path | str = "",
        fmt: str = "%Y-%m-%d",
        *,
        aoi: str | list[str] | list[float] | object | None = None,
        constrained: bool = False,
        unadjusted: bool = True,
        resolution: str = "100m",
        scope: str = "countries",
        generation: str = "R2021",
        level: str = "national",
        year: int | None = None,
        years: list[int] | None = None,
        crs: str = "EPSG:4326",
        api: str = "rest",
        ssp: str = "SSP2",
        allow_large_archive: bool = False,
        catalog: Catalog | None = None,
    ):
        """Initialise a WorldPop backend instance.

        Resolves and statically validates every requested product +
        sub-alias selector against the catalog **before** the parent
        constructor runs (the parent calls `_initialize` first). The AOI is
        resolved to a set of ISO3 codes here too, since `_initialize`
        receives no bbox.

        Args:
            start: Inclusive start of the date window (parsed with `fmt`);
                its year selects the first WorldPop year in range.
            end: Inclusive end of the date window.
            variables: WorldPop product keys — canonical (`"pop"`) or
                friendly aliases (`"population"`, `"age_sex"`, …).
            lat_lim: `[lat_min, lat_max]` in degrees.
            lon_lim: `[lon_min, lon_max]` in degrees.
            temporal_resolution: Advisory label only (WorldPop years are
                annual points); accepted for facade parity. Defaults to
                `"yearly"`.
            path: Output directory. Created by the parent class.
            fmt: `strptime` format for `start` / `end`.
            aoi: Explicit AOI — an ISO3 string, a list of ISO3 strings, a
                `[w, s, e, n]` bbox, or a `GeoDataFrame`. `None` (default)
                derives the ISO3 set from `lat_lim` / `lon_lim`.
            constrained: Settlement-masked *constrained* variant (`True`)
                vs *unconstrained* (`False`, default).
            unadjusted: Raw variant (`True`, default → `wpgp`) vs the
                UN-adjusted variant (`False` → `wpgpunadj`).
            resolution: `"100m"` (default) or `"1km"`.
            scope: `"countries"` (per-ISO3, default) or `"global"` (the
                global mosaic, where the product offers one).
            generation: Product generation — `"R2021"` (default, the
                classic 2000–2020 line) or a Global-2 line (`"R2025A"`, …).
            level: `"national"` (default) or `"subnational"` — only the
                population-weighted-density (`pwd`) product offers both.
            year: A single year to fetch (overrides the date window).
            years: An explicit list of years (overrides the date window
                and `year`).
            crs: Output CRS as an EPSG string / code (default
                `"EPSG:4326"` — WorldPop's native CRS, so no reproject).
            api: Access path — `"rest"` (default; direct REST + pyramids,
                no optional SDK) or `"worldpoppy"` (the optional SDK via its
                file cache).
            ssp: SSP scenario for the `future_pop` `.zip` archives
                (`"SSP1"`…`"SSP5"`; default `"SSP2"`). Ignored by other
                products.
            allow_large_archive: Opt-in required to download the multi-GB
                `future_pop` per-SSP `.zip` archives (~4 GB each). Defaults
                to `False`.
            catalog: Optional pre-built `Catalog` (tests inject a faked
                one); defaults to the bundled catalog.

        Raises:
            ValueError: When `variables` is empty, a product / alias is
                unknown, the selector tuple matches no sub-alias, or
                `resolution` / `scope` / `generation` / `api` is malformed.
            ImportError: When `api="worldpoppy"` but the `[worldpop]` extra
                is not installed.
        """
        if not variables:
            raise ValueError(
                "WorldPop requires a non-empty `variables` list of product keys, "
                'e.g. ["pop"] or ["population"].'
            )
        if api not in _API_MODES:
            raise ValueError(f"api must be one of {sorted(_API_MODES)}; got {api!r}.")
        if resolution not in _RESOLUTIONS:
            raise ValueError(
                f"resolution must be one of {sorted(_RESOLUTIONS)}; got {resolution!r}."
            )
        if scope not in _SCOPES:
            raise ValueError(f"scope must be one of {sorted(_SCOPES)}; got {scope!r}.")
        if level not in _LEVELS:
            raise ValueError(f"level must be one of {sorted(_LEVELS)}; got {level!r}.")
        if generation not in GENERATIONS:
            raise ValueError(
                f"generation must be one of {list(GENERATIONS)}; got {generation!r}."
            )
        if api == "worldpoppy":
            _require_worldpoppy()

        self._catalog = catalog if catalog is not None else Catalog()
        self._constrained = constrained
        self._unadjusted = unadjusted
        self._resolution = resolution
        self._scope = scope
        self._generation = generation
        self._level = level
        self._year_arg = year
        self._years_arg = years
        self._crs = crs
        self._output_epsg = epsg_int(crs)
        self._api_mode = api
        self._ssp = ssp
        self._allow_large_archive = allow_large_archive
        self._auth = WorldPopAuth()
        self._aggregate_cfg = None
        self._show_progress = True

        # Resolve + statically validate (product + selector → sub-alias) up
        # front; year validation happens once the year list is derived.
        self._products: list[str] = [self._catalog.resolve(v) for v in variables]
        self._subalias_ids: dict[str, str] = {
            product: self._catalog.pick_subalias(
                product,
                constrained=constrained,
                unadjusted=unadjusted,
                resolution=resolution,
                scope=scope,
                generation=generation,
                level=level,
            )
            for product in self._products
        }
        self._guard_unsupported()
        self._iso3s: list[str] = self._resolve_aoi(aoi, lat_lim, lon_lim)

        super().__init__(
            start=start,
            end=end,
            variables=variables,
            temporal_resolution=temporal_resolution,
            lat_lim=lat_lim,
            lon_lim=lon_lim,
            fmt=fmt,
            path=path,
        )

        # A polygon AOI (a GeoDataFrame / geometry, not an ISO3 code or
        # bbox) masks the fetched country mosaics to the exact shape; the
        # ISO3 set above already selected which countries to fetch.
        if aoi is not None and (
            hasattr(aoi, "total_bounds") or hasattr(aoi, "__geo_interface__")
        ):
            _, _, geometry = resolve_aoi(aoi)
            if geometry is not None:
                self._attach_clip_geometry(geometry)

    def _guard_unsupported(self) -> None:
        """Gate the multi-GB `.zip` archive products behind an explicit opt-in.

        Per-country / global-mosaic GeoTIFF products and the small `.7z`
        per-continent products (`dependency_ratios`) are fetched directly.
        The `future_pop` SSP `.zip` bundles are **~4 GB each** (×5 scenarios),
        so they require `allow_large_archive=True` to avoid a multi-GB
        surprise download.

        Raises:
            NotImplementedError: If a `.zip` archive product is requested
                without `allow_large_archive=True`.
        """
        for product, subalias_id in self._subalias_ids.items():
            sub = self._catalog.subalias(product, subalias_id)
            if sub.archive == "zip" and not self._allow_large_archive:
                raise NotImplementedError(
                    f"WorldPop {product!r} ({subalias_id!r}) ships as ~4 GB per-SSP "
                    ".zip archives (×5 scenarios). Pass allow_large_archive=True "
                    "(and an ssp=, e.g. ssp='SSP2') to opt into the large download."
                )

    def _resolve_aoi(
        self,
        aoi: str | list[str] | list[float] | object | None,
        lat_lim: list[float],
        lon_lim: list[float],
    ) -> list[str]:
        """Resolve the AOI to a sorted list of ISO3 country codes.

        Args:
            aoi: An ISO3 string, a list of ISO3 strings, a `[w, s, e, n]`
                bbox, a `GeoDataFrame`, or `None` (derive from the bbox).
            lat_lim: `[lat_min, lat_max]` used when `aoi` is `None`.
            lon_lim: `[lon_min, lon_max]` used when `aoi` is `None`.

        Returns:
            list[str]: The intersecting / requested ISO3 codes, sorted.
        """
        if isinstance(aoi, str):
            return [normalise_iso3(aoi)]
        if isinstance(aoi, list) and aoi and isinstance(aoi[0], str):
            return sorted({normalise_iso3(code) for code in aoi})
        if isinstance(aoi, list) and len(aoi) == 4 and isinstance(aoi[0], (int, float)):
            bbox = [float(x) for x in aoi]
        elif aoi is not None and hasattr(aoi, "total_bounds"):  # a GeoDataFrame
            crs = getattr(aoi, "crs", None)
            if crs is not None and crs.to_epsg() != 4326:
                aoi = aoi.to_crs(4326)
            bbox = [float(x) for x in aoi.total_bounds]
        else:
            bbox = [lon_lim[0], lat_lim[0], lon_lim[1], lat_lim[1]]
        return iso3_for_bbox(bbox, load_iso3_bbox())

    def _initialize(self):
        """Configure the (no-op) auth; no network client is created.

        Returns:
            None: WorldPop is open + anonymous, so the parent binds no
                `self.client`.
        """
        self._auth.configure()
        return None

    def _create_grid(self, lat_lim: list, lon_lim: list) -> SpatialExtent:
        """Wrap the user bbox into a `SpatialExtent`.

        Args:
            lat_lim: `[lat_min, lat_max]` in degrees.
            lon_lim: `[lon_min, lon_max]` in degrees.

        Returns:
            SpatialExtent: Validated, frozen bbox (WGS84).
        """
        return SpatialExtent.from_pairs(lat_lim=lat_lim, lon_lim=lon_lim)

    def _check_input_dates(
        self,
        start: str,
        end: str,
        temporal_resolution: str,
        fmt: str,
    ) -> TemporalExtent:
        """Parse the date window into a `TemporalExtent`.

        The window's years select the WorldPop years in range; the
        per-year expansion happens in `_years`.

        Args:
            start: Inclusive start of the window.
            end: Inclusive end of the window.
            temporal_resolution: Advisory label (ignored).
            fmt: `strptime` format applied to `start` / `end`.

        Returns:
            TemporalExtent: Frozen model with the parsed bounds.

        Raises:
            ValueError: If `start` parses to a date later than `end`.
        """
        start_dt = dt.datetime.strptime(start, fmt)
        end_dt = dt.datetime.strptime(end, fmt)
        dates = pd.date_range(start_dt, end_dt, freq="YS")
        return TemporalExtent(
            start_date=start_dt,
            end_date=end_dt,
            resolution="YS",
            dates=dates,
        )

    def _years(self) -> list[int]:
        """Return the explicit years to fetch (from `years` / `year` / window).

        Returns:
            list[int]: Sorted, de-duplicated years. `years=` wins, then
                `year=`, else every year spanned by `start`/`end`.
        """
        if self._years_arg is not None:
            return sorted({int(y) for y in self._years_arg})
        if self._year_arg is not None:
            return [int(self._year_arg)]
        return sorted({d.year for d in self.time.dates})

    def _search(self) -> list[RemoteProduct]:
        """Plan the download — one `RemoteProduct` per `(product, iso3, year, file)`.

        Queries the REST API once per `(product, iso3)` (records carry every
        year) and filters client-side to the requested years. For
        demographic products each year yields many cohort files; for plain
        population products, one.

        Returns:
            list[RemoteProduct]: One item per GeoTIFF URL to download, each
                carrying `product` / `iso3` / `year` / `demographic` /
                `subalias` metadata.
        """
        out: list[RemoteProduct] = []
        years = self._years()
        if self._api_mode == "worldpoppy":
            # The WorldPopPy SDK resolves files itself; the plan is just the
            # (product, iso3, year) cross-product (no REST query, no URLs).
            for product in self._products:
                demographic = self._catalog.get(product).demographic
                for iso3 in self._iso3s:
                    for year in years:
                        out.append(
                            RemoteProduct(
                                id=f"{product}_{iso3}_{year}",
                                href=None,
                                metadata={
                                    "product": product,
                                    "iso3": iso3,
                                    "year": year,
                                    "demographic": demographic,
                                },
                            )
                        )
            return out
        for product in self._products:
            subalias_id = self._subalias_ids[product]
            demographic = self._catalog.get(product).demographic
            if self._catalog.subalias(product, subalias_id).scope == "global":
                out.extend(self._plan_global(product, subalias_id, demographic, years))
            else:
                out.extend(
                    self._plan_countries(product, subalias_id, demographic, years)
                )
        return out

    def _plan_countries(
        self, product: str, subalias_id: str, demographic: bool, years: list[int]
    ) -> list[RemoteProduct]:
        """Plan per-country downloads for one product (records once per ISO3).

        Covariate layers are **undated** (one record, `popyear` is `None`),
        so they are planned once per ISO3 with the year read from the
        filename rather than looped over the requested years.
        """
        endpoint = self._catalog.get(product).endpoint()
        out: list[RemoteProduct] = []
        for iso3 in self._iso3s:
            records = rest_records(endpoint, subalias_id, iso3)
            undated = not any(rec.get("popyear") for rec in records)
            for year in [None] if undated else years:
                for url in files_for_year(records, year):
                    resolved_year = year if year is not None else _year_in(url)
                    out.append(
                        RemoteProduct(
                            id=f"{product}_{iso3}_{resolved_year}_{Path(url).stem}",
                            href=url,
                            metadata={
                                "product": product,
                                "iso3": iso3,
                                "year": resolved_year,
                                "subalias": subalias_id,
                                "demographic": demographic,
                            },
                        )
                    )
        return out

    def _plan_global(
        self, product: str, subalias_id: str, demographic: bool, years: list[int]
    ) -> list[RemoteProduct]:
        """Plan global-mosaic downloads for one product (no ISO3; `?id=` detail).

        A global mosaic is one whole-world GeoTIFF per year (or one per
        age/sex cohort), downloaded once and cropped to the AOI bbox by the
        localise step — there is no per-country mosaic.
        """
        out: list[RemoteProduct] = []
        for year in years:
            for url in global_files_for_year(product, subalias_id, year):
                out.append(
                    RemoteProduct(
                        id=f"{product}_global_{year}_{Path(url).stem}",
                        href=url,
                        metadata={
                            "product": product,
                            "iso3": "global",
                            "year": year,
                            "subalias": subalias_id,
                            "demographic": demographic,
                        },
                    )
                )
        return out

    def _raw_dir(self) -> Path:
        """Return (creating) the directory raw per-country downloads land in."""
        raw = self.root_dir / _RAW_DIRNAME
        raw.mkdir(parents=True, exist_ok=True)
        return raw

    def _http_get(self, url: str, dest: Path) -> Path:
        """Download `url` to `dest`, skipping when the file already exists.

        Transient connection / timeout errors are retried up to
        `_MAX_RETRIES` with exponential backoff; an HTTP status error (e.g.
        404) propagates immediately without retry.

        Args:
            url: The GeoTIFF URL.
            dest: Local destination path.

        Returns:
            Path: `dest`.

        Raises:
            requests.HTTPError: On a non-2xx response (the URL is named).
            requests.ConnectionError | requests.Timeout: If every retry of a
                transient network error is exhausted.
        """
        if dest.exists() and dest.stat().st_size > 0:
            return dest
        http = HttpClient(
            session=_RequestsGet(),
            retry_on_exceptions=(requests.ConnectionError, requests.Timeout),
            status_forcelist=(),
            max_retries=_MAX_RETRIES - 1,
            backoff_factor=_BACKOFF_BASE,
            max_backoff=None,
            timeout=_HTTP_TIMEOUT,
            sleep=lambda seconds: time.sleep(seconds),
        )
        resp = http.get(url)
        dest.write_bytes(resp.content)
        return dest

    def _group_for_mosaic(
        self, products: list[RemoteProduct]
    ) -> dict[
        tuple[str, int, tuple[str, int] | None], list[tuple[Path, RemoteProduct]]
    ]:
        """Download every product and group the files for mosaicking.

        Groups by `(product, year, cohort)` so multi-country requests merge
        correctly and `age_structures` keeps each age/sex cohort separate.

        Args:
            products: The `_search` result.

        Returns:
            A mapping `(product, year, cohort) -> [(local_path, product), …]`.
        """
        raw = self._raw_dir()
        paths = Parallel(n_jobs=_DOWNLOAD_JOBS, prefer="threads")(
            delayed(self._http_get)(rp.href, raw / Path(rp.href).name)
            for rp in products
        )
        groups: dict[
            tuple[str, int, tuple[str, int] | None], list[tuple[Path, RemoteProduct]]
        ] = {}
        for path, rp in zip(paths, products):
            key = (rp.metadata["product"], rp.metadata["year"], cohort_of(rp.href))
            groups.setdefault(key, []).append((path, rp))
        return groups

    def _fetch(self, products: list[RemoteProduct]) -> list[Path]:
        """Download, localise, tabularise demographics, and optionally aggregate.

        Downloads (idempotently, in parallel), mosaics + crops each
        `(product, year, cohort)` group to the AOI, writes a tidy age/sex
        table for demographic products, and — when `aggregate=` was passed
        to `download` — reduces the per-year rasters across years.

        Args:
            products: The `_search` result.

        Returns:
            list[Path]: The written GeoTIFF and table paths (the reduced
                per-window rasters replace the per-year rasters when
                `aggregate=` is set; tables are always included).
        """
        if self._api_mode == "worldpoppy":
            return self._fetch_via_worldpoppy(products)
        return self._finish(self._group_for_mosaic(products))

    def _finish(
        self,
        groups: dict[
            tuple[str, int, tuple[str, int] | None], list[tuple[Path, RemoteProduct]]
        ],
    ) -> list[Path]:
        """Localise each group, write demographic tables, and optionally aggregate.

        Shared tail of both the REST and WorldPopPy fetch paths.

        Args:
            groups: The `(product, year, cohort) -> [(path, product), …]`
                map of downloaded / cached per-country tiles.

        Returns:
            list[Path]: The written GeoTIFF + table paths (reduced
                per-window rasters replace per-year rasters when
                `aggregate=` is set).
        """
        localised: dict[tuple[str, int, tuple[str, int] | None], Path] = {
            key: self._localise(group) for key, group in groups.items()
        }
        tables = self._write_demographic_tables(localised)
        if self._aggregate_cfg is not None:
            rasters = self._aggregate_years(localised, self._aggregate_cfg)
        else:
            rasters = list(localised.values())
        self._sweep_intermediates()
        return rasters + tables

    def _sweep_intermediates(self) -> None:
        """Best-effort removal of leftover `*_merged.tif` mosaics.

        `_localise` deletes each intermediate inline, but on Windows the GDAL
        handle may still be open at that point. Once the per-`_localise`
        datasets are out of scope, a `gc.collect()` releases the handles, so
        this final sweep clears any that survived. Failures are ignored — the
        files live in the hidden raw cache dir and are harmless.
        """
        import gc

        gc.collect()
        raw = self._raw_dir()
        # _localise writes the intermediate with a leading dot, so match both.
        leftovers = list(raw.glob("*_merged.tif")) + list(raw.glob(".*_merged.tif"))
        for leftover in leftovers:
            try:
                leftover.unlink()
            except OSError:
                pass

    def _write_demographic_tables(
        self, localised: dict[tuple[str, int, tuple[str, int] | None], Path]
    ) -> list[Path]:
        """Write a tidy age/sex table per `(product, year)` for demographic products.

        For each cohort raster of a demographic product (`age_structures`),
        the AOI population total is summed and emitted as one tidy row
        `{aoi, year, sex, age_low, population}`; the rows for a
        `(product, year)` are written to `{product}_{year}.csv` alongside
        the per-cohort GeoTIFFs.

        Args:
            localised: The `(product, year, cohort) -> output_path` map.

        Returns:
            list[Path]: The written table paths (empty if no demographic
                product was requested).
        """
        rows_by_table: dict[tuple[str, int], list[dict[str, object]]] = {}
        aoi_label = "+".join(self._iso3s) if self._iso3s else "aoi"
        for (product, year, cohort), path in localised.items():
            if cohort is None or not self._catalog.get(product).demographic:
                continue
            sex, age_low = cohort
            rows_by_table.setdefault((product, year), []).append(
                {
                    "aoi": aoi_label,
                    "year": year,
                    "sex": sex,
                    "age_low": age_low,
                    "population": _zonal_sum(path),
                }
            )
        out: list[Path] = []
        for (product, year), rows in rows_by_table.items():
            frame = pd.DataFrame(rows).sort_values(["sex", "age_low"])
            target = Path(self.path) / f"{product}_{year}.csv"
            frame.to_csv(target, index=False)
            out.append(target)
        return out

    def _aggregate_years(
        self,
        localised: dict[tuple[str, int, tuple[str, int] | None], Path],
        cfg,
    ) -> list[Path]:
        """Reduce the per-year rasters across years, bucketed by `cfg.freq`.

        Groups the localised rasters by `(product, cohort)`, buckets their
        years by the pandas offset `cfg.freq`, reduces each bucket with
        `cfg.op` (`auto` → `mean` for population), and writes one GeoTIFF
        per window.

        Args:
            localised: The `(product, year, cohort) -> output_path` map.
            cfg: An `earthlens.aggregate.AggregationConfig`.

        Returns:
            list[Path]: One reduced GeoTIFF per `(product, cohort, window)`.
        """
        from pyramids.dataset import Dataset

        op = "mean" if cfg.op == "auto" else cfg.op
        by_series: dict[tuple[str, tuple[str, int] | None], dict[int, Path]] = {}
        for (product, year, cohort), path in localised.items():
            by_series.setdefault((product, cohort), {})[year] = path

        out: list[Path] = []
        for (product, cohort), year_paths in by_series.items():
            years = sorted(year_paths)
            index = pd.to_datetime([f"{y}-01-01" for y in years])
            series = pd.Series(years, index=index)
            for window_label, bucket in series.groupby(pd.Grouper(freq=cfg.freq)):
                bucket_years = list(bucket.values)
                if not bucket_years:
                    continue
                template = Dataset.read_file(str(year_paths[bucket_years[0]]))
                stack = np.stack(
                    [
                        _masked_array(Dataset.read_file(str(year_paths[y])))
                        for y in bucket_years
                    ]
                )
                with warnings.catch_warnings():
                    # All-no-data cells reduce to NaN; that is expected for
                    # ocean / outside-AOI pixels, so silence the empty-slice
                    # RuntimeWarning numpy emits for them.
                    warnings.simplefilter("ignore", RuntimeWarning)
                    reduced = _REDUCERS[op](stack, axis=0)
                tag = f"_{cohort[0]}_{cohort[1]}" if cohort else ""
                target = (
                    Path(self.path)
                    / f"{product}{tag}_{cfg.freq}_{window_label:%Y%m%d}_{op}.tif"
                )
                Dataset.create_from_array(
                    arr=reduced, geo=template.geotransform, epsg=template.epsg
                ).to_file(str(target))
                out.append(target)
        return out

    def _fetch_via_worldpoppy(self, products: list[RemoteProduct]) -> list[Path]:
        """Fetch via the optional WorldPopPy SDK — through its file cache only.

        Calls `wp_raster(..., download_dry_run=True)` to populate the SDK's
        on-disk cache, **discards the returned `xarray.DataArray`** (CLAUDE.md
        forbids importing xarray in `src/`), then reads the cached GeoTIFFs
        from `get_cache_dir()` and runs them through the same localise /
        table / aggregate tail as the REST path.

        Args:
            products: The `_search` plan (one item per product / iso3 /
                year); used to bound which cached files are consumed.

        Returns:
            list[Path]: The written GeoTIFF + table paths.

        Raises:
            ValueError: If a requested product has no `worldpoppy_id`.
        """
        from worldpoppy import get_cache_dir, wp_raster

        years = self._years()
        cache = Path(get_cache_dir())
        groups: dict[
            tuple[str, int, tuple[str, int] | None], list[tuple[Path, RemoteProduct]]
        ] = {}
        for product in self._products:
            wp_id = self._catalog.get(product).worldpoppy_id
            if not wp_id:
                raise ValueError(
                    f"{product!r} has no worldpoppy_id mapping; use api='rest'."
                )
            demographic = self._catalog.get(product).demographic
            # Snapshot the cache around each call so the files this product
            # produced are attributed to it by provenance, not by filename
            # convention. If the product was already fully cached (no new
            # files), fall back to demographic-vs-cohort matching across the
            # cache for this product.
            before = set(cache.rglob("*.tif"))
            wp_raster(
                product_name=wp_id,
                aoi=self._iso3s,
                years=years,
                download_dry_run=True,  # the returned xarray.DataArray is discarded
            )
            produced = set(cache.rglob("*.tif")) - before
            if not produced:
                produced = set(cache.rglob("*.tif"))
            for tif in sorted(produced):
                match = re.search(r"_(\d{4})\.tif$", tif.name)
                if match is None:
                    continue
                year = int(match.group(1))
                iso3 = tif.name[:3].upper()
                cohort = cohort_of(tif.name)
                if iso3 not in self._iso3s or year not in years:
                    continue
                if demographic != (cohort is not None):
                    continue
                rp = RemoteProduct(
                    id=f"{product}_{iso3}_{year}_{tif.stem}",
                    href=str(tif),
                    metadata={
                        "product": product,
                        "iso3": iso3,
                        "year": year,
                        "demographic": demographic,
                    },
                )
                groups.setdefault((product, year, cohort), []).append((tif, rp))
        return self._finish(groups)

    def _localise(self, group: list[tuple[Path, RemoteProduct]]) -> Path:
        """Mosaic the per-country GeoTIFFs of one group + crop to the AOI.

        WorldPop is WGS84 (EPSG:4326) natively, so no reproject happens
        unless `crs != 4326`. The crop bbox is always WGS84 regardless of
        the output CRS (pyramids reprojects the bbox).

        Args:
            group: `[(local_path, product), …]` for one `(product, year,
                cohort)` — the per-country tiles to merge.

        Returns:
            Path: The written AOI-cropped GeoTIFF under `self.path`.
        """
        from pyramids.dataset import Dataset
        from pyramids.dataset.merge import merge_rasters

        tifs = [str(path) for path, _ in group]
        rp = group[0][1]
        product = rp.metadata["product"]
        year = rp.metadata["year"]
        dst_crs = self._output_epsg if self._output_epsg != 4326 else None

        work = self._raw_dir() / f".{product}_{year}_{Path(rp.href).stem}_merged.tif"
        merge_rasters(
            tifs,
            str(work),
            method="last",
            dst_crs=dst_crs,
            no_data_value=_WORLDPOP_NODATA,
        )
        dataset = Dataset.read_file(str(work))
        cropped = crop_to_aoi(
            dataset,
            self.space,
            bbox=[
                self.space.west,
                self.space.south,
                self.space.east,
                self.space.north,
            ],
            touch=True,
        )
        cohort = cohort_of(rp.href)
        tag = f"_{cohort[0]}_{cohort[1]}" if cohort else ""
        target = Path(self.path) / f"{product}_{year}{tag}_{self._resolution}.tif"
        cropped.to_file(str(target))
        # Best-effort cleanup of the intermediate mosaic; on Windows the GDAL
        # handle may still hold it open, in which case it stays in the raw
        # cache dir (harmless — a distinct name per group).
        try:
            work.unlink(missing_ok=True)
        except OSError:
            pass
        return target

    def _archive_products(self) -> list[str]:
        """Return the requested products whose sub-alias is archive-distributed."""
        return [
            product
            for product in self._products
            if self._catalog.subalias(product, self._subalias_ids[product]).archive
        ]

    def _dispatch(self) -> list[Path]:
        """Route the request to the archive path or the GeoTIFF search/fetch.

        Archive products (`.7z` / `.zip`) and plain GeoTIFF products cannot
        be combined in one request — they take different fetch paths.

        Raises:
            ValueError: If the request mixes archive and GeoTIFF products.
        """
        archive = self._archive_products()
        if archive and len(archive) != len(self._products):
            raise ValueError(
                "WorldPop cannot mix archive products "
                f"({archive}) with GeoTIFF products in one request; fetch them "
                "separately."
            )
        if archive:
            return self._fetch_archive()
        return self._api_via_search_fetch()

    def _api(self) -> list[Path]:
        """Dispatch the request (archive path or GeoTIFF search/fetch)."""
        return self._dispatch()

    def download(self, progress_bar: bool = True, aggregate=None) -> list[Path]:
        """Fetch the requested products as AOI-cropped GeoTIFFs (+ tables).

        Args:
            progress_bar: Whether per-download progress is shown.
            aggregate: Optional `earthlens.aggregate.AggregationConfig`;
                reduces the per-year raster stack across years. It reduces
                the **rasters** only — for demographic products the per-cohort
                age/sex tables are still written per year (the table column is
                not aggregated). Ignored by the archive products.

        Returns:
            list[Path]: The written GeoTIFF / table paths.
        """
        self._show_progress = progress_bar
        self._aggregate_cfg = aggregate
        return self._dispatch()

    def _fetch_archive(self) -> list[Path]:
        """Fetch archive products (`.7z` / `.zip`): download, extract, crop.

        `dependency_ratios` ships one small `.7z` per continent (the AOI's
        continent is resolved); `future_pop` ships one ~4 GB `.zip` per SSP
        scenario (`ssp=`). Each archive's GeoTIFF members are extracted and
        cropped to the AOI bbox.

        Returns:
            list[Path]: One cropped GeoTIFF per extracted archive member
                (year-filtered for the per-year `.zip` products).
        """
        out: list[Path] = []
        bbox = [self.space.west, self.space.south, self.space.east, self.space.north]
        for product in self._products:
            subalias_id = self._subalias_ids[product]
            fmt = self._catalog.subalias(product, subalias_id).archive
            for url in self._archive_urls(product, subalias_id, fmt, bbox):
                local = self._http_get(url, self._raw_dir() / Path(url).name)
                extract_dir = self._raw_dir() / f".{product}_{Path(url).stem}_extract"
                members = extract_geotiffs(local, fmt, extract_dir)
                for tif in self._select_archive_members(members, fmt):
                    out.append(self._crop_archive_member(tif, product, bbox))
        return out

    def _archive_urls(
        self, product: str, subalias_id: str, fmt: str, bbox: list[float]
    ) -> list[str]:
        """Resolve the archive download URL(s) for one archive product.

        `.7z` (`dependency_ratios`) is per-continent — the AOI's continent
        selects the record; `.zip` (`future_pop`) is per-SSP — `self._ssp`
        selects the archive.

        Raises:
            ValueError: If no record / archive matches the continent or SSP.
        """
        records = global_records(product, subalias_id)
        if fmt == "7z":
            continent = continent_for_bbox(bbox)
            record = next(
                (r for r in records if continent.lower() in r.get("title", "").lower()),
                None,
            )
            if record is None:
                titles = [r.get("title") for r in records]
                raise ValueError(
                    f"WorldPop {product!r} has no {continent!r} archive; "
                    f"available: {titles}."
                )
            return record_archive_files(product, subalias_id, record["id"], "7z")
        # zip (future_pop): a single record whose files are the per-SSP archives.
        urls = record_archive_files(product, subalias_id, records[0]["id"], "zip")
        wanted = [u for u in urls if self._ssp.lower() in Path(u).name.lower()]
        if not wanted:
            names = [Path(u).name for u in urls]
            raise ValueError(
                f"WorldPop {product!r} has no {self._ssp!r} archive; available: {names}."
            )
        return wanted

    def _select_archive_members(self, members: list[Path], fmt: str) -> list[Path]:
        """Filter extracted GeoTIFFs — by requested year for the per-year `.zip`.

        The `.7z` continent products are a single year (all members kept); the
        `.zip` SSP projections are per-year, so keep only members whose
        filename carries one of the requested years.
        """
        if fmt != "zip":
            return members
        wanted_years = {str(y) for y in self._years()}
        selected = [
            m for m in members if set(re.findall(r"(\d{4})", m.stem)) & wanted_years
        ]
        return selected or members

    def _crop_archive_member(self, tif: Path, product: str, bbox: list[float]) -> Path:
        """Crop one extracted GeoTIFF to the AOI bbox (reproject if `crs != 4326`)."""
        from pyramids.dataset import Dataset

        dataset = Dataset.read_file(str(tif))
        cropped = crop_to_aoi(dataset, self.space, bbox=bbox, touch=True)
        if self._output_epsg != 4326:
            cropped = cropped.to_crs(self._output_epsg)
        target = Path(self.path) / f"{product}_{tif.stem}_{self._resolution}.tif"
        cropped.to_file(str(target))
        return target

__init__(start, end, variables, lat_lim, lon_lim, temporal_resolution='yearly', path='', fmt='%Y-%m-%d', *, aoi=None, constrained=False, unadjusted=True, resolution='100m', scope='countries', generation='R2021', level='national', year=None, years=None, crs='EPSG:4326', api='rest', ssp='SSP2', allow_large_archive=False, catalog=None) #

Initialise a WorldPop backend instance.

Resolves and statically validates every requested product + sub-alias selector against the catalog before the parent constructor runs (the parent calls _initialize first). The AOI is resolved to a set of ISO3 codes here too, since _initialize receives no bbox.

Parameters:

Name Type Description Default
start str

Inclusive start of the date window (parsed with fmt); its year selects the first WorldPop year in range.

required
end str

Inclusive end of the date window.

required
variables list[str]

WorldPop product keys — canonical ("pop") or friendly aliases ("population", "age_sex", …).

required
lat_lim list[float]

[lat_min, lat_max] in degrees.

required
lon_lim list[float]

[lon_min, lon_max] in degrees.

required
temporal_resolution str

Advisory label only (WorldPop years are annual points); accepted for facade parity. Defaults to "yearly".

'yearly'
path Path | str

Output directory. Created by the parent class.

''
fmt str

strptime format for start / end.

'%Y-%m-%d'
aoi str | list[str] | list[float] | object | None

Explicit AOI — an ISO3 string, a list of ISO3 strings, a [w, s, e, n] bbox, or a GeoDataFrame. None (default) derives the ISO3 set from lat_lim / lon_lim.

None
constrained bool

Settlement-masked constrained variant (True) vs unconstrained (False, default).

False
unadjusted bool

Raw variant (True, default → wpgp) vs the UN-adjusted variant (Falsewpgpunadj).

True
resolution str

"100m" (default) or "1km".

'100m'
scope str

"countries" (per-ISO3, default) or "global" (the global mosaic, where the product offers one).

'countries'
generation str

Product generation — "R2021" (default, the classic 2000–2020 line) or a Global-2 line ("R2025A", …).

'R2021'
level str

"national" (default) or "subnational" — only the population-weighted-density (pwd) product offers both.

'national'
year int | None

A single year to fetch (overrides the date window).

None
years list[int] | None

An explicit list of years (overrides the date window and year).

None
crs str

Output CRS as an EPSG string / code (default "EPSG:4326" — WorldPop's native CRS, so no reproject).

'EPSG:4326'
api str

Access path — "rest" (default; direct REST + pyramids, no optional SDK) or "worldpoppy" (the optional SDK via its file cache).

'rest'
ssp str

SSP scenario for the future_pop .zip archives ("SSP1""SSP5"; default "SSP2"). Ignored by other products.

'SSP2'
allow_large_archive bool

Opt-in required to download the multi-GB future_pop per-SSP .zip archives (~4 GB each). Defaults to False.

False
catalog Catalog | None

Optional pre-built Catalog (tests inject a faked one); defaults to the bundled catalog.

None

Raises:

Type Description
ValueError

When variables is empty, a product / alias is unknown, the selector tuple matches no sub-alias, or resolution / scope / generation / api is malformed.

ImportError

When api="worldpoppy" but the [worldpop] extra is not installed.

Source code in src/earthlens/worldpop/backend.py
def __init__(
    self,
    start: str,
    end: str,
    variables: list[str],
    lat_lim: list[float],
    lon_lim: list[float],
    temporal_resolution: str = "yearly",
    path: Path | str = "",
    fmt: str = "%Y-%m-%d",
    *,
    aoi: str | list[str] | list[float] | object | None = None,
    constrained: bool = False,
    unadjusted: bool = True,
    resolution: str = "100m",
    scope: str = "countries",
    generation: str = "R2021",
    level: str = "national",
    year: int | None = None,
    years: list[int] | None = None,
    crs: str = "EPSG:4326",
    api: str = "rest",
    ssp: str = "SSP2",
    allow_large_archive: bool = False,
    catalog: Catalog | None = None,
):
    """Initialise a WorldPop backend instance.

    Resolves and statically validates every requested product +
    sub-alias selector against the catalog **before** the parent
    constructor runs (the parent calls `_initialize` first). The AOI is
    resolved to a set of ISO3 codes here too, since `_initialize`
    receives no bbox.

    Args:
        start: Inclusive start of the date window (parsed with `fmt`);
            its year selects the first WorldPop year in range.
        end: Inclusive end of the date window.
        variables: WorldPop product keys — canonical (`"pop"`) or
            friendly aliases (`"population"`, `"age_sex"`, …).
        lat_lim: `[lat_min, lat_max]` in degrees.
        lon_lim: `[lon_min, lon_max]` in degrees.
        temporal_resolution: Advisory label only (WorldPop years are
            annual points); accepted for facade parity. Defaults to
            `"yearly"`.
        path: Output directory. Created by the parent class.
        fmt: `strptime` format for `start` / `end`.
        aoi: Explicit AOI — an ISO3 string, a list of ISO3 strings, a
            `[w, s, e, n]` bbox, or a `GeoDataFrame`. `None` (default)
            derives the ISO3 set from `lat_lim` / `lon_lim`.
        constrained: Settlement-masked *constrained* variant (`True`)
            vs *unconstrained* (`False`, default).
        unadjusted: Raw variant (`True`, default → `wpgp`) vs the
            UN-adjusted variant (`False` → `wpgpunadj`).
        resolution: `"100m"` (default) or `"1km"`.
        scope: `"countries"` (per-ISO3, default) or `"global"` (the
            global mosaic, where the product offers one).
        generation: Product generation — `"R2021"` (default, the
            classic 2000–2020 line) or a Global-2 line (`"R2025A"`, …).
        level: `"national"` (default) or `"subnational"` — only the
            population-weighted-density (`pwd`) product offers both.
        year: A single year to fetch (overrides the date window).
        years: An explicit list of years (overrides the date window
            and `year`).
        crs: Output CRS as an EPSG string / code (default
            `"EPSG:4326"` — WorldPop's native CRS, so no reproject).
        api: Access path — `"rest"` (default; direct REST + pyramids,
            no optional SDK) or `"worldpoppy"` (the optional SDK via its
            file cache).
        ssp: SSP scenario for the `future_pop` `.zip` archives
            (`"SSP1"`…`"SSP5"`; default `"SSP2"`). Ignored by other
            products.
        allow_large_archive: Opt-in required to download the multi-GB
            `future_pop` per-SSP `.zip` archives (~4 GB each). Defaults
            to `False`.
        catalog: Optional pre-built `Catalog` (tests inject a faked
            one); defaults to the bundled catalog.

    Raises:
        ValueError: When `variables` is empty, a product / alias is
            unknown, the selector tuple matches no sub-alias, or
            `resolution` / `scope` / `generation` / `api` is malformed.
        ImportError: When `api="worldpoppy"` but the `[worldpop]` extra
            is not installed.
    """
    if not variables:
        raise ValueError(
            "WorldPop requires a non-empty `variables` list of product keys, "
            'e.g. ["pop"] or ["population"].'
        )
    if api not in _API_MODES:
        raise ValueError(f"api must be one of {sorted(_API_MODES)}; got {api!r}.")
    if resolution not in _RESOLUTIONS:
        raise ValueError(
            f"resolution must be one of {sorted(_RESOLUTIONS)}; got {resolution!r}."
        )
    if scope not in _SCOPES:
        raise ValueError(f"scope must be one of {sorted(_SCOPES)}; got {scope!r}.")
    if level not in _LEVELS:
        raise ValueError(f"level must be one of {sorted(_LEVELS)}; got {level!r}.")
    if generation not in GENERATIONS:
        raise ValueError(
            f"generation must be one of {list(GENERATIONS)}; got {generation!r}."
        )
    if api == "worldpoppy":
        _require_worldpoppy()

    self._catalog = catalog if catalog is not None else Catalog()
    self._constrained = constrained
    self._unadjusted = unadjusted
    self._resolution = resolution
    self._scope = scope
    self._generation = generation
    self._level = level
    self._year_arg = year
    self._years_arg = years
    self._crs = crs
    self._output_epsg = epsg_int(crs)
    self._api_mode = api
    self._ssp = ssp
    self._allow_large_archive = allow_large_archive
    self._auth = WorldPopAuth()
    self._aggregate_cfg = None
    self._show_progress = True

    # Resolve + statically validate (product + selector → sub-alias) up
    # front; year validation happens once the year list is derived.
    self._products: list[str] = [self._catalog.resolve(v) for v in variables]
    self._subalias_ids: dict[str, str] = {
        product: self._catalog.pick_subalias(
            product,
            constrained=constrained,
            unadjusted=unadjusted,
            resolution=resolution,
            scope=scope,
            generation=generation,
            level=level,
        )
        for product in self._products
    }
    self._guard_unsupported()
    self._iso3s: list[str] = self._resolve_aoi(aoi, lat_lim, lon_lim)

    super().__init__(
        start=start,
        end=end,
        variables=variables,
        temporal_resolution=temporal_resolution,
        lat_lim=lat_lim,
        lon_lim=lon_lim,
        fmt=fmt,
        path=path,
    )

    # A polygon AOI (a GeoDataFrame / geometry, not an ISO3 code or
    # bbox) masks the fetched country mosaics to the exact shape; the
    # ISO3 set above already selected which countries to fetch.
    if aoi is not None and (
        hasattr(aoi, "total_bounds") or hasattr(aoi, "__geo_interface__")
    ):
        _, _, geometry = resolve_aoi(aoi)
        if geometry is not None:
            self._attach_clip_geometry(geometry)

download(progress_bar=True, aggregate=None) #

Fetch the requested products as AOI-cropped GeoTIFFs (+ tables).

Parameters:

Name Type Description Default
progress_bar bool

Whether per-download progress is shown.

True
aggregate

Optional earthlens.aggregate.AggregationConfig; reduces the per-year raster stack across years. It reduces the rasters only — for demographic products the per-cohort age/sex tables are still written per year (the table column is not aggregated). Ignored by the archive products.

None

Returns:

Type Description
list[Path]

list[Path]: The written GeoTIFF / table paths.

Source code in src/earthlens/worldpop/backend.py
def download(self, progress_bar: bool = True, aggregate=None) -> list[Path]:
    """Fetch the requested products as AOI-cropped GeoTIFFs (+ tables).

    Args:
        progress_bar: Whether per-download progress is shown.
        aggregate: Optional `earthlens.aggregate.AggregationConfig`;
            reduces the per-year raster stack across years. It reduces
            the **rasters** only — for demographic products the per-cohort
            age/sex tables are still written per year (the table column is
            not aggregated). Ignored by the archive products.

    Returns:
        list[Path]: The written GeoTIFF / table paths.
    """
    self._show_progress = progress_bar
    self._aggregate_cfg = aggregate
    return self._dispatch()

earthlens.worldpop.catalog #

Product / sub-alias / availability catalog for the WorldPop backend.

The WorldPop hub exposes a three-level REST scheme: a top-level product alias (pop, age_structures, births, …), each with a set of sub-aliases that pin a concrete variant (constrained vs unconstrained, 100 m vs 1 km, per-country vs global mosaic, and the product generation — the classic R2021 line vs the newer Global-2 G2_* lines). A sub-alias maps to a …/{alias}/{subalias} REST path that lists one GeoTIFF record per year.

That matrix is small and slow-changing, so it is curated as config-as-code in the bundled worldpop_data_catalog.yaml and validated here against typed pydantic rows. A request names one or more product keys — canonical ("pop") or a friendly alias ("population") — plus constrained / unadjusted / resolution / scope / generation selectors; Catalog.resolve maps an alias to its canonical product and Catalog.pick_subalias resolves the selectors to a single sub-alias id, raising a ValueError that lists the valid options for the product when no sub-alias matches (did-you-mean).

Catalog #

Bases: AbstractCatalog

Product / sub-alias availability catalog for the WorldPop backend.

Reads the bundled worldpop_data_catalog.yaml and exposes its products: block as a map of Product rows keyed by canonical alias under the inherited datasets field (giving cat["pop"], "pop" in cat, len(cat), and the did-you-mean error for free). Instantiate with no arguments (Catalog()); model_post_init loads and validates the YAML.

Attributes:

Name Type Description
datasets dict[str, Product]

Map from canonical product alias to its Product row.

available_datasets list[str]

Every curated product alias, sorted.

Source code in src/earthlens/worldpop/catalog.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
class Catalog(AbstractCatalog):
    """Product / sub-alias availability catalog for the WorldPop backend.

    Reads the bundled `worldpop_data_catalog.yaml` and exposes its
    `products:` block as a map of `Product` rows keyed by canonical alias
    under the inherited `datasets` field (giving `cat["pop"]`, `"pop" in
    cat`, `len(cat)`, and the did-you-mean error for free). Instantiate
    with no arguments (`Catalog()`); `model_post_init` loads and validates
    the YAML.

    Attributes:
        datasets: Map from canonical product alias to its `Product` row.
        available_datasets: Every curated product alias, sorted.
    """

    _catalog_kind: str = "WorldPop product catalog"
    #: Plural noun for the did-you-mean message ("Known products: …"); the
    #: shared AbstractCatalog reads this (its entries are products, not
    #: "datasets").
    _entry_noun: str = "products"

    datasets: dict[str, Product] = Field(default_factory=dict)

    def model_post_init(self, __context: Any) -> None:
        """Auto-load the bundled catalog when no products were supplied.

        `Catalog()` with no args reads `CATALOG_PATH`; passing
        `datasets=...` skips the disk read (used in tests).

        Raises:
            ValueError: Propagated from `load` when the YAML is missing,
                empty, or has a malformed product row.
        """
        if not self.datasets:
            self.datasets = dict(_load_products(CATALOG_PATH))
        if not self.available_datasets:
            self.available_datasets = sorted(self.datasets)
        self._index_aliases()

    def _index_aliases(self) -> None:
        """Build the alias → canonical-alias lookup from the loaded rows."""
        index: dict[str, str] = {}
        for alias, product in self.datasets.items():
            index[alias.lower()] = alias
            for friendly in product.friendly:
                index[friendly.lower()] = alias
        object.__setattr__(self, "_alias_index", index)

    @classmethod
    def load(cls, catalog_path: Path | None = None) -> Catalog:
        """Read the WorldPop product catalog from disk.

        Args:
            catalog_path: Path to the catalog YAML. Defaults to the
                module-level `CATALOG_PATH`.

        Returns:
            A fully-populated `Catalog` with `datasets` and the
            `available_datasets` index set.

        Raises:
            ValueError: If the file has no `products:` block, or a row
                fails `Product` validation.
        """
        catalog_path = catalog_path if catalog_path is not None else CATALOG_PATH
        products = _load_products(catalog_path)
        return cls(datasets=dict(products), available_datasets=sorted(products))

    def get_catalog(self) -> dict[str, Product]:
        """Return the product map (satisfies the abstract contract)."""
        return self.datasets

    def get(self, alias: str) -> Product:
        """Return the `Product` for a canonical alias, did-you-mean on miss.

        Args:
            alias: A canonical product alias (`"pop"`).

        Returns:
            Product: The matching row.

        Raises:
            ValueError: If `alias` is not a curated product.
        """
        return self.get_dataset(alias)

    def resolve(self, key: str) -> str:
        """Resolve a product key or friendly alias to its canonical alias.

        Args:
            key: A canonical alias (`"pop"`) or a friendly alias
                (`"population"`, case-insensitive).

        Returns:
            str: The canonical product alias.

        Raises:
            ValueError: If `key` matches no product or alias; the message
                lists the known products with a did-you-mean hint.

        Examples:
            - A friendly alias and a canonical key both resolve:
                ```python
                >>> from earthlens.worldpop import Catalog
                >>> cat = Catalog()
                >>> cat.resolve("population")
                'pop'
                >>> cat.resolve("pop")
                'pop'

                ```
        """
        index: dict[str, str] = getattr(self, "_alias_index", {})
        canonical = index.get(key.lower())
        if canonical is not None:
            return canonical
        close = difflib.get_close_matches(key.lower(), index, n=1)
        hint = f" Did you mean {index[close[0]]!r}?" if close else ""
        raise ValueError(
            f"{key!r} is not a known WorldPop product or alias. "
            f"Known products: {sorted(self.datasets)}.{hint}"
        )

    def available_products(self) -> list[str]:
        """Return the curated product aliases, sorted."""
        return sorted(self.datasets)

    def pick_subalias(
        self,
        product: str,
        *,
        constrained: bool = False,
        unadjusted: bool = True,
        resolution: str = "100m",
        scope: str = "countries",
        generation: str = "R2021",
        level: str = "national",
    ) -> str:
        """Resolve the selector kwargs to a single REST sub-alias id.

        A product with exactly one sub-alias (`births`, `urban_change`, …)
        returns it directly — the selector kwargs do not apply, since there
        is only one variant. As a guard against a silently-ignored request,
        a `resolution` that differs from the sole sub-alias's resolution
        emits a `UserWarning` (the other selectors are product-intrinsic for
        single-variant products and are not warned on). Otherwise the kwargs
        must match one sub-alias's
        `(constrained, unadjusted, resolution, scope, generation, level)`
        tuple exactly.

        Args:
            product: A product key or alias (resolved first).
            constrained: Settlement-masked variant (`True`) vs
                unconstrained (`False`).
            unadjusted: Raw (`True`) vs UN-adjusted (`False`).
            resolution: `"100m"` or `"1km"`.
            scope: `"countries"` or `"global"`.
            generation: One of `GENERATIONS`.
            level: `"national"` or `"subnational"` (only `pwd` differs).

        Returns:
            str: The matching sub-alias id (e.g. `"wpgp"`).

        Raises:
            ValueError: If no sub-alias matches the selector; the message
                lists the product's available sub-alias tuples.

        Examples:
            - The classic unconstrained 100 m country series resolves to `wpgp`:
                ```python
                >>> from earthlens.worldpop import Catalog
                >>> Catalog().pick_subalias("pop")
                'wpgp'

                ```
        """
        code = self.resolve(product)
        row = self.datasets[code]
        if len(row.subaliases) == 1:
            only = row.subaliases[0]
            if resolution != only.resolution:
                warnings.warn(
                    f"{code!r} offers only the {only.resolution!r} sub-alias "
                    f"{only.id!r}; the requested resolution={resolution!r} is "
                    "ignored.",
                    UserWarning,
                    stacklevel=2,
                )
            return only.id
        want = (constrained, unadjusted, resolution, scope, generation, level)
        for sub in row.subaliases:
            if sub.selector() == want:
                return sub.id
        options = "\n".join(
            f"  - id={s.id!r} constrained={s.constrained} "
            f"unadjusted={s.unadjusted} resolution={s.resolution!r} "
            f"scope={s.scope!r} generation={s.generation!r} level={s.level!r}"
            for s in row.subaliases
        )
        raise ValueError(
            f"{code!r} has no variant for constrained={constrained}, "
            f"unadjusted={unadjusted}, resolution={resolution!r}, scope={scope!r}, "
            f"generation={generation!r}, level={level!r}. "
            f"Available sub-aliases:\n{options}"
        )

    def subalias(self, product: str, subalias_id: str) -> SubAlias:
        """Return the `SubAlias` row of a product by its REST id.

        Args:
            product: A product key or alias (resolved first).
            subalias_id: A sub-alias id belonging to that product.

        Returns:
            SubAlias: The matching sub-alias row.

        Raises:
            ValueError: If `product` is unknown or has no such sub-alias.

        Examples:
            - Look up a sub-alias and read its scope / resolution:
                ```python
                >>> from earthlens.worldpop import Catalog
                >>> sub = Catalog().subalias("pop", "wpgp")
                >>> sub.scope
                'countries'
                >>> sub.resolution
                '100m'

                ```
        """
        code = self.resolve(product)
        for sub in self.datasets[code].subaliases:
            if sub.id == subalias_id:
                return sub
        raise ValueError(
            f"{code!r} has no sub-alias {subalias_id!r}; "
            f"have {[s.id for s in self.datasets[code].subaliases]}."
        )

    def validate(
        self,
        product: str,
        *,
        constrained: bool = False,
        unadjusted: bool = True,
        resolution: str = "100m",
        scope: str = "countries",
        generation: str = "R2021",
        level: str = "national",
        year: int | None = None,
    ) -> tuple[str, str]:
        """Validate a full request and return `(product, subalias_id)`.

        Resolves the product, picks the sub-alias from the selectors, and —
        when `year` is given — checks the sub-alias offers it.

        Args:
            product: A product key or alias.
            constrained: See `pick_subalias`.
            unadjusted: See `pick_subalias`.
            resolution: See `pick_subalias`.
            scope: See `pick_subalias`.
            generation: See `pick_subalias`.
            level: See `pick_subalias`.
            year: Optional year to check against the sub-alias's `years`.

        Returns:
            tuple[str, str]: The canonical `(product, subalias_id)`.

        Raises:
            ValueError: If the selector matches no sub-alias, or `year` is
                outside the sub-alias's available years.
        """
        code = self.resolve(product)
        subalias_id = self.pick_subalias(
            code,
            constrained=constrained,
            unadjusted=unadjusted,
            resolution=resolution,
            scope=scope,
            generation=generation,
            level=level,
        )
        if year is not None:
            sub = next(s for s in self.datasets[code].subaliases if s.id == subalias_id)
            years = sub.years_set()
            if year not in years:
                raise ValueError(
                    f"{code}/{subalias_id} does not offer year {year}; "
                    f"available years: {sorted(years)}."
                )
        return code, subalias_id

    def describe(self, product: str) -> dict[str, Any]:
        """Return a structured introspection record for a product.

        Mirrors `earthlens.ecmwf.Catalog.describe` / the tropycal catalog: a
        runtime "what does product X expose?" helper a CLI / notebook can
        dump without walking the YAML.

        Args:
            product: A product key or friendly alias (resolved first).

        Returns:
            dict[str, Any]: Keys `product` (canonical alias), `friendly`,
            `kind`, `demographic`, `unit`, and `subaliases` (a list of
            per-variant dicts with `id` / `constrained` / `unadjusted` /
            `resolution` / `scope` / `generation` / `level` / `years`).

        Raises:
            ValueError: If `product` is not a curated product.

        Examples:
            - Describe the population product at a glance:
                ```python
                >>> from earthlens.worldpop import Catalog
                >>> info = Catalog().describe("population")
                >>> info["product"]
                'pop'
                >>> info["kind"]
                'raster'
                >>> info["subaliases"][0]["id"]
                'wpgp'

                ```
        """
        code = self.resolve(product)
        row = self.datasets[code]
        return {
            "product": code,
            "friendly": list(row.friendly),
            "kind": row.kind,
            "demographic": row.demographic,
            "unit": row.unit,
            "description": row.description,
            "endpoint": row.endpoint(),
            "subaliases": [
                {
                    "id": sub.id,
                    "constrained": sub.constrained,
                    "unadjusted": sub.unadjusted,
                    "resolution": sub.resolution,
                    "scope": sub.scope,
                    "generation": sub.generation,
                    "level": sub.level,
                    "years": sub.years,
                }
                for sub in row.subaliases
            ],
        }

    def health(self) -> dict[str, list[str]]:
        """Report structural hygiene issues across the loaded catalog.

        Mirrors `earthlens.ecmwf.Catalog.health` / `earthlens.gee.Catalog.health`:
        returns a mapping `check_name -> sorted list of offenders`. An empty
        list means the check passes. Schema-level invariants (duplicate keys,
        unknown fields) are already enforced at load time — these are the
        residual data-quality checks the pydantic schema cannot express.

        Checks reported:

        * `product_without_subaliases` — products carrying zero sub-aliases.
        * `demographic_not_mixed` — products flagged `demographic` whose
          `kind` is not `"mixed"`.
        * `subalias_unknown_generation` — `"<product>:<id>"` whose
          `generation` is not in `GENERATIONS`.
        * `subalias_bad_years` — `"<product>:<id>"` whose `years` spec does
          not parse.

        Returns:
            dict[str, list[str]]: The per-check offender lists.

        Examples:
            - The bundled catalog is clean:
                ```python
                >>> from earthlens.worldpop import Catalog
                >>> Catalog().health()
                {'product_without_subaliases': [], 'demographic_not_mixed': [], 'subalias_unknown_generation': [], 'subalias_bad_years': []}

                ```
        """
        no_subaliases: list[str] = []
        demographic_not_mixed: list[str] = []
        unknown_generation: list[str] = []
        bad_years: list[str] = []
        for alias, product in self.datasets.items():
            if not product.subaliases:
                no_subaliases.append(alias)
            if product.demographic and product.kind != "mixed":
                demographic_not_mixed.append(alias)
            for sub in product.subaliases:
                if sub.generation not in GENERATIONS:
                    unknown_generation.append(f"{alias}:{sub.id}")
                try:
                    sub.years_set()
                except ValueError:
                    bad_years.append(f"{alias}:{sub.id}")
        return {
            "product_without_subaliases": sorted(no_subaliases),
            "demographic_not_mixed": sorted(demographic_not_mixed),
            "subalias_unknown_generation": sorted(unknown_generation),
            "subalias_bad_years": sorted(bad_years),
        }

available_products() #

Return the curated product aliases, sorted.

Source code in src/earthlens/worldpop/catalog.py
def available_products(self) -> list[str]:
    """Return the curated product aliases, sorted."""
    return sorted(self.datasets)

describe(product) #

Return a structured introspection record for a product.

Mirrors earthlens.ecmwf.Catalog.describe / the tropycal catalog: a runtime "what does product X expose?" helper a CLI / notebook can dump without walking the YAML.

Parameters:

Name Type Description Default
product str

A product key or friendly alias (resolved first).

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Keys product (canonical alias), friendly,

dict[str, Any]

kind, demographic, unit, and subaliases (a list of

dict[str, Any]

per-variant dicts with id / constrained / unadjusted /

dict[str, Any]

resolution / scope / generation / level / years).

Raises:

Type Description
ValueError

If product is not a curated product.

Examples:

  • Describe the population product at a glance:
    >>> from earthlens.worldpop import Catalog
    >>> info = Catalog().describe("population")
    >>> info["product"]
    'pop'
    >>> info["kind"]
    'raster'
    >>> info["subaliases"][0]["id"]
    'wpgp'
    
Source code in src/earthlens/worldpop/catalog.py
def describe(self, product: str) -> dict[str, Any]:
    """Return a structured introspection record for a product.

    Mirrors `earthlens.ecmwf.Catalog.describe` / the tropycal catalog: a
    runtime "what does product X expose?" helper a CLI / notebook can
    dump without walking the YAML.

    Args:
        product: A product key or friendly alias (resolved first).

    Returns:
        dict[str, Any]: Keys `product` (canonical alias), `friendly`,
        `kind`, `demographic`, `unit`, and `subaliases` (a list of
        per-variant dicts with `id` / `constrained` / `unadjusted` /
        `resolution` / `scope` / `generation` / `level` / `years`).

    Raises:
        ValueError: If `product` is not a curated product.

    Examples:
        - Describe the population product at a glance:
            ```python
            >>> from earthlens.worldpop import Catalog
            >>> info = Catalog().describe("population")
            >>> info["product"]
            'pop'
            >>> info["kind"]
            'raster'
            >>> info["subaliases"][0]["id"]
            'wpgp'

            ```
    """
    code = self.resolve(product)
    row = self.datasets[code]
    return {
        "product": code,
        "friendly": list(row.friendly),
        "kind": row.kind,
        "demographic": row.demographic,
        "unit": row.unit,
        "description": row.description,
        "endpoint": row.endpoint(),
        "subaliases": [
            {
                "id": sub.id,
                "constrained": sub.constrained,
                "unadjusted": sub.unadjusted,
                "resolution": sub.resolution,
                "scope": sub.scope,
                "generation": sub.generation,
                "level": sub.level,
                "years": sub.years,
            }
            for sub in row.subaliases
        ],
    }

get(alias) #

Return the Product for a canonical alias, did-you-mean on miss.

Parameters:

Name Type Description Default
alias str

A canonical product alias ("pop").

required

Returns:

Name Type Description
Product Product

The matching row.

Raises:

Type Description
ValueError

If alias is not a curated product.

Source code in src/earthlens/worldpop/catalog.py
def get(self, alias: str) -> Product:
    """Return the `Product` for a canonical alias, did-you-mean on miss.

    Args:
        alias: A canonical product alias (`"pop"`).

    Returns:
        Product: The matching row.

    Raises:
        ValueError: If `alias` is not a curated product.
    """
    return self.get_dataset(alias)

get_catalog() #

Return the product map (satisfies the abstract contract).

Source code in src/earthlens/worldpop/catalog.py
def get_catalog(self) -> dict[str, Product]:
    """Return the product map (satisfies the abstract contract)."""
    return self.datasets

health() #

Report structural hygiene issues across the loaded catalog.

Mirrors earthlens.ecmwf.Catalog.health / earthlens.gee.Catalog.health: returns a mapping check_name -> sorted list of offenders. An empty list means the check passes. Schema-level invariants (duplicate keys, unknown fields) are already enforced at load time — these are the residual data-quality checks the pydantic schema cannot express.

Checks reported:

  • product_without_subaliases — products carrying zero sub-aliases.
  • demographic_not_mixed — products flagged demographic whose kind is not "mixed".
  • subalias_unknown_generation"<product>:<id>" whose generation is not in GENERATIONS.
  • subalias_bad_years"<product>:<id>" whose years spec does not parse.

Returns:

Type Description
dict[str, list[str]]

dict[str, list[str]]: The per-check offender lists.

Examples:

  • The bundled catalog is clean:
    >>> from earthlens.worldpop import Catalog
    >>> Catalog().health()
    {'product_without_subaliases': [], 'demographic_not_mixed': [], 'subalias_unknown_generation': [], 'subalias_bad_years': []}
    
Source code in src/earthlens/worldpop/catalog.py
def health(self) -> dict[str, list[str]]:
    """Report structural hygiene issues across the loaded catalog.

    Mirrors `earthlens.ecmwf.Catalog.health` / `earthlens.gee.Catalog.health`:
    returns a mapping `check_name -> sorted list of offenders`. An empty
    list means the check passes. Schema-level invariants (duplicate keys,
    unknown fields) are already enforced at load time — these are the
    residual data-quality checks the pydantic schema cannot express.

    Checks reported:

    * `product_without_subaliases` — products carrying zero sub-aliases.
    * `demographic_not_mixed` — products flagged `demographic` whose
      `kind` is not `"mixed"`.
    * `subalias_unknown_generation` — `"<product>:<id>"` whose
      `generation` is not in `GENERATIONS`.
    * `subalias_bad_years` — `"<product>:<id>"` whose `years` spec does
      not parse.

    Returns:
        dict[str, list[str]]: The per-check offender lists.

    Examples:
        - The bundled catalog is clean:
            ```python
            >>> from earthlens.worldpop import Catalog
            >>> Catalog().health()
            {'product_without_subaliases': [], 'demographic_not_mixed': [], 'subalias_unknown_generation': [], 'subalias_bad_years': []}

            ```
    """
    no_subaliases: list[str] = []
    demographic_not_mixed: list[str] = []
    unknown_generation: list[str] = []
    bad_years: list[str] = []
    for alias, product in self.datasets.items():
        if not product.subaliases:
            no_subaliases.append(alias)
        if product.demographic and product.kind != "mixed":
            demographic_not_mixed.append(alias)
        for sub in product.subaliases:
            if sub.generation not in GENERATIONS:
                unknown_generation.append(f"{alias}:{sub.id}")
            try:
                sub.years_set()
            except ValueError:
                bad_years.append(f"{alias}:{sub.id}")
    return {
        "product_without_subaliases": sorted(no_subaliases),
        "demographic_not_mixed": sorted(demographic_not_mixed),
        "subalias_unknown_generation": sorted(unknown_generation),
        "subalias_bad_years": sorted(bad_years),
    }

load(catalog_path=None) classmethod #

Read the WorldPop product catalog from disk.

Parameters:

Name Type Description Default
catalog_path Path | None

Path to the catalog YAML. Defaults to the module-level CATALOG_PATH.

None

Returns:

Type Description
Catalog

A fully-populated Catalog with datasets and the

Catalog

available_datasets index set.

Raises:

Type Description
ValueError

If the file has no products: block, or a row fails Product validation.

Source code in src/earthlens/worldpop/catalog.py
@classmethod
def load(cls, catalog_path: Path | None = None) -> Catalog:
    """Read the WorldPop product catalog from disk.

    Args:
        catalog_path: Path to the catalog YAML. Defaults to the
            module-level `CATALOG_PATH`.

    Returns:
        A fully-populated `Catalog` with `datasets` and the
        `available_datasets` index set.

    Raises:
        ValueError: If the file has no `products:` block, or a row
            fails `Product` validation.
    """
    catalog_path = catalog_path if catalog_path is not None else CATALOG_PATH
    products = _load_products(catalog_path)
    return cls(datasets=dict(products), available_datasets=sorted(products))

model_post_init(__context) #

Auto-load the bundled catalog when no products were supplied.

Catalog() with no args reads CATALOG_PATH; passing datasets=... skips the disk read (used in tests).

Raises:

Type Description
ValueError

Propagated from load when the YAML is missing, empty, or has a malformed product row.

Source code in src/earthlens/worldpop/catalog.py
def model_post_init(self, __context: Any) -> None:
    """Auto-load the bundled catalog when no products were supplied.

    `Catalog()` with no args reads `CATALOG_PATH`; passing
    `datasets=...` skips the disk read (used in tests).

    Raises:
        ValueError: Propagated from `load` when the YAML is missing,
            empty, or has a malformed product row.
    """
    if not self.datasets:
        self.datasets = dict(_load_products(CATALOG_PATH))
    if not self.available_datasets:
        self.available_datasets = sorted(self.datasets)
    self._index_aliases()

pick_subalias(product, *, constrained=False, unadjusted=True, resolution='100m', scope='countries', generation='R2021', level='national') #

Resolve the selector kwargs to a single REST sub-alias id.

A product with exactly one sub-alias (births, urban_change, …) returns it directly — the selector kwargs do not apply, since there is only one variant. As a guard against a silently-ignored request, a resolution that differs from the sole sub-alias's resolution emits a UserWarning (the other selectors are product-intrinsic for single-variant products and are not warned on). Otherwise the kwargs must match one sub-alias's (constrained, unadjusted, resolution, scope, generation, level) tuple exactly.

Parameters:

Name Type Description Default
product str

A product key or alias (resolved first).

required
constrained bool

Settlement-masked variant (True) vs unconstrained (False).

False
unadjusted bool

Raw (True) vs UN-adjusted (False).

True
resolution str

"100m" or "1km".

'100m'
scope str

"countries" or "global".

'countries'
generation str

One of GENERATIONS.

'R2021'
level str

"national" or "subnational" (only pwd differs).

'national'

Returns:

Name Type Description
str str

The matching sub-alias id (e.g. "wpgp").

Raises:

Type Description
ValueError

If no sub-alias matches the selector; the message lists the product's available sub-alias tuples.

Examples:

  • The classic unconstrained 100 m country series resolves to wpgp:
    >>> from earthlens.worldpop import Catalog
    >>> Catalog().pick_subalias("pop")
    'wpgp'
    
Source code in src/earthlens/worldpop/catalog.py
def pick_subalias(
    self,
    product: str,
    *,
    constrained: bool = False,
    unadjusted: bool = True,
    resolution: str = "100m",
    scope: str = "countries",
    generation: str = "R2021",
    level: str = "national",
) -> str:
    """Resolve the selector kwargs to a single REST sub-alias id.

    A product with exactly one sub-alias (`births`, `urban_change`, …)
    returns it directly — the selector kwargs do not apply, since there
    is only one variant. As a guard against a silently-ignored request,
    a `resolution` that differs from the sole sub-alias's resolution
    emits a `UserWarning` (the other selectors are product-intrinsic for
    single-variant products and are not warned on). Otherwise the kwargs
    must match one sub-alias's
    `(constrained, unadjusted, resolution, scope, generation, level)`
    tuple exactly.

    Args:
        product: A product key or alias (resolved first).
        constrained: Settlement-masked variant (`True`) vs
            unconstrained (`False`).
        unadjusted: Raw (`True`) vs UN-adjusted (`False`).
        resolution: `"100m"` or `"1km"`.
        scope: `"countries"` or `"global"`.
        generation: One of `GENERATIONS`.
        level: `"national"` or `"subnational"` (only `pwd` differs).

    Returns:
        str: The matching sub-alias id (e.g. `"wpgp"`).

    Raises:
        ValueError: If no sub-alias matches the selector; the message
            lists the product's available sub-alias tuples.

    Examples:
        - The classic unconstrained 100 m country series resolves to `wpgp`:
            ```python
            >>> from earthlens.worldpop import Catalog
            >>> Catalog().pick_subalias("pop")
            'wpgp'

            ```
    """
    code = self.resolve(product)
    row = self.datasets[code]
    if len(row.subaliases) == 1:
        only = row.subaliases[0]
        if resolution != only.resolution:
            warnings.warn(
                f"{code!r} offers only the {only.resolution!r} sub-alias "
                f"{only.id!r}; the requested resolution={resolution!r} is "
                "ignored.",
                UserWarning,
                stacklevel=2,
            )
        return only.id
    want = (constrained, unadjusted, resolution, scope, generation, level)
    for sub in row.subaliases:
        if sub.selector() == want:
            return sub.id
    options = "\n".join(
        f"  - id={s.id!r} constrained={s.constrained} "
        f"unadjusted={s.unadjusted} resolution={s.resolution!r} "
        f"scope={s.scope!r} generation={s.generation!r} level={s.level!r}"
        for s in row.subaliases
    )
    raise ValueError(
        f"{code!r} has no variant for constrained={constrained}, "
        f"unadjusted={unadjusted}, resolution={resolution!r}, scope={scope!r}, "
        f"generation={generation!r}, level={level!r}. "
        f"Available sub-aliases:\n{options}"
    )

resolve(key) #

Resolve a product key or friendly alias to its canonical alias.

Parameters:

Name Type Description Default
key str

A canonical alias ("pop") or a friendly alias ("population", case-insensitive).

required

Returns:

Name Type Description
str str

The canonical product alias.

Raises:

Type Description
ValueError

If key matches no product or alias; the message lists the known products with a did-you-mean hint.

Examples:

  • A friendly alias and a canonical key both resolve:
    >>> from earthlens.worldpop import Catalog
    >>> cat = Catalog()
    >>> cat.resolve("population")
    'pop'
    >>> cat.resolve("pop")
    'pop'
    
Source code in src/earthlens/worldpop/catalog.py
def resolve(self, key: str) -> str:
    """Resolve a product key or friendly alias to its canonical alias.

    Args:
        key: A canonical alias (`"pop"`) or a friendly alias
            (`"population"`, case-insensitive).

    Returns:
        str: The canonical product alias.

    Raises:
        ValueError: If `key` matches no product or alias; the message
            lists the known products with a did-you-mean hint.

    Examples:
        - A friendly alias and a canonical key both resolve:
            ```python
            >>> from earthlens.worldpop import Catalog
            >>> cat = Catalog()
            >>> cat.resolve("population")
            'pop'
            >>> cat.resolve("pop")
            'pop'

            ```
    """
    index: dict[str, str] = getattr(self, "_alias_index", {})
    canonical = index.get(key.lower())
    if canonical is not None:
        return canonical
    close = difflib.get_close_matches(key.lower(), index, n=1)
    hint = f" Did you mean {index[close[0]]!r}?" if close else ""
    raise ValueError(
        f"{key!r} is not a known WorldPop product or alias. "
        f"Known products: {sorted(self.datasets)}.{hint}"
    )

subalias(product, subalias_id) #

Return the SubAlias row of a product by its REST id.

Parameters:

Name Type Description Default
product str

A product key or alias (resolved first).

required
subalias_id str

A sub-alias id belonging to that product.

required

Returns:

Name Type Description
SubAlias SubAlias

The matching sub-alias row.

Raises:

Type Description
ValueError

If product is unknown or has no such sub-alias.

Examples:

  • Look up a sub-alias and read its scope / resolution:
    >>> from earthlens.worldpop import Catalog
    >>> sub = Catalog().subalias("pop", "wpgp")
    >>> sub.scope
    'countries'
    >>> sub.resolution
    '100m'
    
Source code in src/earthlens/worldpop/catalog.py
def subalias(self, product: str, subalias_id: str) -> SubAlias:
    """Return the `SubAlias` row of a product by its REST id.

    Args:
        product: A product key or alias (resolved first).
        subalias_id: A sub-alias id belonging to that product.

    Returns:
        SubAlias: The matching sub-alias row.

    Raises:
        ValueError: If `product` is unknown or has no such sub-alias.

    Examples:
        - Look up a sub-alias and read its scope / resolution:
            ```python
            >>> from earthlens.worldpop import Catalog
            >>> sub = Catalog().subalias("pop", "wpgp")
            >>> sub.scope
            'countries'
            >>> sub.resolution
            '100m'

            ```
    """
    code = self.resolve(product)
    for sub in self.datasets[code].subaliases:
        if sub.id == subalias_id:
            return sub
    raise ValueError(
        f"{code!r} has no sub-alias {subalias_id!r}; "
        f"have {[s.id for s in self.datasets[code].subaliases]}."
    )

validate(product, *, constrained=False, unadjusted=True, resolution='100m', scope='countries', generation='R2021', level='national', year=None) #

Validate a full request and return (product, subalias_id).

Resolves the product, picks the sub-alias from the selectors, and — when year is given — checks the sub-alias offers it.

Parameters:

Name Type Description Default
product str

A product key or alias.

required
constrained bool

See pick_subalias.

False
unadjusted bool

See pick_subalias.

True
resolution str

See pick_subalias.

'100m'
scope str

See pick_subalias.

'countries'
generation str

See pick_subalias.

'R2021'
level str

See pick_subalias.

'national'
year int | None

Optional year to check against the sub-alias's years.

None

Returns:

Type Description
tuple[str, str]

tuple[str, str]: The canonical (product, subalias_id).

Raises:

Type Description
ValueError

If the selector matches no sub-alias, or year is outside the sub-alias's available years.

Source code in src/earthlens/worldpop/catalog.py
def validate(
    self,
    product: str,
    *,
    constrained: bool = False,
    unadjusted: bool = True,
    resolution: str = "100m",
    scope: str = "countries",
    generation: str = "R2021",
    level: str = "national",
    year: int | None = None,
) -> tuple[str, str]:
    """Validate a full request and return `(product, subalias_id)`.

    Resolves the product, picks the sub-alias from the selectors, and —
    when `year` is given — checks the sub-alias offers it.

    Args:
        product: A product key or alias.
        constrained: See `pick_subalias`.
        unadjusted: See `pick_subalias`.
        resolution: See `pick_subalias`.
        scope: See `pick_subalias`.
        generation: See `pick_subalias`.
        level: See `pick_subalias`.
        year: Optional year to check against the sub-alias's `years`.

    Returns:
        tuple[str, str]: The canonical `(product, subalias_id)`.

    Raises:
        ValueError: If the selector matches no sub-alias, or `year` is
            outside the sub-alias's available years.
    """
    code = self.resolve(product)
    subalias_id = self.pick_subalias(
        code,
        constrained=constrained,
        unadjusted=unadjusted,
        resolution=resolution,
        scope=scope,
        generation=generation,
        level=level,
    )
    if year is not None:
        sub = next(s for s in self.datasets[code].subaliases if s.id == subalias_id)
        years = sub.years_set()
        if year not in years:
            raise ValueError(
                f"{code}/{subalias_id} does not offer year {year}; "
                f"available years: {sorted(years)}."
            )
    return code, subalias_id

Product #

Bases: BaseModel

One curated WorldPop product family (a top-level REST alias).

Attributes:

Name Type Description
alias str

Canonical product alias ("pop", "age_structures"); set from the YAML mapping key by the loader.

friendly list[str]

Friendly names that also resolve to this product (["population", "population_counts"]).

kind str

"raster" (gridded only) or "mixed" (gridded and a tabular demographic breakdown).

demographic bool

Whether the product ships per-cohort age/sex rasters that earthlens tabularises (only age_structures in practice).

unit str

Human-readable unit of the values ("people/pixel").

worldpoppy_id str | None

The matching WorldPopPy product id for the optional api="worldpoppy" path, or None if unmapped.

rest_alias str

The top-level REST alias to query when it differs from the catalog key. Empty (the default) means "use the key". The covariate products set this to "covariates" (they are sub-aliases of the shared covariates endpoint).

description str

Human-readable description of the product (the hub's title), shown in docs / describe.

subaliases list[SubAlias]

The concrete variants this product offers.

Source code in src/earthlens/worldpop/catalog.py
class Product(BaseModel):
    """One curated WorldPop product family (a top-level REST alias).

    Attributes:
        alias: Canonical product alias (`"pop"`, `"age_structures"`); set
            from the YAML mapping key by the loader.
        friendly: Friendly names that also resolve to this product
            (`["population", "population_counts"]`).
        kind: `"raster"` (gridded only) or `"mixed"` (gridded **and** a
            tabular demographic breakdown).
        demographic: Whether the product ships per-cohort age/sex rasters
            that earthlens tabularises (only `age_structures` in practice).
        unit: Human-readable unit of the values (`"people/pixel"`).
        worldpoppy_id: The matching WorldPopPy product id for the optional
            `api="worldpoppy"` path, or `None` if unmapped.
        rest_alias: The top-level REST alias to query when it differs from
            the catalog key. Empty (the default) means "use the key". The
            covariate products set this to `"covariates"` (they are
            sub-aliases of the shared `covariates` endpoint).
        description: Human-readable description of the product (the hub's
            title), shown in docs / `describe`.
        subaliases: The concrete variants this product offers.
    """

    model_config = ConfigDict(frozen=True, extra="forbid")

    alias: str = ""
    friendly: list[str] = Field(default_factory=list)
    kind: str = "raster"
    demographic: bool = False
    unit: str = ""
    worldpoppy_id: str | None = None
    rest_alias: str = ""
    description: str = ""
    subaliases: list[SubAlias] = Field(default_factory=list)

    def endpoint(self) -> str:
        """Return the REST alias to query (`rest_alias` or the product key)."""
        return self.rest_alias or self.alias

    def selectors(self) -> list[tuple[bool, bool, str, str, str, str]]:
        """Return every sub-alias selector tuple (for did-you-mean listings)."""
        return [s.selector() for s in self.subaliases]

endpoint() #

Return the REST alias to query (rest_alias or the product key).

Source code in src/earthlens/worldpop/catalog.py
def endpoint(self) -> str:
    """Return the REST alias to query (`rest_alias` or the product key)."""
    return self.rest_alias or self.alias

selectors() #

Return every sub-alias selector tuple (for did-you-mean listings).

Source code in src/earthlens/worldpop/catalog.py
def selectors(self) -> list[tuple[bool, bool, str, str, str, str]]:
    """Return every sub-alias selector tuple (for did-you-mean listings)."""
    return [s.selector() for s in self.subaliases]

SubAlias #

Bases: BaseModel

One concrete WorldPop variant under a product alias.

Maps the selector tuple (constrained, unadjusted, resolution, scope, generation) to a REST sub-alias id and the years it offers. The tuple is unique within a product, so Catalog.pick_subalias can resolve a request to exactly one sub-alias.

Attributes:

Name Type Description
id str

The real REST sub-alias id ("wpgp", "cic2020_100m", "G2_CN_POP_R25A_100m", …) — the {subalias} path segment.

constrained bool

Whether this is the settlement-masked constrained variant (True) or the unconstrained variant (False).

unadjusted bool

True for the raw variant; False for the UN-adjusted variant. WorldPop's "UN adjusted" sub-aliases set this False, the plain ones True. Defaults to True.

resolution str

Pixel size — "100m" or "1km".

scope str

"countries" (per-ISO3 rasters) or "global" (a single global mosaic).

generation str

The product generation ("R2021", "R2024B", "R2025A", "2024").

level str

Aggregation level for products that publish both (pwd): "national" or "subnational". "national" for every other product.

archive str

The archive format the product is distributed in, or "" for plain per-year GeoTIFFs. "7z" (dependency_ratios, per-continent) and "zip" (future_pop, per-SSP) products are downloaded as an archive and extracted before cropping; "zip" (multi-GB) additionally requires the allow_large_archive opt-in.

years str

The years this sub-alias offers, as a single year ("2020") or an inclusive range ("2000-2020").

Source code in src/earthlens/worldpop/catalog.py
class SubAlias(BaseModel):
    """One concrete WorldPop variant under a product alias.

    Maps the selector tuple `(constrained, unadjusted, resolution, scope,
    generation)` to a REST sub-alias `id` and the years it offers. The tuple
    is unique within a product, so `Catalog.pick_subalias` can resolve a
    request to exactly one sub-alias.

    Attributes:
        id: The real REST sub-alias id (`"wpgp"`, `"cic2020_100m"`,
            `"G2_CN_POP_R25A_100m"`, …) — the `{subalias}` path segment.
        constrained: Whether this is the settlement-masked *constrained*
            variant (`True`) or the *unconstrained* variant (`False`).
        unadjusted: `True` for the raw variant; `False` for the
            UN-adjusted variant. WorldPop's "UN adjusted" sub-aliases set
            this `False`, the plain ones `True`. Defaults to `True`.
        resolution: Pixel size — `"100m"` or `"1km"`.
        scope: `"countries"` (per-ISO3 rasters) or `"global"` (a single
            global mosaic).
        generation: The product generation (`"R2021"`, `"R2024B"`,
            `"R2025A"`, `"2024"`).
        level: Aggregation level for products that publish both
            (`pwd`): `"national"` or `"subnational"`. `"national"` for
            every other product.
        archive: The archive format the product is distributed in, or `""`
            for plain per-year GeoTIFFs. `"7z"` (`dependency_ratios`,
            per-continent) and `"zip"` (`future_pop`, per-SSP) products are
            downloaded as an archive and extracted before cropping; `"zip"`
            (multi-GB) additionally requires the `allow_large_archive` opt-in.
        years: The years this sub-alias offers, as a single year
            (`"2020"`) or an inclusive range (`"2000-2020"`).
    """

    model_config = ConfigDict(frozen=True, extra="forbid")

    id: str
    constrained: bool = False
    unadjusted: bool = True
    resolution: str = "100m"
    scope: str = "countries"
    generation: str = "R2021"
    level: str = "national"
    archive: str = ""
    years: str = "2000-2020"

    def years_set(self) -> set[int]:
        """Return the set of years this sub-alias offers (parsed from `years`)."""
        return _years_set(self.years)

    def selector(self) -> tuple[bool, bool, str, str, str, str]:
        """Return the selector key.

        The key is `(constrained, unadjusted, resolution, scope, generation,
        level)` — unique within a product.
        """
        return (
            self.constrained,
            self.unadjusted,
            self.resolution,
            self.scope,
            self.generation,
            self.level,
        )

selector() #

Return the selector key.

The key is (constrained, unadjusted, resolution, scope, generation, level) — unique within a product.

Source code in src/earthlens/worldpop/catalog.py
def selector(self) -> tuple[bool, bool, str, str, str, str]:
    """Return the selector key.

    The key is `(constrained, unadjusted, resolution, scope, generation,
    level)` — unique within a product.
    """
    return (
        self.constrained,
        self.unadjusted,
        self.resolution,
        self.scope,
        self.generation,
        self.level,
    )

years_set() #

Return the set of years this sub-alias offers (parsed from years).

Source code in src/earthlens/worldpop/catalog.py
def years_set(self) -> set[int]:
    """Return the set of years this sub-alias offers (parsed from `years`)."""
    return _years_set(self.years)

clear_catalog_cache() #

Empty the module-level product parse cache.

Useful in tests that rewrite the catalog on disk and want to force a re-parse. Production callers do not need this — the cache key includes st_mtime_ns, so any real file mutation invalidates the entry on its own.

Source code in src/earthlens/worldpop/catalog.py
def clear_catalog_cache() -> None:
    """Empty the module-level product parse cache.

    Useful in tests that rewrite the catalog on disk and want to force a
    re-parse. Production callers do not need this — the cache key includes
    `st_mtime_ns`, so any real file mutation invalidates the entry on its
    own.
    """
    _CATALOG_CACHE.clear()

earthlens.worldpop.rest #

WorldPop REST query layer.

Thin requests-based client over hub.worldpop.org/rest/data. The hub's three-level scheme is: /rest/data (product aliases) → /rest/data/{alias} (sub-aliases) → /rest/data/{alias}/{subalias}?iso3=… (one JSON record per year, each carrying a files array of GeoTIFF URLs). Year filtering is client-side on popyear — the query returns every year for the (alias, subalias, iso3) triple, so the caller picks the record whose popyear matches.

files_for_year(records, year) #

Return the GeoTIFF URLs for the record whose popyear matches year.

Parameters:

Name Type Description Default
records list[dict[str, Any]]

The list returned by rest_records.

required
year int | None

The wanted year. None selects the latest available popyear.

required

Returns:

Type Description
list[str]

list[str]: The matching record's GeoTIFF URLs (one for plain population products; many — one per age/sex cohort — for age_structures). Non-raster files entries (e.g. the …_ASCII_XYZ.zip companion the 1 km products ship) are dropped.

Raises:

Type Description
ValueError

If records is empty, no record has popyear == year, or the matching record carries no GeoTIFF; the message lists the available years.

Source code in src/earthlens/worldpop/rest.py
def files_for_year(records: list[dict[str, Any]], year: int | None) -> list[str]:
    """Return the GeoTIFF URLs for the record whose `popyear` matches `year`.

    Args:
        records: The list returned by `rest_records`.
        year: The wanted year. `None` selects the latest available
            `popyear`.

    Returns:
        list[str]: The matching record's GeoTIFF URLs (one for plain
            population products; many — one per age/sex cohort — for
            `age_structures`). Non-raster `files` entries (e.g. the
            `…_ASCII_XYZ.zip` companion the 1 km products ship) are dropped.

    Raises:
        ValueError: If `records` is empty, no record has `popyear == year`,
            or the matching record carries no GeoTIFF; the message lists the
            available years.
    """
    if not records:
        raise ValueError("WorldPop returned no records for this query.")
    dated = [r for r in records if r.get("popyear") is not None]
    if not dated:
        # Undated single record (e.g. a covariate layer): year does not apply.
        record = records[0]
    elif year is None:
        record = max(dated, key=lambda d: int(d["popyear"]))
    else:
        record = next((d for d in dated if int(d["popyear"]) == int(year)), None)
        if record is None:
            available = sorted({int(d["popyear"]) for d in dated})
            raise ValueError(
                f"WorldPop year {year} is not available; have {available}."
            )
    tifs = [
        url
        for url in record.get("files", [])
        if url.lower().endswith((".tif", ".tiff"))
    ]
    if not tifs:
        raise ValueError(
            f"WorldPop record {record.get('popyear')!r} carries no GeoTIFF; "
            f"files: {record.get('files', [])}."
        )
    return tifs

global_files_for_year(alias, subalias_id, year, *, base_url=BASE_URL, session=None, timeout=_TIMEOUT) #

Return the global GeoTIFF URLs for one (alias, subalias, year).

Lists the global records, picks the one whose popyear matches year (or the latest when year is None), then resolves its files via the ?id= detail endpoint.

Parameters:

Name Type Description Default
alias str

Top-level product alias.

required
subalias_id str

A global-scope sub-alias id.

required
year int | None

The wanted year, or None for the latest.

required
base_url str

REST base URL (overridable for tests).

BASE_URL
session Session | None

Optional requests.Session.

None
timeout int

Per-request timeout in seconds.

_TIMEOUT

Returns:

Type Description
list[str]

list[str]: The matching record's GeoTIFF URLs (one global mosaic for plain population; one per age/sex cohort for age_structures).

Raises:

Type Description
ValueError

If no records exist, the year is unavailable, or the matched record carries no GeoTIFF (e.g. an archive-only product).

Source code in src/earthlens/worldpop/rest.py
def global_files_for_year(
    alias: str,
    subalias_id: str,
    year: int | None,
    *,
    base_url: str = BASE_URL,
    session: requests.Session | None = None,
    timeout: int = _TIMEOUT,
) -> list[str]:
    """Return the global GeoTIFF URLs for one `(alias, subalias, year)`.

    Lists the global records, picks the one whose `popyear` matches `year`
    (or the latest when `year` is `None`), then resolves its `files` via the
    `?id=` detail endpoint.

    Args:
        alias: Top-level product alias.
        subalias_id: A global-scope sub-alias id.
        year: The wanted year, or `None` for the latest.
        base_url: REST base URL (overridable for tests).
        session: Optional `requests.Session`.
        timeout: Per-request timeout in seconds.

    Returns:
        list[str]: The matching record's GeoTIFF URLs (one global mosaic for
            plain population; one per age/sex cohort for `age_structures`).

    Raises:
        ValueError: If no records exist, the year is unavailable, or the
            matched record carries no GeoTIFF (e.g. an archive-only product).
    """
    records = global_records(
        alias, subalias_id, base_url=base_url, session=session, timeout=timeout
    )
    dated = [r for r in records if r.get("popyear") is not None]
    if not dated:
        raise ValueError(
            f"WorldPop {alias}/{subalias_id} has no dated global records "
            "(archive-distributed product?)."
        )
    if year is None:
        record = max(dated, key=lambda d: int(d["popyear"]))
    else:
        record = next((d for d in dated if int(d["popyear"]) == int(year)), None)
        if record is None:
            available = sorted({int(d["popyear"]) for d in dated})
            raise ValueError(
                f"WorldPop {alias}/{subalias_id} year {year} is not available; "
                f"have {available}."
            )
    tifs = record_files(
        alias,
        subalias_id,
        record["id"],
        base_url=base_url,
        session=session,
        timeout=timeout,
    )
    if not tifs:
        raise ValueError(
            f"WorldPop {alias}/{subalias_id} record {record.get('popyear')!r} "
            "carries no GeoTIFF (archive-distributed product?)."
        )
    return tifs

global_records(alias, subalias_id, *, base_url=BASE_URL, session=None, timeout=_TIMEOUT) #

Return the index records for a global / non-ISO3 sub-alias.

Global mosaics (wpgp1km, aswpgponekm, …) are queried without iso3. The listing carries one summary record per popyear (id, popyear, title) but no files — fetch those per record via record_files.

Parameters:

Name Type Description Default
alias str

Top-level product alias ("pop", "age_structures").

required
subalias_id str

A global-scope sub-alias id ("wpgp1km").

required
base_url str

REST base URL (overridable for tests).

BASE_URL
session Session | None

Optional requests.Session to reuse a connection.

None
timeout int

Per-request timeout in seconds.

_TIMEOUT

Returns:

Type Description
list[dict[str, Any]]

list[dict]: The data array — one summary record per year.

Raises:

Type Description
HTTPError

If the endpoint returns a non-2xx status.

Source code in src/earthlens/worldpop/rest.py
def global_records(
    alias: str,
    subalias_id: str,
    *,
    base_url: str = BASE_URL,
    session: requests.Session | None = None,
    timeout: int = _TIMEOUT,
) -> list[dict[str, Any]]:
    """Return the index records for a global / non-ISO3 sub-alias.

    Global mosaics (`wpgp1km`, `aswpgponekm`, …) are queried **without**
    `iso3`. The listing carries one summary record per `popyear` (`id`,
    `popyear`, `title`) but **no** `files` — fetch those per record via
    `record_files`.

    Args:
        alias: Top-level product alias (`"pop"`, `"age_structures"`).
        subalias_id: A global-scope sub-alias id (`"wpgp1km"`).
        base_url: REST base URL (overridable for tests).
        session: Optional `requests.Session` to reuse a connection.
        timeout: Per-request timeout in seconds.

    Returns:
        list[dict]: The `data` array — one summary record per year.

    Raises:
        requests.HTTPError: If the endpoint returns a non-2xx status.
    """
    getter = session.get if session is not None else requests.get
    resp = getter(f"{base_url}/{alias}/{subalias_id}", timeout=timeout)
    resp.raise_for_status()
    return resp.json().get("data", [])

record_archive_files(alias, subalias_id, record_id, fmt, *, base_url=BASE_URL, session=None, timeout=_TIMEOUT) #

Return a record's archive URLs (.zip / .7z) via the ?id= detail.

The archive products (future_pop per-SSP .zip, dependency_ratios per-continent .7z) carry their downloads as archives, not GeoTIFFs; this returns the URLs ending in .{fmt}.

Parameters:

Name Type Description Default
alias str

Top-level product alias.

required
subalias_id str

The sub-alias id.

required
record_id str

The id of a record from global_records.

required
fmt str

Archive extension to keep — "zip" or "7z".

required
base_url str

REST base URL (overridable for tests).

BASE_URL
session Session | None

Optional requests.Session.

None
timeout int

Per-request timeout in seconds.

_TIMEOUT

Returns:

Type Description
list[str]

list[str]: The record's archive URLs ending in .{fmt}.

Raises:

Type Description
HTTPError

If the endpoint returns a non-2xx status.

Source code in src/earthlens/worldpop/rest.py
def record_archive_files(
    alias: str,
    subalias_id: str,
    record_id: str,
    fmt: str,
    *,
    base_url: str = BASE_URL,
    session: requests.Session | None = None,
    timeout: int = _TIMEOUT,
) -> list[str]:
    """Return a record's archive URLs (`.zip` / `.7z`) via the `?id=` detail.

    The archive products (`future_pop` per-SSP `.zip`, `dependency_ratios`
    per-continent `.7z`) carry their downloads as archives, not GeoTIFFs;
    this returns the URLs ending in `.{fmt}`.

    Args:
        alias: Top-level product alias.
        subalias_id: The sub-alias id.
        record_id: The `id` of a record from `global_records`.
        fmt: Archive extension to keep — `"zip"` or `"7z"`.
        base_url: REST base URL (overridable for tests).
        session: Optional `requests.Session`.
        timeout: Per-request timeout in seconds.

    Returns:
        list[str]: The record's archive URLs ending in `.{fmt}`.

    Raises:
        requests.HTTPError: If the endpoint returns a non-2xx status.
    """
    getter = session.get if session is not None else requests.get
    resp = getter(
        f"{base_url}/{alias}/{subalias_id}", params={"id": record_id}, timeout=timeout
    )
    resp.raise_for_status()
    data = resp.json().get("data")
    record = data[0] if isinstance(data, list) and data else (data or {})
    suffix = f".{fmt.lower()}"
    return [url for url in (record.get("files") or []) if url.lower().endswith(suffix)]

record_citation(records) #

Return the citation of the first record, or None if absent.

Parameters:

Name Type Description Default
records list[dict[str, Any]]

The list returned by rest_records.

required

Returns:

Type Description
str | None

str | None: The CC-BY-4.0 citation text WorldPop attaches to the dataset, used to stamp output sidecars.

Source code in src/earthlens/worldpop/rest.py
def record_citation(records: list[dict[str, Any]]) -> str | None:
    """Return the `citation` of the first record, or `None` if absent.

    Args:
        records: The list returned by `rest_records`.

    Returns:
        str | None: The CC-BY-4.0 citation text WorldPop attaches to the
            dataset, used to stamp output sidecars.
    """
    for record in records:
        citation = record.get("citation")
        if citation:
            return str(citation)
    return None

record_files(alias, subalias_id, record_id, *, base_url=BASE_URL, session=None, timeout=_TIMEOUT) #

Return the GeoTIFF URLs of one record via the ?id= detail endpoint.

The summary listing omits files; querying ?id={record_id} returns the full record (a dict) whose files array holds the download URLs.

Parameters:

Name Type Description Default
alias str

Top-level product alias.

required
subalias_id str

The sub-alias id.

required
record_id str

The id of a record from global_records.

required
base_url str

REST base URL (overridable for tests).

BASE_URL
session Session | None

Optional requests.Session.

None
timeout int

Per-request timeout in seconds.

_TIMEOUT

Returns:

Type Description
list[str]

list[str]: The record's GeoTIFF URLs (non-raster entries — e.g. the .zip / .7z archives the projection / continent products ship — are dropped, so this is empty for archive-only products).

Raises:

Type Description
HTTPError

If the endpoint returns a non-2xx status.

Source code in src/earthlens/worldpop/rest.py
def record_files(
    alias: str,
    subalias_id: str,
    record_id: str,
    *,
    base_url: str = BASE_URL,
    session: requests.Session | None = None,
    timeout: int = _TIMEOUT,
) -> list[str]:
    """Return the GeoTIFF URLs of one record via the `?id=` detail endpoint.

    The summary listing omits `files`; querying `?id={record_id}` returns the
    full record (a dict) whose `files` array holds the download URLs.

    Args:
        alias: Top-level product alias.
        subalias_id: The sub-alias id.
        record_id: The `id` of a record from `global_records`.
        base_url: REST base URL (overridable for tests).
        session: Optional `requests.Session`.
        timeout: Per-request timeout in seconds.

    Returns:
        list[str]: The record's GeoTIFF URLs (non-raster entries — e.g. the
            `.zip` / `.7z` archives the projection / continent products ship
            — are dropped, so this is empty for archive-only products).

    Raises:
        requests.HTTPError: If the endpoint returns a non-2xx status.
    """
    getter = session.get if session is not None else requests.get
    resp = getter(
        f"{base_url}/{alias}/{subalias_id}", params={"id": record_id}, timeout=timeout
    )
    resp.raise_for_status()
    data = resp.json().get("data")
    record = data[0] if isinstance(data, list) and data else (data or {})
    return [
        url
        for url in (record.get("files") or [])
        if url.lower().endswith((".tif", ".tiff"))
    ]

rest_records(alias, subalias_id, iso3, *, base_url=BASE_URL, session=None, timeout=_TIMEOUT) #

Return the WorldPop records for one (alias, subalias, iso3) triple.

The endpoint returns every year as one record each; year filtering happens client-side in files_for_year.

Parameters:

Name Type Description Default
alias str

Top-level product alias ("pop", "age_structures", …).

required
subalias_id str

The concrete REST sub-alias id ("wpgp", …).

required
iso3 str

An ISO 3166-1 alpha-3 country code.

required
base_url str

REST base URL (overridable for tests).

BASE_URL
session Session | None

Optional requests.Session to reuse a connection.

None
timeout int

Per-request timeout in seconds.

_TIMEOUT

Returns:

Type Description
list[dict[str, Any]]

list[dict]: The data array — one record per popyear, each with id, title, doi, date, popyear, citation, license, and files (a list of GeoTIFF URLs).

Raises:

Type Description
HTTPError

If the endpoint returns a non-2xx status.

Source code in src/earthlens/worldpop/rest.py
def rest_records(
    alias: str,
    subalias_id: str,
    iso3: str,
    *,
    base_url: str = BASE_URL,
    session: requests.Session | None = None,
    timeout: int = _TIMEOUT,
) -> list[dict[str, Any]]:
    """Return the WorldPop records for one `(alias, subalias, iso3)` triple.

    The endpoint returns **every year** as one record each; year filtering
    happens client-side in `files_for_year`.

    Args:
        alias: Top-level product alias (`"pop"`, `"age_structures"`, …).
        subalias_id: The concrete REST sub-alias id (`"wpgp"`, …).
        iso3: An ISO 3166-1 alpha-3 country code.
        base_url: REST base URL (overridable for tests).
        session: Optional `requests.Session` to reuse a connection.
        timeout: Per-request timeout in seconds.

    Returns:
        list[dict]: The `data` array — one record per `popyear`, each with
            `id`, `title`, `doi`, `date`, `popyear`, `citation`,
            `license`, and `files` (a list of GeoTIFF URLs).

    Raises:
        requests.HTTPError: If the endpoint returns a non-2xx status.
    """
    getter = session.get if session is not None else requests.get
    resp = getter(
        f"{base_url}/{alias}/{subalias_id}",
        params={"iso3": iso3},
        timeout=timeout,
    )
    resp.raise_for_status()
    return resp.json().get("data", [])

earthlens.worldpop.auth #

Authentication placeholder for the WorldPop backend.

The WorldPop open population data hub (hub.worldpop.org) is open data, attribution only — every dataset is licensed CC-BY-4.0 and served over plain anonymous HTTPS from data.worldpop.org, so WorldPop performs no login: earthlens.worldpop.backend.WorldPop._initialize reads no credentials and the backend works with no key, env var, or config file.

WorldPopAuth exists so the package mirrors the layout of the authenticated backends (each has an auth.py with an AbstractAuth subclass). It is a no-op: configure() does nothing and is_authenticated() is always True. It carries the required attribution string so the backend can stamp it into output metadata / a sidecar.

WorldPopAuth #

Bases: AbstractAuth[WorldPopCredentials]

No-op auth for the open, attribution-only WorldPop data.

Kept for conformance with the AbstractAuth shape the other backends follow; WorldPop reads no credentials. configure() flips an internal flag and is_authenticated() is always True, so the context-manager form (with WorldPopAuth() as auth: ...) works like any other backend's.

Examples:

  • It is always authenticated, with nothing to configure:
    >>> from earthlens.worldpop import WorldPopAuth
    >>> auth = WorldPopAuth()
    >>> auth.is_authenticated()
    True
    >>> auth.configure()  # idempotent no-op
    >>> auth.is_authenticated()
    True
    
Source code in src/earthlens/worldpop/auth.py
class WorldPopAuth(AbstractAuth[WorldPopCredentials]):
    """No-op auth for the open, attribution-only WorldPop data.

    Kept for conformance with the `AbstractAuth` shape the other
    backends follow; WorldPop reads no credentials. `configure()`
    flips an internal flag and `is_authenticated()` is always
    `True`, so the context-manager form (`with WorldPopAuth() as
    auth: ...`) works like any other backend's.

    Examples:
        - It is always authenticated, with nothing to configure:
            ```python
            >>> from earthlens.worldpop import WorldPopAuth
            >>> auth = WorldPopAuth()
            >>> auth.is_authenticated()
            True
            >>> auth.configure()  # idempotent no-op
            >>> auth.is_authenticated()
            True

            ```
    """

    def __init__(self, credentials: WorldPopCredentials | None = None) -> None:
        """Store the (empty) credentials; default to a fresh `WorldPopCredentials`.

        Args:
            credentials: Optional empty credentials object. Defaults to a
                fresh `WorldPopCredentials()` since WorldPop needs no
                secrets.
        """
        super().__init__(
            credentials if credentials is not None else WorldPopCredentials()
        )
        self._configured = False

    def configure(self) -> None:
        """No-op setup — WorldPop is open + attribution-only (nothing to do)."""
        self._configured = True

    def is_authenticated(self) -> bool:
        """Return `True` — open data needs no credentials."""
        return True

__init__(credentials=None) #

Store the (empty) credentials; default to a fresh WorldPopCredentials.

Parameters:

Name Type Description Default
credentials WorldPopCredentials | None

Optional empty credentials object. Defaults to a fresh WorldPopCredentials() since WorldPop needs no secrets.

None
Source code in src/earthlens/worldpop/auth.py
def __init__(self, credentials: WorldPopCredentials | None = None) -> None:
    """Store the (empty) credentials; default to a fresh `WorldPopCredentials`.

    Args:
        credentials: Optional empty credentials object. Defaults to a
            fresh `WorldPopCredentials()` since WorldPop needs no
            secrets.
    """
    super().__init__(
        credentials if credentials is not None else WorldPopCredentials()
    )
    self._configured = False

configure() #

No-op setup — WorldPop is open + attribution-only (nothing to do).

Source code in src/earthlens/worldpop/auth.py
def configure(self) -> None:
    """No-op setup — WorldPop is open + attribution-only (nothing to do)."""
    self._configured = True

is_authenticated() #

Return True — open data needs no credentials.

Source code in src/earthlens/worldpop/auth.py
def is_authenticated(self) -> bool:
    """Return `True` — open data needs no credentials."""
    return True

WorldPopCredentials #

Bases: BaseModel

Empty credentials value object for the open WorldPop backend.

WorldPop needs no secrets; this exists only to satisfy the earthlens.base.auth.AbstractAuth generic contract that every backend's auth class binds a pydantic.BaseModel credentials type. It carries no fields.

Examples:

  • Construct the empty credentials:
    >>> from earthlens.worldpop import WorldPopCredentials
    >>> WorldPopCredentials()
    WorldPopCredentials()
    
Source code in src/earthlens/worldpop/auth.py
class WorldPopCredentials(BaseModel, frozen=True):
    """Empty credentials value object for the open WorldPop backend.

    WorldPop needs no secrets; this exists only to satisfy the
    `earthlens.base.auth.AbstractAuth` generic contract that every
    backend's auth class binds a `pydantic.BaseModel` credentials
    type. It carries no fields.

    Examples:
        - Construct the empty credentials:
            ```python
            >>> from earthlens.worldpop import WorldPopCredentials
            >>> WorldPopCredentials()
            WorldPopCredentials()

            ```
    """