curtilage 0.3.0 → 0.4.0

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.
Files changed (45) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +75 -0
  3. data/README.md +76 -22
  4. data/SECURITY.md +18 -3
  5. data/docs/reference.md +221 -27
  6. data/docs/schema/site-v1.json +362 -0
  7. data/docs/security.md +69 -0
  8. data/exe/curtilage +375 -82
  9. data/lib/curtilage/audit.rb +5 -5
  10. data/lib/curtilage/auto_data.rb +61 -11
  11. data/lib/curtilage/batch.rb +116 -0
  12. data/lib/curtilage/build.rb +117 -63
  13. data/lib/curtilage/candidates.rb +67 -0
  14. data/lib/curtilage/catalogue.rb +44 -16
  15. data/lib/curtilage/confidence.rb +55 -0
  16. data/lib/curtilage/config.rb +24 -2
  17. data/lib/curtilage/corrections.rb +57 -0
  18. data/lib/curtilage/diff.rb +90 -0
  19. data/lib/curtilage/doctor.rb +92 -0
  20. data/lib/curtilage/download.rb +42 -16
  21. data/lib/curtilage/duckdb.rb +170 -6
  22. data/lib/curtilage/error.rb +3 -0
  23. data/lib/curtilage/features.rb +54 -5
  24. data/lib/curtilage/formats.rb +271 -36
  25. data/lib/curtilage/generator.rb +145 -166
  26. data/lib/curtilage/generator_details.rb +22 -14
  27. data/lib/curtilage/generator_lot.rb +56 -32
  28. data/lib/curtilage/generator_pin.rb +74 -0
  29. data/lib/curtilage/generator_roads.rb +109 -0
  30. data/lib/curtilage/generator_steps.rb +54 -0
  31. data/lib/curtilage/generator_store.rb +18 -4
  32. data/lib/curtilage/generator_zones.rb +93 -0
  33. data/lib/curtilage/geometry.rb +48 -52
  34. data/lib/curtilage/lookup.rb +41 -21
  35. data/lib/curtilage/overture.rb +137 -17
  36. data/lib/curtilage/preview.rb +55 -16
  37. data/lib/curtilage/profiles.rb +62 -0
  38. data/lib/curtilage/regions.rb +4 -8
  39. data/lib/curtilage/result.rb +72 -7
  40. data/lib/curtilage/validation.rb +73 -9
  41. data/lib/curtilage/version.rb +1 -1
  42. data/lib/curtilage/zip_range.rb +81 -16
  43. data/lib/curtilage.rb +155 -17
  44. data/sql/build_from_shapefiles.sql +1 -1
  45. metadata +15 -2
data/exe/curtilage CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env ruby
2
2
  # frozen_string_literal: true
3
3
 
4
+ require "fileutils"
4
5
  require "optparse"
5
6
  require "json"
6
- require "open3"
7
7
  require "tmpdir"
8
8
  require "curtilage"
9
9
 
@@ -11,21 +11,76 @@ USAGE = <<~TEXT
11
11
  Usage:
12
12
  curtilage generate (--pin LNG,LAT ... | --in FILE) [--out FILE] [options]
13
13
  curtilage preview (--pin LNG,LAT ... | --in FILE) [--out FILE] [options]
14
+ curtilage places (--region NAME | --bbox W,S,E,N) (--category NAME | --brand NAME | --place-id ID ...)
15
+ curtilage diff OLD NEW [--threshold IOU] [--out FILE]
14
16
  curtilage build REGION [options]
15
17
  curtilage doctor
16
18
 
17
19
  generate The premises (and store zone) for one or more pins, as GeoJSON,
18
- CSV or KML. Pins from --pin or a CSV/GeoJSON file. Map data is
19
- fetched as needed: nothing to set up or host.
20
+ NDJSON, CSV or KML. Pins from --pin, a CSV/GeoJSON/NDJSON file or
21
+ standard input. Map data is fetched as needed: nothing to set up
22
+ or host.
20
23
  preview Generate, then write an HTML page with a map of each site to
21
24
  check by eye (it loads nothing from the internet).
25
+ places Pins from Overture Maps places (a category or brand in a region),
26
+ to feed generate when you have no pin list.
27
+ diff Compare two runs (GeoJSON or NDJSON) site by site, marking
28
+ sites whose premises changed enough to review again.
22
29
  build Build a region's map data ahead of time (a US state such as
23
30
  "tennessee", or a Geofabrik path such as "europe/germany/bayern").
24
31
  doctor Check that DuckDB and its extensions are ready.
25
32
 
26
- Run "curtilage COMMAND --help" for a command's options.
33
+ Run "curtilage COMMAND --help" for a command's options. Results go to
34
+ standard output, everything else to standard error.
35
+
36
+ Exit codes: 0 ok, 1 some sites have no usable premises, 2 bad input or
37
+ usage, 3 DuckDB missing, 4 map data unavailable, 70 unexpected error.
27
38
  TEXT
28
39
 
40
+ # Everything but results goes to standard error, so standard output can be
41
+ # piped. Anything with puts can take it as a log (builds write progress).
42
+ class CliLog
43
+ def initialize
44
+ @quiet = false
45
+ @json = false
46
+ end
47
+
48
+ def configure(opts)
49
+ @quiet = opts[:quiet]
50
+ @json = opts[:log_format] == "json"
51
+ end
52
+
53
+ # Progress and summaries (hidden by --quiet); a line starting "warning:"
54
+ # is a warning, which --quiet keeps.
55
+ def puts(message)
56
+ warning = message.to_s.start_with?("warning:")
57
+ write(warning ? "warning" : "info", message) if warning || !@quiet
58
+ end
59
+
60
+ def error(message) = write("error", message)
61
+
62
+ private
63
+
64
+ def write(level, message)
65
+ warn(@json ? JSON.generate(level: level, message: message.to_s) : message)
66
+ end
67
+ end
68
+
69
+ LOG = CliLog.new
70
+
71
+ def log_flags(parser, opts)
72
+ parser.on("--quiet", "Only warnings and errors on standard error") { opts[:quiet] = true }
73
+ parser.on("--log-format FORMAT", %w[text json], "text (default) or json: one object per line") do |v|
74
+ opts[:log_format] = v
75
+ end
76
+ end
77
+
78
+ def parse(parser, args, opts)
79
+ parser.parse!(args)
80
+ LOG.configure(opts)
81
+ opts
82
+ end
83
+
29
84
  def duckdb_flags(parser, opts)
30
85
  parser.on("--duckdb PATH", "DuckDB CLI (default: $CURTILAGE_DUCKDB or duckdb on PATH)") { |v| opts[:duckdb] = v }
31
86
  parser.on("--extension-directory DIR", "DuckDB extension folder (default: $CURTILAGE_EXTENSIONS)") do |v|
@@ -35,53 +90,104 @@ end
35
90
 
36
91
  def generate_options(args, command)
37
92
  opts = { pins: [] }
38
- OptionParser.new do |o|
39
- o.banner = "Usage: curtilage #{command} (--pin LNG,LAT ... | --in FILE) [--out FILE] [options]"
93
+ parser = OptionParser.new do |o|
94
+ o.banner = "Usage: curtilage #{command} (--pin LNG,LAT ... | --in FILE|-) [--out FILE] [options]"
40
95
  io_flags(o, opts, command)
41
96
  data_flags(o, opts)
42
97
  style_flags(o, opts)
43
98
  duckdb_flags(o, opts)
44
- end.parse!(args)
45
- opts
99
+ log_flags(o, opts)
100
+ end
101
+ parse(parser, args, opts)
46
102
  end
47
103
 
48
104
  def io_flags(o, opts, command)
49
- o.on("--pin LNG,LAT", "A location; repeat for several") { |v| opts[:pins] << v.split(",").map { |n| Float(n) } }
50
- o.on("--in FILE", "Pins from a CSV (lng and lat columns, optional id) or GeoJSON (Point features)") do |v|
105
+ o.on("--pin LNG,LAT", "A location; repeat for several") { |v| opts[:pins] << v }
106
+ o.on("--in FILE", "Pins from a CSV (lng and lat columns, optional id), GeoJSON (Point features) or NDJSON;",
107
+ "- reads standard input (NDJSON unless --in-format says otherwise)") do |v|
51
108
  opts[:in] = v
52
109
  end
53
- if command == "preview"
54
- o.on("--out FILE", "Where to write the page (default: curtilage-preview.html)") { |v| opts[:out] = v }
55
- o.on("--buffer METRES", Float, "Also draw the premises grown by this much (a geofence margin)") do |v|
56
- opts[:buffer] = v
57
- end
58
- else
59
- o.on("--out FILE", "Write here instead of printing; the format follows the extension") { |v| opts[:out] = v }
60
- o.on("--format NAME", Curtilage::Formats::OUTPUTS.map(&:to_s), "geojson (default), csv or kml") do |v|
61
- opts[:format] = v.to_sym
62
- end
110
+ o.on("--corrections FILE", "Use these polygons for sites with the same id (GeoJSON or NDJSON) " \
111
+ "instead of generating them") { |v| opts[:corrections] = v }
112
+ o.on("--in-format NAME", Curtilage::Formats::INPUTS.map(&:to_s),
113
+ "csv, geojson or ndjson (default: from --in's extension)") do |v|
114
+ opts[:in_format] = v.to_sym
115
+ end
116
+ command == "preview" ? page_flags(o, opts) : output_flags(o, opts)
117
+ end
118
+
119
+ def page_flags(o, opts)
120
+ o.on("--out FILE", "Where to write the page (default: curtilage-preview.html)") { |v| opts[:out] = v }
121
+ o.on("--buffer METRES", Float, "Also draw the premises grown by this much (a geofence margin)") do |v|
122
+ opts[:buffer] = v
123
+ end
124
+ end
125
+
126
+ def output_flags(o, opts)
127
+ o.on("--out FILE", "Write here instead of printing; the format follows the extension") { |v| opts[:out] = v }
128
+ o.on("--format NAME", Curtilage::Formats::OUTPUTS.map(&:to_s), "geojson (default), ndjson, csv or kml") do |v|
129
+ opts[:format] = v.to_sym
130
+ end
131
+ o.on("--min-confidence N", Float, "Leave out results with confidence below N (0 to 1)") do |v|
132
+ raise ArgumentError, "--min-confidence is 0 to 1: #{v}" unless v.between?(0, 1)
133
+
134
+ opts[:min_confidence] = v
63
135
  end
136
+ o.on("--resume", "Carry on an interrupted run into --out FILE.ndjson or .csv, skipping finished sites") do
137
+ opts[:resume] = true
138
+ end
139
+ o.on("--progress", "Show progress even when standard error isn't a terminal") { opts[:progress] = true }
64
140
  end
65
141
 
66
142
  # [pins, ids] from --pin and --in.
67
- def read_sites(opts, command)
68
- sites = opts[:pins].map.with_index(1) { |pin, i| { id: i.to_s, pin: pin } }
69
- sites += Curtilage::Formats.read_pins(opts[:in]) if opts[:in]
70
- abort "curtilage #{command}: give --pin LNG,LAT or --in FILE" if sites.empty?
143
+ def read_sites(opts)
144
+ sites = opts[:pins].map.with_index(1) { |pin, i| { id: i.to_s, pin: Curtilage::Formats.pin_from_text(pin) } }
145
+ sites += read_input(opts) if opts[:in]
146
+ raise ArgumentError, "give --pin LNG,LAT or --in FILE" if sites.empty?
147
+
71
148
  bad = sites.find { |s| !Curtilage::Formats.pin?(s[:pin]) }
72
- abort "curtilage #{command}: #{bad[:id]}: a pin is LNG,LAT (longitude first)" if bad
149
+ raise ArgumentError, "#{bad[:id]}: a pin is LNG,LAT (longitude first)" if bad
150
+
73
151
  [sites.map { |s| s[:pin] }, sites.map { |s| s[:id] }]
74
- rescue ArgumentError, SystemCallError => e
75
- abort "curtilage #{command}: #{e.message}"
152
+ rescue SystemCallError => e
153
+ raise ArgumentError, e.message
154
+ end
155
+
156
+ def read_input(opts)
157
+ return Curtilage::Formats.read_pins(opts[:in], format: opts[:in_format]) unless opts[:in] == "-"
158
+
159
+ text = $stdin.binmode.read(Curtilage::Formats::MAX_BYTES + 1).to_s
160
+ Curtilage::Formats.parse_pins(text, opts[:in_format] || :ndjson)
161
+ end
162
+
163
+ # --preset NAME from --profiles FILE becomes that profile's options.
164
+ def style(opts)
165
+ style = opts.slice(:preset, :buildings, :store_zone, :approach_m, :pickup_m, :snap_m, :candidates)
166
+ return style unless opts[:profiles]
167
+
168
+ profiles = Curtilage::Profiles.load(opts[:profiles])
169
+ return style unless profiles.key?(style[:preset])
170
+
171
+ profiles[style.delete(:preset)].merge(style)
172
+ end
173
+
174
+ # { pin index => { ring:, store_ring: } } for the sites --corrections has
175
+ # a premises polygon for, matched by id.
176
+ def corrections(opts, ids)
177
+ return {} unless opts[:corrections]
178
+
179
+ found = Curtilage::Formats.read_results(opts[:corrections]).select { |_, c| c[:ring] }
180
+ index = ids.each_with_index.to_h
181
+ unmatched = found.keys.reject { |id| index.key?(id) }
182
+ LOG.puts "warning: #{unmatched.size} correction(s) match no site id, e.g. #{unmatched.first}" if unmatched.any?
183
+ found.filter_map { |id, c| [index[id], c.slice(:ring, :store_ring)] if index.key?(id) }.to_h
76
184
  end
77
185
 
78
186
  def run(opts, pins, **extra)
79
187
  catalogue = opts[:catalogue] && Curtilage::Catalogue.from_dir(opts[:catalogue])
80
188
  Curtilage.generate_many(pins, catalogue: catalogue, **opts.slice(:parquet, :source, :cache_dir),
81
- lookup: opts.slice(:duckdb, :extension_directory),
82
- **opts.slice(:preset, :buildings, :store_zone), **extra)
83
- rescue Curtilage::Error, ArgumentError => e
84
- abort "curtilage: #{e.message}"
189
+ lookup: opts.slice(:duckdb, :extension_directory), data: { log: LOG },
190
+ **style(opts), **extra)
85
191
  end
86
192
 
87
193
  def data_flags(o, opts)
@@ -95,41 +201,211 @@ def data_flags(o, opts)
95
201
  end
96
202
 
97
203
  def style_flags(o, opts)
98
- o.on("--preset NAME", Curtilage::PRESETS.keys.map(&:to_s), "whole_lot (default), tight or centre") do |v|
204
+ o.on("--preset NAME", "whole_lot (default), tight, centre, or a profile from --profiles") do |v|
99
205
  opts[:preset] = v.to_sym
100
206
  end
207
+ o.on("--profiles FILE", "Your own named styles (JSON or YAML) for --preset") { |v| opts[:profiles] = v }
101
208
  o.on("--buildings FLAVOUR", Curtilage::Generator::BUILDING_SOURCES.map(&:to_s),
102
209
  "osm (default), osm_filled or ml") { |v| opts[:buildings] = v.to_sym }
103
210
  o.on("--[no-]store", "Include the store zone (default: yes)") { |v| opts[:store_zone] = v }
211
+ o.on("--snap [METRES]", Float, "Move pins that aren't on a building onto the nearest one within METRES " \
212
+ "(default #{Curtilage::Generator::DEFAULT_SNAP_M})") do |v|
213
+ opts[:snap_m] = v || Curtilage::Generator::DEFAULT_SNAP_M
214
+ end
215
+ o.on("--candidates N", Integer, "Also give up to N other premises for ambiguous sites (1 to 5)") do |v|
216
+ opts[:candidates] = v
217
+ end
218
+ o.on("--approach [METRES]", Float, "Add an approach zone: the premises grown by METRES " \
219
+ "(default #{Curtilage::Generator::DEFAULT_APPROACH_M})") do |v|
220
+ opts[:approach_m] = v || Curtilage::Generator::DEFAULT_APPROACH_M
221
+ end
222
+ o.on("--pickup [METRES]", Float, "Add an estimated pickup zone: mapped parking within METRES of the building " \
223
+ "(default #{Curtilage::Generator::DEFAULT_PICKUP_M})") do |v|
224
+ opts[:pickup_m] = v || Curtilage::Generator::DEFAULT_PICKUP_M
225
+ end
226
+ end
227
+
228
+ # Refuses an output path that's a symbolic link (it could point anywhere),
229
+ # before any work is done.
230
+ def check_out(path)
231
+ raise ArgumentError, "#{path} is a symbolic link; refusing to write through it" if path && File.symlink?(path)
232
+ end
233
+
234
+ # Writes next to the target and renames, so a reader never sees half a file
235
+ # and an interrupted run leaves the old one in place.
236
+ def write_out(path, text)
237
+ check_out(path)
238
+ part = File.join(File.dirname(File.expand_path(path)), ".#{File.basename(path)}.#{Process.pid}.part")
239
+ File.write(part, text)
240
+ File.rename(part, path)
241
+ rescue SystemCallError => e
242
+ FileUtils.rm_f(part) if part
243
+ raise ArgumentError, "can't write #{path}: #{e.message}"
104
244
  end
105
245
 
246
+ # In chunks of Batch::CHUNK sites: progress shows, NDJSON and CSV stream
247
+ # (memory stays flat) and an interrupted run can --resume.
106
248
  def generate(args)
107
249
  opts = generate_options(args, "generate")
108
250
  format = opts[:format] || Curtilage::Formats.format_of(opts[:out]) || :geojson
109
- pins, ids = read_sites(opts, "generate")
110
- results = run(opts, pins)
111
- text = Curtilage::Formats.write(results, format, ids: ids, store: opts.fetch(:store_zone, true))
112
- if opts[:out]
113
- File.write(opts[:out], text)
114
- warn "#{results.count(&:ok?)} of #{results.size} ok; wrote #{opts[:out]}"
251
+ check_out(opts[:out])
252
+ pins, ids = read_sites(opts)
253
+ batch = open_batch(opts, format, ids)
254
+ todo = ids.each_index.reject { |i| batch.done.include?(ids[i]) }
255
+ totals = run_batch(opts, [pins, ids], todo, corrections(opts, ids), batch)
256
+ batch.finish { |text| write_out(opts[:out], text) }
257
+ report(totals, opts)
258
+ exit(totals[:kept] == totals[:all] && totals[:ok] == totals[:all] ? 0 : 1)
259
+ end
260
+
261
+ def open_batch(opts, format, ids)
262
+ raise ArgumentError, "--resume needs unique site ids" if opts[:resume] && ids.uniq.size != ids.size
263
+
264
+ Curtilage::Batch.new(format: format, out: opts[:out], store: opts.fetch(:store_zone, true), resume: opts[:resume])
265
+ end
266
+
267
+ def run_batch(opts, sites, todo, fixes, batch)
268
+ pins, ids = sites
269
+ totals = Hash.new(0)
270
+ progress = Curtilage::Batch::Progress.new(todo.size) if opts[:progress] || ($stderr.tty? && !opts[:quiet])
271
+ with_run_cache(opts, todo.size) do |cache|
272
+ todo.each_slice(Curtilage::Batch::CHUNK) do |chunk|
273
+ local = chunk.each_with_index.filter_map { |g, i| [i, fixes[g]] if fixes[g] }.to_h
274
+ results = run(opts.merge(cache_dir: cache), pins.values_at(*chunk), corrections: local)
275
+ batch.add(*confident(results, ids.values_at(*chunk), opts[:min_confidence]))
276
+ count(totals, results, opts[:min_confidence])
277
+ progress&.step(chunk.size)
278
+ end
279
+ end
280
+ progress&.finish
281
+ totals
282
+ end
283
+
284
+ def count(totals, results, min)
285
+ totals[:all] += results.size
286
+ totals[:ok] += results.count(&:ok?)
287
+ totals[:kept] += min ? results.count { |r| r.confidence >= min } : results.size
288
+ end
289
+
290
+ def report(totals, opts)
291
+ left = totals[:all] - totals[:kept]
292
+ LOG.puts "#{left} result(s) below --min-confidence #{opts[:min_confidence]} left out" if left.positive?
293
+ LOG.puts "#{totals[:ok]} of #{totals[:all]} ok; wrote #{opts[:out]}" if opts[:out]
294
+ end
295
+
296
+ # A Geofabrik region a run builds is reused by every chunk: without
297
+ # --cache-dir, a temporary cache lasts the run.
298
+ def with_run_cache(opts, count)
299
+ shared = count > Curtilage::Batch::CHUNK && opts[:source] != :overture &&
300
+ !(opts[:cache_dir] || opts[:catalogue] || opts[:parquet])
301
+ dir = Dir.mktmpdir("curtilage-run") if shared
302
+ yield dir || opts[:cache_dir]
303
+ ensure
304
+ FileUtils.rm_rf(dir) if dir
305
+ end
306
+
307
+ # Writes text to out, or prints it.
308
+ def deliver(text, out, summary)
309
+ if out
310
+ write_out(out, text)
311
+ LOG.puts "#{summary}; wrote #{out}"
115
312
  else
116
- puts text
313
+ $stdout.write(text.empty? || text.end_with?("\n") ? text : "#{text}\n")
117
314
  end
118
- exit(results.all?(&:ok?) ? 0 : 1)
315
+ end
316
+
317
+ # [results, ids] at or above the minimum confidence (all of them without one).
318
+ def confident(results, ids, min)
319
+ return [results, ids] unless min
320
+
321
+ kept = results.zip(ids).select { |result, _| result.confidence >= min }
322
+ [kept.map(&:first), kept.map(&:last)]
119
323
  end
120
324
 
121
325
  def preview(args)
122
326
  opts = generate_options(args, "preview")
123
- pins, ids = read_sites(opts, "preview")
124
- results = run(opts, pins, keep_features: true)
125
327
  out = opts[:out] || "curtilage-preview.html"
126
- File.write(out, Curtilage::Preview.html(results, ids: ids, buffer_m: opts[:buffer]))
127
- puts "#{results.count(&:ok?)} of #{results.size} ok; open #{File.expand_path(out)}"
328
+ check_out(out)
329
+ pins, ids = read_sites(opts)
330
+ results = run(opts, pins, keep_features: true, corrections: corrections(opts, ids))
331
+ write_out(out, Curtilage::Preview.html(results, ids: ids, buffer_m: opts[:buffer]))
332
+ LOG.puts "#{results.count(&:ok?)} of #{results.size} ok; open #{File.expand_path(out)}"
333
+ exit(results.all?(&:ok?) ? 0 : 1)
128
334
  end
129
335
 
130
- def build(args)
131
- opts = { out: ".", work: File.join(Dir.tmpdir, "curtilage-build") }
132
- OptionParser.new do |o|
336
+ def places_options(args)
337
+ opts = { ids: [] }
338
+ parser = OptionParser.new do |o|
339
+ o.banner = "Usage: curtilage places (--region NAME | --bbox W,S,E,N) (--category | --brand | --place-id) ..."
340
+ o.on("--region NAME", "A US state (virginia) or Geofabrik path (europe/germany/bayern)") { |v| opts[:region] = v }
341
+ o.on("--bbox W,S,E,N", Array, "A box instead: west,south,east,north") do |v|
342
+ opts[:bbox] = v.map { |x| Curtilage::Formats.number(x, "--bbox") }
343
+ end
344
+ place_filter_flags(o, opts)
345
+ o.on("--release NAME", "An Overture release, e.g. 2026-11-18.0 (default: the latest)") { |v| opts[:release] = v }
346
+ o.on("--out FILE", "Write here instead of printing; the format follows the extension") { |v| opts[:out] = v }
347
+ o.on("--format NAME", %w[csv ndjson geojson], "csv (default), ndjson or geojson") { |v| opts[:format] = v.to_sym }
348
+ duckdb_flags(o, opts)
349
+ log_flags(o, opts)
350
+ end
351
+ parse(parser, args, opts)
352
+ end
353
+
354
+ def place_filter_flags(o, opts)
355
+ o.on("--category NAME", "An Overture category at any level (pharmacy, health_care)") { |v| opts[:category] = v }
356
+ o.on("--brand NAME", "A brand's name, any case") { |v| opts[:brand] = v }
357
+ o.on("--place-id ID", "An Overture place id; repeat for several") { |v| opts[:ids] << v }
358
+ o.on("--min-confidence N", Float, "Only places Overture is at least this sure of (0 to 1)") do |v|
359
+ opts[:min_confidence] = v
360
+ end
361
+ end
362
+
363
+ # Places are inputs, not results: their licences are the sources' (named
364
+ # per place), and premises made from them stay ODbL like any other.
365
+ def places(args)
366
+ opts = places_options(args)
367
+ check_out(opts[:out])
368
+ filter = opts.slice(:category, :brand, :min_confidence, :release).merge(ids: (opts[:ids] unless opts[:ids].empty?))
369
+ found = Curtilage.places(**opts.slice(:region, :bbox), **filter.compact, **opts.slice(:duckdb, :extension_directory))
370
+ format = opts[:format] || Curtilage::Formats.format_of(opts[:out]) || :csv
371
+ text = Curtilage::Formats.write_places(found, format)
372
+ opts[:out] ? write_out(opts[:out], text) : $stdout.write(text)
373
+ LOG.puts "#{found.size} place(s) from Overture Maps; each row names its sources and licences " \
374
+ "(CDLA Permissive 2.0, CC0 or Apache 2.0)"
375
+ end
376
+
377
+ def diff_options(args)
378
+ opts = {}
379
+ parser = OptionParser.new do |o|
380
+ o.banner = "Usage: curtilage diff OLD NEW [options]"
381
+ o.on("--threshold IOU", Float, "Review sites whose premises overlap the old less than this " \
382
+ "(default #{Curtilage::Diff::REVIEW_IOU})") { |v| opts[:threshold] = v }
383
+ o.on("--out FILE", "Write here instead of printing; the format follows the extension") { |v| opts[:out] = v }
384
+ o.on("--format NAME", %w[csv ndjson], "csv (default) or ndjson") { |v| opts[:format] = v.to_sym }
385
+ log_flags(o, opts)
386
+ end
387
+ parse(parser, args, opts)
388
+ end
389
+
390
+ def diff(args)
391
+ opts = diff_options(args)
392
+ old, new = args.shift(2)
393
+ raise ArgumentError, "give OLD and NEW result files" unless old && new
394
+
395
+ check_out(opts[:out])
396
+ rows = Curtilage::Diff.compare(Curtilage::Formats.read_results(old), Curtilage::Formats.read_results(new),
397
+ **opts.slice(:threshold))
398
+ format = opts[:format] || (Curtilage::Formats.format_of(opts[:out]) == :ndjson ? :ndjson : :csv)
399
+ review = rows.count { |r| r[:review] }
400
+ summary = "#{rows.size} site(s): #{rows.count { |r| r[:status] == "same" }} same, #{review} to review"
401
+ deliver(Curtilage::Diff.write(rows, format), opts[:out], summary)
402
+ LOG.puts summary unless opts[:out]
403
+ exit(review.zero? ? 0 : 1)
404
+ end
405
+
406
+ def build_options(args)
407
+ opts = { out: "." }
408
+ parser = OptionParser.new do |o|
133
409
  o.banner = "Usage: curtilage build REGION [options]"
134
410
  o.on("--out DIR", "Where to write REGION.parquet and REGION.json (default: .)") { |v| opts[:out] = v }
135
411
  o.on("--work DIR", "Download folder (default: a temporary one)") { |v| opts[:work] = v }
@@ -139,51 +415,68 @@ def build(args)
139
415
  opts[:ml] = v
140
416
  end
141
417
  duckdb_flags(o, opts)
142
- end.parse!(args)
143
- region = args.shift or abort "curtilage build: give a REGION, e.g. tennessee"
418
+ log_flags(o, opts)
419
+ end
420
+ parse(parser, args, opts)
421
+ end
422
+
423
+ def build(args)
424
+ opts = build_options(args)
425
+ region = args.shift or raise ArgumentError, "give a REGION, e.g. tennessee"
144
426
 
145
- puts Curtilage::Build.run(region, out_dir: opts[:out], work_dir: opts[:work], date: opts[:date],
146
- ml_footprints: opts[:ml], keep_downloads: opts[:keep],
427
+ # Without --work, a fresh private folder (a fixed name in a shared /tmp
428
+ # could be someone else's), removed afterwards unless downloads are kept.
429
+ work = opts[:work] || Dir.mktmpdir("curtilage-build")
430
+ puts Curtilage::Build.run(region, out_dir: opts[:out], work_dir: work, date: opts[:date],
431
+ ml_footprints: opts[:ml], keep_downloads: opts[:keep], log: LOG,
147
432
  **opts.slice(:duckdb, :extension_directory))
433
+ LOG.puts "downloads kept in #{work}" if opts[:keep] && !opts[:work]
434
+ ensure
435
+ FileUtils.rm_rf(work) if work && !opts[:work] && !opts[:keep]
148
436
  end
149
437
 
150
438
  def doctor(args)
151
439
  opts = {}
152
- OptionParser.new { |o| duckdb_flags(o, opts) }.parse!(args)
153
- settings = Curtilage.duckdb_options(opts)
154
- check_duckdb(settings)
155
- check_extensions(settings)
156
- puts "Ready."
440
+ OptionParser.new do |o|
441
+ o.on("--verify DIR", "Check each built file in DIR (catalogue or cache folder) against its recorded SHA256") do |v|
442
+ opts[:verify] = v
443
+ end
444
+ o.on("--network", "Also check that the map-data hosts answer (no locations are sent)") { opts[:network] = true }
445
+ o.on("--json", "Print the report as JSON, for scripts") { opts[:json] = true }
446
+ duckdb_flags(o, opts)
447
+ end.parse!(args)
448
+ report = Curtilage::Doctor.report(Curtilage.duckdb_options(opts.slice(:duckdb, :extension_directory)),
449
+ network: opts[:network], verify: opts[:verify])
450
+ puts opts[:json] ? JSON.pretty_generate(report) : Curtilage::Doctor.text(report)
451
+ exit(report["ok"] ? 0 : 1)
157
452
  end
158
453
 
159
- def check_duckdb(settings)
160
- version, status = Open3.capture2(settings[:duckdb], "--version")
161
- raise Errno::ENOENT unless status.success?
162
-
163
- puts "DuckDB: #{version.strip}"
164
- rescue Errno::ENOENT
165
- abort "DuckDB CLI not found (#{settings[:duckdb]}). Install DuckDB 1.4 (https://duckdb.org/docs/installation/), " \
166
- "or set CURTILAGE_DUCKDB to its path."
167
- end
454
+ COMMANDS = %w[generate preview places diff build doctor].freeze
168
455
 
169
- def check_extensions(settings)
170
- dir = settings[:extension_directory]
171
- sql = [("SET extension_directory = '#{dir.gsub("'", "''")}';" if dir),
172
- "INSTALL spatial; LOAD spatial; INSTALL httpfs; LOAD httpfs;"].compact.join("\n")
173
- _, err, status = Open3.capture3(settings[:duckdb], stdin_data: sql)
174
- unless status.success?
175
- abort "DuckDB extensions (spatial, httpfs) could not be installed or loaded: #{err.strip[0,
176
- 300]}"
456
+ def exit_code(error)
457
+ case error
458
+ when Curtilage::DependencyError then 3
459
+ when Curtilage::Error then 4
460
+ else 2
177
461
  end
178
-
179
- puts "Extensions: spatial and httpfs ready"
180
462
  end
181
463
 
182
- case ARGV.shift
183
- when "generate" then generate(ARGV)
184
- when "preview" then preview(ARGV)
185
- when "build" then build(ARGV)
186
- when "doctor" then doctor(ARGV)
187
- when "-h", "--help", "help", nil then puts USAGE
188
- else abort USAGE
464
+ command = ARGV.shift
465
+ begin
466
+ case command
467
+ when *COMMANDS then send(command, ARGV)
468
+ when "-h", "--help", "help", nil then puts USAGE
469
+ else
470
+ warn USAGE
471
+ exit 2
472
+ end
473
+ rescue OptionParser::ParseError, ArgumentError, Curtilage::Error => e
474
+ LOG.error("curtilage #{command}: #{e.message}")
475
+ exit exit_code(e)
476
+ rescue StandardError => e
477
+ # A bug, not bad input or missing data: keep exit 1 meaning "some sites
478
+ # failed" and say where it happened, for a report.
479
+ LOG.error("curtilage #{command}: unexpected error (please report it): #{e.class}: #{e.message}\n " \
480
+ "#{e.backtrace&.first(5)&.join("\n ")}")
481
+ exit 70
189
482
  end
@@ -18,11 +18,11 @@ module Curtilage
18
18
 
19
19
  # verdict: :invalid (fails validation), :review (see reasons) or :ok.
20
20
  # options go to Curtilage.generate.
21
- def check(pin, ring, features, thresholds: {}, **)
21
+ def check(pin, ring, features, thresholds: {}, **options)
22
22
  limits = THRESHOLDS.merge(thresholds)
23
23
  features = Features.new(pin, features) unless features.is_a?(Features)
24
- validation = Validation.check(pin, ring)
25
- generated = Curtilage.generate(pin, features, **)
24
+ validation = Validation.check(pin, ring, **options.fetch(:validation, {}))
25
+ generated = Curtilage.generate(pin, features, **options)
26
26
  return Report.new(verdict: :invalid, reasons: validation.errors, validation: validation, generated: generated) \
27
27
  unless validation.ok?
28
28
 
@@ -61,12 +61,12 @@ module Curtilage
61
61
 
62
62
  # Metres of public road and railway more than 1 m inside the polygon.
63
63
  def road_length(xy, features)
64
- lines = features.roads.select { |r| Generator::PUBLIC_HIGHWAYS.include?(r.highway) } + features.railways
64
+ lines = features.public_roads + features.railways
65
65
  lines.sum { |line| line.xy.each_cons(2).sum { |a, b| inside_length(xy, a, b) } }
66
66
  end
67
67
 
68
68
  def inside_length(xy, a, b)
69
- length = Math.hypot(b[0] - a[0], b[1] - a[1])
69
+ length = Geometry.distance(a, b)
70
70
  n = [length.ceil, 1].max
71
71
  inside = n.times.count do |i|
72
72
  p = Geometry.lerp(a, b, (i + 0.5) / n)