import gzip import json import sqlite3 import struct from collections import Counter from pathlib import Path from typing import Callable import pytest from modules.map import lib from modules.map.species import (HIGH_GRID, LOOKUP_GRID, LOW_GRID, SCHEMA, cell_id, encode_cells, encode_months, month_bit, pack_name) PROTOMAPS_LAYERS = ('boundaries', 'buildings', 'earth', 'landcover', 'landuse', 'places', 'pois', 'roads', 'water') def pmtiles_bytes(metadata: dict = None, tile_type: int = 1, min_zoom: int = 0, max_zoom: int = 8, bounds: tuple = (-180.0, -85.0, 180.0, 85.0), compress: bool = True) -> bytes: """A PMTiles version 3 file with a header and metadata, but no tiles.""" raw = json.dumps(metadata if metadata is not None else dict()).encode() if compress: raw = gzip.compress(raw) header = bytearray(127) header[0:7] = b'PMTiles' header[7] = 3 # Root directory (empty), then the metadata. struct.pack_into(' dict: """PMTiles metadata of a vector file with these layers. `geometries` are recorded as tippecanoe does.""" metadata['vector_layers'] = [dict(id=i, fields=dict(name='String'), minzoom=0, maxzoom=8) for i in layer_ids] if geometries: metadata['tilestats'] = dict(layers=[dict(layer=k, geometry=v, count=1) for k, v in geometries.items()]) return metadata @pytest.fixture def make_pmtiles(test_directory) -> Callable[..., Path]: """Create a readable PMTiles file in the media directory. A file is a Protomaps basemap unless `metadata` (or a raster `tile_type`) says otherwise.""" def _(path: str, metadata: dict = None, **kwargs) -> Path: path = test_directory / path path.parent.mkdir(parents=True, exist_ok=True) if metadata is None and kwargs.get('tile_type', 1) == 1: metadata = vector_metadata(*PROTOMAPS_LAYERS, name='Protomaps Basemap', type='baselayer') path.write_bytes(pmtiles_bytes(metadata, **kwargs)) return path return _ @pytest.fixture(autouse=True) def map_export_root(tmp_path, monkeypatch) -> Path: """Exports of the map are kept in a directory of the test, not of the machine.""" from modules.map import export_job root = tmp_path / 'map-export' monkeypatch.setattr(export_job, 'EXPORT_ROOT', root) return root @pytest.fixture def test_nuclear_config(test_directory, monkeypatch): """The map's nuclear targets, kept in the test's media directory.""" from modules.map import nuclear (test_directory / 'config').mkdir(exist_ok=True) config = nuclear.MapNuclearConfig() config.initialize() monkeypatch.setattr(nuclear, 'TEST_MAP_NUCLEAR_CONFIG', config) yield config @pytest.fixture def make_species_pack(test_directory) -> Callable: """Write a species pack to the species directory, the way the build script lays one out. `species` is a list of dicts: taxon_id, name, common_name, wiki_title, grp, and `points`, the (lat, lon) or (lat, lon, month) of each observation (all precise). `months=False` writes a pack from before months were kept.""" def _(region: str, species: list, version: str = '20261123', months: bool = True) -> Path: path = lib.get_species_directory() / pack_name(region, version) with sqlite3.connect(path) as db: db.executescript(SCHEMA) db.executemany('INSERT INTO meta (key, value) VALUES (?, ?)', [('region', region), ('version', version)]) for i in species: points = [(*p, 0)[:3] for p in i['points']] lats, lons = [p[0] for p in points], [p[1] for p in points] monthly = [0] * 12 for *_, month in points: if month: monthly[month - 1] += 1 db.execute('INSERT INTO species VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)', ( i['taxon_id'], i['name'], i.get('common_name'), i.get('wiki_title'), i.get('grp', 0), len(points), min(lats), min(lons), max(lats), max(lons), encode_cells(cell_id(p[0], p[1], LOW_GRID) for p in points), encode_cells(cell_id(p[0], p[1], HIGH_GRID) for p in points), encode_months(monthly), i.get('other_names'), )) counts, masks = Counter(), Counter() for lat, lon, month in points: cell = cell_id(lat, lon, LOOKUP_GRID) counts[cell] += 1 masks[cell] |= month_bit(month) db.executemany('INSERT INTO cell_species VALUES (?, ?, ?, ?)', [(cell, i['taxon_id'], count, masks[cell]) for cell, count in counts.items()]) db.execute("INSERT INTO species_fts(species_fts) VALUES ('rebuild')") if not months: # Before months were kept there were no other names either. db.execute('DROP TABLE species_fts') db.execute("CREATE VIRTUAL TABLE species_fts USING fts5(name, common_name, content='species'," " content_rowid='taxon_id')") db.execute("INSERT INTO species_fts(species_fts) VALUES ('rebuild')") db.execute('ALTER TABLE species DROP COLUMN other_names') db.execute('ALTER TABLE species DROP COLUMN months') db.execute('ALTER TABLE cell_species DROP COLUMN months') return path return _