File size: 2,384 Bytes
f44e04f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""Populated places (Natural Earth 1:10m, public domain): searching by name and naming a location."""

from __future__ import annotations

import csv
import functools
from pathlib import Path

import numpy as np

PLACES_CSV = Path(__file__).with_name("places.csv")
EARTH_KM = 6371.0


@functools.lru_cache(maxsize=1)
def table() -> dict[str, np.ndarray]:
    with open(PLACES_CSV, newline="") as fh:
        rows = list(csv.DictReader(fh))
    return {
        "label": np.array([f"{r['name']}, {r['country']}" for r in rows]),
        "lat": np.array([float(r["lat"]) for r in rows]),
        "lon": np.array([float(r["lon"]) for r in rows]),
        "population": np.array([int(r["population"]) for r in rows]),
    }


def labels() -> list[str]:
    """Place labels, most populated first (unique)."""
    seen, out = set(), []
    for label in table()["label"]:
        if label not in seen:
            seen.add(label)
            out.append(label)
    return out


def find(label: str) -> tuple[float, float] | None:
    """(lat, lon) of a place label, or None."""
    t = table()
    hits = np.flatnonzero(t["label"] == label)
    return (float(t["lat"][hits[0]]), float(t["lon"][hits[0]])) if hits.size else None


def distance_km(lat0, lon0, lat1, lon1):
    p0, p1 = np.deg2rad(lat0), np.deg2rad(lat1)
    dlon = np.deg2rad(np.asarray(lon1) - lon0)
    c = np.sin(p0) * np.sin(p1) + np.cos(p0) * np.cos(p1) * np.cos(dlon)
    return EARTH_KM * np.arccos(np.clip(c, -1, 1))


def describe(lat: float, lon: float, min_population: int = 300_000) -> str:
    """A short human name for a location: "near Lisbon, Portugal" or "600 km W of Lisbon, Portugal"."""
    t = table()
    big = t["population"] >= min_population
    d = distance_km(lat, lon, t["lat"][big], t["lon"][big])
    i = int(np.argmin(d))
    name = t["label"][big][i]
    if d[i] < 250:
        return f"near {name}"
    # Bearing from the city to the point, on 8 compass directions.
    p0, p1 = np.deg2rad(t["lat"][big][i]), np.deg2rad(lat)
    dlon = np.deg2rad(lon - t["lon"][big][i])
    bearing = np.degrees(np.arctan2(np.sin(dlon) * np.cos(p1),
                                    np.cos(p0) * np.sin(p1) - np.sin(p0) * np.cos(p1) * np.cos(dlon))) % 360
    compass = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"][int((bearing + 22.5) // 45) % 8]
    return f"{round(d[i], -2):.0f} km {compass} of {name}"