From a429db441e5dd8d58a8dce71e24230aec2ed624b Mon Sep 17 00:00:00 2001 From: lrnselfreliance <33263708+lrnselfreliance@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:24:01 -0700 Subject: [PATCH] iNaturalist species map (#1033) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add iNaturalist species pack build script Builds one `inat--.species.db` per map region from the iNaturalist research-grade GBIF export (CC BY-NC 4.0). Each species row links to its English Wikipedia article (via Wikidata) so Kiwix supplies the details, and carries its range as compressed per-cell dots (0.1° from all observations, 0.02° from precise ones only). A cell lookup table answers "what lives near here", and FTS5 searches names. Packs, meta4 files and a signed manifest are written for upload to the CDN. modules/map/species.py holds the pack format shared with WROLPi. Co-Authored-By: Claude Opus 5.5 * Download iNaturalist species packs by subscription A species subscription is one recurring (30 day) `species_catalog` Download of the signed species manifest, saved in the downloads config like map subscriptions. Each run creates a `species_pack` Download per subscribed region, which aria2c checks against the manifest's signed hash before the pack is moved into map/inat/; only then are the region's older packs deleted. The map's Manage tab gets a Species section: subscribe, unsubscribe (the pack is kept), and delete a downloaded pack. Pack file names are built and parsed in modules/map/species.py, shared with the build script. Co-Authored-By: Claude Opus 5.5 * Search the downloaded species packs, with their range and Wikipedia article - GET /api/map/species: search by name (every word a prefix), and/or what was seen within radius_km of lat/lon. Nearby species come first, most seen nearby first; an exact name match comes first of all. - GET /api/map/species/: details, and the species' article in the best English Wikipedia Zim (maxi, nopic, mini; newest), found by the libzim worker's new `find` op, else a search link for its name. - GET /api/map/species//range?grid=low|high: GeoJSON dots. Packs are read directly and read-only; a species in several regions is merged (counts summed, bbox and range unioned). Co-Authored-By: Claude Opus 5.5 * Use iNaturalist's common names in the species packs Wikidata's P1843 holds many English names per species and the one we got was arbitrary ("black-tailed deer" for mule deer, "Greek milkweed" for showy milkweed). The build now reads iNaturalist's taxonomy archive (VernacularNames-english.csv) and takes each species' first name not tied to a place ("quaking aspen", not Canada's "trembling aspen"), else its first name; Wikidata's is only a fallback. In us-west this names 30,642 of 52,015 species, up from 17,805. --version publishes a rebuild of the same observations under a new version, and --reuse-split rebuilds from the last build's region work files instead of reading the observations again. Co-Authored-By: Claude Opus 5.5 * Species panel on the map: what lives here, and a species' range as dots A 🌿 button opens the Species panel (it and nuclear mode share the panel's place, so one closes the other). It lists the species seen within 10/30/100 km of the middle of the map, following the map as it moves, with how often each was seen nearby; it can search by name and filter by group. Choosing a species draws its range: the 0.1° grid of every observation below zoom 7, the 0.02° grid of precise ones from it (or the 0.1° grid at every zoom when there is none), put back after a style change and erased on Back or close. "Zoom to range" fits its bbox, and its Wikipedia article opens from the best Wikipedia Zim (or a search, or where to download Wikipedia). The panel is at most half the screen tall and clears the map's buttons, so the range stays in sight on a phone. Co-Authored-By: Claude Opus 5.5 * Species tests: neutral Oregon fixtures Bend, Prineville (~47 km apart) and Crater Lake replace the earlier fixture points; the cases are unchanged. Co-Authored-By: Claude Opus 5.5 * Species: zoom to a range without its outliers, beside the panel "Zoom to range" fitted the species' bbox, so a few planted trees far away (giant sequoias in Seattle and Los Angeles) zoomed the map out to the whole coast, and the panel covered part of the range. It now fits the range's dots less the outermost 2% on each side (from 20 dots), and pads by the panel: beside it on a wide map, above it on a narrow one. The outlying dots are still drawn. Co-Authored-By: Claude Opus 5.5 * Help: the Species page Co-Authored-By: Claude Opus 5.5 * Species: months seen, a popup on each dot, and review fixes Months: packs now keep how many observations each species had in each month, and the months it was seen in each ~11 km square (a bit per month). The species details show a bar per month; clicking a range dot opens a popup of that square: how often the species was seen there and in which months, and the other species seen there, any of which can be opened (GET /api/map/species/here). Packs without months still work. Review fixes: - Common names: the archive's first listed English name, not the first without a place (which was an alias: "Robin Redbreast", "Wanderer", "Duck Hawk"); every other English name is kept in `other_names` and is searchable, and shown as "Also called". - Only the newest pack of each region is read, so a version left beside a newer one is not counted twice; a finished download also removes older versions. A name one pack lacks is taken from another. - No bbox for a species whose packs are on both sides of the antimeridian; Zoom to range takes the short way across it, drops at least one outlier on each side from 20 dots, waits for the dots, and measures the panel against the map. - Wikipedia Zims are tried one at a time, best first, all of Wikipedia before a selection of it. - A failed search keeps the last list and says so; failed details no longer suggest downloading Wikipedia, and the range is still drawn. - Species range dots are left out of PDF exports. - Unsubscribe (species and map regions) is red again; the Manage table refreshes until a subscribed pack arrives; a refused Delete fails. Co-Authored-By: Claude Opus 5.5 * Species: less work for the WROLPi per search and range Measured on a Pi 4 with the us-west pack, the panel's search (species within 30 km, asked each time the map stops moving) took 146 ms, and a wide species' fine range 280 ms and 2.7 MB of GeoJSON. - Search ranks the matching species from bare (taxon, names, counts) tuples and reads only the species it returns in full: 30 km 87 ms, 100 km 445 -> 277 ms, a broad name prefix 480 -> 200 ms. - The range is sent as its sorted cells, as differences, and the browser makes the dots: the red-tailed hawk's fine range 34 ms and 95 KB, its coarse range 87 -> 10 ms and 939 -> 29 KB. A dot's popup asks for the species clicked, and always shows how often and in which months it was seen in that square, not only when it is among the most seen there. The popup is drawn over the Species panel. Co-Authored-By: Claude Opus 5.5 * Species: a planet pack, every region in one file `--planet` merges every region's pack into `inat-planet-` (counts and months summed, ranges, bboxes and lookup cells joined, the first name a pack has), and adds it to the manifest; `--merge-only` makes it from the region packs of a finished build. An observation exactly on a shared region edge is in both regions' packs, so the planet counts it twice; that is rare enough to leave. On the device the planet is a choice in the Species catalog, and when its pack is downloaded it is the only one read, so the regions it holds are not counted again. Co-Authored-By: Claude Opus 5.5 * Species: sizes of the 20261129 packs; no hang re-signing a manifest The packs grew about 15% with months and other names; the planet pack is 993 MB. Re-signing a manifest (--planet --merge-only) hung: gpg asks before replacing an existing signature and nothing could answer. The old signature is now removed first. Help: a dot's popup, months, other names, and the planet. Co-Authored-By: Claude Opus 5.5 * Species: the planet from each observation once; overlaps counted once Map regions overlap, some widely (southern Arizona is in us-west and mexico, north Africa in five regions): about 42M of 173M observations are in two or more. Merging the region packs counted those twice, so the planet is now built like a region from every observation once. Its work is split into 8 files by species and built a file at a time (all at once its sets would need ~25 GB). `planet` is a region for --regions, built by default, and the manifest lists every pack of the version in the folder, so a planet-only run keeps the regions. The merge and its flags are gone. On a device with overlapping region packs, a square both hold was counted twice in "near" and in a dot's popup; each square now counts the larger of the packs' counts. Species totals still add up across overlapping packs; the planet pack is exact. Co-Authored-By: Claude Opus 5.5 * Help: Species screenshots from the planet pack Co-Authored-By: Claude Opus 5.5 * Species: Zoom to range fits the cluster of dots nearest the view On the planet pack, giant sequoia (planted in Britain, New Zealand and elsewhere) zoomed out to the whole world: far more than the 2% of dots the zoom left out were planted away from its groves. Dots in touching 2° squares (about 220 km, also across the antimeridian) are now one cluster, and Zoom to range fits the cluster nearest the middle of the map: California from Yosemite, the planted trees from London. A range spread across a continent is one cluster. Help updated. Co-Authored-By: Claude Opus 5.5 * Species: Planet is listed first on the Manage tab Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- app/src/App.css | 5 + app/src/api.js | 85 +++ app/src/components/Map.js | 9 +- app/src/components/MapPreview.test.js | 2 + app/src/components/MapSpecies.js | 144 +++++ app/src/components/MapSpecies.test.js | 149 ++++++ app/src/components/MapSpeciesPanel.js | 533 +++++++++++++++++++ app/src/components/MapSpeciesPanel.test.js | 424 +++++++++++++++ app/src/components/MapTables.test.js | 5 + app/src/components/MapViewer.js | 53 +- docker/help/wrolpi-help | 2 +- modules/map/api.py | 120 ++++- modules/map/catalog.py | 41 ++ modules/map/conftest.py | 55 ++ modules/map/downloader.py | 167 ++++++ modules/map/lib.py | 103 +++- modules/map/schema.py | 5 + modules/map/species.py | 167 ++++++ modules/map/species_search.py | 417 +++++++++++++++ modules/map/test/test_build_inat_regions.py | 455 ++++++++++++++++ modules/map/test/test_species.py | 51 ++ modules/map/test/test_species_download.py | 357 +++++++++++++ modules/map/test/test_species_search.py | 404 ++++++++++++++ modules/zim/libzim_worker.py | 13 + wrolpi/scripts/build_inat_regions.py | 554 ++++++++++++++++++++ 25 files changed, 4312 insertions(+), 8 deletions(-) create mode 100644 app/src/components/MapSpecies.js create mode 100644 app/src/components/MapSpecies.test.js create mode 100644 app/src/components/MapSpeciesPanel.js create mode 100644 app/src/components/MapSpeciesPanel.test.js create mode 100644 modules/map/species.py create mode 100644 modules/map/species_search.py create mode 100644 modules/map/test/test_build_inat_regions.py create mode 100644 modules/map/test/test_species.py create mode 100644 modules/map/test/test_species_download.py create mode 100644 modules/map/test/test_species_search.py create mode 100644 wrolpi/scripts/build_inat_regions.py diff --git a/app/src/App.css b/app/src/App.css index 0286fa80..5af4c9e4 100644 --- a/app/src/App.css +++ b/app/src/App.css @@ -840,6 +840,11 @@ tr.drag-deselecting td { } /* Map popups (POI details and pins) follow the active theme's tokens. */ +/* A species dot's popup is drawn over the Species panel (z-index 1002) it was opened from. */ +.maplibregl-popup.wrolpi-species-popup { + z-index: 1003; +} + /* Scoped under .maplibregl-popup to outrank maplibre-gl.css, which loads after this file. */ .maplibregl-popup .maplibregl-popup-content { background: var(--panel); diff --git a/app/src/api.js b/app/src/api.js index ef773bcf..176a8064 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -1712,6 +1712,91 @@ export async function mapUnsubscribe(region) { } } +// The species pack catalog, subscriptions, and downloaded packs: {catalog, subscriptions, files}, or undefined. +export async function fetchSpeciesSubscriptions() { + const response = await apiGet(`${API_URI}/map/species/subscribe`); + if (response.ok) { + return await response.json(); + } else { + const message = await getErrorMessage(response, 'Could not get species subscriptions'); + toast({type: 'error', title: 'Species Error', description: message, time: 5000}); + } +} + +export async function speciesSubscribe(region) { + const response = await apiPost(`${API_URI}/map/species/subscribe`, {region}); + if (!response.ok) { + const message = await getErrorMessage(response, 'Could not subscribe to species'); + toast({type: 'error', title: 'Species Error', description: message, time: 5000}); + } +} + +export async function speciesUnsubscribe(region) { + const response = await apiDelete(`${API_URI}/map/species/subscribe/${encodeURIComponent(region)}`); + if (!response.ok) { + const message = await getErrorMessage(response, 'Could not unsubscribe from species'); + toast({type: 'error', title: 'Species Error', description: message, time: 5000}); + } +} + +// GET a species endpoint: its JSON, or undefined when it failed (a response that was not OK, or no response at +// all), after an error was shown. +async function getSpeciesJson(url, failure) { + try { + const response = await apiGet(url); + if (response.ok) { + return await response.json(); + } + const message = await getErrorMessage(response, failure); + toast({type: 'error', title: 'Species Error', description: message, time: 5000}); + } catch (e) { + console.error(e); + toast({type: 'error', title: 'Species Error', description: failure, time: 5000}); + } +} + +// Search the downloaded species: {q, lat, lon, radius_km, group, limit} (any may be omitted). +// Returns {species, packs, groups}, or undefined (an error was shown). +export async function searchSpecies(params) { + const query = new URLSearchParams(); + Object.entries(params).forEach(([key, value]) => { + if (value !== null && value !== undefined && value !== '') query.set(key, value); + }); + return await getSpeciesJson(`${API_URI}/map/species?${query}`, 'Could not search species'); +} + +// A species' details and its Wikipedia article: {taxon_id, name, ..., wikipedia}, or undefined. +export async function getSpecies(taxonId) { + return await getSpeciesJson(`${API_URI}/map/species/${encodeURIComponent(taxonId)}`, + 'Could not get the species'); +} + +// What was seen in the ~11 km square of a point: {bbox, species_count, species: [{..., here_count, here_months}]}. +// `taxonId`: the species clicked, returned as `taxon` however few times it was seen there. +export async function getSpeciesHere(lat, lon, limit, taxonId) { + const query = new URLSearchParams({lat, lon}); + if (limit) query.set('limit', limit); + if (taxonId) query.set('taxon_id', taxonId); + return await getSpeciesJson(`${API_URI}/map/species/here?${query}`, 'Could not get the species seen here'); +} + +// A species' range: {grid, count, deltas} of grid 'low' (0.1°, every observation) or 'high' (0.02°, precise); see +// rangeGeoJSON. +export async function getSpeciesRange(taxonId, grid) { + return await getSpeciesJson(`${API_URI}/map/species/${encodeURIComponent(taxonId)}/range?grid=${grid}`, + "Could not get the species' range"); +} + +// Throws (after showing why) when the pack was not deleted, so the button that asked shows it failed. +export async function deleteSpeciesFiles(region) { + const response = await apiDelete(`${API_URI}/map/species/files/${encodeURIComponent(region)}`); + if (!response.ok) { + const message = await getErrorMessage(response, 'Could not delete species pack'); + toast({type: 'error', title: 'Species Error', description: message, time: 5000}); + throw new Error(message); + } +} + // Which months of the fallout climatology are kept: {version, months, missing, published}, or null. export async function getFalloutClimatology() { const response = await apiGet(`${API_URI}/map/fallout/climatology`); diff --git a/app/src/components/Map.js b/app/src/components/Map.js index 1bf7ad24..a2b0b105 100644 --- a/app/src/components/Map.js +++ b/app/src/components/Map.js @@ -22,6 +22,7 @@ import {Media, StatusContext} from "../contexts/contexts"; import {MAP_VIEWER_URI} from "./Vars"; import MapViewer from "./MapViewer"; import {WeatherSection} from "./MapWeather"; +import {SpeciesSection} from "./MapSpecies"; import {AddToPlaylistButton} from "./AddToPlaylist"; import {solarCalculatorPath} from "./calculators/solar"; import maplibregl from "maplibre-gl"; @@ -268,9 +269,9 @@ function MapCatalogRow({item, subscribedRegions, fetchData}) { aria-label={`Preview ${name}`} onClick={() => setPreviewOpen(true)} />} + {/* A `color` would replace the danger role's red, so only Subscribe has one. */} + {file && + Delete + } + + + ; +} + +export function SpeciesSection() { + // null = pending, undefined = fetch failed. + const [data, setData] = useState(null); + // Only the newest request may write state: a subscribe refetches while the mount request may be in flight. + const generation = useRef(0); + + const fetchData = async () => { + const gen = ++generation.current; + let fetched; + try { + fetched = await fetchSpeciesSubscriptions(); + } catch (e) { + console.error(e); + } + if (gen === generation.current) { + setData(fetched || undefined); + } + }; + + useEffect(() => { + fetchData(); + }, []); + + // A subscribed region's pack arrives later (see Downloads): asked again until every one is here. + const waiting = !!data && (data.subscriptions || []).some( + (subscription) => !(data.files || []).some((file) => file.region === subscription.region)); + useEffect(() => { + if (!waiting) return; + const timer = setInterval(fetchData, REFRESH_MS); + return () => clearInterval(timer); + }, [waiting]); + + const headers = [ + // The planet is every region in one download; it sorts ahead of the regions. + {key: 'name', text: 'Region', sortBy: i => i.region === PLANET ? '' : i.name.toLowerCase()}, + {key: 'size', text: 'Size', sortBy: i => i.size_estimate || 0}, + {key: 'version', text: 'Downloaded', sortBy: null}, + {key: 'actions', text: '', sortBy: null}, + ]; + + let body; + if (data === undefined) { + body = Could not fetch species subscriptions; + } else { + const subscribed = new Set((data?.subscriptions || []).map(i => i.region)); + const files = Object.fromEntries((data?.files || []).map(i => [i.region, i])); + // A null catalog shows the table's placeholder while it loads. + body = } + rowKey='region' + defaultSortColumn='name' + />; + } + + return <> +
Species
+ {body} + +

Subscribe to a region to download where its plants and animals have been seen, and to keep it + up to date each month. Each species links to its Wikipedia article when you have a Wikipedia Zim.

+

Observations: iNaturalist contributors, iNaturalist Research-grade Observations (doi:10.15468/ab3s5x), + CC BY-NC 4.0. Common names: iNaturalist. Articles: Wikidata.

+
+ ; +} diff --git a/app/src/components/MapSpecies.test.js b/app/src/components/MapSpecies.test.js new file mode 100644 index 00000000..1315afe9 --- /dev/null +++ b/app/src/components/MapSpecies.test.js @@ -0,0 +1,149 @@ +import React from 'react'; +import {act, screen, waitFor, within} from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import {renderWithProviders as render} from '../test-utils'; +import {packDate, REFRESH_MS, SpeciesSection} from './MapSpecies'; + +jest.mock('../api', () => ({ + ...jest.requireActual('../api'), + fetchSpeciesSubscriptions: jest.fn(), + speciesSubscribe: jest.fn(), + speciesUnsubscribe: jest.fn(), + deleteSpeciesFiles: jest.fn(), +})); + +const api = require('../api'); + +const CATALOG = [ + {name: 'United States (West)', region: 'us-west', bbox: '-125.0,24.4,-104.0,49.4', size_estimate: 78000000}, + {name: 'Alaska', region: 'us-alaska', bbox: '-180.0,51.0,-129.0,71.5', size_estimate: 5000000}, +]; + +const rowOf = async (name) => (await screen.findByText(name)).closest('tr'); + +beforeEach(() => { + jest.clearAllMocks(); + api.fetchSpeciesSubscriptions.mockResolvedValue({ + catalog: CATALOG, + subscriptions: [{region: 'us-west'}], + files: [{name: 'inat-us-west-20261123.species.db', region: 'us-west', version: '20261123', size: 77893632}], + }); + api.speciesSubscribe.mockResolvedValue(undefined); + api.speciesUnsubscribe.mockResolvedValue(undefined); + api.deleteSpeciesFiles.mockResolvedValue(undefined); +}); + +test('packDate', () => { + expect(packDate('20261123')).toBe('2026-11-23'); + expect(packDate(undefined)).toBe(undefined); +}); + +test('a downloaded pack shows its size and date; others show an estimate', async () => { + render(); + + const west = await rowOf('United States (West)'); + expect(within(west).getByText('2026-11-23')).toBeInTheDocument(); + expect(within(west).getByText('Unsubscribe')).toBeInTheDocument(); + expect(within(west).getByText('Delete')).toBeInTheDocument(); + expect(within(west).queryByText(/^~/)).not.toBeInTheDocument(); + + const alaska = await rowOf('Alaska'); + expect(within(alaska).getByText(/^~/)).toBeInTheDocument(); + expect(within(alaska).getByText('Subscribe')).toBeInTheDocument(); + expect(within(alaska).queryByText('Delete')).not.toBeInTheDocument(); +}); + +test('subscribing and unsubscribing refetch the subscriptions', async () => { + render(); + + await userEvent.click(within(await rowOf('Alaska')).getByText('Subscribe')); + await waitFor(() => expect(api.speciesSubscribe).toHaveBeenCalledWith('us-alaska')); + await waitFor(() => expect(api.fetchSpeciesSubscriptions).toHaveBeenCalledTimes(2)); + + await userEvent.click(within(await rowOf('United States (West)')).getByText('Unsubscribe')); + await waitFor(() => expect(api.speciesUnsubscribe).toHaveBeenCalledWith('us-west')); + await waitFor(() => expect(api.fetchSpeciesSubscriptions).toHaveBeenCalledTimes(3)); +}); + +test('deleting a pack asks first', async () => { + render(); + + await userEvent.click(within(await rowOf('United States (West)')).getByText('Delete')); + expect(api.deleteSpeciesFiles).not.toHaveBeenCalled(); + expect(await screen.findByText('Delete the species of United States (West)?')).toBeInTheDocument(); + + await userEvent.click(within(await screen.findByRole('dialog')).getByRole('button', {name: 'Delete'})); + await waitFor(() => expect(api.deleteSpeciesFiles).toHaveBeenCalledWith('us-west')); +}); + +test('pending: shows a placeholder', () => { + api.fetchSpeciesSubscriptions.mockReturnValue(new Promise(() => { + })); + const {container} = render(); + expect(container.querySelector('.wrolpi-placeholder')).toBeInTheDocument(); +}); + +test('a failed fetch is an error, not an empty table', async () => { + api.fetchSpeciesSubscriptions.mockResolvedValue(undefined); + render(); + expect(await screen.findByText('Could not fetch species subscriptions')).toBeInTheDocument(); +}); + +test('Unsubscribe is a danger button; Subscribe is not', async () => { + render(); + const unsubscribe = within(await rowOf('United States (West)')).getByRole('button', {name: 'Unsubscribe'}); + const subscribe = within(await rowOf('Alaska')).getByRole('button', {name: 'Subscribe'}); + expect(unsubscribe.className).toContain('wrolpi-button-danger'); + // The danger role's red is not replaced by a color. + expect(unsubscribe.getAttribute('style') || '').not.toContain('violet'); + expect(subscribe.className).not.toContain('wrolpi-button-danger'); +}); + +test('asked again while a subscribed region has no pack yet', async () => { + jest.useFakeTimers(); + try { + api.fetchSpeciesSubscriptions.mockResolvedValue({ + catalog: CATALOG, subscriptions: [{region: 'us-alaska'}], files: [], + }); + render(); + await rowOf('Alaska'); + const calls = api.fetchSpeciesSubscriptions.mock.calls.length; + await act(async () => jest.advanceTimersByTime(REFRESH_MS)); + expect(api.fetchSpeciesSubscriptions.mock.calls.length).toBe(calls + 1); + + // Once the pack is here, it stops. + api.fetchSpeciesSubscriptions.mockResolvedValue({ + catalog: CATALOG, subscriptions: [{region: 'us-alaska'}], + files: [{name: 'inat-us-alaska-20261123.species.db', region: 'us-alaska', version: '20261123', size: 1}], + }); + await act(async () => jest.advanceTimersByTime(REFRESH_MS)); + const settled = api.fetchSpeciesSubscriptions.mock.calls.length; + await act(async () => jest.advanceTimersByTime(REFRESH_MS * 3)); + expect(api.fetchSpeciesSubscriptions.mock.calls.length).toBe(settled); + } finally { + jest.useRealTimers(); + } +}); + +test('a refused delete still refreshes the table', async () => { + api.deleteSpeciesFiles.mockRejectedValue(new Error('WROL Mode is enabled')); + render(); + await userEvent.click(within(await rowOf('United States (West)')).getByText('Delete')); + await userEvent.click(within(await screen.findByRole('dialog')).getByRole('button', {name: 'Delete'})); + await waitFor(() => expect(api.deleteSpeciesFiles).toHaveBeenCalled()); + await waitFor(() => expect(api.fetchSpeciesSubscriptions).toHaveBeenCalledTimes(2)); +}); + +test('the planet is listed first, before the regions by name', async () => { + api.fetchSpeciesSubscriptions.mockResolvedValue({ + catalog: [...CATALOG, {name: 'Planet (every region)', region: 'planet', bbox: '-180.0,-90.0,180.0,90.0', + size_estimate: 993000000}], + subscriptions: [], + files: [], + }); + render(); + + await screen.findByText('Planet (every region)'); + const names = screen.getAllByRole('row').slice(1).map(row => within(row).getAllByRole('cell')[0].textContent); + expect(names).toEqual(['Planet (every region)', 'Alaska', 'United States (West)']); +}); diff --git a/app/src/components/MapSpeciesPanel.js b/app/src/components/MapSpeciesPanel.js new file mode 100644 index 00000000..4c78658e --- /dev/null +++ b/app/src/components/MapSpeciesPanel.js @@ -0,0 +1,533 @@ +import React, {useCallback, useEffect, useRef, useState} from "react"; +import {createRoot} from "react-dom/client"; +import {Link} from "react-router"; +import maplibregl from "maplibre-gl"; +import {getSpecies, getSpeciesHere, getSpeciesRange, searchSpecies} from "../api"; +import {Button, Select, TextInput} from "./ui"; + +// The map's species view: what plants and animals have been seen around the middle of the map (or are named +// what was searched), from the downloaded iNaturalist packs; and a species' range, drawn as dots. + +// The range is of the app, not of the map: an exported map (PDF) leaves out what starts with this. +export const SPECIES_LAYER_PREFIX = "species-range-"; +export const RANGE_SOURCES = {low: `${SPECIES_LAYER_PREFIX}low`, high: `${SPECIES_LAYER_PREFIX}high`}; +export const RANGE_LAYERS = {low: `${SPECIES_LAYER_PREFIX}low`, high: `${SPECIES_LAYER_PREFIX}high`}; +// Below this zoom the range is the 0.1° grid of every observation; from it, the 0.02° grid of the precise ones. +export const HIGH_ZOOM = 7; +// Map data, not app chrome: one strong color that reads on every basemap. +const DOT_COLOR = "#d9480f"; +export const RADII = [10, 30, 100]; +const DEFAULT_RADIUS = 30; +// The list follows the map: it is asked again this long after the map stops moving. +const MOVE_DELAY_MS = 400; +// The panel floats over the map (z-index 1002); its dropdowns open above it. +const DROPDOWN = {zIndex: 1100}; + +const number = (n) => (n || 0).toLocaleString(); + +export const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", + "October", "November", "December"]; +// How many other species a dot's popup lists. +const HERE_LIMIT = 8; + +// How often a species was seen in each month of the year: a bar per month, January first. +export function MonthsBar({counts}) { + const most = Math.max(...(counts || [])); + if (!counts || most <= 0) return null; + return
+ {counts.map((count, i) =>
+
+
+
+
{MONTHS[i][0]}
+
)} +
; +} + +// The months (1-12) a species was seen in, as the year's letters with those months marked. +export function MonthsSeen({months}) { + if (!months || months.length === 0) return null; + const seen = new Set(months); + return
MONTHS[m - 1]).join(", ")}`} + style={{display: "flex", gap: "2px"}}> + {MONTHS.map((name, i) => {name[0]})} +
; +} + +// A dot's popup: the species seen in its square (about 11 km), and the others seen there; one of those can be chosen. +export function SpeciesHerePopup({species, here, onSelect}) { + const self = here.taxon || here.species.find((i) => i.taxon_id === species.taxon_id); + const others = here.species.filter((i) => i.taxon_id !== species.taxon_id); + const more = here.species_count - here.species.length; + return
+
{species.common_name || species.name}
+
+ {self ? `Seen ${number(self.here_count)} times in this square (about 11 km).` + : "Seen in this square (about 11 km)."} +
+ {self && } + {others.length > 0 && <> +
Also seen here
+ {others.map((i) => )} + {more > 0 &&
+ and {number(more)} more species +
} + } +
; +} + +// A range as the API sends it ({grid, deltas}: the sorted cells of a grid as differences, cells numbered row by row +// from the south-west corner of the world) as GeoJSON points, one at the middle of each cell. The browser does this +// so the WROLPi does not have to. +export function rangeGeoJSON(range) { + const features = []; + if (range?.deltas) { + const grid = range.grid; + const columns = Math.round(360 / grid); + let cell = 0; + for (const delta of range.deltas) { + cell += delta; + const row = Math.floor(cell / columns); + const lat = row * grid - 90 + grid / 2; + const lon = (cell - row * columns) * grid - 180 + grid / 2; + features.push({type: "Feature", properties: {}, + geometry: {type: "Point", coordinates: [Math.round(lon * 1e4) / 1e4, Math.round(lat * 1e4) / 1e4]}}); + } + } + return {type: "FeatureCollection", features}; +} + +// The circle layers of a range. A species with no precise observation has no high grid: its low grid is drawn at +// every zoom. +export function rangeLayers(hasHigh) { + const paint = { + "circle-color": DOT_COLOR, + "circle-opacity": 0.8, + "circle-stroke-color": "#ffffff", + "circle-stroke-width": 0.5, + "circle-radius": ["interpolate", ["linear"], ["zoom"], 0, 1.5, 4, 2.5, 7, 4, 12, 6], + }; + const low = {id: RANGE_LAYERS.low, type: "circle", source: RANGE_SOURCES.low, paint}; + if (!hasHigh) return [low]; + return [ + {...low, maxzoom: HIGH_ZOOM}, + {id: RANGE_LAYERS.high, type: "circle", source: RANGE_SOURCES.high, minzoom: HIGH_ZOOM, paint}, + ]; +} + +// "Zoom to range" fits the cluster of dots nearest the middle of the map: dots in touching squares this many degrees +// across (about 220 km) are one cluster. A species planted far from its home (giant sequoias in Britain) is drawn +// everywhere, but zooms to the place being looked at; one spread across a continent is one cluster. +const CLUSTER_DEGREES = 2; +const CLUSTER_COLUMNS = 360 / CLUSTER_DEGREES; +// The least room (pixels) "Zoom to range" leaves for the range beside or above the panel. +const MIN_FIT = 80; + +// The dots' clusters: groups of [lon, lat] whose CLUSTER_DEGREES squares touch, also across the antimeridian. +export function rangeClusters(points) { + const squares = new Map(); + for (const point of points) { + const column = Math.floor((point[0] + 180) / CLUSTER_DEGREES) % CLUSTER_COLUMNS; + const row = Math.floor((point[1] + 90) / CLUSTER_DEGREES); + const key = `${row},${column}`; + if (!squares.has(key)) squares.set(key, {row, column, points: []}); + squares.get(key).points.push(point); + } + const clusters = []; + const seen = new Set(); + for (const [key, first] of squares) { + if (seen.has(key)) continue; + seen.add(key); + const cluster = []; + const stack = [first]; + while (stack.length) { + const square = stack.pop(); + cluster.push(...square.points); + for (let dRow = -1; dRow <= 1; dRow++) { + for (let dColumn = -1; dColumn <= 1; dColumn++) { + const column = (square.column + dColumn + CLUSTER_COLUMNS) % CLUSTER_COLUMNS; + const next = `${square.row + dRow},${column}`; + if (squares.has(next) && !seen.has(next)) { + seen.add(next); + stack.push(squares.get(next)); + } + } + } + } + clusters.push(cluster); + } + return clusters; +} + +// About how far apart two [lon, lat] are, in degrees of latitude; enough to say which is nearer. +function distance([lon1, lat1], [lon2, lat2]) { + const dLon = Math.abs(lon1 - lon2) % 360; + const across = Math.min(dLon, 360 - dLon) * Math.cos(((lat1 + lat2) / 2) * Math.PI / 180); + return Math.hypot(across, lat1 - lat2); +} + +// [[west, south], [east, north]] of points, the short way around: a span across the antimeridian has its east past +// 180 (west 170, east 190), which MapLibre fits as one span. +function pointsBounds(points) { + const lats = points.map((p) => p[1]).sort((a, b) => a - b); + const lons = points.map((p) => p[0]).sort((a, b) => a - b); + // The span is the circle of longitudes less its largest empty gap; the gap across ±180 is the usual one. + let start = 0; + let largest = lons[0] + 360 - lons[lons.length - 1]; + for (let i = 1; i < lons.length; i++) { + if (lons[i] - lons[i - 1] > largest) { + largest = lons[i] - lons[i - 1]; + start = i; + } + } + const arc = [...lons.slice(start), ...lons.slice(0, start).map((lon) => lon + 360)]; + return [[arc[0], lats[0]], [arc[arc.length - 1], lats[lats.length - 1]]]; +} + +// The bounds of the cluster of a range's dots nearest `center` ([lon, lat]); null when it has no dots. +export function rangeBounds(features, center) { + const points = (features || []).map((f) => f.geometry.coordinates); + if (points.length === 0) return null; + let nearest = null; + let nearestDistance = Infinity; + for (const cluster of rangeClusters(points)) { + const away = center ? Math.min(...cluster.map((point) => distance(point, center))) : 0; + if (away < nearestDistance) { + nearest = cluster; + nearestDistance = away; + } + } + return pointsBounds(nearest); +} + +function eraseRange(map) { + try { + Object.values(RANGE_LAYERS).forEach((id) => map.getLayer(id) && map.removeLayer(id)); + Object.values(RANGE_SOURCES).forEach((id) => map.getSource(id) && map.removeSource(id)); + } catch (e) { + // The map is gone. + } +} + +function drawRange(map, range) { + eraseRange(map); + if (!range) return; + const hasHigh = range.high?.features?.length > 0; + map.addSource(RANGE_SOURCES.low, {type: "geojson", data: range.low}); + if (hasHigh) map.addSource(RANGE_SOURCES.high, {type: "geojson", data: range.high}); + rangeLayers(hasHigh).forEach((layer) => map.addLayer(layer)); +} + +// How many times a species was seen near the middle of the map. +export function NearBadge({species}) { + if (species.near_count === null || species.near_count === undefined) return null; + const near = species.near_count > 0; + return {near ? `${number(species.near_count)} nearby` : "Not nearby"}; +} + +function SpeciesName({species}) { + return <> +
{species.common_name || species.name}
+ {species.common_name &&
+ {species.name} +
} + ; +} + +function SpeciesRow({species, onSelect}) { + const near = species.near_count === null || species.near_count === undefined || species.near_count > 0; + return ; +} + +// Where to read about a species: its Wikipedia article, a search, or a suggestion to download Wikipedia. +export function WikipediaLink({wikipedia, name}) { + if (wikipedia === undefined) return null; + if (wikipedia === null) { + return
+ Download Wikipedia to read about {name}. +
; + } + if (wikipedia.zim_id) { + return Read in Wikipedia; + } + return Search for {name}; +} + +// The regions a species was counted in, to say so; the planet pack is every region and is not named. +export const regionNames = (regions) => (regions || []).filter((i) => i !== "planet").join(", "); + +function SpeciesDetails({map, species, onBack, onSelect, panelRef}) { + // undefined while loading, null when it could not be had (the request said why). + const [details, setDetails] = useState(undefined); + const [range, setRange] = useState(undefined); + const rangeRef = useRef(null); + + useEffect(() => { + let current = true; + // Each is used as it comes: a range is drawn even if the details failed. + getSpecies(species.taxon_id).then((found) => current && setDetails(found || null)); + Promise.all([getSpeciesRange(species.taxon_id, "low"), getSpeciesRange(species.taxon_id, "high")]) + .then(([low, high]) => current + && setRange(low ? {low: rangeGeoJSON(low), high: rangeGeoJSON(high)} : null)); + return () => { + current = false; + }; + }, [species.taxon_id]); + + // The range is a layer of the map's style, which a change of style removes: it is put back when the style has + // loaded, and erased when the species is put away. + useEffect(() => { + rangeRef.current = range; + if (map && range) drawRange(map, range); + }, [map, range]); + useEffect(() => { + if (!map) return; + const restore = () => drawRange(map, rangeRef.current); + map.on("style.load", restore); + return () => { + map.off("style.load", restore); + eraseRange(map); + }; + }, [map]); + + // Clicking a dot opens a popup of what was seen in its square. + useEffect(() => { + if (!map) return; + let popup = null; + let root = null; + let clicked = 0; + const close = () => { + if (popup) popup.remove(); + popup = null; + }; + const onClick = async (e) => { + const feature = e.features?.[0]; + if (!feature) return; + const [lon, lat] = feature.geometry.coordinates; + const click = ++clicked; + const here = await getSpeciesHere(lat, lon, HERE_LIMIT + 1, species.taxon_id); + if (!here || click !== clicked) return; + close(); + const node = document.createElement("div"); + root = createRoot(node); + const current = root; + root.render( { + close(); + onSelect(other); + }}/>); + popup = new maplibregl.Popup({offset: 6, maxWidth: "18rem", className: "wrolpi-species-popup"}) + .setLngLat([lon, lat]).setDOMContent(node).addTo(map); + // Unmounted after the popup's own event, not during it. + popup.on("close", () => setTimeout(() => current.unmount())); + }; + const pointer = () => map.getCanvas().style.cursor = "pointer"; + const plain = () => map.getCanvas().style.cursor = ""; + const layers = Object.values(RANGE_LAYERS); + layers.forEach((layer) => { + map.on("click", layer, onClick); + map.on("mouseenter", layer, pointer); + map.on("mouseleave", layer, plain); + }); + return () => { + clicked++; + layers.forEach((layer) => { + map.off("click", layer, onClick); + map.off("mouseenter", layer, pointer); + map.off("mouseleave", layer, plain); + }); + close(); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [map, species.taxon_id]); + + // The range's dots once they are here (the cluster nearest the view); the species' bbox only when it has no dots. + const bbox = details?.bbox || species.bbox; + const canZoom = range !== undefined && (range?.low?.features?.length > 0 || !!bbox); + const zoomToRange = () => { + const center = map.getCenter(); + const bounds = rangeBounds(range?.low?.features, [center.lng, center.lat]) + || (bbox && [[bbox[0], bbox[1]], [bbox[2], bbox[3]]]); + if (!bounds) return; + // Not behind the panel: beside it on a wide map, above it on a narrow one. What is left to fit the range + // in is never less than MIN_FIT pixels across, or MapLibre would not move at all. + const padding = {top: 40, right: 60, bottom: 40, left: 40}; + const panel = panelRef?.current?.getBoundingClientRect(); + const canvas = map.getContainer?.()?.getBoundingClientRect(); + if (panel && canvas) { + if (canvas.width > panel.width * 2) { + padding.left = Math.min(panel.right - canvas.left + 20, canvas.width - padding.right - MIN_FIT); + } else { + padding.bottom = Math.min(canvas.bottom - panel.top + 20, canvas.height - padding.top - MIN_FIT); + } + } + map.fitBounds(bounds, {padding, maxZoom: 12}); + }; + const dots = range ? (range.low?.features?.length || 0) : null; + + return
+
+ + {details?.other_names &&
+ Also called {details.other_names.split("; ").join(", ")}. +
} +
+ {species.group} + +
+ +
+ Seen {number(details?.obs_count ?? species.obs_count)} times + {/* The planet pack is every region: it names none. */} + {regionNames(details?.regions) ? ` in ${regionNames(details.regions)}` : ""}. + {dots !== null && ` ${number(dots)} places on the map.`} +
+
+ + {/* Nothing while loading or when the details failed; null `wikipedia` is "no Wikipedia Zim". */} + {details && } +
+
+ Dots are approximate; iNaturalist blurs some locations on purpose. Click a dot to see what else was seen + there. +
+
; +} + +export default function MapSpeciesPanel({map, onClose}) { + const [q, setQ] = useState(""); + const [group, setGroup] = useState(null); + const [radius, setRadius] = useState(DEFAULT_RADIUS); + // null while the first search is pending. A failed search keeps the last result, and says it failed. + const [result, setResult] = useState(null); + const [failed, setFailed] = useState(false); + const [selected, setSelected] = useState(null); + const generation = useRef(0); + const panelRef = useRef(null); + + const search = useCallback(async () => { + if (!map) return; + const gen = ++generation.current; + const center = map.getCenter(); + const found = await searchSpecies({ + q: q.trim(), group, radius_km: radius, + lat: center.lat.toFixed(4), lon: center.wrap().lng.toFixed(4), + }); + if (gen !== generation.current) return; + setFailed(!found); + if (found) setResult(found); + }, [map, q, group, radius]); + + // Asked again when the search changes (typing waits a moment), and when the map stops moving. + useEffect(() => { + const timer = setTimeout(search, MOVE_DELAY_MS); + return () => clearTimeout(timer); + }, [search]); + useEffect(() => { + if (!map) return; + let timer; + const moved = () => { + clearTimeout(timer); + timer = setTimeout(search, MOVE_DELAY_MS); + }; + map.on("moveend", moved); + return () => { + clearTimeout(timer); + map.off("moveend", moved); + }; + }, [map, search]); + + const groups = [{value: "", label: "All groups"}, + ...(result?.groups || []).map((g) => ({value: String(g.code), label: g.name}))]; + const species = result?.species || []; + + let body; + if (selected) { + body = setSelected(null)} + onSelect={setSelected} panelRef={panelRef}/>; + } else if (result === null && !failed) { + body =
Searching…
; + } else if (result?.packs === 0) { + body =
+ No species have been downloaded. Subscribe to a region's species on the{" "} + Manage page. +
; + } else { + body = <> +
+ setQ(e.currentTarget.value)}/> +
+ ({value: String(r), label: `Within ${r} km`}))} + value={String(radius)} onChange={(value) => setRadius(Number(value))} + allowDeselect={false} comboboxProps={DROPDOWN} aria-label="Radius" style={{flex: 1}}/> +
+
+
+ {failed &&
+ Could not search the species.{result ? " This is the last list found." : ""} +
} + {!result ? null : species.length === 0 + ?
+ {q.trim() ? "No species have that name" : "No species have been seen here"} in the regions + downloaded on the Manage page. +
+ : species.map((s) => )} +
+ ; + } + + return
+
+ Species near the middle of the map +
+ {body} +
+ Observations: iNaturalist contributors, research grade. +
+
; +} diff --git a/app/src/components/MapSpeciesPanel.test.js b/app/src/components/MapSpeciesPanel.test.js new file mode 100644 index 00000000..82b79599 --- /dev/null +++ b/app/src/components/MapSpeciesPanel.test.js @@ -0,0 +1,424 @@ +import React from 'react'; +import {act, screen, waitFor, within} from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import {renderWithProviders as render} from '../test-utils'; +import MapSpeciesPanel, { + HIGH_ZOOM, MonthsBar, MonthsSeen, RANGE_LAYERS, RANGE_SOURCES, rangeBounds, rangeClusters, rangeGeoJSON, + rangeLayers, regionNames, + SPECIES_LAYER_PREFIX, + SpeciesHerePopup, WikipediaLink, +} from './MapSpeciesPanel'; +import {exportStyle} from './mapExport'; + +// The popups opened: their content, where they are, and whether they were closed. +const popups = []; +jest.mock('maplibre-gl', () => ({ + __esModule: true, + default: { + Popup: class { + constructor() { + this.removed = false; + popups.push(this); + } + + setLngLat(lngLat) { + this.lngLat = lngLat; + return this; + } + + setDOMContent(node) { + this.node = node; + return this; + } + + addTo() { + return this; + } + + on() { + return this; + } + + remove() { + this.removed = true; + } + }, + }, +})); + +jest.mock('../api', () => ({ + ...jest.requireActual('../api'), + searchSpecies: jest.fn(), + getSpecies: jest.fn(), + getSpeciesRange: jest.fn(), + getSpeciesHere: jest.fn(), +})); + +const api = require('../api'); + +const GROUPS = [{code: 0, name: 'Other'}, {code: 1, name: 'Plants'}, {code: 3, name: 'Mammals'}]; +const ASPEN = { + taxon_id: 54840, name: 'Populus tremuloides', common_name: 'quaking aspen', wiki_title: 'Populus_tremuloides', + group: 'Plants', group_code: 1, obs_count: 22310, near_count: 585, bbox: [-124.9, 25.9, -104.0, 49.4], + regions: ['us-west'], +}; +const DEER = {...ASPEN, taxon_id: 42220, name: 'Odocoileus hemionus', common_name: 'Mule Deer', group: 'Mammals', + group_code: 3, near_count: 0}; +// A range of `n` neighboring cells of the 0.1° grid, as the API sends it: the first cell, then 1 apart. The first is +// the cell whose south-west corner is 40°N 111°W. +const FIRST_CELL = 1300 * 3600 + 690; +const dots = (n) => ({grid: 0.1, count: n, deltas: n ? [FIRST_CELL, ...Array(n - 1).fill(1)] : []}); + +// The parts of a MapLibre map the panel uses: sources and layers are kept, so drawing can be checked. +function fakeMap() { + const handlers = {}; + const sources = {}, layers = {}; + return { + sources, layers, handlers, + getCenter: () => ({lat: 44.06, lng: -121.31, wrap: () => ({lng: -121.31})}), + // A handler of one layer's events is kept as "event:layer". + on: jest.fn((event, layer, fn) => { + const key = fn ? `${event}:${layer}` : event; + (handlers[key] = handlers[key] || []).push(fn || layer); + }), + off: jest.fn((event, layer, fn) => { + const key = fn ? `${event}:${layer}` : event; + handlers[key] = (handlers[key] || []).filter((i) => i !== (fn || layer)); + }), + getCanvas: () => ({style: {}}), + addSource: jest.fn((id, source) => { + sources[id] = source; + }), + addLayer: jest.fn((layer) => { + layers[layer.id] = layer; + }), + getSource: (id) => sources[id], + getLayer: (id) => layers[id], + removeSource: jest.fn((id) => delete sources[id]), + removeLayer: jest.fn((id) => delete layers[id]), + fitBounds: jest.fn(), + fire: (event, arg) => (handlers[event] || []).forEach((fn) => fn(arg)), + }; +} + +const HERE = { + bbox: [-121.4, 44.0, -121.3, 44.1], species_count: 12, + species: [ + {...DEER, here_count: 40, here_months: [6, 7, 8]}, + {...ASPEN, here_count: 25, here_months: [5, 9, 10]}, + ], +}; + +beforeEach(() => { + jest.clearAllMocks(); + popups.length = 0; + api.getSpeciesHere.mockResolvedValue(HERE); + api.searchSpecies.mockResolvedValue({species: [ASPEN, DEER], packs: 1, groups: GROUPS}); + api.getSpecies.mockResolvedValue({...ASPEN, other_names: 'trembling aspen; popple', wikipedia: {zim_id: 3, path: 'Populus_tremuloides', + title: 'Populus tremuloides', url: '/api/zim/3/entry/Populus_tremuloides'}}); + api.getSpeciesRange.mockImplementation(async (id, grid) => dots(grid === 'low' ? 3 : 5)); +}); + +describe('rangeLayers', () => { + test('the low grid below HIGH_ZOOM, the high grid from it', () => { + const [low, high] = rangeLayers(true); + expect(low).toMatchObject({id: RANGE_LAYERS.low, source: RANGE_SOURCES.low, maxzoom: HIGH_ZOOM}); + expect(high).toMatchObject({id: RANGE_LAYERS.high, source: RANGE_SOURCES.high, minzoom: HIGH_ZOOM}); + }); + + test('without precise observations, the low grid at every zoom', () => { + const layers = rangeLayers(false); + expect(layers).toHaveLength(1); + expect(layers[0].maxzoom).toBeUndefined(); + }); +}); + +test('regionNames: the planet pack is not named', () => { + expect(regionNames(['us-west', 'us-central'])).toBe('us-west, us-central'); + expect(regionNames(['planet'])).toBe(''); + expect(regionNames(undefined)).toBe(''); +}); + +describe('rangeGeoJSON', () => { + test('the middle of each cell, from the differences', () => { + const geojson = rangeGeoJSON(dots(3)); + expect(geojson.features.map((f) => f.geometry.coordinates)).toEqual( + [[-110.95, 40.05], [-110.85, 40.05], [-110.75, 40.05]]); + }); + + test('the corners of the world', () => { + const last = 1800 * 3600 - 1; + expect(rangeGeoJSON({grid: 0.1, deltas: [0, last]}).features.map((f) => f.geometry.coordinates)) + .toEqual([[-179.95, -89.95], [179.95, 89.95]]); + // The high grid has 18,000 columns. + expect(rangeGeoJSON({grid: 0.02, deltas: [18000]}).features[0].geometry.coordinates).toEqual([-179.99, -89.97]); + }); + + test('nothing: no dots', () => { + expect(rangeGeoJSON(undefined).features).toEqual([]); + expect(rangeGeoJSON({grid: 0.1, deltas: []}).features).toEqual([]); + }); +}); + +describe('rangeBounds', () => { + const at = (points) => points.map(([lon, lat]) => ({geometry: {coordinates: [lon, lat]}})); + // Giant sequoia: its groves in the Sierra Nevada, and trees planted in Britain and New Zealand. + const SIERRA = Array.from({length: 40}, (_, i) => [-120.5 + i * 0.05, 36 + i * 0.07]); + const BRITAIN = [[-3.2, 55.9], [-1.5, 53.8], [-0.1, 51.5], [-2.6, 51.4]]; + const NEW_ZEALAND = [[175.3, -37.8], [176.2, -38.1]]; + const SEQUOIA = at([...SIERRA, ...BRITAIN, ...NEW_ZEALAND]); + const YOSEMITE = [-119.59, 37.745]; + const LONDON = [-0.12, 51.5]; + + test('one cluster: all of its dots', () => { + expect(rangeBounds(at([[-120, 37], [-118, 36], [-119, 38]]), YOSEMITE)).toEqual([[-120, 36], [-118, 38]]); + }); + + test('the cluster nearest the middle of the map', () => { + const [[west, south], [east, north]] = rangeBounds(SEQUOIA, YOSEMITE); + expect([west, south]).toEqual([-120.5, 36]); + expect(east).toBeCloseTo(-120.5 + 39 * 0.05); + expect(north).toBeCloseTo(36 + 39 * 0.07); + // From London, the trees planted in Britain, though there are far fewer of them. + expect(rangeBounds(SEQUOIA, LONDON)).toEqual([[-3.2, 51.4], [-0.1, 55.9]]); + // From Auckland, New Zealand's. + expect(rangeBounds(SEQUOIA, [174.76, -36.85])).toEqual([[175.3, -38.1], [176.2, -37.8]]); + }); + + test('dots in touching 2° squares are one cluster; a wider gap is two', () => { + // A chain of dots 1.5° apart across 9°: one cluster. + const chain = Array.from({length: 7}, (_, i) => [-110 + i * 1.5, 40]); + expect(rangeClusters(chain)).toHaveLength(1); + // Two dots 5° apart: two clusters. + expect(rangeClusters([[-110, 40], [-105, 40]])).toHaveLength(2); + }); + + test('across the antimeridian: one cluster, the short way, with its east past 180', () => { + const fiji = [[178.5, -18], [179.5, -17], [-179.5, -16], [-178.5, -17]]; + expect(rangeClusters(fiji)).toHaveLength(1); + expect(rangeBounds(at(fiji), [178, -17])).toEqual([[178.5, -18], [181.5, -16]]); + }); + + test('no dots: none', () => { + expect(rangeBounds([], YOSEMITE)).toBeNull(); + expect(rangeBounds(undefined, YOSEMITE)).toBeNull(); + }); +}); + +describe('months', () => { + test('a bar per month, or nothing without any', () => { + const {rerender} = render(); + expect(screen.getByRole('img', {name: 'Seen by month'})).toBeInTheDocument(); + expect(screen.getByTitle('April: 10')).toBeInTheDocument(); + rerender(); + expect(screen.queryByRole('img', {name: 'Seen by month'})).not.toBeInTheDocument(); + }); + + test('the months seen, named', () => { + render(); + expect(screen.getByLabelText('Seen in May, October')).toBeInTheDocument(); + }); +}); + +describe('SpeciesHerePopup', () => { + test('the species clicked, even when it is not among the most seen there', () => { + const here = {...HERE, species: [HERE.species[0]], taxon: {...ASPEN, here_count: 2, here_months: [6]}}; + render(); + expect(screen.getByText('Seen 2 times in this square (about 11 km).')).toBeInTheDocument(); + expect(screen.getByLabelText('Seen in June')).toBeInTheDocument(); + }); + + test("the species' count in the square, and the others seen there", async () => { + const onSelect = jest.fn(); + render(); + expect(screen.getByText('Seen 25 times in this square (about 11 km).')).toBeInTheDocument(); + expect(screen.getByLabelText('Seen in May, September, October')).toBeInTheDocument(); + expect(screen.getByText('and 10 more species')).toBeInTheDocument(); + await userEvent.click(screen.getByRole('button', {name: /Mule Deer/})); + expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({taxon_id: DEER.taxon_id})); + }); +}); + +describe('WikipediaLink', () => { + test('an article opens in a new tab', () => { + render(); + const link = screen.getByRole('link', {name: 'Read in Wikipedia'}); + expect(link).toHaveAttribute('href', '/api/zim/3/entry/Populus_tremuloides'); + expect(link).toHaveAttribute('target', '_blank'); + }); + + test('no article: a search for the name', () => { + render(); + expect(screen.getByRole('link', {name: 'Search for Populus tremuloides'})) + .toHaveAttribute('href', '/search?q=Populus%20tremuloides'); + }); + + test('no Wikipedia: where to download it', () => { + render(); + expect(screen.getByRole('link', {name: 'Download Wikipedia'})).toHaveAttribute('href', '/zim/manage'); + }); +}); + +describe('MapSpeciesPanel', () => { + test('lists the species near the middle of the map', async () => { + render(); + expect(await screen.findByText('quaking aspen')).toBeInTheDocument(); + expect(screen.getByText('585 nearby')).toBeInTheDocument(); + expect(screen.getByText('Not nearby')).toBeInTheDocument(); + expect(api.searchSpecies).toHaveBeenCalledWith( + {q: '', group: null, radius_km: 30, lat: '44.0600', lon: '-121.3100'}); + }); + + test('nothing downloaded: says where to subscribe', async () => { + api.searchSpecies.mockResolvedValue({species: [], packs: 0, groups: GROUPS}); + render(); + expect(await screen.findByText(/No species have been downloaded/)).toBeInTheDocument(); + expect(screen.getByRole('link', {name: 'Manage'})).toHaveAttribute('href', '/map/manage'); + }); + + test('searching by name asks again', async () => { + render(); + await screen.findByText('quaking aspen'); + await userEvent.type(screen.getByLabelText('Search species'), 'aspen'); + await waitFor(() => expect(api.searchSpecies).toHaveBeenLastCalledWith( + expect.objectContaining({q: 'aspen'}))); + }); + + test('the list follows the map', async () => { + const map = fakeMap(); + render(); + await screen.findByText('quaking aspen'); + const calls = api.searchSpecies.mock.calls.length; + act(() => map.fire('moveend')); + await waitFor(() => expect(api.searchSpecies.mock.calls.length).toBe(calls + 1)); + }); + + test('a species: its range is drawn, put back after a style change, and erased on Back', async () => { + const map = fakeMap(); + render(); + await userEvent.click(await screen.findByRole('button', {name: 'quaking aspen'})); + + expect(await screen.findByText(/3 places on the map/)).toBeInTheDocument(); + expect(screen.getByRole('link', {name: 'Read in Wikipedia'})).toBeInTheDocument(); + expect(screen.getByText('Also called trembling aspen, popple.')).toBeInTheDocument(); + expect(Object.keys(map.layers).sort()).toEqual([RANGE_LAYERS.high, RANGE_LAYERS.low].sort()); + expect(map.sources[RANGE_SOURCES.low].data.features).toHaveLength(3); + expect(map.sources[RANGE_SOURCES.high].data.features).toHaveLength(5); + + // A new style drops the map's layers; the range comes back. + Object.keys(map.layers).forEach((id) => delete map.layers[id]); + Object.keys(map.sources).forEach((id) => delete map.sources[id]); + act(() => map.fire('style.load')); + expect(Object.keys(map.layers)).toHaveLength(2); + + await userEvent.click(screen.getByRole('button', {name: 'Zoom to range'})); + // The bounds of the dots drawn: the middles of the first and last cells. + expect(map.fitBounds).toHaveBeenCalledWith([[-110.95, 40.05], [-110.75, 40.05]], + expect.objectContaining({maxZoom: 12})); + + await userEvent.click(screen.getByRole('button', {name: 'Back'})); + expect(Object.keys(map.layers)).toHaveLength(0); + expect(Object.keys(map.sources)).toHaveLength(0); + expect(await screen.findByText('Mule Deer')).toBeInTheDocument(); + }); + + test('closing the panel erases the range', async () => { + const map = fakeMap(); + const {unmount} = render(); + await userEvent.click(await screen.findByRole('button', {name: 'quaking aspen'})); + await screen.findByText(/3 places on the map/); + unmount(); + expect(Object.keys(map.layers)).toHaveLength(0); + }); +}); + +describe('when requests fail', () => { + test('a failed search keeps the last list and says so', async () => { + const map = fakeMap(); + render(); + await screen.findByText('quaking aspen'); + api.searchSpecies.mockResolvedValue(undefined); + act(() => map.fire('moveend')); + expect(await screen.findByRole('alert')).toHaveTextContent('Could not search the species. This is the last list'); + expect(screen.getByText('quaking aspen')).toBeInTheDocument(); + expect(screen.queryByText(/No species have been seen here/)).not.toBeInTheDocument(); + }); + + test('a failed first search can be tried again', async () => { + api.searchSpecies.mockResolvedValue(undefined); + render(); + expect(await screen.findByRole('alert')).toHaveTextContent('Could not search the species.'); + expect(screen.queryByText('Searching…')).not.toBeInTheDocument(); + api.searchSpecies.mockResolvedValue({species: [ASPEN], packs: 1, groups: GROUPS}); + await userEvent.type(screen.getByLabelText('Search species'), 'a'); + expect(await screen.findByText('quaking aspen')).toBeInTheDocument(); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + }); + + test('failed details: no Wikipedia suggestion, and the range is still drawn', async () => { + api.getSpecies.mockResolvedValue(undefined); + const map = fakeMap(); + render(); + await userEvent.click(await screen.findByRole('button', {name: 'quaking aspen'})); + expect(await screen.findByText(/3 places on the map/)).toBeInTheDocument(); + expect(screen.queryByText('Download Wikipedia')).not.toBeInTheDocument(); + expect(Object.keys(map.layers)).toHaveLength(2); + }); + + test('Zoom to range waits for the dots', async () => { + // Both grids are asked for; neither answers until the test says. + const answers = []; + api.getSpeciesRange.mockImplementation(() => new Promise((resolve) => answers.push(resolve))); + render(); + await userEvent.click(await screen.findByRole('button', {name: 'quaking aspen'})); + expect(screen.getByRole('button', {name: 'Zoom to range'})).toBeDisabled(); + await act(async () => answers.forEach((resolve) => resolve(dots(3)))); + await waitFor(() => expect(screen.getByRole('button', {name: 'Zoom to range'})).toBeEnabled()); + }); +}); + +describe('clicking a dot', () => { + test("opens a popup of what was seen in its square; choosing one shows that species", async () => { + const map = fakeMap(); + render(); + await userEvent.click(await screen.findByRole('button', {name: 'quaking aspen'})); + await screen.findByText(/3 places on the map/); + + const dot = {features: [{geometry: {coordinates: [-121.35, 44.05]}}]}; + await act(async () => map.fire(`click:${RANGE_LAYERS.low}`, dot)); + expect(api.getSpeciesHere).toHaveBeenCalledWith(44.05, -121.35, 9, ASPEN.taxon_id); + expect(popups).toHaveLength(1); + expect(popups[0].lngLat).toEqual([-121.35, 44.05]); + const popup = within(popups[0].node); + // The stand-in Popup never puts its content in the page, so it is read where it was rendered. + await waitFor(() => expect(popups[0].node.textContent).toContain('Seen 25 times in this square (about 11 km).')); + + // Choosing the deer closes the popup and shows the deer. + await act(async () => popup.getByRole('button', {name: /Mule Deer/}).click()); + expect(popups[0].removed).toBe(true); + await waitFor(() => expect(api.getSpecies).toHaveBeenLastCalledWith(DEER.taxon_id)); + }); + + test('Back closes the popup and stops listening', async () => { + const map = fakeMap(); + render(); + await userEvent.click(await screen.findByRole('button', {name: 'quaking aspen'})); + await screen.findByText(/3 places on the map/); + await act(async () => map.fire(`click:${RANGE_LAYERS.high}`, {features: [{geometry: {coordinates: [-121.3, 44]}}]})); + await userEvent.click(screen.getByRole('button', {name: 'Back'})); + expect(popups[0].removed).toBe(true); + expect(map.handlers[`click:${RANGE_LAYERS.low}`]).toHaveLength(0); + }); +}); + +test('an exported map leaves out the range', () => { + const style = { + version: 8, sources: {basemap: {type: 'vector'}, [RANGE_SOURCES.low]: {type: 'geojson', data: rangeGeoJSON(dots(1))}}, + layers: [{id: 'water', type: 'fill', source: 'basemap'}, ...rangeLayers(false)], + }; + const exported = exportStyle(style, [SPECIES_LAYER_PREFIX]); + expect(exported.layers.map((layer) => layer.id)).toEqual(['water']); + expect(Object.keys(exported.sources)).toEqual(['basemap']); +}); diff --git a/app/src/components/MapTables.test.js b/app/src/components/MapTables.test.js index b3e5fedd..abb1e0b3 100644 --- a/app/src/components/MapTables.test.js +++ b/app/src/components/MapTables.test.js @@ -27,6 +27,7 @@ jest.mock('../api', () => ({ ...jest.requireActual('../api'), getMapFiles: jest.fn(), fetchMapSubscriptions: jest.fn(), + fetchSpeciesSubscriptions: jest.fn(), getMapPins: jest.fn(), getMapTargets: jest.fn(), getWeather: jest.fn(), @@ -64,6 +65,10 @@ beforeEach(() => { })); api.getMapFiles.mockResolvedValue({files: []}); api.fetchMapSubscriptions.mockResolvedValue({catalog: [], subscriptions: []}); + // A species catalog with a region, so "No results" can only come from the map's table. + api.fetchSpeciesSubscriptions.mockResolvedValue({ + catalog: [{name: 'Alaska', region: 'us-alaska', size_estimate: 5000000}], subscriptions: [], files: [], + }); api.getMapPins.mockResolvedValue({pins: []}); api.getMapTargets.mockResolvedValue([]); api.deleteMapTarget.mockResolvedValue(true); diff --git a/app/src/components/MapViewer.js b/app/src/components/MapViewer.js index 409fc689..cda1d820 100644 --- a/app/src/components/MapViewer.js +++ b/app/src/components/MapViewer.js @@ -55,6 +55,7 @@ import { import {addMissingOverlayIcon, loadOverlayStyles, OVERLAY_ICONS_SPRITE_ID} from "./mapOverlayStyle"; import MapQuadPicker, {QUAD_LAYER_PREFIX} from "./MapQuadPicker"; import FalloutPanel, {targetsUnsaved, WeaponPicker, withSavedTargets, withWeapon} from "./FalloutPanel"; +import MapSpeciesPanel, {RANGE_LAYERS, SPECIES_LAYER_PREFIX} from "./MapSpeciesPanel"; import {DEFAULT_WEAPON} from "../map-shared/fallout/targets.js"; import {contourInterval, contourThresholds, DEFAULT_TERRAIN_MAX_ZOOM, terrainMaxZoom} from "../map-shared/terrain.js"; import {quadAt} from "./mapQuads"; @@ -100,6 +101,8 @@ maplibregl.addProtocol("pmtiles", protocol.tile); // Planet overview blob — provides global basemap at zoom 0-6. const MAP_OVERVIEW_URL = "/blobs/map-overview.pmtiles"; +// Layers the app draws over the map (a quadrangle being chosen, a species' range), which an exported map leaves out. +const APP_LAYER_PREFIXES = [QUAD_LAYER_PREFIX, SPECIES_LAYER_PREFIX]; // Layers to skip from non-primary sources (they would paint over the primary source's content). const SKIP_SECONDARY = new Set(["background", "earth"]); @@ -748,6 +751,9 @@ export default function MapViewer() { const nuclearButtonRef = useRef(null); // The fallout view (nuclear mode): open or not. const [falloutOpen, setFalloutOpen] = useState(false); + // The species view: open or not. It and nuclear mode share the panel's place: one at a time. + const [speciesOpen, setSpeciesOpen] = useState(false); + const speciesButtonRef = useRef(null); // The saved nuclear targets (map_nuclear.yaml). const [savedTargets, setSavedTargets] = useState([]); const markersRef = useRef([]); @@ -957,6 +963,29 @@ export default function MapViewer() { onRemove: () => {}, }, "top-right"); + // The species seen around here, and their ranges. + const speciesButton = document.createElement("button"); + speciesButton.type = "button"; + speciesButton.title = "Species: plants and animals seen here"; + speciesButton.setAttribute("aria-label", "Species"); + speciesButton.setAttribute("aria-pressed", "false"); + speciesButton.textContent = "🌿"; + speciesButton.style.cssText = pinToggle.style.cssText; + speciesButton.addEventListener("click", () => { + if (destroyed) return; + setSpeciesOpen(open => !open); + }); + speciesButtonRef.current = speciesButton; + map.addControl({ + onAdd: () => { + const container = document.createElement("div"); + container.className = "maplibregl-ctrl maplibregl-ctrl-group"; + container.appendChild(speciesButton); + return container; + }, + onRemove: () => {}, + }, "top-right"); + // Right-click context menu (desktop). map.on("contextmenu", (e) => { if (destroyed) return; @@ -986,6 +1015,9 @@ export default function MapViewer() { layers.length ? map.queryRenderedFeatures(point, {layers}) : []; map.on("click", (e) => { if (destroyed || pickingQuadRef.current || placingTargetRef.current) return; + // A species' range dot has its own popup (the Species panel's). + const speciesLayers = Object.values(RANGE_LAYERS).filter(id => map.getLayer(id)); + if (featuresAt(e.point, speciesLayers).length) return; const html = overlayPopupHtml(featuresAt(e.point, overlayLayerIds())) || poiPopupHtml(featuresAt(e.point, poiLayerIds()), e.lngLat); if (!html) return; @@ -1203,8 +1235,10 @@ export default function MapViewer() { // A map file which is of somewhere else is not drawn. const outside = await sourcesOutside( style, [quad.west, quad.south, quad.east, quad.north], readTileBounds); + // The quadrangle's outline and a species' range are of the app: they are not exported. + const appLayer = id => APP_LAYER_PREFIXES.some(prefix => id.startsWith(prefix)); const groups = exportGroups( - style.layers.filter(layer => !layer.id.startsWith(QUAD_LAYER_PREFIX) && !outside.has(layer.source)), + style.layers.filter(layer => !appLayer(layer.id) && !outside.has(layer.source)), {layerGroups: LAYER_GROUPS, overlayLabels}); if (!groups.length) throw new Error("No layer of the map is turned on"); // How sharp the map may be depends on how many images it is, which is not known until @@ -1218,7 +1252,7 @@ export default function MapViewer() { style, frameFor, groups, - ignoredPrefixes: [QUAD_LAYER_PREFIX], + ignoredPrefixes: APP_LAYER_PREFIXES, readTile: readVectorTile, setup: exportMap => exportMap.on("styleimagemissing", e => addMissingOverlayIcon(exportMap, e.id)), // Stopped between two layers, as soon as the person exporting asks. @@ -1409,8 +1443,19 @@ export default function MapViewer() { // Nuclear mode opens the fallout panel on its targets step; leaving it closes the panel. setFalloutOpen(nuclear); if (!nuclear) setPlacingTarget(false); + if (nuclear) setSpeciesOpen(false); }, [nuclear, showPins]); + // The species view open or not: the button says so, and it leaves nuclear mode (they share the panel's place). + useEffect(() => { + const button = speciesButtonRef.current; + if (button) { + button.style.background = speciesOpen ? "#b2f2bb" : "white"; + button.setAttribute("aria-pressed", String(speciesOpen)); + } + if (speciesOpen) setNuclear(false); + }, [speciesOpen]); + // Global callback for popup delete buttons. useEffect(() => { window.__deleteMapPin = async (pinId) => { @@ -1604,6 +1649,10 @@ export default function MapViewer() { setFalloutOpen(false); }} />} + {mapReady && speciesOpen && setSpeciesOpen(false)} + />} {addingPin && ') +@openapi.description("Unsubscribe from a region's species pack; a downloaded pack is kept") +@wrol_mode_check +async def delete_species_subscription(request: Request, region: str): + try: + with request.ctx.db.write() as session: + await lib.species_unsubscribe(session, region) + except ValueError as e: + return response.json({'error': str(e)}, HTTPStatus.NOT_FOUND) + + return response.empty(HTTPStatus.NO_CONTENT) + + +@map_bp.delete('/species/files/') +@openapi.description("Delete a region's downloaded species pack") +@wrol_mode_check +async def delete_species_files(request: Request, region: str): + if lib.delete_species_files(region): + return response.empty() + return response.json({'error': 'No species pack for that region'}, HTTPStatus.NOT_FOUND) + + +@map_bp.get('/species') +@openapi.description('Search the downloaded species by name (q), and/or what lives near a point (lat, lon, radius_km)') +async def get_species_search(request: Request): + args = request.args + try: + lat = float(args['lat'][0]) if 'lat' in args else None + lon = float(args['lon'][0]) if 'lon' in args else None + radius_km = float(args.get('radius_km', species_search.DEFAULT_RADIUS_KM)) + group = int(args['group'][0]) if 'group' in args else None + limit = int(args.get('limit', species_search.DEFAULT_LIMIT)) + except (ValueError, TypeError): + return json_response({'error': 'Invalid query parameters'}, HTTPStatus.BAD_REQUEST) + if (lat is None) != (lon is None): + return json_response({'error': 'lat and lon must be given together'}, HTTPStatus.BAD_REQUEST) + if lat is not None and not (-90 <= lat <= 90 and -180 <= lon <= 180): + return json_response({'error': 'lat or lon is out of range'}, HTTPStatus.BAD_REQUEST) + if not 0 < radius_km <= species_search.MAX_RADIUS_KM: + return json_response({'error': f'radius_km must be from 0 to {species_search.MAX_RADIUS_KM}'}, + HTTPStatus.BAD_REQUEST) + if not 0 < limit <= 500: + return json_response({'error': 'limit must be from 1 to 500'}, HTTPStatus.BAD_REQUEST) + + species = await asyncio.to_thread(species_search.search_species, args.get('q', '').strip() or None, lat, lon, + radius_km, group, limit) + return json_response(dict( + species=species, + packs=len(lib.get_species_files()), + groups=[dict(code=code, name=name) for code, name in sorted(GROUP_NAMES.items())], + ), HTTPStatus.OK) + + +@map_bp.get('/species/here') +@openapi.description('What was seen in the ~11 km square containing lat, lon: the species most seen there first') +async def get_species_here(request: Request): + try: + lat, lon = float(request.args['lat'][0]), float(request.args['lon'][0]) + limit = int(request.args.get('limit', species_search.DEFAULT_LIMIT)) + taxon_id = int(request.args['taxon_id'][0]) if 'taxon_id' in request.args else None + except (KeyError, ValueError, TypeError): + return json_response({'error': 'lat and lon are required'}, HTTPStatus.BAD_REQUEST) + if not (-90 <= lat <= 90 and -180 <= lon <= 180) or not 0 < limit <= 500: + return json_response({'error': 'Invalid query parameters'}, HTTPStatus.BAD_REQUEST) + here = await asyncio.to_thread(species_search.species_here, lat, lon, limit, taxon_id) + return json_response(here, HTTPStatus.OK) + + +@map_bp.get('/species/') +@openapi.description("A species' details, and where to read about it in Wikipedia") +async def get_species(request: Request, taxon_id: int): + species = await asyncio.to_thread(species_search.get_species, taxon_id) + if not species: + return json_response({'error': 'Unknown species'}, HTTPStatus.NOT_FOUND) + species['wikipedia'] = await species_search.find_wikipedia_article( + request.ctx.session, species['wiki_title'], species['name']) + return json_response(species, HTTPStatus.OK) + + +@map_bp.get('/species//range') +@openapi.description("A species' range: the cells (as differences) of grid=low (0.1°, every observation) or high " + "(0.02°, precise ones)") +async def get_species_range(request: Request, taxon_id: int): + grid = request.args.get('grid', 'low') + if grid not in ('low', 'high'): + return json_response({'error': 'grid must be low or high'}, HTTPStatus.BAD_REQUEST) + cells = await asyncio.to_thread(species_search.get_species_range, taxon_id, grid) + if cells is None: + return json_response({'error': 'Unknown species'}, HTTPStatus.NOT_FOUND) + return response.json(cells) + + @map_bp.get('/pins') @openapi.description('Get all map pins') def get_pins(_: Request): diff --git a/modules/map/catalog.py b/modules/map/catalog.py index 2ccda88d..f266fe77 100644 --- a/modules/map/catalog.py +++ b/modules/map/catalog.py @@ -3,6 +3,8 @@ MB = 1_000_000 # Manifest URL — points to a JSON file on the CDN that contains the current planet file URL. MANIFEST_URL = 'https://wrolpi.nyc3.cdn.digitaloceanspaces.com/maps/manifest.json' +# The signed manifest of the iNaturalist species packs, one per region (see wrolpi/scripts/build_inat_regions.py). +SPECIES_MANIFEST_URL = 'https://wrolpi.nyc3.cdn.digitaloceanspaces.com/maps/inat/manifest.json' # Predefined regions with bounding boxes for pmtiles extract. # These regions collectively cover the entire planet. @@ -230,3 +232,42 @@ MAP_REGIONS = [ ] MAP_REGIONS_BY_NAME = {r['name']: r for r in MAP_REGIONS} + +# Species pack sizes, measured from the 20261129 packs. Regions without a pack (terrain) are not listed. `planet` is +# every region in one pack. +SPECIES_SIZE_ESTIMATES = { + 'planet': 993 * MB, + 'us-west': 91 * MB, + 'us-central': 96 * MB, + 'us-east': 179 * MB, + 'us-alaska': 6 * MB, + 'canada-west': 27 * MB, + 'canada-central': 9 * MB, + 'canada-east': 62 * MB, + 'mexico': 73 * MB, + 'central-america': 27 * MB, + 'south-america': 62 * MB, + 'europe-nw': 49 * MB, + 'europe-sw': 50 * MB, + 'europe-n-central': 14 * MB, + 'europe-central': 43 * MB, + 'europe-s-central': 48 * MB, + 'europe-ne-central': 35 * MB, + 'europe-se-central': 26 * MB, + 'europe-ne': 44 * MB, + 'europe-se': 19 * MB, + 'africa-north': 26 * MB, + 'africa-south': 40 * MB, + 'middle-east': 16 * MB, + 'russia-west': 49 * MB, + 'russia-central': 30 * MB, + 'russia-east': 9 * MB, + 'south-asia': 23 * MB, + 'east-asia-north': 23 * MB, + 'east-asia-south': 38 * MB, + 'southeast-asia': 44 * MB, + 'oceania': 77 * MB, + 'pacific-islands': 5 * MB, + 'greenland': 2 * MB, + 'antarctica': 299_000, +} diff --git a/modules/map/conftest.py b/modules/map/conftest.py index b535aa7b..e1ee031e 100644 --- a/modules/map/conftest.py +++ b/modules/map/conftest.py @@ -1,11 +1,17 @@ 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') @@ -69,3 +75,52 @@ def test_nuclear_config(test_directory, monkeypatch): 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 _ diff --git a/modules/map/downloader.py b/modules/map/downloader.py index 3c2d9c4d..32101714 100644 --- a/modules/map/downloader.py +++ b/modules/map/downloader.py @@ -11,6 +11,7 @@ from xml.sax.saxutils import escape, quoteattr from sqlalchemy.orm import Session from modules.map import lib +from modules.map.species import pack_name, parse_pack_name from wrolpi.common import logger, verify_gpg_signature from wrolpi.downloader import ( Download, @@ -26,6 +27,8 @@ __all__ = [ 'PreparedMapExtract', 'ExecutedMapExtract', 'PreparedMapSearchIndex', 'ExecutedMapSearchIndex', 'map_catalog_downloader', 'map_extract_downloader', 'map_search_index_downloader', + 'SpeciesCatalogDownloader', 'SpeciesPackDownloader', 'PreparedSpeciesPack', 'ExecutedSpeciesPack', + 'species_catalog_downloader', 'species_pack_downloader', ] logger = logger.getChild(__name__) @@ -599,3 +602,167 @@ class MapSearchIndexDownloader(Downloader): map_search_index_downloader = MapSearchIndexDownloader() + + +# --------------------------------------------------------------------------- +# SpeciesCatalogDownloader +# --------------------------------------------------------------------------- + + +class SpeciesCatalogDownloader(MapCatalogDownloader): + """Fetches the signed species manifest and creates a `species_pack` Download for each subscribed region.""" + + name = 'species_catalog' + listable = False + + def finalize_download(self, session: Session, download: Download, + executed: ExecutedMapCatalog) -> DownloadResult: + if executed.error: + return DownloadResult(success=False, error=executed.error) + + manifest = executed.manifest or {} + version = manifest.get('version', '') + manifest_regions = manifest.get('regions', {}) + hashes = manifest.get('sha256', {}) + if not manifest_regions or not version: + return DownloadResult(success=False, error='Species manifest does not contain regions and a version') + if not executed.subscribed_regions: + return DownloadResult(success=True) + + created = 0 + for subscription in executed.subscribed_regions: + region = subscription.get('region', '') + if not (url := manifest_regions.get(region)): + logger.warning(f'Subscribed species region {region!r} not found in manifest, skipping') + continue + + # A new version replaces the Download of the old one. + for old in session.query(Download).filter( + Download.downloader == 'species_pack', + Download.settings['region'].as_string() == region, + Download.url != url, + ): + logger.info(f'Deleting stale species download for {region}: {old.url}') + session.delete(old) + session.flush() + + child = download_manager.get_or_create_download(session, url, reset_attempts=True, override_skip=True) + child.downloader = 'species_pack' + child.location = '/map/manage' + child.settings = {'region': region, 'version': version, 'sha256': hashes.get(url)} + child.renew(reset_attempts=True) + created += 1 + + if not created: + return DownloadResult(success=False, error='No subscribed species regions found in manifest') + + logger.info(f'Created {created} species pack downloads') + return DownloadResult(success=True, location='/map/manage') + + +species_catalog_downloader = SpeciesCatalogDownloader() + + +# --------------------------------------------------------------------------- +# SpeciesPackDownloader +# --------------------------------------------------------------------------- + + +@dataclass +class PreparedSpeciesPack: + region: str + output_path: Optional[pathlib.Path] = None + sha256: Optional[str] = None # From the signed manifest. + already_done: bool = False + error: Optional[str] = None + + +@dataclass +class ExecutedSpeciesPack: + region: str + skipped: bool = False + error: Optional[str] = None + + +class SpeciesPackDownloader(Downloader): + """Downloads a region's species pack into the species directory, checked by aria2c against its signed hash. + + The pack replaces the region's older packs only once it has been downloaded and checked.""" + + name = 'species_pack' + listable = False + + def prepare_download(self, session: Session, download: Download) -> PreparedSpeciesPack: + settings = download.settings or {} + region = settings.get('region', '') + name = pack_name(region, settings.get('version', '')) + # The name must parse back to this region, so a region can never name a path outside the directory. + if parse_pack_name(name) is None or parse_pack_name(name)[0] != region: + return PreparedSpeciesPack(region=region, error='Invalid region or version in download settings') + + output_path = lib.get_species_directory() / name + prepared = PreparedSpeciesPack(region=region, output_path=output_path, sha256=settings.get('sha256')) + if output_path.is_file(): + logger.info(f'{name} already exists, skipping download') + # An earlier download may have stopped before it deleted the older versions. + remove_old_species_packs(output_path) + prepared.already_done = True + return prepared + + async def execute_download(self, prepared: PreparedSpeciesPack, ctx: DownloadContext, + download: Download = None) -> ExecutedSpeciesPack: + if prepared.error: + return ExecutedSpeciesPack(region=prepared.region, error=prepared.error) + if prepared.already_done: + return ExecutedSpeciesPack(region=prepared.region, skipped=True) + + download = download if download is not None else Download(url=prepared.output_path.name) + url = download.url + + # A species pack is never downloaded without a signed hash. + label = f'{prepared.region} species' + sha256, error = await get_signed_sha256(self, url, prepared.sha256, label) + if error: + return ExecutedSpeciesPack(region=prepared.region, error=error) + if not (name := meta4_file_name(url)): + return ExecutedSpeciesPack(region=prepared.region, error=f'No usable file name in {url}') + + logger.warning(f'Downloading {label} from {url}') + partial_directory = lib.get_map_directory() / PARTIAL_DIRECTORY + partial_directory.mkdir(parents=True, exist_ok=True) + try: + downloaded_path = await self.download_file( + download, url, partial_directory, + check_for_meta4=False, concurrent=1, meta4_xml=make_meta4(url, name, sha256), + ctx=ctx, + ) + # Only the file aria2c saved under the meta4's name was checked against the signed hash. + if downloaded_path != partial_directory / name: + raise RuntimeError(f'Downloaded {downloaded_path.name!r}, expected {name!r}') + downloaded_path.rename(prepared.output_path) + except Exception as e: + logger.error(f'Download failed for {label}: {e}') + remove_rejected_partial(e, partial_directory / name) + return ExecutedSpeciesPack(region=prepared.region, error=f'Download failed: {str(e)[:500]}') + + remove_old_species_packs(prepared.output_path) + logger.warning(f'Downloaded {label} ({prepared.output_path.stat().st_size} bytes)') + return ExecutedSpeciesPack(region=prepared.region) + + def finalize_download(self, session: Session, download: Download, + executed: ExecutedSpeciesPack) -> DownloadResult: + if executed.error: + return DownloadResult(success=False, error=executed.error) + return DownloadResult(success=True, location='/map/manage') + + +def remove_old_species_packs(current: pathlib.Path): + """Delete the other versions of `current`'s region.""" + region, _ = parse_pack_name(current.name) + for path in current.parent.iterdir(): + if path != current and (parsed := parse_pack_name(path.name)) and parsed[0] == region: + logger.warning(f'Deleting old species pack: {path}') + path.unlink() + + +species_pack_downloader = SpeciesPackDownloader() diff --git a/modules/map/lib.py b/modules/map/lib.py index 9b3bc1f9..fa664e54 100644 --- a/modules/map/lib.py +++ b/modules/map/lib.py @@ -6,8 +6,10 @@ from typing import List, Dict from sqlalchemy.orm import Session from modules.map import pmtiles -from modules.map.catalog import MAP_REGIONS, MAP_REGIONS_BY_NAME, MANIFEST_URL +from modules.map.catalog import MAP_REGIONS, MAP_REGIONS_BY_NAME, MANIFEST_URL, SPECIES_MANIFEST_URL, \ + SPECIES_SIZE_ESTIMATES from modules.map.config import get_maps_config +from modules.map.species import PLANET, SPECIES_DB_SUFFIX, parse_pack_name from wrolpi.common import get_media_directory, walk, logger, get_wrolpi_config, aiohttp_get, verify_gpg_signature from wrolpi.downloader import DownloadFrequency, Download, save_downloads_config, download_manager @@ -202,8 +204,105 @@ async def unsubscribe(session: Session, region: str): save_downloads_config.activate_switch() +# Species packs are kept in this directory of the map directory. +SPECIES_DIRECTORY = 'inat' + + +def get_species_directory() -> Path: + species_directory = get_map_directory() / SPECIES_DIRECTORY + species_directory.mkdir(parents=True, exist_ok=True) + return species_directory + + +def get_species_catalog() -> List[dict]: + """The map regions that have a species pack, and the planet (every region in one pack).""" + planet = dict(name='Planet (every region)', region=PLANET, bbox='-180.0,-90.0,180.0,90.0', + size_estimate=SPECIES_SIZE_ESTIMATES[PLANET]) + return [planet] + [dict(name=i['name'], region=i['region'], bbox=i['bbox'], + size_estimate=SPECIES_SIZE_ESTIMATES[i['region']]) + for i in MAP_REGIONS if i['region'] in SPECIES_SIZE_ESTIMATES] + + +def get_species_files() -> List[dict]: + """The species packs in the species directory: the newest version of each region. + + An older version left beside a newer one (a download cut short before it deleted the old) is ignored, so its + observations are never counted twice.""" + newest = dict() + for path in sorted(get_species_directory().glob(f'*{SPECIES_DB_SUFFIX}')): + if path.is_file() and (parsed := parse_pack_name(path.name)): + region, version = parsed + if region not in newest or version > newest[region]['version']: + newest[region] = dict(name=path.name, region=region, version=version, size=path.stat().st_size) + return sorted(newest.values(), key=lambda i: i['region']) + + +def delete_species_files(region: str) -> bool: + """Delete every version of a region's species pack. Returns True if any were deleted.""" + deleted = False + for path in get_species_directory().glob(f'*{SPECIES_DB_SUFFIX}'): + if (parsed := parse_pack_name(path.name)) and parsed[0] == region: + logger.warning(f'Deleting species pack: {path}') + path.unlink() + deleted = True + return deleted + + +def _get_species_download(session: Session) -> Download | None: + """The single recurring species download, if it exists.""" + return session.query(Download).filter_by(url=SPECIES_MANIFEST_URL, downloader='species_catalog').one_or_none() + + +def get_species_subscriptions(session: Session) -> List[dict]: + """The subscribed species regions.""" + download = _get_species_download(session) + return list((download.settings or {}).get('regions', [])) if download else [] + + +async def species_subscribe(session: Session, region: str): + """Subscribe to a region's species pack.""" + if region not in SPECIES_SIZE_ESTIMATES: + raise ValueError(f'{region!r} has no species pack') + + download = _get_species_download(session) + if not download: + download = download_manager.get_or_create_download(session, SPECIES_MANIFEST_URL, reset_attempts=True, + override_skip=True) + download.downloader = 'species_catalog' + # Packs are built monthly from iNaturalist's export. + download.frequency = DownloadFrequency.days30 + download.settings = {'regions': []} + download.location = '/map/manage' + download.attempts = 0 + session.flush([download]) + + regions = list(download.settings.get('regions', [])) + if any(i['region'] == region for i in regions): + return + + download.settings = {**download.settings, 'regions': [*regions, {'region': region}]} + download.renew(reset_attempts=True) + session.commit() + save_downloads_config.activate_switch() + + +async def species_unsubscribe(session: Session, region: str): + """Stop updating a region's species pack. A downloaded pack is kept.""" + download = _get_species_download(session) + if not download: + raise ValueError('No species subscriptions exist') + + regions = [i for i in download.settings.get('regions', []) if i['region'] != region] + if regions: + download.settings = {**download.settings, 'regions': regions} + else: + session.delete(download) + session.commit() + save_downloads_config.activate_switch() + + async def fetch_manifest(url: str = None) -> dict: - """Fetch the map manifest JSON from the CDN and verify its GPG signature.""" + """Fetch a manifest JSON (the map manifest by default) from the CDN and verify its GPG signature.""" url = url or MANIFEST_URL sig_url = f'{url}.sig' diff --git a/modules/map/schema.py b/modules/map/schema.py index 203a0e31..61ebdbbc 100644 --- a/modules/map/schema.py +++ b/modules/map/schema.py @@ -8,6 +8,11 @@ class MapSubscribeRequest: region: str +@dataclass +class SpeciesSubscribeRequest: + region: str + + @dataclass class MapFileVisibleRequest: map_path: str diff --git a/modules/map/species.py b/modules/map/species.py new file mode 100644 index 00000000..9d82f8a7 --- /dev/null +++ b/modules/map/species.py @@ -0,0 +1,167 @@ +"""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 diff --git a/modules/map/species_search.py b/modules/map/species_search.py new file mode 100644 index 00000000..26b85269 --- /dev/null +++ b/modules/map/species_search.py @@ -0,0 +1,417 @@ +"""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)}') diff --git a/modules/map/test/test_build_inat_regions.py b/modules/map/test/test_build_inat_regions.py new file mode 100644 index 00000000..8f0c82a5 --- /dev/null +++ b/modules/map/test/test_build_inat_regions.py @@ -0,0 +1,455 @@ +import csv +import gzip +import io +import json +import sqlite3 +import zipfile +from unittest import mock + +import pytest + +from modules.map.species import HIGH_GRID, LOW_GRID, LOOKUP_GRID, cell_id, decode_cells, decode_months, mask_months +from wrolpi.scripts import build_inat_regions as build + +# A tiny taxonomy: (taxon_id, ancestry, rank, name). +TAXA = [ + (48460, '', 'stateofmatter', 'Life'), + (1, '48460', 'kingdom', 'Animalia'), + (3, '48460/1', 'class', 'Aves'), + (12727, '48460/1/3', 'species', 'Turdus migratorius'), + (999001, '48460/1/3/12727', 'subspecies', 'Turdus migratorius migratorius'), + (47158, '48460/1', 'class', 'Insecta'), + (88, '48460/1/47158', 'species', 'Coccinella septempunctata'), + (6000, '48460/1', 'species', 'Animalia incertae'), + (47126, '48460', 'kingdom', 'Plantae'), + (54000, '48460/47126', 'genus', 'Acer'), + (54001, '48460/47126/54000', 'species', 'Acer macrophyllum'), +] + +BEND = (44.06, -121.31) +PRINEVILLE = (44.30, -120.83) +BOUNDARY = (39.74, -104.0) # On the edge of us-west and us-central: in both. + +# (lat, lon, taxon_id, uncertainty, withheld, eventDate) +OBSERVATIONS = [ + (*BEND, 12727, '10', '', '2026-05-01T08:00:00-07:00'), + (*BEND, 12727, '', '', '2026-05-20'), + (*PRINEVILLE, 999001, '', '', '2025-06-10T09:30:00Z'), # A subspecies: counted as its species. + (*BOUNDARY, 12727, '', '', '2026-07-04'), + (*BEND, 54001, '', 'Coordinate uncertainty increased to 26807m at the request of the observer', '2024-10-01'), + (*PRINEVILLE, 54001, '30000', '', ''), # Imprecise, and no date. + (*BEND, 54000, '', '', '2026-01-01'), # Genus only: skipped. + (*BEND, 424242, '', '', '2026-01-01'), # Unknown taxon: skipped. + ('', '', 12727, '', 'Coordinates hidden at the request of the observer', '2026-01-01'), # No coordinates: skipped. + (-50.0, -30.0, 88, '', '', '2026-01-01'), # In no region: skipped. + (*BEND, 88, '', '', '2026-06-15'), + (*BEND, 6000, '', '', 'spring 2026'), # Not a date. +] + +COLUMNS = ['id', 'informationWithheld', 'decimalLatitude', 'decimalLongitude', 'coordinateUncertaintyInMeters', + 'taxonID', 'scientificName', 'eventDate'] + +US_REGIONS = [ + {'region': 'us-west', 'bbox': '-125.0,24.4,-104.0,49.4'}, + {'region': 'us-central', 'bbox': '-104.0,24.4,-87.0,49.4'}, + {'region': 'us-east', 'bbox': '-87.0,24.4,-66.9,49.4'}, + {'region': 'terrain-z0-8', 'bbox': None}, +] + +# iNaturalist's English names: (taxon_id, name, locality), in the archive's order. As in the real archive, the name +# iNaturalist shows is listed first and is tied to a place; aliases without a place come after it. The first wins. +VERNACULAR = [ + (12727, 'American Robin', 'United States'), + (12727, 'Robin Redbreast', ''), + (12727, 'robin redbreast', ''), # The same name again. + (12727, 'Migratory Thrush', ''), + (54001, 'bigleaf maple', 'Oregon, US'), + (54001, '', ''), + (999001, 'Eastern American Robin', ''), +] + +WIKIDATA = { + '12727': {'title': 'American_robin', 'common': 'American robin'}, + '54001': {'title': 'Acer_macrophyllum', 'common': 'bigleaf maple'}, + '88': {}, +} + + +@pytest.fixture +def taxa_path(test_directory): + path = test_directory / 'taxa.csv.gz' + with gzip.open(path, 'wt', newline='') as fh: + writer = csv.writer(fh, delimiter='\t') + writer.writerow(['taxon_id', 'ancestry', 'rank_level', 'rank', 'name', 'active']) + for taxon_id, ancestry, rank, name in TAXA: + writer.writerow([taxon_id, ancestry, '', rank, name, 'true']) + return path + + +@pytest.fixture +def taxonomy_path(test_directory): + """iNaturalist's taxonomy archive, with only the English names.""" + path = test_directory / 'inaturalist-taxonomy.dwca.zip' + fh = io.StringIO() + writer = csv.writer(fh) + writer.writerow(['id', 'vernacularName', 'language', 'locality', 'countryCode', 'source', 'lexicon', + 'contributor', 'created']) + for taxon_id, name, locality in VERNACULAR: + writer.writerow([taxon_id, name, 'en', locality, '', '', 'English', '', '2026-01-01T00:00:00Z']) + with zipfile.ZipFile(path, 'w') as zf: + zf.writestr('VernacularNames-english.csv', fh.getvalue()) + return path + + +@pytest.fixture +def taxa(taxa_path): + return build.Taxa.load(taxa_path) + + +@pytest.fixture +def dwca_path(test_directory): + path = test_directory / 'dwca.zip' + buffer = io.StringIO() + writer = csv.writer(buffer) + writer.writerow(COLUMNS) + for i, (lat, lon, taxon_id, uncertainty, withheld, event_date) in enumerate(OBSERVATIONS): + writer.writerow([i, withheld, lat, lon, uncertainty, taxon_id, 'name, with a comma', event_date]) + with zipfile.ZipFile(path, 'w') as zf: + zf.writestr('eml.xml', '\n 2026-11-23\n') + zf.writestr('observations.csv', buffer.getvalue()) + return path + + +def test_dwca_version(dwca_path): + assert build.dwca_version(dwca_path) == '20261123' + + +def test_read_observations(dwca_path): + observations = list(build.read_observations(dwca_path)) + # Only the observation without coordinates is dropped here. + assert len(observations) == len(OBSERVATIONS) - 1 + precise = {(lat, lon, taxon_id): p for lat, lon, taxon_id, p, _ in observations} + assert precise[(*BEND, 12727)] is True + assert precise[(*BEND, 54001)] is False, 'withheld' + assert precise[(*PRINEVILLE, 54001)] is False, 'uncertainty over 5 km' + months = {(lat, lon, taxon_id): month for lat, lon, taxon_id, _, month in observations} + assert months[(*PRINEVILLE, 999001)] == 6 + assert months[(*PRINEVILLE, 54001)] == 0, 'no date' + assert months[(*BEND, 6000)] == 0, 'not a date' + + +@pytest.mark.parametrize('event_date,month', [ + ('2025-09-04T14:22:00+02:00', 9), + ('2025-12-31', 12), + ('2025-01', 1), + ('2025', 0), + ('2025-13-01', 0), + ('2025-00-01', 0), + ('', 0), + ('spring 2026', 0), +]) +def test_observation_month(event_date, month): + assert build.observation_month(event_date) == month + + +def test_taxa(taxa): + assert taxa.species_of(12727) == 12727 + assert taxa.species_of(999001) == 12727 + assert taxa.species_of(54000) is None, 'a genus has no species' + assert taxa.species_of(424242) is None + assert taxa.group_of(12727) == 2 # Birds + assert taxa.group_of(88) == 7 # Insects, not Animalia's "other". + assert taxa.group_of(54001) == 1 # Plants + assert taxa.group_of(6000) == 0 + + +def test_bbox_regions(): + regions = build.bbox_regions(US_REGIONS) + assert [name for name, _ in regions] == ['us-west', 'us-central', 'us-east'], 'terrain has no bbox' + assert regions[0][1] == (-125.0, 24.4, -104.0, 49.4) + # Every real map region parses. + assert len(build.bbox_regions()) > 20 + + +def test_split_by_region(test_directory, dwca_path, taxa): + regions = build.bbox_regions(US_REGIONS) + paths = build.split_by_region(build.read_observations(dwca_path), taxa, regions, test_directory) + assert set(paths) == {'us-west', 'us-central'}, 'us-east received nothing' + assert not (test_directory / 'us-east.tsv').exists() + + west = [line.split('\t') for line in paths['us-west'][0].read_text().splitlines()] + central = [line.split('\t') for line in paths['us-central'][0].read_text().splitlines()] + # Bend robin x2, Prineville subspecies, boundary robin, 2 maples, ladybug, other. + assert len(west) == 8 + assert central == [['39.74', '-104.0', '12727', '1', '7']], 'the boundary is in both regions' + assert ['44.3', '-120.83', '12727', '1', '6'] in west, 'the subspecies became its species' + assert build.species_in(paths['us-west'][0]) == {12727, 54001, 88, 6000} + + +@pytest.fixture +def west_pack(test_directory, dwca_path, taxa): + regions = build.bbox_regions(US_REGIONS) + paths = build.split_by_region(build.read_observations(dwca_path), taxa, regions, test_directory) + db_path = test_directory / build.pack_name('us-west', '20261123') + stats = build.build_pack(paths['us-west'], 'us-west', regions[0][1], taxa, WIKIDATA, '20261123', db_path) + return db_path, stats + + +def test_load_english_names(taxonomy_path): + assert build.load_english_names(taxonomy_path) == { + 12727: ['American Robin', 'Robin Redbreast', 'Migratory Thrush'], + 54001: ['bigleaf maple'], + 999001: ['Eastern American Robin'], + } + + +def test_build_pack_common_names(test_directory, dwca_path, taxa, taxonomy_path): + """iNaturalist's first name is the common name, before Wikidata's; every other name is searchable.""" + regions = build.bbox_regions(US_REGIONS) + paths = build.split_by_region(build.read_observations(dwca_path), taxa, regions, test_directory) + db_path = test_directory / build.pack_name('us-west', '20261123') + wikidata = {**WIKIDATA, '88': {'title': 'Coccinella_septempunctata', 'common': 'seven-spot ladybird'}} + build.build_pack(paths['us-west'], 'us-west', regions[0][1], taxa, wikidata, '20261123', db_path, + build.load_english_names(taxonomy_path)) + with sqlite3.connect(db_path) as db: + names = {taxon: (common, other) for taxon, common, other in + db.execute('SELECT taxon_id, common_name, other_names FROM species')} + match = 'SELECT rowid FROM species_fts WHERE species_fts MATCH ?' + assert db.execute(match, ('"redbreast"*',)).fetchall() == [(12727,)], 'an alias finds its species' + assert db.execute(match, ('"american"* "robin"*',)).fetchall() == [(12727,)] + assert names == { + # Wikidata's name ("American robin") is the same name; it is not repeated. + 12727: ('American Robin', 'Robin Redbreast; Migratory Thrush'), + 54001: ('bigleaf maple', None), + 88: ('seven-spot ladybird', None), + 6000: (None, None), + } + + +def test_build_pack(west_pack): + db_path, stats = west_pack + assert db_path.name == 'inat-us-west-20261123.species.db' + assert stats['species'] == 4 + assert stats['observations'] == 8 + assert stats['precise'] == 6 + + db = sqlite3.connect(db_path) + meta = dict(db.execute('SELECT key, value FROM meta')) + assert meta['version'] == '20261123' + assert meta['region'] == 'us-west' + assert meta['license'] == 'CC BY-NC 4.0' + assert '10.15468/ab3s5x' in meta['attribution'] + assert meta['observations'] == '8' + + species = {row[0]: row for row in db.execute( + 'SELECT taxon_id, name, common_name, wiki_title, grp, obs_count, min_lat, min_lon, max_lat, max_lon,' + ' range_low, range_high FROM species')} + robin = species[12727] + assert robin[1:6] == ('Turdus migratorius', 'American robin', 'American_robin', 2, 4) + assert robin[6:10] == (BOUNDARY[0], BEND[1], PRINEVILLE[0], BOUNDARY[1]) + assert decode_cells(robin[10]) == sorted({cell_id(*p, LOW_GRID) for p in (BEND, PRINEVILLE, BOUNDARY)}) + assert decode_cells(robin[11]) == sorted({cell_id(*p, HIGH_GRID) for p in (BEND, PRINEVILLE, BOUNDARY)}) + + maple = species[54001] + assert maple[2:6] == ('bigleaf maple', 'Acer_macrophyllum', 1, 2) + assert maple[6:10] == (None, None, None, None), 'no precise observation, no bbox' + assert decode_cells(maple[10]) == sorted({cell_id(*p, LOW_GRID) for p in (BEND, PRINEVILLE)}), 'blurred still count' + assert maple[11] is None, 'blurred observations make no precise dots' + + assert species[88][2:4] == (None, None), 'Wikidata had nothing' + assert species[6000][4] == 0 + + # The lookup cells add up to every observation, and find the species around Bend. + assert db.execute('SELECT SUM(obs_count) FROM cell_species').fetchone()[0] == 8 + bend = cell_id(*BEND, LOOKUP_GRID) + assert dict(db.execute('SELECT taxon_id, obs_count FROM cell_species WHERE cell = ?', (bend,))) == { + 12727: 2, 54001: 1, 88: 1, 6000: 1} + + # Months: how many each month of the year, and the months seen in each lookup cell. + months = dict(db.execute('SELECT taxon_id, months FROM species')) + assert decode_months(months[12727]) == [0, 0, 0, 0, 2, 1, 1, 0, 0, 0, 0, 0], 'May, May, June (Prineville), July' + assert decode_months(months[54001]) == [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], 'the undated maple is not a month' + assert months[6000] is None, 'never dated' + in_bend = dict(db.execute('SELECT taxon_id, months FROM cell_species WHERE cell = ?', (bend,))) + assert {taxon: mask_months(mask) for taxon, mask in in_bend.items()} == {12727: [5], 54001: [10], 88: [6], 6000: []} + + # Names are searchable. + match = 'SELECT rowid FROM species_fts WHERE species_fts MATCH ?' + assert db.execute(match, ('bigleaf',)).fetchall() == [(54001,)] + assert db.execute(match, ('turdus',)).fetchall() == [(12727,)] + + +def test_parse_wikidata_bindings(): + bindings = [ + {'inat': {'value': '1'}, 'article': {'value': 'https://en.wikipedia.org/wiki/Artemisia_(plant)'}}, + {'inat': {'value': '1'}, 'article': {'value': 'https://en.wikipedia.org/wiki/Second'}, + 'common': {'value': 'sagebrush'}}, + {'inat': {'value': '2'}, 'article': {'value': 'https://en.wikipedia.org/wiki/Caf%C3%A9'}}, + {'inat': {'value': '3'}}, + {'article': {'value': 'https://en.wikipedia.org/wiki/No_taxon'}}, + ] + assert build.parse_wikidata_bindings(bindings) == { + '1': {'title': 'Artemisia_(plant)', 'common': 'sagebrush'}, + '2': {'title': 'Café'}, + '3': {}, + } + + +def test_fetch_wikidata_caches(test_directory): + cache_path = test_directory / 'wikidata.json' + asked = [] + + def query(taxon_ids): + asked.append(list(taxon_ids)) + return [{'inat': {'value': '1'}, 'article': {'value': 'https://en.wikipedia.org/wiki/One'}}] + + assert build.fetch_wikidata([1, 2], cache_path, query=query, delay=0) == {'1': {'title': 'One'}, '2': {}} + assert asked == [['1', '2']] + # Both are cached, even the taxon Wikidata knows nothing about. + assert build.fetch_wikidata([2, 1], cache_path, query=query, delay=0) == {'1': {'title': 'One'}, '2': {}} + assert len(asked) == 1 + + +def test_fetch_wikidata_failure_not_cached(test_directory): + """A batch that fails is not cached, so the next build asks again.""" + cache_path = test_directory / 'wikidata.json' + + def failing(taxon_ids): + raise RuntimeError('timeout') + + assert build.fetch_wikidata([1, 2, 3], cache_path, query=failing, delay=0) == {} + assert not cache_path.exists() + + +def test_fetch_wikidata_splits_failing_batch(test_directory): + """A failing batch is split; the halves that work are kept.""" + ids = [str(i) for i in range(40)] + + def query(taxon_ids): + if '0' in taxon_ids: + raise RuntimeError('this one is cursed') + return [{'inat': {'value': i}, 'common': {'value': f'name {i}'}} for i in taxon_ids] + + found = build.fetch_wikidata(ids, test_directory / 'wikidata.json', query=query, delay=0) + # Halved until the batch of 10 holding '0' failed alone; the other 30 were answered. (Ids sort as text.) + failed = sorted(ids)[:10] + assert len(found) == 30 + assert not set(failed) & set(found), 'the failed batch is not cached' + assert found['39'] == {'common': 'name 39'} + + +def assert_not_exists(path): + assert not path.exists(), f'{path} is still there when the manifest is signed' + + +def test_write_manifest(test_directory, west_pack): + db_path, _ = west_pack + # A signature from an earlier build: gpg would ask before replacing it, and wait forever for an answer. + old_signature = test_directory / 'manifest.json.sig' + old_signature.write_text('old') + with mock.patch.object(build, 'write_meta4', return_value='abc123') as write_meta4, \ + mock.patch.object(build, 'sign_manifest', side_effect=lambda path: assert_not_exists(old_signature)) \ + as sign_manifest: + manifest_path = build.write_manifest(test_directory, '20261123', 'https://cdn.example/inat', + {'us-west': db_path}) + url = 'https://cdn.example/inat/20261123/inat-us-west-20261123.species.db' + manifest = json.loads(manifest_path.read_text()) + assert manifest['version'] == '20261123' + assert manifest['regions'] == {'us-west': url} + assert manifest['sizes'] == {'us-west': db_path.stat().st_size} + assert manifest['sha256'] == {url: 'abc123'} + assert manifest['license'] == 'CC BY-NC 4.0' + write_meta4.assert_called_once_with(str(db_path), url) + sign_manifest.assert_called_once_with(str(manifest_path)) + + +def test_main(test_directory, dwca_path, taxa_path, taxonomy_path): + """The whole build, offline: given sources, two regions, no signing.""" + work_dir, output_dir = test_directory / 'work', test_directory / 'out' + argv = ['build_inat_regions.py', str(work_dir), str(output_dir), '--dwca', str(dwca_path), '--taxa', + str(taxa_path), '--taxonomy', str(taxonomy_path), '--regions', 'us-west,us-central', '--no-sign'] + with mock.patch('sys.argv', argv), \ + mock.patch.object(build, 'query_wikidata', return_value=[]), \ + mock.patch.object(build, 'download') as download: + build.main() + download.assert_not_called() + + manifest = json.loads((output_dir / 'manifest.json').read_text()) + assert set(manifest['regions']) == {'us-west', 'us-central'} + assert (output_dir / '20261123' / 'inat-us-central-20261123.species.db').is_file() + assert (output_dir / '20261123' / 'inat-us-west-20261123.species.db').is_file() + assert json.loads((work_dir / 'wikidata.json').read_text()) == {'12727': {}, '54001': {}, '88': {}, '6000': {}} + with sqlite3.connect(output_dir / '20261123' / 'inat-us-west-20261123.species.db') as db: + assert db.execute('SELECT common_name FROM species WHERE taxon_id = 12727').fetchone() == ('American Robin',) + + # A rebuild of the same observations, with a new version, from the last build's region work files. + with mock.patch('sys.argv', argv + ['--version', '20261128', '--reuse-split']), \ + mock.patch.object(build, 'query_wikidata', return_value=[]), \ + mock.patch.object(build, 'read_observations') as read_observations: + build.main() + read_observations.assert_not_called() + manifest = json.loads((output_dir / 'manifest.json').read_text()) + assert manifest['version'] == '20261128' + assert manifest['regions']['us-west'].endswith('/20261128/inat-us-west-20261128.species.db') + with sqlite3.connect(output_dir / '20261128' / 'inat-us-west-20261128.species.db') as db: + assert dict(db.execute('SELECT key, value FROM meta'))['version'] == '20261128' + assert db.execute('SELECT COUNT(*) FROM species').fetchone() == (4,) + + +@pytest.mark.parametrize('extra', [['--version', '2026-11-28'], ['--reuse-split']]) +def test_main_invalid(test_directory, dwca_path, taxa_path, taxonomy_path, extra): + """A version must be YYYYMMDD; --reuse-split needs the work files of a last build.""" + argv = ['build_inat_regions.py', str(test_directory / 'work'), str(test_directory / 'out'), '--dwca', + str(dwca_path), '--taxa', str(taxa_path), '--taxonomy', str(taxonomy_path), '--no-sign', *extra] + with mock.patch('sys.argv', argv), pytest.raises(SystemExit): + build.main() + + +def test_main_unknown_region(test_directory): + argv = ['build_inat_regions.py', str(test_directory), str(test_directory), '--regions', 'atlantis'] + with mock.patch('sys.argv', argv), pytest.raises(SystemExit): + build.main() + + +def test_planet(test_directory, dwca_path, taxa, taxonomy_path): + """The planet is every observation once, though regions overlap, built from work files split by species.""" + regions = build.bbox_regions(US_REGIONS) + paths = build.split_by_region(build.read_observations(dwca_path), taxa, regions, test_directory, planet=True) + buckets = paths['planet'] + assert len(buckets) == build.PLANET_BUCKETS + # Each species is in one bucket; every observation of a species (in a region or not) is in it once. + species_of_bucket = [build.species_in(i) for i in buckets] + assert sum(len(i) for i in species_of_bucket) == len(set().union(*species_of_bucket)) == 4 + # Bend robin x2, Prineville subspecies, boundary robin, 2 maples, 2 ladybugs (one in no region), other. + assert sum(len(i.read_text().splitlines()) for i in buckets) == 9 + + planet = test_directory / build.pack_name('planet', '20261123') + stats = build.build_pack(buckets, 'planet', build.PLANET_BBOX, taxa, WIKIDATA, '20261123', planet, + build.load_english_names(taxonomy_path)) + assert (stats['species'], stats['observations']) == (4, 9) + + db = sqlite3.connect(planet) + meta = dict(db.execute('SELECT key, value FROM meta')) + assert (meta['region'], meta['bbox'], meta['observations']) == ('planet', '-180.0,-90.0,180.0,90.0', '9') + # The boundary robin is in both us-west and us-central, but once here: Bend x2, Prineville, the boundary. + robin = db.execute('SELECT common_name, obs_count, months FROM species WHERE taxon_id = 12727').fetchone() + assert robin == ('American Robin', 4, '0,0,0,0,2,1,1,0,0,0,0,0') + assert db.execute('SELECT SUM(obs_count) FROM cell_species').fetchone() == (9,) + assert db.execute("SELECT rowid FROM species_fts WHERE species_fts MATCH '\"redbreast\"*'").fetchall() == [(12727,)] + + +def test_main_planet_alone(test_directory, dwca_path, taxa_path, taxonomy_path): + """`--regions planet` builds only the planet; the manifest also lists the regions already built for the version.""" + work_dir, output_dir = test_directory / 'work', test_directory / 'out' + argv = ['build_inat_regions.py', str(work_dir), str(output_dir), '--dwca', str(dwca_path), '--taxa', + str(taxa_path), '--taxonomy', str(taxonomy_path), '--no-sign'] + with mock.patch('sys.argv', argv + ['--regions', 'us-west,us-central']), \ + mock.patch.object(build, 'query_wikidata', return_value=[]): + build.main() + assert not (output_dir / '20261123' / 'inat-planet-20261123.species.db').exists() + with mock.patch('sys.argv', argv + ['--regions', 'planet']), \ + mock.patch.object(build, 'query_wikidata', return_value=[]): + build.main() + manifest = json.loads((output_dir / 'manifest.json').read_text()) + assert set(manifest['regions']) == {'us-west', 'us-central', 'planet'} + assert not (work_dir / 'regions' / 'us-west.tsv').read_text() == '', 'the regions\' work was left alone' diff --git a/modules/map/test/test_species.py b/modules/map/test/test_species.py new file mode 100644 index 00000000..57c3a985 --- /dev/null +++ b/modules/map/test/test_species.py @@ -0,0 +1,51 @@ +import pytest + +from modules.map.species import (HIGH_GRID, LOW_GRID, cell_center, cell_id, decode_cells, decode_months, encode_cells, + encode_months, mask_months, month_bit) + + +@pytest.mark.parametrize('grid', [LOW_GRID, HIGH_GRID]) +@pytest.mark.parametrize('lat,lon', [ + (44.06, -121.31), + (-33.86, 151.21), + (0.0, 0.0), + (-90.0, -180.0), + (90.0, 180.0), # The north pole and the antimeridian fall in the last row/column. + (89.999, 179.999), +]) +def test_cell_center_contains_point(grid, lat, lon): + """The center of a point's cell is within half a cell of the point (or on the world's edge, the last cell).""" + center_lat, center_lon = cell_center(cell_id(lat, lon, grid), grid) + assert abs(center_lat - lat) <= grid / 2 + 1e-9 + assert abs(center_lon - lon) <= grid / 2 + 1e-9 + + +def test_cell_id_neighbors(): + """Cells are numbered row by row from the south-west corner.""" + assert cell_id(-90, -180, LOW_GRID) == 0 + assert cell_id(-90, -179.95, LOW_GRID) == 0 + assert cell_id(-90, -179.85, LOW_GRID) == 1 + assert cell_id(-89.85, -180, LOW_GRID) == 3600 + assert cell_id(90, 180, LOW_GRID) == 1800 * 3600 - 1 + + +@pytest.mark.parametrize('cells', [ + [], + [0], + [5, 3, 5, 1], # Unsorted, with a duplicate. + [127, 128, 16_383, 16_384, 2 ** 28 - 1], # Varint boundaries and the largest high grid cell. + list(range(0, 1_000_000, 37)), +]) +def test_encode_decode_cells(cells): + assert decode_cells(encode_cells(cells)) == sorted(set(cells)) + + +def test_months(): + assert [month_bit(i) for i in (0, 1, 12, 13)] == [0, 1, 2048, 0] + assert mask_months(month_bit(1) | month_bit(6) | month_bit(12)) == [1, 6, 12] + assert mask_months(0) == [] + counts = [0, 0, 3, 10, 0, 0, 0, 0, 0, 0, 1, 0] + assert decode_months(encode_months(counts)) == counts + assert encode_months([0] * 12) is None + assert decode_months(None) == [0] * 12 + assert decode_months('1,2') == [0] * 12, 'malformed' diff --git a/modules/map/test/test_species_download.py b/modules/map/test/test_species_download.py new file mode 100644 index 00000000..eae716c2 --- /dev/null +++ b/modules/map/test/test_species_download.py @@ -0,0 +1,357 @@ +"""Subscribing to species packs and downloading them: lib helpers, the downloaders, and the API.""" +import json +from http import HTTPStatus +from unittest import mock + +import pytest +import yaml + +from modules.map import lib +from modules.map.catalog import MAP_REGIONS, SPECIES_MANIFEST_URL +from modules.map.downloader import ( + ExecutedMapCatalog, + PreparedSpeciesPack, + species_catalog_downloader, + species_pack_downloader, +) +from wrolpi.conftest import make_test_ctx +from wrolpi.downloader import Download, DownloadFrequency, import_downloads_config + +SHA256 = 'a' * 64 +CDN = 'https://cdn.example.com/maps/inat' + + +def make_pack(region: str, version: str, contents: bytes = b'pack'): + path = lib.get_species_directory() / f'inat-{region}-{version}.species.db' + path.write_bytes(contents) + return path + + +def manifest(version: str = '20261123', *regions: str) -> dict: + regions = regions or ('us-west', 'us-alaska') + urls = {i: f'{CDN}/{version}/inat-{i}-{version}.species.db' for i in regions} + return {'version': version, 'regions': urls, 'sha256': {url: SHA256 for url in urls.values()}} + + +# --------------------------------------------------------------------------- +# lib +# --------------------------------------------------------------------------- + + +def test_species_catalog(test_directory): + """Every map region with a bbox has a species pack; terrain does not.""" + catalog = lib.get_species_catalog() + regions = {i['region'] for i in catalog} + assert regions == {i['region'] for i in MAP_REGIONS if i['bbox']} | {'planet'} + assert 'terrain-z0-8' not in regions + us_west, = [i for i in catalog if i['region'] == 'us-west'] + assert us_west['name'] == 'United States (West)' + assert us_west['bbox'] == '-125.0,24.4,-104.0,49.4' + assert us_west['size_estimate'] > 0 + + +def test_species_directory(test_directory, test_wrolpi_config): + """Packs are kept in `inat/` of the map directory.""" + assert lib.get_species_directory() == test_directory / 'map/inat' + assert lib.get_species_directory().is_dir() + + +def test_species_files(test_directory): + """Only pack files are listed, with their region and version.""" + make_pack('us-west', '20261123', b'12345') + make_pack('europe-ne-central', '20261123') + (lib.get_species_directory() / 'notes.txt').write_text('not a pack') + (lib.get_species_directory() / 'inat-us-west.species.db').write_text('no version') + + files = lib.get_species_files() + assert [(i['region'], i['version']) for i in files] == [('europe-ne-central', '20261123'), ('us-west', '20261123')] + assert files[1]['size'] == 5 + assert files[1]['name'] == 'inat-us-west-20261123.species.db' + + +def test_delete_species_files(test_directory): + """Deleting a region's packs deletes every version of it, and no other region with the same prefix.""" + old = make_pack('europe-ne', '20261023') + new = make_pack('europe-ne', '20261123') + other = make_pack('europe-ne-central', '20261123') + + assert lib.delete_species_files('europe-ne') is True + assert not old.exists() and not new.exists() + assert other.exists() + assert lib.delete_species_files('europe-ne') is False + # A region never names a path. + assert lib.delete_species_files('../../etc') is False + + +@pytest.mark.asyncio +async def test_species_subscribe(async_client, test_session, test_directory): + """Subscriptions share one recurring Download of the species manifest.""" + await lib.species_subscribe(test_session, 'us-alaska') + await lib.species_subscribe(test_session, 'us-west') + await lib.species_subscribe(test_session, 'us-west') # Not duplicated. + await lib.species_subscribe(test_session, 'planet') + await lib.species_unsubscribe(test_session, 'planet') + + assert lib.get_species_subscriptions(test_session) == [{'region': 'us-alaska'}, {'region': 'us-west'}] + download = lib._get_species_download(test_session) + assert download.url == SPECIES_MANIFEST_URL + assert download.downloader == 'species_catalog' + assert download.frequency == DownloadFrequency.days30 + assert download.status == 'new' + + with pytest.raises(ValueError): + await lib.species_subscribe(test_session, 'atlantis') + # Terrain is a map region, but has no species. + with pytest.raises(ValueError): + await lib.species_subscribe(test_session, 'terrain-z0-8') + + +@pytest.mark.asyncio +async def test_species_unsubscribe(async_client, test_session, test_directory): + """Unsubscribing keeps the downloaded pack; the last one deletes the Download.""" + pack = make_pack('us-alaska', '20261123') + await lib.species_subscribe(test_session, 'us-alaska') + await lib.species_subscribe(test_session, 'us-west') + + await lib.species_unsubscribe(test_session, 'us-alaska') + assert lib.get_species_subscriptions(test_session) == [{'region': 'us-west'}] + assert pack.is_file() + + await lib.species_unsubscribe(test_session, 'us-west') + assert lib.get_species_subscriptions(test_session) == [] + assert lib._get_species_download(test_session) is None + + with pytest.raises(ValueError): + await lib.species_unsubscribe(test_session, 'us-west') + + +@pytest.mark.asyncio +async def test_species_subscriptions_config(async_client, test_session, test_directory, test_download_manager_config, + await_switches): + """Subscriptions are saved to the downloads config, and come back when it is imported.""" + await lib.species_subscribe(test_session, 'us-west') + await await_switches() + + with test_download_manager_config.open() as fh: + downloads = yaml.safe_load(fh)['downloads'] + saved, = [i for i in downloads if i['url'] == SPECIES_MANIFEST_URL] + assert saved['downloader'] == 'species_catalog' + assert saved['settings'] == {'regions': [{'region': 'us-west'}]} + + test_session.query(Download).delete() + test_session.commit() + assert lib.get_species_subscriptions(test_session) == [] + + await import_downloads_config() + assert lib.get_species_subscriptions(test_session) == [{'region': 'us-west'}] + + +# --------------------------------------------------------------------------- +# SpeciesCatalogDownloader +# --------------------------------------------------------------------------- + + +def test_catalog_creates_pack_downloads(test_session, test_directory): + """A species_pack Download is created for each subscribed region in the manifest, with its signed hash.""" + download = Download(url=SPECIES_MANIFEST_URL, downloader='species_catalog') + executed = ExecutedMapCatalog(manifest=manifest(), subscribed_regions=[{'region': 'us-west'}, {'region': 'mars'}]) + + result = species_catalog_downloader.finalize_download(test_session, download, executed) + + assert result.success is True + child, = test_session.query(Download).filter_by(downloader='species_pack').all() + assert child.url == f'{CDN}/20261123/inat-us-west-20261123.species.db' + assert child.settings == {'region': 'us-west', 'version': '20261123', 'sha256': SHA256} + assert child.status == 'new' + + +def test_catalog_replaces_old_version(test_session, test_directory): + """A new version replaces the old version's Download; other regions' Downloads are left alone.""" + download = Download(url=SPECIES_MANIFEST_URL, downloader='species_catalog') + subscribed = [{'region': 'us-west'}, {'region': 'us-alaska'}] + species_catalog_downloader.finalize_download( + test_session, download, ExecutedMapCatalog(manifest=manifest('20261023'), subscribed_regions=subscribed)) + test_session.commit() + + # The next month only us-west was rebuilt. + new = manifest('20261123', 'us-west') + new['regions']['us-alaska'] = f'{CDN}/20261023/inat-us-alaska-20261023.species.db' + new['sha256'][new['regions']['us-alaska']] = SHA256 + species_catalog_downloader.finalize_download( + test_session, download, ExecutedMapCatalog(manifest=new, subscribed_regions=subscribed)) + test_session.commit() + + urls = sorted(i.url for i in test_session.query(Download).filter_by(downloader='species_pack')) + assert urls == [f'{CDN}/20261023/inat-us-alaska-20261023.species.db', + f'{CDN}/20261123/inat-us-west-20261123.species.db'] + + +@pytest.mark.parametrize('bad_manifest,error', [ + ({'regions': {}, 'version': '20261123'}, 'does not contain regions'), + ({'regions': {'us-west': 'https://x'}}, 'does not contain regions'), + (manifest('20261123', 'mexico'), 'No subscribed species regions'), +]) +def test_catalog_failures(test_session, test_directory, bad_manifest, error): + download = Download(url=SPECIES_MANIFEST_URL, downloader='species_catalog') + executed = ExecutedMapCatalog(manifest=bad_manifest, subscribed_regions=[{'region': 'us-west'}]) + result = species_catalog_downloader.finalize_download(test_session, download, executed) + assert result.success is False + assert error in result.error + + +@pytest.mark.asyncio +async def test_catalog_fetches_species_manifest(test_session, test_directory): + """The species catalog fetches (and verifies) the manifest at its Download's URL.""" + download = Download(url=SPECIES_MANIFEST_URL, downloader='species_catalog', settings={'regions': []}) + prepared = species_catalog_downloader.prepare_download(test_session, download) + with mock.patch('modules.map.lib.fetch_manifest', mock.AsyncMock(return_value=manifest())) as fetch: + executed = await species_catalog_downloader.execute_download(prepared, make_test_ctx()) + fetch.assert_called_once_with(SPECIES_MANIFEST_URL) + assert executed.manifest == manifest() + + +# --------------------------------------------------------------------------- +# SpeciesPackDownloader +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize('settings', [ + {}, + {'region': 'us-west'}, + {'region': 'us-west', 'version': 'latest'}, + {'region': '../../etc', 'version': '20261123'}, + {'region': 'US West', 'version': '20261123'}, +]) +def test_pack_prepare_invalid(test_session, test_directory, settings): + """A pack's region and version must make a pack name; nothing else is downloaded.""" + download = Download(url=f'{CDN}/x.species.db', downloader='species_pack', settings=settings) + prepared = species_pack_downloader.prepare_download(test_session, download) + assert prepared.error == 'Invalid region or version in download settings' + + +def test_pack_prepare_already_done(test_session, test_directory): + make_pack('us-west', '20261123') + download = Download(url=f'{CDN}/20261123/inat-us-west-20261123.species.db', downloader='species_pack', + settings={'region': 'us-west', 'version': '20261123', 'sha256': SHA256}) + prepared = species_pack_downloader.prepare_download(test_session, download) + assert prepared.already_done is True + assert prepared.output_path == test_directory / 'map/inat/inat-us-west-20261123.species.db' + + +@pytest.mark.asyncio +async def test_pack_refuses_without_signed_hash(test_session, test_directory): + """With no hash in the manifest and no meta4, nothing is downloaded.""" + url = f'{CDN}/20261123/inat-us-west-20261123.species.db' + download = Download(url=url, downloader='species_pack', settings={'region': 'us-west', 'version': '20261123'}) + prepared = species_pack_downloader.prepare_download(test_session, download) + + with mock.patch.object(species_pack_downloader, 'get_meta4_contents', mock.AsyncMock(return_value=None)), \ + mock.patch.object(species_pack_downloader, 'download_file') as download_file: + executed = await species_pack_downloader.execute_download(prepared, make_test_ctx(), download) + + assert 'No signed hash' in executed.error + download_file.assert_not_called() + + +@pytest.mark.asyncio +async def test_pack_download_replaces_old_version(test_session, test_directory): + """The new pack is moved in only after aria2c checked it against the signed hash; then old versions go.""" + old = make_pack('us-west', '20261023', b'old') + neighbor = make_pack('us-west-coast', '20261023', b'not this region') # Hypothetical region with the prefix. + url = f'{CDN}/20261123/inat-us-west-20261123.species.db' + download = Download(url=url, downloader='species_pack', + settings={'region': 'us-west', 'version': '20261123', 'sha256': SHA256}) + prepared = species_pack_downloader.prepare_download(test_session, download) + + async def fake_download_file(download_, url_, destination, **kwargs): + assert SHA256.encode() in kwargs['meta4_xml'] + # Not in the species directory until it is checked. + assert destination == test_directory / 'map/.partial' + path = destination / 'inat-us-west-20261123.species.db' + path.write_bytes(b'new') + return path + + with mock.patch.object(species_pack_downloader, 'download_file', fake_download_file): + executed = await species_pack_downloader.execute_download(prepared, make_test_ctx(), download) + + assert executed.error is None + assert (test_directory / 'map/inat/inat-us-west-20261123.species.db').read_bytes() == b'new' + assert not old.exists() + assert neighbor.exists() + assert species_pack_downloader.finalize_download(test_session, download, executed).success is True + + +@pytest.mark.asyncio +async def test_pack_download_failure_keeps_old_version(test_session, test_directory): + """A failed (or rejected) download leaves the region's current pack in place.""" + old = make_pack('us-west', '20261023', b'old') + url = f'{CDN}/20261123/inat-us-west-20261123.species.db' + download = Download(url=url, downloader='species_pack', + settings={'region': 'us-west', 'version': '20261123', 'sha256': SHA256}) + prepared = species_pack_downloader.prepare_download(test_session, download) + + with mock.patch.object(species_pack_downloader, 'download_file', + mock.AsyncMock(side_effect=RuntimeError('aria2c failed with return code 32'))): + executed = await species_pack_downloader.execute_download(prepared, make_test_ctx(), download) + + assert 'Download failed' in executed.error + assert old.read_bytes() == b'old' + assert not (test_directory / 'map/inat/inat-us-west-20261123.species.db').exists() + assert species_pack_downloader.finalize_download(test_session, download, executed).success is False + + +@pytest.mark.asyncio +async def test_pack_skipped(test_session, test_directory): + prepared = PreparedSpeciesPack(region='us-west', already_done=True) + executed = await species_pack_downloader.execute_download(prepared, make_test_ctx()) + assert executed.skipped is True + + +# --------------------------------------------------------------------------- +# API +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_species_api(async_client, test_session, test_directory): + """The species catalog can be fetched, subscribed to, and unsubscribed from; packs can be deleted.""" + request, response = await async_client.get('/api/map/species/subscribe') + assert response.status_code == HTTPStatus.OK + assert response.json['subscriptions'] == [] + assert response.json['files'] == [] + assert 'us-west' in [i['region'] for i in response.json['catalog']] + + request, response = await async_client.post('/api/map/species/subscribe', content=json.dumps({'region': 'us-west'})) + assert response.status_code == HTTPStatus.CREATED + request, response = await async_client.post('/api/map/species/subscribe', content=json.dumps({'region': 'mars'})) + assert response.status_code == HTTPStatus.BAD_REQUEST + + make_pack('us-west', '20261123', b'12345') + request, response = await async_client.get('/api/map/species/subscribe') + assert response.json['subscriptions'] == [{'region': 'us-west'}] + assert [(i['region'], i['version'], i['size']) for i in response.json['files']] == [('us-west', '20261123', 5)] + + request, response = await async_client.delete('/api/map/species/subscribe/us-west') + assert response.status_code == HTTPStatus.NO_CONTENT + request, response = await async_client.delete('/api/map/species/subscribe/us-west') + assert response.status_code == HTTPStatus.NOT_FOUND + + request, response = await async_client.delete('/api/map/species/files/us-west') + assert response.status_code == HTTPStatus.NO_CONTENT + request, response = await async_client.delete('/api/map/species/files/us-west') + assert response.status_code == HTTPStatus.NOT_FOUND + + request, response = await async_client.get('/api/map/species/subscribe') + assert response.json['subscriptions'] == [] + assert response.json['files'] == [] + + +def test_pack_already_done_removes_old_versions(test_session, test_directory): + """A download that stopped before deleting the older versions is finished on the next run.""" + old = make_pack('us-west', '20261023', b'old') + make_pack('us-west', '20261123', b'new') + download = Download(url=f'{CDN}/20261123/inat-us-west-20261123.species.db', downloader='species_pack', + settings={'region': 'us-west', 'version': '20261123', 'sha256': SHA256}) + prepared = species_pack_downloader.prepare_download(test_session, download) + assert prepared.already_done is True + assert not old.exists() diff --git a/modules/map/test/test_species_search.py b/modules/map/test/test_species_search.py new file mode 100644 index 00000000..556003bc --- /dev/null +++ b/modules/map/test/test_species_search.py @@ -0,0 +1,404 @@ +"""Reading the species packs: search by name and place, details, range dots, and the Wikipedia article.""" +import itertools +from http import HTTPStatus +from unittest import mock + +import pytest + +from modules.map import lib, species_search +from modules.map.species import HIGH_GRID, LOOKUP_GRID, LOW_GRID, cell_center, cell_id +from modules.map.species_search import cells_within, fts_query, haversine_km + +BEND = (44.06, -121.31) +PRINEVILLE = (44.30, -120.83) # ~47 km east of Bend. +CRATER_LAKE = (42.94, -122.10) # ~140 km from Bend. +DENVER = (39.74, -104.99) # In us-central. + +ASPEN = dict(taxon_id=1, name='Populus tremuloides', common_name='quaking aspen', wiki_title='one', grp=1) +GRASS = dict(taxon_id=2, name='Briza maxima', common_name='big quakinggrass', grp=1) +DEER = dict(taxon_id=3, name='Odocoileus hemionus', common_name='mule deer', wiki_title='Mule_deer', grp=3) +# Its (made up) common name is exactly "aspen". +FLEABANE = dict(taxon_id=4, name='Erigeron speciosus', common_name='aspen', grp=1) + + +@pytest.fixture +def us_packs(test_directory, make_species_pack): + make_species_pack('us-west', [ + {**ASPEN, 'points': [BEND, BEND, BEND, CRATER_LAKE]}, + {**GRASS, 'points': [PRINEVILLE] * 5}, + {**DEER, 'points': [BEND] + [CRATER_LAKE] * 10}, + {**FLEABANE, 'points': [PRINEVILLE]}, + ]) + make_species_pack('us-central', [ + {**ASPEN, 'points': [DENVER, DENVER]}, + ]) + + +def taxa(results): + return [i['taxon_id'] for i in results] + + +# --- Cells ------------------------------------------------------------------------------------------------------------ + + +def test_cells_within(): + lat, lon = BEND + cells = cells_within(lat, lon, 30) + assert cell_id(lat, lon, LOOKUP_GRID) in cells + # Every cell has some part within the radius: its center is within the radius plus half its diagonal (~7 km). + assert all(haversine_km(lat, lon, *cell_center(i, LOOKUP_GRID)) < 30 + 8 for i in cells) + assert cell_id(lat, lon + 0.2, LOOKUP_GRID) in cells # ~16 km east. + assert cell_id(lat, lon + 0.6, LOOKUP_GRID) not in cells # ~48 km east. + assert cell_id(*PRINEVILLE, LOOKUP_GRID) not in cells + assert cell_id(*PRINEVILLE, LOOKUP_GRID) in cells_within(lat, lon, 60) + + # A tiny radius is still the point's own cell. + assert cells_within(lat, lon, 0.001) == [cell_id(lat, lon, LOOKUP_GRID)] + + +def test_cells_within_antimeridian_and_pole(): + # Fiji: the radius crosses the antimeridian into the first column. + cells = cells_within(-17.0, 179.99, 20) + assert cell_id(-17.0, -179.95, LOOKUP_GRID) in cells + assert cell_id(-17.0, 179.95, LOOKUP_GRID) in cells + # Near the pole every column of the last rows is near. + cells = cells_within(89.99, 0, 50) + assert cell_id(89.95, 179.95, LOOKUP_GRID) in cells + assert cell_id(89.95, -179.95, LOOKUP_GRID) in cells + + +@pytest.mark.parametrize('q,expected', [ + ('quaking asp', '"quaking"* "asp"*'), + ("O'Brien", '"O"* "Brien"*'), + ('"*', None), + ('', None), +]) +def test_fts_query(q, expected): + assert fts_query(q) == expected + + +# --- Search ----------------------------------------------------------------------------------------------------------- + + +def test_search_no_packs(test_directory): + assert species_search.search_species(q='aspen') == [] + assert species_search.search_species(lat=BEND[0], lon=BEND[1]) == [] + + +def test_search_by_name(us_packs): + """Every word is a prefix; without a place the most observed come first. A species in two regions is merged.""" + results = species_search.search_species(q='quak') + assert taxa(results) == [1, 2] + aspen, grass = results + assert aspen['obs_count'] == 6 # 4 in us-west + 2 in us-central. + assert aspen['regions'] == ['us-central', 'us-west'] + assert aspen['bbox'] == [CRATER_LAKE[1], DENVER[0], DENVER[1], BEND[0]] + assert aspen['near_count'] is None + assert aspen['group'] == 'Plants' + assert aspen['common_name'] == 'quaking aspen' + + assert taxa(species_search.search_species(q='quaking aspen')) == [1] + assert taxa(species_search.search_species(q='odocoileus')) == [3] + assert taxa(species_search.search_species(q='nothing')) == [] + assert taxa(species_search.search_species(q='"*')) == [] + + +def test_search_exact_name_first(us_packs): + """A species named exactly what was searched comes first, however rarely it was seen.""" + assert taxa(species_search.search_species(q='aspen')) == [4, 1] + assert taxa(species_search.search_species(q='Populus tremuloides')) == [1] + + +def test_search_near(us_packs): + """Without a name: only species seen within the radius, the most seen nearby first.""" + lat, lon = BEND + results = species_search.search_species(lat=lat, lon=lon, radius_km=30) + assert [(i['taxon_id'], i['near_count']) for i in results] == [(1, 3), (3, 1)] + # Near counts are only nearby observations; totals are every region's. + assert results[1]['obs_count'] == 11 + + # Prineville is within 60 km. Equal near counts are ordered by total observations. + results = species_search.search_species(lat=lat, lon=lon, radius_km=60) + assert [(i['taxon_id'], i['near_count']) for i in results] == [(2, 5), (1, 3), (3, 1), (4, 1)] + + # Nothing is seen in the ocean. + assert species_search.search_species(lat=30.0, lon=-140.0) == [] + + +def test_search_name_and_near(us_packs): + """With a name and a place, matching species seen nearby come first; the others are still listed.""" + lat, lon = BEND + results = species_search.search_species(q='quak', lat=lat, lon=lon, radius_km=30) + assert [(i['taxon_id'], i['near_count']) for i in results] == [(1, 3), (2, 0)] + + +def test_search_group_and_limit(us_packs): + lat, lon = BEND + assert taxa(species_search.search_species(lat=lat, lon=lon, radius_km=60, group=3)) == [3] + assert taxa(species_search.search_species(lat=lat, lon=lon, radius_km=60, group=1)) == [2, 1, 4] + assert taxa(species_search.search_species(lat=lat, lon=lon, radius_km=60, limit=2)) == [2, 1] + # Neither a name nor a place: the most observed. + assert taxa(species_search.search_species(limit=2)) == [3, 1] + + +# --- Details and range ------------------------------------------------------------------------------------------------ + + +def test_get_species(us_packs): + aspen = species_search.get_species(1) + assert aspen['name'] == 'Populus tremuloides' + assert aspen['obs_count'] == 6 + assert aspen['regions'] == ['us-central', 'us-west'] + assert species_search.get_species(999) is None + + +@pytest.mark.parametrize('grid,size', [('low', LOW_GRID), ('high', HIGH_GRID)]) +def test_get_species_range(us_packs, grid, size): + """Every cell the species was seen in, in every region, each once: sorted, as differences.""" + found = species_search.get_species_range(1, grid) + assert found['grid'] == size + assert found['count'] == 3 + cells = list(itertools.accumulate(found['deltas'])) + assert cells == sorted(cell_id(*point, size) for point in (BEND, CRATER_LAKE, DENVER)) + assert species_search.get_species_range(999, grid) is None + + +# --- Wikipedia -------------------------------------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_wikipedia_none(test_session, test_directory, zim_factory): + """Without a Wikipedia Zim there is nowhere to read about a species.""" + zim_factory('gutenberg_en_all_2026-01.zim') + assert await species_search.find_wikipedia_article(test_session, 'one', 'Populus tremuloides') is None + + +@pytest.mark.asyncio +async def test_wikipedia_article(test_session, test_directory, zim_factory): + """The article is found in the best Wikipedia Zim; a missing article falls back to a search for the name.""" + mini = zim_factory('wikipedia_en_all_mini_2026-03.zim') + maxi = zim_factory('wikipedia_en_all_maxi_2026-01.zim') + old_maxi = zim_factory('wikipedia_en_all_maxi_2025-01.zim') + zim_factory('wiktionary_en_all_maxi_2026-01.zim') + test_session.commit() + + assert species_search.wikipedia_zims(test_session) == [maxi, old_maxi, mini] + + # The test Zim has an article at `one`. + article = await species_search.find_wikipedia_article(test_session, 'one', 'Populus tremuloides') + assert article == dict(zim_id=maxi.id, path='one', title='One', url=f'/api/zim/{maxi.id}/entry/one') + + search = dict(zim_id=None, path=None, title=None, url='/search?q=Populus%20tremuloides') + assert await species_search.find_wikipedia_article(test_session, 'Populus_tremuloides', + 'Populus tremuloides') == search + assert await species_search.find_wikipedia_article(test_session, None, 'Populus tremuloides') == search + + +# --- API -------------------------------------------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_species_search_api(async_client, us_packs): + request, response = await async_client.get('/api/map/species', params={'q': 'quak'}) + assert response.status_code == HTTPStatus.OK + assert taxa(response.json['species']) == [1, 2] + assert response.json['packs'] == 2 + assert {'code': 1, 'name': 'Plants'} in response.json['groups'] + + params = {'lat': BEND[0], 'lon': BEND[1], 'radius_km': 60, 'group': 1, 'limit': 2} + request, response = await async_client.get('/api/map/species', params=params) + assert [(i['taxon_id'], i['near_count']) for i in response.json['species']] == [(2, 5), (1, 3)] + + +@pytest.mark.asyncio +@pytest.mark.parametrize('params', [ + {'lat': 40}, + {'lat': 100, 'lon': 0}, + {'lat': 0, 'lon': 181}, + {'lat': 'x', 'lon': 0}, + {'radius_km': 0}, + {'radius_km': 201}, + {'group': 'plants'}, + {'limit': 0}, + {'limit': 501}, +]) +async def test_species_search_api_invalid(async_client, test_directory, params): + request, response = await async_client.get('/api/map/species', params=params) + assert response.status_code == HTTPStatus.BAD_REQUEST + + +@pytest.mark.asyncio +async def test_species_detail_api(async_client, test_session, us_packs, zim_factory): + request, response = await async_client.get('/api/map/species/1') + assert response.status_code == HTTPStatus.OK + assert response.json['common_name'] == 'quaking aspen' + assert response.json['wikipedia'] is None + + zim = zim_factory('wikipedia_en_all_nopic_2026-01.zim') + test_session.commit() + request, response = await async_client.get('/api/map/species/1') + assert response.json['wikipedia']['url'] == f'/api/zim/{zim.id}/entry/one' + + request, response = await async_client.get('/api/map/species/999') + assert response.status_code == HTTPStatus.NOT_FOUND + + +@pytest.mark.asyncio +async def test_species_range_api(async_client, us_packs): + for grid in ('low', 'high'): + request, response = await async_client.get('/api/map/species/1/range', params={'grid': grid}) + assert response.status_code == HTTPStatus.OK + assert response.json['count'] == 3 + + request, response = await async_client.get('/api/map/species/1/range', params={'grid': 'medium'}) + assert response.status_code == HTTPStatus.BAD_REQUEST + request, response = await async_client.get('/api/map/species/999/range') + assert response.status_code == HTTPStatus.NOT_FOUND + + +# --- Months and what was seen here ------------------------------------------------------------------------------------- + + +@pytest.fixture +def dated_packs(test_directory, make_species_pack): + """Aspen seen around Bend in May and October, and in us-central in October; deer at Bend in July.""" + make_species_pack('us-west', [ + {**ASPEN, 'points': [(*BEND, 5), (*BEND, 5), (*BEND, 10), CRATER_LAKE]}, # Crater Lake is undated. + {**DEER, 'points': [(*BEND, 7)]}, + {**GRASS, 'points': [(*PRINEVILLE, 4)]}, + ]) + make_species_pack('us-central', [{**ASPEN, 'points': [(*DENVER, 10)]}]) + + +def test_species_months(dated_packs): + """A species' months are summed over every region.""" + aspen = species_search.get_species(1) + assert aspen['months'] == [0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0] + assert species_search.search_species(q='mule')[0]['months'][6] == 1 + + +def test_species_here(dated_packs): + """The species seen in the square of a point, the most seen first, with the months seen there.""" + here = species_search.species_here(*BEND) + assert here['species_count'] == 2 + assert [(i['taxon_id'], i['here_count'], i['here_months']) for i in here['species']] == [(1, 3, [5, 10]), (3, 1, [7])] + # The square holds the point, and is 0.1° wide. + west, south, east, north = here['bbox'] + assert west <= BEND[1] <= east and south <= BEND[0] <= north + assert (east - west, north - south) == pytest.approx((LOOKUP_GRID, LOOKUP_GRID)) + + assert [i['taxon_id'] for i in species_search.species_here(*BEND, limit=1)['species']] == [1] + # The species asked about is there however few times it was seen, even beyond the limit. + deer = species_search.species_here(*BEND, limit=1, taxon_id=DEER['taxon_id'])['taxon'] + assert (deer['taxon_id'], deer['here_count'], deer['here_months']) == (DEER['taxon_id'], 1, [7]) + assert species_search.species_here(*BEND, taxon_id=GRASS['taxon_id'])['taxon'] is None, 'seen elsewhere only' + assert species_search.species_here(30.0, -140.0) == { + 'taxon': None, 'bbox': pytest.approx([-140.0, 30.0, -139.9, 30.1]), 'species_count': 0, 'species': []} + + +def test_old_packs_have_no_months(test_directory, make_species_pack): + """Packs built before months were kept still work, without months.""" + make_species_pack('us-west', [{**ASPEN, 'points': [(*BEND, 5)]}], months=False) + assert species_search.get_species(1)['months'] == [0] * 12 + assert species_search.search_species(q='aspen')[0]['obs_count'] == 1 + here = species_search.species_here(*BEND) + assert [(i['taxon_id'], i['here_count'], i['here_months']) for i in here['species']] == [(1, 1, [])] + + +@pytest.mark.asyncio +async def test_species_here_api(async_client, dated_packs): + request, response = await async_client.get('/api/map/species/here', + params={'lat': BEND[0], 'lon': BEND[1], 'taxon_id': DEER['taxon_id']}) + assert response.status_code == HTTPStatus.OK + assert response.json['taxon']['here_months'] == [7] + assert response.json['species'][0]['common_name'] == 'quaking aspen' + assert response.json['species'][0]['here_months'] == [5, 10] + + for params in ({}, {'lat': BEND[0]}, {'lat': 'x', 'lon': 0}, {'lat': 91, 'lon': 0}, {'lat': 0, 'lon': 0, 'limit': 0}): + request, response = await async_client.get('/api/map/species/here', params=params) + assert response.status_code == HTTPStatus.BAD_REQUEST, params + + +# --- Review fixes -------------------------------------------------------------------------------------------------- + + +def test_only_newest_version_counted(test_directory, make_species_pack): + """An older version of a region left beside the newer one is not counted again.""" + make_species_pack('us-west', [{**ASPEN, 'points': [BEND] * 3}], version='20261023') + make_species_pack('us-west', [{**ASPEN, 'points': [BEND] * 5}], version='20261123') + assert [i['version'] for i in lib.get_species_files()] == ['20261123'] + aspen = species_search.get_species(1) + assert aspen['obs_count'] == 5 + assert aspen['regions'] == ['us-west'] + assert species_search.search_species(lat=BEND[0], lon=BEND[1])[0]['near_count'] == 5 + + +def test_names_from_any_pack(test_directory, make_species_pack): + """A name one region's pack lacks is taken from another's; the newest pack's name wins.""" + make_species_pack('us-west', [{**ASPEN, 'common_name': None, 'wiki_title': None, 'points': [BEND]}], + version='20261123') + make_species_pack('us-central', [{**ASPEN, 'common_name': 'quaking aspen', 'points': [DENVER]}], + version='20261023') + aspen = species_search.get_species(1) + assert (aspen['common_name'], aspen['wiki_title']) == ('quaking aspen', 'one') + + +def test_other_names_searchable(test_directory, make_species_pack): + make_species_pack('us-west', [{**ASPEN, 'other_names': 'trembling aspen; popple', 'points': [BEND]}]) + found, = species_search.search_species(q='popple') + assert found['taxon_id'] == 1 + assert found['other_names'] == 'trembling aspen; popple' + + +def test_bbox_across_antimeridian(test_directory, make_species_pack): + """A species in packs on both sides of the antimeridian has no bbox, not one the long way around the world.""" + make_species_pack('russia-east', [{**DEER, 'points': [(60.0, 179.5)]}]) + make_species_pack('us-alaska', [{**DEER, 'points': [(60.0, -179.5)]}]) + deer = species_search.get_species(DEER['taxon_id']) + assert deer['bbox'] is None + assert species_search.get_species_range(DEER['taxon_id'])['count'] == 2 + + +def test_wikipedia_zims_prefer_all(test_session, test_directory, zim_factory): + """Within a flavor, all of Wikipedia comes before a newer selection of it.""" + top = zim_factory('wikipedia_en_top_maxi_2026-06.zim') + everything = zim_factory('wikipedia_en_all_maxi_2026-01.zim') + nopic = zim_factory('wikipedia_en_all_nopic_2026-06.zim') + test_session.commit() + assert species_search.wikipedia_zims(test_session) == [everything, top, nopic] + + +@pytest.mark.asyncio +async def test_wikipedia_stops_at_first_article(test_session, test_directory, zim_factory): + """Zims are opened one at a time, best first, until one has the article.""" + zim_factory('wikipedia_en_all_maxi_2026-01.zim') + zim_factory('wikipedia_en_all_mini_2026-01.zim') + test_session.commit() + with mock.patch('modules.map.species_search.run_libzim_jobs', + mock.AsyncMock(return_value=[{'found': 'one', 'title': 'One'}])) as run: + article = await species_search.find_wikipedia_article(test_session, 'one', 'Populus tremuloides') + assert article['path'] == 'one' + run.assert_called_once() + assert run.call_args[0][0][0]['path'].endswith('wikipedia_en_all_maxi_2026-01.zim') + + +def test_planet_pack_is_read_alone(test_directory, make_species_pack): + """With the planet pack downloaded, the regions' packs (which it holds) are not read too.""" + make_species_pack('us-west', [{**ASPEN, 'points': [BEND] * 3}]) + make_species_pack('planet', [{**ASPEN, 'points': [BEND] * 3 + [DENVER]}]) + aspen = species_search.get_species(1) + assert (aspen['obs_count'], aspen['regions']) == (4, ['planet']) + assert species_search.search_species(lat=BEND[0], lon=BEND[1])[0]['near_count'] == 3 + + +def test_overlapping_regions_not_counted_twice(test_directory, make_species_pack): + """Regions overlap (us-west and mexico both hold southern Arizona): a square both hold is counted once, not twice.""" + tucson = (32.22, -110.97) + make_species_pack('us-west', [{**DEER, 'points': [tucson] * 4 + [BEND]}]) + make_species_pack('mexico', [{**DEER, 'points': [tucson] * 4}]) + found, = species_search.search_species(lat=tucson[0], lon=tucson[1]) + assert found['near_count'] == 4 + here = species_search.species_here(*tucson)['species'][0] + assert here['here_count'] == 4 + # Elsewhere one pack holds the square: its counts are its own. + assert species_search.search_species(lat=BEND[0], lon=BEND[1])[0]['near_count'] == 1 diff --git a/modules/zim/libzim_worker.py b/modules/zim/libzim_worker.py index f48466d6..180d36ad 100644 --- a/modules/zim/libzim_worker.py +++ b/modules/zim/libzim_worker.py @@ -12,6 +12,7 @@ Reads `{"jobs": [...]}` from stdin and writes one result per job, in order, to s {"op": "search", "search_str": ..., "offset": ..., "limit": ...} -> {"estimate": int, "entries": [{"path", "title", "content"}]} {"op": "entries", "paths": [...]} -> {"entries": [{"path", "title", "content"}]} + {"op": "find", "paths": [...]} -> {"found": path or None, "title": str or None} {"op": "metadata"} -> {} (with the metadata below) Any job may add `"metadata": true` to also get the Zim's metadata. A job that fails returns `{"error": str}` @@ -74,6 +75,18 @@ def run_job(job: dict) -> dict: result['entries'] = [entry_dict(archive, i) for i in paths] elif op == 'entries': result['entries'] = [entry_dict(archive, i) for i in job['paths']] + elif op == 'find': + # The first of `paths` that is an entry, following a redirect. + result['found'] = result['title'] = None + for path in job['paths']: + try: + entry = archive.get_entry_by_path(path) + except KeyError: + continue + if entry.is_redirect: + entry = entry.get_redirect_entry() + result['found'], result['title'] = entry.path, entry.title + break elif op == 'metadata': job['metadata'] = True else: diff --git a/wrolpi/scripts/build_inat_regions.py b/wrolpi/scripts/build_inat_regions.py new file mode 100644 index 00000000..c1cae6e8 --- /dev/null +++ b/wrolpi/scripts/build_inat_regions.py @@ -0,0 +1,554 @@ +#!/usr/bin/env python3 +"""Build the iNaturalist species packs: one `inat--.species.db` for each map region, and a signed +manifest, for the CDN. + +Usage: + python wrolpi/scripts/build_inat_regions.py [--regions us-west,us-central] + [--dwca FILE] [--taxa FILE] [--taxonomy FILE] [--cdn-base URL] + [--version YYYYMMDD] [--reuse-split] [--no-sign] + +Run by the maintainers, monthly, on a machine with the Internet and ~200 GB free. WROLPi devices never contact +iNaturalist or Wikidata; they download these packs. + +Sources: + - iNaturalist Research-grade Observations, the Darwin Core Archive iNaturalist publishes weekly for GBIF (~30 GB zip, + `observations.csv` inside is ~120 GB). Only observations under CC0, CC BY or CC BY-NC; the packs are therefore + CC BY-NC 4.0. https://doi.org/10.15468/ab3s5x + - iNaturalist's taxa table (Open Data on AWS, ~40 MB), for rolling subspecies up to their species and for groups. + - iNaturalist's taxonomy Darwin Core Archive (~80 MB): each species' English common name, the one iNaturalist + shows. Taxonomic information carries no license. + - Wikidata (P3151, the iNaturalist taxon id): each species' English Wikipedia article, and a common name for species + iNaturalist has none for. Answers are cached in , so a monthly build only asks about new species. + +Steps: + 1. Download the sources into (skipped when the file there is already the published size). + 2. One streamed pass over the observations (or, with --reuse-split, the work files of the last build): keep those + with coordinates, roll each up to its species, and append it to the work file of every region whose bbox + contains it (map regions overlap, some widely), and once to the planet's. + 3. Ask Wikidata about every species found. + 4. For each region: count, grid and compress (see modules/map/species.py) into its species.db. + The planet (`inat-planet-.species.db`) is built like a region, from each observation once; its work + is split into PLANET_BUCKETS files by species, built one at a time, so it fits in memory. + 5. sha256 + signed meta4 of each pack, and the signed manifest.json. Upload to the CDN base. +""" +import argparse +import collections +import csv +import datetime +import gzip +import io +import json +import os +import re +import sqlite3 +import subprocess +import sys +import time +import urllib.parse +import zipfile +from pathlib import Path +from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union + +import requests + +# Add project root to path so we can import the map module. +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from modules.map.catalog import MAP_REGIONS +from modules.map.species import (GROUPS, HIGH_GRID, LOOKUP_GRID, LOW_GRID, PLANET, SCHEMA, SPECIES_DB_SUFFIX, cell_id, + encode_cells, encode_months, month_bit, pack_name, parse_pack_name) +from wrolpi.scripts.build_map_regions import format_size, sign_manifest, write_meta4 + +DWCA_URL = 'https://static.inaturalist.org/observations/gbif-observations-dwca.zip' +TAXA_URL = 'https://inaturalist-open-data.s3.amazonaws.com/taxa.csv.gz' +TAXONOMY_URL = 'https://www.inaturalist.org/taxa/inaturalist-taxonomy.dwca.zip' +DEFAULT_CDN_BASE = 'https://wrolpi.nyc3.cdn.digitaloceanspaces.com/maps/inat' +SPARQL_URL = 'https://query.wikidata.org/sparql' +USER_AGENT = 'WROLPi' +SPARQL_BATCH_SIZE = 300 +SPARQL_DELAY = 1 # seconds between batches. + +LICENSE = 'CC BY-NC 4.0' +ATTRIBUTION = ('Observations: iNaturalist contributors, iNaturalist Research-grade Observations ' + '(https://doi.org/10.15468/ab3s5x). Common names: iNaturalist. Articles: Wikidata.') + +# An observation is precise when iNaturalist withheld nothing and its uncertainty is at most this. Only precise +# observations make the high grid dots and the species' bbox; the low grid and the counts use every observation. +PRECISE_METERS = 5000 + +# Keys of the in-memory sets: species * KEY_SPAN + cell. The high grid has 9,000 x 18,000 cells. +KEY_SPAN = 1 << 28 + +# The planet is every observation once. Its work is split into this many files by species, and built a file at a time, +# so its sets fit in memory (all at once they would be ~25 GB). +PLANET_BUCKETS = 8 +PLANET_BBOX = (-180.0, -90.0, 180.0, 90.0) + + +# --- sources ---------------------------------------------------------------------------------------------------------- + + +def download(url: str, destination: Path): + """Download a file, unless `destination` already is the size the server reports.""" + response = requests.head(url, allow_redirects=True, headers={'User-Agent': USER_AGENT}, timeout=60) + response.raise_for_status() + size = int(response.headers.get('Content-Length') or 0) + if destination.is_file() and size and destination.stat().st_size == size: + print(f'Already downloaded: {destination.name} ({format_size(size)})') + return + print(f'Downloading {url} ({format_size(size)})...', flush=True) + partial = destination.with_name(f'{destination.name}.partial') + subprocess.run(['aria2c', '-q', '-x4', '-s4', '-U', USER_AGENT, '--file-allocation=none', '--allow-overwrite=true', + '-d', str(destination.parent), '-o', partial.name, url], check=True) + partial.rename(destination) + + +def dwca_version(dwca_path: Path) -> str: + """YYYYMMDD of the archive's publication date (eml.xml `pubDate`).""" + with zipfile.ZipFile(dwca_path) as zf: + eml = zf.read('eml.xml').decode() + match = re.search(r'\s*(\d{4})-(\d{2})-(\d{2})', eml) + if not match: + raise ValueError(f'No pubDate in {dwca_path}') + return ''.join(match.groups()) + + +def load_english_names(taxonomy_path: Path) -> Dict[int, List[str]]: + """Each taxon's English names from iNaturalist's taxonomy archive, in the order it lists them. + + The archive has no "preferred" column, and its order is not by preference among the names without a place; but + the first listed is the name iNaturalist shows for the birds and butterflies checked (American Robin, not the later + alias "Robin Redbreast"; Monarch Butterfly, not "Wanderer"), so it is the common name. Every name is searchable.""" + names = collections.defaultdict(list) + with zipfile.ZipFile(taxonomy_path) as zf, zf.open('VernacularNames-english.csv') as fh: + for row in csv.DictReader(io.TextIOWrapper(fh, encoding='utf-8', newline='')): + name = row['vernacularName'].strip() + if not name or not row['id'].isdigit(): + continue + listed = names[int(row['id'])] + if name.lower() not in (i.lower() for i in listed): + listed.append(name) + return dict(names) + + +class Taxa: + """iNaturalist's taxa table: each species of a taxon, and each species' group.""" + + def __init__(self, rows: Dict[int, Tuple[str, str, str]]): + # taxon_id -> (ancestry "1/2/3", rank, name) + self.rows = rows + self._species = dict() + + @classmethod + def load(cls, taxa_path: Path) -> 'Taxa': + rows = dict() + with gzip.open(taxa_path, 'rt', newline='') as fh: + for row in csv.DictReader(fh, delimiter='\t'): + rows[int(row['taxon_id'])] = (row['ancestry'] or '', row['rank'], row['name']) + return cls(rows) + + def species_of(self, taxon_id: int) -> Optional[int]: + """The species of a taxon: itself, the species above a subspecies/variety/..., or None above species.""" + try: + return self._species[taxon_id] + except KeyError: + pass + species = None + row = self.rows.get(taxon_id) + if row: + if row[1] == 'species': + species = taxon_id + else: + for ancestor in reversed(row[0].split('/') if row[0] else []): + ancestor_row = self.rows.get(int(ancestor)) + if ancestor_row and ancestor_row[1] == 'species': + species = int(ancestor) + break + self._species[taxon_id] = species + return species + + def group_of(self, taxon_id: int) -> int: + ancestry = set(self.rows[taxon_id][0].split('/')) + for group_taxon_id, code, _ in GROUPS: + if str(group_taxon_id) in ancestry: + return code + return 0 + + def name_of(self, taxon_id: int) -> str: + return self.rows[taxon_id][2] + + +# --- regions ---------------------------------------------------------------------------------------------------------- + + +def bbox_regions(regions: List[dict] = None) -> List[Tuple[str, Tuple[float, float, float, float]]]: + """(region, (min_lon, min_lat, max_lon, max_lat)) of each map region that has a bbox.""" + regions = MAP_REGIONS if regions is None else regions + return [(r['region'], tuple(float(i) for i in r['bbox'].split(','))) for r in regions if r.get('bbox')] + + +def regions_containing(lat: float, lon: float, regions) -> Iterator[str]: + for name, (min_lon, min_lat, max_lon, max_lat) in regions: + if min_lon <= lon <= max_lon and min_lat <= lat <= max_lat: + yield name + + +def observation_month(event_date: str) -> int: + """The month (1-12) of an observation's `eventDate` (ISO 8601, e.g. 2025-09-04T14:22:00+02:00), else 0.""" + month = event_date[5:7] + if event_date[4:5] == '-' and month.isdigit() and 1 <= int(month) <= 12: + return int(month) + return 0 + + +def read_observations(dwca_path: Path) -> Iterator[Tuple[float, float, int, bool, int]]: + """(lat, lon, taxon_id, precise, month) of each observation in the archive which has coordinates.""" + csv.field_size_limit(16 * 1024 * 1024) + with zipfile.ZipFile(dwca_path) as zf, zf.open('observations.csv') as raw: + reader = csv.reader(io.TextIOWrapper(raw, encoding='utf-8', newline='')) + index = {name: i for i, name in enumerate(next(reader))} + i_lat, i_lon = index['decimalLatitude'], index['decimalLongitude'] + i_uncertainty, i_taxon, i_withheld = (index['coordinateUncertaintyInMeters'], index['taxonID'], + index['informationWithheld']) + i_date = index['eventDate'] + for row in reader: + if not row[i_lat] or not row[i_lon] or not row[i_taxon]: + continue + try: + lat, lon, taxon_id = float(row[i_lat]), float(row[i_lon]), int(row[i_taxon]) + uncertainty = float(row[i_uncertainty]) if row[i_uncertainty] else 0 + except ValueError: + continue + precise = not row[i_withheld] and uncertainty <= PRECISE_METERS + yield lat, lon, taxon_id, precise, observation_month(row[i_date]) + + +def split_by_region(observations: Iterable[Tuple[float, float, int, bool, int]], taxa: Taxa, regions, + work_dir: Path, planet: bool = False) -> Dict[str, List[Path]]: + """Append each observation, as its species, to the work file of each region containing it, and with `planet` once + to one of the planet's work files (the species decides which). + + Returns the work files of each region that received any.""" + paths = {name: work_dir / f'{name}.tsv' for name, _ in regions} + buckets = [work_dir / f'{PLANET}-{i}.tsv' for i in range(PLANET_BUCKETS)] if planet else [] + files = {name: open(path, 'w') for name, path in paths.items()} + bucket_files = [open(path, 'w') for path in buckets] + used = set() + start = time.time() + total = kept = 0 + try: + for lat, lon, taxon_id, precise, month in observations: + total += 1 + if total % 10_000_000 == 0: + print(f' {total:,} observations, {kept:,} kept, {time.time() - start:.0f}s', flush=True) + species = taxa.species_of(taxon_id) + if species is None: + continue + line = f'{lat}\t{lon}\t{species}\t{1 if precise else 0}\t{month}\n' + in_region = False + for name in regions_containing(lat, lon, regions): + in_region = True + files[name].write(line) + used.add(name) + kept += in_region + if bucket_files: + bucket_files[species % PLANET_BUCKETS].write(line) + finally: + for fh in [*files.values(), *bucket_files]: + fh.close() + for name, path in paths.items(): + if name not in used: + path.unlink() + print(f'{total:,} observations, {kept:,} of a species in a region, {time.time() - start:.0f}s') + found = {name: [path] for name, path in paths.items() if name in used} + if buckets: + found[PLANET] = buckets + return found + + +# --- Wikidata --------------------------------------------------------------------------------------------------------- + + +def parse_wikidata_bindings(bindings: List[dict]) -> Dict[str, dict]: + """taxon_id -> {'title': enwiki title, 'common': English common name} from SPARQL results. The first title and + common name of a taxon win.""" + found = collections.defaultdict(dict) + for binding in bindings: + taxon_id = binding.get('inat', {}).get('value') + if not taxon_id: + continue + entry = found[taxon_id] + article = binding.get('article', {}).get('value') + if article and 'title' not in entry and '/wiki/' in article: + entry['title'] = urllib.parse.unquote(article.rsplit('/wiki/', 1)[1]) + common = binding.get('common', {}).get('value') + if common and 'common' not in entry: + entry['common'] = common + return dict(found) + + +def query_wikidata(taxon_ids: List[str]) -> List[dict]: + values = ' '.join(f'"{i}"' for i in taxon_ids) + sparql = f'''SELECT ?inat ?article ?common WHERE {{ + VALUES ?inat {{ {values} }} + ?item wdt:P3151 ?inat . + OPTIONAL {{ ?article schema:about ?item ; schema:isPartOf . }} + OPTIONAL {{ ?item wdt:P1843 ?common . FILTER(LANG(?common) = "en") }} + }}''' + response = requests.post(SPARQL_URL, data={'query': sparql, 'format': 'json'}, + headers={'User-Agent': USER_AGENT, 'Accept': 'application/sparql-results+json'}, + timeout=120) + response.raise_for_status() + return response.json().get('results', {}).get('bindings', []) + + +def _query_batch(taxon_ids: List[str], query: Callable, delay: float, + min_batch: int = 10) -> Tuple[List[dict], List[str]]: + """Query a batch, splitting it in half when it fails. Returns the bindings, and the taxa that were answered (a + taxon in a batch that failed even at the smallest size was not).""" + try: + return query(taxon_ids), list(taxon_ids) + except Exception as e: + if len(taxon_ids) <= min_batch: + print(f' WARNING: Wikidata batch of {len(taxon_ids)} failed, skipping: {e}', flush=True) + return [], [] + middle = len(taxon_ids) // 2 + time.sleep(delay) + left, left_answered = _query_batch(taxon_ids[:middle], query, delay, min_batch) + time.sleep(delay) + right, right_answered = _query_batch(taxon_ids[middle:], query, delay, min_batch) + return left + right, left_answered + right_answered + + +def fetch_wikidata(taxon_ids: Iterable[int], cache_path: Path, query: Callable = None, + delay: float = SPARQL_DELAY) -> Dict[str, dict]: + """taxon_id (str) -> {'title', 'common'} (either may be missing) for every taxon. Answers are cached in + `cache_path`, a taxon without any is cached too; a failed batch is not, so the next build asks again.""" + query = query or query_wikidata + cache = json.loads(cache_path.read_text()) if cache_path.is_file() else dict() + todo = sorted({str(i) for i in taxon_ids} - set(cache)) + print(f'Wikidata: {len(todo):,} species to look up ({len(cache):,} cached)', flush=True) + for start in range(0, len(todo), SPARQL_BATCH_SIZE): + batch = todo[start:start + SPARQL_BATCH_SIZE] + bindings, answered = _query_batch(batch, query, delay) + found = parse_wikidata_bindings(bindings) + for taxon_id in answered: + cache[taxon_id] = found.get(taxon_id, dict()) + if answered: + cache_path.write_text(json.dumps(cache)) + if start + SPARQL_BATCH_SIZE < len(todo): + time.sleep(delay) + return cache + + +# --- packs ------------------------------------------------------------------------------------------------------------ + + +def species_in(region_path: Path) -> set: + with open(region_path) as fh: + return {int(line.split('\t', 3)[2]) for line in fh} + + +def build_pack(work_files: Union[Path, List[Path]], region: str, bbox, taxa: Taxa, wikidata: Dict[str, dict], + version: str, db_path: Path, english_names: Dict[int, List[str]] = None) -> dict: + """Write a region's species.db from its work files. Returns its statistics. + + The work files are written into the pack one at a time, and no species may be in two of them (the planet's are + split by species), so only one file's observations are in memory at once. A species' common name is the first of + iNaturalist's (`english_names`), else Wikidata's; its other names are searchable.""" + work_files = [work_files] if isinstance(work_files, Path) else list(work_files) + if db_path.exists(): + db_path.unlink() + db = sqlite3.connect(db_path) + stats = collections.Counter() + try: + db.executescript(SCHEMA) + for path in work_files: + stats.update(_add_work_file(db, path, taxa, wikidata, english_names or dict())) + meta = dict( + version=version, + region=region, + bbox=','.join(str(i) for i in bbox), + source='iNaturalist Research-grade Observations (GBIF DwC-A)', + license=LICENSE, + attribution=ATTRIBUTION, + low_grid=LOW_GRID, + high_grid=HIGH_GRID, + lookup_grid=LOOKUP_GRID, + precise_meters=PRECISE_METERS, + observations=stats['observations'], + built=datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds'), + ) + db.executemany('INSERT INTO meta (key, value) VALUES (?, ?)', [(k, str(v)) for k, v in meta.items()]) + db.execute("INSERT INTO species_fts (species_fts) VALUES ('rebuild')") + db.commit() + db.execute('VACUUM') + finally: + db.close() + return dict(stats, size=db_path.stat().st_size) + + +def _add_work_file(db: sqlite3.Connection, path: Path, taxa: Taxa, wikidata: Dict[str, dict], + english_names: Dict[int, List[str]]) -> dict: + """Write the species of one work file, and their lookup cells, into a pack. Returns their statistics.""" + counts = collections.Counter() + low, high = set(), set() + lookup = collections.Counter() + # Months: of each species (twelve counts), and of each lookup cell of each species (a bit per month). + months = collections.defaultdict(lambda: [0] * 12) + lookup_months = collections.Counter() + bboxes = dict() + precise_count = 0 + with open(path) as fh: + for line in fh: + # Work files written before months were kept have no month. + lat, lon, species, precise, month = (line.rstrip('\n').split('\t') + ['0'])[:5] + lat, lon, species, month = float(lat), float(lon), int(species), int(month) + counts[species] += 1 + key = species * KEY_SPAN + low.add(key + cell_id(lat, lon, LOW_GRID)) + lookup_key = key + cell_id(lat, lon, LOOKUP_GRID) + lookup[lookup_key] += 1 + if month: + months[species][month - 1] += 1 + lookup_months[lookup_key] |= month_bit(month) + if precise == '1': + precise_count += 1 + high.add(key + cell_id(lat, lon, HIGH_GRID)) + b = bboxes.get(species) + bboxes[species] = (lat, lon, lat, lon) if b is None else ( + min(b[0], lat), min(b[1], lon), max(b[2], lat), max(b[3], lon)) + + low_cells, high_cells = collections.defaultdict(list), collections.defaultdict(list) + for keys, cells in ((low, low_cells), (high, high_cells)): + for key in keys: + species, cell = divmod(key, KEY_SPAN) + cells[species].append(cell) + + rows = [] + for species, count in counts.items(): + wiki = wikidata.get(str(species)) or dict() + high_blob = encode_cells(high_cells[species]) if species in high_cells else None + names = list(english_names.get(species) or []) + if wiki.get('common') and wiki['common'].lower() not in (i.lower() for i in names): + names.append(wiki['common']) + rows.append((species, taxa.name_of(species), names[0] if names else None, wiki.get('title'), + taxa.group_of(species), count, *(bboxes.get(species) or (None, None, None, None)), + encode_cells(low_cells[species]), high_blob, + encode_months(months[species]) if species in months else None, + '; '.join(names[1:]) or None)) + db.executemany('INSERT INTO species VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)', rows) + db.executemany('INSERT INTO cell_species (cell, taxon_id, obs_count, months) VALUES (?, ?, ?, ?)', + ((key % KEY_SPAN, key // KEY_SPAN, n, lookup_months.get(key, 0)) for key, n in lookup.items())) + db.commit() + return dict(species=len(counts), observations=sum(counts.values()), precise=precise_count, + low_dots=len(low), high_dots=len(high), lookup_rows=len(lookup)) + + +def write_manifest(output_dir: Path, version: str, cdn_base: str, packs: Dict[str, Path], sign: bool = True) -> Path: + """manifest.json: each region's pack URL, size and sha256 (from its signed meta4), then its signature.""" + regions, sizes, hashes = dict(), dict(), dict() + for region, path in sorted(packs.items()): + url = f'{cdn_base}/{version}/{path.name}' + regions[region] = url + sizes[region] = path.stat().st_size + hashes[url] = write_meta4(str(path), url) if sign else None + manifest = dict(version=version, license=LICENSE, attribution=ATTRIBUTION, regions=regions, sizes=sizes, + sha256=hashes) + manifest_path = output_dir / 'manifest.json' + manifest_path.write_text(json.dumps(manifest, indent=2)) + print(f'Manifest written to: {manifest_path}') + if sign: + # gpg asks before replacing a signature, and no one is there to answer: it would wait forever. + manifest_path.with_name(f'{manifest_path.name}.sig').unlink(missing_ok=True) + sign_manifest(str(manifest_path)) + return manifest_path + + +def main(): + parser = argparse.ArgumentParser(description='Build iNaturalist species packs for the map regions.') + parser.add_argument('work_dir', help='Downloads, work files and the Wikidata cache (kept between builds)') + parser.add_argument('output_dir', help='The packs and manifest.json, to upload to --cdn-base') + parser.add_argument('--regions', help=f'Comma separated map regions, and/or {PLANET!r} (default: all of them)') + parser.add_argument('--dwca', help='Use this DwC-A zip instead of downloading it') + parser.add_argument('--taxa', help='Use this taxa.csv.gz instead of downloading it') + parser.add_argument('--taxonomy', help='Use this taxonomy DwC-A zip instead of downloading it') + parser.add_argument('--cdn-base', default=DEFAULT_CDN_BASE) + parser.add_argument('--version', help="The packs' version (YYYYMMDD), instead of the observations' publication " + 'date; to publish a rebuild of the same observations') + parser.add_argument('--reuse-split', action='store_true', + help="Use the region work files of the last build instead of reading the observations") + parser.add_argument('--no-sign', action='store_true', help='Skip the meta4 files and signatures (testing)') + args = parser.parse_args() + + work_dir, output_dir = Path(args.work_dir), Path(args.output_dir) + work_dir.mkdir(parents=True, exist_ok=True) + regions = bbox_regions() + planet = True + if args.regions: + wanted = set(args.regions.split(',')) + unknown = wanted - {name for name, _ in regions} - {PLANET} + if unknown: + parser.error(f'Unknown regions: {", ".join(sorted(unknown))}') + regions = [r for r in regions if r[0] in wanted] + planet = PLANET in wanted + + dwca_path = Path(args.dwca) if args.dwca else work_dir / 'gbif-observations-dwca.zip' + taxa_path = Path(args.taxa) if args.taxa else work_dir / 'taxa.csv.gz' + taxonomy_path = Path(args.taxonomy) if args.taxonomy else work_dir / 'inaturalist-taxonomy.dwca.zip' + if not args.dwca: + download(DWCA_URL, dwca_path) + if not args.taxa: + download(TAXA_URL, taxa_path) + if not args.taxonomy: + download(TAXONOMY_URL, taxonomy_path) + version = args.version or dwca_version(dwca_path) + if not re.fullmatch(r'\d{8}', version): + parser.error(f'The version must be YYYYMMDD, not {version!r}') + print(f'Version {version}') + pack_dir = output_dir / version + pack_dir.mkdir(parents=True, exist_ok=True) + + taxa = Taxa.load(taxa_path) + region_dir = work_dir / 'regions' + region_dir.mkdir(exist_ok=True) + if args.reuse_split: + region_paths = {name: [region_dir / f'{name}.tsv'] for name, _ in regions + if (region_dir / f'{name}.tsv').is_file()} + buckets = [region_dir / f'{PLANET}-{i}.tsv' for i in range(PLANET_BUCKETS)] + if planet and all(i.is_file() for i in buckets): + region_paths[PLANET] = buckets + if not region_paths: + parser.error(f'--reuse-split: no region work files in {region_dir}') + print(f'Reusing the work files of {len(region_paths)} regions') + else: + region_paths = split_by_region(read_observations(dwca_path), taxa, regions, region_dir, planet=planet) + english_names = load_english_names(taxonomy_path) + print(f'{len(english_names):,} taxa with English names') + + all_species = set() + for paths in region_paths.values(): + for path in paths: + all_species |= species_in(path) + wikidata = fetch_wikidata(all_species, work_dir / 'wikidata.json') + + packs = dict() + bboxes = {**dict(regions), PLANET: PLANET_BBOX} + for region, paths in region_paths.items(): + start = time.time() + db_path = pack_dir / pack_name(region, version) + stats = build_pack(paths, region, bboxes[region], taxa, wikidata, version, db_path, english_names) + packs[region] = db_path + print(f'{region}: {stats["species"]:,} species, {stats["observations"]:,} observations, ' + f'{format_size(stats["size"])}, {time.time() - start:.0f}s', flush=True) + + # Every pack of this version, also those of an earlier run (e.g. the regions, when only the planet was built). + for path in pack_dir.glob(f'*-{version}{SPECIES_DB_SUFFIX}'): + if parsed := parse_pack_name(path.name): + packs.setdefault(parsed[0], path) + write_manifest(output_dir, version, args.cdn_base, packs, sign=not args.no_sign) + print(f'\nUpload the contents of {output_dir} to {args.cdn_base}') + + +if __name__ == '__main__': + main()