"""iNaturalist species packs: the format shared by the build (wrolpi/scripts/build_inat_regions.py) and WROLPi. A pack is one SQLite file per map region, `inat--.species.db`: meta key/value: version, region, bbox, source, license, attribution, grids species one row per species; `range_low`/`range_high` are its range dots, see `encode_cells`; `months` is how many observations were made in each month, see `encode_months`; `other_names` its other English names ("; " between them) cell_species (lookup grid cell, taxon) -> observation count and the months it was seen in (a bit per month); answers "what lives near this point" species_fts full text search of species names, common names and other names A species' range is drawn as dots, one per grid cell it was observed in. Cells are numbered row by row from the south-west corner of the world: `row * columns + column`. """ import math import re from typing import Iterable, List, Optional, Tuple import zlib __all__ = ['GROUPS', 'GROUP_NAMES', 'LOW_GRID', 'HIGH_GRID', 'LOOKUP_GRID', 'PLANET', 'SPECIES_DB_SUFFIX', 'SCHEMA', 'cell_id', 'cell_center', 'encode_cells', 'decode_cells', 'pack_name', 'parse_pack_name', 'month_bit', 'mask_months', 'encode_months', 'decode_months'] SPECIES_DB_SUFFIX = '.species.db' # The pack of every region merged. Where it is downloaded, it is read instead of the regions' packs. PLANET = 'planet' # A region is lowercase words joined by hyphens; a version is the export's date. PACK_NAME_PATTERN = re.compile(r'inat-([a-z0-9]+(?:-[a-z0-9]+)*)-(\d{8})' + re.escape(SPECIES_DB_SUFFIX)) # Degrees. LOW: every observation, for the zoomed-out range. HIGH: precise observations only, for zoomed in. LOW_GRID = 0.1 HIGH_GRID = 0.02 # "What lives near this point" sums the cells within a radius. LOOKUP_GRID = 0.1 # (iNaturalist taxon id, group code, name). A species is in the first group in its ancestry, so classes come before # the kingdoms that contain them. 0 is any other group. GROUPS: List[Tuple[int, int, str]] = [ (3, 2, 'Birds'), (40151, 3, 'Mammals'), (26036, 4, 'Reptiles'), (20978, 5, 'Amphibians'), (47178, 6, 'Ray-finned fishes'), (47158, 7, 'Insects'), (47119, 8, 'Arachnids'), (47115, 9, 'Mollusks'), (47126, 1, 'Plants'), (47170, 10, 'Fungi'), ] GROUP_NAMES = {code: name for _, code, name in GROUPS} GROUP_NAMES[0] = 'Other' SCHEMA = ''' CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT); CREATE TABLE species ( taxon_id INTEGER PRIMARY KEY, name TEXT NOT NULL, common_name TEXT, wiki_title TEXT, grp INTEGER NOT NULL, obs_count INTEGER NOT NULL, min_lat REAL, min_lon REAL, max_lat REAL, max_lon REAL, range_low BLOB, range_high BLOB, months TEXT, other_names TEXT ); CREATE TABLE cell_species ( cell INTEGER NOT NULL, taxon_id INTEGER NOT NULL, obs_count INTEGER NOT NULL, months INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (cell, taxon_id) ) WITHOUT ROWID; CREATE VIRTUAL TABLE species_fts USING fts5(name, common_name, other_names, content='species', content_rowid='taxon_id'); ''' def pack_name(region: str, version: str) -> str: """The file name of a region's pack.""" return f'inat-{region}-{version}{SPECIES_DB_SUFFIX}' def parse_pack_name(name: str) -> Optional[Tuple[str, str]]: """(region, version) of a pack's file name, or None if it is not one.""" if match := PACK_NAME_PATTERN.fullmatch(name): return match.group(1), match.group(2) return None def _dimensions(grid: float) -> Tuple[int, int]: return round(180 / grid), round(360 / grid) def cell_id(lat: float, lon: float, grid: float) -> int: """The cell of a grid that contains a point. The north pole and the antimeridian fall in the last row/column.""" rows, columns = _dimensions(grid) row = min(max(math.floor((lat + 90) / grid), 0), rows - 1) column = min(max(math.floor((lon + 180) / grid), 0), columns - 1) return row * columns + column def cell_center(cell: int, grid: float) -> Tuple[float, float]: """(lat, lon) of the center of a cell.""" _, columns = _dimensions(grid) row, column = divmod(cell, columns) return row * grid - 90 + grid / 2, column * grid - 180 + grid / 2 def encode_cells(cells: Iterable[int]) -> bytes: """Compress a set of cell ids: sorted, each stored as the difference from the last (a varint), then zlib.""" out = bytearray() last = 0 for cell in sorted(set(cells)): delta = cell - last last = cell while True: byte = delta & 0x7F delta >>= 7 out.append(byte | (0x80 if delta else 0)) if not delta: break return zlib.compress(bytes(out), 9) def decode_cells(blob: bytes) -> List[int]: """The sorted cell ids of `encode_cells`.""" cells = [] last = shift = value = 0 for byte in zlib.decompress(blob): value |= (byte & 0x7F) << shift if byte & 0x80: shift += 7 continue last += value cells.append(last) shift = value = 0 return cells # Months are 1 (January) to 12; 0 is an observation without a date. Packs built before months were kept have no # `months` columns. def month_bit(month: int) -> int: """The bit of a month in a mask of months (January is bit 0); 0 for no month.""" return 1 << (month - 1) if 1 <= month <= 12 else 0 def mask_months(mask: int) -> List[int]: """The months (1-12) in a mask of months.""" return [month for month in range(1, 13) if mask & month_bit(month)] def encode_months(counts: List[int]) -> Optional[str]: """Twelve monthly counts (January first) as text, or None when every one is 0.""" return ','.join(str(i) for i in counts) if any(counts) else None def decode_months(text: Optional[str]) -> List[int]: """The twelve monthly counts of `encode_months`; all 0 for none.""" if not text: return [0] * 12 counts = [int(i) for i in text.split(',')] return counts if len(counts) == 12 else [0] * 12