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
@@ -25,17 +25,27 @@ module Curtilage
25
25
 
26
26
  # Notes explain each step; flags are reasons a person should look first.
27
27
  # access: where driveways taken into the premises meet the street.
28
- Log = Struct.new(:notes, :flags, :access) do
29
- def note(text) = notes << text
28
+ # notes: the explanation in words; steps: the same, one record per note
29
+ # (Result#steps): { step:, text:, rule:, features:, distance_m:,
30
+ # area_before_m2:, area_after_m2:, flag: }, unknown fields left out.
31
+ Log = Struct.new(:notes, :flags, :access, :steps) do
32
+ def note(text, step: "note", **fields)
33
+ notes << text
34
+ self.steps ||= []
35
+ steps << { step: step, text: text, **fields }.compact
36
+ end
30
37
 
31
- def access_point(xy) = (self.access ||= []) << xy
38
+ # Where a driveway (id) meets a street (a Features::Line), in metres.
39
+ def access_point(xy, street, driveway) = (self.access ||= []) << { xy: xy, street: street, driveway: driveway }
32
40
 
33
- def flag(name, text)
41
+ def flag(name, text, **)
34
42
  flags << name unless flags.include?(name)
35
- notes << text
43
+ note(text, flag: name, **)
36
44
  end
37
45
  end
38
46
 
47
+ # The methods generate accepts, and the order propose falls back through.
48
+ # Kept apart on purpose: a method can be offered without being a fallback.
39
49
  METHODS = %i[grow_trim building].freeze
40
50
  CHAIN = %i[grow_trim building].freeze
41
51
 
@@ -90,11 +100,34 @@ module Curtilage
90
100
  max_store_vertices: 20, # the store outline is simplified to at most this many corners
91
101
  buildings: :osm, # :osm, :osm_filled (ML footprints where OSM has none) or :ml
92
102
  scope: :site, # :site, or :centre (the whole shopping centre when on a shared lot)
103
+ validation: {}, # limits for Validation.check, e.g. { max_area_error_m2: 300_000 }
104
+ precision: 7, # decimal places in output coordinates (7: about 1 cm)
105
+ approach_m: nil, # also an approach zone: the premises grown this much (nil: none)
106
+ pickup_m: nil, # also a pickup zone: mapped parking this close to the building (nil: none)
107
+ snap_m: nil, # move a pin that's off any building onto the nearest within this (nil: don't)
93
108
  }.freeze
94
109
 
95
110
  BUILDING_SOURCES = %i[osm osm_filled ml].freeze
96
111
  SCOPES = %i[site centre].freeze
97
112
 
113
+ # Allowed values for the numeric options: [min, max, whole number?].
114
+ # Out-of-range values would make no sense (a negative distance) or make
115
+ # the rules run on a city block.
116
+ DISTANCE = [0, 1_000, false].freeze
117
+ AREA = [0, 10_000_000, false].freeze
118
+ RANGES = {
119
+ building_max_distance_m: DISTANCE, pin_clearance_m: DISTANCE, building_clearance_m: DISTANCE,
120
+ grow_m: DISTANCE, road_offset_m: DISTANCE, neighbour_gap_m: DISTANCE, house_street_m: DISTANCE,
121
+ parking_reach_m: DISTANCE, parking_max_extent_m: DISTANCE, building_margin_m: DISTANCE,
122
+ approach_m: DISTANCE, pickup_m: DISTANCE, snap_m: DISTANCE,
123
+ large_building_m2: AREA, large_building_note_m2: AREA, neighbour_min_area_m2: AREA,
124
+ neighbour_strip_min_area_m2: AREA, house_max_m2: AREA, small_building_m2: AREA,
125
+ shared_lot_buildings: [1, 1_000, true], max_vertices: [4, 50, true], max_store_vertices: [3, 200, true],
126
+ precision: [5, 15, true]
127
+ }.freeze
128
+ # Options where nil means "work it out" (by road class; halfway).
129
+ NIL_ALLOWED = %i[road_offset_m neighbour_gap_m approach_m pickup_m snap_m].freeze
130
+
98
131
  module_function
99
132
 
100
133
  # The recommended path: grow_trim, falling back to building when its
@@ -108,12 +141,12 @@ module Curtilage
108
141
  if result.ok?
109
142
  unless failures.empty?
110
143
  result.flags.unshift(:fallback)
111
- result.explanation.unshift(*failures)
144
+ prepend_failures(result, failures)
112
145
  end
113
146
  return result
114
147
  end
115
- failures << "#{method} failed (#{failure_reason(result)})"
116
- return result.tap { |r| r.explanation = failures + r.explanation } if method == CHAIN.last
148
+ failures << ["#{method} failed (#{failure_reason(result)})", method]
149
+ return prepend_failures(result, failures) if method == CHAIN.last
117
150
  end
118
151
  end
119
152
 
@@ -121,13 +154,17 @@ module Curtilage
121
154
  def generate(method, pin, features, **options)
122
155
  raise ArgumentError, "unknown method #{method.inspect}" unless METHODS.include?(method)
123
156
 
157
+ pin = Validation.pin(pin)
124
158
  opts = checked_options(options)
125
159
  features = Features.new(pin, features) unless features.is_a?(Features)
126
160
  features = choose_buildings(features, opts[:buildings])
127
161
  log = Log.new([], [])
128
- log.note("dropped #{features.dropped} unusable OSM features") if features.dropped.positive?
162
+ log.note("dropped #{features.dropped} unusable OSM features", step: "drop_features") if features.dropped.positive?
163
+ quality = pin_quality(features, opts)
164
+ features, quality[:moved_from] = snap_pin(features, opts, log) if opts[:snap_m]
129
165
  xy, target = send(method, features, opts, log)
130
- finish(method, pin, [xy, target, features], log, opts)
166
+ finish(method, quality[:moved_from] ? features.pin : pin, [xy, target, features], log, opts)
167
+ .tap { |r| r.pin_quality = quality.compact }
131
168
  end
132
169
 
133
170
  # DEFAULTS with the options applied. A misspelt option would otherwise be
@@ -137,12 +174,30 @@ module Curtilage
137
174
  raise ArgumentError, "unknown option(s): #{unknown.join(", ")} (see Generator::DEFAULTS)" if unknown.any?
138
175
 
139
176
  opts = DEFAULTS.merge(options)
140
- raise ArgumentError, "unknown scope: #{opts[:scope].inspect} (have: site, centre)" \
177
+ check_choices(opts)
178
+ raise ArgumentError, "validation must be a Hash of limits" unless opts[:validation].is_a?(Hash)
179
+
180
+ Validation.limits(opts[:validation])
181
+ RANGES.each { |key, range| check_range(key, opts[key], *range) }
182
+ opts
183
+ end
184
+
185
+ def check_choices(opts)
186
+ raise ArgumentError, "unknown scope: #{opts[:scope].inspect} (have: #{SCOPES.join(", ")})" \
141
187
  unless SCOPES.include?(opts[:scope])
142
188
  raise ArgumentError, "unknown buildings: #{opts[:buildings].inspect} (have: #{BUILDING_SOURCES.join(", ")})" \
143
189
  unless BUILDING_SOURCES.include?(opts[:buildings])
190
+ raise ArgumentError, "store_zone must be true or false" unless [true, false].include?(opts[:store_zone])
191
+ end
144
192
 
145
- opts
193
+ def check_range(key, value, min, max, whole)
194
+ return if value.nil? && NIL_ALLOWED.include?(key)
195
+
196
+ ok = value.is_a?(Numeric) && value.real? && value.to_f.finite? && value.between?(min, max) &&
197
+ (!whole || value.is_a?(Integer))
198
+ return if ok
199
+
200
+ raise ArgumentError, "#{key} must be #{"a whole number " if whole}from #{min} to #{max}: #{value.inspect}"
146
201
  end
147
202
 
148
203
  # The building flavour: OSM only (default), OSM filled in with ML
@@ -161,18 +216,23 @@ module Curtilage
161
216
 
162
217
  def finish(method, pin, shape, log, opts)
163
218
  xy, target, features = shape
164
- result = Result.new(method_name: method, pin: pin, explanation: log.notes, flags: log.flags,
165
- building: target&.id, features: features)
219
+ log.steps ||= []
220
+ result = Result.new(method_name: method, pin: pin, explanation: log.notes, flags: log.flags, steps: log.steps,
221
+ building: target&.id, features: features,
222
+ provenance: { gem_version: VERSION, features_sha256: features.sha256, options: opts })
166
223
  unless xy
167
224
  result.validation = Validation.check(pin, nil)
168
225
  return result
169
226
  end
170
227
 
171
228
  premises = premises_xy(xy, target, opts, log)
172
- result.ring = ring_of(premises, pin)
173
- result.store_ring = ring_of(store_xy(target, premises, opts, log), pin) if target && opts[:store_zone]
174
- result.validation = Validation.check(pin, result.ring)
175
- result.details = details(target, premises, features, pin, log)
229
+ result.ring = ring_of(premises, pin, opts[:precision])
230
+ if target && opts[:store_zone]
231
+ result.store_ring = ring_of(store_xy(target, premises, opts, log), pin, opts[:precision])
232
+ end
233
+ result.validation = Validation.check(pin, result.ring, **opts[:validation])
234
+ result.details = details(target, premises, features, pin, log, precision: opts[:precision])
235
+ add_zones(result, [premises, target, features], opts, log)
176
236
  result
177
237
  end
178
238
 
@@ -182,24 +242,23 @@ module Curtilage
182
242
  def premises_xy(xy, target, opts, log)
183
243
  xy = Geometry.clean(Geometry.counter_clockwise(xy))
184
244
  if target && !target.hull.all? { |p| inside?(xy, p) }
185
- log.note("widened the premises to take in the whole building")
186
- xy = Geometry.counter_clockwise(Geometry.convex_hull(xy + target.hull))
245
+ wider = Geometry.counter_clockwise(Geometry.convex_hull(xy + target.hull))
246
+ log.note("widened the premises to take in the whole building", step: "widen", features: [target.id],
247
+ area_before_m2: m2(xy), area_after_m2: m2(wider))
248
+ xy = wider
187
249
  end
188
250
  return xy if xy.size <= opts[:max_vertices]
189
251
 
190
- log.note("simplified #{xy.size} vertices to at most #{opts[:max_vertices]}")
191
- Geometry.simplify_containing(xy, opts[:max_vertices], (target ? target.hull : []) + [[0.0, 0.0]])
252
+ simple = Geometry.simplify_containing(xy, opts[:max_vertices], (target ? target.hull : []) + [[0.0, 0.0]])
253
+ log.note("simplified #{xy.size} vertices to at most #{opts[:max_vertices]}",
254
+ step: "simplify", rule: "max_vertices", area_before_m2: m2(xy), area_after_m2: m2(simple))
255
+ simple
192
256
  end
193
257
 
194
258
  def inside?(xy, point)
195
259
  Geometry.contains?(xy, point) || Geometry.distance_to_edges(xy, point) < 0.01
196
260
  end
197
261
 
198
- def ring_of(xy, pin)
199
- ring = Geometry.unproject(xy, pin).map { |lng, lat| [lng.round(7), lat.round(7)] }
200
- ring << ring.first
201
- end
202
-
203
262
  def failure_reason(result)
204
263
  return result.explanation.last if result.ring.nil?
205
264
 
@@ -214,7 +273,10 @@ module Curtilage
214
273
  target = find_building(features, opts, log)
215
274
  return [nil, nil] unless target
216
275
 
217
- poly = trim_at_roads(grown(target, opts, log), features, target, opts, log)
276
+ poly = grown(target, opts[:grow_m], opts)
277
+ log.note("grew the building rectangle by #{opts[:grow_m]} m", step: "grow", rule: "grow_m", features: [target.id],
278
+ distance_m: opts[:grow_m], area_after_m2: m2(poly))
279
+ poly = trim_at_roads(poly, features, target, opts, log)
218
280
  lots, shared = own_parking(features, target, opts, log)
219
281
  return [centre(shared, Site.new(features, target, opts, log)), target] if opts[:scope] == :centre && shared.any?
220
282
 
@@ -229,23 +291,30 @@ module Curtilage
229
291
  features.buildings.reject { |b| b.equal?(target) || b.area < opts[:neighbour_min_area_m2] }
230
292
  end
231
293
 
294
+ # Nearest first (ties by id): each cut depends on the ones before it, so
295
+ # the closest building, which bounds the lot most, goes first, whatever
296
+ # order the map data came in.
297
+ def nearest_first(buildings, target)
298
+ buildings.sort_by { |b| [Geometry.closest_points(target.hull, b.hull)[0], b.id.to_s] }
299
+ end
300
+
232
301
  # The building's minimum rectangle plus a margin, trimmed at public
233
302
  # roads (premises never cross one).
234
303
  def building(features, opts, log)
235
304
  target = find_building(features, opts, log)
236
305
  return [nil, nil] unless target
237
306
 
238
- rect = Geometry.minimum_rectangle(target.xy)
239
- log.note("building rectangle grown by #{opts[:building_margin_m]} m")
240
- box = Geometry.oriented_box(rect[:corners], rect[:angle], opts[:building_margin_m])
241
- poly = Geometry.counter_clockwise(Geometry.convex_hull(box + pin_square(opts)))
307
+ poly = grown(target, opts[:building_margin_m], opts)
308
+ log.note("building rectangle grown by #{opts[:building_margin_m]} m",
309
+ step: "grow", rule: "building_margin_m", features: [target.id], distance_m: opts[:building_margin_m],
310
+ area_after_m2: m2(poly))
242
311
  [trim_at_roads(poly, features, target, opts, log), target]
243
312
  end
244
313
 
245
- def grown(target, opts, log)
314
+ # The building's rectangle grown by margin metres, taking in the pin.
315
+ def grown(target, margin, opts)
246
316
  rect = target.rectangle
247
- log.note("grew the building rectangle by #{opts[:grow_m]} m")
248
- box = Geometry.oriented_box(rect[:corners], rect[:angle], opts[:grow_m])
317
+ box = Geometry.oriented_box(rect[:corners], rect[:angle], margin)
249
318
  Geometry.counter_clockwise(Geometry.convex_hull(box + pin_square(opts)))
250
319
  end
251
320
 
@@ -255,48 +324,54 @@ module Curtilage
255
324
  target = building_under_pin(features, log) || nearest_building(features, opts, log)
256
325
  if target&.kind == "ml_building"
257
326
  log.flag(:ml_footprint, "building #{target.id} is a machine-learned footprint, not mapped in OSM: " \
258
- "check it exists")
327
+ "check it exists", step: "check_building", features: [target.id])
259
328
  end
260
329
  if target && target.area < opts[:small_building_m2]
261
330
  log.flag(:small_building, "building is only #{target.area.round} m2: check it's the site " \
262
- "(a kiosk or drive-through), not a shed or canopy next to it")
331
+ "(a kiosk or drive-through), not a shed or canopy next to it",
332
+ step: "check_building", rule: "small_building_m2", features: [target.id])
263
333
  end
264
334
  if target && target.area > opts[:large_building_m2]
265
335
  log.flag(:large_building, "building is over #{opts[:large_building_m2]} m2: if it's shared " \
266
- "(strip mall, several tenants), check which part is the site")
336
+ "(strip mall, several tenants), check which part is the site",
337
+ step: "check_building", rule: "large_building_m2", features: [target.id])
267
338
  elsif target && target.area > opts[:large_building_note_m2]
268
- log.note("building is #{target.area.round} m2: large enough that it may be shared")
339
+ log.note("building is #{target.area.round} m2: large enough that it may be shared",
340
+ step: "check_building", rule: "large_building_note_m2", features: [target.id])
269
341
  end
270
342
  target
271
343
  end
272
344
 
273
345
  def building_under_pin(features, log)
274
346
  target = features.buildings.select { |b| Geometry.contains?(b.xy, [0.0, 0.0]) }.min_by(&:area)
275
- log.note("building #{target.id} is under the pin (#{target.area.round} m2)") if target
347
+ if target
348
+ log.note("building #{target.id} is under the pin (#{target.area.round} m2)", step: "find_building",
349
+ features: [target.id])
350
+ end
276
351
  target
277
352
  end
278
353
 
279
- # A tiny structure (a canopy or kiosk roof) right by the pin loses to a
280
- # real building in reach: the canopy then counts as part of the lot.
281
- # The usual reason is a building missing from OSM, which machine-learned
282
- # footprints often fill.
354
+ # Why no building was found, as a hint: usually it's missing from OSM,
355
+ # which machine-learned footprints often fill.
283
356
  def missing_hint(opts)
284
357
  return "" unless opts[:buildings] == :osm
285
358
 
286
359
  " (it may be missing from OpenStreetMap: try buildings: :osm_filled)"
287
360
  end
288
361
 
362
+ # A tiny structure (a canopy or kiosk roof) right by the pin loses to a
363
+ # real building in reach: the canopy then counts as part of the lot.
289
364
  def nearest_building(features, opts, log)
290
- in_reach = features.buildings.map { |b| [Geometry.distance_to_edges(b.xy, [0.0, 0.0]), b] }
291
- .select { |d, _| d <= opts[:building_max_distance_m] }
292
- real = in_reach.reject { |_, b| b.area < opts[:small_building_m2] }
293
- distance, target = (real.empty? ? in_reach : real).min_by(&:first)
365
+ distance, target = nearest_in_reach(features, opts, opts[:building_max_distance_m])
294
366
  if target
295
367
  log.flag(:building_not_under_pin, "no building under the pin; using building #{target.id}, " \
296
- "#{distance.round} m away (#{target.area.round} m2)")
368
+ "#{distance.round} m away (#{target.area.round} m2)",
369
+ step: "find_building", rule: "building_max_distance_m", features: [target.id],
370
+ distance_m: distance.round(1))
297
371
  target
298
372
  else
299
- log.note("no building within #{opts[:building_max_distance_m]} m of the pin#{missing_hint(opts)}")
373
+ log.note("no building within #{opts[:building_max_distance_m]} m of the pin#{missing_hint(opts)}",
374
+ step: "find_building", rule: "building_max_distance_m", distance_m: opts[:building_max_distance_m])
300
375
  nil
301
376
  end
302
377
  end
@@ -315,102 +390,18 @@ module Curtilage
315
390
 
316
391
  trimmed, used = trim_along(poly, fit_direction(run, target), target, offset,
317
392
  [opts[:building_clearance_m], opts[:pin_clearance_m]])
318
- next log.note("kept the part beyond #{road_label(road)}: it would cut the building") unless trimmed
393
+ unless trimmed
394
+ next log.note("kept the part beyond #{road_label(road)}: it would cut the building",
395
+ step: "keep_road_side", features: [road.id])
396
+ end
319
397
  next if trimmed.size < 3
320
398
 
321
- label = "trimmed at #{road_label(road)}, #{used.round} m short of its centreline"
322
- log.note(label) unless log.notes.include?(label)
399
+ note_trim(log, road, [used, offset], [poly, trimmed], opts)
323
400
  poly = trimmed
324
401
  end
325
402
  poly
326
403
  end
327
404
 
328
- # [road, stretch points, offset] for every public road and railway near
329
- # the building, nearest stretch first.
330
- def road_stretches(features, target, opts)
331
- (features.roads.select { |road| PUBLIC_HIGHWAYS.include?(road.highway) } + features.railways)
332
- .flat_map { |road| road_runs(road, target).map { |run| [road, run, road_offset(road, opts)] } }
333
- .sort_by { |_, run, _| run.map { |p| Geometry.distance_to_edges(target.hull, p) }.min }
334
- end
335
-
336
- ROAD_REACH_M = 60 # only the road this close to the building bounds the site
337
- ROAD_BEND_DEG = 30 # a sharper turn starts a new stretch
338
- ROAD_SNAP_DEG = 10 # a stretch this close to a building side is squared to it
339
-
340
- # Points every 2 m along the road within reach of the building, split
341
- # into stretches wherever the road turns by more than ROAD_BEND_DEG.
342
- def road_runs(road, target)
343
- runs = []
344
- run = nil
345
- road.xy.each_cons(2) do |a, b|
346
- heading = Math.atan2(b[1] - a[1], b[0] - a[0]) % Math::PI
347
- samples(a, b).each do |p|
348
- if Geometry.distance_to_edges(target.hull, p) > ROAD_REACH_M
349
- run = nil
350
- next
351
- end
352
- if run.nil? || angle_between(run[:heading], heading) > ROAD_BEND_DEG * Math::PI / 180
353
- run = { heading: heading, points: [] }
354
- runs << run
355
- end
356
- run[:points] << p
357
- end
358
- end
359
- runs.map { |r| r[:points] }.select { |pts| pts.size >= 2 }
360
- end
361
-
362
- def samples(a, b)
363
- n = [(Math.hypot(b[0] - a[0], b[1] - a[1]) / 2).ceil, 1].max
364
- (0..n).map { |i| Geometry.lerp(a, b, i.fdiv(n)) }
365
- end
366
-
367
- # Smallest angle between two undirected headings (radians, mod pi).
368
- def angle_between(first, second)
369
- d = (first - second).abs % Math::PI
370
- [d, Math::PI - d].min
371
- end
372
-
373
- # [centroid, unit direction] of the stretch's best-fit line, snapped to a
374
- # building side when nearly parallel.
375
- #
376
- # The direction is the length-weighted average of the stretch's own
377
- # heading (a short jog or fork barely moves it), and the line sits at the
378
- # median of the points across it (one side branch can't drag it).
379
- def fit_direction(points, target)
380
- heading = mean_heading(points)
381
- axis = target.rectangle[:angle]
382
- 2.times do |k|
383
- side = axis + (k * Math::PI / 2)
384
- heading = side if angle_between(heading % Math::PI, side % Math::PI) <= ROAD_SNAP_DEG * Math::PI / 180
385
- end
386
- direction = [Math.cos(heading), Math.sin(heading)]
387
- [median_line_point(points, direction), direction]
388
- end
389
-
390
- # Average of segment headings as undirected lines (doubled angles), each
391
- # weighted by its length.
392
- def mean_heading(points)
393
- sum_cos = 0.0
394
- sum_sin = 0.0
395
- points.each_cons(2) do |a, b|
396
- length = Math.hypot(b[0] - a[0], b[1] - a[1])
397
- angle = 2 * Math.atan2(b[1] - a[1], b[0] - a[0])
398
- sum_cos += length * Math.cos(angle)
399
- sum_sin += length * Math.sin(angle)
400
- end
401
- Math.atan2(sum_sin, sum_cos) / 2
402
- end
403
-
404
- # A point on the line with the given direction that has half the points
405
- # on each side.
406
- def median_line_point(points, direction)
407
- normal = [-direction[1], direction[0]]
408
- centre = Geometry.centroid(points)
409
- offsets = points.map { |p| Geometry.dot([p[0] - centre[0], p[1] - centre[1]], normal) }.sort
410
- median = offsets[offsets.size / 2]
411
- [centre[0] + (normal[0] * median), centre[1] + (normal[1] * median)]
412
- end
413
-
414
405
  # Clips at the line, moved toward the pin by up to offset metres but
415
406
  # never closer than clearance metres to the building (the pavement in
416
407
  # front of a building on the street stays in the premises) or to the pin
@@ -448,23 +439,22 @@ module Curtilage
448
439
  def trim_at_neighbours(poly, features, target, opts, log)
449
440
  hull = target.hull
450
441
  area = Geometry.bounds(poly)
451
- neighbours(features, target, opts).each do |other|
452
- next unless Geometry.bounds_near?(area, other.bounds)
453
-
442
+ near = neighbours(features, target, opts).select { |other| Geometry.bounds_near?(area, other.bounds) }
443
+ nearest_first(near, target).each do |other|
454
444
  other_hull = other.hull
455
445
  next unless Geometry.overlap?(other_hull, poly)
456
446
 
457
447
  if Geometry.overlap?(other_hull, hull)
458
- log.note("building #{other.id} touches the building, so it can't be split off")
448
+ log.note("building #{other.id} touches the building, so it can't be split off",
449
+ step: "keep_neighbour", features: [other.id])
459
450
  next
460
451
  end
461
452
  home = home?(other, features, opts) && (behind_home?(other, target, features) ? :behind : :beside)
462
- other.instance_variable_set(:@home, home)
463
- strip = neighbour_strip(other, opts)
453
+ strip = neighbour_strip(other, home, opts)
464
454
  trimmed = split_from_neighbour(poly, hull, other_hull, target.rectangle[:angle], stop: strip_stop(strip))
465
455
  next if trimmed.size < 3
466
456
 
467
- explain_cut(log, other, strip)
457
+ explain_cut(log, other, home, strip, area_before_m2: m2(poly), area_after_m2: m2(trimmed))
468
458
  poly = trimmed
469
459
  end
470
460
  poly
@@ -472,27 +462,14 @@ module Curtilage
472
462
 
473
463
  HALFWAY = ->(near, far) { (near + far) / 2 }
474
464
 
475
- def explain_cut(log, other, strip)
476
- case other.instance_variable_get(:@home)
477
- when :behind
478
- log.flag(:near_houses, "the lot backs onto a home (building #{other.id}): split halfway, " \
479
- "check where its yard starts")
480
- when :beside
481
- log.flag(:near_houses, "the lot runs beside a home (building #{other.id}), stopping " \
482
- "#{strip} m short of it: check the property line")
483
- else
484
- log.note(strip ? "stopped #{strip} m short of building #{other.id}" : "split halfway to building #{other.id}")
485
- end
486
- end
487
-
488
465
  # The strip left to a neighbour, or nil to split halfway. Pavement
489
466
  # between two buildings usually belongs to one of them, and the site's
490
467
  # own lot is the likelier owner, so claim it up to a narrow strip.
491
468
  # Small neighbours (houses, below neighbour_strip_min_area_m2) keep the
492
469
  # halfway split: their yard isn't the site's.
493
- def neighbour_strip(other, opts)
470
+ def neighbour_strip(other, home, opts)
494
471
  gap = opts[:neighbour_gap_m]
495
- return nil if other.instance_variable_get(:@home) == :behind
472
+ return nil if home == :behind
496
473
 
497
474
  gap if gap && other.area >= opts[:neighbour_strip_min_area_m2]
498
475
  end
@@ -523,12 +500,14 @@ module Curtilage
523
500
  cosine < -0.5
524
501
  end
525
502
 
526
- def nearest_street_point(point, features)
527
- roads = features.roads.select { |r| PUBLIC_HIGHWAYS.include?(r.highway) }
528
- points = roads.flat_map do |road|
529
- road.xy.each_cons(2).map { |a, b| Geometry.closest_point_on_segment(point, a, b) }
503
+ def nearest_street_point(point, features) = nearest_street(point, features)&.last
504
+
505
+ # [public road, its point nearest point], or nil without public roads.
506
+ def nearest_street(point, features)
507
+ pairs = features.public_roads.flat_map do |road|
508
+ road.xy.each_cons(2).map { |a, b| [road, Geometry.closest_point_on_segment(point, a, b)] }
530
509
  end
531
- points.min_by { |p| Math.hypot(p[0] - point[0], p[1] - point[1]) }
510
+ pairs.min_by { |_, p| Geometry.distance(p, point) }
532
511
  end
533
512
 
534
513
  # Never less than halfway: a narrow gap is still split down the middle.
@@ -16,29 +16,41 @@ module Curtilage
16
16
 
17
17
  module_function
18
18
 
19
- def details(target, premises, features, pin, log)
19
+ def details(target, premises, features, pin, log, precision: 7)
20
20
  parking = parking_area(premises, features)
21
+ entrances = entrances(log, pin, precision)
21
22
  {
22
- building: building_info(target, pin),
23
+ building: building_info(target, pin, precision),
23
24
  parking_area_m2: parking.round,
24
25
  parking_spaces_estimate: (parking / M2_PER_PARKING_SPACE).floor,
25
26
  frontage_m: frontage(premises, features).round,
26
- access_points: to_lnglat(distinct(log.access || []), pin),
27
+ access_points: entrances.map { |e| e[:point] },
28
+ entrances: entrances,
27
29
  }
28
30
  end
29
31
 
32
+ # Where vehicles enter from the street: one per driveway mouth (those
33
+ # within ACCESS_MERGE_M are one), with the street it opens onto.
34
+ def entrances(log, pin, precision)
35
+ distinct(log.access || []).map do |a|
36
+ street = a[:street]
37
+ { point: Geometry.lnglat([a[:xy]], pin, precision).first, street: street.name, street_class: street.highway,
38
+ street_id: street.id, driveway: a[:driveway] }
39
+ end
40
+ end
41
+
30
42
  # Driveways mapped as several pieces meet the street at nearly the same
31
43
  # spot: count it once.
32
- def distinct(points, within = ACCESS_MERGE_M)
33
- points.each_with_object([]) do |p, out|
34
- out << p unless out.any? { |q| Math.hypot(p[0] - q[0], p[1] - q[1]) < within }
44
+ def distinct(access, within = ACCESS_MERGE_M)
45
+ access.each_with_object([]) do |a, out|
46
+ out << a unless out.any? { |b| Geometry.distance(a[:xy], b[:xy]) < within }
35
47
  end
36
48
  end
37
49
 
38
- def building_info(target, pin)
50
+ def building_info(target, pin, precision)
39
51
  return nil unless target
40
52
 
41
- outline = to_lnglat(target.xy, pin)
53
+ outline = Geometry.lnglat(target.xy, pin, precision)
42
54
  { id: target.id, name: target.name, type: target.category, area_m2: target.area.round,
43
55
  footprint: outline + [outline.first] }
44
56
  end
@@ -56,11 +68,11 @@ module Curtilage
56
68
 
57
69
  # Length of premises edges running along a public road.
58
70
  def frontage(premises, features)
59
- roads = features.roads.select { |r| PUBLIC_HIGHWAYS.include?(r.highway) }
71
+ roads = features.public_roads
60
72
  premises.each_index.sum do |i|
61
73
  a = premises[i]
62
74
  b = premises[(i + 1) % premises.size]
63
- along_road?(Geometry.lerp(a, b, 0.5), roads) ? Math.hypot(b[0] - a[0], b[1] - a[1]) : 0
75
+ along_road?(Geometry.lerp(a, b, 0.5), roads) ? Geometry.distance(a, b) : 0
64
76
  end
65
77
  end
66
78
 
@@ -70,9 +82,5 @@ module Curtilage
70
82
  road.xy.each_cons(2).any? { |p, q| Geometry.segment_distance(point, p, q) <= reach }
71
83
  end
72
84
  end
73
-
74
- def to_lnglat(xy, pin)
75
- Geometry.unproject(xy, pin).map { |lng, lat| [lng.round(7), lat.round(7)] }
76
- end
77
85
  end
78
86
  end