"""Read the downloaded iNaturalist species packs (see `modules/map/species.py`): search species by name and by what lives near a point, a species' details and range dots, and its Wikipedia article in a Zim. Packs are read directly and read-only, like the map's `.search.db` files; nothing is copied into WROLPi's database. A species may be in several packs (regions) at once: its counts are summed, its bbox and range are unions. """ import math import re import sqlite3 import urllib.parse from contextlib import closing from dataclasses import dataclass, field from pathlib import Path from typing import Dict, Iterable, List, Optional, Tuple from sqlalchemy.orm import Session from modules.map import lib from modules.map.species import (GROUP_NAMES, HIGH_GRID, LOOKUP_GRID, LOW_GRID, PLANET, cell_center, cell_id, decode_cells, decode_months, mask_months) from modules.zim.lib import parse_name, run_libzim_jobs from modules.zim.models import Zim from wrolpi.common import logger logger = logger.getChild(__name__) __all__ = ['DEFAULT_RADIUS_KM', 'MAX_RADIUS_KM', 'cells_within', 'search_species', 'get_species', 'get_species_range', 'species_here', 'wikipedia_zims', 'find_wikipedia_article'] DEFAULT_RADIUS_KM = 30 MAX_RADIUS_KM = 200 DEFAULT_LIMIT = 50 EARTH_RADIUS_KM = 6371.0 SPECIES_COLUMNS = 'taxon_id, name, common_name, wiki_title, grp, obs_count, min_lat, min_lon, max_lat, max_lon' # Columns added to packs later: older packs do not have them. OPTIONAL_COLUMNS = ('months', 'other_names') # Wikipedia Zims, best first: kiwix names them wikipedia_en___.zim. WIKIPEDIA_PREFIX = 'wikipedia_en_' WIKIPEDIA_FLAVORS = ('maxi', 'nopic', 'mini') def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float: lat1, lon1, lat2, lon2 = map(math.radians, (lat1, lon1, lat2, lon2)) a = math.sin((lat2 - lat1) / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2 return 2 * EARTH_RADIUS_KM * math.asin(min(1.0, math.sqrt(a))) def cells_within(lat: float, lon: float, radius_km: float, grid: float = LOOKUP_GRID) -> List[int]: """The cells of a grid any part of which is within `radius_km` of a point (always including the point's own).""" rows, columns = round(180 / grid), round(360 / grid) delta_lat = math.degrees(radius_km / EARTH_RADIUS_KM) cos_lat = math.cos(math.radians(lat)) delta_lon = 180 if cos_lat < 1e-9 else min(180.0, delta_lat / cos_lat) row_min = max(0, math.floor((lat - delta_lat + 90) / grid)) row_max = min(rows - 1, math.floor((lat + delta_lat + 90) / grid)) # Columns are not wrapped yet, so a cell's edges are on the same side of the antimeridian as `lon`. column_min = math.floor((lon - delta_lon + 180) / grid) column_max = math.floor((lon + delta_lon + 180) / grid) if column_max - column_min + 1 >= columns: column_min, column_max = 0, columns - 1 cells = set() for row in range(row_min, row_max + 1): south = row * grid - 90 nearest_lat = min(max(lat, south), south + grid) for column in range(column_min, column_max + 1): west = column * grid - 180 nearest_lon = min(max(lon, west), west + grid) if haversine_km(lat, lon, nearest_lat, nearest_lon) <= radius_km: cells.add(row * columns + column % columns) row = min(max(math.floor((lat + 90) / grid), 0), rows - 1) cells.add(row * columns + min(max(math.floor((lon + 180) / grid), 0), columns - 1)) return sorted(cells) def fts_query(q: str) -> Optional[str]: """An FTS5 query matching every word of `q` as a prefix, or None if `q` has no words.""" words = re.findall(r'\w+', q) return ' '.join(f'"{word}"*' for word in words) or None def species_packs() -> List[Path]: """The downloaded species packs, one per region, the newest versions first (their names are preferred). The planet pack holds every region: when it is downloaded, it is the only one read, so no observation is counted twice.""" directory = lib.get_species_directory() files = sorted(lib.get_species_files(), key=lambda i: i['version'], reverse=True) if planet := [i for i in files if i['region'] == PLANET]: files = planet return [directory / i['name'] for i in files] def has_column(db: sqlite3.Connection, table: str, column: str) -> bool: """Whether a pack's table has a column: packs built before months were kept have no `months`.""" return any(row[1] == column for row in db.execute(f'PRAGMA table_info({table})')) def species_columns(db: sqlite3.Connection) -> str: return ', '.join([SPECIES_COLUMNS] + [i for i in OPTIONAL_COLUMNS if has_column(db, 'species', i)]) def open_pack(path: Path) -> sqlite3.Connection: db = sqlite3.connect(f'{path.as_uri()}?mode=ro', uri=True) db.row_factory = sqlite3.Row return db @dataclass class Species: """A species merged from every pack it is in.""" taxon_id: int name: str common_name: Optional[str] wiki_title: Optional[str] group_code: int obs_count: int = 0 near_count: Optional[int] = None bbox: Optional[List[float]] = None # [min_lon, min_lat, max_lon, max_lat] regions: List[str] = field(default_factory=list) # Observations in each month, January first; all 0 when the packs have no months. months: List[int] = field(default_factory=lambda: [0] * 12) other_names: Optional[str] = None # Packs on both sides of the antimeridian: a min/max bbox would be the long way around the world. bbox_wraps: bool = False def add(self, row: sqlite3.Row, region: str): self.obs_count += row['obs_count'] self.regions.append(region) keys = row.keys() # A name a pack lacks is taken from another (packs are read newest first, so the newest name wins). self.common_name = self.common_name or row['common_name'] self.wiki_title = self.wiki_title or row['wiki_title'] if 'other_names' in keys: self.other_names = self.other_names or row['other_names'] if 'months' in keys: self.months = [a + b for a, b in zip(self.months, decode_months(row['months']))] if row['min_lat'] is not None: bbox = [row['min_lon'], row['min_lat'], row['max_lon'], row['max_lat']] self.bbox = bbox if self.bbox is None else [ min(self.bbox[0], bbox[0]), min(self.bbox[1], bbox[1]), max(self.bbox[2], bbox[2]), max(self.bbox[3], bbox[3]), ] self.bbox_wraps = self.bbox_wraps or self.bbox[2] - self.bbox[0] > 180 def __json__(self) -> dict: return dict( taxon_id=self.taxon_id, name=self.name, common_name=self.common_name, wiki_title=self.wiki_title, group=GROUP_NAMES.get(self.group_code, GROUP_NAMES[0]), group_code=self.group_code, obs_count=self.obs_count, near_count=self.near_count, bbox=None if self.bbox_wraps else self.bbox, regions=self.regions, months=self.months, other_names=self.other_names, ) def _merge(merged: Dict[int, Species], rows: Iterable[sqlite3.Row], region: str): for row in rows: if not (species := merged.get(row['taxon_id'])): species = merged[row['taxon_id']] = Species( taxon_id=row['taxon_id'], name=row['name'], common_name=row['common_name'], wiki_title=row['wiki_title'], group_code=row['grp']) species.add(row, region) def _region(db: sqlite3.Connection, path: Path) -> str: row = db.execute("SELECT value FROM meta WHERE key = 'region'").fetchone() return row['value'] if row else path.stem def near_counts(packs: List[Path], cells: str) -> Dict[int, int]: """How many times each species was seen in `cells` (a JSON list of lookup cells). Map regions overlap, some widely: where two packs hold the same cell, each holds all of its observations, so the larger count of the two is taken, not their sum. Only when one pack holds these cells (the usual case) are its counts simply summed by SQLite.""" holding = [] for path in packs: try: with closing(open_pack(path)) as db: if db.execute('SELECT 1 FROM cell_species WHERE cell IN (SELECT value FROM json_each(?)) LIMIT 1', (cells,)).fetchone(): holding.append(path) except sqlite3.Error as e: logger.error(f'Could not read species pack {path}', exc_info=e) if len(holding) == 1: with closing(open_pack(holding[0])) as db: return dict(db.execute('SELECT taxon_id, SUM(obs_count) FROM cell_species' ' WHERE cell IN (SELECT value FROM json_each(?)) GROUP BY taxon_id', (cells,))) largest: Dict[Tuple[int, int], int] = dict() for path in holding: with closing(open_pack(path)) as db: for cell, taxon_id, count in db.execute( 'SELECT cell, taxon_id, obs_count FROM cell_species WHERE cell IN (SELECT value FROM json_each(?))', (cells,)): if count > largest.get((cell, taxon_id), 0): largest[(cell, taxon_id)] = count near: Dict[int, int] = dict() for (_, taxon_id), count in largest.items(): near[taxon_id] = near.get(taxon_id, 0) + count return near def search_species(q: str = None, lat: float = None, lon: float = None, radius_km: float = DEFAULT_RADIUS_KM, group: int = None, limit: int = DEFAULT_LIMIT) -> List[dict]: """Species whose names match `q` (every word, as a prefix), or with a location and no `q`, the species seen within `radius_km` of it. With a location each species has a `near_count` (its observations within the radius), and those seen nearby come first, most observed nearby first; then the rest by their total observations. An exact name match comes first. Thousands of species may match (all those seen within 100 km), but only `limit` are returned: they are ranked from bare (taxon, names, count) tuples, and only those returned are read in full.""" located = lat is not None and lon is not None match = fts_query(q) if q else None if q and not match: return [] cells = str(cells_within(lat, lon, radius_km)) if located else None totals: Dict[int, int] = dict() names: Dict[int, Tuple[str, Optional[str]]] = dict() packs = species_packs() near = near_counts(packs, cells) if located else dict() for path in packs: try: with closing(open_pack(path)) as db: db.row_factory = None where, params = [], [] if match: where.append('taxon_id IN (SELECT rowid FROM species_fts WHERE species_fts MATCH ?)') params.append(match) if group is not None: where.append('grp = ?') params.append(group) if located and not match: # What lives here: only the species seen nearby. if not near: break where.append('taxon_id IN (SELECT value FROM json_each(?))') params.append(str(list(near))) sql = 'SELECT taxon_id, name, common_name, obs_count FROM species' if where: sql += ' WHERE ' + ' AND '.join(where) for taxon_id, name, common_name, obs_count in db.execute(sql, params): totals[taxon_id] = totals.get(taxon_id, 0) + obs_count if taxon_id not in names or (common_name and not names[taxon_id][1]): names[taxon_id] = (name, common_name) except sqlite3.Error as e: logger.error(f'Could not read species pack {path}', exc_info=e) q_lower = (q or '').strip().lower() def rank(taxon_id: int): name, common_name = names[taxon_id] exact = bool(q_lower) and q_lower in ((name or '').lower(), (common_name or '').lower()) return not exact, -near.get(taxon_id, 0), -totals[taxon_id], name chosen = sorted(totals, key=rank)[:limit] if not chosen: return [] # Only the species returned are read in full. merged: Dict[int, Species] = dict() for path in packs: try: with closing(open_pack(path)) as db: _merge(merged, db.execute( f'SELECT {species_columns(db)} FROM species WHERE taxon_id IN (SELECT value FROM json_each(?))', (str(chosen),)), _region(db, path)) except sqlite3.Error as e: logger.error(f'Could not read species pack {path}', exc_info=e) results = [] for taxon_id in chosen: if species := merged.get(taxon_id): if located: species.near_count = near.get(taxon_id, 0) results.append(species.__json__()) return results def _species_rows(taxon_id: int) -> Tuple[Optional[Species], List[sqlite3.Row]]: """A species merged from every pack, and its row in each (which hold its range dots).""" merged: Dict[int, Species] = dict() rows = [] for path in species_packs(): try: with closing(open_pack(path)) as db: row = db.execute(f'SELECT {species_columns(db)}, range_low, range_high FROM species' f' WHERE taxon_id = ?', (taxon_id,)).fetchone() if row: _merge(merged, [row], _region(db, path)) rows.append(row) except sqlite3.Error as e: logger.error(f'Could not read species pack {path}', exc_info=e) return merged.get(taxon_id), rows def species_here(lat: float, lon: float, limit: int = DEFAULT_LIMIT, taxon_id: int = None) -> dict: """What was seen in the lookup cell (about 11 km) containing a point: the cell's bounds, how many species, and the species most seen there first, each with `here_count` (its observations in the cell) and `here_months` (the months it was seen in there; empty when the packs have no months). `taxon`: the species `taxon_id` there, however few times it was seen (None when it was not).""" cell = cell_id(lat, lon, LOOKUP_GRID) south_lat, west_lon = (i - LOOKUP_GRID / 2 for i in cell_center(cell, LOOKUP_GRID)) merged: Dict[int, Species] = dict() here: Dict[int, List[int]] = dict() # taxon_id -> [count, mask of months] for path in species_packs(): try: with closing(open_pack(path)) as db: months = 'months' if has_column(db, 'cell_species', 'months') else '0' rows = db.execute(f'SELECT taxon_id, obs_count, {months} FROM cell_species WHERE cell = ?', (cell,)).fetchall() if not rows: continue for taxon, count, mask in rows: # Overlapping regions each hold all of the cell's observations: the larger count, not the sum. entry = here.setdefault(taxon, [0, 0]) entry[0] = max(entry[0], count) entry[1] |= mask _merge(merged, db.execute( f'SELECT {species_columns(db)} FROM species WHERE taxon_id IN (SELECT value FROM json_each(?))', (str([row[0] for row in rows]),)), _region(db, path)) except sqlite3.Error as e: logger.error(f'Could not read species pack {path}', exc_info=e) def entry(i: Species) -> dict: count, mask = here[i.taxon_id] return {**i.__json__(), 'here_count': count, 'here_months': mask_months(mask)} found = sorted(merged.values(), key=lambda i: (-here[i.taxon_id][0], i.name)) species = [entry(i) for i in found[:limit]] return dict( taxon=entry(merged[taxon_id]) if taxon_id in merged else None, bbox=[round(west_lon, 4), round(south_lat, 4), round(west_lon + LOOKUP_GRID, 4), round(south_lat + LOOKUP_GRID, 4)], species_count=len(found), species=species, ) def get_species(taxon_id: int) -> Optional[dict]: species, _ = _species_rows(taxon_id) return species.__json__() if species else None def get_species_range(taxon_id: int, grid: str = 'low') -> Optional[dict]: """The cells of a grid a species was observed in, for the browser to draw as dots: `{grid, count, deltas}`. `low` is a 0.1° grid of every observation, `high` a 0.02° grid of the precise ones only. The cells are sorted and sent as differences (the first cell, then each one's distance from the one before), which keeps a wide range's response small; a cell is `row * columns + column` from the south-west corner (see `modules.map.species`).""" column, size = ('range_high', HIGH_GRID) if grid == 'high' else ('range_low', LOW_GRID) species, rows = _species_rows(taxon_id) if not species: return None cells = set() for row in rows: if row[column]: cells.update(decode_cells(row[column])) deltas, last = [], 0 for cell in sorted(cells): deltas.append(cell - last) last = cell return dict(grid=size, count=len(deltas), deltas=deltas) # --- Wikipedia -------------------------------------------------------------------------------------------------------- def wikipedia_zims(session: Session) -> list: """The English Wikipedia Zims, best first: maxi, nopic, mini, then any other; within each, all of Wikipedia (`wikipedia_en_all_*`) before a selection of it (`top`, `medicine`, ...), then the newest.""" zims = [] for zim in session.query(Zim).all(): try: name, date = parse_name(zim.path) except ValueError: continue if not name.startswith(WIKIPEDIA_PREFIX): continue flavor = name.rsplit('_', 1)[-1] rank = WIKIPEDIA_FLAVORS.index(flavor) if flavor in WIKIPEDIA_FLAVORS else len(WIKIPEDIA_FLAVORS) everything = name.startswith(f'{WIKIPEDIA_PREFIX}all_') zims.append((rank, not everything, -date.timestamp(), zim)) return [zim for *_, zim in sorted(zims, key=lambda i: i[:3])] def article_paths(wiki_title: str) -> List[str]: """The paths a Wikipedia article may have in a Zim: the title, then the old `A/` namespace.""" title = wiki_title.replace(' ', '_') return [title, f'A/{title}'] async def find_wikipedia_article(session: Session, wiki_title: Optional[str], name: str) -> Optional[dict]: """Where to read about a species: its article in the best Wikipedia Zim that has it, else a search for its name. None when there is no Wikipedia Zim.""" zims = wikipedia_zims(session) if not zims: return None if wiki_title: # One Zim at a time, best first: opening a large Zim cold takes seconds, and the best usually has the article. for zim in zims: try: result, = await run_libzim_jobs([dict(op='find', path=str(zim.path), paths=article_paths(wiki_title))]) except Exception as e: logger.error(f'Could not look for {wiki_title!r} in {zim.path}', exc_info=e) continue if path := result.get('found'): return dict(zim_id=zim.id, path=path, title=result.get('title'), url=f'/api/zim/{zim.id}/entry/{urllib.parse.quote(path)}') return dict(zim_id=None, path=None, title=None, url=f'/search?q={urllib.parse.quote(name)}')