Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / networklocation / geodb_build / src / bin / geodb_build.rs

geodb_build.rs163 lines · 5.2 KiBRaw
1//! `geodb_build IN.osm.pbf --out geocoder.db [--bbox BOX] [--threads N]`
2
3use std::path::PathBuf;
4use std::process::ExitCode;
5
6use geodb_build::{commas, extract, human_bytes, write};
7use osm_ingest::bbox::BBox;
8
9/// An allocator decides where, never what, so this cannot change a byte of the output.
10#[global_allocator]
11static ALLOCATOR: mimalloc::MiMalloc = mimalloc::MiMalloc;
12
13const USAGE: &str = "\
14Usage: geodb_build IN.osm.pbf --out FILE [--bbox W,S,E,N] [--threads N] [--no-verify]
15
16 --out geocoder.db to write
17 --bbox clip to a box, for a metro or region rehearsal
18 --threads worker threads (default: all cores, or MAPS_THREADS)
19 --no-verify skip the read-back check (not recommended)";
20
21struct Args {
22 input: PathBuf,
23 out: PathBuf,
24 bbox: Option<BBox>,
25 threads: Option<usize>,
26 verify: bool,
27}
28
29fn parse_args(argv: &[String]) -> Result<Args, String> {
30 let mut input = None;
31 let mut out = None;
32 let mut bbox = None;
33 let mut threads = None;
34 let mut verify = true;
35
36 let mut i = 0;
37 while i < argv.len() {
38 let a = argv[i].as_str();
39 let value = || argv.get(i + 1).cloned().ok_or_else(|| format!("{a} needs a value"));
40 match a {
41 "--out" => {
42 out = Some(PathBuf::from(value()?));
43 i += 2;
44 }
45 "--bbox" => {
46 bbox = Some(BBox::parse(&value()?).map_err(|e| e.0)?);
47 i += 2;
48 }
49 "--threads" => {
50 threads = Some(osm_ingest::par::parse_threads(&value()?)?);
51 i += 2;
52 }
53 "--no-verify" => {
54 verify = false;
55 i += 1;
56 }
57 "-h" | "--help" => return Err("help".to_string()),
58 other if other.starts_with('-') => return Err(format!("unknown option: {other}")),
59 other => {
60 if input.replace(PathBuf::from(other)).is_some() {
61 return Err("more than one input given".to_string());
62 }
63 i += 1;
64 }
65 }
66 }
67 Ok(Args {
68 input: input.ok_or("an input .osm.pbf is required")?,
69 out: out.ok_or("--out is required")?,
70 bbox,
71 threads,
72 verify,
73 })
74}
75
76fn main() -> ExitCode {
77 let argv: Vec<String> = std::env::args().skip(1).collect();
78 let args = match parse_args(&argv) {
79 Ok(a) => a,
80 Err(e) => {
81 if e != "help" {
82 eprintln!("error: {e}");
83 }
84 eprintln!("{USAGE}");
85 return if e == "help" { ExitCode::SUCCESS } else { ExitCode::FAILURE };
86 }
87 };
88 if let Some(n) = args.threads {
89 osm_ingest::par::set_threads(n);
90 }
91 let _ = rayon::ThreadPoolBuilder::new()
92 .num_threads(osm_ingest::par::threads())
93 .build_global();
94
95 let started = std::time::Instant::now();
96 let (mut rows, mut strings, stats) = match extract::extract(&args.input, args.bbox.as_ref()) {
97 Ok(v) => v,
98 Err(e) => {
99 eprintln!("error: {e}");
100 return ExitCode::FAILURE;
101 }
102 };
103 println!(
104 "Extracted {} row(s) in {:.1}s",
105 commas(stats.rows()),
106 started.elapsed().as_secs_f64()
107 );
108 println!(
109 " {} address, {} street sample, {} POI, {} place",
110 commas(stats.addresses),
111 commas(stats.streets),
112 commas(stats.pois),
113 commas(stats.places)
114 );
115 println!(
116 " from {} node(s), {} way(s), {} relation(s); {} incomplete, {} outside bbox",
117 commas(stats.from_nodes),
118 commas(stats.from_ways),
119 commas(stats.from_relations),
120 commas(stats.incomplete),
121 commas(stats.outside_bbox)
122 );
123
124 let t = std::time::Instant::now();
125 let report = match write::write(&args.out, &mut rows, &mut strings) {
126 Ok(r) => r,
127 Err(e) => {
128 eprintln!("error: writing {}: {e}", args.out.display());
129 return ExitCode::FAILURE;
130 }
131 };
132 println!("Wrote {} in {:.1}s", args.out.display(), t.elapsed().as_secs_f64());
133 println!(
134 " {} ({} records, {:.1} bits/record)",
135 human_bytes(report.total),
136 commas(report.n),
137 report.bits_per_record()
138 );
139 for (name, bytes) in report.dicts.iter().chain(report.columns.iter()) {
140 println!(" {name:<9} {:>12}", human_bytes(*bytes));
141 }
142 println!(" {:<9} {:>12}", "grid", human_bytes(report.grid));
143 println!(" {:<9} {:>12}", "fwd", human_bytes(report.fwd));
144 println!(" {:<9} {:>12}", "nameidx", human_bytes(report.name_index));
145 for (name, count) in &report.dict_counts {
146 println!(" dict {name:<9} {:>12} distinct", commas(*count));
147 }
148
149 if args.verify {
150 let t = std::time::Instant::now();
151 if let Err(e) = write::verify(&args.out, &rows) {
152 eprintln!("error: verification failed: {e}");
153 return ExitCode::FAILURE;
154 }
155 println!("Verified {} record(s) in {:.1}s", commas(report.n), t.elapsed().as_secs_f64());
156 } else {
157 eprintln!("WARNING: --no-verify; the database was not read back");
158 }
159
160 println!("Peak RSS: {}", osm_ingest::mem::peak_rss_report());
161 println!("Total {:.1}s", started.elapsed().as_secs_f64());
162 ExitCode::SUCCESS
163}