firms_client.anomaly

Is this season unusual? A value against its own history.

Everyone asks it in August, and an LLM should never answer it from memory. anomaly() compares one year's value with the other years of a series: rank, percentile, and a robust z-score (median and MAD, so that one catastrophic year does not hide the next). season_anomaly() builds the series from a country's archives: fires per year, for a month or the whole year, optionally inside a bbox.

Counts are detections kept by ~firms_client.select(), a proxy for fire activity, not burnt area. Compare a product with itself: MODIS and VIIRS see different pixel sizes.

  1"""Is this season unusual? A value against its own history.
  2
  3Everyone asks it in August, and an LLM should never answer it from memory.
  4:func:`anomaly` compares one year's value with the other years of a
  5series: rank, percentile, and a robust z-score (median and MAD, so that one
  6catastrophic year does not hide the next). :func:`season_anomaly` builds
  7the series from a country's archives: fires per year, for a month or the
  8whole year, optionally inside a bbox.
  9
 10Counts are detections kept by :func:`~firms_client.select`, a proxy for
 11fire activity, not burnt area. Compare a product with itself: MODIS and
 12VIIRS see different pixel sizes.
 13"""
 14
 15from __future__ import annotations
 16
 17import statistics
 18from collections.abc import Mapping
 19from dataclasses import dataclass
 20from datetime import date
 21from typing import TYPE_CHECKING, Any
 22
 23from firms_client.client import fetch_archive
 24from firms_client.hotspots import select, within
 25from firms_client.retry import RetryPolicy
 26from firms_client.sources import VIIRS_SNPP, ArchiveProduct, BBox, archive_years
 27
 28if TYPE_CHECKING:
 29    import httpx
 30
 31#: MAD to standard deviation, for normally distributed data.
 32_MAD_SCALE = 1.4826
 33
 34
 35@dataclass(frozen=True, slots=True)
 36class Anomaly:
 37    """One year's value against the other years of its series."""
 38
 39    year: int
 40    value: float
 41    baseline: dict[int, float]
 42    median: float
 43    mean: float
 44    robust_z: float | None
 45    rank: int
 46    of: int
 47    percentile: float
 48
 49    def describe(self) -> str:
 50        """In words: ``"2021: 6,600, the highest of 14 years (robust z +2.4)"``."""
 51        place = "the highest" if self.rank == 1 else f"{_ordinal(self.rank)} highest"
 52        if self.rank == self.of:
 53            place = "the lowest"
 54        z = f" (robust z {self.robust_z:+.1f})" if self.robust_z is not None else ""
 55        return f"{self.year}: {self.value:,.0f}, {place} of {self.of} years{z}"
 56
 57    def as_dict(self) -> dict[str, Any]:
 58        """JSON-ready, with the description."""
 59        return {
 60            "year": self.year,
 61            "value": self.value,
 62            "median": self.median,
 63            "mean": round(self.mean, 2),
 64            "robust_z": None if self.robust_z is None else round(self.robust_z, 2),
 65            "rank": self.rank,
 66            "of": self.of,
 67            "percentile": round(self.percentile, 1),
 68            "baseline": {str(y): v for y, v in sorted(self.baseline.items())},
 69            "description": self.describe(),
 70        }
 71
 72
 73def anomaly(series: Mapping[int, float], year: int) -> Anomaly:
 74    """``series[year]`` against every other year of ``series``.
 75
 76    ``rank`` is 1 for the highest of all years (ties share the better
 77    rank); ``percentile`` is the share of other years strictly below. The
 78    robust z is ``(value - median) / (1.4826 * MAD)`` over the other years,
 79    ``None`` when they do not vary or are fewer than three.
 80    """
 81    if year not in series:
 82        raise ValueError(f"{year} is not in the series")
 83    value = float(series[year])
 84    baseline = {y: float(v) for y, v in series.items() if y != year}
 85    if not baseline:
 86        raise ValueError("the series needs at least one other year")
 87    others = list(baseline.values())
 88    median = statistics.median(others)
 89    mad = statistics.median(abs(v - median) for v in others)
 90    robust_z = (value - median) / (_MAD_SCALE * mad) if mad and len(others) >= 3 else None
 91    return Anomaly(
 92        year=year,
 93        value=value,
 94        baseline=baseline,
 95        median=median,
 96        mean=statistics.fmean(others),
 97        robust_z=robust_z,
 98        rank=1 + sum(1 for v in others if v > value),
 99        of=len(others) + 1,
100        percentile=100 * sum(1 for v in others if v < value) / len(others),
101    )
102
103
104async def season_anomaly(
105    client: httpx.AsyncClient,
106    country: str,
107    year: int,
108    *,
109    month: int | None = None,
110    bbox: BBox | None = None,
111    product: ArchiveProduct = VIIRS_SNPP,
112    first_year: int | None = None,
113    last_year: int | None = None,
114    retry: RetryPolicy | None = None,
115) -> Anomaly:
116    """Fires in ``year`` (or in its ``month``) against the other archive years.
117
118    The series runs from ``first_year`` (default: the product's first) to
119    ``last_year`` (default: last year); years not published are skipped.
120    """
121    if month is not None and not 1 <= month <= 12:
122        raise ValueError("month is 1 to 12")
123    last = last_year if last_year is not None else max(year, date.today().year - 1)
124    first = first_year if first_year is not None else product.first_year
125    series: dict[int, float] = {}
126    for y in archive_years(product, until=last):
127        if y < first:
128            continue
129        rows = await fetch_archive(client, product, y, country, retry=retry)
130        if rows is None:
131            continue
132        fires = select(within(rows, bbox))
133        series[y] = sum(1 for h in fires if month is None or h.acq_date.month == month)
134    if year not in series:
135        raise ValueError(f"no {product.slug} archive for {country} in {year}")
136    return anomaly(series, year)
137
138
139def _ordinal(n: int) -> str:
140    suffix = "th" if 10 <= n % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
141    return f"{n}{suffix}"
@dataclass(frozen=True, slots=True)
class Anomaly:
36@dataclass(frozen=True, slots=True)
37class Anomaly:
38    """One year's value against the other years of its series."""
39
40    year: int
41    value: float
42    baseline: dict[int, float]
43    median: float
44    mean: float
45    robust_z: float | None
46    rank: int
47    of: int
48    percentile: float
49
50    def describe(self) -> str:
51        """In words: ``"2021: 6,600, the highest of 14 years (robust z +2.4)"``."""
52        place = "the highest" if self.rank == 1 else f"{_ordinal(self.rank)} highest"
53        if self.rank == self.of:
54            place = "the lowest"
55        z = f" (robust z {self.robust_z:+.1f})" if self.robust_z is not None else ""
56        return f"{self.year}: {self.value:,.0f}, {place} of {self.of} years{z}"
57
58    def as_dict(self) -> dict[str, Any]:
59        """JSON-ready, with the description."""
60        return {
61            "year": self.year,
62            "value": self.value,
63            "median": self.median,
64            "mean": round(self.mean, 2),
65            "robust_z": None if self.robust_z is None else round(self.robust_z, 2),
66            "rank": self.rank,
67            "of": self.of,
68            "percentile": round(self.percentile, 1),
69            "baseline": {str(y): v for y, v in sorted(self.baseline.items())},
70            "description": self.describe(),
71        }

One year's value against the other years of its series.

Anomaly( year: int, value: float, baseline: dict[int, float], median: float, mean: float, robust_z: float | None, rank: int, of: int, percentile: float)
year: int
value: float
baseline: dict[int, float]
median: float
mean: float
robust_z: float | None
rank: int
of: int
percentile: float
def describe(self) -> str:
50    def describe(self) -> str:
51        """In words: ``"2021: 6,600, the highest of 14 years (robust z +2.4)"``."""
52        place = "the highest" if self.rank == 1 else f"{_ordinal(self.rank)} highest"
53        if self.rank == self.of:
54            place = "the lowest"
55        z = f" (robust z {self.robust_z:+.1f})" if self.robust_z is not None else ""
56        return f"{self.year}: {self.value:,.0f}, {place} of {self.of} years{z}"

In words: "2021: 6,600, the highest of 14 years (robust z +2.4)".

def as_dict(self) -> dict[str, typing.Any]:
58    def as_dict(self) -> dict[str, Any]:
59        """JSON-ready, with the description."""
60        return {
61            "year": self.year,
62            "value": self.value,
63            "median": self.median,
64            "mean": round(self.mean, 2),
65            "robust_z": None if self.robust_z is None else round(self.robust_z, 2),
66            "rank": self.rank,
67            "of": self.of,
68            "percentile": round(self.percentile, 1),
69            "baseline": {str(y): v for y, v in sorted(self.baseline.items())},
70            "description": self.describe(),
71        }

JSON-ready, with the description.

def anomaly(series: Mapping[int, float], year: int) -> Anomaly:
 74def anomaly(series: Mapping[int, float], year: int) -> Anomaly:
 75    """``series[year]`` against every other year of ``series``.
 76
 77    ``rank`` is 1 for the highest of all years (ties share the better
 78    rank); ``percentile`` is the share of other years strictly below. The
 79    robust z is ``(value - median) / (1.4826 * MAD)`` over the other years,
 80    ``None`` when they do not vary or are fewer than three.
 81    """
 82    if year not in series:
 83        raise ValueError(f"{year} is not in the series")
 84    value = float(series[year])
 85    baseline = {y: float(v) for y, v in series.items() if y != year}
 86    if not baseline:
 87        raise ValueError("the series needs at least one other year")
 88    others = list(baseline.values())
 89    median = statistics.median(others)
 90    mad = statistics.median(abs(v - median) for v in others)
 91    robust_z = (value - median) / (_MAD_SCALE * mad) if mad and len(others) >= 3 else None
 92    return Anomaly(
 93        year=year,
 94        value=value,
 95        baseline=baseline,
 96        median=median,
 97        mean=statistics.fmean(others),
 98        robust_z=robust_z,
 99        rank=1 + sum(1 for v in others if v > value),
100        of=len(others) + 1,
101        percentile=100 * sum(1 for v in others if v < value) / len(others),
102    )

series[year] against every other year of series.

rank is 1 for the highest of all years (ties share the better rank); percentile is the share of other years strictly below. The robust z is (value - median) / (1.4826 * MAD) over the other years, None when they do not vary or are fewer than three.

async def season_anomaly( client: httpx.AsyncClient, country: str, year: int, *, month: int | None = None, bbox: tuple[float, float, float, float] | None = None, product: firms_client.ArchiveProduct = ArchiveProduct(slug='viirs-snpp', first_year=2012), first_year: int | None = None, last_year: int | None = None, retry: firms_client.RetryPolicy | None = None) -> Anomaly:
105async def season_anomaly(
106    client: httpx.AsyncClient,
107    country: str,
108    year: int,
109    *,
110    month: int | None = None,
111    bbox: BBox | None = None,
112    product: ArchiveProduct = VIIRS_SNPP,
113    first_year: int | None = None,
114    last_year: int | None = None,
115    retry: RetryPolicy | None = None,
116) -> Anomaly:
117    """Fires in ``year`` (or in its ``month``) against the other archive years.
118
119    The series runs from ``first_year`` (default: the product's first) to
120    ``last_year`` (default: last year); years not published are skipped.
121    """
122    if month is not None and not 1 <= month <= 12:
123        raise ValueError("month is 1 to 12")
124    last = last_year if last_year is not None else max(year, date.today().year - 1)
125    first = first_year if first_year is not None else product.first_year
126    series: dict[int, float] = {}
127    for y in archive_years(product, until=last):
128        if y < first:
129            continue
130        rows = await fetch_archive(client, product, y, country, retry=retry)
131        if rows is None:
132            continue
133        fires = select(within(rows, bbox))
134        series[y] = sum(1 for h in fires if month is None or h.acq_date.month == month)
135    if year not in series:
136        raise ValueError(f"no {product.slug} archive for {country} in {year}")
137    return anomaly(series, year)

Fires in year (or in its month) against the other archive years.

The series runs from first_year (default: the product's first) to last_year (default: last year); years not published are skipped.