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

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

geodb_build.rs161 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().num_threads(osm_ingest::par::threads()).build_global();
92
93 let started = std::time::Instant::now();
94 let (mut rows, mut strings, stats) = match extract::extract(&args.input, args.bbox.as_ref()) {
95 Ok(v) => v,
96 Err(e) => {
97 eprintln!("error: {e}");
98 return ExitCode::FAILURE;
99 }
100 };
101 println!(
102 "Extracted {} row(s) in {:.1}s",
103 commas(stats.rows()),
104 started.elapsed().as_secs_f64()
105 );
106 println!(
107 " {} address, {} street sample, {} POI, {} place",
108 commas(stats.addresses),
109 commas(stats.streets),
110 commas(stats.pois),
111 commas(stats.places)
112 );
113 println!(
114 " from {} node(s), {} way(s), {} relation(s); {} incomplete, {} outside bbox",
115 commas(stats.from_nodes),
116 commas(stats.from_ways),
117 commas(stats.from_relations),
118 commas(stats.incomplete),
119 commas(stats.outside_bbox)
120 );
121
122 let t = std::time::Instant::now();
123 let report = match write::write(&args.out, &mut rows, &mut strings) {
124 Ok(r) => r,
125 Err(e) => {
126 eprintln!("error: writing {}: {e}", args.out.display());
127 return ExitCode::FAILURE;
128 }
129 };
130 println!("Wrote {} in {:.1}s", args.out.display(), t.elapsed().as_secs_f64());
131 println!(
132 " {} ({} records, {:.1} bits/record)",
133 human_bytes(report.total),
134 commas(report.n),
135 report.bits_per_record()
136 );
137 for (name, bytes) in report.dicts.iter().chain(report.columns.iter()) {
138 println!(" {name:<9} {:>12}", human_bytes(*bytes));
139 }
140 println!(" {:<9} {:>12}", "grid", human_bytes(report.grid));
141 println!(" {:<9} {:>12}", "fwd", human_bytes(report.fwd));
142 println!(" {:<9} {:>12}", "nameidx", human_bytes(report.name_index));
143 for (name, count) in &report.dict_counts {
144 println!(" dict {name:<9} {:>12} distinct", commas(*count));
145 }
146
147 if args.verify {
148 let t = std::time::Instant::now();
149 if let Err(e) = write::verify(&args.out, &rows) {
150 eprintln!("error: verification failed: {e}");
151 return ExitCode::FAILURE;
152 }
153 println!("Verified {} record(s) in {:.1}s", commas(report.n), t.elapsed().as_secs_f64());
154 } else {
155 eprintln!("WARNING: --no-verify; the database was not read back");
156 }
157
158 println!("Peak RSS: {}", osm_ingest::mem::peak_rss_report());
159 println!("Total {:.1}s", started.elapsed().as_secs_f64());
160 ExitCode::SUCCESS
161}