gnsskit 0.4.2__tar.gz → 0.5.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {gnsskit-0.4.2 → gnsskit-0.5.1}/PKG-INFO +36 -5
- {gnsskit-0.4.2 → gnsskit-0.5.1}/README.md +35 -4
- {gnsskit-0.4.2 → gnsskit-0.5.1}/pyproject.toml +1 -1
- {gnsskit-0.4.2 → gnsskit-0.5.1}/pyproject.toml.orig +1 -1
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/__init__.py +12 -1
- gnsskit-0.5.1/src/gnsskit/plot/__init__.py +12 -0
- gnsskit-0.5.1/src/gnsskit/plot/_map.py +233 -0
- gnsskit-0.5.1/src/gnsskit/plot/occupations.py +268 -0
- gnsskit-0.5.1/src/gnsskit/plot/solutions.py +422 -0
- gnsskit-0.5.1/src/gnsskit/plot/visibility.py +130 -0
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/rinex.py +222 -56
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/static/__init__.py +0 -2
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/static/baseline.py +26 -55
- gnsskit-0.5.1/src/gnsskit/static/closure.py +61 -0
- gnsskit-0.4.2/src/gnsskit/static/closure.py +0 -79
- {gnsskit-0.4.2 → gnsskit-0.5.1}/LICENSE +0 -0
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/kinematic/__init__.py +0 -0
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/kinematic/trajectory.py +0 -0
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/ppp/__init__.py +0 -0
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/py.typed +0 -0
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/refsys.py +0 -0
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/rtklib/__init__.py +0 -0
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/rtklib/config.py +0 -0
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/rtklib/pos.py +0 -0
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/rtklib/runner.py +0 -0
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/static/network.py +0 -0
- {gnsskit-0.4.2 → gnsskit-0.5.1}/src/gnsskit/static/solve.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: gnsskit
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.1
|
|
4
4
|
Summary: RTKLIB-based GNSS post-processing toolkit: RINEX tools, RTKLIB wrappers, static baselines and network adjustment, kinematic trajectories
|
|
5
5
|
Keywords: gnss,gps,rtklib,ppk,surveying,least-squares
|
|
6
6
|
Author: Francesco Ioli
|
|
@@ -46,9 +46,16 @@ Shared tools for post-processing GNSS data with [RTKLIB](https://www.rtklib.com/
|
|
|
46
46
|
- **RTKLIB wrappers** (`gnsskit.rtklib`): `RtkConfig`, a typed, immutable set of `rnx2rtkp` options
|
|
47
47
|
(`from_file`, `updated`, `with_options`, `with_base_llh`, `write`); `run_rnx2rtkp` and `find_rnx2rtkp`;
|
|
48
48
|
`read_pos` (llh, xyz and enu `.pos` files).
|
|
49
|
-
- **RINEX** (`gnsskit.rinex`): `rinex_span`, `header_llh`, `trim_rinex`; inspection with
|
|
50
|
-
(span, sampling, gaps, satellites)
|
|
51
|
-
|
|
49
|
+
- **RINEX** (`gnsskit.rinex`): `rinex_span`, `header_llh`, `header_xyz`, `trim_rinex`; inspection with
|
|
50
|
+
`obs_summary` (span, sampling, gaps, satellites) and `read_visibility`; survey occupations with
|
|
51
|
+
`read_occupations` (point, receiver, session, time span and position of every occupation, from the
|
|
52
|
+
file names, a field book or the headers), `sessions_from_overlap` and `flag_stale_headers`.
|
|
53
|
+
- **Plots** (`gnsskit.plot`, needs the `plot` extra): `plot_visibility` (RTKPLOT-style satellite
|
|
54
|
+
visibility), `plot_occupations` (map of where, when and with which receiver every point was
|
|
55
|
+
occupied), `plot_baselines` (baseline network: arrows base -> rover, fixed/float, repeated
|
|
56
|
+
baselines side by side, optional error ellipses) and `plot_pos` (RTKPLOT-like view of a static or
|
|
57
|
+
kinematic `.pos` solution: ground track and E/N/U, satellites and ratio against time, colored by
|
|
58
|
+
solution quality). The maps can be drawn over OpenStreetMap tiles.
|
|
52
59
|
- **Static** (`gnsskit.static`): `solve_static` (one solution over a time window), `process_baseline`
|
|
53
60
|
(static baselines with covariance), baseline IO and `loop_closures` (misclosure of every triangle of baselines); least-squares adjustment of a redundant baseline
|
|
54
61
|
network in `gnsskit.static.network` (needs the `network` extra).
|
|
@@ -63,7 +70,7 @@ With [uv](https://docs.astral.sh/uv/) (recommended), in your project:
|
|
|
63
70
|
```sh
|
|
64
71
|
uv add gnsskit # library
|
|
65
72
|
uv add "gnsskit[network]" # + network adjustment (scipy, pyproj)
|
|
66
|
-
uv add "gnsskit[network,plot]" # +
|
|
73
|
+
uv add "gnsskit[network,plot]" # + visibility plots and occupation maps (matplotlib)
|
|
67
74
|
uv add "gnsskit[all]" # every extra
|
|
68
75
|
uv add git+https://github.com/franioli/gnsskit # development version
|
|
69
76
|
```
|
|
@@ -107,6 +114,30 @@ pos_file = run_rnx2rtkp(rover_obs, base_obs, [nav], config, "out.pos")
|
|
|
107
114
|
pos = read_pos(pos_file)
|
|
108
115
|
```
|
|
109
116
|
|
|
117
|
+
Map of the occupations of a survey, from files named e.g. `s1_A1_gs14.26o`:
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
from gnsskit import find_rinex_obs, plot_occupations, read_occupations
|
|
121
|
+
|
|
122
|
+
occ = read_occupations(
|
|
123
|
+
find_rinex_obs(["rinex"]),
|
|
124
|
+
name_pattern=r"(?P<session>s\d+)_(?P<point>[^_]+)_(?P<receiver>[^.]+)",
|
|
125
|
+
)
|
|
126
|
+
plot_occupations(occ, "occupations.png", stations={"mil": (4421979.92, 718518.37, 4524921.24)},
|
|
127
|
+
basemap=True) # OpenStreetMap tiles: needs internet, falls back to a plain map
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Baseline network and RTKLIB solutions:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
import pandas as pd
|
|
134
|
+
from gnsskit import plot_baselines, plot_pos
|
|
135
|
+
|
|
136
|
+
baselines = pd.read_csv("baselines.csv", dtype={"base": str, "rover": str}) # baselines_to_df
|
|
137
|
+
plot_baselines(baselines, "network.png", fixed={"mil": (4421979.92, 718518.37, 4524921.24)})
|
|
138
|
+
plot_pos("rover.pos", "rover.png") # static or kinematic, llh / xyz / enu
|
|
139
|
+
```
|
|
140
|
+
|
|
110
141
|
See [example/](https://github.com/franioli/gnsskit/tree/main/example) for complete static, kinematic and network adjustment examples.
|
|
111
142
|
|
|
112
143
|
## Contributing
|
|
@@ -12,9 +12,16 @@ Shared tools for post-processing GNSS data with [RTKLIB](https://www.rtklib.com/
|
|
|
12
12
|
- **RTKLIB wrappers** (`gnsskit.rtklib`): `RtkConfig`, a typed, immutable set of `rnx2rtkp` options
|
|
13
13
|
(`from_file`, `updated`, `with_options`, `with_base_llh`, `write`); `run_rnx2rtkp` and `find_rnx2rtkp`;
|
|
14
14
|
`read_pos` (llh, xyz and enu `.pos` files).
|
|
15
|
-
- **RINEX** (`gnsskit.rinex`): `rinex_span`, `header_llh`, `trim_rinex`; inspection with
|
|
16
|
-
(span, sampling, gaps, satellites)
|
|
17
|
-
|
|
15
|
+
- **RINEX** (`gnsskit.rinex`): `rinex_span`, `header_llh`, `header_xyz`, `trim_rinex`; inspection with
|
|
16
|
+
`obs_summary` (span, sampling, gaps, satellites) and `read_visibility`; survey occupations with
|
|
17
|
+
`read_occupations` (point, receiver, session, time span and position of every occupation, from the
|
|
18
|
+
file names, a field book or the headers), `sessions_from_overlap` and `flag_stale_headers`.
|
|
19
|
+
- **Plots** (`gnsskit.plot`, needs the `plot` extra): `plot_visibility` (RTKPLOT-style satellite
|
|
20
|
+
visibility), `plot_occupations` (map of where, when and with which receiver every point was
|
|
21
|
+
occupied), `plot_baselines` (baseline network: arrows base -> rover, fixed/float, repeated
|
|
22
|
+
baselines side by side, optional error ellipses) and `plot_pos` (RTKPLOT-like view of a static or
|
|
23
|
+
kinematic `.pos` solution: ground track and E/N/U, satellites and ratio against time, colored by
|
|
24
|
+
solution quality). The maps can be drawn over OpenStreetMap tiles.
|
|
18
25
|
- **Static** (`gnsskit.static`): `solve_static` (one solution over a time window), `process_baseline`
|
|
19
26
|
(static baselines with covariance), baseline IO and `loop_closures` (misclosure of every triangle of baselines); least-squares adjustment of a redundant baseline
|
|
20
27
|
network in `gnsskit.static.network` (needs the `network` extra).
|
|
@@ -29,7 +36,7 @@ With [uv](https://docs.astral.sh/uv/) (recommended), in your project:
|
|
|
29
36
|
```sh
|
|
30
37
|
uv add gnsskit # library
|
|
31
38
|
uv add "gnsskit[network]" # + network adjustment (scipy, pyproj)
|
|
32
|
-
uv add "gnsskit[network,plot]" # +
|
|
39
|
+
uv add "gnsskit[network,plot]" # + visibility plots and occupation maps (matplotlib)
|
|
33
40
|
uv add "gnsskit[all]" # every extra
|
|
34
41
|
uv add git+https://github.com/franioli/gnsskit # development version
|
|
35
42
|
```
|
|
@@ -73,6 +80,30 @@ pos_file = run_rnx2rtkp(rover_obs, base_obs, [nav], config, "out.pos")
|
|
|
73
80
|
pos = read_pos(pos_file)
|
|
74
81
|
```
|
|
75
82
|
|
|
83
|
+
Map of the occupations of a survey, from files named e.g. `s1_A1_gs14.26o`:
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from gnsskit import find_rinex_obs, plot_occupations, read_occupations
|
|
87
|
+
|
|
88
|
+
occ = read_occupations(
|
|
89
|
+
find_rinex_obs(["rinex"]),
|
|
90
|
+
name_pattern=r"(?P<session>s\d+)_(?P<point>[^_]+)_(?P<receiver>[^.]+)",
|
|
91
|
+
)
|
|
92
|
+
plot_occupations(occ, "occupations.png", stations={"mil": (4421979.92, 718518.37, 4524921.24)},
|
|
93
|
+
basemap=True) # OpenStreetMap tiles: needs internet, falls back to a plain map
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Baseline network and RTKLIB solutions:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
import pandas as pd
|
|
100
|
+
from gnsskit import plot_baselines, plot_pos
|
|
101
|
+
|
|
102
|
+
baselines = pd.read_csv("baselines.csv", dtype={"base": str, "rover": str}) # baselines_to_df
|
|
103
|
+
plot_baselines(baselines, "network.png", fixed={"mil": (4421979.92, 718518.37, 4524921.24)})
|
|
104
|
+
plot_pos("rover.pos", "rover.png") # static or kinematic, llh / xyz / enu
|
|
105
|
+
```
|
|
106
|
+
|
|
76
107
|
See [example/](https://github.com/franioli/gnsskit/tree/main/example) for complete static, kinematic and network adjustment examples.
|
|
77
108
|
|
|
78
109
|
## Contributing
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
from importlib.metadata import version
|
|
4
4
|
|
|
5
5
|
from .kinematic import interpolate
|
|
6
|
+
from .plot import plot_baselines, plot_occupations, plot_pos, plot_visibility
|
|
6
7
|
from .refsys import (
|
|
7
8
|
GPS_EPOCH,
|
|
8
9
|
GPST_UTC_OFFSET_S,
|
|
@@ -16,12 +17,15 @@ from .refsys import (
|
|
|
16
17
|
)
|
|
17
18
|
from .rinex import (
|
|
18
19
|
find_rinex_obs,
|
|
20
|
+
flag_stale_headers,
|
|
19
21
|
header_llh,
|
|
22
|
+
header_xyz,
|
|
20
23
|
obs_summary,
|
|
21
|
-
|
|
24
|
+
read_occupations,
|
|
22
25
|
read_visibility,
|
|
23
26
|
rinex_span,
|
|
24
27
|
satellite_stats,
|
|
28
|
+
sessions_from_overlap,
|
|
25
29
|
signal_stats,
|
|
26
30
|
trim_rinex,
|
|
27
31
|
)
|
|
@@ -54,21 +58,28 @@ __all__ = [
|
|
|
54
58
|
"df_to_baselines",
|
|
55
59
|
"enu_diff",
|
|
56
60
|
"find_rinex_obs",
|
|
61
|
+
"flag_stale_headers",
|
|
57
62
|
"gpst_to_local",
|
|
58
63
|
"header_llh",
|
|
64
|
+
"header_xyz",
|
|
59
65
|
"interpolate",
|
|
60
66
|
"loop_closures",
|
|
61
67
|
"navsys_mask",
|
|
62
68
|
"obs_summary",
|
|
69
|
+
"plot_baselines",
|
|
70
|
+
"plot_occupations",
|
|
71
|
+
"plot_pos",
|
|
63
72
|
"plot_visibility",
|
|
64
73
|
"process_baseline",
|
|
65
74
|
"read_header",
|
|
75
|
+
"read_occupations",
|
|
66
76
|
"read_pos",
|
|
67
77
|
"read_ref_pos",
|
|
68
78
|
"read_visibility",
|
|
69
79
|
"rinex_span",
|
|
70
80
|
"run_rnx2rtkp",
|
|
71
81
|
"satellite_stats",
|
|
82
|
+
"sessions_from_overlap",
|
|
72
83
|
"signal_stats",
|
|
73
84
|
"solve_static",
|
|
74
85
|
"trim_rinex",
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Plots: RINEX visibility, occupation maps, baseline networks and RTKLIB solutions.
|
|
2
|
+
|
|
3
|
+
Needs matplotlib (`pip install 'gnsskit[plot]'`), imported only when a plot is made, so the
|
|
4
|
+
rest of gnsskit works without it. The data come from the other modules (`gnsskit.rinex`,
|
|
5
|
+
`gnsskit.rtklib`, `gnsskit.static`); this package only draws.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .occupations import plot_occupations
|
|
9
|
+
from .solutions import plot_baselines, plot_pos
|
|
10
|
+
from .visibility import plot_visibility
|
|
11
|
+
|
|
12
|
+
__all__ = ["plot_baselines", "plot_occupations", "plot_pos", "plot_visibility"]
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Shared pieces of the map plots: style, map tiles, axes and label placement (private)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import urllib.request
|
|
7
|
+
import warnings
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
from ..refsys import ENUFrame
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from matplotlib.axes import Axes
|
|
18
|
+
from matplotlib.figure import Figure
|
|
19
|
+
from matplotlib.transforms import Bbox
|
|
20
|
+
|
|
21
|
+
# validated categorical palette, fixed order (one color per category, never cycled)
|
|
22
|
+
CATEGORICAL = [
|
|
23
|
+
"#2a78d6",
|
|
24
|
+
"#eb6834",
|
|
25
|
+
"#1baf7a",
|
|
26
|
+
"#eda100",
|
|
27
|
+
"#e87ba4",
|
|
28
|
+
"#008300",
|
|
29
|
+
"#6250d6",
|
|
30
|
+
"#e34948",
|
|
31
|
+
]
|
|
32
|
+
SHAPES = ["o", "s", "D", "v", "p", "h", "X", "P"]
|
|
33
|
+
SHAPE_SCALE = {"o": 1.0, "s": 0.9, "D": 0.85, "v": 1.25, "p": 1.05, "h": 1.0, "X": 1.0, "P": 1.0}
|
|
34
|
+
INK, MUTED, GRID = "#1f1f1e", "#6b6a64", "#e4e3dd"
|
|
35
|
+
|
|
36
|
+
OSM_TILES = "https://tile.openstreetmap.org/{z}/{x}/{y}.png"
|
|
37
|
+
OSM_USER_AGENT = "gnsskit (+https://github.com/franioli/gnsskit)"
|
|
38
|
+
OSM_CACHE = Path.home() / ".cache" / "gnsskit" / "tiles"
|
|
39
|
+
MAX_TILES = 40 # be polite with the tile servers
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def categorical_colors(values: Sequence[str], fixed: dict | None = None) -> dict:
|
|
43
|
+
"""Color of each value: the categorical palette in order, or one hue if more than 8."""
|
|
44
|
+
if len(values) <= len(CATEGORICAL):
|
|
45
|
+
colors = {v: CATEGORICAL[i] for i, v in enumerate(values)}
|
|
46
|
+
else: # too many categories: one hue, light to dark in sorted order
|
|
47
|
+
from matplotlib import colormaps
|
|
48
|
+
|
|
49
|
+
ramp = colormaps["Blues"]
|
|
50
|
+
colors = {v: ramp(0.35 + 0.65 * i / (len(values) - 1)) for i, v in enumerate(values)}
|
|
51
|
+
colors.update({str(k): v for k, v in (fixed or {}).items()})
|
|
52
|
+
return colors
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _tile_xy(lat: float, lon: float, z: int) -> tuple[float, float]:
|
|
56
|
+
"""Web Mercator tile coordinates (fractional) of a point (lat, lon [deg]) at zoom z."""
|
|
57
|
+
n = 2**z
|
|
58
|
+
return (lon + 180) / 360 * n, (1 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2 * n
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _tile_latlon(x: float, y: float, z: int) -> tuple[float, float]:
|
|
62
|
+
"""Latitude and longitude [deg] of the tile coordinates (x, y) at zoom z."""
|
|
63
|
+
n = 2**z
|
|
64
|
+
return math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * y / n)))), x / n * 360 - 180
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _fetch_tile(url: str, user_agent: str, cache: Path, z: int, x: int, y: int) -> np.ndarray:
|
|
68
|
+
"""One map tile as an RGB array, from the cache or downloaded."""
|
|
69
|
+
from PIL import Image # installed with matplotlib
|
|
70
|
+
|
|
71
|
+
f = cache / str(z) / str(x) / f"{y}.png"
|
|
72
|
+
if not f.exists():
|
|
73
|
+
req = urllib.request.Request(url.format(z=z, x=x, y=y), headers={"User-Agent": user_agent})
|
|
74
|
+
with urllib.request.urlopen(req, timeout=10) as r:
|
|
75
|
+
data = r.read()
|
|
76
|
+
f.parent.mkdir(parents=True, exist_ok=True)
|
|
77
|
+
f.write_bytes(data)
|
|
78
|
+
return np.asarray(Image.open(f).convert("RGB"))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _tile_image(
|
|
82
|
+
frame: ENUFrame, lo: np.ndarray, hi: np.ndarray, url: str, user_agent: str, cache: Path
|
|
83
|
+
) -> tuple[np.ndarray, list[float]]:
|
|
84
|
+
"""Map image covering the east-north box lo-hi [m] and its extent in east-north.
|
|
85
|
+
|
|
86
|
+
Over a few kilometres the Web Mercator grid of the tiles is, within centimetres, a
|
|
87
|
+
uniformly scaled east-north grid, so the image is placed by its corners only.
|
|
88
|
+
"""
|
|
89
|
+
lat0, _, h0 = frame.llh
|
|
90
|
+
lat, lon, _ = frame.enu_to_llh(np.array([[lo[0], lo[1], 0.0], [hi[0], hi[1], 0.0]]))
|
|
91
|
+
tile_m = (hi[0] - lo[0]) / 4 # about 4 tiles across the map
|
|
92
|
+
z = int(np.clip(round(math.log2(40075016.686 * math.cos(math.radians(lat0)) / tile_m)), 1, 18))
|
|
93
|
+
x0, y0 = (int(v) for v in _tile_xy(lat[1], lon[0], z)) # north-west corner
|
|
94
|
+
x1, y1 = (int(v) for v in _tile_xy(lat[0], lon[1], z)) # south-east corner
|
|
95
|
+
if (x1 - x0 + 1) * (y1 - y0 + 1) > MAX_TILES:
|
|
96
|
+
raise ValueError("too many tiles")
|
|
97
|
+
img = np.vstack(
|
|
98
|
+
[
|
|
99
|
+
np.hstack([_fetch_tile(url, user_agent, cache, z, x, y) for x in range(x0, x1 + 1)])
|
|
100
|
+
for y in range(y0, y1 + 1)
|
|
101
|
+
]
|
|
102
|
+
)
|
|
103
|
+
(n_lat, w_lon), (s_lat, e_lon) = _tile_latlon(x0, y0, z), _tile_latlon(x1 + 1, y1 + 1, z)
|
|
104
|
+
nw = frame.llh_to_enu(n_lat, w_lon, h0)
|
|
105
|
+
se = frame.llh_to_enu(s_lat, e_lon, h0)
|
|
106
|
+
return img, [nw[0], se[0], se[1], nw[1]]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def map_figure(xy: np.ndarray, origin_name: str, pad: float = 0.35) -> tuple[Figure, Axes, float]:
|
|
110
|
+
"""Figure with one east-north map axes around the points xy [m], sized on them.
|
|
111
|
+
|
|
112
|
+
Returns the figure, the axes (limits set, with `pad` x span of room for the labels) and
|
|
113
|
+
the marker size [points], proportional to the map size.
|
|
114
|
+
"""
|
|
115
|
+
from matplotlib.backends.backend_agg import FigureCanvasAgg
|
|
116
|
+
from matplotlib.figure import Figure
|
|
117
|
+
|
|
118
|
+
span = max(float(np.ptp(xy, axis=0).max()), 1.0)
|
|
119
|
+
lo, hi = xy.min(axis=0) - pad * span, xy.max(axis=0) + pad * span
|
|
120
|
+
width = 11.0
|
|
121
|
+
fig = Figure(figsize=(width, max(5.0, width * (hi[1] - lo[1]) / (hi[0] - lo[0])) + 1.2))
|
|
122
|
+
FigureCanvasAgg(fig) # no pyplot: no GUI backend needed
|
|
123
|
+
ax = fig.subplots()
|
|
124
|
+
style_map_axes(ax, origin_name)
|
|
125
|
+
ax.set_xlim(lo[0], hi[0])
|
|
126
|
+
ax.set_ylim(lo[1], hi[1])
|
|
127
|
+
ax_w, ax_h = ax.get_position().size * fig.get_size_inches() * 72
|
|
128
|
+
ms = float(np.clip(min(ax_w, ax_h) / 45, 10, 20))
|
|
129
|
+
return fig, ax, ms
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def style_map_axes(ax: Axes, origin_name: str) -> None:
|
|
133
|
+
"""Equal scale, recessive grid and axes, east/north labels."""
|
|
134
|
+
ax.set_aspect("equal")
|
|
135
|
+
ax.grid(color=GRID, linewidth=0.8)
|
|
136
|
+
ax.set_axisbelow(True)
|
|
137
|
+
for side in ax.spines.values():
|
|
138
|
+
side.set_color(GRID)
|
|
139
|
+
ax.tick_params(colors=MUTED, labelsize=9)
|
|
140
|
+
ax.set_xlabel(f"east of {origin_name} [m]", color=MUTED)
|
|
141
|
+
ax.set_ylabel(f"north of {origin_name} [m]", color=MUTED)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def add_basemap(
|
|
145
|
+
ax: Axes, frame: ENUFrame | None, url: str, user_agent: str, cache: Path | str
|
|
146
|
+
) -> None:
|
|
147
|
+
"""Map tiles under the current limits of an east-north axes; a warning if not available."""
|
|
148
|
+
if frame is None:
|
|
149
|
+
warnings.warn("basemap needs geographic positions: map without tiles", stacklevel=3)
|
|
150
|
+
return
|
|
151
|
+
lo = np.array([ax.get_xlim()[0], ax.get_ylim()[0]])
|
|
152
|
+
hi = np.array([ax.get_xlim()[1], ax.get_ylim()[1]])
|
|
153
|
+
try:
|
|
154
|
+
img, extent = _tile_image(frame, lo, hi, url, user_agent, Path(cache))
|
|
155
|
+
except (OSError, ValueError) as e: # no internet, server error, too many tiles
|
|
156
|
+
warnings.warn(f"basemap not available ({e}): map without tiles", stacklevel=3)
|
|
157
|
+
return
|
|
158
|
+
ax.imshow(0.55 * img / 255 + 0.45, extent=extent, interpolation="bilinear", zorder=0)
|
|
159
|
+
ax.set_xlim(lo[0], hi[0])
|
|
160
|
+
ax.set_ylim(lo[1], hi[1])
|
|
161
|
+
ax.text(0.995, 0.005, "© OpenStreetMap contributors" if url == OSM_TILES else "map tiles",
|
|
162
|
+
transform=ax.transAxes, ha="right", va="bottom", fontsize=7, color=MUTED,
|
|
163
|
+
bbox={"boxstyle": "round,pad=0.2", "fc": "white", "ec": "none", "alpha": 0.8}) # fmt: skip
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def place_labels(
|
|
167
|
+
ax: Axes, labels: list[tuple[str, np.ndarray, float]], ms: float, mid: np.ndarray | None = None
|
|
168
|
+
) -> None:
|
|
169
|
+
"""Draw the labels (text, xy, width of the marker row [points]) without overlaps.
|
|
170
|
+
|
|
171
|
+
Call it last, with the layout fixed: the existing texts, the legend and the marker rows
|
|
172
|
+
are obstacles; each label goes in a free direction, away from `mid` if possible.
|
|
173
|
+
"""
|
|
174
|
+
from matplotlib.transforms import Bbox
|
|
175
|
+
|
|
176
|
+
fig = ax.figure
|
|
177
|
+
fig.canvas.draw()
|
|
178
|
+
renderer = fig.canvas.get_renderer()
|
|
179
|
+
px = fig.dpi / 72
|
|
180
|
+
obstacles = [a.get_tightbbox(renderer).padded(2) for a in ax.texts]
|
|
181
|
+
if ax.get_legend() is not None:
|
|
182
|
+
obstacles.append(ax.get_legend().get_window_extent(renderer).padded(2))
|
|
183
|
+
for _, xy, row in labels:
|
|
184
|
+
x, y = ax.transData.transform(xy)
|
|
185
|
+
obstacles.append(
|
|
186
|
+
Bbox.from_extents(x - row * px / 2, y - ms * px / 2, x + row * px / 2, y + ms * px / 2)
|
|
187
|
+
)
|
|
188
|
+
if mid is None:
|
|
189
|
+
mid = np.mean([xy for _, xy, _ in labels], axis=0)
|
|
190
|
+
for text, xy, row in labels:
|
|
191
|
+
d = np.asarray(xy) - mid
|
|
192
|
+
away = d / np.hypot(*d) if np.hypot(*d) > 0 else np.array([0.0, 1.0])
|
|
193
|
+
obstacles.append(_place_label(ax, text, xy, away, row, ms, obstacles))
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _place_label(ax: Axes, text: str, xy: np.ndarray, away: np.ndarray, row_pt: float, ms: float,
|
|
197
|
+
obstacles: list[Bbox]) -> Bbox: # fmt: skip
|
|
198
|
+
"""Label in the best of 8 directions around a row of markers; returns its box.
|
|
199
|
+
|
|
200
|
+
Directions are tried from `away`; the first one inside the axes and without overlaps
|
|
201
|
+
with the obstacles is taken, else the one with the least overlap (going out of the axes
|
|
202
|
+
counts more).
|
|
203
|
+
"""
|
|
204
|
+
from matplotlib.transforms import Bbox
|
|
205
|
+
|
|
206
|
+
renderer = ax.figure.canvas.get_renderer()
|
|
207
|
+
inside = ax.get_window_extent(renderer)
|
|
208
|
+
base = np.arctan2(away[1], away[0])
|
|
209
|
+
best = None
|
|
210
|
+
for step in (0, 1, -1, 2, -2, 3, -3, 4):
|
|
211
|
+
a = base + step * np.pi / 4
|
|
212
|
+
c, s = np.cos(a), np.sin(a)
|
|
213
|
+
ann = ax.annotate(
|
|
214
|
+
text, xy, xytext=(c * (row_pt / 2 + 8), s * (0.6 * ms + 8)), textcoords="offset points",
|
|
215
|
+
fontsize=8.5, family="monospace", color=INK, multialignment="left",
|
|
216
|
+
ha="left" if c > 0.3 else "right" if c < -0.3 else "center",
|
|
217
|
+
va="bottom" if s > 0.3 else "top" if s < -0.3 else "center",
|
|
218
|
+
bbox={"boxstyle": "round,pad=0.4", "fc": "white", "ec": GRID}, zorder=6,
|
|
219
|
+
) # fmt: skip
|
|
220
|
+
box = ann.get_tightbbox(renderer).padded(2)
|
|
221
|
+
clipped = Bbox.intersection(box, inside)
|
|
222
|
+
out_area = box.width * box.height - (clipped.width * clipped.height if clipped else 0)
|
|
223
|
+
overlap = sum(b.width * b.height for o in obstacles if (b := Bbox.intersection(box, o)))
|
|
224
|
+
score = overlap + 10 * out_area
|
|
225
|
+
if best is None or score < best[0]:
|
|
226
|
+
if best is not None:
|
|
227
|
+
best[1].remove()
|
|
228
|
+
best = (score, ann, box)
|
|
229
|
+
else:
|
|
230
|
+
ann.remove()
|
|
231
|
+
if score == 0:
|
|
232
|
+
break
|
|
233
|
+
return best[2]
|