Coverage for app / documents / visuals / maps / outlines.py: 96%

53 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""Natural Earth's country and lake outlines, packed in svc-ai's image. 

2 

3A PDF fetches nothing, so a map's basemap is these: public-domain outlines 

4at 1:110m and 1:50m (``data/natural_earth.bin``, built by 

5``dev/build_natural_earth.py``; its source and digest in 

6``data/NATURAL_EARTH.md``). Loaded once, lazily, behind a lock — PDFs are 

7rendered in a thread pool — and read part by part: only the parts whose 

8bounding box meets the view are decoded. 

9""" 

10 

11from __future__ import annotations 

12 

13import json 

14import sys 

15import threading 

16import zlib 

17from array import array 

18from dataclasses import dataclass 

19from itertools import accumulate 

20from pathlib import Path 

21 

22DATA = Path(__file__).with_name("data") / "natural_earth.bin" 

23#: The packed format this reads (``dev/build_natural_earth.py`` ``FORMAT``). 

24FORMAT = 1 

25CREDIT = "Outlines: Natural Earth" 

26 

27 

28@dataclass(frozen=True) 

29class Part: 

30 """One polygon of a layer: its bounding box in degrees, and its rings 

31 (the outer first) as offsets into the packed points.""" 

32 

33 min_lng: float 

34 min_lat: float 

35 max_lng: float 

36 max_lat: float 

37 rings: tuple[tuple[int, int], ...] 

38 

39 def meets(self, lng0: float, lat0: float, lng1: float, lat1: float) -> bool: 

40 return not ( 

41 self.max_lng < lng0 

42 or self.min_lng > lng1 

43 or self.max_lat < lat0 

44 or self.min_lat > lat1 

45 ) 

46 

47 

48class Outlines: 

49 def __init__(self, data: bytes) -> None: 

50 payload = zlib.decompress(data) 

51 newline = payload.index(b"\n") 

52 header = json.loads(payload[:newline]) 

53 if header.get("format") != FORMAT: 

54 raise ValueError(f"natural_earth.bin is format {header.get('format')}") 

55 self.version = str(header.get("version")) 

56 quantum = float(header["quantum"]) 

57 self._quantum = quantum 

58 values = array("i") 

59 values.frombytes(payload[newline + 1 :]) 

60 if sys.byteorder != "little": 

61 values.byteswap() 

62 self._values = values 

63 self.layers: dict[str, list[Part]] = { 

64 name: [ 

65 Part( 

66 x0 / quantum, 

67 y0 / quantum, 

68 x1 / quantum, 

69 y1 / quantum, 

70 tuple((offset, count) for offset, count in rings), 

71 ) 

72 for x0, y0, x1, y1, rings in parts 

73 ] 

74 for name, parts in header["layers"].items() 

75 } 

76 

77 def parts( 

78 self, layer: str, lng0: float, lat0: float, lng1: float, lat1: float 

79 ) -> list[Part]: 

80 """The layer's parts whose bounding box meets the view.""" 

81 return [ 

82 p for p in self.layers.get(layer, []) if p.meets(lng0, lat0, lng1, lat1) 

83 ] 

84 

85 def ring(self, offset: int, count: int) -> list[tuple[float, float]]: 

86 """A ring's points, ``(lng, lat)``: the first absolute, the rest 

87 added up from their differences.""" 

88 chunk = self._values[2 * offset : 2 * (offset + count)] 

89 q = self._quantum 

90 xs = accumulate(chunk[0::2]) 

91 ys = accumulate(chunk[1::2]) 

92 return [(x / q, y / q) for x, y in zip(xs, ys)] 

93 

94 

95_LOCK = threading.Lock() 

96_LOADED: Outlines | None = None 

97 

98 

99def load() -> Outlines: 

100 global _LOADED 

101 if _LOADED is None: 

102 with _LOCK: 

103 if _LOADED is None: 

104 _LOADED = Outlines(DATA.read_bytes()) 

105 return _LOADED