firms_client
Client for NASA FIRMS active-fire detections.
1"""Client for NASA FIRMS active-fire detections.""" 2 3from importlib.metadata import version 4 5from firms_client.anomaly import Anomaly, anomaly, season_anomaly 6from firms_client.bulletin import ( 7 Bulletin, 8 BulletinError, 9 ClaudeWriter, 10 Place, 11 bulletin_facts, 12 check_grounding, 13 draft_bulletin, 14 nearest_places, 15) 16from firms_client.cells import ( 17 CellStats, 18 DegreeGrid, 19 Grid, 20 LaeaGrid, 21 cell_stats, 22 laea, 23 laea_inverse, 24) 25from firms_client.check import check_text 26from firms_client.client import ( 27 ENV_DATA_DIR, 28 ENV_DATA_ROOT, 29 ENV_MAP_KEY, 30 default_directory, 31 download_archive, 32 env_file_value, 33 fetch_archive, 34 fetch_archive_csv, 35 fetch_area, 36 fetch_area_range, 37 map_key_from_env, 38) 39from firms_client.errors import FirmsError 40from firms_client.events import FireEvent, cluster, distance_m 41from firms_client.export import CSV_COLUMNS, to_csv, to_geojson 42from firms_client.hotspots import ( 43 ACTIVE_VOLCANO, 44 OFFSHORE, 45 STATIC_LAND_SOURCE, 46 VEGETATION_FIRE, 47 ConfidenceLevel, 48 Hotspot, 49 confidence_level, 50 is_hotspot_csv, 51 parse_csv, 52 select, 53 within, 54) 55from firms_client.init import ( 56 InitReport, 57 download_worldcover_tile, 58 init, 59 worldcover_tiles, 60) 61from firms_client.landcover import ( 62 WORLDCOVER_CLASSES, 63 BurningRules, 64 BurningVerdict, 65 WorldCover, 66 classify_burning, 67 event_land_cover, 68 land_kind, 69 save_worldcover, 70) 71from firms_client.mask import ( 72 CellVerdict, 73 MaskRules, 74 StaticMask, 75 build_static_mask, 76 fetch_static_mask, 77) 78from firms_client.reliability import RELIABLE_FROM, Reliability, Seen, seen, trust 79from firms_client.retry import RetryPolicy 80from firms_client.service import ( 81 MissingDays, 82 check_columns, 83 data_availability, 84 is_map_key, 85 latest_archive, 86 map_key_status, 87 missing_days, 88) 89from firms_client.sources import ( 90 ARCHIVE_PRODUCTS, 91 MAX_AREA_DAYS, 92 MODIS, 93 NRT_SOURCES, 94 SP_SOURCES, 95 VIIRS_SNPP, 96 ArchiveProduct, 97 BBox, 98 archive_filename, 99 archive_url, 100 archive_years, 101 area_url, 102 area_windows, 103) 104from firms_client.summary import ATTRIBUTION, TYPE_NAMES, summarize 105from firms_client.sync import SyncReport, sync 106 107__version__ = version("firms-client") 108 109__all__ = [ 110 "ACTIVE_VOLCANO", 111 "ARCHIVE_PRODUCTS", 112 "ATTRIBUTION", 113 "CSV_COLUMNS", 114 "ENV_DATA_DIR", 115 "ENV_DATA_ROOT", 116 "ENV_MAP_KEY", 117 "MAX_AREA_DAYS", 118 "MODIS", 119 "NRT_SOURCES", 120 "OFFSHORE", 121 "RELIABLE_FROM", 122 "SP_SOURCES", 123 "STATIC_LAND_SOURCE", 124 "TYPE_NAMES", 125 "VEGETATION_FIRE", 126 "VIIRS_SNPP", 127 "WORLDCOVER_CLASSES", 128 "Anomaly", 129 "ArchiveProduct", 130 "BBox", 131 "Bulletin", 132 "BulletinError", 133 "BurningRules", 134 "BurningVerdict", 135 "CellStats", 136 "CellVerdict", 137 "ClaudeWriter", 138 "ConfidenceLevel", 139 "DegreeGrid", 140 "FireEvent", 141 "FirmsError", 142 "Grid", 143 "Hotspot", 144 "InitReport", 145 "LaeaGrid", 146 "MaskRules", 147 "MissingDays", 148 "Place", 149 "Reliability", 150 "RetryPolicy", 151 "Seen", 152 "StaticMask", 153 "SyncReport", 154 "WorldCover", 155 "__version__", 156 "anomaly", 157 "archive_filename", 158 "archive_url", 159 "archive_years", 160 "area_url", 161 "area_windows", 162 "build_static_mask", 163 "bulletin_facts", 164 "cell_stats", 165 "check_columns", 166 "check_grounding", 167 "check_text", 168 "classify_burning", 169 "cluster", 170 "confidence_level", 171 "data_availability", 172 "default_directory", 173 "distance_m", 174 "download_archive", 175 "download_worldcover_tile", 176 "draft_bulletin", 177 "env_file_value", 178 "event_land_cover", 179 "fetch_archive", 180 "fetch_archive_csv", 181 "fetch_area", 182 "fetch_area_range", 183 "fetch_static_mask", 184 "init", 185 "is_hotspot_csv", 186 "is_map_key", 187 "laea", 188 "laea_inverse", 189 "land_kind", 190 "latest_archive", 191 "map_key_from_env", 192 "map_key_status", 193 "missing_days", 194 "nearest_places", 195 "parse_csv", 196 "save_worldcover", 197 "season_anomaly", 198 "seen", 199 "select", 200 "summarize", 201 "sync", 202 "to_csv", 203 "to_geojson", 204 "trust", 205 "within", 206 "worldcover_tiles", 207]
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.
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)".
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.
48@dataclass(frozen=True, slots=True) 49class ArchiveProduct: 50 """A product published as per-country yearly archives.""" 51 52 slug: str 53 first_year: int
A product published as per-country yearly archives.
198@dataclass(frozen=True, slots=True) 199class Bulletin: 200 """A draft for an operator, with what did and did not check out.""" 201 202 headline: str 203 body: str 204 key_facts: list[str] 205 places_mentioned: list[str] 206 caveats: list[str] 207 problems: list[str] = field(default_factory=list) 208 attempts: int = 1 209 status: str = "draft" 210 211 @property 212 def grounded(self) -> bool: 213 """Every number and place in the text is in the facts.""" 214 return not self.problems 215 216 def as_text(self) -> str: 217 """Headline, body and key facts, for a message or a log.""" 218 facts = "\n".join(f"- {f}" for f in self.key_facts) 219 return f"{self.headline}\n\n{self.body}\n\n{facts}\n"
A draft for an operator, with what did and did not check out.
285class BulletinError(Exception): 286 """The writer could not produce a bulletin (a refusal, an empty answer)."""
The writer could not produce a bulletin (a refusal, an empty answer).
85@dataclass(frozen=True, slots=True) 86class BurningRules: 87 """The thresholds of :func:`classify_burning`.""" 88 89 natural_share: float = 0.5 90 crop_share: float = 0.7 91 crop_natural_max: float = 0.15 92 crop_max_days: int = 2 93 crop_max_hotspots: int = 15 94 artificial_share: float = 0.5
The thresholds of classify_burning().
97@dataclass(frozen=True, slots=True) 98class BurningVerdict: 99 """What burned, by the land cover under an event.""" 100 101 kind: Kind 102 reason: str 103 shares: dict[str, float] 104 sampled: int 105 106 def as_dict(self) -> dict[str, Any]: 107 """JSON-ready.""" 108 return { 109 "kind": self.kind, 110 "reason": self.reason, 111 "land_cover": self.shares, 112 "hotspots_sampled": self.sampled, 113 }
What burned, by the land cover under an event.
219@dataclass(frozen=True, slots=True) 220class CellStats[C: Hashable]: 221 """What FIRMS says about one cell; ``None`` is not measured, never 0.""" 222 223 cell: C 224 area_km2: float 225 measured: bool 226 detections: int | None 227 fire_days: int | None 228 fire_days_per_km2: float | None 229 cropland: float | None 230 natural: float | None 231 land_days: int 232 static_km: float | None 233 score: float | None 234 reason: str | None = None 235 236 def as_dict(self) -> dict[str, Any]: 237 """JSON-ready, the cell as given.""" 238 return { 239 "cell": self.cell, 240 "area_km2": self.area_km2, 241 "measured": self.measured, 242 "detections": self.detections, 243 "fire_days": self.fire_days, 244 "fire_days_per_km2": self.fire_days_per_km2, 245 "cropland": self.cropland, 246 "natural": self.natural, 247 "land_days": self.land_days, 248 "static_km": self.static_km, 249 "score": self.score, 250 "reason": self.reason, 251 }
What FIRMS says about one cell; None is not measured, never 0.
236 def as_dict(self) -> dict[str, Any]: 237 """JSON-ready, the cell as given.""" 238 return { 239 "cell": self.cell, 240 "area_km2": self.area_km2, 241 "measured": self.measured, 242 "detections": self.detections, 243 "fire_days": self.fire_days, 244 "fire_days_per_km2": self.fire_days_per_km2, 245 "cropland": self.cropland, 246 "natural": self.natural, 247 "land_days": self.land_days, 248 "static_km": self.static_km, 249 "score": self.score, 250 "reason": self.reason, 251 }
JSON-ready, the cell as given.
52@dataclass(frozen=True, slots=True) 53class CellVerdict: 54 """Why a cell is static, and the history behind it.""" 55 56 detection_type: int 57 reason: Reason 58 detections: int 59 fire_days: int 60 years: int 61 months: int 62 static_share: float
Why a cell is static, and the history behind it.
289class ClaudeWriter: 290 """A :class:`Writer` on the Anthropic API, with structured output. 291 292 Credentials come from the environment, as for any Anthropic client 293 (``ANTHROPIC_API_KEY``, or an ``ant auth login`` profile). Refusals are 294 retried server-side on Anthropic's recommended fallback model. 295 """ 296 297 def __init__( 298 self, 299 client: AsyncAnthropic | None = None, 300 *, 301 model: str = "claude-opus-5-5", 302 effort: Effort = "medium", 303 max_tokens: int = 16000, 304 ) -> None: 305 if client is None: 306 from anthropic import AsyncAnthropic 307 308 client = AsyncAnthropic() 309 self.client = client 310 self.model = model 311 self.effort = effort 312 self.max_tokens = max_tokens 313 314 async def __call__( 315 self, system: str, facts_json: str, schema: dict[str, Any] 316 ) -> dict[str, Any]: 317 messages: list[BetaMessageParam] = [{"role": "user", "content": facts_json}] 318 config: BetaOutputConfigParam = { 319 "effort": self.effort, 320 "format": {"type": "json_schema", "schema": schema}, 321 } 322 response = await self.client.beta.messages.create( 323 model=self.model, 324 max_tokens=self.max_tokens, 325 system=system, 326 messages=messages, 327 output_config=config, 328 betas=["server-side-fallback-2026-07-01"], 329 fallbacks="default", 330 ) 331 if response.stop_reason == "refusal": 332 raise BulletinError(f"the model declined to write the bulletin ({response.model})") 333 text = next((b.text for b in response.content if b.type == "text"), "") 334 if not text: 335 raise BulletinError(f"empty answer (stop_reason {response.stop_reason})") 336 data: dict[str, Any] = json.loads(text) 337 return data
A Writer on the Anthropic API, with structured output.
Credentials come from the environment, as for any Anthropic client
(ANTHROPIC_API_KEY, or an ant auth login profile). Refusals are
retried server-side on Anthropic's recommended fallback model.
297 def __init__( 298 self, 299 client: AsyncAnthropic | None = None, 300 *, 301 model: str = "claude-opus-5-5", 302 effort: Effort = "medium", 303 max_tokens: int = 16000, 304 ) -> None: 305 if client is None: 306 from anthropic import AsyncAnthropic 307 308 client = AsyncAnthropic() 309 self.client = client 310 self.model = model 311 self.effort = effort 312 self.max_tokens = max_tokens
191@dataclass(frozen=True, slots=True) 192class DegreeGrid: 193 """Cells of ``step`` degrees; cells are ``(i, j)`` = floor(lat / step), floor(lon / step).""" 194 195 step: float = 0.01 196 197 def cell_of(self, latitude: float, longitude: float) -> tuple[int, int]: 198 return math.floor(latitude / self.step), math.floor(longitude / self.step) 199 200 def area_km2(self, cell: tuple[int, int]) -> float: 201 south = math.radians(cell[0] * self.step) 202 north = math.radians((cell[0] + 1) * self.step) 203 return _EARTH_KM**2 * math.radians(self.step) * abs(math.sin(north) - math.sin(south)) 204 205 def centre(self, cell: tuple[int, int]) -> tuple[float, float]: 206 return (cell[0] + 0.5) * self.step, (cell[1] + 0.5) * self.step
Cells of step degrees; cells are (i, j) = floor(lat / step), floor(lon / step).
40@dataclass(frozen=True, slots=True) 41class FireEvent: 42 """Hotspots that belong together, with the numbers people ask for.""" 43 44 hotspots: tuple[Hotspot, ...] 45 start: date 46 end: date 47 latitude: float 48 longitude: float 49 bbox: BBox 50 peak_frp_mw: float | None 51 total_frp_mw: float 52 overpasses: int 53 54 @classmethod 55 def of(cls, hotspots: Sequence[Hotspot]) -> FireEvent: 56 """The event made of ``hotspots`` (at least one).""" 57 if not hotspots: 58 raise ValueError("an event needs at least one hotspot") 59 rows = tuple(sorted(hotspots, key=lambda h: (h.acq_date, h.acq_time))) 60 lats = [h.latitude for h in rows] 61 lons = [h.longitude for h in rows] 62 frp = [h.frp_mw for h in rows if h.frp_mw is not None] 63 return cls( 64 hotspots=rows, 65 start=rows[0].acq_date, 66 end=rows[-1].acq_date, 67 latitude=sum(lats) / len(lats), 68 longitude=sum(lons) / len(lons), 69 bbox=(min(lons), min(lats), max(lons), max(lats)), 70 peak_frp_mw=max(frp) if frp else None, 71 total_frp_mw=sum(frp), 72 overpasses=len({(h.acq_date, h.acq_time, h.satellite) for h in rows}), 73 ) 74 75 @property 76 def size(self) -> int: 77 """Number of hotspots.""" 78 return len(self.hotspots) 79 80 @property 81 def days(self) -> int: 82 """Calendar days from the first detection to the last, both included.""" 83 return (self.end - self.start).days + 1 84 85 def as_dict(self) -> dict[str, Any]: 86 """The event without its hotspots, ready for JSON (and for an LLM).""" 87 return { 88 "start": self.start.isoformat(), 89 "end": self.end.isoformat(), 90 "days": self.days, 91 "latitude": round(self.latitude, 5), 92 "longitude": round(self.longitude, 5), 93 "bbox": [round(c, 5) for c in self.bbox], 94 "hotspots": self.size, 95 "overpasses": self.overpasses, 96 "peak_frp_mw": self.peak_frp_mw, 97 "total_frp_mw": round(self.total_frp_mw, 2), 98 }
Hotspots that belong together, with the numbers people ask for.
54 @classmethod 55 def of(cls, hotspots: Sequence[Hotspot]) -> FireEvent: 56 """The event made of ``hotspots`` (at least one).""" 57 if not hotspots: 58 raise ValueError("an event needs at least one hotspot") 59 rows = tuple(sorted(hotspots, key=lambda h: (h.acq_date, h.acq_time))) 60 lats = [h.latitude for h in rows] 61 lons = [h.longitude for h in rows] 62 frp = [h.frp_mw for h in rows if h.frp_mw is not None] 63 return cls( 64 hotspots=rows, 65 start=rows[0].acq_date, 66 end=rows[-1].acq_date, 67 latitude=sum(lats) / len(lats), 68 longitude=sum(lons) / len(lons), 69 bbox=(min(lons), min(lats), max(lons), max(lats)), 70 peak_frp_mw=max(frp) if frp else None, 71 total_frp_mw=sum(frp), 72 overpasses=len({(h.acq_date, h.acq_time, h.satellite) for h in rows}), 73 )
The event made of hotspots (at least one).
80 @property 81 def days(self) -> int: 82 """Calendar days from the first detection to the last, both included.""" 83 return (self.end - self.start).days + 1
Calendar days from the first detection to the last, both included.
85 def as_dict(self) -> dict[str, Any]: 86 """The event without its hotspots, ready for JSON (and for an LLM).""" 87 return { 88 "start": self.start.isoformat(), 89 "end": self.end.isoformat(), 90 "days": self.days, 91 "latitude": round(self.latitude, 5), 92 "longitude": round(self.longitude, 5), 93 "bbox": [round(c, 5) for c in self.bbox], 94 "hotspots": self.size, 95 "overpasses": self.overpasses, 96 "peak_frp_mw": self.peak_frp_mw, 97 "total_frp_mw": round(self.total_frp_mw, 2), 98 }
The event without its hotspots, ready for JSON (and for an LLM).
2class FirmsError(Exception): 3 """FIRMS answered, but not with a hotspot CSV (bad MAP_KEY, unknown source, …)."""
FIRMS answered, but not with a hotspot CSV (bad MAP_KEY, unknown source, …).
131class Grid[C: Hashable](Protocol): 132 """Anything that puts a position in a cell and knows the cell's size.""" 133 134 def cell_of(self, latitude: float, longitude: float) -> C | None: 135 """The cell of a position, or ``None`` when the grid does not cover it.""" 136 ... 137 138 def area_km2(self, cell: C) -> float: 139 """The cell's area in km².""" 140 ... 141 142 def centre(self, cell: C) -> tuple[float, float]: 143 """``(latitude, longitude)`` of the cell's centre.""" 144 ...
Anything that puts a position in a cell and knows the cell's size.
1771def _no_init_or_replace_init(self, *args, **kwargs): 1772 cls = type(self) 1773 1774 if cls._is_protocol: 1775 raise TypeError('Protocols cannot be instantiated') 1776 1777 # Already using a custom `__init__`. No need to calculate correct 1778 # `__init__` to call. This can lead to RecursionError. See bpo-45121. 1779 if cls.__init__ is not _no_init_or_replace_init: 1780 return 1781 1782 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. 1783 # The first instantiation of the subclass will call `_no_init_or_replace_init` which 1784 # searches for a proper new `__init__` in the MRO. The new `__init__` 1785 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent 1786 # instantiation of the protocol subclass will thus use the new 1787 # `__init__` and no longer call `_no_init_or_replace_init`. 1788 for base in cls.__mro__: 1789 init = base.__dict__.get('__init__', _no_init_or_replace_init) 1790 if init is not _no_init_or_replace_init: 1791 cls.__init__ = init 1792 break 1793 else: 1794 # should not happen 1795 cls.__init__ = object.__init__ 1796 1797 cls.__init__(self, *args, **kwargs)
134 def cell_of(self, latitude: float, longitude: float) -> C | None: 135 """The cell of a position, or ``None`` when the grid does not cover it.""" 136 ...
The cell of a position, or None when the grid does not cover it.
59@dataclass(frozen=True, slots=True) 60class Hotspot: 61 """One detection. ``acq_time`` is UTC ``HHMM`` as an integer (``126`` = 01:26). 62 63 The fields after ``detection_type`` are the rest of the CSV, for 64 analysis and models: the 11 µm brightness (``bright_ti5`` for VIIRS, 65 ``bright_t31`` for MODIS), the pixel size along scan and track (km) and 66 the processing version (``2``, ``2.0NRT``, ``61.03``). They default to 67 ``None``, so a ``Hotspot`` built by hand needs only the first eleven. 68 """ 69 70 latitude: float 71 longitude: float 72 acq_date: date 73 acq_time: int 74 confidence: str | None 75 frp_mw: float | None 76 brightness_k: float | None 77 daynight: str | None 78 satellite: str | None 79 instrument: str | None 80 detection_type: int | None 81 brightness_t5_k: float | None = None 82 scan_km: float | None = None 83 track_km: float | None = None 84 version: str | None = None 85 86 @property 87 def is_vegetation_fire(self) -> bool | None: 88 """``type == 0``; ``None`` when the row does not say.""" 89 return None if self.detection_type is None else self.detection_type == VEGETATION_FIRE
One detection. acq_time is UTC HHMM as an integer (126 = 01:26).
The fields after detection_type are the rest of the CSV, for
analysis and models: the 11 µm brightness (bright_ti5 for VIIRS,
bright_t31 for MODIS), the pixel size along scan and track (km) and
the processing version (2, 2.0NRT, 61.03). They default to
None, so a Hotspot built by hand needs only the first eleven.
52@dataclass(slots=True) 53class InitReport: 54 """What :func:`init` did, file by file (names, not paths).""" 55 56 directory: str 57 downloaded: list[str] = field(default_factory=list) 58 skipped: list[str] = field(default_factory=list) 59 missing: list[str] = field(default_factory=list) 60 failed: dict[str, str] = field(default_factory=dict) 61 62 @property 63 def ok(self) -> bool: 64 """No file failed: what exists is all there is.""" 65 return not self.failed 66 67 def as_dict(self) -> dict[str, Any]: 68 """JSON-ready.""" 69 return {**asdict(self), "ok": self.ok}
What init() did, file by file (names, not paths).
147@dataclass(frozen=True, slots=True) 148class LaeaGrid: 149 """Square cells of ``size_m`` metres in ETRS89-LAEA; cells are ``(row, col)``. 150 151 ``row`` counts northwards and ``col`` eastwards from ``origin`` (the 152 south-west corner of cell ``(0, 0)``, in EPSG:3035 metres). The default 153 origin is that of the EEA reference grid. 154 """ 155 156 size_m: float = 1000.0 157 origin: tuple[float, float] = (0.0, 0.0) 158 159 def cell_of(self, latitude: float, longitude: float) -> tuple[int, int]: 160 x, y = laea(latitude, longitude) 161 return ( 162 math.floor((y - self.origin[1]) / self.size_m), 163 math.floor((x - self.origin[0]) / self.size_m), 164 ) 165 166 def area_km2(self, cell: tuple[int, int]) -> float: # noqa: ARG002 (the Grid protocol) 167 return self.size_m * self.size_m / 1e6 168 169 def centre(self, cell: tuple[int, int]) -> tuple[float, float]: 170 row, col = cell 171 return laea_inverse( 172 self.origin[0] + (col + 0.5) * self.size_m, 173 self.origin[1] + (row + 0.5) * self.size_m, 174 ) 175 176 def code(self, cell: tuple[int, int]) -> str: 177 """The EEA reference-grid code of a cell: ``1kmE4321N3210``. 178 179 Only for a grid of whole kilometres on a whole-kilometre origin, as 180 the reference grid is. 181 """ 182 km, rest = divmod(self.size_m, 1000) 183 if rest or self.origin[0] % self.size_m or self.origin[1] % self.size_m: 184 raise ValueError("not a grid of the EEA reference: whole km cells on a km origin") 185 row, col = cell 186 east = int((self.origin[0] + col * self.size_m) // self.size_m) 187 north = int((self.origin[1] + row * self.size_m) // self.size_m) 188 return f"{int(km)}kmE{east}N{north}"
Square cells of size_m metres in ETRS89-LAEA; cells are (row, col).
row counts northwards and col eastwards from origin (the
south-west corner of cell (0, 0), in EPSG:3035 metres). The default
origin is that of the EEA reference grid.
176 def code(self, cell: tuple[int, int]) -> str: 177 """The EEA reference-grid code of a cell: ``1kmE4321N3210``. 178 179 Only for a grid of whole kilometres on a whole-kilometre origin, as 180 the reference grid is. 181 """ 182 km, rest = divmod(self.size_m, 1000) 183 if rest or self.origin[0] % self.size_m or self.origin[1] % self.size_m: 184 raise ValueError("not a grid of the EEA reference: whole km cells on a km origin") 185 row, col = cell 186 east = int((self.origin[0] + col * self.size_m) // self.size_m) 187 north = int((self.origin[1] + row * self.size_m) // self.size_m) 188 return f"{int(km)}kmE{east}N{north}"
The EEA reference-grid code of a cell: 1kmE4321N3210.
Only for a grid of whole kilometres on a whole-kilometre origin, as the reference grid is.
65@dataclass(frozen=True, slots=True) 66class MaskRules: 67 """The thresholds :func:`build_static_mask` applies; kept with the mask.""" 68 69 cell_deg: float = 0.01 70 min_detections: int = 3 71 min_static_share: float = 0.5 72 persistent_fire_days: int = 30 73 persistent_years: int = 6 74 persistent_months: int = 8
The thresholds build_static_mask() applies; kept with the mask.
80@dataclass(frozen=True, slots=True) 81class MissingDays: 82 """Days with no data in FIRMS, by satellite: standard (SP) and near real time (NRT).""" 83 84 standard: dict[str, frozenset[date]] = field(default_factory=dict) 85 near_real_time: dict[str, frozenset[date]] = field(default_factory=dict) 86 87 def missing(self, satellite: str, day: date, *, nrt: bool = False) -> bool: 88 """Whether ``satellite`` (``VIIRS_SNPP``, …) has no data on ``day``.""" 89 table = self.near_real_time if nrt else self.standard 90 return day in table.get(satellite, frozenset()) 91 92 def as_dict(self) -> dict[str, Any]: 93 """JSON-ready: sorted ISO dates.""" 94 return { 95 kind: {sat: sorted(d.isoformat() for d in days) for sat, days in table.items()} 96 for kind, table in ( 97 ("standard", self.standard), 98 ("near_real_time", self.near_real_time), 99 ) 100 }
Days with no data in FIRMS, by satellite: standard (SP) and near real time (NRT).
87 def missing(self, satellite: str, day: date, *, nrt: bool = False) -> bool: 88 """Whether ``satellite`` (``VIIRS_SNPP``, …) has no data on ``day``.""" 89 table = self.near_real_time if nrt else self.standard 90 return day in table.get(satellite, frozenset())
Whether satellite (VIIRS_SNPP, …) has no data on day.
92 def as_dict(self) -> dict[str, Any]: 93 """JSON-ready: sorted ISO dates.""" 94 return { 95 kind: {sat: sorted(d.isoformat() for d in days) for sat, days in table.items()} 96 for kind, table in ( 97 ("standard", self.standard), 98 ("near_real_time", self.near_real_time), 99 ) 100 }
JSON-ready: sorted ISO dates.
89@dataclass(frozen=True, slots=True) 90class Place: 91 """A named place from your gazetteer: a town, a village, a facility.""" 92 93 name: str 94 latitude: float 95 longitude: float 96 kind: str = ""
A named place from your gazetteer: a town, a village, a facility.
82@dataclass(frozen=True, slots=True) 83class Reliability: 84 """How far a detection at a place can be read as a vegetation fire.""" 85 86 latitude: float 87 longitude: float 88 score: float | None 89 reliable: bool 90 static: float | None 91 land: float | None 92 land_cover: dict[str, float] 93 reasons: tuple[str, ...] 94 95 def as_dict(self) -> dict[str, Any]: 96 """JSON-ready.""" 97 return { 98 "latitude": self.latitude, 99 "longitude": self.longitude, 100 "score": self.score, 101 "reliable": self.reliable, 102 "parts": {"static": self.static, "land": self.land}, 103 "land_cover": self.land_cover, 104 "reasons": list(self.reasons), 105 }
How far a detection at a place can be read as a vegetation fire.
95 def as_dict(self) -> dict[str, Any]: 96 """JSON-ready.""" 97 return { 98 "latitude": self.latitude, 99 "longitude": self.longitude, 100 "score": self.score, 101 "reliable": self.reliable, 102 "parts": {"static": self.static, "land": self.land}, 103 "land_cover": self.land_cover, 104 "reasons": list(self.reasons), 105 }
JSON-ready.
24@dataclass(frozen=True, slots=True) 25class RetryPolicy: 26 """How many times to try, and how long to wait in between. 27 28 ``attempts`` counts the first try too. The wait doubles from 29 ``backoff_s`` up to ``max_backoff_s``; a ``Retry-After`` header in 30 seconds wins, within the same cap. Responses in ``statuses`` and, when 31 ``transport_errors`` is true, :class:`httpx.TransportError` (timeouts, 32 refused or dropped connections) are retried. The last attempt behaves 33 as if there were no policy: its response or error is what you get. 34 """ 35 36 attempts: int = 3 37 backoff_s: float = 1.0 38 max_backoff_s: float = 30.0 39 statuses: frozenset[int] = frozenset({429, 500, 502, 503, 504}) 40 transport_errors: bool = True 41 42 def __post_init__(self) -> None: 43 if self.attempts < 1: 44 raise ValueError("attempts must be at least 1") 45 46 def delay(self, attempt: int, retry_after: str | None = None) -> float: 47 """Seconds to wait after the failed ``attempt`` (0-based).""" 48 wait = self.backoff_s * float(2**attempt) 49 if retry_after is not None: 50 with contextlib.suppress(ValueError): # an HTTP date: keep the backoff 51 wait = max(float(retry_after), 0.0) 52 return min(wait, self.max_backoff_s)
How many times to try, and how long to wait in between.
attempts counts the first try too. The wait doubles from
backoff_s up to max_backoff_s; a Retry-After header in
seconds wins, within the same cap. Responses in statuses and, when
transport_errors is true, httpx.TransportError (timeouts,
refused or dropped connections) are retried. The last attempt behaves
as if there were no policy: its response or error is what you get.
46 def delay(self, attempt: int, retry_after: str | None = None) -> float: 47 """Seconds to wait after the failed ``attempt`` (0-based).""" 48 wait = self.backoff_s * float(2**attempt) 49 if retry_after is not None: 50 with contextlib.suppress(ValueError): # an HTTP date: keep the backoff 51 wait = max(float(retry_after), 0.0) 52 return min(wait, self.max_backoff_s)
Seconds to wait after the failed attempt (0-based).
175@dataclass(frozen=True, slots=True) 176class Seen: 177 """How often FIRMS saw a fire of this size: measured, with its counts.""" 178 179 area_ha: float 180 from_ha: float 181 to_ha: float | None 182 period: str 183 perimeters: int 184 seen: int 185 no_data: int 186 country: str 187 product: str 188 189 @property 190 def share(self) -> float: 191 """Seen perimeters over all perimeters of the class.""" 192 return self.seen / self.perimeters 193 194 def describe(self) -> str: 195 """One sentence, with the numbers it rests on.""" 196 size = ( 197 f"{self.from_ha:g} to {self.to_ha:g} ha" 198 if self.to_ha is not None 199 else f"{self.from_ha:g} ha or more" 200 ) 201 return ( 202 f"In {self.country}, {self.period}, {self.product} saw {100 * self.share:.0f}% " 203 f"of the fires of {size} ({self.seen} of " 204 f"{self.perimeters} EFFIS burnt areas): no detection is not no fire." 205 )
How often FIRMS saw a fire of this size: measured, with its counts.
194 def describe(self) -> str: 195 """One sentence, with the numbers it rests on.""" 196 size = ( 197 f"{self.from_ha:g} to {self.to_ha:g} ha" 198 if self.to_ha is not None 199 else f"{self.from_ha:g} ha or more" 200 ) 201 return ( 202 f"In {self.country}, {self.period}, {self.product} saw {100 * self.share:.0f}% " 203 f"of the fires of {size} ({self.seen} of " 204 f"{self.perimeters} EFFIS burnt areas): no detection is not no fire." 205 )
One sentence, with the numbers it rests on.
77@dataclass(frozen=True, slots=True) 78class StaticMask: 79 """Static cells and the rules that found them.""" 80 81 cells: dict[Cell, CellVerdict] 82 rules: MaskRules = field(default_factory=MaskRules) 83 known: frozenset[Cell] = frozenset() 84 meta: dict[str, Any] = field(default_factory=dict) 85 86 def cell_of(self, latitude: float, longitude: float) -> Cell: 87 """The grid cell of a position.""" 88 size = self.rules.cell_deg 89 return math.floor(latitude / size), math.floor(longitude / size) 90 91 def verdict(self, h: Hotspot) -> CellVerdict | None: 92 """The static verdict for a hotspot's position, or ``None``. 93 94 Its own cell decides when the archives saw it often enough; otherwise 95 the most active static neighbour, if any. 96 """ 97 return self.verdict_at(h.latitude, h.longitude) 98 99 def verdict_at(self, latitude: float, longitude: float) -> CellVerdict | None: 100 """The static verdict for a position, by the rule of :meth:`verdict`.""" 101 y, x = self.cell_of(latitude, longitude) 102 if (y, x) in self.cells: 103 return self.cells[(y, x)] 104 if (y, x) in self.known: 105 return None 106 neighbours = [ 107 self.cells[c] 108 for c in ((y + dy, x + dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1)) 109 if c in self.cells 110 ] 111 return max(neighbours, key=lambda v: v.fire_days, default=None) 112 113 def label( 114 self, 115 hotspots: Iterable[Hotspot], 116 *, 117 overwrite: bool = False, 118 spare_frp_mw: float | None = None, 119 ) -> list[Hotspot]: 120 """The hotspots, with the ``type`` of the static cells they fall in. 121 122 Only rows without ``type`` change, unless ``overwrite``. With 123 ``spare_frp_mw``, a detection at least that strong keeps its 124 ``type``: a wildfire next to a factory should not be masked away. 125 Then :func:`~firms_client.select` drops what is static. 126 """ 127 out = [] 128 for h in hotspots: 129 if h.detection_type is not None and not overwrite: 130 out.append(h) 131 continue 132 if spare_frp_mw is not None and h.frp_mw is not None and h.frp_mw >= spare_frp_mw: 133 out.append(h) 134 continue 135 found = self.verdict(h) 136 out.append(h if found is None else replace(h, detection_type=found.detection_type)) 137 return out 138 139 def to_json(self) -> dict[str, Any]: 140 """A JSON-ready form; :meth:`from_json` reads it back.""" 141 return { 142 "format": _FORMAT, 143 "rules": {k: getattr(self.rules, k) for k in MaskRules.__dataclass_fields__}, 144 "meta": self.meta, 145 "cells": [ 146 [y, x, v.detection_type, v.reason, v.detections, v.fire_days, v.years, v.months, 147 v.static_share] 148 for (y, x), v in sorted(self.cells.items()) 149 ], 150 "known": sorted([y, x] for y, x in self.known), 151 } # fmt: skip 152 153 @classmethod 154 def from_json(cls, data: dict[str, Any]) -> StaticMask: 155 """The mask :meth:`to_json` wrote.""" 156 if data.get("format") != _FORMAT: 157 raise ValueError(f"unknown static mask format {data.get('format')!r}") 158 cells = { 159 (y, x): CellVerdict(kind, reason, n, days, years, months, share) 160 for y, x, kind, reason, n, days, years, months, share in data["cells"] 161 } 162 return cls( 163 cells=cells, 164 rules=MaskRules(**data["rules"]), 165 known=frozenset((y, x) for y, x in data["known"]), 166 meta=dict(data.get("meta", {})), 167 ) 168 169 def save(self, path: Path) -> Path: 170 """Write the mask as JSON; returns ``path``.""" 171 path.parent.mkdir(parents=True, exist_ok=True) 172 path.write_text(json.dumps(self.to_json(), separators=(",", ":")), encoding="utf-8") 173 return path 174 175 @classmethod 176 def load(cls, path: Path) -> StaticMask: 177 """Read a mask :meth:`save` wrote.""" 178 return cls.from_json(json.loads(path.read_text(encoding="utf-8")))
Static cells and the rules that found them.
86 def cell_of(self, latitude: float, longitude: float) -> Cell: 87 """The grid cell of a position.""" 88 size = self.rules.cell_deg 89 return math.floor(latitude / size), math.floor(longitude / size)
The grid cell of a position.
91 def verdict(self, h: Hotspot) -> CellVerdict | None: 92 """The static verdict for a hotspot's position, or ``None``. 93 94 Its own cell decides when the archives saw it often enough; otherwise 95 the most active static neighbour, if any. 96 """ 97 return self.verdict_at(h.latitude, h.longitude)
The static verdict for a hotspot's position, or None.
Its own cell decides when the archives saw it often enough; otherwise the most active static neighbour, if any.
99 def verdict_at(self, latitude: float, longitude: float) -> CellVerdict | None: 100 """The static verdict for a position, by the rule of :meth:`verdict`.""" 101 y, x = self.cell_of(latitude, longitude) 102 if (y, x) in self.cells: 103 return self.cells[(y, x)] 104 if (y, x) in self.known: 105 return None 106 neighbours = [ 107 self.cells[c] 108 for c in ((y + dy, x + dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1)) 109 if c in self.cells 110 ] 111 return max(neighbours, key=lambda v: v.fire_days, default=None)
The static verdict for a position, by the rule of verdict().
113 def label( 114 self, 115 hotspots: Iterable[Hotspot], 116 *, 117 overwrite: bool = False, 118 spare_frp_mw: float | None = None, 119 ) -> list[Hotspot]: 120 """The hotspots, with the ``type`` of the static cells they fall in. 121 122 Only rows without ``type`` change, unless ``overwrite``. With 123 ``spare_frp_mw``, a detection at least that strong keeps its 124 ``type``: a wildfire next to a factory should not be masked away. 125 Then :func:`~firms_client.select` drops what is static. 126 """ 127 out = [] 128 for h in hotspots: 129 if h.detection_type is not None and not overwrite: 130 out.append(h) 131 continue 132 if spare_frp_mw is not None and h.frp_mw is not None and h.frp_mw >= spare_frp_mw: 133 out.append(h) 134 continue 135 found = self.verdict(h) 136 out.append(h if found is None else replace(h, detection_type=found.detection_type)) 137 return out
The hotspots, with the type of the static cells they fall in.
Only rows without type change, unless overwrite. With
spare_frp_mw, a detection at least that strong keeps its
type: a wildfire next to a factory should not be masked away.
Then ~firms_client.select() drops what is static.
139 def to_json(self) -> dict[str, Any]: 140 """A JSON-ready form; :meth:`from_json` reads it back.""" 141 return { 142 "format": _FORMAT, 143 "rules": {k: getattr(self.rules, k) for k in MaskRules.__dataclass_fields__}, 144 "meta": self.meta, 145 "cells": [ 146 [y, x, v.detection_type, v.reason, v.detections, v.fire_days, v.years, v.months, 147 v.static_share] 148 for (y, x), v in sorted(self.cells.items()) 149 ], 150 "known": sorted([y, x] for y, x in self.known), 151 } # fmt: skip
A JSON-ready form; from_json() reads it back.
153 @classmethod 154 def from_json(cls, data: dict[str, Any]) -> StaticMask: 155 """The mask :meth:`to_json` wrote.""" 156 if data.get("format") != _FORMAT: 157 raise ValueError(f"unknown static mask format {data.get('format')!r}") 158 cells = { 159 (y, x): CellVerdict(kind, reason, n, days, years, months, share) 160 for y, x, kind, reason, n, days, years, months, share in data["cells"] 161 } 162 return cls( 163 cells=cells, 164 rules=MaskRules(**data["rules"]), 165 known=frozenset((y, x) for y, x in data["known"]), 166 meta=dict(data.get("meta", {})), 167 )
The mask to_json() wrote.
169 def save(self, path: Path) -> Path: 170 """Write the mask as JSON; returns ``path``.""" 171 path.parent.mkdir(parents=True, exist_ok=True) 172 path.write_text(json.dumps(self.to_json(), separators=(",", ":")), encoding="utf-8") 173 return path
Write the mask as JSON; returns path.
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.
201class WorldCover: 202 """ESA WorldCover 10 m, read in place from its public bucket (or a local copy). 203 204 ``source`` is the bucket URL, or a local directory holding the tiles 205 under the same names (``v200/2021/map/ESA_WorldCover_10m_2021_v200_N36E012_Map.tif``). 206 Tiles are opened once and kept open; use it as a context manager, or 207 call :meth:`close`. Reads are blocking; run them in a thread from async 208 code (``asyncio.to_thread``). 209 """ 210 211 def __init__(self, source: str = WORLDCOVER_URL, *, year: int = 2021) -> None: 212 if year not in (2020, 2021): 213 raise ValueError("WorldCover exists for 2020 (v100) and 2021 (v200)") 214 self.source = source.rstrip("/") 215 self.year = year 216 self.version = "v200" if year == 2021 else "v100" 217 self._open: dict[str, DatasetReader | None] = {} 218 self._env: Any = None 219 220 @classmethod 221 def synced(cls, directory: Path | None = None, *, year: int = 2021) -> WorldCover: 222 """The local copy :func:`save_worldcover` made in the data directory, else the bucket.""" 223 local = (directory or default_directory()) / WORLDCOVER_DIR 224 return cls(str(local) if local.is_dir() else WORLDCOVER_URL, year=year) 225 226 def tile(self, latitude: float, longitude: float) -> str: 227 """The tile file of a position: ``…_N36E012_Map.tif`` covers 36-39 N, 12-15 E.""" 228 south = math.floor(latitude / 3) * 3 229 west = math.floor(longitude / 3) * 3 230 ns = f"{'N' if south >= 0 else 'S'}{abs(south):02d}" 231 ew = f"{'E' if west >= 0 else 'W'}{abs(west):03d}" 232 name = f"ESA_WorldCover_10m_{self.year}_{self.version}_{ns}{ew}_Map.tif" 233 return f"{self.source}/{self.version}/{self.year}/map/{name}" 234 235 def shares( 236 self, latitude: float, longitude: float, radius_m: float = 190.0 237 ) -> dict[int, float]: 238 """Class shares in the square around a position; ``{}`` where there is no tile or data.""" 239 import numpy as np 240 from rasterio.errors import WindowError 241 from rasterio.windows import Window, from_bounds 242 243 dataset = self._dataset(self.tile(latitude, longitude)) 244 if dataset is None: 245 return {} 246 dlat = radius_m / _METRES_PER_DEGREE 247 dlon = dlat / max(math.cos(math.radians(latitude)), 0.01) 248 window = from_bounds( 249 longitude - dlon, latitude - dlat, longitude + dlon, latitude + dlat, dataset.transform 250 ) 251 col0, row0 = math.floor(window.col_off), math.floor(window.row_off) 252 col1 = math.ceil(window.col_off + window.width) 253 row1 = math.ceil(window.row_off + window.height) 254 try: # whole pixels, outwards, inside the tile 255 window = Window(col0, row0, col1 - col0, row1 - row0).intersection( 256 Window(0, 0, dataset.width, dataset.height) 257 ) 258 except WindowError: # outside the tile 259 return {} 260 pixels = dataset.read(1, window=window) 261 values, counts = np.unique(pixels[pixels > 0], return_counts=True) 262 total = int(counts.sum()) 263 if not total: 264 return {} 265 return {int(v): int(n) / total for v, n in zip(values, counts, strict=True)} 266 267 def _dataset(self, path: str) -> DatasetReader | None: 268 if path in self._open: 269 return self._open[path] 270 import rasterio 271 from rasterio.errors import RasterioIOError 272 273 if self._env is None: 274 self._env = rasterio.Env( 275 GDAL_DISABLE_READDIR_ON_OPEN="EMPTY_DIR", 276 CPL_VSIL_CURL_ALLOWED_EXTENSIONS=".tif", 277 GDAL_HTTP_MAX_RETRY="3", 278 VSI_CACHE="TRUE", 279 ) 280 self._env.__enter__() 281 remote = path.startswith(("http://", "https://")) 282 try: 283 dataset: DatasetReader | None = rasterio.open(f"/vsicurl/{path}" if remote else path) 284 except RasterioIOError: # no tile: open sea, or outside the map 285 dataset = None 286 self._open[path] = dataset 287 return dataset 288 289 def close(self) -> None: 290 """Close the open tiles.""" 291 for dataset in self._open.values(): 292 if dataset is not None: 293 dataset.close() 294 self._open.clear() 295 if self._env is not None: 296 from rasterio.errors import EnvError 297 298 # Opened in another thread (asyncio.to_thread): GDAL's environment is per thread. 299 with contextlib.suppress(EnvError): 300 self._env.__exit__(None, None, None) 301 self._env = None 302 303 def __enter__(self) -> WorldCover: 304 return self 305 306 def __exit__(self, *exc: object) -> None: 307 self.close()
ESA WorldCover 10 m, read in place from its public bucket (or a local copy).
source is the bucket URL, or a local directory holding the tiles
under the same names (v200/2021/map/ESA_WorldCover_10m_2021_v200_N36E012_Map.tif).
Tiles are opened once and kept open; use it as a context manager, or
call close(). Reads are blocking; run them in a thread from async
code (asyncio.to_thread).
211 def __init__(self, source: str = WORLDCOVER_URL, *, year: int = 2021) -> None: 212 if year not in (2020, 2021): 213 raise ValueError("WorldCover exists for 2020 (v100) and 2021 (v200)") 214 self.source = source.rstrip("/") 215 self.year = year 216 self.version = "v200" if year == 2021 else "v100" 217 self._open: dict[str, DatasetReader | None] = {} 218 self._env: Any = None
220 @classmethod 221 def synced(cls, directory: Path | None = None, *, year: int = 2021) -> WorldCover: 222 """The local copy :func:`save_worldcover` made in the data directory, else the bucket.""" 223 local = (directory or default_directory()) / WORLDCOVER_DIR 224 return cls(str(local) if local.is_dir() else WORLDCOVER_URL, year=year)
The local copy save_worldcover() made in the data directory, else the bucket.
226 def tile(self, latitude: float, longitude: float) -> str: 227 """The tile file of a position: ``…_N36E012_Map.tif`` covers 36-39 N, 12-15 E.""" 228 south = math.floor(latitude / 3) * 3 229 west = math.floor(longitude / 3) * 3 230 ns = f"{'N' if south >= 0 else 'S'}{abs(south):02d}" 231 ew = f"{'E' if west >= 0 else 'W'}{abs(west):03d}" 232 name = f"ESA_WorldCover_10m_{self.year}_{self.version}_{ns}{ew}_Map.tif" 233 return f"{self.source}/{self.version}/{self.year}/map/{name}"
The tile file of a position: …_N36E012_Map.tif covers 36-39 N, 12-15 E.
289 def close(self) -> None: 290 """Close the open tiles.""" 291 for dataset in self._open.values(): 292 if dataset is not None: 293 dataset.close() 294 self._open.clear() 295 if self._env is not None: 296 from rasterio.errors import EnvError 297 298 # Opened in another thread (asyncio.to_thread): GDAL's environment is per thread. 299 with contextlib.suppress(EnvError): 300 self._env.__exit__(None, None, None) 301 self._env = None
Close the open tiles.
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.
61def archive_filename(product: ArchiveProduct, year: int, country: str) -> str: 62 """The name FIRMS gives the yearly CSV: ``viirs-snpp_2025_Italy.csv``.""" 63 return f"{product.slug}_{year}_{country}.csv"
The name FIRMS gives the yearly CSV: viirs-snpp_2025_Italy.csv.
66def archive_url(product: ArchiveProduct, year: int, country: str) -> str: 67 """The yearly CSV of ``country`` (English name, as FIRMS writes it: ``Italy``).""" 68 return f"{ARCHIVE_BASE}/{product.slug}/{year}/{archive_filename(product, year, country)}"
The yearly CSV of country (English name, as FIRMS writes it: Italy).
71def archive_years(product: ArchiveProduct, *, until: int) -> list[int]: 72 """The years worth asking for, from the product's first.""" 73 return list(range(product.first_year, until + 1))
The years worth asking for, from the product's first.
76def area_url( 77 map_key: str, 78 source: str, 79 bbox: BBox, 80 *, 81 days: int = 1, 82 on_date: date | None = None, 83 base: str = AREA_API_BASE, 84) -> str: 85 """The area API URL. 86 87 Without ``on_date``, the last ``days`` days up to today; with it, the 88 ``days`` days starting on ``on_date``. ``days`` is 1 to 5. ``base`` is the 89 area API's root, for a proxy or a mirror. 90 """ 91 if not 1 <= days <= MAX_AREA_DAYS: 92 raise ValueError(f"days must be 1 to {MAX_AREA_DAYS}, got {days}") 93 area = ",".join(f"{c:g}" for c in bbox) 94 url = f"{base.rstrip('/')}/{map_key}/{source}/{area}/{days}" 95 return f"{url}/{on_date.isoformat()}" if on_date is not None else url
The area API URL.
Without on_date, the last days days up to today; with it, the
days days starting on on_date. days is 1 to 5. base is the
area API's root, for a proxy or a mirror.
98def area_windows(start: date, end: date) -> list[tuple[date, int]]: 99 """``(on_date, days)`` pairs covering ``start`` to ``end``, both included.""" 100 if end < start: 101 raise ValueError(f"end {end} is before start {start}") 102 windows = [] 103 day = start 104 while day <= end: 105 days = min(MAX_AREA_DAYS, (end - day).days + 1) 106 windows.append((day, days)) 107 day += timedelta(days=days) 108 return windows
(on_date, days) pairs covering start to end, both included.
181def build_static_mask( 182 hotspots: Iterable[Hotspot], 183 rules: MaskRules | None = None, 184 *, 185 meta: dict[str, Any] | None = None, 186) -> StaticMask: 187 """Learn the static cells from archive rows (all of them, not :func:`select`-ed). 188 189 Rows without ``type`` count for persistence but not for the labelled rule. 190 """ 191 rules = rules or MaskRules() 192 size = rules.cell_deg 193 days: dict[Cell, set[date]] = defaultdict(set) 194 kinds: dict[Cell, Counter[int | None]] = defaultdict(Counter) 195 for h in hotspots: 196 cell = (math.floor(h.latitude / size), math.floor(h.longitude / size)) 197 days[cell].add(h.acq_date) 198 kinds[cell][h.detection_type] += 1 199 200 cells: dict[Cell, CellVerdict] = {} 201 known: set[Cell] = set() 202 for cell, seen in days.items(): 203 counts = kinds[cell] 204 n = sum(counts.values()) 205 if n < rules.min_detections: 206 continue 207 known.add(cell) 208 typed = n - counts[None] 209 static = Counter( 210 {k: counts[k] for k in (ACTIVE_VOLCANO, STATIC_LAND_SOURCE, OFFSHORE) if counts[k]} 211 ) 212 share = sum(static.values()) / typed if typed else 0.0 213 years = len({d.year for d in seen}) 214 months = len({d.month for d in seen}) 215 common = {"detections": n, "fire_days": len(seen), "years": years, "months": months} 216 if typed and share >= rules.min_static_share: 217 kind = static.most_common(1)[0][0] 218 assert kind is not None 219 cells[cell] = CellVerdict(kind, "labelled", static_share=round(share, 3), **common) 220 elif ( 221 len(seen) >= rules.persistent_fire_days 222 and years >= rules.persistent_years 223 and months >= rules.persistent_months 224 ): 225 cells[cell] = CellVerdict( 226 STATIC_LAND_SOURCE, "persistent", static_share=round(share, 3), **common 227 ) 228 return StaticMask(cells=cells, rules=rules, known=frozenset(known), meta=dict(meta or {}))
Learn the static cells from archive rows (all of them, not select()-ed).
Rows without type count for persistence but not for the labelled rule.
139def bulletin_facts( 140 event: FireEvent, 141 *, 142 places: Iterable[Place] = (), 143 mask: StaticMask | None = None, 144 anomaly: Anomaly | None = None, 145 burning: BurningVerdict | None = None, 146 source: str | None = None, 147 region: str | None = None, 148 nearest: int = 3, 149) -> dict[str, Any]: 150 """Everything a bulletin may say about ``event``, as JSON-ready facts.""" 151 first, last = event.hotspots[0], event.hotspots[-1] 152 facts: dict[str, Any] = { 153 "event": { 154 **event.as_dict(), 155 "first_seen_utc": _when(first.acq_date.isoformat(), first.acq_time), 156 "last_seen_utc": _when(last.acq_date.isoformat(), last.acq_time), 157 "satellites": sorted({h.satellite for h in event.hotspots if h.satellite}), 158 "day_detections": sum(1 for h in event.hotspots if h.daynight == "D"), 159 "night_detections": sum(1 for h in event.hotspots if h.daynight == "N"), 160 }, 161 "region": region, 162 "source": source, 163 "nearest_places": nearest_places(event.latitude, event.longitude, places, k=nearest), 164 "static_source": None, 165 "season": anomaly.as_dict() if anomaly is not None else None, 166 "land_cover": burning.as_dict() if burning is not None else None, 167 "caveats": [ 168 "Satellite detections of heat, not ground observations; confirm on the ground.", 169 "Detections are hot pixels of about 375 m (VIIRS) or 1 km (MODIS); the extent " 170 "is approximate.", 171 "FIRMS is presence-only: clouds and smoke can hide parts of a fire.", 172 ], 173 "attribution": ATTRIBUTION, 174 } 175 if burning is not None: 176 facts["caveats"].append( 177 "What burns is inferred from a land-cover map (ESA WorldCover 2021) under the " 178 "detections, not observed: fields and forests may have changed since." 179 ) 180 if mask is not None: 181 verdicts = [mask.verdict(h) for h in event.hotspots] 182 found = [v for v in verdicts if v is not None] 183 if found: 184 top = max(found, key=lambda v: v.fire_days) 185 facts["static_source"] = { 186 "type": TYPE_NAMES.get(top.detection_type, "static_land_source"), 187 "reason": top.reason, 188 "share_of_event": round(len(found) / len(verdicts), 2), 189 "archive_fire_days": top.fire_days, 190 } 191 facts["caveats"].append( 192 "Part of this event is at a known static heat source (industry, volcano or " 193 "offshore platform) learned from the archives." 194 ) 195 return facts
Everything a bulletin may say about event, as JSON-ready facts.
290def cell_stats[C: Hashable]( 291 hotspots: Iterable[Hotspot], 292 grid: Grid[C], 293 *, 294 cells: Iterable[C] = (), 295 mask: StaticMask | None = None, 296 land: LandCover | None = None, 297 land_radius_m: float = LAND_RADIUS_M, 298 include_untyped: bool = False, 299) -> dict[C, CellStats[C]]: 300 """Fire-days, land under the fires, distance from static sources, per cell. 301 302 The result has a row for every cell with a vegetation-fire detection and 303 for every cell in ``cells`` (pass the whole grid to get its zeros). The 304 hotspots are counted as given: filter confidence first, with 305 :func:`~firms_client.select` (``vegetation_only=False`` keeps the 306 filtering of ``type`` here, where it is counted). See the module. 307 """ 308 days: dict[C, dict[date, list[Hotspot]]] = defaultdict(lambda: defaultdict(list)) 309 for h in hotspots: 310 kind = h.detection_type 311 if kind != VEGETATION_FIRE and not (kind is None and include_untyped): 312 continue 313 cell = grid.cell_of(h.latitude, h.longitude) 314 if cell is not None: 315 days[cell][h.acq_date].append(h) 316 317 index = _StaticIndex(mask) if mask is not None else None 318 shares_at: dict[tuple[float, float], dict[int, float]] = {} 319 320 def shares(h: Hotspot) -> dict[int, float]: 321 assert land is not None 322 key = (h.latitude, h.longitude) 323 if key not in shares_at: 324 shares_at[key] = land.shares(h.latitude, h.longitude, land_radius_m) 325 return shares_at[key] 326 327 out: dict[C, CellStats[C]] = {} 328 for cell in dict.fromkeys([*days, *cells]): 329 lat, lon = grid.centre(cell) 330 area = grid.area_km2(cell) 331 static_km = index.nearest_km(lat, lon) if index is not None else None 332 verdict = mask.verdict_at(lat, lon) if mask is not None else None 333 if verdict is not None: 334 out[cell] = CellStats( 335 cell, area, False, None, None, None, None, None, 0, static_km, 0.0, 336 f"a static source of the mask ({verdict.fire_days} fire-days over " 337 f"{verdict.years} years): its detections are not vegetation fires", 338 ) # fmt: skip 339 continue 340 by_day = days.get(cell, {}) 341 cropland = natural = None 342 land_days = 0 343 if land is not None and by_day: 344 crop_sum = natural_sum = 0.0 345 for rows in by_day.values(): 346 found = [s for s in (shares(h) for h in rows) if s] 347 if not found: 348 continue 349 land_days += 1 350 crop_sum += sum(s.get(CROPLAND, 0.0) for s in found) / len(found) 351 natural_sum += sum( 352 sum(v for c, v in s.items() if c in NATURAL) for s in found 353 ) / len(found) 354 if land_days: 355 cropland, natural = crop_sum / land_days, natural_sum / land_days 356 score = None 357 if by_day and (mask is not None or land is not None): 358 score = trust(lat, lon, mask=mask, land=land).score 359 out[cell] = CellStats( 360 cell=cell, 361 area_km2=area, 362 measured=True, 363 detections=sum(len(rows) for rows in by_day.values()), 364 fire_days=len(by_day), 365 fire_days_per_km2=len(by_day) / area, 366 cropland=cropland, 367 natural=natural, 368 land_days=land_days, 369 static_km=static_km, 370 score=score, 371 ) 372 return out
Fire-days, land under the fires, distance from static sources, per cell.
The result has a row for every cell with a vegetation-fire detection and
for every cell in cells (pass the whole grid to get its zeros). The
hotspots are counted as given: filter confidence first, with
~firms_client.select() (vegetation_only=False keeps the
filtering of type here, where it is counted). See the module.
216def check_columns(header: str) -> dict[str, list[str]]: 217 """What a CSV header lacks of the required columns, and what it has that is not read.""" 218 names = {n.strip().lower() for n in next(csv.reader([header]))} 219 return { 220 "missing": sorted(REQUIRED_COLUMNS - names), 221 "unknown": sorted(names - READ_COLUMNS), 222 }
What a CSV header lacks of the required columns, and what it has that is not read.
230def check_grounding(draft: dict[str, Any], facts: dict[str, Any]) -> list[str]: 231 """What in ``draft`` is not in ``facts``: numbers, places, missing fields.""" 232 problems = [f"missing field {k!r}" for k in BULLETIN_SCHEMA["required"] if k not in draft] 233 if problems: 234 return problems 235 known = _numbers_in(facts) 236 text = " ".join([draft["headline"], draft["body"], *draft["key_facts"]]) 237 for token in _NUMBER.findall(text): 238 value = _to_number(token) 239 if value is not None and not _matches(value, known): 240 problems.append(f"number {token!r} is not in the facts") 241 names = {p["name"] for p in facts.get("nearest_places", [])} 242 region = facts.get("region") 243 if region: 244 names.add(region) 245 for name in draft["places_mentioned"]: 246 if name not in names: 247 problems.append(f"place {name!r} is not in the facts") 248 return problems
What in draft is not in facts: numbers, places, missing fields.
103def check_text(text: str, facts: Any, *, lang: Lang = "en", question: str = "") -> list[str]: 104 """The numbers of ``text`` that no figure of ``facts`` gives (empty: all found). 105 106 Numbers written in ``question`` are allowed: an answer may repeat them. 107 """ 108 known = list(figures(facts)) 109 asked = {n.value for n in numbers(question, lang)} 110 return [ 111 n.text 112 for n in numbers(text, lang) 113 if n.value not in asked and not any(same(n, f) for f in known) 114 ]
The numbers of text that no figure of facts gives (empty: all found).
Numbers written in question are allowed: an answer may repeat them.
167def classify_burning( 168 event: FireEvent, 169 land: LandCover, 170 rules: BurningRules | None = None, 171 *, 172 sample: int = 10, 173 radius_m: float = 190.0, 174) -> BurningVerdict: 175 """Crop burning, wildfire or something else, by the land cover under ``event``.""" 176 rules = rules or BurningRules() 177 shares, sampled = event_land_cover(event, land, sample=sample, radius_m=radius_m) 178 named = { 179 WORLDCOVER_CLASSES.get(cls, f"class_{cls}"): round(v, 3) 180 for cls, v in sorted(shares.items(), key=lambda kv: -kv[1]) 181 if v >= 0.005 182 } 183 if not sampled: 184 return BurningVerdict("unknown", "no land cover under the hotspots", named, 0) 185 found, reason = land_kind(shares, rules) 186 kind: Kind 187 if found == "natural": 188 kind = "wildfire" 189 elif found == "cropland": 190 small = event.days <= rules.crop_max_days and event.size <= rules.crop_max_hotspots 191 kind = "crop_burning" if small else "cropland_fire" 192 days = f"{event.days} day{'s' if event.days > 1 else ''}" 193 reason = f"{reason}, {event.size} hotspots over {days}" 194 elif found == "artificial": 195 kind = "other" 196 else: 197 kind = "mixed" 198 return BurningVerdict(kind, reason, named, sampled)
Crop burning, wildfire or something else, by the land cover under event.
101def cluster( 102 hotspots: Iterable[Hotspot], *, radius_m: float = 750.0, gap_days: int = 1 103) -> list[FireEvent]: 104 """Group hotspots into events, the largest by total FRP first. 105 106 Two hotspots are linked when they are at most ``radius_m`` apart and at 107 most ``gap_days`` calendar days apart (``0``: the same day only). Pass 108 :func:`~firms_client.select` output, or a steelworks becomes the 109 longest fire of the year. 110 """ 111 if radius_m <= 0: 112 raise ValueError("radius_m must be positive") 113 if gap_days < 0: 114 raise ValueError("gap_days must be 0 or more") 115 rows = list(hotspots) 116 if not rows: 117 return [] 118 119 # A grid whose cells are at least radius_m wide everywhere in the data: 120 # a longitude degree is shortest at the highest latitude. 121 lat_cell = radius_m / _METRES_PER_DEGREE 122 top = min(max(abs(h.latitude) for h in rows), 89.0) 123 lon_cell = radius_m / (_METRES_PER_DEGREE * math.cos(math.radians(top))) 124 grid: dict[tuple[int, int, date], list[int]] = defaultdict(list) 125 for i, h in enumerate(rows): 126 grid[_cell(h, lat_cell, lon_cell)].append(i) 127 128 parent = list(range(len(rows))) 129 130 def root(i: int) -> int: 131 while parent[i] != i: 132 parent[i] = parent[parent[i]] 133 i = parent[i] 134 return i 135 136 for i, h in enumerate(rows): 137 y, x, day = _cell(h, lat_cell, lon_cell) 138 for dy in (-1, 0, 1): 139 for dx in (-1, 0, 1): 140 for dd in range(-gap_days, gap_days + 1): 141 for j in grid.get((y + dy, x + dx, day + timedelta(days=dd)), ()): 142 if j > i and distance_m(h, rows[j]) <= radius_m: 143 parent[root(j)] = root(i) 144 145 groups: dict[int, list[Hotspot]] = defaultdict(list) 146 for i, h in enumerate(rows): 147 groups[root(i)].append(h) 148 events = [FireEvent.of(members) for members in groups.values()] 149 events.sort(key=lambda e: (-e.total_frp_mw, -e.size, e.start)) 150 return events
Group hotspots into events, the largest by total FRP first.
Two hotspots are linked when they are at most radius_m apart and at
most gap_days calendar days apart (0: the same day only). Pass
~firms_client.select() output, or a steelworks becomes the
longest fire of the year.
136def confidence_level( 137 raw: str | None, *, nominal_from_pct: int = 30, high_from_pct: int = 80 138) -> ConfidenceLevel | None: 139 """A VIIRS level as is; a MODIS percentage mapped by the two thresholds. 140 141 The defaults follow the FIRMS MODIS guidance (below 30 low, 30-79 142 nominal, 80 and above high). ``None`` when the value is missing or 143 unreadable. 144 """ 145 if raw is None or not raw.strip(): 146 return None 147 token = raw.strip().lower() 148 if token in _LEVELS: 149 return _LEVELS[token] 150 try: 151 pct = float(token) 152 except ValueError: 153 return None 154 if pct >= high_from_pct: 155 return "high" 156 return "nominal" if pct >= nominal_from_pct else "low"
A VIIRS level as is; a MODIS percentage mapped by the two thresholds.
The defaults follow the FIRMS MODIS guidance (below 30 low, 30-79
nominal, 80 and above high). None when the value is missing or
unreadable.
198async def data_availability( 199 client: httpx.AsyncClient, 200 map_key: str, 201 source: str = "ALL", 202 *, 203 retry: RetryPolicy | None = None, 204) -> list[dict[str, str]]: 205 """The first and last date of each source, one row per source, as FIRMS writes them.""" 206 url = f"{AREA_API_BASE.rsplit('/area', 1)[0]}/data_availability/csv/{map_key}/{source}" 207 response = await _get(client, url, retry) 208 if response.status_code in (400, 401, 403): 209 raise FirmsError(response.text.strip() or f"HTTP {response.status_code}") 210 response.raise_for_status() 211 if response.text.lstrip().startswith("<"): 212 raise FirmsError("FIRMS answered with a page, not a CSV") 213 return list(csv.DictReader(io.StringIO(response.text)))
The first and last date of each source, one row per source, as FIRMS writes them.
51def default_directory() -> Path: 52 """The data directory: every download goes there, and is read from there. 53 54 In order (an explicit ``directory=`` argument always wins over all of 55 them), each read from the environment, else from the ``.env`` file of 56 the current directory: 57 58 * ``FIRMS_DATA_DIR``: this library's own directory (kept for 59 compatibility); 60 * ``DATA_ROOT``: the data root shared by the agent-engineering-studio 61 libraries; this one uses ``$DATA_ROOT/firms-client``; 62 * else ``firms-client`` in the user cache (``$XDG_CACHE_HOME``, or 63 ``~/.cache``). 64 65 Archives, the static mask, WorldCover and ``sync.json`` all live in it. 66 """ 67 configured = _setting(ENV_DATA_DIR) 68 if configured: 69 return Path(configured).expanduser() 70 root = _setting(ENV_DATA_ROOT) 71 if root: 72 return Path(root).expanduser() / DATA_ROOT_FOLDER 73 cache = os.environ.get("XDG_CACHE_HOME", "").strip() or "~/.cache" 74 return Path(cache).expanduser() / DATA_ROOT_FOLDER
The data directory: every download goes there, and is read from there.
In order (an explicit directory= argument always wins over all of
them), each read from the environment, else from the .env file of
the current directory:
FIRMS_DATA_DIR: this library's own directory (kept for compatibility);DATA_ROOT: the data root shared by the agent-engineering-studio libraries; this one uses$DATA_ROOT/firms-client;- else
firms-clientin the user cache ($XDG_CACHE_HOME, or~/.cache).
Archives, the static mask, WorldCover and sync.json all live in it.
31def distance_m(a: Hotspot, b: Hotspot) -> float: 32 """Great-circle distance between two hotspots, in metres.""" 33 lat1, lat2 = math.radians(a.latitude), math.radians(b.latitude) 34 dlat = lat2 - lat1 35 dlon = math.radians(b.longitude - a.longitude) 36 h = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2 37 return 2 * _EARTH_RADIUS_M * math.asin(min(1.0, math.sqrt(h)))
Great-circle distance between two hotspots, in metres.
109async def download_archive( 110 client: httpx.AsyncClient, 111 product: ArchiveProduct, 112 year: int, 113 country: str, 114 directory: Path | None = None, 115 *, 116 retry: RetryPolicy | None = None, 117) -> Path | None: 118 """The yearly CSV in ``directory``, downloaded if missing; ``None`` when not published. 119 120 ``directory`` defaults to :func:`default_directory`. A file already there 121 is returned without asking FIRMS; delete it to download it again. A year 122 not published is not remembered, since it may be published later. 123 """ 124 directory = directory or default_directory() 125 path = directory / archive_filename(product, year, country) 126 if path.exists(): 127 return path 128 partial = path.with_name(f"{path.name}.part") 129 url = archive_url(product, year, country) 130 131 async def attempt(final: bool) -> bool: 132 async with client.stream("GET", url) as response: 133 if response.status_code == 404: 134 return False 135 if retryable(retry, response, final): 136 raise RetryableStatusError(response) 137 response.raise_for_status() 138 directory.mkdir(parents=True, exist_ok=True) 139 with partial.open("wb") as out: 140 async for chunk in response.aiter_bytes(_CHUNK): 141 out.write(chunk) 142 return True 143 144 try: 145 if not await with_retries(retry, attempt): 146 return None 147 with partial.open(encoding="utf-8", errors="replace") as part: 148 head = part.read(400) 149 if not is_hotspot_csv(head): 150 raise FirmsError(f"FIRMS archive did not return a CSV: {head[:200]!r}") 151 partial.rename(path) 152 finally: 153 partial.unlink(missing_ok=True) 154 return path
The yearly CSV in directory, downloaded if missing; None when not published.
directory defaults to default_directory(). A file already there
is returned without asking FIRMS; delete it to download it again. A year
not published is not remembered, since it may be published later.
96async def download_worldcover_tile( 97 client: httpx.AsyncClient, 98 url: str, 99 directory: Path | None = None, 100 *, 101 retry: RetryPolicy | None = None, 102) -> Path | None: 103 """One whole WorldCover tile into the data directory; ``None`` if it does not exist (sea). 104 105 A tile already there is returned without asking the bucket. 106 """ 107 path = worldcover_path(url, directory) 108 if path.exists(): 109 return path 110 partial = path.with_name(f"{path.name}.part") 111 112 async def attempt(final: bool) -> bool: 113 async with client.stream("GET", url) as response: 114 if response.status_code == 404: 115 return False 116 if retryable(retry, response, final): 117 raise RetryableStatusError(response) 118 response.raise_for_status() 119 path.parent.mkdir(parents=True, exist_ok=True) 120 with partial.open("wb") as out: 121 async for chunk in response.aiter_bytes(_CHUNK): 122 out.write(chunk) 123 return True 124 125 try: 126 if not await with_retries(retry, attempt): 127 return None 128 partial.rename(path) 129 finally: 130 partial.unlink(missing_ok=True) 131 return path
One whole WorldCover tile into the data directory; None if it does not exist (sea).
A tile already there is returned without asking the bucket.
251async def draft_bulletin( 252 facts: dict[str, Any], 253 writer: Writer | Callable[[str, str, dict[str, Any]], Awaitable[dict[str, Any]]], 254 *, 255 language: str = "en", 256 retries: int = 1, 257) -> Bulletin: 258 """Ask ``writer`` for a bulletin, check it, and ask again once if it strays.""" 259 payload = {"language": language, **facts} 260 system = SYSTEM_PROMPT 261 attempts = 0 262 while True: 263 attempts += 1 264 draft = await writer(system, json.dumps(payload, ensure_ascii=False), BULLETIN_SCHEMA) 265 problems = check_grounding(draft, facts) 266 if not problems or attempts > retries: 267 break 268 system = ( 269 SYSTEM_PROMPT 270 + "\nYour previous draft was rejected. Fix exactly these problems and change " 271 + "nothing else:\n" 272 + "\n".join(f"- {p}" for p in problems) 273 ) 274 return Bulletin( 275 headline=str(draft.get("headline", "")), 276 body=str(draft.get("body", "")), 277 key_facts=list(draft.get("key_facts", [])), 278 places_mentioned=list(draft.get("places_mentioned", [])), 279 caveats=list(draft.get("caveats", [])), 280 problems=problems, 281 attempts=attempts, 282 )
Ask writer for a bulletin, check it, and ask again once if it strays.
86def env_file_value(name: str, path: Path | None = None) -> str | None: 87 """The value of ``name`` in a ``.env`` file (default: the current directory's). 88 89 Plain ``NAME=value`` lines; ``export``, quotes and ``#`` comments are 90 understood. The environment is not changed. 91 """ 92 path = path or Path.cwd() / ".env" 93 if not path.is_file(): 94 return None 95 for line in path.read_text(encoding="utf-8").splitlines(): 96 line = line.strip().removeprefix("export ").strip() 97 if not line or line.startswith("#") or "=" not in line: 98 continue 99 key, _, value = line.partition("=") 100 if key.strip() != name: 101 continue 102 value = value.strip() 103 if value[:1] in "\"'" and value[:1] == value[-1:] and len(value) > 1: 104 return value[1:-1] 105 return value.split(" #", 1)[0].strip() or None 106 return None
The value of name in a .env file (default: the current directory's).
Plain NAME=value lines; export, quotes and # comments are
understood. The environment is not changed.
116def event_land_cover( 117 event: FireEvent, land: LandCover, *, sample: int = 10, radius_m: float = 190.0 118) -> tuple[dict[int, float], int]: 119 """Mean class shares around up to ``sample`` of the event's hotspots, spread evenly. 120 121 ``radius_m`` 190 is half a VIIRS pixel; use about 500 for MODIS. Returns 122 the shares and how many hotspots were sampled (positions with no data, 123 over the sea, are skipped). 124 """ 125 rows = event.hotspots 126 step = max(1, math.ceil(len(rows) / sample)) 127 total: dict[int, float] = {} 128 sampled = 0 129 for h in rows[::step][:sample]: 130 found = land.shares(h.latitude, h.longitude, radius_m) 131 if not found: 132 continue 133 sampled += 1 134 for cls, share in found.items(): 135 total[cls] = total.get(cls, 0.0) + share 136 if not sampled: 137 return {}, 0 138 return {cls: v / sampled for cls, v in total.items()}, sampled
Mean class shares around up to sample of the event's hotspots, spread evenly.
radius_m 190 is half a VIIRS pixel; use about 500 for MODIS. Returns
the shares and how many hotspots were sampled (positions with no data,
over the sea, are skipped).
171async def fetch_archive( 172 client: httpx.AsyncClient, 173 product: ArchiveProduct, 174 year: int, 175 country: str, 176 directory: Path | None = None, 177 *, 178 retry: RetryPolicy | None = None, 179) -> list[Hotspot] | None: 180 """One year of a country's archive, parsed; ``None`` when not published.""" 181 text = await fetch_archive_csv(client, product, year, country, directory, retry=retry) 182 return parse_csv(text) if text is not None else None
One year of a country's archive, parsed; None when not published.
157async def fetch_archive_csv( 158 client: httpx.AsyncClient, 159 product: ArchiveProduct, 160 year: int, 161 country: str, 162 directory: Path | None = None, 163 *, 164 retry: RetryPolicy | None = None, 165) -> str | None: 166 """The raw yearly CSV, via :func:`download_archive`; ``None`` when not published.""" 167 path = await download_archive(client, product, year, country, directory, retry=retry) 168 return path.read_text(encoding="utf-8") if path is not None else None
The raw yearly CSV, via download_archive(); None when not published.
185async def fetch_area( 186 client: httpx.AsyncClient, 187 map_key: str, 188 source: str, 189 bbox: BBox, 190 *, 191 days: int = 1, 192 on_date: date | None = None, 193 retry: RetryPolicy | None = None, 194) -> list[Hotspot]: 195 """Detections of ``source`` over ``bbox``. A bad key or source raises :class:`FirmsError`. 196 197 Without ``on_date``, the last ``days`` days up to today; with it, the 198 ``days`` days starting on ``on_date`` (1 to 5). 199 """ 200 url = area_url(map_key, source, bbox, days=days, on_date=on_date) 201 202 async def attempt(final: bool) -> httpx.Response: 203 response = await client.get(url) 204 if retryable(retry, response, final): 205 raise RetryableStatusError(response) 206 return response 207 208 response = await with_retries(retry, attempt) 209 if response.status_code != 200 or not is_hotspot_csv(response.text): 210 if response.status_code == 200 and not response.text.strip(): 211 return [] 212 raise FirmsError( 213 f"FIRMS area API (HTTP {response.status_code}): {response.text[:200].strip()}" 214 ) 215 return parse_csv(response.text)
Detections of source over bbox. A bad key or source raises FirmsError.
Without on_date, the last days days up to today; with it, the
days days starting on on_date (1 to 5).
218async def fetch_area_range( 219 client: httpx.AsyncClient, 220 map_key: str, 221 source: str, 222 bbox: BBox, 223 start: date, 224 end: date, 225 *, 226 retry: RetryPolicy | None = None, 227) -> list[Hotspot]: 228 """Detections from ``start`` to ``end`` (both included), in 5-day requests. 229 230 The windows are fetched one after the other, to stay gentle with the 231 MAP_KEY's transaction limit; pass a ``retry`` policy for long ranges. 232 Use an ``*_SP`` source for anything older than a few months. 233 """ 234 out: list[Hotspot] = [] 235 for on_date, days in area_windows(start, end): 236 out += await fetch_area( 237 client, map_key, source, bbox, days=days, on_date=on_date, retry=retry 238 ) 239 return out
Detections from start to end (both included), in 5-day requests.
The windows are fetched one after the other, to stay gentle with the
MAP_KEY's transaction limit; pass a retry policy for long ranges.
Use an *_SP source for anything older than a few months.
231async def fetch_static_mask( 232 client: httpx.AsyncClient, 233 country: str, 234 *, 235 product: ArchiveProduct = VIIRS_SNPP, 236 first_year: int | None = None, 237 last_year: int | None = None, 238 rules: MaskRules | None = None, 239 directory: Path | None = None, 240 retry: RetryPolicy | None = None, 241) -> StaticMask: 242 """The mask of ``country`` from its archives, built once and saved next to them. 243 244 Years default to the whole product up to last year. The mask is saved as 245 ``static-mask_{product}_{country}_{first}-{last}.json`` in the data 246 directory and read from there afterwards; delete it to rebuild. 247 """ 248 last = last_year if last_year is not None else date.today().year - 1 249 first = first_year if first_year is not None else product.first_year 250 rules = rules or MaskRules() 251 folder = directory or default_directory() 252 path = folder / f"static-mask_{product.slug}_{country}_{first}-{last}.json" 253 if path.exists(): 254 mask = StaticMask.load(path) 255 if mask.rules == rules: 256 return mask 257 rows: list[Hotspot] = [] 258 years = [] 259 for year in archive_years(product, until=last): 260 if year < first: 261 continue 262 found = await fetch_archive(client, product, year, country, folder, retry=retry) 263 if found is not None: 264 rows += found 265 years.append(year) 266 if not years: 267 raise ValueError(f"no {product.slug} archive for {country} from {first} to {last}") 268 meta = {"country": country, "product": product.slug, "years": years, "detections": len(rows)} 269 mask = build_static_mask(rows, rules, meta=meta) 270 mask.save(path) 271 return mask
The mask of country from its archives, built once and saved next to them.
Years default to the whole product up to last year. The mask is saved as
static-mask_{product}_{country}_{first}-{last}.json in the data
directory and read from there afterwards; delete it to rebuild.
134async def init( 135 directory: Path | None = None, 136 *, 137 country: str, 138 years: Iterable[int], 139 bbox: BBox | None = None, 140 products: tuple[ArchiveProduct, ...] = (VIIRS_SNPP,), 141 client: httpx.AsyncClient | None = None, 142 retry: RetryPolicy | None = None, 143) -> InitReport: 144 """Archives of ``country`` for ``years`` and the WorldCover tiles over ``bbox``; see the module. 145 146 ``directory`` defaults to :func:`~firms_client.default_directory`. 147 ``missing`` lists the years not published (and the sea tiles), which 148 are not errors; ``failed`` maps a file to its error. 149 """ 150 folder = directory or default_directory() 151 report = InitReport(directory=str(folder)) 152 own = client is None 153 http = client or httpx.AsyncClient(timeout=600, follow_redirects=True) 154 try: 155 for product in products: 156 for year in years: 157 if year < product.first_year: 158 continue 159 name = archive_filename(product, year, country) 160 if (folder / name).exists(): 161 report.skipped.append(name) 162 continue 163 try: 164 found = await download_archive( 165 http, product, year, country, folder, retry=retry 166 ) 167 except (httpx.HTTPError, FirmsError, OSError) as error: 168 report.failed[name] = str(error) or type(error).__name__ 169 continue 170 (report.downloaded if found is not None else report.missing).append(name) 171 for url in worldcover_tiles(bbox) if bbox is not None else []: 172 name = url.rsplit("/", 1)[-1] 173 if worldcover_path(url, folder).exists(): 174 report.skipped.append(name) 175 continue 176 try: 177 found = await download_worldcover_tile(http, url, folder, retry=retry) 178 except (httpx.HTTPError, OSError) as error: 179 report.failed[name] = str(error) or type(error).__name__ 180 continue 181 (report.downloaded if found is not None else report.missing).append(name) 182 finally: 183 if own: 184 await http.aclose() 185 return report
Archives of country for years and the WorldCover tiles over bbox; see the module.
directory defaults to ~firms_client.default_directory().
missing lists the years not published (and the sea tiles), which
are not errors; failed maps a file to its error.
130def is_hotspot_csv(text: str) -> bool: 131 """True only for a real hotspot CSV: an error body may come with any status.""" 132 head = text.lstrip()[:400].lower() 133 return "latitude" in head and "longitude" in head and "acq_date" in head
True only for a real hotspot CSV: an error body may come with any status.
178def is_map_key(key: str) -> bool: 179 """Whether ``key`` has the shape of a MAP_KEY: 32 lowercase letters and digits.""" 180 return bool(MAP_KEY_PATTERN.match(key))
Whether key has the shape of a MAP_KEY: 32 lowercase letters and digits.
88def laea(latitude: float, longitude: float) -> tuple[float, float]: 89 """``(x, y)`` in metres in ETRS89-LAEA (EPSG:3035): easting and northing.""" 90 beta = math.asin(_q(math.radians(latitude)) / _QP) 91 dlon = math.radians(longitude) - _LON0 92 b = _RQ * math.sqrt( 93 2 94 / ( 95 1 96 + math.sin(_BETA0) * math.sin(beta) 97 + math.cos(_BETA0) * math.cos(beta) * math.cos(dlon) 98 ) 99 ) 100 x = _FALSE_EASTING + b * _D * math.cos(beta) * math.sin(dlon) 101 y = _FALSE_NORTHING + (b / _D) * ( 102 math.cos(_BETA0) * math.sin(beta) - math.sin(_BETA0) * math.cos(beta) * math.cos(dlon) 103 ) 104 return x, y
(x, y) in metres in ETRS89-LAEA (EPSG:3035): easting and northing.
107def laea_inverse(x: float, y: float) -> tuple[float, float]: 108 """``(latitude, longitude)`` of an ETRS89-LAEA (EPSG:3035) position.""" 109 dx, dy = x - _FALSE_EASTING, y - _FALSE_NORTHING 110 rho = math.hypot(dx / _D, _D * dy) 111 if rho == 0: 112 return math.degrees(_LAT0), math.degrees(_LON0) 113 c = 2 * math.asin(rho / (2 * _RQ)) 114 beta = math.asin( 115 math.cos(c) * math.sin(_BETA0) + _D * dy * math.sin(c) * math.cos(_BETA0) / rho 116 ) 117 e4, e6 = _E2 * _E2, _E2 * _E2 * _E2 118 lat = ( 119 beta 120 + (_E2 / 3 + 31 * e4 / 180 + 517 * e6 / 5040) * math.sin(2 * beta) 121 + (23 * e4 / 360 + 251 * e6 / 3780) * math.sin(4 * beta) 122 + (761 * e6 / 45360) * math.sin(6 * beta) 123 ) 124 lon = _LON0 + math.atan2( 125 dx * math.sin(c), 126 _D * rho * math.cos(_BETA0) * math.cos(c) - _D * _D * dy * math.sin(_BETA0) * math.sin(c), 127 ) 128 return math.degrees(lat), math.degrees(lon)
(latitude, longitude) of an ETRS89-LAEA (EPSG:3035) position.
148def land_kind(shares: dict[int, float], rules: BurningRules | None = None) -> tuple[LandKind, str]: 149 """What land class shares describe, by the rules of :func:`classify_burning`. 150 151 ``natural`` (wildfire land), ``cropland``, ``artificial`` (built-up or 152 bare) or ``mixed``, with the reason in words. 153 """ 154 rules = rules or BurningRules() 155 natural = sum(v for cls, v in shares.items() if cls in NATURAL) 156 crop = shares.get(CROPLAND, 0.0) 157 artificial = sum(v for cls, v in shares.items() if cls in ARTIFICIAL) 158 if natural >= rules.natural_share: 159 return "natural", f"natural vegetation {_pct(natural)}" 160 if crop >= rules.crop_share and natural <= rules.crop_natural_max: 161 return "cropland", f"cropland {_pct(crop)}, natural vegetation {_pct(natural)}" 162 if artificial >= rules.artificial_share: 163 return "artificial", f"built-up or bare ground {_pct(artificial)}" 164 return "mixed", f"cropland {_pct(crop)}, natural vegetation {_pct(natural)}"
What land class shares describe, by the rules of classify_burning().
natural (wildfire land), cropland, artificial (built-up or
bare) or mixed, with the reason in words.
158async def latest_archive( 159 client: httpx.AsyncClient, 160 product: ArchiveProduct, 161 country: str, 162 *, 163 until: int | None = None, 164 retry: RetryPolicy | None = None, 165) -> int | None: 166 """The last year (up to ``until``, default this year) with a published archive.""" 167 year = until if until is not None else date.today().year 168 while year >= product.first_year: 169 response = await _get(client, archive_url(product, year, country), retry) 170 if response.status_code == 200: 171 return year 172 if response.status_code != 404: 173 response.raise_for_status() 174 year -= 1 175 return None
The last year (up to until, default this year) with a published archive.
81def map_key_from_env() -> str | None: 82 """``FIRMS_MAP_KEY`` from the environment, else from the current directory's ``.env``.""" 83 return _setting(ENV_MAP_KEY)
FIRMS_MAP_KEY from the environment, else from the current directory's .env.
183async def map_key_status( 184 client: httpx.AsyncClient, map_key: str, *, retry: RetryPolicy | None = None 185) -> dict[str, Any]: 186 """The MAP_KEY's transactions, as FIRMS reports them (a JSON object).""" 187 response = await _get(client, MAP_KEY_STATUS_URL, retry, params={"MAP_KEY": map_key}) 188 if response.status_code in (400, 401, 403): 189 raise FirmsError(response.text.strip() or f"HTTP {response.status_code}") 190 response.raise_for_status() 191 try: 192 status: dict[str, Any] = response.json() 193 except json.JSONDecodeError: 194 raise FirmsError("the MAP_KEY status is not JSON") from None 195 return status
The MAP_KEY's transactions, as FIRMS reports them (a JSON object).
137async def missing_days( 138 client: httpx.AsyncClient, *, retry: RetryPolicy | None = None 139) -> MissingDays: 140 """The days each satellite has no data in FIRMS; see the module.""" 141 response = await _get( 142 client, 143 MISSING_DATA_URL, 144 retry, 145 params={"action": "fetch_data"}, 146 headers={"X-Requested-With": "XMLHttpRequest"}, 147 ) 148 response.raise_for_status() 149 try: 150 payload = response.json() 151 except json.JSONDecodeError: 152 raise FirmsError("the missing-data page did not answer with JSON") from None 153 if not payload.get("success") or "html" not in payload: 154 raise FirmsError("the missing-data page reported a failure") 155 return parse_missing_days(payload["html"])
The days each satellite has no data in FIRMS; see the module.
117def nearest_places( 118 latitude: float, longitude: float, places: Iterable[Place], *, k: int = 3 119) -> list[dict[str, Any]]: 120 """The ``k`` nearest places, with the event's direction *from* each place. 121 122 ``"direction": "NE"`` reads "the fire is north-east of the place". 123 """ 124 ranked = sorted( 125 ((distance_km(p.latitude, p.longitude, latitude, longitude), p) for p in places), 126 key=lambda pair: pair[0], 127 )[:k] 128 return [ 129 { 130 "name": p.name, 131 "kind": p.kind or None, 132 "distance_km": round(d, 1), 133 "direction": bearing(p.latitude, p.longitude, latitude, longitude), 134 } 135 for d, p in ranked 136 ]
The k nearest places, with the event's direction from each place.
"direction": "NE" reads "the fire is north-east of the place".
92def parse_csv(text: str) -> list[Hotspot]: 93 """Every well-formed row; rows without coordinates, date or time are skipped.""" 94 out: list[Hotspot] = [] 95 for raw in csv.DictReader(io.StringIO(text)): 96 row = {str(k).strip().lower(): (v or "").strip() for k, v in raw.items() if k} 97 lat, lon = _float(row.get("latitude")), _float(row.get("longitude")) 98 if lat is None or lon is None: 99 continue 100 try: 101 day = date.fromisoformat(row.get("acq_date", "")[:10]) 102 hhmm = int(row.get("acq_time", "")) 103 except ValueError: 104 continue 105 if not 0 <= hhmm <= 2359: 106 continue 107 kind = _float(row.get("type")) 108 out.append( 109 Hotspot( 110 latitude=lat, 111 longitude=lon, 112 acq_date=day, 113 acq_time=hhmm, 114 confidence=row.get("confidence") or None, 115 frp_mw=_float(row.get("frp")), 116 brightness_k=_float(row.get("bright_ti4")) or _float(row.get("brightness")), 117 daynight=row.get("daynight") or None, 118 satellite=row.get("satellite") or None, 119 instrument=row.get("instrument") or None, 120 detection_type=int(kind) if kind is not None else None, 121 brightness_t5_k=_float(row.get("bright_ti5")) or _float(row.get("bright_t31")), 122 scan_km=_float(row.get("scan")), 123 track_km=_float(row.get("track")), 124 version=row.get("version") or None, 125 ) 126 ) 127 return out
Every well-formed row; rows without coordinates, date or time are skipped.
310def save_worldcover( 311 bbox: tuple[float, float, float, float], 312 directory: Path | None = None, 313 *, 314 year: int = 2021, 315 source: str = WORLDCOVER_URL, 316) -> list[Path]: 317 """Copy WorldCover over ``bbox`` into ``directory/worldcover``, under the tiles' names. 318 319 Then :meth:`WorldCover.synced` (or ``WorldCover(<that folder>)``) reads 320 it without the network. One file per tile the box touches, cut to the 321 box; a file that already covers its part is kept, so running it again 322 costs nothing. Returns the files. 323 """ 324 import rasterio 325 from rasterio.windows import Window, from_bounds 326 327 west, south, east, north = bbox 328 if not (west < east and south < north): 329 raise ValueError("bbox is west,south,east,north with west < east and south < north") 330 land = WorldCover(source, year=year) 331 out_root = (directory or default_directory()) / WORLDCOVER_DIR 332 corners = range(math.floor(south / 3) * 3, math.ceil(north / 3) * 3, 3) 333 columns = range(math.floor(west / 3) * 3, math.ceil(east / 3) * 3, 3) 334 written: list[Path] = [] 335 for tile_south in corners: 336 for tile_west in columns: 337 part = ( 338 max(west, tile_west), 339 max(south, tile_south), 340 min(east, tile_west + 3), 341 min(north, tile_south + 3), 342 ) 343 path = land.tile(tile_south + 1.5, tile_west + 1.5) 344 out = out_root / path.removeprefix(land.source + "/") 345 if out.exists() and _covers(out, part): 346 written.append(out) 347 continue 348 dataset = land._dataset(path) 349 if dataset is None: # open sea: no tile 350 continue 351 window = from_bounds(*part, dataset.transform).round_offsets().round_lengths() 352 window = window.intersection(Window(0, 0, dataset.width, dataset.height)) 353 profile = { 354 "driver": "GTiff", 355 "height": window.height, 356 "width": window.width, 357 "count": 1, 358 "dtype": "uint8", 359 "crs": dataset.crs, 360 "transform": dataset.window_transform(window), 361 "nodata": 0, 362 "compress": "deflate", 363 "tiled": True, 364 } 365 out.parent.mkdir(parents=True, exist_ok=True) 366 with rasterio.open(out, "w", **profile) as copy: 367 for row in range(0, window.height, _BLOCK_ROWS): 368 rows = min(_BLOCK_ROWS, window.height - row) 369 block = Window(window.col_off, window.row_off + row, window.width, rows) 370 copy.write( 371 dataset.read(1, window=block), 1, window=Window(0, row, window.width, rows) 372 ) 373 written.append(out) 374 land.close() 375 return written
Copy WorldCover over bbox into directory/worldcover, under the tiles' names.
Then WorldCover.synced() (or WorldCover(<that folder>)) reads
it without the network. One file per tile the box touches, cut to the
box; a file that already covers its part is kept, so running it again
costs nothing. Returns the files.
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.
216def seen(area_ha: float, *, period: str = LATEST) -> Seen: 217 """How often FIRMS saw a fire of ``area_ha`` hectares, in the measured ``period``.""" 218 if area_ha < 0: 219 raise ValueError("area_ha must be 0 or more") 220 table = detection_table() 221 row = next(c for c in reversed(table["classes"]) if area_ha >= c["from_ha"]) 222 if period not in row["periods"]: 223 raise ValueError(f"period must be one of {sorted(row['periods'])}") 224 counts = row["periods"][period] 225 return Seen( 226 area_ha=area_ha, 227 from_ha=row["from_ha"], 228 to_ha=row["to_ha"], 229 period=period, 230 perimeters=counts["perimeters"], 231 seen=counts["seen"], 232 no_data=counts.get("no_data", 0), 233 country=table["country"], 234 product=table["product"], 235 )
How often FIRMS saw a fire of area_ha hectares, in the measured period.
159def select( 160 hotspots: Iterable[Hotspot], 161 *, 162 vegetation_only: bool = True, 163 min_confidence: ConfidenceLevel = "nominal", 164 min_confidence_pct: int | None = None, 165 min_frp_mw: float = 0.0, 166) -> list[Hotspot]: 167 """Keep the detections that look like fires. 168 169 * ``vegetation_only`` drops ``type`` 1-3 (volcanoes, industry, offshore); 170 a row without ``type`` is kept, since it cannot be judged; 171 * the confidence bar is ``min_confidence`` for VIIRS levels, and 172 ``min_confidence_pct`` for MODIS percentages when given (otherwise the 173 percentage is mapped with :func:`confidence_level`). A missing 174 confidence is kept: dropping a real fire is worse than keeping a 175 doubtful pixel; 176 * ``min_frp_mw`` drops weaker detections, and those without FRP, when 177 above zero. 178 """ 179 out = [] 180 for h in hotspots: 181 if vegetation_only and h.is_vegetation_fire is False: 182 continue 183 if not _confident(h.confidence, min_confidence, min_confidence_pct): 184 continue 185 if min_frp_mw > 0 and (h.frp_mw is None or h.frp_mw < min_frp_mw): 186 continue 187 out.append(h) 188 return out
Keep the detections that look like fires.
vegetation_onlydropstype1-3 (volcanoes, industry, offshore); a row withouttypeis kept, since it cannot be judged;- the confidence bar is
min_confidencefor VIIRS levels, andmin_confidence_pctfor MODIS percentages when given (otherwise the percentage is mapped withconfidence_level()). A missing confidence is kept: dropping a real fire is worse than keeping a doubtful pixel; min_frp_mwdrops weaker detections, and those without FRP, when above zero.
55def summarize( 56 hotspots: Iterable[Hotspot], 57 *, 58 top_events: int = 10, 59 top_cells: int = 5, 60 radius_m: float = 750.0, 61 gap_days: int = 1, 62) -> dict[str, Any]: 63 """Everything worth knowing about ``hotspots``, in a few kilobytes. 64 65 * ``detections``, ``period``, ``by_type``, ``by_month``, ``by_daynight``, 66 ``frp_mw``: about every row; 67 * ``fires``: how many :func:`~firms_client.select` keeps (defaults); 68 * ``events``: the kept fires clustered with :func:`~firms_client.cluster` 69 (``radius_m``, ``gap_days``), the ``top_events`` largest by total FRP; 70 * ``hot_cells``: the ``top_cells`` cells of 0.01° (about 1 km) with the 71 most fire-days over every row, with the share that is not vegetation: 72 where the steelworks are; 73 * ``caveats`` and ``attribution``: to pass on with the numbers. 74 """ 75 rows = list(hotspots) 76 fires = select(rows) 77 events = cluster(fires, radius_m=radius_m, gap_days=gap_days) 78 untyped = sum(1 for h in rows if h.detection_type is None) 79 80 caveats = [PRESENCE_ONLY, PIXELS_NOT_FIRES] 81 if untyped: 82 caveats.append( 83 f"{untyped} of {len(rows)} detections have no type (near-real-time data): " 84 "industrial sources, volcanoes and flares cannot be told from fires, " 85 "and were kept as fires." 86 ) 87 88 frp = [h.frp_mw for h in rows if h.frp_mw is not None] 89 return { 90 "detections": len(rows), 91 "period": _period(rows), 92 "by_type": _by_type(rows), 93 "by_month": dict(sorted(Counter(h.acq_date.strftime("%Y-%m") for h in rows).items())), 94 "by_daynight": dict(sorted(Counter(h.daynight or "unknown" for h in rows).items())), 95 "frp_mw": { 96 "max": max(frp), 97 "median": round(statistics.median(frp), 2), 98 "total": round(sum(frp), 2), 99 } 100 if frp 101 else None, 102 "fires": len(fires), 103 "events": { 104 "count": len(events), 105 "radius_m": radius_m, 106 "gap_days": gap_days, 107 "largest": [e.as_dict() for e in events[:top_events]], 108 }, 109 "hot_cells": _hot_cells(rows, top_cells), 110 "caveats": caveats, 111 "attribution": ATTRIBUTION, 112 }
Everything worth knowing about hotspots, in a few kilobytes.
detections,period,by_type,by_month,by_daynight,frp_mw: about every row;fires: how many~firms_client.select()keeps (defaults);events: the kept fires clustered with~firms_client.cluster()(radius_m,gap_days), thetop_eventslargest by total FRP;hot_cells: thetop_cellscells of 0.01° (about 1 km) with the most fire-days over every row, with the share that is not vegetation: where the steelworks are;caveatsandattribution: to pass on with the numbers.
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.
39def to_csv(hotspots: Iterable[Hotspot]) -> str: 40 """One row per hotspot, with :data:`CSV_COLUMNS`; missing values are empty.""" 41 out = io.StringIO() 42 writer = csv.DictWriter(out, fieldnames=CSV_COLUMNS, lineterminator="\n") 43 writer.writeheader() 44 for h in hotspots: 45 writer.writerow(_plain(h)) 46 return out.getvalue()
One row per hotspot, with CSV_COLUMNS; missing values are empty.
23def to_geojson(hotspots: Iterable[Hotspot]) -> dict[str, Any]: 24 """A GeoJSON ``FeatureCollection`` of points; every other field is a property.""" 25 features = [] 26 for h in hotspots: 27 properties = _plain(h) 28 del properties["latitude"], properties["longitude"] 29 features.append( 30 { 31 "type": "Feature", 32 "geometry": {"type": "Point", "coordinates": [h.longitude, h.latitude]}, 33 "properties": properties, 34 } 35 ) 36 return {"type": "FeatureCollection", "features": features}
A GeoJSON FeatureCollection of points; every other field is a property.
108def trust( 109 latitude: float, 110 longitude: float, 111 *, 112 mask: StaticMask | None = None, 113 land: LandCover | None = None, 114 radius_m: float = RADIUS_M, 115 rules: BurningRules | None = None, 116) -> Reliability: 117 """How far a detection at a place can be read as a vegetation fire. 118 119 Pass the country's static mask (:func:`~firms_client.fetch_static_mask`) 120 and a land cover (:class:`~firms_client.WorldCover`); a part without its 121 source stays unknown and does not count. 122 """ 123 reasons: list[str] = [] 124 static: float | None = None 125 if mask is not None: 126 found = mask.verdict_at(latitude, longitude) 127 static = 1.0 128 if found is not None: 129 static = 0.0 130 name = TYPE_NAMES.get(found.detection_type, "static").replace("_", " ") 131 reasons.append( 132 f"{name}: {found.fire_days} fire-days over {found.years} years in the archives" 133 ) 134 land_part: float | None = None 135 named: dict[str, float] = {} 136 if land is not None: 137 shares = land.shares(latitude, longitude, radius_m) 138 water = sum(v for c, v in shares.items() if c in NO_VEGETATION) 139 if shares and water >= NO_VEGETATION_SHARE: 140 land_part = 0.0 141 reasons.append( 142 f"water or snow {100 * round(water, 3):.0f}%: no vegetation can burn here" 143 ) 144 elif shares: 145 kind, why = land_kind(shares, rules) 146 land_part = {"natural": 1.0, "cropland": 1.0, "mixed": MIXED_LAND}.get( 147 kind, ARTIFICIAL_LAND 148 ) 149 if kind == "mixed": 150 reasons.append(f"{why}: crop burning and wildfire cannot be told apart") 151 elif kind == "artificial": 152 reasons.append(f"{why}: hot surfaces and industry look like fires") 153 if shares: 154 named = { 155 WORLDCOVER_CLASSES.get(c, f"class_{c}"): round(v, 3) 156 for c, v in sorted(shares.items(), key=lambda kv: -kv[1]) 157 if v >= 0.005 158 } 159 known = [p for p in (static, land_part) if p is not None] 160 score = min(known) if known else None 161 if score is None: 162 reasons.append("not measured: no static mask and no land cover here") 163 return Reliability( 164 latitude=latitude, 165 longitude=longitude, 166 score=score, 167 reliable=score is not None and score >= RELIABLE_FROM, 168 static=static, 169 land=land_part, 170 land_cover=named, 171 reasons=tuple(reasons), 172 )
How far a detection at a place can be read as a vegetation fire.
Pass the country's static mask (~firms_client.fetch_static_mask())
and a land cover (~firms_client.WorldCover); a part without its
source stays unknown and does not count.
191def within( 192 hotspots: Iterable[Hotspot], bbox: tuple[float, float, float, float] | None 193) -> list[Hotspot]: 194 """The hotspots inside ``bbox`` ``(west, south, east, north)``, edges included. 195 196 All of them when ``bbox`` is ``None``. Use it to look at one region of a 197 country's archive. 198 """ 199 if bbox is None: 200 return list(hotspots) 201 west, south, east, north = bbox 202 return [h for h in hotspots if west <= h.longitude <= east and south <= h.latitude <= north]
The hotspots inside bbox (west, south, east, north), edges included.
All of them when bbox is None. Use it to look at one region of a
country's archive.
72def worldcover_tiles(bbox: BBox, *, year: int = 2021) -> list[str]: 73 """The bucket URLs of the WorldCover tiles that touch ``bbox`` (west, south, east, north).""" 74 west, south, east, north = bbox 75 land = WorldCover(year=year) 76 return [ 77 land.tile(lat + TILE_DEG / 2, lon + TILE_DEG / 2) 78 for lat in range( 79 math.floor(south / TILE_DEG) * TILE_DEG, 80 math.ceil(north / TILE_DEG) * TILE_DEG, 81 TILE_DEG, 82 ) 83 for lon in range( 84 math.floor(west / TILE_DEG) * TILE_DEG, math.ceil(east / TILE_DEG) * TILE_DEG, TILE_DEG 85 ) 86 ]
The bucket URLs of the WorldCover tiles that touch bbox (west, south, east, north).