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/lib/curtilage.rb CHANGED
@@ -8,10 +8,20 @@ require_relative "curtilage/geometry"
8
8
  require_relative "curtilage/validation"
9
9
  require_relative "curtilage/features"
10
10
  require_relative "curtilage/result"
11
+ require_relative "curtilage/confidence"
11
12
  require_relative "curtilage/generator"
12
13
  require_relative "curtilage/generator_lot"
14
+ require_relative "curtilage/generator_roads"
13
15
  require_relative "curtilage/generator_store"
14
16
  require_relative "curtilage/generator_details"
17
+ require_relative "curtilage/generator_steps"
18
+ require_relative "curtilage/generator_zones"
19
+ require_relative "curtilage/generator_pin"
20
+ require_relative "curtilage/candidates"
21
+ require_relative "curtilage/profiles"
22
+ require_relative "curtilage/corrections"
23
+ require_relative "curtilage/diff"
24
+ require_relative "curtilage/batch"
15
25
  require_relative "curtilage/lookup"
16
26
  require_relative "curtilage/download"
17
27
  require_relative "curtilage/zip_range"
@@ -24,6 +34,7 @@ require_relative "curtilage/overture"
24
34
  require_relative "curtilage/audit"
25
35
  require_relative "curtilage/formats"
26
36
  require_relative "curtilage/preview"
37
+ require_relative "curtilage/doctor"
27
38
 
28
39
  # Premises generation from OpenStreetMap data. Coordinates are [lng, lat]
29
40
  # throughout, matching GeoJSON.
@@ -37,10 +48,12 @@ module Curtilage
37
48
  building_not_under_pin: "No building under the pin; the nearest one within 30 m was used.",
38
49
  store_may_be_unit: "The store zone is a building over 1,500 m2: the store may be one unit of it.",
39
50
  shopping_centre: "The whole shopping centre was mapped (scope: :centre).",
51
+ pin_moved: "The pin wasn't on a building and was moved onto the nearest one (snap_m:): check it's the right one.",
40
52
  fallback: "The main method failed validation; the building rectangle was used.",
41
53
  ml_footprint: "Built on a machine-learned footprint, not an OSM building.",
42
54
  no_data: "No map data covers the pin.",
43
55
  partial_data: "Part of the area around the pin is in a region that isn't built.",
56
+ error: "Generating this site raised an error (see its explanation); the rest of the batch went on.",
44
57
  }.freeze
45
58
 
46
59
  # Named styles; any option passed alongside a preset overrides it.
@@ -70,14 +83,40 @@ module Curtilage
70
83
  premises(pin, **, store_zone: false).details&.fetch(:building)
71
84
  end
72
85
 
86
+ # Places from Overture Maps to generate premises for, when you have no
87
+ # pins: one filter (category:, brand: or ids:, see Overture.places) inside
88
+ # a region (a US state such as "virginia", or a Geofabrik path, looked up
89
+ # in Geofabrik's region index and matched to its outline) or a bbox:
90
+ # [west, south, east, north]. Each place's pin feeds generate_many:
91
+ #
92
+ # places = Curtilage.places(region: "delaware", category: "pharmacy")
93
+ # results = Curtilage.generate_many(places.map { |p| p[:pin] })
94
+ def self.places(region: nil, bbox: nil, **)
95
+ raise ArgumentError, "give region: or bbox:, not both" unless region.nil? ^ bbox.nil?
96
+ return Overture.places(bbox: bbox, **) if bbox
97
+
98
+ path = Build.region_path(region)
99
+ area = Regions.download.regions.find { |r| r.path == path } or
100
+ raise ArgumentError, "no Geofabrik region #{path} (see https://download.geofabrik.de)"
101
+ Overture.places(bbox: area.bbox, **).select { |place| area.covers?(place[:pin]) }
102
+ end
103
+
73
104
  # Premises for one pin from features you already have (Lookup.features).
74
105
  # With no method or preset, the recommended method with its fallback
75
106
  # (Generator.propose).
76
- def self.generate(pin, features, method: nil, preset: nil, **options)
107
+ #
108
+ # candidates: N (1 to 5) also returns up to N other premises the site
109
+ # could have, in Result#candidates (see Candidates).
110
+ def self.generate(pin, features, method: nil, preset: nil, candidates: nil, **options)
77
111
  opts = preset_options(preset).merge(options)
78
112
  method ||= opts.delete(:method)
79
113
  opts.delete(:method)
80
- method ? Generator.generate(method, pin, features, **opts) : Generator.propose(pin, features, **opts)
114
+ result = method ? Generator.generate(method, pin, features, **opts) : Generator.propose(pin, features, **opts)
115
+ return result unless candidates
116
+
117
+ result.tap do |r|
118
+ r.candidates = Candidates.for(r, pin, features, { method: method, preset: preset, **options }.compact, candidates)
119
+ end
81
120
  end
82
121
 
83
122
  SOURCES = %i[auto geofabrik overture].freeze
@@ -85,6 +124,10 @@ module Curtilage
85
124
  # already cached); fewer pins are cheaper to read from Overture. Measured:
86
125
  # Overture about 5.6 s a pin, a mid-size US state about 60-90 s to build.
87
126
  AUTO_BUILD_MIN_PINS = 10
127
+ # One call's worth: more is likely a mistake, and a bigger batch should be
128
+ # split so a failure costs less (max_pins: raises it).
129
+ MAX_PINS_PER_CALL = 100_000
130
+ DATA_OPTIONS = %i[max_age_days ml_footprints parallel_builds log auto_build_min_pins release].freeze
88
131
 
89
132
  # Results for many pins, in pin order, looking features up once per group
90
133
  # of pins that share data.
@@ -105,14 +148,76 @@ module Curtilage
105
148
  # puts; default $stderr), release: (Overture). keep_features: true keeps each
106
149
  # result's map data (Result#features, which Preview draws); by default it's
107
150
  # dropped to save memory. Other options go to generate.
108
- def self.generate_many(pins, keep_features: false, **)
109
- results = fetch_and_generate(pins, **)
110
- results.each { |r| r.features = nil } unless keep_features
151
+ #
152
+ # corrections: { pin index => ring (or { ring:, store_ring: }) } uses
153
+ # those polygons instead of generating (see Corrections); their pins
154
+ # fetch no data.
155
+ def self.generate_many(pins, keep_features: false, max_pins: MAX_PINS_PER_CALL, corrections: {}, **options)
156
+ pins = checked_pins(pins, max_pins)
157
+ fixed = Corrections.checked(corrections, pins.size)
158
+ rest = pins.each_index.reject { |i| fixed.key?(i) }
159
+ generated = rest.empty? ? [] : fetch_and_generate(pins.values_at(*rest), **options)
160
+ manual = fixed.map do |i, c|
161
+ Corrections.result(pins[i], c[:ring], store_ring: c[:store_ring], validation: options.fetch(:validation, {}))
162
+ end
163
+ results = merge(pins.size, [rest, generated], [fixed.keys, manual])
164
+ results.each { |r| [r, *r.candidates].each { |c| c.features = nil } } unless keep_features
111
165
  results
112
166
  end
113
167
 
168
+ # Every pin checked before any data is fetched, so a bad one fails the
169
+ # call at once (naming it) rather than after builds have run.
170
+ def self.checked_pins(pins, max)
171
+ raise ArgumentError, "pins must be a list of [lng, lat] pins" unless pins.is_a?(Array)
172
+ raise ArgumentError, "#{pins.size} pins is more than max_pins (#{max}): split the batch" if pins.size > max
173
+
174
+ pins.each_with_index.map do |pin, i|
175
+ Validation.pin(pin)
176
+ rescue ArgumentError => e
177
+ raise ArgumentError, "pin #{i + 1}: #{e.message}"
178
+ end
179
+ end
180
+
181
+ # Options are checked once, before any work, so a mistake in them fails
182
+ # the call instead of turning every site into an error result.
183
+ def self.check_generation_options(options)
184
+ count = options[:candidates]
185
+ unless count.nil? || (count.is_a?(Integer) && count.between?(1, Candidates::MAX))
186
+ raise ArgumentError, "candidates must be a whole number from 1 to #{Candidates::MAX}: #{count.inspect}"
187
+ end
188
+
189
+ opts = preset_options(options[:preset]).merge(options.except(:preset, :candidates))
190
+ method = opts.delete(:method)
191
+ raise ArgumentError, "unknown method #{method.inspect}" if method && !Generator::METHODS.include?(method)
192
+
193
+ Generator.checked_options(opts)
194
+ end
195
+
196
+ # One site's result, never an exception: a site whose generation raises
197
+ # gets an error result (flag :error) and the rest of the batch goes on.
198
+ def self.generate_safely(pin, features, options)
199
+ generate(pin, features, **options)
200
+ rescue StandardError => e
201
+ Result.new(method_name: nil, pin: pin, flags: [:error], building: nil,
202
+ explanation: [], steps: [],
203
+ validation: Validation::Result.new(["error"], [], {}), provenance: { gem_version: VERSION })
204
+ .prepend_step("generating this site failed: #{e.class}: #{e.message[0, 300]}", step: "error", flag: :error)
205
+ end
206
+
207
+ def self.check_data(data)
208
+ unknown = data.keys - DATA_OPTIONS
209
+ raise ArgumentError, "unknown data: option(s): #{unknown.join(", ")} (have: #{DATA_OPTIONS.join(", ")})" \
210
+ if unknown.any?
211
+
212
+ min_pins = data.fetch(:auto_build_min_pins, AUTO_BUILD_MIN_PINS)
213
+ raise ArgumentError, "auto_build_min_pins must be a whole number from 1: #{min_pins.inspect}" \
214
+ unless min_pins.is_a?(Integer) && min_pins >= 1
215
+ end
216
+
114
217
  def self.fetch_and_generate(pins, source: nil, catalogue: nil, parquet: nil, cache_dir: nil, lookup: {}, data: {},
115
218
  **options)
219
+ check_data(data)
220
+ check_generation_options(options)
116
221
  lookup = duckdb_options(lookup)
117
222
  return run_many(pins, catalogue, parquet, lookup, options) if catalogue || parquet
118
223
 
@@ -172,7 +277,7 @@ module Curtilage
172
277
  return [] if pins.empty?
173
278
 
174
279
  run_many(pins, auto.catalogue_for(pins), nil, lookup, options).each do |r|
175
- r.explanation.unshift("map data: OpenStreetMap, built from Geofabrik")
280
+ r.prepend_step("map data: OpenStreetMap, built from Geofabrik", step: "data")
176
281
  end
177
282
  end
178
283
 
@@ -182,13 +287,17 @@ module Curtilage
182
287
  results
183
288
  end
184
289
 
290
+ # The release is settled once up front, so every result names the one
291
+ # it was read from.
185
292
  def self.from_overture(pins, lookup, data, options)
186
- lists = Overture.features_many(pins, **lookup.slice(:duckdb, :extension_directory, :radius_deg),
187
- **data.slice(:release))
293
+ online!("reading Overture Maps (use a catalogue or cached builds)")
294
+ release = Overture.release(data)
295
+ lists = Overture.features_many(pins, **lookup.slice(:duckdb, :extension_directory, :radius_deg), release: release)
188
296
  pins.zip(lists).map do |pin, features|
189
- generate(pin, features, **options).tap do |r|
190
- r.attribution = Overture::ATTRIBUTION
191
- r.explanation.unshift("map data: OpenStreetMap, read from Overture Maps")
297
+ generate_safely(pin, features, options).tap do |r|
298
+ r.provenance[:data] = { source: "overture", release: release }
299
+ r.attribution = Overture.attribution(r.features)
300
+ r.prepend_step("map data: OpenStreetMap, read from Overture Maps", step: "data")
192
301
  end
193
302
  end
194
303
  end
@@ -207,6 +316,28 @@ module Curtilage
207
316
  results
208
317
  end
209
318
 
319
+ # The threads' values once every one has finished, then the first error
320
+ # if any thread failed: callers may delete what the others are using.
321
+ def self.join_all(threads)
322
+ outcomes = threads.map do |thread|
323
+ thread.value
324
+ rescue StandardError => e
325
+ e
326
+ end
327
+ error = outcomes.find { |o| o.is_a?(StandardError) }
328
+ raise error if error
329
+
330
+ outcomes
331
+ end
332
+
333
+ # Readers never see a half-written file, even with several processes
334
+ # sharing a folder: written under a unique name, then renamed into place.
335
+ def self.write_atomically(file, data)
336
+ part = "#{file}.#{Process.pid}.#{Thread.current.object_id}.part"
337
+ File.binwrite(part, data)
338
+ File.rename(part, file)
339
+ end
340
+
210
341
  def self.preset_options(preset)
211
342
  return {} if preset.nil?
212
343
 
@@ -216,7 +347,13 @@ module Curtilage
216
347
  end
217
348
 
218
349
  def self.generate_one(pin, features, files, catalogue, options)
219
- result = generate(pin, features, **options)
350
+ result = generate_safely(pin, features, options)
351
+ result.provenance[:data] = if files.empty? then nil
352
+ elsif catalogue then catalogue.provenance(files)
353
+ else { source: "parquet" }
354
+ end
355
+ credits = catalogue&.attribution(files) || []
356
+ result.attribution = credits unless credits.empty?
220
357
  if files.empty?
221
358
  no_data(result)
222
359
  elsif catalogue && catalogue.coverage(pin) == :partial
@@ -227,15 +364,16 @@ module Curtilage
227
364
 
228
365
  def self.partial_data(result)
229
366
  result.flags << :partial_data
230
- result.explanation.unshift("part of the area around the pin is in a region that isn't built: " \
231
- "buildings or roads there are missing")
367
+ result.prepend_step("part of the area around the pin is in a region that isn't built: " \
368
+ "buildings or roads there are missing", step: "data", flag: :partial_data)
232
369
  end
233
370
 
234
371
  def self.no_data(result)
235
372
  result.flags << :no_data
236
- result.explanation.unshift("no map data covers this pin")
373
+ result.prepend_step("no map data covers this pin", step: "data", flag: :no_data)
237
374
  end
238
375
 
239
- private_class_method :fetch_and_generate, :auto_plan, :build_and_read, :wait_quietly, :from_builds, :merge,
240
- :from_overture, :run_many, :preset_options, :generate_one, :partial_data, :no_data
376
+ private_class_method :fetch_and_generate, :checked_pins, :check_data, :check_generation_options, :generate_safely,
377
+ :auto_plan, :build_and_read, :wait_quietly, :from_builds, :merge, :from_overture, :run_many,
378
+ :preset_options, :generate_one, :partial_data, :no_data
241
379
  end
@@ -49,4 +49,4 @@ COPY (
49
49
  FROM features
50
50
  WHERE geom IS NOT NULL AND NOT ST_IsEmpty(geom) -- a few shapefile records have no geometry
51
51
  ORDER BY ST_Hilbert(geom, {'min_x': -180, 'min_y': -90, 'max_x': 180, 'max_y': 90}::BOX_2D)
52
- ) TO (getvariable('out_path')) (FORMAT parquet, COMPRESSION zstd, ROW_GROUP_SIZE 20000);
52
+ ) TO (getvariable('out_path')) (FORMAT parquet, COMPRESSION zstd, ROW_GROUP_SIZE 5000);
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: curtilage
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.0
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Emil M
@@ -28,13 +28,21 @@ files:
28
28
  - README.md
29
29
  - SECURITY.md
30
30
  - docs/reference.md
31
+ - docs/schema/site-v1.json
32
+ - docs/security.md
31
33
  - exe/curtilage
32
34
  - lib/curtilage.rb
33
35
  - lib/curtilage/audit.rb
34
36
  - lib/curtilage/auto_data.rb
37
+ - lib/curtilage/batch.rb
35
38
  - lib/curtilage/build.rb
39
+ - lib/curtilage/candidates.rb
36
40
  - lib/curtilage/catalogue.rb
41
+ - lib/curtilage/confidence.rb
37
42
  - lib/curtilage/config.rb
43
+ - lib/curtilage/corrections.rb
44
+ - lib/curtilage/diff.rb
45
+ - lib/curtilage/doctor.rb
38
46
  - lib/curtilage/download.rb
39
47
  - lib/curtilage/duckdb.rb
40
48
  - lib/curtilage/error.rb
@@ -44,11 +52,16 @@ files:
44
52
  - lib/curtilage/generator.rb
45
53
  - lib/curtilage/generator_details.rb
46
54
  - lib/curtilage/generator_lot.rb
55
+ - lib/curtilage/generator_pin.rb
56
+ - lib/curtilage/generator_roads.rb
57
+ - lib/curtilage/generator_steps.rb
47
58
  - lib/curtilage/generator_store.rb
59
+ - lib/curtilage/generator_zones.rb
48
60
  - lib/curtilage/geometry.rb
49
61
  - lib/curtilage/lookup.rb
50
62
  - lib/curtilage/overture.rb
51
63
  - lib/curtilage/preview.rb
64
+ - lib/curtilage/profiles.rb
52
65
  - lib/curtilage/regions.rb
53
66
  - lib/curtilage/result.rb
54
67
  - lib/curtilage/validation.rb
@@ -78,7 +91,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
78
91
  - !ruby/object:Gem::Version
79
92
  version: '0'
80
93
  requirements: []
81
- rubygems_version: 3.7.2
94
+ rubygems_version: 4.0.20
82
95
  specification_version: 4
83
96
  summary: Generate a site's premises polygon (building + lot) from OpenStreetMap data.
84
97
  test_files: []