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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +75 -0
- data/README.md +76 -22
- data/SECURITY.md +18 -3
- data/docs/reference.md +221 -27
- data/docs/schema/site-v1.json +362 -0
- data/docs/security.md +69 -0
- data/exe/curtilage +375 -82
- data/lib/curtilage/audit.rb +5 -5
- data/lib/curtilage/auto_data.rb +61 -11
- data/lib/curtilage/batch.rb +116 -0
- data/lib/curtilage/build.rb +117 -63
- data/lib/curtilage/candidates.rb +67 -0
- data/lib/curtilage/catalogue.rb +44 -16
- data/lib/curtilage/confidence.rb +55 -0
- data/lib/curtilage/config.rb +24 -2
- data/lib/curtilage/corrections.rb +57 -0
- data/lib/curtilage/diff.rb +90 -0
- data/lib/curtilage/doctor.rb +92 -0
- data/lib/curtilage/download.rb +42 -16
- data/lib/curtilage/duckdb.rb +170 -6
- data/lib/curtilage/error.rb +3 -0
- data/lib/curtilage/features.rb +54 -5
- data/lib/curtilage/formats.rb +271 -36
- data/lib/curtilage/generator.rb +145 -166
- data/lib/curtilage/generator_details.rb +22 -14
- data/lib/curtilage/generator_lot.rb +56 -32
- data/lib/curtilage/generator_pin.rb +74 -0
- data/lib/curtilage/generator_roads.rb +109 -0
- data/lib/curtilage/generator_steps.rb +54 -0
- data/lib/curtilage/generator_store.rb +18 -4
- data/lib/curtilage/generator_zones.rb +93 -0
- data/lib/curtilage/geometry.rb +48 -52
- data/lib/curtilage/lookup.rb +41 -21
- data/lib/curtilage/overture.rb +137 -17
- data/lib/curtilage/preview.rb +55 -16
- data/lib/curtilage/profiles.rb +62 -0
- data/lib/curtilage/regions.rb +4 -8
- data/lib/curtilage/result.rb +72 -7
- data/lib/curtilage/validation.rb +73 -9
- data/lib/curtilage/version.rb +1 -1
- data/lib/curtilage/zip_range.rb +81 -16
- data/lib/curtilage.rb +155 -17
- data/sql/build_from_shapefiles.sql +1 -1
- metadata +15 -2
data/lib/curtilage/preview.rb
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
require "cgi"
|
|
3
|
+
require "cgi/escape"
|
|
4
|
+
require "digest"
|
|
4
5
|
|
|
5
6
|
module Curtilage
|
|
6
7
|
# A self-contained HTML page for checking results by eye: one map per
|
|
@@ -29,7 +30,9 @@ module Curtilage
|
|
|
29
30
|
ids ||= (1..results.size).map(&:to_s)
|
|
30
31
|
cards = results.zip(ids).each_with_index.map { |(result, id), i| card(result, id, i, buffer_m) }
|
|
31
32
|
credits = results.flat_map { |r| r.attribution || Result::OSM_ATTRIBUTION }.uniq
|
|
32
|
-
|
|
33
|
+
zones = %w[approach pickup].select { |z| results.any? { |r| r.public_send("#{z}_ring") } }
|
|
34
|
+
zones << "candidate" if results.any? { |r| r.candidates&.any? }
|
|
35
|
+
page(title, cards, toolbar(results), credits, [buffer_m, zones])
|
|
33
36
|
end
|
|
34
37
|
|
|
35
38
|
# ok, flagged (ok, with flags) or invalid.
|
|
@@ -59,7 +62,8 @@ module Curtilage
|
|
|
59
62
|
["ok", "Ok, no flags (#{count.call("ok")})"]] + flags.map { |f, n| ["flag:#{f}", "Flag #{f} (#{n})"] }
|
|
60
63
|
end
|
|
61
64
|
|
|
62
|
-
SORTS = [%w[input Input order], ["look", "Needs a look first"],
|
|
65
|
+
SORTS = [%w[input Input order], ["look", "Needs a look first"], ["confidence", "Lowest confidence first"],
|
|
66
|
+
%w[id Id], ["large", "Largest premises first"],
|
|
63
67
|
["small", "Smallest premises first"]].map { |key, *words| [key, words.join(" ")] }.freeze
|
|
64
68
|
|
|
65
69
|
def select_options(options)
|
|
@@ -85,7 +89,8 @@ module Curtilage
|
|
|
85
89
|
def card_data(result, id, index)
|
|
86
90
|
area = result.ring ? result.validation.metrics[:area_m2].to_f.round : -1
|
|
87
91
|
%(data-index="#{index}" data-id="#{h(id)}" data-state="#{state(result)}" ) +
|
|
88
|
-
%(data-flags="#{h(result.flags.join(" "))}" data-nflags="#{result.flags.size}" data-area="#{area}")
|
|
92
|
+
%(data-flags="#{h(result.flags.join(" "))}" data-nflags="#{result.flags.size}" data-area="#{area}" ) +
|
|
93
|
+
%(data-confidence="#{result.confidence}")
|
|
89
94
|
end
|
|
90
95
|
|
|
91
96
|
def flag_tags(flags)
|
|
@@ -95,18 +100,23 @@ module Curtilage
|
|
|
95
100
|
def shapes(result, buffer_m)
|
|
96
101
|
parts = result.features ? map_shapes(result.features, result.building) : []
|
|
97
102
|
grown = buffer_m && result.ring && result.buffered(buffer_m)
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
parts << path(
|
|
103
|
+
rings = { "buffer" => grown, "approach" => result.approach_ring, "premises" => result.ring,
|
|
104
|
+
"pickup" => result.pickup_ring, "store" => result.store_ring }
|
|
105
|
+
rings.each { |css, ring| parts << path(ring, result.pin, css) if ring }
|
|
106
|
+
(result.candidates || []).each { |c| parts.unshift(path(c.ring, result.pin, "candidate")) }
|
|
101
107
|
parts.concat(access_marks(result))
|
|
102
108
|
parts << %(<circle r="2.2" class="pin"><title>pin</title></circle>) << scale_bar
|
|
103
109
|
end
|
|
104
110
|
|
|
105
111
|
def access_marks(result)
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
112
|
+
marks = result.entrances.map do |e|
|
|
113
|
+
street = [e[:street], e[:street_class]].compact.join(", ")
|
|
114
|
+
[e[:point], "driveway entrance#{" from #{street}" unless street.empty?}", "access"]
|
|
115
|
+
end
|
|
116
|
+
marks << [result.staging_point, "staging point (estimated)", "staging"] if result.staging_point
|
|
117
|
+
marks.map do |point, tip, css|
|
|
118
|
+
x, y = Geometry.project([point], result.pin).first
|
|
119
|
+
%(<circle cx="#{x.round(1)}" cy="#{(-y).round(1)}" r="3.5" class="#{css}"><title>#{h(tip)}</title></circle>)
|
|
110
120
|
end
|
|
111
121
|
end
|
|
112
122
|
|
|
@@ -144,15 +154,20 @@ module Curtilage
|
|
|
144
154
|
d = result.details
|
|
145
155
|
return "" unless d
|
|
146
156
|
|
|
147
|
-
items = []
|
|
157
|
+
items = ["confidence #{result.confidence}"]
|
|
148
158
|
items << "building #{d[:building][:area_m2]} m²" if d[:building]
|
|
149
159
|
items << "premises #{result.validation.metrics[:area_m2]&.round} m²" if result.ring
|
|
150
160
|
items << "parking #{d[:parking_area_m2]} m² (about #{d[:parking_spaces_estimate]} spaces)"
|
|
151
161
|
items << "street frontage #{d[:frontage_m]} m"
|
|
152
162
|
items << "#{d[:access_points].size} driveway entrance(s)" if d[:access_points].any?
|
|
163
|
+
items << candidates_fact(result.candidates) if result.candidates&.any?
|
|
153
164
|
%(<p class="facts">#{h(items.join(" · "))}</p>)
|
|
154
165
|
end
|
|
155
166
|
|
|
167
|
+
def candidates_fact(candidates)
|
|
168
|
+
"#{candidates.size} other candidate(s) (dashed), confidence #{candidates.map(&:confidence).join(", ")}"
|
|
169
|
+
end
|
|
170
|
+
|
|
156
171
|
def path(ring, pin, css)
|
|
157
172
|
xy_path(Geometry.open_ring(Geometry.project(ring, pin)), css)
|
|
158
173
|
end
|
|
@@ -165,26 +180,43 @@ module Curtilage
|
|
|
165
180
|
%(<path d="#{d}" class="#{css}">#{tip}</path>)
|
|
166
181
|
end
|
|
167
182
|
|
|
168
|
-
|
|
183
|
+
# Unicode direction controls can make text read differently from what it
|
|
184
|
+
# is (a name that seems to say one thing and says another); they never
|
|
185
|
+
# belong in a map label.
|
|
186
|
+
BIDI = /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/
|
|
187
|
+
|
|
188
|
+
def h(text) = CGI.escapeHTML(text.to_s.gsub(BIDI, ""))
|
|
189
|
+
|
|
190
|
+
# Only the page's own inline style and script may run, by hash; nothing
|
|
191
|
+
# can be loaded from anywhere. A missed escape can't run script.
|
|
192
|
+
def csp
|
|
193
|
+
"default-src 'none'; style-src 'sha256-#{Digest::SHA256.base64digest(STYLE)}'; " \
|
|
194
|
+
"script-src 'sha256-#{Digest::SHA256.base64digest(SCRIPT)}'; img-src data:; base-uri 'none'; form-action 'none'"
|
|
195
|
+
end
|
|
169
196
|
|
|
170
|
-
|
|
197
|
+
# extras: [buffer_m, zones drawn on some card], for the legend.
|
|
198
|
+
def page(title, cards, toolbar, credits, extras)
|
|
171
199
|
<<~HTML
|
|
172
200
|
<!doctype html><html lang="en"><head><meta charset="utf-8">
|
|
201
|
+
<meta http-equiv="Content-Security-Policy" content="#{csp}">
|
|
173
202
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
174
203
|
<title>#{h(title)}</title><style>#{STYLE}</style></head><body>
|
|
175
204
|
<h1>#{h(title)}</h1>#{toolbar}
|
|
176
|
-
<p class="legend">#{legend(
|
|
205
|
+
<p class="legend">#{legend(*extras)}</p>
|
|
177
206
|
<p class="muted">Each map is #{VIEW_M * 2} m across, north up, drawn from the map data only (no imagery).
|
|
178
207
|
Hover over a flag for what it means, or a road for its name. Map data: #{h(credits.join("; "))}.</p>
|
|
179
208
|
<main>#{cards.join}</main><script>#{SCRIPT}</script></body></html>
|
|
180
209
|
HTML
|
|
181
210
|
end
|
|
182
211
|
|
|
183
|
-
def legend(buffer_m)
|
|
212
|
+
def legend(buffer_m, zones = [])
|
|
184
213
|
keys = [%w[premises premises], ["store", "store zone"], ["site", "the site's building"],
|
|
185
214
|
["building", "other buildings"], %w[parking parking], ["road", "public road"],
|
|
186
215
|
["service", "service road or driveway"], %w[rail railway], ["access", "driveway entrance"]]
|
|
187
216
|
keys << ["buffer", "premises + #{format("%g", buffer_m)} m"] if buffer_m
|
|
217
|
+
keys << ["approach", "approach zone"] if zones.include?("approach")
|
|
218
|
+
keys << ["pickup", "pickup zone (estimated)"] if zones.include?("pickup")
|
|
219
|
+
keys << ["candidate", "other candidates"] if zones.include?("candidate")
|
|
188
220
|
keys.map { |css, text| %(<span><i class="k-#{css}"></i>#{h(text)}</span>) }.join(" ")
|
|
189
221
|
end
|
|
190
222
|
|
|
@@ -199,6 +231,7 @@ module Curtilage
|
|
|
199
231
|
input: (a, b) => num(a, "index") - num(b, "index"),
|
|
200
232
|
look: (a, b) => rank[a.dataset.state] - rank[b.dataset.state] || num(b, "nflags") - num(a, "nflags") ||
|
|
201
233
|
num(a, "index") - num(b, "index"),
|
|
234
|
+
confidence: (a, b) => num(a, "confidence") - num(b, "confidence") || num(a, "index") - num(b, "index"),
|
|
202
235
|
id: (a, b) => a.dataset.id.localeCompare(b.dataset.id, undefined, { numeric: true }),
|
|
203
236
|
large: (a, b) => num(b, "area") - num(a, "area"),
|
|
204
237
|
small: (a, b) => (num(a, "area") < 0) - (num(b, "area") < 0) || num(a, "area") - num(b, "area"),
|
|
@@ -252,6 +285,10 @@ module Curtilage
|
|
|
252
285
|
.premises { fill: var(--premises); fill-opacity: .12; stroke: var(--premises); stroke-width: 2; }
|
|
253
286
|
.buffer { fill: none; stroke: var(--premises); stroke-width: 1.2; stroke-dasharray: 4 3; }
|
|
254
287
|
.store { fill: none; stroke: var(--store); stroke-width: 1.5; } .pin { fill: var(--fg); }
|
|
288
|
+
.approach { fill: none; stroke: var(--premises); stroke-width: 1; stroke-dasharray: 1 3; }
|
|
289
|
+
.pickup { fill: var(--access); fill-opacity: .25; stroke: var(--access); stroke-width: 1; }
|
|
290
|
+
.staging { fill: var(--card); stroke: var(--access); stroke-width: 2; }
|
|
291
|
+
.candidate { fill: none; stroke: var(--access); stroke-width: 1; stroke-dasharray: 5 3; }
|
|
255
292
|
.access { fill: var(--access); stroke: var(--card); stroke-width: 1; }
|
|
256
293
|
.scale path { fill: none; stroke: var(--fg); stroke-width: 1.2; }
|
|
257
294
|
.scale text { fill: var(--fg); font-size: 9px; dominant-baseline: middle; }
|
|
@@ -271,6 +308,8 @@ module Curtilage
|
|
|
271
308
|
.k-rail { height: 0 !important; border-top: 2px dashed var(--fg); }
|
|
272
309
|
.k-access { width: 9px !important; height: 9px !important; border-radius: 50%; background: var(--access); }
|
|
273
310
|
.k-buffer { border: 1px dashed var(--premises); }
|
|
311
|
+
.k-candidate { border: 1px dashed var(--access); }
|
|
312
|
+
.k-approach { border: 1px dotted var(--premises); } .k-pickup { background: var(--access); opacity: .4; }
|
|
274
313
|
CSS
|
|
275
314
|
end
|
|
276
315
|
end
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "psych"
|
|
5
|
+
|
|
6
|
+
module Curtilage
|
|
7
|
+
# Your own named styles, from a JSON or YAML file: each profile is a set
|
|
8
|
+
# of generation options, optionally starting from a built-in preset.
|
|
9
|
+
#
|
|
10
|
+
# # profiles.yml
|
|
11
|
+
# big_box:
|
|
12
|
+
# preset: whole_lot
|
|
13
|
+
# parking_max_extent_m: 150
|
|
14
|
+
# validation: { max_area_error_m2: 300000 }
|
|
15
|
+
#
|
|
16
|
+
# options = Curtilage::Profiles.load("profiles.yml")[:big_box]
|
|
17
|
+
# Curtilage.generate_many(pins, **options)
|
|
18
|
+
module Profiles
|
|
19
|
+
MAX_BYTES = 1_000_000
|
|
20
|
+
MAX_PROFILES = 100
|
|
21
|
+
# Options whose values are names, given as text in the file.
|
|
22
|
+
NAMES = %i[method scope buildings preset].freeze
|
|
23
|
+
|
|
24
|
+
module_function
|
|
25
|
+
|
|
26
|
+
# { name => options } from path (.json, .yml or .yaml). Every profile
|
|
27
|
+
# is checked like generate's options, so a mistake fails here, naming it.
|
|
28
|
+
def load(path)
|
|
29
|
+
raise ArgumentError, "#{path} is over #{MAX_BYTES / 1000} KB" if File.size(path) > MAX_BYTES
|
|
30
|
+
|
|
31
|
+
text = File.read(path, encoding: "bom|utf-8")
|
|
32
|
+
parse(text, File.extname(path).downcase == ".json" ? :json : :yaml)
|
|
33
|
+
rescue SystemCallError => e
|
|
34
|
+
raise ArgumentError, "can't read profiles: #{e.message}"
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def parse(text, format)
|
|
38
|
+
doc = format == :json ? JSON.parse(text, max_nesting: 10) : Psych.safe_load(text)
|
|
39
|
+
raise ArgumentError, "profiles are a map of name => options" unless doc.is_a?(Hash) && doc.values.all?(Hash)
|
|
40
|
+
raise ArgumentError, "more than #{MAX_PROFILES} profiles" if doc.size > MAX_PROFILES
|
|
41
|
+
|
|
42
|
+
doc.to_h { |name, options| [name.to_s.to_sym, profile(name, options)] }
|
|
43
|
+
rescue JSON::ParserError, Psych::Exception => e
|
|
44
|
+
raise ArgumentError, "unreadable profiles: #{e.message[0, 200]}"
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def profile(name, options)
|
|
48
|
+
opts = options.to_h { |k, v| [k.to_s.to_sym, value(k.to_s.to_sym, v)] }
|
|
49
|
+
Curtilage.send(:check_generation_options, opts)
|
|
50
|
+
opts
|
|
51
|
+
rescue ArgumentError => e
|
|
52
|
+
raise ArgumentError, "profile #{name}: #{e.message}"
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def value(key, value)
|
|
56
|
+
return value.to_s.to_sym if NAMES.include?(key) && value.is_a?(String)
|
|
57
|
+
return value.to_h { |k, v| [k.to_s.to_sym, v] } if key == :validation && value.is_a?(Hash)
|
|
58
|
+
|
|
59
|
+
value
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
end
|
data/lib/curtilage/regions.rb
CHANGED
|
@@ -13,12 +13,7 @@ module Curtilage
|
|
|
13
13
|
MAX_INDEX_BYTES = 50_000_000
|
|
14
14
|
|
|
15
15
|
Region = Struct.new(:id, :path, :bbox, :rings, :extent_area, keyword_init: true) do
|
|
16
|
-
def covers?(point)
|
|
17
|
-
lng, lat = point
|
|
18
|
-
return false unless lng.between?(bbox[0], bbox[2]) && lat.between?(bbox[1], bbox[3])
|
|
19
|
-
|
|
20
|
-
rings.any? { |ring| Geometry.contains?(ring, point) }
|
|
21
|
-
end
|
|
16
|
+
def covers?(point) = Geometry.in_rings?(point, bbox, rings)
|
|
22
17
|
end
|
|
23
18
|
|
|
24
19
|
def self.download
|
|
@@ -28,6 +23,8 @@ module Curtilage
|
|
|
28
23
|
def self.parse(json)
|
|
29
24
|
features = JSON.parse(json).fetch("features")
|
|
30
25
|
new(features.filter_map { |f| region(f) })
|
|
26
|
+
rescue JSON::ParserError, KeyError, TypeError, NoMethodError => e
|
|
27
|
+
raise Error, "unreadable Geofabrik region index: #{e.message[0, 200]}"
|
|
31
28
|
end
|
|
32
29
|
|
|
33
30
|
def self.region(feature)
|
|
@@ -36,8 +33,7 @@ module Curtilage
|
|
|
36
33
|
rings = outer_rings(feature["geometry"])
|
|
37
34
|
return nil unless path && !rings.empty?
|
|
38
35
|
|
|
39
|
-
|
|
40
|
-
bbox = [points.map(&:first).min, points.map(&:last).min, points.map(&:first).max, points.map(&:last).max]
|
|
36
|
+
bbox = Geometry.bounds(rings.flatten(1))
|
|
41
37
|
Region.new(id: props["id"], path: path, bbox: bbox, rings: rings,
|
|
42
38
|
extent_area: (bbox[2] - bbox[0]) * (bbox[3] - bbox[1]))
|
|
43
39
|
end
|
data/lib/curtilage/result.rb
CHANGED
|
@@ -9,8 +9,15 @@ module Curtilage
|
|
|
9
9
|
# premises were made. features: the map data it was made from (a Features,
|
|
10
10
|
# in metres around pin), kept for previews and debugging; generate_many
|
|
11
11
|
# drops it unless asked (keep_features: true), and it isn't serialised.
|
|
12
|
+
# steps: the explanation as records, one per line, for tools to show or
|
|
13
|
+
# audit (see the reference for the fields).
|
|
14
|
+
# provenance: what the result was made from and with (gem version, data
|
|
15
|
+
# source and release, options, a hash of the map data), so it can be
|
|
16
|
+
# reproduced; it holds no timestamps, so the same inputs give the same
|
|
17
|
+
# output byte for byte.
|
|
12
18
|
Result = Struct.new(:method_name, :pin, :ring, :store_ring, :explanation, :flags, :validation, :building,
|
|
13
|
-
:details, :attribution, :features,
|
|
19
|
+
:details, :attribution, :features, :provenance, :steps, :approach_ring, :pickup_ring,
|
|
20
|
+
:staging_point, :pin_quality, :candidates, keyword_init: true) do
|
|
14
21
|
def ok?
|
|
15
22
|
!ring.nil? && validation.ok?
|
|
16
23
|
end
|
|
@@ -35,26 +42,80 @@ module Curtilage
|
|
|
35
42
|
include_store ? { type: "FeatureCollection", features: list } : list.first
|
|
36
43
|
end
|
|
37
44
|
|
|
38
|
-
# [premises Feature, store Feature
|
|
39
|
-
# a store zone).
|
|
45
|
+
# [premises Feature, store Feature, then any zones asked for] (the
|
|
46
|
+
# store's geometry is nil without a store zone). properties.role tells
|
|
47
|
+
# them apart: premises, store, approach or pickup.
|
|
40
48
|
def geojson_features(attribution: self.attribution || Result::OSM_ATTRIBUTION, properties: {})
|
|
41
49
|
premises = {
|
|
42
50
|
type: "Feature",
|
|
43
51
|
geometry: Result.polygon(ring),
|
|
44
52
|
properties: properties.merge(
|
|
45
|
-
role: "premises", ok: ok?,
|
|
53
|
+
role: "premises", ok: ok?, pin_quality: pin_quality, confidence: confidence,
|
|
54
|
+
confidence_factors: confidence_factors,
|
|
55
|
+
method: method_name, flags: flags, building: building, details: details,
|
|
46
56
|
errors: validation.errors, warnings: validation.warnings, metrics: validation.metrics,
|
|
47
|
-
explanation: explanation, attribution: attribution
|
|
57
|
+
explanation: explanation, steps: steps || [], attribution: attribution, provenance: provenance
|
|
48
58
|
),
|
|
49
59
|
}
|
|
50
60
|
store = { type: "Feature", geometry: Result.polygon(store_ring),
|
|
51
61
|
properties: properties.merge(role: "store", building: building, attribution: attribution) }
|
|
52
|
-
[premises, store]
|
|
62
|
+
[premises, store] + zone_features(properties.merge(attribution: attribution)) + candidate_features(properties)
|
|
53
63
|
end
|
|
54
64
|
|
|
65
|
+
# Each candidate (generate's candidates:) as a Feature of its own, role
|
|
66
|
+
# candidate, rank 1 for the most confident, with everything a premises
|
|
67
|
+
# Feature carries.
|
|
68
|
+
def candidate_features(properties)
|
|
69
|
+
(candidates || []).each_with_index.map do |c, i|
|
|
70
|
+
c.geojson_features(properties: properties).first.tap do |f|
|
|
71
|
+
f[:properties] = f[:properties].merge(role: "candidate", rank: i + 1)
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# The candidates in short, for NDJSON and the like.
|
|
77
|
+
def candidate_summaries
|
|
78
|
+
(candidates || []).each_with_index.map do |c, i|
|
|
79
|
+
{ rank: i + 1, geometry: Result.polygon(c.ring), confidence: c.confidence, flags: c.flags,
|
|
80
|
+
building: c.building, method: c.method_name, explanation: c.explanation }
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# The approach and pickup zones and the staging point, when asked for
|
|
85
|
+
# and made. The pickup zone and staging point are always estimated (no
|
|
86
|
+
# source maps pickup spots or entrances).
|
|
87
|
+
def zone_features(properties)
|
|
88
|
+
zones = { "approach" => [Result.polygon(approach_ring), {}],
|
|
89
|
+
"pickup" => [Result.polygon(pickup_ring), { estimated: true }],
|
|
90
|
+
"staging" => [Result.point(staging_point), { estimated: true }] }
|
|
91
|
+
zones.filter_map do |role, (geometry, extra)|
|
|
92
|
+
geometry && { type: "Feature", geometry: geometry, properties: properties.merge(role: role, **extra) }
|
|
93
|
+
end
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# Where vehicles enter from the street: [{ point: [lng, lat], street:,
|
|
97
|
+
# street_class:, street_id:, driveway: }, ...] (details[:entrances]).
|
|
98
|
+
def entrances = details ? details[:entrances] : []
|
|
99
|
+
|
|
100
|
+
# Puts a step, and its line of the explanation, before the others (the
|
|
101
|
+
# data source, a failed first attempt).
|
|
102
|
+
def prepend_step(text, step:, **fields)
|
|
103
|
+
explanation.unshift(text)
|
|
104
|
+
(self.steps ||= []).unshift({ step: step, text: text, **fields }.compact)
|
|
105
|
+
self
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# How far to trust the result, 0 to 1 (see Confidence), and the factors
|
|
109
|
+
# behind it: [{ name:, met:, weight: }, ...].
|
|
110
|
+
def confidence = Confidence.assess(self)[0]
|
|
111
|
+
def confidence_factors = Confidence.assess(self)[1]
|
|
112
|
+
|
|
55
113
|
# Well-known text, for databases and spreadsheets.
|
|
56
114
|
def to_wkt = Result.wkt(ring)
|
|
57
115
|
def store_wkt = Result.wkt(store_ring)
|
|
116
|
+
def approach_wkt = Result.wkt(approach_ring)
|
|
117
|
+
def pickup_wkt = Result.wkt(pickup_ring)
|
|
118
|
+
def staging_wkt = staging_point && "POINT (#{staging_point.join(" ")})"
|
|
58
119
|
|
|
59
120
|
# The premises grown (positive metres) or shrunk (negative) evenly, for a
|
|
60
121
|
# geofence with a margin: [[lng, lat], ...] closed. Corners are rounded
|
|
@@ -66,7 +127,7 @@ module Curtilage
|
|
|
66
127
|
grown = metres.negative? ? Geometry.clip_inside(xy, xy, -metres) : Geometry.round_buffer(xy, metres)
|
|
67
128
|
return nil if grown.size < 3 || Geometry.area(grown) < 1
|
|
68
129
|
|
|
69
|
-
out = Geometry.
|
|
130
|
+
out = Geometry.lnglat(Geometry.clean(grown), pin, provenance&.dig(:options, :precision) || 7)
|
|
70
131
|
out << out.first
|
|
71
132
|
end
|
|
72
133
|
|
|
@@ -79,6 +140,10 @@ module Curtilage
|
|
|
79
140
|
def self.polygon(ring)
|
|
80
141
|
ring && { type: "Polygon", coordinates: [ring] }
|
|
81
142
|
end
|
|
143
|
+
|
|
144
|
+
def self.point(lnglat)
|
|
145
|
+
lnglat && { type: "Point", coordinates: lnglat }
|
|
146
|
+
end
|
|
82
147
|
end
|
|
83
148
|
|
|
84
149
|
Result::OSM_ATTRIBUTION = ["© OpenStreetMap contributors"].freeze
|
data/lib/curtilage/validation.rb
CHANGED
|
@@ -25,25 +25,88 @@ module Curtilage
|
|
|
25
25
|
swap_near_m: 1_000,
|
|
26
26
|
}.freeze
|
|
27
27
|
|
|
28
|
+
# A number written as text: plain decimal, optionally with an exponent.
|
|
29
|
+
# Ruby's Float() also takes hex ("0x1A") and underscores ("1_0"), which
|
|
30
|
+
# in a pin list are mistakes, not numbers.
|
|
31
|
+
DECIMAL = /\A[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE]([+-]?\d+))?\z/
|
|
32
|
+
|
|
28
33
|
module_function
|
|
29
34
|
|
|
30
|
-
# pin
|
|
35
|
+
# The pin as [lng, lat] floats, or ArgumentError: two finite numbers (or
|
|
36
|
+
# decimal strings), longitude within 180 and latitude within 90. Every
|
|
37
|
+
# entry point checks pins through here.
|
|
38
|
+
def pin(pin)
|
|
39
|
+
raise ArgumentError, "a pin is [lng, lat]: #{pin.inspect}" unless pin.is_a?(Array) && pin.size >= 2
|
|
40
|
+
|
|
41
|
+
lng, lat = pin.first(2).map { |v| coordinate(v, pin) }
|
|
42
|
+
raise ArgumentError, "pin out of range (longitude first): #{pin.inspect}" unless lng.abs <= 180 && lat.abs <= 90
|
|
43
|
+
|
|
44
|
+
[lng, lat]
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def coordinate(value, pin)
|
|
48
|
+
number = case value
|
|
49
|
+
when Numeric then value.to_f
|
|
50
|
+
when String then decimal(value.strip)
|
|
51
|
+
end
|
|
52
|
+
raise ArgumentError, "a pin is two numbers: #{pin.inspect}" unless number&.finite?
|
|
53
|
+
|
|
54
|
+
number
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# A plain decimal string as a float, or nil. Exponents past 300 are
|
|
58
|
+
# refused before converting: no coordinate needs one, and Float() warns.
|
|
59
|
+
def decimal(text)
|
|
60
|
+
match = DECIMAL.match(text)
|
|
61
|
+
return nil unless match && match[1].to_i.abs <= 300
|
|
62
|
+
|
|
63
|
+
Float(text)
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# The limits with options applied; unknown keys and values that aren't
|
|
67
|
+
# positive numbers are refused (a misspelt limit would be ignored).
|
|
68
|
+
def limits(options)
|
|
69
|
+
unknown = options.keys - DEFAULTS.keys
|
|
70
|
+
raise ArgumentError, "unknown validation limit(s): #{unknown.join(", ")} (have: #{DEFAULTS.keys.join(", ")})" \
|
|
71
|
+
if unknown.any?
|
|
72
|
+
|
|
73
|
+
options.each do |key, value|
|
|
74
|
+
next if value.is_a?(Numeric) && value.real? && value.to_f.finite? && value.positive? && value <= 1e9
|
|
75
|
+
|
|
76
|
+
raise ArgumentError, "validation limit #{key} must be a positive number: #{value.inspect}"
|
|
77
|
+
end
|
|
78
|
+
DEFAULTS.merge(options)
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# pin: [lng, lat]. ring: [[lng, lat], ...], closed or not. options: the
|
|
82
|
+
# limits in DEFAULTS, e.g. max_area_error_m2: 300_000 for big lots.
|
|
31
83
|
def check(pin, ring, **options)
|
|
32
|
-
opts =
|
|
33
|
-
|
|
34
|
-
return Result.new(
|
|
84
|
+
opts = limits(options)
|
|
85
|
+
errors = shape_errors(pin, ring)
|
|
86
|
+
return Result.new(errors, [], {}) if errors.intersect?(%w[missing invalid_coordinates too_few_points])
|
|
35
87
|
|
|
36
|
-
errors = Geometry.closed?(ring) ? [] : ["unclosed"]
|
|
37
88
|
open = Geometry.open_ring(ring)
|
|
38
|
-
return Result.new(errors + ["too_few_points"], [], {}) if open.uniq.size < 3
|
|
39
|
-
|
|
40
89
|
xy = Geometry.project(open, pin)
|
|
41
90
|
metrics = measure(xy).merge(points: open.size)
|
|
42
91
|
errors << "swapped" if swapped?(open, pin, xy, opts)
|
|
43
|
-
errors << "self_intersecting" if Geometry.self_intersects?(xy)
|
|
44
92
|
Result.new(errors + metric_errors(metrics, opts), metric_warnings(metrics, opts), metrics)
|
|
45
93
|
end
|
|
46
94
|
|
|
95
|
+
# What makes any ring unusable, whatever its size: missing, bad
|
|
96
|
+
# coordinates, unclosed, too few points, crossing itself. Zones other
|
|
97
|
+
# than the premises (Generator zones) get only this check.
|
|
98
|
+
def shape_errors(pin, ring)
|
|
99
|
+
return ["missing"] if ring.nil? || ring.empty?
|
|
100
|
+
return ["invalid_coordinates"] unless Geometry.valid_coordinates?(ring)
|
|
101
|
+
|
|
102
|
+
errors = Geometry.closed?(ring) ? [] : ["unclosed"]
|
|
103
|
+
open = Geometry.open_ring(ring)
|
|
104
|
+
return errors + ["too_few_points"] if open.uniq.size < 3
|
|
105
|
+
|
|
106
|
+
errors << "self_intersecting" if Geometry.self_intersects?(Geometry.project(open, pin))
|
|
107
|
+
errors
|
|
108
|
+
end
|
|
109
|
+
|
|
47
110
|
def metric_errors(metrics, opts)
|
|
48
111
|
errors = []
|
|
49
112
|
errors << "pin_outside" unless metrics[:pin_inside]
|
|
@@ -63,7 +126,8 @@ module Curtilage
|
|
|
63
126
|
|
|
64
127
|
def measure(xy)
|
|
65
128
|
origin = [0.0, 0.0]
|
|
66
|
-
|
|
129
|
+
rect = Geometry.minimum_rectangle(xy)
|
|
130
|
+
mbr_area, orientation = rect ? [rect[:area], (rect[:angle] * 180 / Math::PI) % 180] : [0.0, 0.0]
|
|
67
131
|
area = Geometry.area(xy)
|
|
68
132
|
{
|
|
69
133
|
area_m2: area.round,
|
data/lib/curtilage/version.rb
CHANGED
data/lib/curtilage/zip_range.rb
CHANGED
|
@@ -22,34 +22,99 @@ module Curtilage
|
|
|
22
22
|
LOCAL_SIGNATURE = 0x04034b50
|
|
23
23
|
TAIL_BYTES = 65_557 # end-of-central-directory record plus the longest comment
|
|
24
24
|
MAX_ENTRIES = 1_000
|
|
25
|
+
# Decompression bombs: the layers a build takes may not inflate to more
|
|
26
|
+
# than this in all (Texas's are a few GB), nor any member by more than
|
|
27
|
+
# this ratio (padded .dbf text compresses well, but not this well).
|
|
28
|
+
MAX_UNCOMPRESSED_BYTES = 20_000_000_000
|
|
29
|
+
MAX_RATIO = 200
|
|
30
|
+
MEMBER_NAME = /\A[\w.-]+\z/
|
|
25
31
|
|
|
26
32
|
module_function
|
|
27
33
|
|
|
28
34
|
# Extracts the members whose names match any of patterns (File.fnmatch)
|
|
29
35
|
# into dir. Returns the extracted file paths.
|
|
30
36
|
def extract(host, path, patterns, dir, max_bytes:)
|
|
31
|
-
|
|
37
|
+
chosen = choose(entries(host, path), patterns, max_bytes)
|
|
38
|
+
|
|
39
|
+
FileUtils.mkdir_p(dir)
|
|
40
|
+
# Each run (adjacent members) streams on its own connection, in parallel.
|
|
41
|
+
# All finish before any error is raised: the caller may delete dir.
|
|
42
|
+
threads = runs(chosen).map do |run|
|
|
43
|
+
Thread.new do
|
|
44
|
+
Thread.current.report_on_exception = false
|
|
45
|
+
fetch_run(host, path, run, dir)
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
Curtilage.join_all(threads).flatten
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# The members to take: those matching patterns, with plain file names
|
|
52
|
+
# (nothing can land outside the folder), within the size caps.
|
|
53
|
+
def choose(entries, patterns, max_bytes)
|
|
32
54
|
chosen = entries.select { |e| patterns.any? { |p| File.fnmatch(p, File.basename(e.name)) } }
|
|
33
55
|
raise Unsupported, "no members match #{patterns.join(", ")}" if chosen.empty?
|
|
34
56
|
raise Unsupported, "members over #{max_bytes} bytes" if chosen.sum(&:compressed_size) > max_bytes
|
|
35
57
|
|
|
58
|
+
chosen.each { |e| check_member(e) }
|
|
59
|
+
total = chosen.sum(&:uncompressed_size)
|
|
60
|
+
raise Corrupt, "members would inflate to #{total} bytes, over #{MAX_UNCOMPRESSED_BYTES}" \
|
|
61
|
+
if total > MAX_UNCOMPRESSED_BYTES
|
|
62
|
+
|
|
63
|
+
chosen
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def check_member(entry)
|
|
67
|
+
raise Corrupt, "bad member name #{entry.name.inspect}" unless File.basename(entry.name).match?(MEMBER_NAME)
|
|
68
|
+
|
|
69
|
+
ratio = entry.uncompressed_size / [entry.compressed_size, 1].max
|
|
70
|
+
return unless ratio > MAX_RATIO && entry.uncompressed_size > 1_000_000
|
|
71
|
+
|
|
72
|
+
raise Corrupt, "#{entry.name} would inflate #{ratio} times"
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# Applies the same checks to a zip already on disk.
|
|
76
|
+
def check_local(zip, patterns, max_bytes:)
|
|
77
|
+
choose(local_entries(zip), patterns, max_bytes)
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
# Extracts the matching members of a zip on disk into dir, with the same
|
|
81
|
+
# checks and CRCs as a range download: no unzip needed. Returns the paths.
|
|
82
|
+
def extract_local(zip, patterns, dir, max_bytes:)
|
|
83
|
+
chosen = check_local(zip, patterns, max_bytes: max_bytes)
|
|
36
84
|
FileUtils.mkdir_p(dir)
|
|
37
|
-
|
|
38
|
-
|
|
85
|
+
File.open(zip, "rb") do |file|
|
|
86
|
+
runs(chosen).flat_map do |run|
|
|
87
|
+
reader = RunReader.new(run, dir)
|
|
88
|
+
file.seek(run.first.offset)
|
|
89
|
+
left = run.last.data_end - run.first.offset
|
|
90
|
+
while left.positive? && (chunk = file.read([left, 1 << 20].min))
|
|
91
|
+
reader << chunk
|
|
92
|
+
left -= chunk.bytesize
|
|
93
|
+
end
|
|
94
|
+
reader.finish
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def local_entries(zip)
|
|
100
|
+
entries_from(File.size(zip), ->(first, last) { File.binread(zip, last - first + 1, first) })
|
|
39
101
|
end
|
|
40
102
|
|
|
41
103
|
# The zip's central directory, each entry knowing where its bytes end.
|
|
42
104
|
def entries(host, path)
|
|
43
|
-
|
|
44
|
-
|
|
105
|
+
entries_from(content_length(host, path), ->(first, last) { range(host, path, first, last) })
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# read: (first, last) -> those bytes of the zip.
|
|
109
|
+
def entries_from(length, read)
|
|
110
|
+
tail = read.call([length - TAIL_BYTES, 0].max, length - 1)
|
|
45
111
|
eocd = tail.rindex(EOCD_SIGNATURE) or raise Unsupported, "no end-of-central-directory record"
|
|
46
112
|
count, cd_size, cd_offset = tail.byteslice(eocd + 10, 10).unpack("vVV")
|
|
47
113
|
if count == 0xFFFF || cd_offset == 0xFFFFFFFF || count > MAX_ENTRIES
|
|
48
|
-
raise Unsupported,
|
|
49
|
-
"zip64 or too many entries"
|
|
114
|
+
raise Unsupported, "zip64 or too many entries"
|
|
50
115
|
end
|
|
51
116
|
|
|
52
|
-
list = parse_central(
|
|
117
|
+
list = parse_central(read.call(cd_offset, cd_offset + cd_size - 1), count)
|
|
53
118
|
ends = list.map(&:offset).sort + [cd_offset]
|
|
54
119
|
list.each { |e| e.data_end = ends[ends.index(e.offset) + 1] }
|
|
55
120
|
end
|
|
@@ -128,6 +193,8 @@ module Curtilage
|
|
|
128
193
|
def <<(chunk)
|
|
129
194
|
@buffer << chunk
|
|
130
195
|
step while @member && !@buffer.empty? && progress?
|
|
196
|
+
rescue Zlib::Error => e
|
|
197
|
+
raise ZipRange::Corrupt, "#{@member&.name} doesn't inflate: #{e.message}"
|
|
131
198
|
end
|
|
132
199
|
|
|
133
200
|
def finish
|
|
@@ -193,8 +260,12 @@ module Curtilage
|
|
|
193
260
|
@remaining = @member.compressed_size
|
|
194
261
|
end
|
|
195
262
|
|
|
263
|
+
# Raw member bytes: inflated first when the member is compressed.
|
|
196
264
|
def write(bytes)
|
|
197
|
-
|
|
265
|
+
write_inflated(@inflate ? @inflate.inflate(bytes) : bytes)
|
|
266
|
+
end
|
|
267
|
+
|
|
268
|
+
def write_inflated(data)
|
|
198
269
|
@written += data.bytesize
|
|
199
270
|
raise ZipRange::Corrupt, "#{@member.name} inflates past its size" if @written > @member.uncompressed_size
|
|
200
271
|
|
|
@@ -204,7 +275,7 @@ module Curtilage
|
|
|
204
275
|
|
|
205
276
|
def finish_member
|
|
206
277
|
if @inflate
|
|
207
|
-
|
|
278
|
+
write_inflated(@inflate.finish)
|
|
208
279
|
@inflate.close
|
|
209
280
|
end
|
|
210
281
|
@file.close
|
|
@@ -213,12 +284,6 @@ module Curtilage
|
|
|
213
284
|
start_member
|
|
214
285
|
end
|
|
215
286
|
|
|
216
|
-
def write_tail(data)
|
|
217
|
-
@written += data.bytesize
|
|
218
|
-
@crc = Zlib.crc32(data, @crc)
|
|
219
|
-
@file.write(data)
|
|
220
|
-
end
|
|
221
|
-
|
|
222
287
|
def check_member
|
|
223
288
|
return if @crc == @member.crc && @written == @member.uncompressed_size
|
|
224
289
|
|