firms_client.sync

Fill the data directory once, before it is needed: archives, mask, land cover.

The library reads lazily: an archive is downloaded the first time it is asked for, the static mask is built the first time it is needed (from every year of the archives, about 30 MB for Italy), and WorldCover is read from its public bucket a block at a time. That suits a script or a notebook. A server does better to do it all before its first request, and to work after that without reaching NASA or ESA: sync() does exactly what the lazy path would, in advance, and running it again costs nothing.

  • the yearly archives of country, for each product, from its first year (or first_year) to last year;
  • the static mask of the country, from those VIIRS S-NPP archives;
  • with worldcover, a local copy of ESA WorldCover over that box (~firms_client.landcover.save_worldcover(); the landcover extra).

It writes sync.json in the data directory: what is there, and when it was synced. The current year is not in the archives; the near-real-time area API covers it and is never cached.

  1"""Fill the data directory once, before it is needed: archives, mask, land cover.
  2
  3The library reads lazily: an archive is downloaded the first time it is
  4asked for, the static mask is built the first time it is needed (from every
  5year of the archives, about 30 MB for Italy), and WorldCover is read from
  6its public bucket a block at a time. That suits a script or a notebook. A
  7server does better to do it all before its first request, and to work after
  8that without reaching NASA or ESA: :func:`sync` does exactly what the lazy
  9path would, in advance, and running it again costs nothing.
 10
 11* the yearly archives of ``country``, for each product, from its first
 12  year (or ``first_year``) to last year;
 13* the static mask of the country, from those VIIRS S-NPP archives;
 14* with ``worldcover``, a local copy of ESA WorldCover over that box
 15  (:func:`~firms_client.landcover.save_worldcover`; the ``landcover`` extra).
 16
 17It writes ``sync.json`` in the data directory: what is there, and when it
 18was synced. The current year is not in the archives; the near-real-time
 19area API covers it and is never cached.
 20"""
 21
 22from __future__ import annotations
 23
 24import asyncio
 25import json
 26from dataclasses import asdict, dataclass, field
 27from datetime import UTC, date, datetime
 28from pathlib import Path
 29from typing import Any
 30
 31import httpx
 32
 33from firms_client.client import default_directory, download_archive
 34from firms_client.mask import fetch_static_mask
 35from firms_client.retry import RetryPolicy
 36from firms_client.sources import VIIRS_SNPP, ArchiveProduct, BBox, archive_years
 37
 38#: The manifest :func:`sync` writes in the data directory.
 39MANIFEST = "sync.json"
 40
 41
 42@dataclass(slots=True)
 43class SyncReport:
 44    """What :func:`sync` left in the data directory."""
 45
 46    country: str
 47    directory: str
 48    archives: dict[str, list[int]] = field(default_factory=dict)
 49    missing: dict[str, list[int]] = field(default_factory=dict)
 50    mask: str | None = None
 51    mask_cells: int = 0
 52    worldcover: list[str] = field(default_factory=list)
 53    worldcover_bbox: BBox | None = None
 54    synced: str = ""
 55
 56    def as_dict(self) -> dict[str, Any]:
 57        """JSON-ready."""
 58        return asdict(self)
 59
 60
 61async def sync(
 62    client: httpx.AsyncClient,
 63    country: str,
 64    *,
 65    products: tuple[ArchiveProduct, ...] = (VIIRS_SNPP,),
 66    first_year: int | None = None,
 67    last_year: int | None = None,
 68    worldcover: BBox | None = None,
 69    directory: Path | None = None,
 70    retry: RetryPolicy | None = None,
 71) -> SyncReport:
 72    """Download what the library would read lazily, now; see the module."""
 73    folder = directory or default_directory()
 74    last = last_year if last_year is not None else date.today().year - 1
 75    report = SyncReport(country=country, directory=str(folder))
 76    for product in products:
 77        for year in archive_years(product, until=last):
 78            if first_year is not None and year < first_year:
 79                continue
 80            path = await download_archive(client, product, year, country, folder, retry=retry)
 81            target = report.archives if path is not None else report.missing
 82            target.setdefault(product.slug, []).append(year)
 83    if VIIRS_SNPP in products and report.archives.get(VIIRS_SNPP.slug):
 84        mask = await fetch_static_mask(
 85            client,
 86            country,
 87            first_year=first_year,
 88            last_year=last,
 89            directory=folder,
 90            retry=retry,
 91        )
 92        first = first_year if first_year is not None else VIIRS_SNPP.first_year
 93        name = f"static-mask_{VIIRS_SNPP.slug}_{country}_{first}-{last}.json"
 94        report.mask = str(folder / name)
 95        report.mask_cells = len(mask.cells)
 96    if worldcover is not None:
 97        from firms_client.landcover import save_worldcover
 98
 99        files = await asyncio.to_thread(save_worldcover, worldcover, folder)
100        report.worldcover = [str(f) for f in files]
101        report.worldcover_bbox = worldcover
102    report.synced = datetime.now(UTC).isoformat(timespec="seconds")
103    folder.mkdir(parents=True, exist_ok=True)
104    (folder / MANIFEST).write_text(json.dumps(report.as_dict(), indent=2) + "\n")
105    return report
MANIFEST = 'sync.json'
@dataclass(slots=True)
class SyncReport:
43@dataclass(slots=True)
44class SyncReport:
45    """What :func:`sync` left in the data directory."""
46
47    country: str
48    directory: str
49    archives: dict[str, list[int]] = field(default_factory=dict)
50    missing: dict[str, list[int]] = field(default_factory=dict)
51    mask: str | None = None
52    mask_cells: int = 0
53    worldcover: list[str] = field(default_factory=list)
54    worldcover_bbox: BBox | None = None
55    synced: str = ""
56
57    def as_dict(self) -> dict[str, Any]:
58        """JSON-ready."""
59        return asdict(self)

What sync() left in the data directory.

SyncReport( country: str, directory: str, archives: dict[str, list[int]] = <factory>, missing: dict[str, list[int]] = <factory>, mask: str | None = None, mask_cells: int = 0, worldcover: list[str] = <factory>, worldcover_bbox: tuple[float, float, float, float] | None = None, synced: str = '')
country: str
directory: str
archives: dict[str, list[int]]
missing: dict[str, list[int]]
mask: str | None
mask_cells: int
worldcover: list[str]
worldcover_bbox: tuple[float, float, float, float] | None
synced: str
def as_dict(self) -> dict[str, typing.Any]:
57    def as_dict(self) -> dict[str, Any]:
58        """JSON-ready."""
59        return asdict(self)

JSON-ready.

async def sync( client: httpx.AsyncClient, country: str, *, products: tuple[firms_client.ArchiveProduct, ...] = (ArchiveProduct(slug='viirs-snpp', first_year=2012),), first_year: int | None = None, last_year: int | None = None, worldcover: tuple[float, float, float, float] | None = None, directory: pathlib.Path | None = None, retry: firms_client.RetryPolicy | None = None) -> SyncReport:
 62async def sync(
 63    client: httpx.AsyncClient,
 64    country: str,
 65    *,
 66    products: tuple[ArchiveProduct, ...] = (VIIRS_SNPP,),
 67    first_year: int | None = None,
 68    last_year: int | None = None,
 69    worldcover: BBox | None = None,
 70    directory: Path | None = None,
 71    retry: RetryPolicy | None = None,
 72) -> SyncReport:
 73    """Download what the library would read lazily, now; see the module."""
 74    folder = directory or default_directory()
 75    last = last_year if last_year is not None else date.today().year - 1
 76    report = SyncReport(country=country, directory=str(folder))
 77    for product in products:
 78        for year in archive_years(product, until=last):
 79            if first_year is not None and year < first_year:
 80                continue
 81            path = await download_archive(client, product, year, country, folder, retry=retry)
 82            target = report.archives if path is not None else report.missing
 83            target.setdefault(product.slug, []).append(year)
 84    if VIIRS_SNPP in products and report.archives.get(VIIRS_SNPP.slug):
 85        mask = await fetch_static_mask(
 86            client,
 87            country,
 88            first_year=first_year,
 89            last_year=last,
 90            directory=folder,
 91            retry=retry,
 92        )
 93        first = first_year if first_year is not None else VIIRS_SNPP.first_year
 94        name = f"static-mask_{VIIRS_SNPP.slug}_{country}_{first}-{last}.json"
 95        report.mask = str(folder / name)
 96        report.mask_cells = len(mask.cells)
 97    if worldcover is not None:
 98        from firms_client.landcover import save_worldcover
 99
100        files = await asyncio.to_thread(save_worldcover, worldcover, folder)
101        report.worldcover = [str(f) for f in files]
102        report.worldcover_bbox = worldcover
103    report.synced = datetime.now(UTC).isoformat(timespec="seconds")
104    folder.mkdir(parents=True, exist_ok=True)
105    (folder / MANIFEST).write_text(json.dumps(report.as_dict(), indent=2) + "\n")
106    return report

Download what the library would read lazily, now; see the module.