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
@@ -28,6 +28,12 @@ module Curtilage
28
28
  xy.map { |x, y| [lng0 + (x / sx), lat0 + (y / METRES_PER_DEGREE_LAT)] }
29
29
  end
30
30
 
31
+ # Inverse of project, rounded to 7 decimals (about a centimetre): what
32
+ # results hand out.
33
+ def lnglat(xy, origin, precision = 7)
34
+ unproject(xy, origin).map { |lng, lat| [lng.round(precision), lat.round(precision)] }
35
+ end
36
+
31
37
  def metres_per_degree_lng(lat)
32
38
  Math.cos(lat * Math::PI / 180) * METRES_PER_DEGREE_LNG_AT_EQUATOR
33
39
  end
@@ -59,6 +65,10 @@ module Curtilage
59
65
  (sum / 2.0).abs
60
66
  end
61
67
 
68
+ def distance(p, q)
69
+ Math.hypot(p[0] - q[0], p[1] - q[1])
70
+ end
71
+
62
72
  def centroid(xy)
63
73
  [xy.sum { |p| p[0] } / xy.size, xy.sum { |p| p[1] } / xy.size]
64
74
  end
@@ -83,21 +93,14 @@ module Curtilage
83
93
  end
84
94
 
85
95
  def segment_distance(point, a, b)
86
- px, py = point
87
- ax, ay = a
88
- bx, by = b
89
- dx = bx - ax
90
- dy = by - ay
91
- len2 = (dx * dx) + (dy * dy)
92
- t = len2.zero? ? 0 : (((px - ax) * dx) + ((py - ay) * dy)) / len2
93
- t = t.clamp(0.0, 1.0)
94
- Math.hypot(px - (ax + (t * dx)), py - (ay + (t * dy)))
96
+ distance(point, closest_point_on_segment(point, a, b))
95
97
  end
96
98
 
97
99
  # True when any two non-adjacent edges cross. O(n^2), fine for premises.
98
100
  def self_intersects?(xy)
99
101
  n = xy.size
100
102
  return false if n < 4
103
+ return swept_crossing?(xy) if n > 8
101
104
 
102
105
  edges = xy.each_index.map { |i| [xy[i], xy[(i + 1) % n]] }
103
106
  edges.each_index.any? do |i|
@@ -109,6 +112,30 @@ module Curtilage
109
112
  end
110
113
  end
111
114
 
115
+ # The same answer as checking every pair of edges, for bigger rings:
116
+ # edges in order of their left end, each checked only against earlier
117
+ # ones still overlapping it in x (two edges that cross overlap in x).
118
+ def swept_crossing?(xy)
119
+ n = xy.size
120
+ edges = xy.each_index.map { |i| [xy[i], xy[(i + 1) % n]] }
121
+ ranges = edges.map { |a, b| [a[0], b[0]].minmax }
122
+ active = []
123
+ (0...n).sort_by { |i| ranges[i][0] }.each do |i|
124
+ active.select! { |j| ranges[j][1] >= ranges[i][0] }
125
+ return true if crosses_any?(edges, i, active)
126
+
127
+ active << i
128
+ end
129
+ false
130
+ end
131
+
132
+ def crosses_any?(edges, index, others)
133
+ others.any? { |j| !adjacent?(index - j, edges.size) && segments_cross?(*edges[index], *edges[j]) }
134
+ end
135
+
136
+ # Edges whose indexes are gap apart in a ring of size share a vertex.
137
+ def adjacent?(gap, size) = [1, size - 1].include?(gap.abs)
138
+
112
139
  def segments_cross?(p1, p2, p3, p4)
113
140
  d1 = cross(p3, p4, p1)
114
141
  d2 = cross(p3, p4, p2)
@@ -157,14 +184,6 @@ module Curtilage
157
184
  best.min_by { |r| r[:area] }
158
185
  end
159
186
 
160
- # [area_m2, orientation_degrees_0_to_180] of the minimum rectangle.
161
- def min_rotated_rectangle(xy)
162
- rect = minimum_rectangle(xy)
163
- return [0.0, 0.0] unless rect
164
-
165
- [rect[:area], (rect[:angle] * 180 / Math::PI) % 180]
166
- end
167
-
168
187
  # The box around the points with sides parallel and perpendicular to
169
188
  # angle (radians), grown by margin metres on every side. Counter-clockwise.
170
189
  def oriented_box(xy, angle, margin = 0)
@@ -192,24 +211,6 @@ module Curtilage
192
211
  signed_area(xy).negative? ? xy.reverse : xy
193
212
  end
194
213
 
195
- # Centre of mass of the polygon's area (the vertex mean is biased toward
196
- # densely sampled edges).
197
- def area_centroid(xy)
198
- a = signed_area(xy)
199
- return centroid(xy) if a.abs < 1e-9
200
-
201
- cx = 0.0
202
- cy = 0.0
203
- xy.each_index do |i|
204
- x1, y1 = xy[i]
205
- x2, y2 = xy[(i + 1) % xy.size]
206
- f = (x1 * y2) - (x2 * y1)
207
- cx += (x1 + x2) * f
208
- cy += (y1 + y2) * f
209
- end
210
- [cx / (6 * a), cy / (6 * a)]
211
- end
212
-
213
214
  # Keeps the part of the polygon where (p - origin) . normal <= 0
214
215
  # (Sutherland-Hodgman against one line). Works for any simple polygon;
215
216
  # a non-convex input can come back with zero-width bridges, which don't
@@ -232,16 +233,7 @@ module Curtilage
232
233
  end
233
234
 
234
235
  # The part of subject inside a convex clipper.
235
- def clip_convex(subject, clipper)
236
- clipper = counter_clockwise(clipper)
237
- clipper.each_index.reduce(subject) do |poly, i|
238
- break [] if poly.size < 3
239
-
240
- a = clipper[i]
241
- b = clipper[(i + 1) % clipper.size]
242
- clip_half_plane(poly, a, [b[1] - a[1], a[0] - b[0]])
243
- end
244
- end
236
+ def clip_convex(subject, clipper) = clip_inside(subject, clipper, 0)
245
237
 
246
238
  def closest_point_on_segment(point, a, b)
247
239
  dx = b[0] - a[0]
@@ -259,18 +251,22 @@ module Curtilage
259
251
  from.each do |p|
260
252
  to.each_index do |i|
261
253
  q = closest_point_on_segment(p, to[i], to[(i + 1) % to.size])
262
- candidates << (if flipped
263
- [Math.hypot(p[0] - q[0], p[1] - q[1]), q,
264
- p]
265
- else
266
- [Math.hypot(p[0] - q[0], p[1] - q[1]), p, q]
267
- end)
254
+ candidates << [distance(p, q), *(flipped ? [q, p] : [p, q])]
268
255
  end
269
256
  end
270
257
  end
271
258
  candidates.min_by(&:first)
272
259
  end
273
260
 
261
+ # Whether [lng, lat] is in a region given by its bbox and outline rings;
262
+ # nil rings (an older build with no outline) mean the bbox alone.
263
+ def in_rings?(point, bbox, rings)
264
+ lng, lat = point
265
+ return false unless lng.between?(bbox[0], bbox[2]) && lat.between?(bbox[1], bbox[3])
266
+
267
+ rings.nil? || rings.any? { |ring| contains?(ring, point) }
268
+ end
269
+
274
270
  # [min_x, min_y, max_x, max_y].
275
271
  def bounds(xy)
276
272
  xs = xy.map(&:first)
@@ -373,7 +369,7 @@ module Curtilage
373
369
  end
374
370
 
375
371
  def drop_repeats(xy, tolerance)
376
- near = ->(p, q) { Math.hypot(p[0] - q[0], p[1] - q[1]) < tolerance }
372
+ near = ->(p, q) { distance(p, q) < tolerance }
377
373
  pts = xy.each_with_object([]) { |p, out| out << p unless out.last && near.call(p, out.last) }
378
374
  pts.pop while pts.size > 1 && near.call(pts[0], pts[-1])
379
375
  pts
@@ -18,6 +18,8 @@ module Curtilage
18
18
  # the lot and its bounding roads.
19
19
  DEFAULT_RADIUS_DEG = 0.004
20
20
  MAX_OUTPUT_BYTES = 200_000_000
21
+ # A lookup only reads the row groups near its pins: this is headroom.
22
+ DEFAULT_MEMORY = "1GB"
21
23
  # Each pin is one scan in a UNION ALL, and DuckDB refuses queries nested
22
24
  # more than 1,000 deep: larger batches take several calls.
23
25
  PINS_PER_CALL = 500
@@ -46,10 +48,12 @@ module Curtilage
46
48
 
47
49
  def read_batch(files, pins, options)
48
50
  sql = sql(files, pins, options[:extension_directory], options.fetch(:radius_deg, DEFAULT_RADIUS_DEG),
49
- options[:setup_sql])
50
- out, err, status = DuckDB.capture(options.fetch(:duckdb, "duckdb"), sql, "-json")
51
+ options[:setup_sql], duckdb: options.fetch(:duckdb, "duckdb"),
52
+ memory_limit: options.fetch(:memory_limit, DEFAULT_MEMORY))
53
+ out, err, status = DuckDB.capture(options.fetch(:duckdb, "duckdb"), sql, "-json",
54
+ timeout: options.fetch(:timeout, Curtilage.config.duckdb_timeout),
55
+ max_output: MAX_OUTPUT_BYTES)
51
56
  raise Error, "duckdb failed: #{err.strip[0, 500]}" unless status.success?
52
- raise Error, "duckdb output too large" if out.bytesize > MAX_OUTPUT_BYTES
53
57
 
54
58
  group(out, pins.size)
55
59
  end
@@ -58,6 +62,7 @@ module Curtilage
58
62
  raise ArgumentError, "no parquet file given" if files.empty?
59
63
 
60
64
  files.each do |f|
65
+ Curtilage.online!("reading #{f}") if f.to_s.match?(REMOTE)
61
66
  next if f.to_s.match?(REMOTE)
62
67
  raise ArgumentError, "parquet file not found: #{f}" unless File.file?(f.to_s)
63
68
  end
@@ -78,41 +83,56 @@ module Curtilage
78
83
  lists
79
84
  end
80
85
 
81
- def sql(files, pins, extension_directory, radius_deg, setup_sql = nil)
86
+ def sql(files, pins, extension_directory, radius_deg, setup_sql = nil, duckdb: nil, memory_limit: DEFAULT_MEMORY)
82
87
  r = Float(radius_deg)
83
88
  raise ArgumentError, "radius out of range" unless r.positive? && r <= 0.05
84
89
 
85
- [setup(files, extension_directory, setup_sql), query(files, pins, r)].join("\n")
90
+ [setup(files, extension_directory, setup_sql, duckdb, memory_limit), query(files, pins, r)].join("\n")
86
91
  end
87
92
 
88
- def setup(files, extension_directory, setup_sql)
89
- [("SET extension_directory = #{quote(File.expand_path(extension_directory))};" if extension_directory),
90
- "INSTALL spatial; LOAD spatial;",
91
- ("INSTALL httpfs; LOAD httpfs;" if files.any? { |f| f.to_s.match?(REMOTE) }),
93
+ def setup(files, extension_directory, setup_sql, duckdb, memory_limit)
94
+ [(DuckDB.extension_sql(extension_directory, duckdb) if extension_directory),
95
+ DuckDB.memory_limit(memory_limit),
96
+ DuckDB.load_sql("spatial"),
97
+ (DuckDB.load_sql("httpfs") if files.any? { |f| f.to_s.match?(REMOTE) }),
92
98
  setup_sql].compact.join("\n")
93
99
  end
94
100
 
95
- # One scan per pin with constant bounds, so DuckDB can skip every row
96
- # group (and file) away from that pin; a join on a pins table can't.
101
+ # wkb::GEOMETRY: DuckDB 1.4 reads the column as a geometry already, 2.0
102
+ # as bytes, and only a cast suits both.
103
+ COLUMNS = "id, feature, highway, name, ST_AsGeoJSON(wkb::GEOMETRY)::VARCHAR AS geometry"
104
+
105
+ # Local files: one scan joined to a table of the pins' boxes, about ten
106
+ # times faster than a scan per pin (reading a local file whole is cheap).
107
+ # Remote files: one scan per pin with constant bounds, so DuckDB reads
108
+ # only the row groups (and files) near each pin, not whole files.
97
109
  def query(files, pins, radius)
98
110
  list = files.map { |f| quote(f) }.join(", ")
99
- scans = pins.each_with_index.map do |pin, i|
111
+ boxes = pins.map do |pin|
100
112
  lng, lat = checked(pin)
101
- "SELECT #{i} AS pin_index, id, feature, highway, name, ST_AsGeoJSON(wkb)::VARCHAR AS geometry " \
102
- "FROM read_parquet([#{list}]) WHERE max_lng >= #{lng - radius} AND min_lng <= #{lng + radius} " \
103
- "AND max_lat >= #{lat - radius} AND min_lat <= #{lat + radius}"
113
+ [lng - radius, lat - radius, lng + radius, lat + radius]
104
114
  end
105
- "#{scans.join(" UNION ALL ")};"
115
+ files.any? { |f| f.to_s.match?(REMOTE) } ? scan_per_pin(list, boxes) : joined(list, boxes)
106
116
  end
107
117
 
108
- def checked(pin)
109
- lng = Float(pin[0])
110
- lat = Float(pin[1])
111
- raise ArgumentError, "pin out of range: #{pin.inspect}" unless lng.abs <= 180 && lat.abs <= 90
118
+ def joined(list, boxes)
119
+ rows = boxes.each_with_index.map { |(x0, y0, x1, y1), i| "(#{i}, #{x0}, #{y0}, #{x1}, #{y1})" }
120
+ "CREATE TEMP TABLE boxes (pin_index INTEGER, x0 DOUBLE, y0 DOUBLE, x1 DOUBLE, y1 DOUBLE); " \
121
+ "INSERT INTO boxes VALUES #{rows.join(", ")};\n" \
122
+ "SELECT b.pin_index, #{COLUMNS} FROM read_parquet([#{list}]) f JOIN boxes b " \
123
+ "ON f.max_lng >= b.x0 AND f.min_lng <= b.x1 AND f.max_lat >= b.y0 AND f.min_lat <= b.y1;"
124
+ end
112
125
 
113
- [lng, lat]
126
+ def scan_per_pin(list, boxes)
127
+ scans = boxes.each_with_index.map do |(x0, y0, x1, y1), i|
128
+ "SELECT #{i} AS pin_index, #{COLUMNS} FROM read_parquet([#{list}]) " \
129
+ "WHERE max_lng >= #{x0} AND min_lng <= #{x1} AND max_lat >= #{y0} AND min_lat <= #{y1}"
130
+ end
131
+ "#{scans.join(" UNION ALL ")};"
114
132
  end
115
133
 
134
+ def checked(pin) = Validation.pin(pin)
135
+
116
136
  def quote(text) = DuckDB.quote(text)
117
137
  end
118
138
  end
@@ -32,6 +32,7 @@ module Curtilage
32
32
  # A list of feature lists, in pin order. options: duckdb:,
33
33
  # extension_directory:, radius_deg:, release: (default: the latest).
34
34
  def features_many(pins, **options)
35
+ Curtilage.online!("reading Overture Maps (use a catalogue or cached builds)")
35
36
  options = Curtilage.duckdb_options(options)
36
37
  radius = Float(options.fetch(:radius_deg, Lookup::DEFAULT_RADIUS_DEG))
37
38
  boxes = pins.map { |pin| box(pin, radius) }
@@ -46,20 +47,121 @@ module Curtilage
46
47
  end
47
48
  end
48
49
 
50
+ # Places matching one filter inside a box (west, south, east, north),
51
+ # from Overture's places theme: [{ id:, name:, brand:, category:,
52
+ # confidence:, sources:, licences:, pin: [lng, lat] }, ...], open or of
53
+ # unknown status, by id. category: matches any level of Overture's
54
+ # taxonomy (pharmacy, or health_care for all of it) or its basic
55
+ # category; brand: the brand's primary name, any case; ids: place ids.
56
+ # min_confidence: drop places Overture is less sure of (0 to 1).
57
+ # Each place keeps its own sources and licences (CDLA Permissive 2.0,
58
+ # CC0 or Apache 2.0, by source). The storage host learns the box.
59
+ def places(bbox:, category: nil, brand: nil, ids: nil, min_confidence: nil, max: Formats::MAX_PINS, **options)
60
+ Curtilage.online!("reading Overture Maps places")
61
+ options = Curtilage.duckdb_options(options)
62
+ bbox = checked_bbox(bbox)
63
+ where = place_filter(category, brand, ids)
64
+ if min_confidence
65
+ raise ArgumentError, "min_confidence is 0 to 1" unless min_confidence.is_a?(Numeric) && min_confidence.between?(
66
+ 0, 1
67
+ )
68
+
69
+ where += " AND confidence >= #{min_confidence.to_f}"
70
+ end
71
+ Dir.mktmpdir("curtilage-places") do |dir|
72
+ index = File.join(dir, "index.parquet")
73
+ File.binwrite(index, Download.read(STAC_HOST, "/#{release(options)}/collections.parquet",
74
+ max_bytes: MAX_INDEX_BYTES))
75
+ files = place_files(index, bbox, options)
76
+ rows = files.empty? ? [] : run(places_sql(files, bbox, where, max, options), options)
77
+ raise ArgumentError, "more than #{max} places match: narrow the box or the filter" if rows.size > max
78
+
79
+ rows.map { |r| place(r) }
80
+ end
81
+ end
82
+
83
+ PLACE_TEXT = /\A[^[:cntrl:]]{1,200}\z/
84
+ # A box bigger than this (about a large US state) is likely a mistake.
85
+ MAX_PLACES_BOX_DEG2 = 400
86
+
87
+ # [west, south, east, north] as finite floats in range, west < east.
88
+ def checked_bbox(bbox)
89
+ raise ArgumentError, "a box is [west, south, east, north]" unless bbox.is_a?(Array) && bbox.size == 4
90
+
91
+ w, s, e, n = bbox.map { |v| Validation.coordinate(v, bbox) }
92
+ raise ArgumentError, "box out of range or west/south not below east/north: #{bbox.inspect}" \
93
+ unless w.abs <= 180 && e.abs <= 180 && s.abs <= 90 && n.abs <= 90 && w < e && s < n
94
+ raise ArgumentError, "box over #{MAX_PLACES_BOX_DEG2} square degrees: narrow it" \
95
+ if (e - w) * (n - s) > MAX_PLACES_BOX_DEG2
96
+
97
+ [w, s, e, n]
98
+ end
99
+
100
+ def place_filter(category, brand, ids)
101
+ given = { category: category, brand: brand, ids: ids }.compact
102
+ raise ArgumentError, "give one of category:, brand: or ids:" unless given.size == 1
103
+
104
+ values = Array(given.values.first).map(&:to_s)
105
+ raise ArgumentError, "place filters are 1-200 characters, no control characters" \
106
+ unless values.any? && values.size <= 1_000 && values.all? { |v| v.match?(PLACE_TEXT) }
107
+
108
+ case given.keys.first
109
+ when :category
110
+ "(list_contains(taxonomy.hierarchy, #{quote(values[0])}) OR basic_category = #{quote(values[0])})"
111
+ when :brand then "lower(brand.names.\"primary\") = lower(#{quote(values[0])})"
112
+ else "id IN (#{values.map { |v| quote(v) }.join(", ")})"
113
+ end
114
+ end
115
+
116
+ def place_files(index, bbox, options)
117
+ sql = "SELECT assets.aws.alternate.s3.href AS href FROM read_parquet(#{quote(index)}) " \
118
+ "WHERE collection = 'place' AND #{box_filter("bbox", bbox)};"
119
+ hrefs = run([setup(options, remote: false), sql].join("\n"), options).map { |r| r["href"] }
120
+ hrefs.select { |h| h.to_s.start_with?("s3://overturemaps-") }
121
+ end
122
+
123
+ PLACE_COLUMNS = "id, names.\"primary\" AS name, brand.names.\"primary\" AS brand, " \
124
+ "taxonomy.\"primary\" AS category, confidence, " \
125
+ "list_distinct(list_transform(sources, lambda s: s.dataset)) AS sources, " \
126
+ "list_distinct(list_transform(sources, lambda s: s.license)) AS licences, " \
127
+ "ST_X(geometry) AS lng, ST_Y(geometry) AS lat"
128
+
129
+ def places_sql(files, bbox, where, max, options)
130
+ list = files.map { |f| quote(f) }.join(", ")
131
+ query = "SELECT #{PLACE_COLUMNS} FROM read_parquet([#{list}]) WHERE #{box_filter("bbox", bbox)} AND #{where} " \
132
+ "AND coalesce(operating_status, 'open') NOT IN ('permanently_closed', 'temporarily_closed') " \
133
+ "AND ST_GeometryType(geometry) = 'POINT' ORDER BY id LIMIT #{max + 1};"
134
+ [setup(options, remote: true), query].join("\n")
135
+ end
136
+
137
+ # A place from a result row; its text is map data, so cleaned and capped.
138
+ def place(row)
139
+ text = ->(v) { v && v.to_s.gsub(/[[:cntrl:]]/, "").strip[0, 200] }
140
+ list = ->(v) { Array(v).filter_map { |x| text.call(x) }.reject(&:empty?) }
141
+ { id: text.call(row["id"]), name: text.call(row["name"]), brand: text.call(row["brand"]),
142
+ category: text.call(row["category"]), confidence: row["confidence"]&.to_f&.round(2),
143
+ sources: list.call(row["sources"]), licences: list.call(row["licences"]),
144
+ pin: Validation.pin([row["lng"], row["lat"]]) }
145
+ end
146
+
147
+ RELEASE = /\A\d{4}-\d{2}-\d{2}(\.\d+)?\z/
148
+
49
149
  def release(options)
50
- return options[:release] if options[:release]
150
+ if options[:release]
151
+ raise ArgumentError, "an Overture release looks like 2026-11-18.0: #{options[:release].inspect}" \
152
+ unless options[:release].to_s.match?(RELEASE)
153
+
154
+ return options[:release].to_s
155
+ end
51
156
 
52
157
  latest = JSON.parse(Download.read(STAC_HOST, CATALOG, max_bytes: 1_000_000))["latest"].to_s
53
- raise Error, "no latest Overture release in the catalog" unless latest.match?(/\A[\d.-]+\z/)
158
+ raise Error, "no latest Overture release in the catalog" unless latest.match?(RELEASE)
54
159
 
55
160
  latest
56
161
  end
57
162
 
58
163
  def box(pin, radius)
59
- lng = Float(pin[0])
60
- lat = Float(pin[1])
61
- raise ArgumentError, "pin out of range: #{pin.inspect}" unless lng.abs <= 180 && lat.abs <= 90
62
-
164
+ lng, lat = Lookup.checked(pin)
63
165
  [lng - radius, lat - radius, lng + radius, lat + radius]
64
166
  end
65
167
 
@@ -110,8 +212,9 @@ module Curtilage
110
212
  envelope = [group.map { |b| b[0] }.min, group.map { |b| b[1] }.min, group.map { |b| b[2] }.max,
111
213
  group.map { |b| b[3] }.max]
112
214
  any = group.map { |b| "(#{box_filter("bbox", b)})" }.join(" OR ")
113
- "SELECT p.pin_index, d.id, d.feature, d.highway, d.name, d.geometry FROM (SELECT #{columns(collection)}, " \
114
- "bbox AS box FROM read_parquet([#{files.map { |f| quote(f) }.join(", ")}]) " \
215
+ "SELECT p.pin_index, d.id, d.feature, d.highway, d.name, d.source, d.geometry " \
216
+ "FROM (SELECT #{columns(collection)}, bbox AS box " \
217
+ "FROM read_parquet([#{files.map { |f| quote(f) }.join(", ")}]) " \
115
218
  "WHERE #{box_filter("bbox", envelope)} AND (#{any}) AND #{filter(collection)}) d " \
116
219
  "JOIN boxes p ON p.pin_index IN (#{indexes.join(", ")}) AND d.box.xmin <= p.x1 AND d.box.xmax >= p.x0 " \
117
220
  "AND d.box.ymin <= p.y1 AND d.box.ymax >= p.y0"
@@ -128,14 +231,16 @@ module Curtilage
128
231
  case collection
129
232
  when "building"
130
233
  "id, CASE WHEN sources[1].dataset = 'OpenStreetMap' THEN 'building' ELSE 'ml_building' END AS feature, " \
131
- "class AS highway, names.\"primary\" AS name, ST_AsGeoJSON(geometry)::VARCHAR AS geometry"
234
+ "class AS highway, names.\"primary\" AS name, sources[1].dataset AS source, " \
235
+ "ST_AsGeoJSON(geometry)::VARCHAR AS geometry"
132
236
  when "segment"
133
237
  rail = RAIL_CLASSES.map { |k, v| "WHEN #{quote(k)} THEN #{quote(v)}" }.join(" ")
134
238
  "id, CASE subtype WHEN 'road' THEN 'road' ELSE 'railway' END AS feature, " \
135
239
  "CASE WHEN subtype = 'rail' THEN (CASE class #{rail} END) WHEN subclass = 'link' THEN class || '_link' " \
136
- "ELSE class END AS highway, names.\"primary\" AS name, ST_AsGeoJSON(geometry)::VARCHAR AS geometry"
240
+ "ELSE class END AS highway, names.\"primary\" AS name, NULL AS source, " \
241
+ "ST_AsGeoJSON(geometry)::VARCHAR AS geometry"
137
242
  else
138
- "id, 'parking' AS feature, NULL AS highway, names.\"primary\" AS name, " \
243
+ "id, 'parking' AS feature, NULL AS highway, names.\"primary\" AS name, NULL AS source, " \
139
244
  "ST_AsGeoJSON(geometry)::VARCHAR AS geometry"
140
245
  end
141
246
  end
@@ -149,7 +254,7 @@ module Curtilage
149
254
  "((subtype = 'road' AND class IN (#{ROAD_CLASSES.map { |c| quote(c) }.join(", ")})) " \
150
255
  "OR (subtype = 'rail' AND class IN (#{RAIL_CLASSES.keys.map { |c| quote(c) }.join(", ")}))) " \
151
256
  "AND NOT list_has_any(flatten(list_transform(coalesce(road_flags, []) || coalesce(rail_flags, []), " \
152
- "f -> f.\"values\")), ['is_tunnel', 'is_bridge'])"
257
+ "lambda f: f.\"values\")), ['is_tunnel', 'is_bridge'])"
153
258
  else
154
259
  "subtype = 'transit' AND class = 'parking' AND ST_GeometryType(geometry) IN ('POLYGON', 'MULTIPOLYGON')"
155
260
  end
@@ -157,28 +262,43 @@ module Curtilage
157
262
 
158
263
  def setup(options, remote:)
159
264
  ext = options[:extension_directory]
160
- [("SET extension_directory = #{quote(File.expand_path(ext))};" if ext), "INSTALL spatial; LOAD spatial;",
265
+ [(DuckDB.extension_sql(ext, options.fetch(:duckdb, "duckdb")) if ext),
266
+ DuckDB.memory_limit(options.fetch(:memory_limit, Lookup::DEFAULT_MEMORY)), DuckDB.load_sql("spatial"),
161
267
  # Pins in the same files share one read of each file's metadata.
162
268
  (if remote
163
- "INSTALL httpfs; LOAD httpfs; SET s3_region = 'us-west-2'; SET parquet_metadata_cache = true; " \
164
- "SET enable_http_metadata_cache = true;"
269
+ # A region-only secret (no keys, so reads stay anonymous): DuckDB 2.0
270
+ # deprecates SET s3_region and warns about it inside -json output.
271
+ # CREATE SECRET prints a result row of its own, so it goes nowhere.
272
+ "#{DuckDB.load_sql("httpfs")}\n.output #{File::NULL}\nCREATE TEMPORARY SECRET overture (TYPE s3, " \
273
+ "REGION 'us-west-2', SCOPE 's3://overturemaps-us-west-2');\n.output\n" \
274
+ "SET parquet_metadata_cache = true; SET enable_http_metadata_cache = true;"
165
275
  end)].compact.join("\n")
166
276
  end
167
277
 
168
278
  # Remote reads occasionally stall and DuckDB exits without a message;
169
279
  # one retry gets past that.
170
280
  def run(sql, options, attempts: 2)
171
- out, err, status = DuckDB.capture(options.fetch(:duckdb, "duckdb"), sql, "-json")
281
+ out, err, status = DuckDB.capture(options.fetch(:duckdb, "duckdb"), sql, "-json",
282
+ timeout: options.fetch(:timeout, Curtilage.config.duckdb_timeout),
283
+ max_output: MAX_OUTPUT_BYTES)
172
284
  unless status.success?
173
285
  return run(sql, options, attempts: attempts - 1) if err.strip.empty? && attempts > 1
174
286
 
175
287
  raise Error, "duckdb failed: #{err.strip.empty? ? "no message (network?)" : err.strip[0, 500]}"
176
288
  end
177
- raise Error, "duckdb output too large" if out.bytesize > MAX_OUTPUT_BYTES
178
289
 
179
290
  out.strip.empty? ? [] : JSON.parse(out)
180
291
  end
181
292
 
293
+ # OSM and Overture, plus a line for each other source whose buildings
294
+ # the result could use (buildings: :osm_filled or :ml). The source names
295
+ # come from the data, so they're cleaned and capped like any map text.
296
+ def attribution(features)
297
+ used = features ? features.buildings.select { |b| b.kind == "ml_building" } : []
298
+ sources = used.filter_map { |b| b.source.to_s.gsub(/[[:cntrl:]]/, "").strip[0, 80] }.reject(&:empty?)
299
+ ATTRIBUTION + sources.uniq.sort.map { |s| "Building footprints: #{s} (via Overture Maps)" }
300
+ end
301
+
182
302
  def quote(text) = DuckDB.quote(text)
183
303
  end
184
304
  end