roadpack 0.1.0__py3-none-any.whl
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.
- roadpack/__init__.py +2 -0
- roadpack/__main__.py +3 -0
- roadpack/arrays.py +30 -0
- roadpack/ch/__init__.py +4 -0
- roadpack/ch/build_ch.cpp +101 -0
- roadpack/ch/builder.py +91 -0
- roadpack/cli.py +242 -0
- roadpack/format/__init__.py +6 -0
- roadpack/format/chunks.py +27 -0
- roadpack/format/reader.py +192 -0
- roadpack/format/spec.py +53 -0
- roadpack/format/writer.py +107 -0
- roadpack/geo.py +63 -0
- roadpack/graph/__init__.py +6 -0
- roadpack/graph/build.py +293 -0
- roadpack/graph/restrictions.py +251 -0
- roadpack/osm/__init__.py +5 -0
- roadpack/osm/loader.py +205 -0
- roadpack/osm/profiles.py +83 -0
- roadpack/pipeline.py +55 -0
- roadpack/preview.py +192 -0
- roadpack/regions.py +15 -0
- roadpack/routing/__init__.py +5 -0
- roadpack/routing/maneuvers.py +142 -0
- roadpack/routing/search.py +128 -0
- roadpack/stats.py +97 -0
- roadpack-0.1.0.dist-info/METADATA +207 -0
- roadpack-0.1.0.dist-info/RECORD +31 -0
- roadpack-0.1.0.dist-info/WHEEL +4 -0
- roadpack-0.1.0.dist-info/entry_points.txt +2 -0
- roadpack-0.1.0.dist-info/licenses/LICENSE +21 -0
roadpack/__init__.py
ADDED
roadpack/__main__.py
ADDED
roadpack/arrays.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""numpy helpers. np.unique is avoided on large arrays: recent numpy versions may use a hash table that takes
|
|
2
|
+
several times the memory of sorting (1 GB for 10 million ids)."""
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def unique(a):
|
|
7
|
+
"""Sorted distinct values of a."""
|
|
8
|
+
s = np.sort(a)
|
|
9
|
+
return s[np.concatenate(([True], s[1:] != s[:-1]))] if len(s) else s
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def unique_inverse(a):
|
|
13
|
+
"""(distinct values, index of each element of a among them)."""
|
|
14
|
+
u = unique(a)
|
|
15
|
+
return u, np.searchsorted(u, a)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def first_occurrences(keys):
|
|
19
|
+
"""(distinct keys, position of the first occurrence of each), sorted by key."""
|
|
20
|
+
order = np.argsort(keys, kind="stable")
|
|
21
|
+
s = keys[order]
|
|
22
|
+
group = np.concatenate(([True], s[1:] != s[:-1])) if len(s) else np.zeros(0, bool)
|
|
23
|
+
return s[group], order[group]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def ranges(starts, counts):
|
|
27
|
+
"""Concatenation of arange(starts[k], starts[k] + counts[k]) for every k."""
|
|
28
|
+
counts = np.asarray(counts, np.int64)
|
|
29
|
+
offsets = np.repeat(np.cumsum(counts) - counts, counts)
|
|
30
|
+
return np.repeat(np.asarray(starts, np.int64), counts) + (np.arange(int(counts.sum())) - offsets)
|
roadpack/ch/__init__.py
ADDED
roadpack/ch/build_ch.cpp
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Builds the contraction hierarchy (CH) of a graph with RoutingKit and writes it reorganized by node number
|
|
2
|
+
// (not by rank), so that nodes close on the map stay close on the SD card.
|
|
3
|
+
//
|
|
4
|
+
// Input (little-endian): u32 node_count, u32 arc_count, u32 tail[arc_count], u32 head[arc_count],
|
|
5
|
+
// u32 weight[arc_count]
|
|
6
|
+
// Output (little-endian), for each side (forward first, then backward):
|
|
7
|
+
// u32 arc_count, u32 first_out[node_count + 1], arcs[arc_count] of 16 bytes:
|
|
8
|
+
// u32 other (head in forward, tail in backward), u32 weight, u32 a, u32 b
|
|
9
|
+
// Original arc: a = ORIGINAL | id of the input arc, b = 0.
|
|
10
|
+
// Shortcut: a = arc of the backward side, b = arc of the forward side (its two halves).
|
|
11
|
+
//
|
|
12
|
+
// Usage: build_ch input.bin output.bin
|
|
13
|
+
|
|
14
|
+
#include <routingkit/contraction_hierarchy.h>
|
|
15
|
+
|
|
16
|
+
#include <cstdint>
|
|
17
|
+
#include <cstdio>
|
|
18
|
+
#include <fstream>
|
|
19
|
+
#include <iostream>
|
|
20
|
+
#include <vector>
|
|
21
|
+
|
|
22
|
+
using namespace RoutingKit;
|
|
23
|
+
|
|
24
|
+
static const uint32_t ORIGINAL = 0x80000000u;
|
|
25
|
+
|
|
26
|
+
static std::vector<uint32_t> readArray(std::ifstream &in, size_t n) {
|
|
27
|
+
std::vector<uint32_t> v(n);
|
|
28
|
+
in.read(reinterpret_cast<char *>(v.data()), n * 4);
|
|
29
|
+
return v;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
static void writeU32(std::ofstream &out, uint32_t v) { out.write(reinterpret_cast<const char *>(&v), 4); }
|
|
33
|
+
|
|
34
|
+
// Reorders one side of the CH: from rank-indexed to node-indexed.
|
|
35
|
+
// newArc[old] is the new position of each arc, used to rewrite the references inside shortcuts.
|
|
36
|
+
static void reorder(const ContractionHierarchy &ch, const ContractionHierarchy::Side &side, std::vector<uint32_t> &firstOut,
|
|
37
|
+
std::vector<uint32_t> &newArc) {
|
|
38
|
+
const uint32_t n = ch.node_count();
|
|
39
|
+
firstOut.assign(n + 1, 0);
|
|
40
|
+
for (uint32_t node = 0; node < n; node++) {
|
|
41
|
+
uint32_t r = ch.rank[node];
|
|
42
|
+
firstOut[node + 1] = firstOut[node] + (side.first_out[r + 1] - side.first_out[r]);
|
|
43
|
+
}
|
|
44
|
+
newArc.assign(side.head.size(), 0);
|
|
45
|
+
for (uint32_t node = 0; node < n; node++) {
|
|
46
|
+
uint32_t r = ch.rank[node];
|
|
47
|
+
for (uint32_t k = 0; k < side.first_out[r + 1] - side.first_out[r]; k++) newArc[side.first_out[r] + k] = firstOut[node] + k;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
static void writeSide(std::ofstream &out, const ContractionHierarchy &ch, const ContractionHierarchy::Side &side,
|
|
52
|
+
const std::vector<uint32_t> &firstOut, const std::vector<uint32_t> &newArc,
|
|
53
|
+
const std::vector<uint32_t> &newBackward, const std::vector<uint32_t> &newForward) {
|
|
54
|
+
const size_t arcs = side.head.size();
|
|
55
|
+
std::vector<uint32_t> rec(arcs * 4);
|
|
56
|
+
for (size_t old = 0; old < arcs; old++) {
|
|
57
|
+
uint32_t *r = &rec[newArc[old] * 4];
|
|
58
|
+
r[0] = ch.order[side.head[old]]; // rank -> node number
|
|
59
|
+
r[1] = side.weight[old];
|
|
60
|
+
if (side.is_shortcut_an_original_arc.is_set(old)) {
|
|
61
|
+
r[2] = ORIGINAL | side.shortcut_first_arc[old];
|
|
62
|
+
r[3] = 0;
|
|
63
|
+
} else {
|
|
64
|
+
r[2] = newBackward[side.shortcut_first_arc[old]];
|
|
65
|
+
r[3] = newForward[side.shortcut_second_arc[old]];
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
writeU32(out, (uint32_t)arcs);
|
|
69
|
+
out.write(reinterpret_cast<const char *>(firstOut.data()), firstOut.size() * 4);
|
|
70
|
+
out.write(reinterpret_cast<const char *>(rec.data()), rec.size() * 4);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
int main(int argc, char **argv) {
|
|
74
|
+
if (argc != 3) {
|
|
75
|
+
std::cerr << "usage: build_ch input.bin output.bin\n";
|
|
76
|
+
return 2;
|
|
77
|
+
}
|
|
78
|
+
std::ifstream in(argv[1], std::ios::binary);
|
|
79
|
+
uint32_t nodeCount = 0, arcCount = 0;
|
|
80
|
+
in.read(reinterpret_cast<char *>(&nodeCount), 4);
|
|
81
|
+
in.read(reinterpret_cast<char *>(&arcCount), 4);
|
|
82
|
+
std::vector<unsigned> tail = readArray(in, arcCount), head = readArray(in, arcCount), weight = readArray(in, arcCount);
|
|
83
|
+
if (!in) {
|
|
84
|
+
std::cerr << "truncated input\n";
|
|
85
|
+
return 1;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
ContractionHierarchy ch = ContractionHierarchy::build(nodeCount, tail, head, weight,
|
|
89
|
+
[](const std::string &msg) { std::cerr << " [ch] " << msg << "\n"; });
|
|
90
|
+
check_contraction_hierarchy_for_errors(ch);
|
|
91
|
+
|
|
92
|
+
std::vector<uint32_t> fwdFirst, bwdFirst, newForward, newBackward;
|
|
93
|
+
reorder(ch, ch.forward, fwdFirst, newForward);
|
|
94
|
+
reorder(ch, ch.backward, bwdFirst, newBackward);
|
|
95
|
+
|
|
96
|
+
std::ofstream out(argv[2], std::ios::binary);
|
|
97
|
+
writeSide(out, ch, ch.forward, fwdFirst, newForward, newBackward, newForward);
|
|
98
|
+
writeSide(out, ch, ch.backward, bwdFirst, newBackward, newBackward, newForward);
|
|
99
|
+
std::cerr << " [ch] " << ch.forward.head.size() << " forward arcs, " << ch.backward.head.size() << " backward arcs\n";
|
|
100
|
+
return out ? 0 : 1;
|
|
101
|
+
}
|
roadpack/ch/builder.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Contraction hierarchy layer: precomputes shortcuts with RoutingKit so a device can route long distances
|
|
2
|
+
settling a few hundred nodes.
|
|
3
|
+
|
|
4
|
+
The C++ helper (build_ch.cpp, next to this file) is compiled on first use into a cache directory, together
|
|
5
|
+
with a pinned RoutingKit checkout. Requires git and a C++17 compiler.
|
|
6
|
+
"""
|
|
7
|
+
import hashlib
|
|
8
|
+
import os
|
|
9
|
+
import shutil
|
|
10
|
+
import struct
|
|
11
|
+
import subprocess
|
|
12
|
+
import tempfile
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from ..format.spec import CH_ARC
|
|
19
|
+
|
|
20
|
+
ROUTINGKIT_URL = "https://github.com/RoutingKit/RoutingKit.git"
|
|
21
|
+
ROUTINGKIT_COMMIT = "54d49bb0cdea56dde182357522e4e86a03c57852"
|
|
22
|
+
ROUTINGKIT_SOURCES = ("contraction_hierarchy.cpp", "bit_vector.cpp", "timer.cpp", "vector_io.cpp", "graph_util.cpp")
|
|
23
|
+
SOURCE = Path(__file__).with_name("build_ch.cpp")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class ContractionHierarchy:
|
|
28
|
+
"""Forward and backward sections, already serialized as FORMAT.md describes."""
|
|
29
|
+
forward: bytes
|
|
30
|
+
backward: bytes
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def forward_arcs(self):
|
|
34
|
+
return struct.unpack_from("<I", self.forward)[0]
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def backward_arcs(self):
|
|
38
|
+
return struct.unpack_from("<I", self.backward)[0]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def cache_dir() -> Path:
|
|
42
|
+
"""Where RoutingKit and the compiled helper live: $ROADPACK_CACHE, or ~/.cache/roadpack."""
|
|
43
|
+
if os.environ.get("ROADPACK_CACHE"):
|
|
44
|
+
return Path(os.environ["ROADPACK_CACHE"])
|
|
45
|
+
return Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "roadpack"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def ensure_tool(log=print) -> Path:
|
|
49
|
+
"""Path to the compiled build_ch helper, building it (and fetching RoutingKit) if needed."""
|
|
50
|
+
root = cache_dir()
|
|
51
|
+
# Named after the RoutingKit commit and the helper's source, so any change rebuilds it.
|
|
52
|
+
source_hash = hashlib.sha1(SOURCE.read_bytes()).hexdigest()[:8]
|
|
53
|
+
tool = root / f"build_ch-{ROUTINGKIT_COMMIT[:8]}-{source_hash}"
|
|
54
|
+
if tool.exists():
|
|
55
|
+
return tool
|
|
56
|
+
routingkit = root / "RoutingKit"
|
|
57
|
+
if not (routingkit / "src").exists():
|
|
58
|
+
log(f"Fetching RoutingKit into {routingkit} ...")
|
|
59
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
60
|
+
subprocess.run(["git", "clone", "-q", ROUTINGKIT_URL, str(routingkit)], check=True)
|
|
61
|
+
subprocess.run(["git", "-C", str(routingkit), "checkout", "-q", ROUTINGKIT_COMMIT], check=True)
|
|
62
|
+
|
|
63
|
+
compiler = os.environ.get("CXX") or shutil.which("clang++") or shutil.which("g++")
|
|
64
|
+
if not compiler:
|
|
65
|
+
raise RuntimeError("a C++17 compiler is needed to build the contraction hierarchy (set CXX)")
|
|
66
|
+
log(f"Compiling the contraction hierarchy helper with {Path(compiler).name} ...")
|
|
67
|
+
src = routingkit / "src"
|
|
68
|
+
subprocess.run([compiler, "-std=c++17", "-O3", "-DNDEBUG", f"-I{routingkit / 'include'}", "-o", str(tool),
|
|
69
|
+
str(SOURCE), *(str(src / f) for f in ROUTINGKIT_SOURCES)], check=True)
|
|
70
|
+
return tool
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def build_ch(node_count, tails, heads, weights, log=print) -> ContractionHierarchy:
|
|
74
|
+
"""Contraction hierarchy of a directed graph given as parallel arc arrays (weights in tenths of a second)."""
|
|
75
|
+
tool = ensure_tool(log)
|
|
76
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
77
|
+
src, dst = Path(tmp) / "graph.bin", Path(tmp) / "ch.bin"
|
|
78
|
+
with open(src, "wb") as f:
|
|
79
|
+
f.write(struct.pack("<II", node_count, len(tails)))
|
|
80
|
+
for arr in (tails, heads, weights):
|
|
81
|
+
f.write(np.asarray(arr, "<u4").tobytes())
|
|
82
|
+
subprocess.run([str(tool), str(src), str(dst)], check=True, stderr=subprocess.DEVNULL)
|
|
83
|
+
data = dst.read_bytes()
|
|
84
|
+
fwd_arcs = struct.unpack_from("<I", data, 0)[0]
|
|
85
|
+
fwd_size = 4 + (node_count + 1) * 4 + fwd_arcs * CH_ARC.size
|
|
86
|
+
return ContractionHierarchy(data[:fwd_size], data[fwd_size:])
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def build_graph_ch(graph, log=print) -> ContractionHierarchy:
|
|
90
|
+
"""Contraction hierarchy of a RoadGraph, on its travel-time weights."""
|
|
91
|
+
return build_ch(graph.node_count, graph.source, graph.target, graph.weight, log)
|
roadpack/cli.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
"""Command line: roadpack build | info | route."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
import time
|
|
6
|
+
from collections import Counter
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .format.spec import ROAD_CLASSES
|
|
11
|
+
|
|
12
|
+
def _mb(n):
|
|
13
|
+
return f"{n / 1048576:,.1f} MB"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _point(text):
|
|
17
|
+
try:
|
|
18
|
+
lat, lon = (float(v) for v in text.split(","))
|
|
19
|
+
except ValueError:
|
|
20
|
+
raise argparse.ArgumentTypeError("expected lat,lon") from None
|
|
21
|
+
return lat, lon
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _bbox(text):
|
|
25
|
+
from .regions import parse_bbox
|
|
26
|
+
try:
|
|
27
|
+
return parse_bbox(text)
|
|
28
|
+
except ValueError as e:
|
|
29
|
+
raise argparse.ArgumentTypeError(str(e)) from None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _print_sections(sections, total):
|
|
33
|
+
for name, size in sections.items():
|
|
34
|
+
print(f" {name:<12} {_mb(size):>10} {size / total:6.1%}")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
COORDINATE_OPTIONS = ("--bbox", "--from", "--to")
|
|
38
|
+
WHOLE_WORLD = (-90.0, -180.0, 90.0, 180.0)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _join_coordinate_values(argv):
|
|
42
|
+
"""argparse takes "-12.1,-77.0" for an option: glue coordinates to their flag (--from=-12.1,-77.0)."""
|
|
43
|
+
out, i = [], 0
|
|
44
|
+
while i < len(argv):
|
|
45
|
+
if argv[i] in COORDINATE_OPTIONS and i + 1 < len(argv):
|
|
46
|
+
out.append(f"{argv[i]}={argv[i + 1]}")
|
|
47
|
+
i += 2
|
|
48
|
+
else:
|
|
49
|
+
out.append(argv[i])
|
|
50
|
+
i += 1
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def cmd_build(args):
|
|
55
|
+
from .osm import PROFILES
|
|
56
|
+
from .pipeline import build
|
|
57
|
+
from .regions import REGIONS
|
|
58
|
+
|
|
59
|
+
bbox = args.bbox or (REGIONS[args.region] if args.region else WHOLE_WORLD)
|
|
60
|
+
chunk_dir = None if args.no_chunks else (args.chunk_dir or args.output.with_suffix(""))
|
|
61
|
+
stats = build(args.pbf, bbox, PROFILES[args.profile], args.output, chunk_dir,
|
|
62
|
+
restrictions=not args.no_restrictions)
|
|
63
|
+
|
|
64
|
+
s = stats["sections"]
|
|
65
|
+
print(f"\nWrote {args.output} ({_mb(s['total'])}) in {stats['total_seconds']:.0f} s")
|
|
66
|
+
print(f" OSM: {stats['osm_ways']:,} drivable ways, {stats['osm_nodes']:,} nodes")
|
|
67
|
+
print(f" graph: {stats['nodes']:,} nodes ({stats['nodes'] / stats['osm_nodes']:.0%} of the OSM nodes), "
|
|
68
|
+
f"{stats['edges']:,} directed edges")
|
|
69
|
+
print(f" shape: {stats['shape_points_kept']:,} of {stats['shape_points']:,} points between nodes kept")
|
|
70
|
+
if stats.get("restrictions"):
|
|
71
|
+
print(f" turn restrictions: {stats['restrictions_applied']:,} of {stats['restrictions']:,} applied, "
|
|
72
|
+
f"{stats['node_copies']:,} junction copies")
|
|
73
|
+
print(" sections:")
|
|
74
|
+
_print_sections({k: s[k] for k in ("nodes", "edges", "grid", "geometry", "names", "ch_forward", "ch_backward",
|
|
75
|
+
"copies")}, s["total"])
|
|
76
|
+
if chunk_dir is not None:
|
|
77
|
+
print(f" SD card: {chunk_dir}/ ({stats['chunks']} chunks) -> copy it to /maps/{chunk_dir.name}/")
|
|
78
|
+
if args.stats_json:
|
|
79
|
+
args.stats_json.write_text(json.dumps(stats, indent=2) + "\n")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def cmd_info(args):
|
|
83
|
+
from .format import Gmap
|
|
84
|
+
|
|
85
|
+
g = Gmap(args.gmap)
|
|
86
|
+
sections = g.section_sizes()
|
|
87
|
+
total = len(g.data)
|
|
88
|
+
classes = Counter(f & 0x0F for f in g.flags)
|
|
89
|
+
km = sum(length for length, src in zip(g.length, g.source) if not g.is_copy(src)) / 1000 # copies: same road
|
|
90
|
+
if args.json:
|
|
91
|
+
print(json.dumps({
|
|
92
|
+
"nodes": g.node_count, "edges": g.edge_count,
|
|
93
|
+
"bounds": [g.min_lat, g.min_lon, g.max_lat, g.max_lon],
|
|
94
|
+
"grid": {"cell_deg": g.cell, "cols": g.cols, "rows": g.rows, "non_empty": len(g.cell_ids)},
|
|
95
|
+
"ch_arcs": {"forward": g.ch_fwd.arc_count, "backward": g.ch_bwd.arc_count},
|
|
96
|
+
"directed_km": km, "sections": sections, "size": total, "version": g.version,
|
|
97
|
+
"junction_copies": g.copy_count,
|
|
98
|
+
"edges_by_class": {ROAD_CLASSES[c]: n for c, n in sorted(classes.items())},
|
|
99
|
+
}, indent=2))
|
|
100
|
+
return
|
|
101
|
+
print(f"{args.gmap}: .gmap v{g.version}, {_mb(total)}")
|
|
102
|
+
print(f" {g.node_count:,} nodes, {g.edge_count:,} directed edges ({km:,.0f} km), "
|
|
103
|
+
f"{total / g.node_count:.0f} bytes per node in total")
|
|
104
|
+
print(f" bounds: {g.min_lat:.4f},{g.min_lon:.4f} – {g.max_lat:.4f},{g.max_lon:.4f}")
|
|
105
|
+
print(f" grid: {g.cols} × {g.rows} cells of {g.cell:g}°, {len(g.cell_ids):,} non-empty")
|
|
106
|
+
print(f" contraction hierarchy: {g.ch_fwd.arc_count:,} forward + {g.ch_bwd.arc_count:,} backward arcs")
|
|
107
|
+
if g.copy_count:
|
|
108
|
+
print(f" turn restrictions: {g.copy_count:,} junction copies")
|
|
109
|
+
print(" sections:")
|
|
110
|
+
_print_sections({k: v for k, v in sections.items() if k != "header"}, total)
|
|
111
|
+
print(" edges by road class:")
|
|
112
|
+
for c, n in sorted(classes.items()):
|
|
113
|
+
print(f" {ROAD_CLASSES[c]:<12} {n:>10,} {n / g.edge_count:6.1%}")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def cmd_stats(args):
|
|
117
|
+
from .format import Gmap
|
|
118
|
+
from .stats import sample_routes
|
|
119
|
+
|
|
120
|
+
g = Gmap(args.gmap)
|
|
121
|
+
r = sample_routes(g, args.routes, args.seed, args.check)
|
|
122
|
+
if args.json:
|
|
123
|
+
print(json.dumps(r, indent=2))
|
|
124
|
+
return
|
|
125
|
+
print(f"{args.gmap}: {g.node_count:,} nodes, {_mb(len(g.data))}")
|
|
126
|
+
print(f" {r['routes']} random routes ({r['unreachable']} pairs without a route)")
|
|
127
|
+
rows = [("route length (km)", "route_km", "{:,.1f}"), ("nodes settled", "settled_nodes", "{:,}"),
|
|
128
|
+
("KB read by the query", "query_kb_read", "{:,.0f}"), ("KB read incl. geometry", "route_kb_read", "{:,.0f}"),
|
|
129
|
+
("Python time (ms)", "python_ms", "{:,.1f}")]
|
|
130
|
+
print(f" {'':<24}{'median':>10}{'p95':>10}{'max':>10}")
|
|
131
|
+
for label, key, fmt in rows:
|
|
132
|
+
v = r[key]
|
|
133
|
+
cells = "".join(f"{fmt.format(v[q]):>10}" if v[q] is not None else f"{'-':>10}" for q in ("median", "p95", "max"))
|
|
134
|
+
print(f" {label:<24}{cells}")
|
|
135
|
+
print(f" pages of {r['page_size']} bytes; what a device reads with an empty cache")
|
|
136
|
+
if r["astar_checked"]:
|
|
137
|
+
verdict = "all the same cost" if not r["astar_mismatches"] else f"{r['astar_mismatches']} MISMATCHES"
|
|
138
|
+
print(f" A* on the full graph: {r['astar_checked']} routes, {verdict}, "
|
|
139
|
+
f"{r['astar_settled_mean']:,.0f} nodes settled on average")
|
|
140
|
+
if r["astar_mismatches"]:
|
|
141
|
+
sys.exit(1)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def cmd_route(args):
|
|
145
|
+
from .format import Gmap
|
|
146
|
+
from .preview import format_distance
|
|
147
|
+
from .routing import maneuvers, route_astar, route_ch
|
|
148
|
+
|
|
149
|
+
g = Gmap(args.gmap)
|
|
150
|
+
start, goal = g.nearest_node(*args.origin), g.nearest_node(*args.dest)
|
|
151
|
+
stats = {}
|
|
152
|
+
t = time.perf_counter()
|
|
153
|
+
path, cost = route_ch(g, start, goal, stats)
|
|
154
|
+
elapsed = time.perf_counter() - t
|
|
155
|
+
if path is None:
|
|
156
|
+
sys.exit("No route between those points.")
|
|
157
|
+
if not path:
|
|
158
|
+
sys.exit("Both points snap to the same node.")
|
|
159
|
+
ms = maneuvers(g, path)
|
|
160
|
+
|
|
161
|
+
total_m = sum(g.length[e] for e in path)
|
|
162
|
+
print(f"Route: {format_distance(total_m)}, ~{cost / 600:.0f} min, {len(path)} edges, {len(ms)} maneuvers")
|
|
163
|
+
print(f" contraction hierarchy settled {stats['settled']:,} nodes in {elapsed * 1000:.0f} ms (Python)")
|
|
164
|
+
if args.check:
|
|
165
|
+
astar = {}
|
|
166
|
+
t = time.perf_counter()
|
|
167
|
+
_, ref_cost = route_astar(g, start, goal, astar)
|
|
168
|
+
elapsed = time.perf_counter() - t
|
|
169
|
+
verdict = "same cost" if ref_cost == cost else f"MISMATCH: {ref_cost} vs {cost}"
|
|
170
|
+
print(f" A* on the full graph settled {astar['settled']:,} nodes in {elapsed * 1000:.0f} ms: {verdict}")
|
|
171
|
+
print()
|
|
172
|
+
for prev, m in zip([None, *ms], ms):
|
|
173
|
+
gap = m.at_m - prev.at_m if prev else 0
|
|
174
|
+
print(f" {m.at_m / 1000:6.2f} km (+{format_distance(gap):>7}) {m.text()}")
|
|
175
|
+
|
|
176
|
+
if args.images:
|
|
177
|
+
from .preview import render
|
|
178
|
+
count = render(g, path, ms, args.images)
|
|
179
|
+
print(f"\n{count} images in {args.images}/")
|
|
180
|
+
if args.check and ref_cost != cost:
|
|
181
|
+
sys.exit(1)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def main(argv=None):
|
|
185
|
+
from .osm import PROFILES
|
|
186
|
+
from .regions import REGIONS
|
|
187
|
+
|
|
188
|
+
parser = argparse.ArgumentParser(
|
|
189
|
+
prog="roadpack",
|
|
190
|
+
description="Compact OpenStreetMap road graphs for microcontrollers: build, inspect and test .gmap files.")
|
|
191
|
+
parser.add_argument("--version", action="version", version=f"roadpack {__version__}")
|
|
192
|
+
sub = parser.add_subparsers(dest="command", required=True, metavar="command")
|
|
193
|
+
|
|
194
|
+
b = sub.add_parser("build", help="OSM extract -> .gmap (and SD card chunks)",
|
|
195
|
+
description="Build a .gmap from an OpenStreetMap extract (.osm.pbf), e.g. from Geofabrik.")
|
|
196
|
+
b.add_argument("pbf", type=Path, help="OpenStreetMap extract (.osm.pbf)")
|
|
197
|
+
b.add_argument("-o", "--output", required=True, type=Path, help="output .gmap file")
|
|
198
|
+
area = b.add_mutually_exclusive_group()
|
|
199
|
+
area.add_argument("--bbox", type=_bbox, metavar="MINLAT,MINLON,MAXLAT,MAXLON",
|
|
200
|
+
help="keep the roads that touch this rectangle (default: the whole extract)")
|
|
201
|
+
area.add_argument("--region", choices=sorted(REGIONS), help="predefined bounding box")
|
|
202
|
+
b.add_argument("--profile", choices=sorted(PROFILES), default="motorcycle",
|
|
203
|
+
help="vehicle whose access and oneway rules apply (default: motorcycle)")
|
|
204
|
+
b.add_argument("--chunk-dir", type=Path, help="where to write the SD card chunks (default: output without .gmap)")
|
|
205
|
+
b.add_argument("--no-chunks", action="store_true", help="do not split the file into SD card chunks")
|
|
206
|
+
b.add_argument("--no-restrictions", action="store_true", help="ignore OSM turn restrictions")
|
|
207
|
+
b.add_argument("--stats-json", type=Path, metavar="FILE", help="also write the build statistics as JSON")
|
|
208
|
+
b.set_defaults(func=cmd_build)
|
|
209
|
+
|
|
210
|
+
i = sub.add_parser("info", help="what is inside a .gmap", description="Counts, bounds and section sizes.")
|
|
211
|
+
i.add_argument("gmap", type=Path, help=".gmap file or directory of SD card chunks")
|
|
212
|
+
i.add_argument("--json", action="store_true", help="machine-readable output")
|
|
213
|
+
i.set_defaults(func=cmd_info)
|
|
214
|
+
|
|
215
|
+
st = sub.add_parser("stats", help="cost of random routes: nodes settled and KB read",
|
|
216
|
+
description="Route between random pairs of nodes like a device would and report how many "
|
|
217
|
+
"nodes the contraction hierarchy settles and how much of the file it reads.")
|
|
218
|
+
st.add_argument("gmap", type=Path, help=".gmap file or directory of SD card chunks")
|
|
219
|
+
st.add_argument("--routes", type=int, default=100, help="random node pairs (default: 100)")
|
|
220
|
+
st.add_argument("--seed", type=int, default=1)
|
|
221
|
+
st.add_argument("--check", type=int, default=0, metavar="N", help="also run A* on the first N routes")
|
|
222
|
+
st.add_argument("--json", action="store_true", help="machine-readable output")
|
|
223
|
+
st.set_defaults(func=cmd_stats)
|
|
224
|
+
|
|
225
|
+
r = sub.add_parser("route", help="route between two points and print the maneuvers",
|
|
226
|
+
description="Route with the contraction hierarchy, like a device would.")
|
|
227
|
+
r.add_argument("gmap", type=Path, help=".gmap file or directory of SD card chunks")
|
|
228
|
+
r.add_argument("--from", dest="origin", required=True, type=_point, metavar="LAT,LON")
|
|
229
|
+
r.add_argument("--to", dest="dest", required=True, type=_point, metavar="LAT,LON")
|
|
230
|
+
r.add_argument("--check", action="store_true", help="also run A* on the full graph and compare the cost")
|
|
231
|
+
r.add_argument("--images", type=Path, metavar="DIR", help="render the route and each maneuver screen as PNG")
|
|
232
|
+
r.set_defaults(func=cmd_route)
|
|
233
|
+
|
|
234
|
+
args = parser.parse_args(_join_coordinate_values(sys.argv[1:] if argv is None else argv))
|
|
235
|
+
try:
|
|
236
|
+
args.func(args)
|
|
237
|
+
except (OSError, ValueError, RuntimeError) as e:
|
|
238
|
+
sys.exit(f"roadpack: {e}")
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
if __name__ == "__main__":
|
|
242
|
+
main()
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""The .gmap binary format: layout constants, writer, reader and SD card chunks."""
|
|
2
|
+
from .chunks import CHUNK_SIZE, join_chunks, write_chunks
|
|
3
|
+
from .reader import Gmap
|
|
4
|
+
from .writer import write_gmap
|
|
5
|
+
|
|
6
|
+
__all__ = ["CHUNK_SIZE", "Gmap", "join_chunks", "write_chunks", "write_gmap"]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Splitting a .gmap into fixed-size files for a FAT-formatted SD card.
|
|
2
|
+
|
|
3
|
+
Without FAT "fast seek" (the Arduino ESP32 core does not enable it), seeking backwards inside a file of
|
|
4
|
+
hundreds of MB walks the whole cluster chain: ~12 ms per read measured on an ESP32-S3. Small chunks keep the
|
|
5
|
+
seeks short; too small and the device spends its time opening files (~17 ms each). 4 MiB is the sweet spot.
|
|
6
|
+
"""
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
CHUNK_SIZE = 4 << 20
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def write_chunks(gmap_path: Path, out_dir: Path, chunk_size: int = CHUNK_SIZE) -> int:
|
|
13
|
+
"""Split a .gmap into out_dir/0000.bin, 0001.bin, ... (removing old chunks first). Returns the count."""
|
|
14
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
15
|
+
for old in out_dir.glob("*.bin"):
|
|
16
|
+
old.unlink()
|
|
17
|
+
with open(gmap_path, "rb") as f:
|
|
18
|
+
i = 0
|
|
19
|
+
while chunk := f.read(chunk_size):
|
|
20
|
+
(out_dir / f"{i:04d}.bin").write_bytes(chunk)
|
|
21
|
+
i += 1
|
|
22
|
+
return i
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def join_chunks(chunk_dir: Path) -> bytes:
|
|
26
|
+
"""Concatenate the chunks of a directory back into the original .gmap bytes."""
|
|
27
|
+
return b"".join(p.read_bytes() for p in sorted(chunk_dir.glob("*.bin")))
|