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/auto_data.rb
CHANGED
|
@@ -26,9 +26,38 @@ module Curtilage
|
|
|
26
26
|
|
|
27
27
|
def initialize(**options)
|
|
28
28
|
@opts = OPTIONS.merge(options.compact)
|
|
29
|
+
check_options
|
|
29
30
|
@temporary = @opts[:cache_dir].nil?
|
|
30
31
|
@cache_dir = @opts[:cache_dir] || Dir.mktmpdir("curtilage")
|
|
31
|
-
FileUtils.mkdir_p(@cache_dir)
|
|
32
|
+
FileUtils.mkdir_p(@cache_dir, mode: 0o700)
|
|
33
|
+
problem = AutoData.cache_problem(File.stat(@cache_dir), @cache_dir)
|
|
34
|
+
raise Error, problem if problem
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# Each build peaks near 600 MB; more than 8 at once would swamp most
|
|
38
|
+
# machines and Geofabrik.
|
|
39
|
+
MAX_PARALLEL_BUILDS = 8
|
|
40
|
+
|
|
41
|
+
def check_options
|
|
42
|
+
builds = @opts[:parallel_builds]
|
|
43
|
+
unless builds.is_a?(Integer) && builds.between?(1, MAX_PARALLEL_BUILDS)
|
|
44
|
+
raise ArgumentError, "parallel_builds must be a whole number from 1 to #{MAX_PARALLEL_BUILDS}: " \
|
|
45
|
+
"#{builds.inspect}"
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
age = @opts[:max_age_days]
|
|
49
|
+
raise ArgumentError, "max_age_days must be a number of days from 0 to 3650: #{age.inspect}" \
|
|
50
|
+
unless age.is_a?(Numeric) && age.to_f.finite? && age.between?(0, 3650)
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# DuckDB reads the cache's Parquet files and the gem trusts its
|
|
54
|
+
# metadata, so a cache someone else can write to is refused.
|
|
55
|
+
def self.cache_problem(stat, dir)
|
|
56
|
+
if stat.uid != Process.uid
|
|
57
|
+
"the cache folder #{dir} belongs to another user: use a folder you own"
|
|
58
|
+
elsif stat.mode.anybits?(0o002)
|
|
59
|
+
"the cache folder #{dir} is writable by every user: run `chmod 700 #{dir}` or use another folder"
|
|
60
|
+
end
|
|
32
61
|
end
|
|
33
62
|
|
|
34
63
|
# A Catalogue covering the pins, building what's missing first. Pins in
|
|
@@ -43,14 +72,18 @@ module Curtilage
|
|
|
43
72
|
needed.each { |region| queue << region }
|
|
44
73
|
# Closed, so pop returns nil once it's empty instead of waiting.
|
|
45
74
|
queue.close
|
|
46
|
-
workers = Array.new(@opts[:parallel_builds].
|
|
75
|
+
workers = Array.new(@opts[:parallel_builds].clamp(1, [needed.size, 1].max)) do
|
|
47
76
|
Thread.new do
|
|
77
|
+
Thread.current.report_on_exception = false
|
|
48
78
|
while (region = queue.pop)
|
|
49
79
|
ensure_built(region)
|
|
50
80
|
end
|
|
81
|
+
rescue StandardError
|
|
82
|
+
queue.clear # the others finish their build but start no new one
|
|
83
|
+
raise
|
|
51
84
|
end
|
|
52
85
|
end
|
|
53
|
-
|
|
86
|
+
Curtilage.join_all(workers) # cleanup may delete the folder they build in
|
|
54
87
|
Catalogue.from_dir(@cache_dir)
|
|
55
88
|
end
|
|
56
89
|
|
|
@@ -73,7 +106,7 @@ module Curtilage
|
|
|
73
106
|
|
|
74
107
|
def ensure_built(region)
|
|
75
108
|
with_lock(name(region)) do
|
|
76
|
-
next if
|
|
109
|
+
next if fresh_region?(region.path)
|
|
77
110
|
|
|
78
111
|
@opts[:log].puts "building #{region.path} into #{@cache_dir}"
|
|
79
112
|
build(region)
|
|
@@ -88,12 +121,18 @@ module Curtilage
|
|
|
88
121
|
**@opts.slice(:ml_footprints, :duckdb, :extension_directory, :log))
|
|
89
122
|
end
|
|
90
123
|
|
|
124
|
+
# Built recently enough, with its Parquet file present at the size the
|
|
125
|
+
# metadata recorded: a missing, truncated or replaced file is rebuilt.
|
|
126
|
+
# (doctor --verify checks the full SHA256.)
|
|
91
127
|
def fresh?(metadata_file)
|
|
92
128
|
return false unless File.file?(metadata_file)
|
|
93
129
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
130
|
+
meta = JSON.parse(File.read(metadata_file, encoding: "utf-8"))
|
|
131
|
+
parquet = File.join(@cache_dir, File.basename(meta["parquet"].to_s))
|
|
132
|
+
built = Time.parse(meta["built_at"].to_s)
|
|
133
|
+
Time.now - built < @opts[:max_age_days] * 86_400 && File.file?(parquet) &&
|
|
134
|
+
File.size(parquet) == meta["parquet_bytes"]
|
|
135
|
+
rescue ArgumentError, TypeError, JSON::ParserError
|
|
97
136
|
false
|
|
98
137
|
end
|
|
99
138
|
|
|
@@ -105,12 +144,23 @@ module Curtilage
|
|
|
105
144
|
end
|
|
106
145
|
end
|
|
107
146
|
|
|
147
|
+
# Geofabrik's index, cached for max_age_days. A cached copy that can't
|
|
148
|
+
# be read (cut short, say) is fetched again rather than trusted.
|
|
108
149
|
def load_regions
|
|
109
150
|
file = File.join(@cache_dir, INDEX_FILE)
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
151
|
+
cached = File.file?(file) && Time.now - File.mtime(file) < @opts[:max_age_days] * 86_400 && read_index(file)
|
|
152
|
+
return cached if cached
|
|
153
|
+
|
|
154
|
+
json = Download.read(Regions::HOST, Regions::INDEX, max_bytes: Regions::MAX_INDEX_BYTES)
|
|
155
|
+
regions = Regions.parse(json)
|
|
156
|
+
Curtilage.write_atomically(file, json)
|
|
157
|
+
regions
|
|
158
|
+
end
|
|
159
|
+
|
|
160
|
+
def read_index(file)
|
|
161
|
+
Regions.parse(File.read(file, encoding: "utf-8"))
|
|
162
|
+
rescue Error
|
|
163
|
+
nil
|
|
114
164
|
end
|
|
115
165
|
end
|
|
116
166
|
end
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module Curtilage
|
|
6
|
+
# Writing a big run as it goes (the command line's generate): NDJSON and
|
|
7
|
+
# CSV are streamed chunk by chunk, so memory stays flat, into OUT.part
|
|
8
|
+
# (renamed to OUT at the end, so readers never see half a file), which
|
|
9
|
+
# --resume picks up after a crash or Ctrl-C. GeoJSON and KML are single
|
|
10
|
+
# documents, so they're written whole at the end.
|
|
11
|
+
class Batch
|
|
12
|
+
CHUNK = 500
|
|
13
|
+
STREAMED = %i[ndjson csv].freeze
|
|
14
|
+
|
|
15
|
+
attr_reader :done
|
|
16
|
+
|
|
17
|
+
# out: a path, or nil for io. resume: carry on from OUT.part.
|
|
18
|
+
def initialize(format:, out: nil, store: true, resume: false, output: $stdout)
|
|
19
|
+
@format = format.to_sym
|
|
20
|
+
@out = out
|
|
21
|
+
@store = store
|
|
22
|
+
@io = output
|
|
23
|
+
@done = Set.new
|
|
24
|
+
@buffer = [[], []]
|
|
25
|
+
raise ArgumentError, "--resume needs --out FILE.ndjson or FILE.csv" if resume && !(out && streamed?)
|
|
26
|
+
|
|
27
|
+
if out && streamed?
|
|
28
|
+
open_part(resume)
|
|
29
|
+
elsif streamed? && @format == :csv
|
|
30
|
+
@io.write(Formats.csv_text([Formats::CSV_COLUMNS]))
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def streamed? = STREAMED.include?(@format)
|
|
35
|
+
|
|
36
|
+
# The .part file next to out; its fixed name is what lets a later run
|
|
37
|
+
# resume it.
|
|
38
|
+
def part = File.join(File.dirname(File.expand_path(@out)), ".#{File.basename(@out)}.part")
|
|
39
|
+
|
|
40
|
+
def add(results, ids)
|
|
41
|
+
return @buffer.zip([results, ids]).each { |list, more| list.concat(more) } unless streamed?
|
|
42
|
+
|
|
43
|
+
text = Formats.write(results, @format, ids: ids, store: @store)
|
|
44
|
+
text = text.lines.drop(1).join if @format == :csv
|
|
45
|
+
(@file || @io).write(text)
|
|
46
|
+
(@file || @io).flush
|
|
47
|
+
@done.merge(ids)
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def finish
|
|
51
|
+
if @file
|
|
52
|
+
@file.close
|
|
53
|
+
File.rename(part, @out)
|
|
54
|
+
elsif !streamed?
|
|
55
|
+
text = Formats.write(@buffer[0], @format, ids: @buffer[1], store: @store)
|
|
56
|
+
return yield(text) if @out
|
|
57
|
+
|
|
58
|
+
@io.write(text.end_with?("\n") ? text : "#{text}\n")
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
private
|
|
63
|
+
|
|
64
|
+
def open_part(resume)
|
|
65
|
+
if resume && File.file?(part)
|
|
66
|
+
keep_whole_lines
|
|
67
|
+
@done = Set.new(written_ids)
|
|
68
|
+
@file = File.open(part, "a")
|
|
69
|
+
else
|
|
70
|
+
@file = File.open(part, "w")
|
|
71
|
+
@file.write(Formats.csv_text([Formats::CSV_COLUMNS])) if @format == :csv
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# A crash can cut the last line short: drop it, so its site runs again.
|
|
76
|
+
def keep_whole_lines
|
|
77
|
+
text = File.binread(part)
|
|
78
|
+
return if text.empty? || text.end_with?("\n")
|
|
79
|
+
|
|
80
|
+
File.truncate(part, (text.rindex("\n") || -1) + 1)
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def written_ids
|
|
84
|
+
text = File.read(part, encoding: "utf-8")
|
|
85
|
+
if @format == :csv
|
|
86
|
+
Formats.parse_csv(text, max_rows: Float::INFINITY).drop(1).map(&:first)
|
|
87
|
+
else
|
|
88
|
+
text.each_line.map { |l| JSON.parse(l).dig("properties", "id").to_s }
|
|
89
|
+
end
|
|
90
|
+
rescue JSON::ParserError, ArgumentError => e
|
|
91
|
+
raise ArgumentError, "can't resume from #{part}: #{e.message[0, 200]}"
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# Sites done per second and the time left, on a terminal.
|
|
95
|
+
class Progress
|
|
96
|
+
def initialize(total, output: $stderr, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
|
|
97
|
+
@total = total
|
|
98
|
+
@io = output
|
|
99
|
+
@clock = clock
|
|
100
|
+
@start = clock.call
|
|
101
|
+
@done = 0
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
def step(count)
|
|
105
|
+
@done += count
|
|
106
|
+
elapsed = @clock.call - @start
|
|
107
|
+
rate = elapsed.positive? ? @done.to_f / elapsed : 0
|
|
108
|
+
left = rate.positive? ? ((@total - @done) / rate).round : 0
|
|
109
|
+
@io.print "\r#{@done}/#{@total} sites (#{@done * 100 / [@total, 1].max}%), " \
|
|
110
|
+
"#{rate.round(1)}/s, about #{format("%<m>d:%<s>02d", m: left / 60, s: left % 60)} left "
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def finish = @io.puts
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
end
|
data/lib/curtilage/build.rb
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require "date"
|
|
4
|
+
require "digest"
|
|
4
5
|
require "fileutils"
|
|
5
6
|
require "json"
|
|
6
|
-
require "open3"
|
|
7
7
|
require "time"
|
|
8
8
|
|
|
9
9
|
module Curtilage
|
|
10
10
|
# Builds a region's features Parquet from Geofabrik's free shapefiles:
|
|
11
11
|
# find the newest dated extract, download only the layers used (range
|
|
12
|
-
# requests, CRC-checked; the whole zip
|
|
13
|
-
# do ranges), and run sql/build_from_shapefiles.sql with the DuckDB CLI.
|
|
12
|
+
# requests, CRC-checked; the whole zip, read the same way, only if the
|
|
13
|
+
# server can't do ranges), and run sql/build_from_shapefiles.sql with the DuckDB CLI.
|
|
14
14
|
# Optionally adds machine-learned building footprints (see Footprints).
|
|
15
15
|
#
|
|
16
16
|
# Network access is limited to Geofabrik (and the footprint host when asked
|
|
@@ -26,13 +26,14 @@ module Curtilage
|
|
|
26
26
|
"#{US}/california" => %W[#{US}/california/norcal #{US}/california/socal],
|
|
27
27
|
}.freeze
|
|
28
28
|
LAYERS = %w[buildings_a traffic_a roads railways].freeze
|
|
29
|
+
LAYER_PATTERNS = LAYERS.map { |layer| "gis_osm_#{layer}_free_*" }.freeze
|
|
29
30
|
REGION = %r{\A[a-z]+(-[a-z]+)*(/[a-z]+(-[a-z]+)*)*\z}
|
|
30
31
|
MAX_DOWNLOAD_BYTES = 5_000_000_000
|
|
31
32
|
LOOKBACK_DAYS = 8
|
|
32
33
|
SQL_FILE = File.expand_path("../../sql/build_from_shapefiles.sql", __dir__)
|
|
33
34
|
|
|
34
35
|
OPTIONS = {
|
|
35
|
-
date: nil, memory_limit: "400MB", threads: 1,
|
|
36
|
+
date: nil, memory_limit: "400MB", threads: 1, timeout: 3600,
|
|
36
37
|
ml_footprints: nil, keep_downloads: false, name: nil, outline: nil, log: $stderr
|
|
37
38
|
}.freeze
|
|
38
39
|
|
|
@@ -49,21 +50,33 @@ module Curtilage
|
|
|
49
50
|
def run(region, out_dir:, work_dir:, **options)
|
|
50
51
|
opts = OPTIONS.merge(Curtilage.duckdb_options(options))
|
|
51
52
|
path = region_path(region)
|
|
52
|
-
|
|
53
|
+
check_options(opts)
|
|
53
54
|
FileUtils.mkdir_p([out_dir, work_dir])
|
|
54
|
-
fetched = PARTS.fetch(path, [path]).map { |part| fetch(part, opts[:date], work_dir, opts[:log]) }
|
|
55
|
-
dirs = fetched.map
|
|
55
|
+
fetched = PARTS.fetch(path, [path]).map { |part| [part, *fetch(part, opts[:date], work_dir, opts[:log])] }
|
|
56
|
+
dirs = fetched.map { |_, dir, _| dir }
|
|
56
57
|
opts = opts.merge(temp_directory: File.join(work_dir, "duckdb_tmp"))
|
|
57
|
-
ml = ml_files(dirs, work_dir, opts)
|
|
58
|
+
ml, ml_bbox = ml_files(dirs, work_dir, opts)
|
|
58
59
|
out = File.join(out_dir, "#{output_name(path, opts[:name])}.parquet")
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
finish(out, path, fetched.map(&:last), opts)
|
|
60
|
+
build_parquet(sql(dirs, "#{out}.tmp", opts, ml_files: ml, ml_bbox: ml_bbox), out, opts)
|
|
61
|
+
write_metadata(out, path, fetched.map(&:last), opts.merge(provenance(fetched, ml)))
|
|
62
|
+
out
|
|
63
63
|
ensure
|
|
64
64
|
cleanup(work_dir, dirs, opts[:keep_downloads]) if dirs
|
|
65
65
|
end
|
|
66
66
|
|
|
67
|
+
# What was downloaded, for the metadata: each part's layer files and
|
|
68
|
+
# each footprint tile, with sizes and SHA256s.
|
|
69
|
+
def provenance(fetched, ml_files)
|
|
70
|
+
{ sources: fetched.map { |part, dir, date| source_record(part, date, dir) },
|
|
71
|
+
ml_sources: ml_files.map { |f| record(f) } }
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def build_parquet(sql, out, opts)
|
|
75
|
+
opts[:log].puts "building #{out}"
|
|
76
|
+
run_duckdb(sql, opts[:duckdb], timeout: opts[:timeout])
|
|
77
|
+
File.rename("#{out}.tmp", out)
|
|
78
|
+
end
|
|
79
|
+
|
|
67
80
|
def output_name(path, name)
|
|
68
81
|
name ||= File.basename(path)
|
|
69
82
|
raise ArgumentError, "bad output name #{name.inspect}" unless name.match?(/\A[a-z0-9-]+\z/)
|
|
@@ -78,7 +91,12 @@ module Curtilage
|
|
|
78
91
|
region.include?("/") ? region : "#{US}/#{region}"
|
|
79
92
|
end
|
|
80
93
|
|
|
81
|
-
|
|
94
|
+
# date: goes into a file name and a URL, so only YYMMDD will do.
|
|
95
|
+
def check_options(opts)
|
|
96
|
+
date = opts[:date]
|
|
97
|
+
raise ArgumentError, "date is YYMMDD: #{date.inspect}" unless date.nil? || date.to_s.match?(/\A\d{6}\z/)
|
|
98
|
+
|
|
99
|
+
source = opts[:ml_footprints]
|
|
82
100
|
return if source.nil? || Footprints::SOURCES.include?(source.to_s)
|
|
83
101
|
|
|
84
102
|
raise ArgumentError, "unknown ml_footprints source #{source.inspect} (have: #{Footprints::SOURCES.join(", ")})"
|
|
@@ -101,15 +119,13 @@ module Curtilage
|
|
|
101
119
|
log.puts "downloading https://#{HOST}#{url_path(part, date)}"
|
|
102
120
|
Download.fetch(HOST, url_path(part, date), zip, max_bytes: MAX_DOWNLOAD_BYTES)
|
|
103
121
|
end
|
|
104
|
-
|
|
105
|
-
unzip_layers(zip, dir)
|
|
122
|
+
extract_zip(zip, dir)
|
|
106
123
|
[dir, date]
|
|
107
124
|
end
|
|
108
125
|
|
|
109
126
|
def fetch_layers(part, date, dir, log)
|
|
110
127
|
log.puts "downloading the layers used from https://#{HOST}#{url_path(part, date)}"
|
|
111
|
-
|
|
112
|
-
ZipRange.extract(HOST, url_path(part, date), patterns, dir, max_bytes: MAX_DOWNLOAD_BYTES)
|
|
128
|
+
ZipRange.extract(HOST, url_path(part, date), LAYER_PATTERNS, dir, max_bytes: MAX_DOWNLOAD_BYTES)
|
|
113
129
|
true
|
|
114
130
|
rescue ZipRange::Unsupported => e
|
|
115
131
|
log.puts "range download not possible (#{e.message}); downloading the whole file"
|
|
@@ -129,45 +145,34 @@ module Curtilage
|
|
|
129
145
|
"(large regions are only offered as sub-regions)"
|
|
130
146
|
end
|
|
131
147
|
|
|
132
|
-
#
|
|
133
|
-
#
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
148
|
+
# The layers from a zip downloaded whole, read by the gem itself (no
|
|
149
|
+
# unzip): names, sizes and each member's CRC are checked, which catches
|
|
150
|
+
# a truncated or corrupt download. A bad zip is deleted.
|
|
151
|
+
def extract_zip(zip, dir)
|
|
152
|
+
ZipRange.extract_local(zip, LAYER_PATTERNS, dir, max_bytes: MAX_DOWNLOAD_BYTES)
|
|
153
|
+
rescue ZipRange::Corrupt, ZipRange::Unsupported => e
|
|
138
154
|
File.delete(zip)
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
def unzip(*)
|
|
143
|
-
Open3.capture3("unzip", *)
|
|
144
|
-
rescue Errno::ENOENT
|
|
145
|
-
raise Error, "unzip not found: it's needed when a server can't serve byte ranges"
|
|
146
|
-
end
|
|
147
|
-
|
|
148
|
-
def unzip_layers(zip, dir)
|
|
149
|
-
FileUtils.mkdir_p(dir)
|
|
150
|
-
patterns = LAYERS.map { |layer| "gis_osm_#{layer}_free_*" }
|
|
151
|
-
_, err, status = unzip("-oq", zip, *patterns, "-d", dir)
|
|
152
|
-
raise Error, "unzip failed: #{err.strip[0, 200]}" unless status.success?
|
|
155
|
+
FileUtils.rm_rf(dir)
|
|
156
|
+
raise Error, "corrupt download #{File.basename(zip)} (deleted): #{e.message}"
|
|
153
157
|
end
|
|
154
158
|
|
|
155
|
-
#
|
|
159
|
+
# [footprint tiles covering the region's extent, that extent], or [[],
|
|
160
|
+
# nil] when not asked for.
|
|
156
161
|
def ml_files(dirs, work_dir, opts)
|
|
157
|
-
return [] unless opts[:ml_footprints]
|
|
162
|
+
return [[], nil] unless opts[:ml_footprints]
|
|
158
163
|
|
|
159
164
|
bbox = extent(dirs, opts)
|
|
160
|
-
Footprints.microsoft(bbox, File.join(work_dir, "ml_footprints"), log: opts[:log])
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
165
|
+
files = Footprints.microsoft(bbox, File.join(work_dir, "ml_footprints"), log: opts[:log])
|
|
166
|
+
raise Error, "no ML footprint tiles cover #{bbox.inspect}" if files.empty?
|
|
167
|
+
|
|
168
|
+
[files, bbox]
|
|
164
169
|
end
|
|
165
170
|
|
|
166
171
|
# [min_lng, min_lat, max_lng, max_lat] of the region's roads.
|
|
167
172
|
def extent(dirs, opts)
|
|
168
173
|
query = "SELECT min(ST_XMin(geom)) a, min(ST_YMin(geom)) b, max(ST_XMax(geom)) c, max(ST_YMax(geom)) d " \
|
|
169
174
|
"FROM roads_src;"
|
|
170
|
-
out = run_duckdb([setup(opts), "
|
|
175
|
+
out = run_duckdb([setup(opts), DuckDB.load_sql("spatial"), layer_view("roads", dirs), query].join("\n"),
|
|
171
176
|
opts[:duckdb], "-json")
|
|
172
177
|
row = JSON.parse(out).first
|
|
173
178
|
%w[a b c d].map { |k| Float(row[k]) }
|
|
@@ -175,9 +180,9 @@ module Curtilage
|
|
|
175
180
|
|
|
176
181
|
# The build query reads one view per layer; large layers come in parts
|
|
177
182
|
# (_1, _2, ...) and multi-part regions in several folders.
|
|
178
|
-
def sql(dirs, out, opts, ml_files: [])
|
|
183
|
+
def sql(dirs, out, opts, ml_files: [], ml_bbox: nil)
|
|
179
184
|
views = LAYERS.map { |layer| layer_view(layer, dirs) }
|
|
180
|
-
[setup(opts), "
|
|
185
|
+
[setup(opts), DuckDB.load_sql("spatial"), *views, ml_view(ml_files, ml_bbox),
|
|
181
186
|
"SET VARIABLE out_path = #{quote(out)};", File.read(SQL_FILE)].join("\n")
|
|
182
187
|
end
|
|
183
188
|
|
|
@@ -204,23 +209,23 @@ module Curtilage
|
|
|
204
209
|
|
|
205
210
|
def setup(opts)
|
|
206
211
|
ext = opts[:extension_directory]
|
|
207
|
-
[(
|
|
208
|
-
|
|
209
|
-
"SET threads = #{
|
|
212
|
+
[(DuckDB.extension_sql(ext, opts[:duckdb]) if ext),
|
|
213
|
+
DuckDB.memory_limit(opts[:memory_limit]),
|
|
214
|
+
"SET threads = #{threads(opts[:threads])};",
|
|
210
215
|
("SET temp_directory = #{quote(opts[:temp_directory])};" if opts[:temp_directory])].compact.join("\n")
|
|
211
216
|
end
|
|
212
217
|
|
|
213
|
-
def
|
|
214
|
-
|
|
215
|
-
raise
|
|
218
|
+
def threads(value)
|
|
219
|
+
count = Integer(value, exception: false)
|
|
220
|
+
raise ArgumentError, "threads must be a whole number from 1 to 64: #{value.inspect}" unless count&.between?(1, 64)
|
|
216
221
|
|
|
217
|
-
|
|
222
|
+
count
|
|
218
223
|
end
|
|
219
224
|
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
225
|
+
def run_duckdb(sql, duckdb, *, timeout: OPTIONS[:timeout])
|
|
226
|
+
out, err, status = DuckDB.capture(duckdb, sql, *, timeout: timeout)
|
|
227
|
+
raise Error, "duckdb failed: #{err.strip[0, 500]}" unless status.success? && err.strip.empty?
|
|
228
|
+
|
|
224
229
|
out
|
|
225
230
|
end
|
|
226
231
|
|
|
@@ -235,12 +240,25 @@ module Curtilage
|
|
|
235
240
|
nil
|
|
236
241
|
end
|
|
237
242
|
|
|
243
|
+
# Writes <region>.json next to the Parquet file: what it holds, where it
|
|
244
|
+
# came from and how to attribute it. Catalogue reads these. The outline
|
|
245
|
+
# comes from Geofabrik's index only when the caller didn't pass one
|
|
246
|
+
# (AutoData does, so the index isn't downloaded twice).
|
|
238
247
|
def write_metadata(parquet, path, dates, opts)
|
|
239
248
|
stats = run_duckdb([setup(opts), "SELECT feature, count(*) AS n, min(min_lng) a, min(min_lat) b, " \
|
|
240
249
|
"max(max_lng) c, max(max_lat) d FROM read_parquet(#{quote(parquet)}) " \
|
|
241
250
|
"GROUP BY feature;"].join("\n"), opts[:duckdb], "-json")
|
|
242
251
|
rows = JSON.parse(stats)
|
|
243
|
-
|
|
252
|
+
loaded = "#{setup(opts)}\n#{DuckDB.load_sql("spatial")}"
|
|
253
|
+
opts = opts.merge(outline: opts[:outline] || outline(path, opts[:log]),
|
|
254
|
+
duckdb_version: DuckDB.version(opts[:duckdb]),
|
|
255
|
+
extensions: DuckDB.extension_versions(opts[:duckdb], loaded, %w[spatial]))
|
|
256
|
+
file = parquet.sub(/\.parquet\z/, ".json")
|
|
257
|
+
upstream_changes(previous_metadata(file), opts[:sources]).each do |name|
|
|
258
|
+
opts[:log].puts "warning: #{name} differs from the copy the last build of this region used " \
|
|
259
|
+
"(republished upstream, or altered in transit): check before trusting either build"
|
|
260
|
+
end
|
|
261
|
+
Curtilage.write_atomically(file, JSON.pretty_generate(metadata(parquet, path, dates, rows, opts)))
|
|
244
262
|
end
|
|
245
263
|
|
|
246
264
|
def metadata(parquet, path, dates, rows, opts)
|
|
@@ -249,12 +267,47 @@ module Curtilage
|
|
|
249
267
|
region: path, parquet: File.basename(parquet), format: 1,
|
|
250
268
|
source: "Geofabrik OpenStreetMap shapefiles", source_dates: source_dates,
|
|
251
269
|
built_at: Time.now.utc.iso8601, ml_footprints: opts[:ml_footprints],
|
|
252
|
-
bbox:
|
|
253
|
-
rows.map { |r| r["d"] }.max],
|
|
270
|
+
bbox: bbox_of(rows),
|
|
254
271
|
counts: rows.to_h { |r| [r["feature"], r["n"]] },
|
|
255
272
|
licence: "ODbL-1.0", attribution: attribution(opts[:ml_footprints]),
|
|
256
|
-
outline: rounded(opts[:outline])
|
|
257
|
-
|
|
273
|
+
outline: rounded(opts[:outline]), sources: opts[:sources], ml_sources: opts[:ml_sources],
|
|
274
|
+
parquet_bytes: File.size?(parquet), parquet_sha256: sha256(parquet), gem_version: VERSION,
|
|
275
|
+
duckdb_version: opts[:duckdb_version], extensions: opts[:extensions]
|
|
276
|
+
}.compact
|
|
277
|
+
end
|
|
278
|
+
|
|
279
|
+
# What was downloaded for one part: its dated zip's name and each layer
|
|
280
|
+
# file taken from it, with size and SHA256. Geofabrik publishes no
|
|
281
|
+
# checksums, so this is what a later build compares against.
|
|
282
|
+
def source_record(part, date, dir)
|
|
283
|
+
files = LAYER_PATTERNS.flat_map { |pattern| Dir.glob(File.join(dir, pattern)) }.sort
|
|
284
|
+
{ "file" => File.basename(url_path(part, date)), "members" => files.to_h { |f| [File.basename(f), record(f)] } }
|
|
285
|
+
end
|
|
286
|
+
|
|
287
|
+
def record(file)
|
|
288
|
+
{ "file" => File.basename(file), "bytes" => File.size(file), "sha256" => Digest::SHA256.file(file).hexdigest }
|
|
289
|
+
end
|
|
290
|
+
|
|
291
|
+
# Dated files whose contents differ from what the previous build of
|
|
292
|
+
# this region recorded under the same name: Geofabrik republished them,
|
|
293
|
+
# or something altered them on the way. Either way, worth a look.
|
|
294
|
+
def upstream_changes(previous, sources)
|
|
295
|
+
before = Array(previous && previous["sources"]).to_h { |s| [s["file"], s["members"]] }
|
|
296
|
+
Array(sources).filter_map { |s| s["file"] if before[s["file"]] && before[s["file"]] != s["members"] }
|
|
297
|
+
end
|
|
298
|
+
|
|
299
|
+
def previous_metadata(file)
|
|
300
|
+
File.file?(file) ? JSON.parse(File.read(file, encoding: "utf-8")) : nil
|
|
301
|
+
rescue JSON::ParserError
|
|
302
|
+
nil
|
|
303
|
+
end
|
|
304
|
+
|
|
305
|
+
def sha256(file)
|
|
306
|
+
File.file?(file) ? Digest::SHA256.file(file).hexdigest : nil
|
|
307
|
+
end
|
|
308
|
+
|
|
309
|
+
def bbox_of(rows)
|
|
310
|
+
%w[a b].map { |k| rows.map { |r| r[k] }.min } + %w[c d].map { |k| rows.map { |r| r[k] }.max }
|
|
258
311
|
end
|
|
259
312
|
|
|
260
313
|
def rounded(rings)
|
|
@@ -262,7 +315,8 @@ module Curtilage
|
|
|
262
315
|
end
|
|
263
316
|
|
|
264
317
|
def attribution(ml_footprints)
|
|
265
|
-
["© OpenStreetMap contributors",
|
|
318
|
+
["© OpenStreetMap contributors",
|
|
319
|
+
("Microsoft Global ML Building Footprints (CDLA Permissive 2.0)" if ml_footprints)].compact
|
|
266
320
|
end
|
|
267
321
|
|
|
268
322
|
def cleanup(work_dir, dirs, keep_downloads)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Curtilage
|
|
4
|
+
# Other premises a site could have, for when the result is ambiguous
|
|
5
|
+
# (generate's candidates: N): a reviewer or a downstream system picks.
|
|
6
|
+
# Each is a full Result with its own confidence, flags and steps.
|
|
7
|
+
module Candidates
|
|
8
|
+
# Below this confidence the building rectangle is offered too.
|
|
9
|
+
LOW_CONFIDENCE = 0.7
|
|
10
|
+
MAX = 5
|
|
11
|
+
|
|
12
|
+
module_function
|
|
13
|
+
|
|
14
|
+
# Up to count valid alternatives to result, unlike it and each other,
|
|
15
|
+
# most confident first:
|
|
16
|
+
# - another building within building_max_distance_m of the pin (the pin
|
|
17
|
+
# may be on the wrong one), with the pin moved onto it;
|
|
18
|
+
# - on a shared lot, the whole shopping centre (scope: :centre);
|
|
19
|
+
# - when confidence is low, the building rectangle (method: :building).
|
|
20
|
+
def for(result, pin, features, options, count)
|
|
21
|
+
unless count.is_a?(Integer) && count.between?(1, MAX)
|
|
22
|
+
raise ArgumentError, "candidates must be a whole number from 1 to #{MAX}: #{count.inspect}"
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
features = Features.new(pin, features) unless features.is_a?(Features)
|
|
26
|
+
found = other_buildings(result, features, options) + other_shapes(result, pin, features, options)
|
|
27
|
+
found.select(&:ok?).reject { |c| c.ring == result.ring }.uniq(&:ring)
|
|
28
|
+
.sort_by { |c| -c.confidence }.first(count)
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def other_buildings(result, features, options)
|
|
32
|
+
opts = Generator.checked_options(Curtilage.send(:preset_options, options[:preset])
|
|
33
|
+
.merge(options.except(:preset, :method)))
|
|
34
|
+
own = Generator.choose_buildings(features, opts[:buildings])
|
|
35
|
+
reach = own.buildings.filter_map do |b|
|
|
36
|
+
distance = Geometry.distance_to_edges(b.xy, Generator::ORIGIN)
|
|
37
|
+
[distance, b] if b.id != result.building && distance <= opts[:building_max_distance_m] &&
|
|
38
|
+
b.area >= opts[:small_building_m2]
|
|
39
|
+
end
|
|
40
|
+
reach.sort_by { |d, b| [d, b.id.to_s] }.first(MAX).map { |d, b| on_building(b, d, features, result, options) }
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def on_building(building, distance, features, result, options)
|
|
44
|
+
moved = features.moved_to(Generator.inside_point(building))
|
|
45
|
+
Curtilage.generate(moved.pin, moved, **options).tap do |c|
|
|
46
|
+
c.flags << :pin_moved unless c.flags.include?(:pin_moved)
|
|
47
|
+
c.pin_quality = (result.pin_quality || {}).merge(moved_from: result.pin)
|
|
48
|
+
c.prepend_step("candidate: building #{building.id}, #{distance.round} m from the pin, instead",
|
|
49
|
+
step: "candidate", features: [building.id], distance_m: distance.round(1))
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def other_shapes(result, pin, features, options)
|
|
54
|
+
shared = result.steps.to_a.any? { |s| s[:rule] == "shared_lot_buildings" }
|
|
55
|
+
list = []
|
|
56
|
+
list << [{ scope: :centre }, "the whole shopping centre"] if shared && options[:scope] != :centre
|
|
57
|
+
if result.method_name == :grow_trim && result.confidence < LOW_CONFIDENCE
|
|
58
|
+
list << [{ method: :building }, "the building rectangle"]
|
|
59
|
+
end
|
|
60
|
+
list.map do |change, words|
|
|
61
|
+
Curtilage.generate(pin, features, **options, **change).tap do |c|
|
|
62
|
+
c.prepend_step("candidate: #{words}", step: "candidate", rule: change.keys.first.to_s)
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
end
|