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
@@ -10,8 +10,9 @@ module Curtilage
10
10
  # Mapped parking that touches the building or holds the pin is the
11
11
  # site's lot.
12
12
  # A lot touching shared_lot_buildings or more other buildings is a shared
13
- # (shopping-centre) lot: splitting it between them leaves slivers, and it
14
- # isn't this site's alone, so it's left out and flagged.
13
+ # (shopping-centre) lot: it isn't this site's alone, so share_lot later
14
+ # claims only the part nearer this building than the others (or centre
15
+ # takes the whole centre, with scope: :centre).
15
16
  #
16
17
  # Parking garages, carports and canopies next to the building count as
17
18
  # lot too (LOT_TYPES). Returns [the site's lots, those of them shared].
@@ -24,18 +25,24 @@ module Curtilage
24
25
  next false unless Geometry.contains?(lot.xy, [0.0, 0.0]) || touches?(lot, target, opts)
25
26
 
26
27
  others = sharers(lot, features, target, opts)
27
- if others >= opts[:shared_lot_buildings]
28
- shared << lot
29
- log.note("parking #{lot.id} (#{lot.area.round} m2) is shared with #{others} other buildings: " \
30
- "claimed the part nearer this building than the others")
31
- next true
32
- end
33
- log.note("#{lot_label(lot)} (#{lot.area.round} m2) touches the building, so it's part of the lot")
28
+ shared << lot if others >= opts[:shared_lot_buildings]
29
+ note_lot(log, lot, others, opts)
34
30
  true
35
31
  end
36
32
  [lots, shared]
37
33
  end
38
34
 
35
+ def note_lot(log, lot, others, opts)
36
+ if others >= opts[:shared_lot_buildings]
37
+ log.note("parking #{lot.id} (#{lot.area.round} m2) is shared with #{others} other buildings: " \
38
+ "claimed the part nearer this building than the others",
39
+ step: "claim_lot", rule: "shared_lot_buildings", features: [lot.id])
40
+ else
41
+ log.note("#{lot_label(lot)} (#{lot.area.round} m2) touches the building, so it's part of the lot",
42
+ step: "claim_lot", rule: "parking_reach_m", features: [lot.id], distance_m: opts[:parking_reach_m])
43
+ end
44
+ end
45
+
39
46
  # Other buildings (not garages or canopies) the lot also touches.
40
47
  def sharers(lot, features, target, opts)
41
48
  neighbours(features, target, opts).count do |other|
@@ -62,6 +69,9 @@ module Curtilage
62
69
  parts = lots.map { |lot| share_lot(Geometry.clip_convex(lot.xy, far), lot, site) }
63
70
  grown = lot_box(poly + parts.select { |p| p.size >= 3 }.flatten(1), far, site.target)
64
71
  grown = add_entrances(grown, far, site)
72
+ site.log.note("took in the lot: premises #{m2(poly)} m2 to #{m2(grown)} m2",
73
+ step: "add_lot", rule: "parking_max_extent_m", features: lots.map(&:id),
74
+ distance_m: site.opts[:parking_max_extent_m], area_before_m2: m2(poly), area_after_m2: m2(grown))
65
75
  keep_off_neighbours(grown, site.features, site.target, site.opts, site.log)
66
76
  end
67
77
 
@@ -101,66 +111,79 @@ module Curtilage
101
111
  pts = road.xy.each_cons(2).flat_map { |a, b| samples(a, b) }.select { |p| Geometry.contains?(fence, p) }
102
112
  return [] unless pts.any? { |p| Geometry.contains?(poly, p) } && meets_public_road?(pts, site.features)
103
113
 
104
- site.log.note("took in the driveway #{road.id} to the street")
114
+ site.log.note("took in the driveway #{road.id} to the street", step: "take_driveway", rule: "ENTRANCE_REACH_M",
115
+ features: [road.id], distance_m: ENTRANCE_REACH_M)
105
116
  taken = pts.select { |p| Geometry.contains?(poly, p) || Geometry.distance_to_edges(poly, p) <= ENTRANCE_REACH_M }
106
- access = street_access(taken, site.features)
107
- site.log.access_point(access) if access
117
+ point, street = street_access(taken, site.features)
118
+ site.log.access_point(point, street, road.id) if point
108
119
  taken
109
120
  end
110
121
 
111
122
  def meets_public_road?(points, features)
112
123
  street = points.filter_map do |p|
113
- nearest_street_point(p, features)&.then do |q|
114
- Math.hypot(q[0] - p[0], q[1] - p[1])
115
- end
124
+ nearest_street_point(p, features)&.then { |q| Geometry.distance(p, q) }
116
125
  end
117
126
  street.any? { |d| d <= ENTRANCE_MAX_M }
118
127
  end
119
128
 
120
- # Where the part of a driveway taken in meets the street: the point on a
121
- # public road nearest it, or nil if that's further than ENTRANCE_MAX_M
122
- # (the driveway reaches the street elsewhere, beyond the premises).
129
+ # Where the part of a driveway taken in meets the street: [the point on
130
+ # a public road nearest it, that road], or nil if that's further than
131
+ # ENTRANCE_MAX_M (the driveway reaches the street elsewhere, beyond the
132
+ # premises).
123
133
  def street_access(points, features)
124
- pair = points.filter_map { |p| nearest_street_point(p, features)&.then { |q| [p, q] } }
125
- .min_by { |p, q| Math.hypot(q[0] - p[0], q[1] - p[1]) }
126
- return nil unless pair && Math.hypot(pair[1][0] - pair[0][0], pair[1][1] - pair[0][1]) <= ENTRANCE_MAX_M
134
+ best = points.filter_map { |p| nearest_street(p, features)&.then { |road, q| [p, q, road] } }
135
+ .min_by { |p, q, _| Geometry.distance(p, q) }
136
+ return nil unless best && Geometry.distance(best[0], best[1]) <= ENTRANCE_MAX_M
127
137
 
128
- pair.last
138
+ best.drop(1)
129
139
  end
130
140
 
131
141
  # A lot the site shares with one or two other buildings is still the
132
- # site's (three or more is a shopping-centre lot, left out earlier): it is
133
- # claimed whole, and keep_off_neighbours stays clear of their walls.
142
+ # site's: it is claimed whole, and keep_off_neighbours stays clear of
143
+ # their walls. A shopping-centre lot (shared_lot_buildings or more) is
144
+ # split halfway with each building on it.
134
145
  # Homes are the exception: a lot touching one is split halfway with it,
135
146
  # so the claim stops short of the yard.
136
147
  def share_lot(part, lot, site)
137
148
  features, target, opts, log = site.to_a
138
149
  shared = site.shared.include?(lot)
139
- others = neighbours(features, target, opts).select do |other|
140
- touches?(lot, other, opts) && !Geometry.overlap?(other.hull, target.hull)
141
- end
150
+ others = lot_neighbours(lot, features, target, opts)
142
151
  others.each do |other|
143
152
  next unless (shared && !LOT_TYPES.include?(other.category)) || home?(other, features, opts)
144
153
  next if part.size < 3
145
154
 
146
155
  part = split_from_neighbour(part, target.hull, other.hull, target.rectangle[:angle])
147
156
  end
148
- log.note("parking #{lot.id} also touches building #{others.map(&:id).join(", ")}") if others.any?
157
+ if others.any?
158
+ log.note("parking #{lot.id} also touches building #{others.map(&:id).join(", ")}",
159
+ step: "share_lot", features: [lot.id, *others.map(&:id)])
160
+ end
149
161
  part
150
162
  end
151
163
 
164
+ # Other buildings the lot touches (not ones joined to the site's own),
165
+ # nearest first.
166
+ def lot_neighbours(lot, features, target, opts)
167
+ touching = neighbours(features, target, opts).select do |other|
168
+ touches?(lot, other, opts) && !Geometry.overlap?(other.hull, target.hull)
169
+ end
170
+ nearest_first(touching, target)
171
+ end
172
+
152
173
  # Stops 1 m short of any neighbouring building the lot reached.
153
174
  def keep_off_neighbours(poly, features, target, opts, log)
154
175
  area = Geometry.bounds(poly)
155
- neighbours(features, target, opts).each do |other|
156
- next unless Geometry.bounds_near?(area, other.bounds)
176
+ near = neighbours(features, target, opts).select { |other| Geometry.bounds_near?(area, other.bounds) }
177
+ nearest_first(near, target).each do |other|
157
178
  next if Geometry.overlap?(other.hull, target.hull) || !Geometry.overlap?(other.hull, poly)
158
179
 
159
180
  trimmed = split_from_neighbour(poly, target.hull, other.hull, target.rectangle[:angle],
160
181
  stop: ->(near, far) { [far - 1, near].max })
161
182
  next if trimmed.size < 3
162
183
 
163
- log.note("stopped 1 m short of building #{other.id}")
184
+ log.note("stopped 1 m short of building #{other.id}", step: "keep_off_neighbour", features: [other.id],
185
+ distance_m: 1, area_before_m2: m2(poly),
186
+ area_after_m2: m2(trimmed))
164
187
  poly = trimmed
165
188
  end
166
189
  poly
@@ -176,7 +199,8 @@ module Curtilage
176
199
  points = shared.flat_map(&:xy) + members.flat_map(&:hull)
177
200
  poly = trim_at_roads(Geometry.counter_clockwise(Geometry.convex_hull(points)), features, target, opts, log)
178
201
  log.flag(:shopping_centre, "mapped the whole shopping centre: #{members.size} buildings around " \
179
- "#{shared.size} shared parking lot(s)")
202
+ "#{shared.size} shared parking lot(s)",
203
+ step: "whole_centre", features: members.map(&:id) + shared.map(&:id), area_after_m2: m2(poly))
180
204
  poly
181
205
  end
182
206
 
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Curtilage
4
+ # The pin: how good it is (geocoders often drop pins on the street or the
5
+ # wrong building) and, if asked (snap_m:), moving it onto the nearest
6
+ # building. Features are in metres around the pin, which is [0, 0].
7
+ module Generator
8
+ ORIGIN = [0.0, 0.0].freeze
9
+ DEFAULT_SNAP_M = 30
10
+ # A snapped pin goes this far inside the building's edge.
11
+ SNAP_INSET_M = 1
12
+
13
+ module_function
14
+
15
+ # { quality:, building_m: } for the pin as given: on_building, on_road
16
+ # (within half a public road's width of its centreline), near_building
17
+ # (a building within building_max_distance_m) or far; building_m is the
18
+ # distance to the nearest building's edge (0 on one, nil with none).
19
+ def pin_quality(features, opts)
20
+ return { quality: "on_building", building_m: 0 } if on_building?(features)
21
+
22
+ nearest = features.buildings.map { |b| Geometry.distance_to_edges(b.xy, ORIGIN) }.min
23
+ quality = if features.public_roads.any? { |r| road_distance(r) <= road_offset(r, opts) } then "on_road"
24
+ elsif nearest && nearest <= opts[:building_max_distance_m] then "near_building"
25
+ else "far"
26
+ end
27
+ { quality: quality, building_m: nearest&.round(1) }
28
+ end
29
+
30
+ def on_building?(features) = features.buildings.any? { |b| Geometry.contains?(b.xy, ORIGIN) }
31
+
32
+ def road_distance(road)
33
+ road.xy.each_cons(2).map { |a, b| Geometry.segment_distance(ORIGIN, a, b) }.min || Float::INFINITY
34
+ end
35
+
36
+ # [features around the moved pin, the pin as given], or [features, nil]
37
+ # when the pin is on a building or none is within snap_m.
38
+ def snap_pin(features, opts, log)
39
+ return [features, nil] if on_building?(features)
40
+
41
+ _, target = nearest_in_reach(features, opts, opts[:snap_m])
42
+ return [features, nil] unless target
43
+
44
+ point = inside_point(target)
45
+ moved = Geometry.distance(point, ORIGIN)
46
+ log.flag(:pin_moved, "moved the pin #{moved.round} m onto building #{target.id}: it wasn't on a building",
47
+ step: "snap_pin", rule: "snap_m", features: [target.id], distance_m: moved.round(1))
48
+ [features.moved_to(point), features.pin]
49
+ end
50
+
51
+ # [distance, building] for the nearest building within reach, preferring
52
+ # real buildings to kiosks and canopies; nil if none.
53
+ def nearest_in_reach(features, opts, reach)
54
+ in_reach = features.buildings.map { |b| [Geometry.distance_to_edges(b.xy, ORIGIN), b] }
55
+ .select { |d, _| d <= reach }
56
+ real = in_reach.reject { |_, b| b.area < opts[:small_building_m2] }
57
+ (real.empty? ? in_reach : real).min_by(&:first)
58
+ end
59
+
60
+ # The building's edge point nearest the pin, carried SNAP_INSET_M on
61
+ # inside; its centroid if that isn't inside (an odd shape).
62
+ def inside_point(building)
63
+ ring = building.xy + [building.xy.first]
64
+ edge = ring.each_cons(2).map { |a, b| Geometry.closest_point_on_segment(ORIGIN, a, b) }
65
+ .min_by { |p| Geometry.distance(p, ORIGIN) }
66
+ length = Geometry.distance(edge, ORIGIN)
67
+ inset = edge.map { |v| v + (v / length * SNAP_INSET_M) }
68
+ return inset if Geometry.contains?(building.xy, inset)
69
+
70
+ centre = Geometry.centroid(building.xy)
71
+ Geometry.contains?(building.xy, centre) ? centre : edge
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Curtilage
4
+ # Where public roads and railways run beside the building, as stretches
5
+ # to trim along (see trim_at_roads). Split from generator.rb only to keep
6
+ # files a readable size.
7
+ module Generator
8
+ ROAD_REACH_M = 60 # only the road this close to the building bounds the site
9
+ ROAD_BEND_DEG = 30 # a sharper turn starts a new stretch
10
+ ROAD_SNAP_DEG = 10 # a stretch this close to a building side is squared to it
11
+
12
+ module_function
13
+
14
+ # [road, stretch points, offset] for every public road and railway near
15
+ # the building, nearest stretch first.
16
+ def road_stretches(features, target, opts)
17
+ (features.public_roads + features.railways)
18
+ .flat_map { |road| road_runs(road, target).map { |run| [road, run, road_offset(road, opts)] } }
19
+ .sort_by { |_, run, _| run.map { |p| Geometry.distance_to_edges(target.hull, p) }.min }
20
+ end
21
+
22
+ # Points every 2 m along the road within reach of the building, split
23
+ # into stretches wherever the road turns by more than ROAD_BEND_DEG.
24
+ #
25
+ # A segment whose box is more than ROAD_REACH_M from the building's box
26
+ # has no point in reach, so it's skipped unsampled: most roads in the
27
+ # map data around a pin are far from the building.
28
+ def road_runs(road, target)
29
+ runs = []
30
+ run = nil
31
+ road.xy.each_cons(2) do |a, b|
32
+ run = segment_in_reach?(a, b, target) ? extend_runs(runs, run, a, b, target) : nil
33
+ end
34
+ runs.map { |r| r[:points] }.select { |pts| pts.size >= 2 }
35
+ end
36
+
37
+ def segment_in_reach?(first, last, target)
38
+ Geometry.bounds_near?(Geometry.bounds([first, last]), target.bounds, ROAD_REACH_M)
39
+ end
40
+
41
+ # Adds the segment a-b's points in reach to the stretch going on, or to
42
+ # a new one after a gap or a sharp turn; returns the stretch going on.
43
+ def extend_runs(runs, run, a, b, target)
44
+ heading = Math.atan2(b[1] - a[1], b[0] - a[0]) % Math::PI
45
+ samples(a, b).each do |p|
46
+ next run = nil if Geometry.distance_to_edges(target.hull, p) > ROAD_REACH_M
47
+
48
+ if run.nil? || angle_between(run[:heading], heading) > ROAD_BEND_DEG * Math::PI / 180
49
+ run = { heading: heading, points: [] }
50
+ runs << run
51
+ end
52
+ run[:points] << p
53
+ end
54
+ run
55
+ end
56
+
57
+ def samples(a, b)
58
+ n = [(Geometry.distance(a, b) / 2).ceil, 1].max
59
+ (0..n).map { |i| Geometry.lerp(a, b, i.fdiv(n)) }
60
+ end
61
+
62
+ # Smallest angle between two undirected headings (radians, mod pi).
63
+ def angle_between(first, second)
64
+ d = (first - second).abs % Math::PI
65
+ [d, Math::PI - d].min
66
+ end
67
+
68
+ # [centroid, unit direction] of the stretch's best-fit line, snapped to a
69
+ # building side when nearly parallel.
70
+ #
71
+ # The direction is the length-weighted average of the stretch's own
72
+ # heading (a short jog or fork barely moves it), and the line sits at the
73
+ # median of the points across it (one side branch can't drag it).
74
+ def fit_direction(points, target)
75
+ heading = mean_heading(points)
76
+ axis = target.rectangle[:angle]
77
+ 2.times do |k|
78
+ side = axis + (k * Math::PI / 2)
79
+ heading = side if angle_between(heading % Math::PI, side % Math::PI) <= ROAD_SNAP_DEG * Math::PI / 180
80
+ end
81
+ direction = [Math.cos(heading), Math.sin(heading)]
82
+ [median_line_point(points, direction), direction]
83
+ end
84
+
85
+ # Average of segment headings as undirected lines (doubled angles), each
86
+ # weighted by its length.
87
+ def mean_heading(points)
88
+ sum_cos = 0.0
89
+ sum_sin = 0.0
90
+ points.each_cons(2) do |a, b|
91
+ length = Geometry.distance(a, b)
92
+ angle = 2 * Math.atan2(b[1] - a[1], b[0] - a[0])
93
+ sum_cos += length * Math.cos(angle)
94
+ sum_sin += length * Math.sin(angle)
95
+ end
96
+ Math.atan2(sum_sin, sum_cos) / 2
97
+ end
98
+
99
+ # A point on the line with the given direction that has half the points
100
+ # on each side.
101
+ def median_line_point(points, direction)
102
+ normal = [-direction[1], direction[0]]
103
+ centre = Geometry.centroid(points)
104
+ offsets = points.map { |p| Geometry.dot([p[0] - centre[0], p[1] - centre[1]], normal) }.sort
105
+ median = offsets[offsets.size / 2]
106
+ [centre[0] + (normal[0] * median), centre[1] + (normal[1] * median)]
107
+ end
108
+ end
109
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Curtilage
4
+ # How the rules record what they did: each line of the explanation with
5
+ # its structured step (Result#steps). Split from generator.rb only to keep
6
+ # files a readable size.
7
+ module Generator
8
+ module_function
9
+
10
+ # Whole square metres, for steps.
11
+ def m2(xy) = xy && xy.size >= 3 ? Geometry.area(xy).round : 0
12
+
13
+ # Each failed attempt first, in order, as a step of its own.
14
+ def prepend_failures(result, failures)
15
+ failures.reverse_each { |text, method| result.prepend_step(text, step: "fallback", rule: method.to_s) }
16
+ result
17
+ end
18
+
19
+ # One step per road, however many of its stretches trimmed: a later
20
+ # stretch updates the area after. rule: what set the distance (a fixed
21
+ # road_offset_m, half the road's width by class, or a clearance that
22
+ # kept the cut further from the centreline's other side).
23
+ def note_trim(log, road, distances, polys, opts)
24
+ used, offset = distances
25
+ label = "trimmed at #{road_label(road)}, #{used.round} m short of its centreline"
26
+ earlier = (log.steps || []).find { |s| s[:text] == label }
27
+ return earlier[:area_after_m2] = m2(polys[1]) if earlier
28
+
29
+ rule = if used < offset - 0.01 then "clearance"
30
+ elsif opts[:road_offset_m] then "road_offset_m"
31
+ else "road_class_half_width"
32
+ end
33
+ log.note(label, step: "trim_road", rule: rule, features: [road.id], distance_m: used.round(1),
34
+ area_before_m2: m2(polys[0]), area_after_m2: m2(polys[1]))
35
+ end
36
+
37
+ # home: :behind, :beside or false (not a home).
38
+ def explain_cut(log, other, home, strip, **areas)
39
+ step = { step: "split_neighbour", features: [other.id], rule: strip ? "neighbour_gap_m" : "halfway",
40
+ distance_m: strip, **areas }
41
+ case home
42
+ when :behind
43
+ log.flag(:near_houses, "the lot backs onto a home (building #{other.id}): split halfway, " \
44
+ "check where its yard starts", **step)
45
+ when :beside
46
+ log.flag(:near_houses, "the lot runs beside a home (building #{other.id}), stopping " \
47
+ "#{strip} m short of it: check the property line", **step)
48
+ else
49
+ log.note(strip ? "stopped #{strip} m short of building #{other.id}" : "split halfway to building #{other.id}",
50
+ **step)
51
+ end
52
+ end
53
+ end
54
+ end
@@ -11,7 +11,7 @@ module Curtilage
11
11
  # The building's OSM footprint, simplified to max_store_vertices.
12
12
  # Footprints can be any shape (L, U, courtyards' outer edge); if
13
13
  # simplifying would make the outline cross itself, its convex outline is
14
- # used instead. It is then kept STORE_MARGIN_M inside the premises, so
14
+ # used instead. It is then kept inside the premises by store_margin, so
15
15
  # the store zone always sits within them, even after rounding.
16
16
  def store_xy(target, premises, opts, log)
17
17
  xy = Geometry.clean(Geometry.counter_clockwise(target.xy))
@@ -21,11 +21,25 @@ module Curtilage
21
21
  end
22
22
  if target.area > opts[:large_building_note_m2]
23
23
  log.flag(:store_may_be_unit, "the store outline is the whole #{target.area.round} m2 building: " \
24
- "if the store is one unit of it, trim the outline to that unit")
24
+ "if the store is one unit of it, trim the outline to that unit",
25
+ step: "check_store", rule: "large_building_note_m2", features: [target.id])
26
+ end
27
+ inside = Geometry.clean(Geometry.clip_inside(xy, premises, store_margin(opts[:precision])))
28
+ if Geometry.area(inside) < Geometry.area(xy) - 1
29
+ log.note("trimmed the store outline to fit inside the premises",
30
+ step: "trim_store", features: [target.id], area_before_m2: m2(xy), area_after_m2: m2(inside))
25
31
  end
26
- inside = Geometry.clean(Geometry.clip_inside(xy, premises, STORE_MARGIN_M))
27
- log.note("trimmed the store outline to fit inside the premises") if Geometry.area(inside) < Geometry.area(xy) - 1
28
32
  inside
29
33
  end
34
+
35
+ # Rounding to precision decimal places moves each corner of both rings by
36
+ # up to half a unit in each axis (a degree is longest along the equator),
37
+ # so a store corner and a premises edge can close in by twice the
38
+ # diagonal of that: keep at least that much apart (plus a centimetre),
39
+ # and never less than STORE_MARGIN_M.
40
+ def store_margin(precision)
41
+ rounding = 0.5 * (10.0**-precision) * Geometry::METRES_PER_DEGREE_LNG_AT_EQUATOR
42
+ [STORE_MARGIN_M, (2 * Math.sqrt(2) * rounding) + 0.01].max
43
+ end
30
44
  end
31
45
  end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Curtilage
4
+ # Optional zones around and inside the premises for arrival detection,
5
+ # nested by construction: approach (premises grown, "customer is near")
6
+ # holds the premises ("arrived"), which hold the store zone and the pickup
7
+ # zone. Off by default (approach_m:, pickup_m:).
8
+ module Generator
9
+ DEFAULT_APPROACH_M = 150
10
+ DEFAULT_PICKUP_M = 25
11
+ # The approach zone is simplified to at most this many corners.
12
+ MAX_APPROACH_VERTICES = 16
13
+ # Parking pieces smaller than this (about one space) aren't a pickup zone.
14
+ MIN_PICKUP_M2 = 25
15
+
16
+ module_function
17
+
18
+ # The premises grown by approach_m, simplified only by dropping corners
19
+ # that keep every premises corner inside (so it still holds them).
20
+ def approach_xy(premises, opts)
21
+ grown = Geometry.round_buffer(premises, opts[:approach_m])
22
+ Geometry.simplify_containing(grown, MAX_APPROACH_VERTICES, premises)
23
+ end
24
+
25
+ # Neither data source maps pickup or curbside spots, so the zone is
26
+ # estimated: the largest piece of mapped parking within pickup_m of the
27
+ # building, kept inside the premises like the store zone. nil without
28
+ # mapped parking there.
29
+ def pickup_xy(target, premises, features, opts, log)
30
+ rect = target.rectangle
31
+ reach = Geometry.counter_clockwise(Geometry.oriented_box(rect[:corners], rect[:angle], opts[:pickup_m]))
32
+ pieces = features.parking.map do |lot|
33
+ piece = Geometry.clip_convex(lot.xy, reach)
34
+ [lot, Geometry.clean(Geometry.clip_inside(piece, premises, store_margin(opts[:precision])))]
35
+ end
36
+ lot, best = pieces.select { |_, xy| m2(xy) >= MIN_PICKUP_M2 }.max_by { |_, xy| m2(xy) }
37
+ note_pickup(log, lot, best, opts)
38
+ best
39
+ end
40
+
41
+ def note_pickup(log, lot, xy, opts)
42
+ unless xy
43
+ return log.note("no pickup zone: no mapped parking within #{opts[:pickup_m]} m of the building",
44
+ step: "pickup_zone", rule: "pickup_m", distance_m: opts[:pickup_m])
45
+ end
46
+
47
+ log.note("pickup zone estimated from parking #{lot.id} within #{opts[:pickup_m]} m of the building " \
48
+ "(#{m2(xy)} m2)", step: "pickup_zone", rule: "pickup_m", features: [lot.id],
49
+ distance_m: opts[:pickup_m], area_after_m2: m2(xy))
50
+ end
51
+
52
+ def add_zones(result, shape, opts, log)
53
+ premises, target, features = shape
54
+ if opts[:approach_m]
55
+ xy = approach_xy(premises, opts)
56
+ log.note("approach zone: the premises grown by #{opts[:approach_m]} m",
57
+ step: "approach_zone", rule: "approach_m", distance_m: opts[:approach_m], area_after_m2: m2(xy))
58
+ result.approach_ring = zone_ring(xy, "approach", result.pin, opts, log)
59
+ end
60
+ return unless opts[:pickup_m] && target
61
+
62
+ pickup = pickup_xy(target, premises, features, opts, log)
63
+ result.pickup_ring = zone_ring(pickup, "pickup", result.pin, opts, log)
64
+ result.staging_point = staging_point(pickup, target, result.pin, opts, log) if result.pickup_ring
65
+ end
66
+
67
+ # Where a driver might wait: the pickup zone's point nearest the
68
+ # building. Estimated like the zone (no entrances are mapped).
69
+ def staging_point(pickup, target, pin, opts, log)
70
+ distance, point, = Geometry.closest_points(pickup, target.hull)
71
+ log.note("staging point: the pickup zone's nearest point to the building, #{distance.round} m from it",
72
+ step: "staging_point", features: [target.id], distance_m: distance.round(1))
73
+ Geometry.lnglat([point], pin, opts[:precision]).first
74
+ end
75
+
76
+ def ring_of(xy, pin, precision)
77
+ ring = Geometry.lnglat(xy, pin, precision)
78
+ ring << ring.first
79
+ end
80
+
81
+ # A zone as a ring, or nil (with a note) if it isn't a usable shape.
82
+ def zone_ring(xy, name, pin, opts, log)
83
+ return nil unless xy && xy.size >= 3
84
+
85
+ ring = ring_of(xy, pin, opts[:precision])
86
+ problems = Validation.shape_errors(pin, ring)
87
+ return ring if problems.empty?
88
+
89
+ log.note("dropped the #{name} zone: #{problems.join(", ")}", step: "#{name}_zone")
90
+ nil
91
+ end
92
+ end
93
+ end