@mailwoman/zoning 9.2.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 (82) hide show
  1. package/README.md +315 -0
  2. package/lib/index.ts +616 -0
  3. package/lib/ring-roles.ts +233 -0
  4. package/lib/rings.ts +34 -0
  5. package/lib/schema.ts +449 -0
  6. package/lib/scripts/ingest-chunk.ts +41 -0
  7. package/lib/sdk/build-zoning.ts +790 -0
  8. package/lib/sdk/cells.ts +276 -0
  9. package/lib/sdk/client.ts +335 -0
  10. package/lib/sdk/download.ts +78 -0
  11. package/lib/sdk/index.ts +15 -0
  12. package/lib/sdk/ingest-chunk.ts +360 -0
  13. package/lib/sdk/ingest.ts +402 -0
  14. package/lib/sdk/measure-resolutions.ts +100 -0
  15. package/lib/sdk/verify.ts +350 -0
  16. package/lib/test-kit.ts +207 -0
  17. package/lib/vocabulary.ts +342 -0
  18. package/out/index.d.ts +257 -0
  19. package/out/index.d.ts.map +1 -0
  20. package/out/index.js +325 -0
  21. package/out/index.js.map +1 -0
  22. package/out/ring-roles.d.ts +88 -0
  23. package/out/ring-roles.d.ts.map +1 -0
  24. package/out/ring-roles.js +151 -0
  25. package/out/ring-roles.js.map +1 -0
  26. package/out/rings.d.ts +22 -0
  27. package/out/rings.d.ts.map +1 -0
  28. package/out/rings.js +22 -0
  29. package/out/rings.js.map +1 -0
  30. package/out/schema.d.ts +325 -0
  31. package/out/schema.d.ts.map +1 -0
  32. package/out/schema.js +186 -0
  33. package/out/schema.js.map +1 -0
  34. package/out/scripts/ingest-chunk.d.ts +11 -0
  35. package/out/scripts/ingest-chunk.d.ts.map +1 -0
  36. package/out/scripts/ingest-chunk.js +36 -0
  37. package/out/scripts/ingest-chunk.js.map +1 -0
  38. package/out/sdk/build-zoning.d.ts +283 -0
  39. package/out/sdk/build-zoning.d.ts.map +1 -0
  40. package/out/sdk/build-zoning.js +462 -0
  41. package/out/sdk/build-zoning.js.map +1 -0
  42. package/out/sdk/cells.d.ts +137 -0
  43. package/out/sdk/cells.d.ts.map +1 -0
  44. package/out/sdk/cells.js +176 -0
  45. package/out/sdk/cells.js.map +1 -0
  46. package/out/sdk/client.d.ts +151 -0
  47. package/out/sdk/client.d.ts.map +1 -0
  48. package/out/sdk/client.js +239 -0
  49. package/out/sdk/client.js.map +1 -0
  50. package/out/sdk/download.d.ts +51 -0
  51. package/out/sdk/download.d.ts.map +1 -0
  52. package/out/sdk/download.js +57 -0
  53. package/out/sdk/download.js.map +1 -0
  54. package/out/sdk/index.d.ts +15 -0
  55. package/out/sdk/index.d.ts.map +1 -0
  56. package/out/sdk/index.js +15 -0
  57. package/out/sdk/index.js.map +1 -0
  58. package/out/sdk/ingest-chunk.d.ts +130 -0
  59. package/out/sdk/ingest-chunk.d.ts.map +1 -0
  60. package/out/sdk/ingest-chunk.js +206 -0
  61. package/out/sdk/ingest-chunk.js.map +1 -0
  62. package/out/sdk/ingest.d.ts +191 -0
  63. package/out/sdk/ingest.d.ts.map +1 -0
  64. package/out/sdk/ingest.js +238 -0
  65. package/out/sdk/ingest.js.map +1 -0
  66. package/out/sdk/measure-resolutions.d.ts +51 -0
  67. package/out/sdk/measure-resolutions.d.ts.map +1 -0
  68. package/out/sdk/measure-resolutions.js +64 -0
  69. package/out/sdk/measure-resolutions.js.map +1 -0
  70. package/out/sdk/verify.d.ts +176 -0
  71. package/out/sdk/verify.d.ts.map +1 -0
  72. package/out/sdk/verify.js +202 -0
  73. package/out/sdk/verify.js.map +1 -0
  74. package/out/test-kit.d.ts +97 -0
  75. package/out/test-kit.d.ts.map +1 -0
  76. package/out/test-kit.js +180 -0
  77. package/out/test-kit.js.map +1 -0
  78. package/out/vocabulary.d.ts +221 -0
  79. package/out/vocabulary.d.ts.map +1 -0
  80. package/out/vocabulary.js +299 -0
  81. package/out/vocabulary.js.map +1 -0
  82. package/package.json +245 -0
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file The acquisition + build surface for the Irish zoning layer. The READER is the package root.
6
+ */
7
+
8
+ export * from "#sdk/build-zoning"
9
+ export * from "#sdk/cells"
10
+ export * from "#sdk/client"
11
+ export * from "#sdk/download"
12
+ export * from "#sdk/ingest"
13
+ export * from "#sdk/ingest-chunk"
14
+ export * from "#sdk/measure-resolutions"
15
+ export * from "#sdk/verify"
@@ -0,0 +1,360 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The streaming pass — every feature into `zoning_area` and into `zoning_cell` — as a unit of work that can
7
+ * run over PART of the source.
8
+ *
9
+ * WHY THIS IS A CHUNK RATHER THAN THE WHOLE FILE. h3's WASM heap cannot be reset from JavaScript, and it
10
+ * does not survive an unbounded number of polyfill calls: over a sibling product, runs died after roughly
11
+ * 510,000 and 798,000 features on geometry that classifies in milliseconds in a fresh process. A build that
12
+ * completes only when fragmentation happens to stay low is not a reproducible build, so the classification
13
+ * is bounded BY CONSTRUCTION — one process per range of the authority's own feature ids. This product's
14
+ * 85,330 features fit inside the default bound; the bound ships anyway, because determinism by construction
15
+ * is not the same fact as determinism by luck.
16
+ *
17
+ * THE VOCABULARY IS A CENSUS, NOT A CHECK. The declared generic-type domain is closed and the source
18
+ * already breaks it — `N/A` appears on 4 rows and in no domain — so an undeclared value is RECORDED as
19
+ * observed-but-undeclared rather than throwing. That is the opposite of the sibling layers' rule and it is
20
+ * the publisher's own doing: refusing here would refuse the Department's own data. What DOES throw is a
21
+ * blank local code, because the local code is the claim.
22
+ *
23
+ * THE CROSSWALK PAIRS ARE COUNTED HERE BECAUSE THEY ARE THE ARGUMENT FOR THE SCHEMA. If a local code
24
+ * determined a generic type, the mapping could ship as an edge table and the local column would be
25
+ * redundant. It does not: measured nationally, 52 of 795 (authority, local code) pairs take more than one
26
+ * generic type. The chunk reports the pairs it saw and the build refuses to write an edge table while any
27
+ * such pair exists, so the empty `zoning_crosswalk_edge` is a checked consequence rather than an omission.
28
+ *
29
+ * THE CHUNK OWNS NO ARTIFACT. It appends rows to a database the parent created and will seal, and returns
30
+ * counts the parent adds up. Chunks run one at a time against that file, so there is no concurrent writer
31
+ * and no locking to reason about. The jurisdiction, plan and vocabulary rows are RETURNED rather than
32
+ * written: they are per-chunk partials that have to be merged before insertion, and 30 authorities, 63
33
+ * plans and about 880 vocabulary rows cross a process boundary for nothing.
34
+ */
35
+
36
+ import { addCoverageCells, encodeRings, ringAreaReadings, ringsBoundingBox } from "@mailwoman/spatial"
37
+ import { beginBatched } from "@mailwoman/sqlite/batched"
38
+ import type { DatabaseClient } from "@mailwoman/sqlite/client"
39
+
40
+ import type { ZoningDatabase } from "#schema"
41
+ import { classifyFeatureCells, featureCellRows } from "#sdk/cells"
42
+ import type { ZoningFeatureSource, ZoningSourceFeature } from "#sdk/ingest"
43
+ import { GZT_CROSSWALK_SCHEME, GZT_PROVENANCE_GRADE, GZT_ROLLUP_SCHEME, localSchemeFor } from "#vocabulary"
44
+
45
+ /**
46
+ * Rows per bulk-insert transaction. Chosen for the geometry table, whose rows carry a blob: a larger transaction grows
47
+ * the write-ahead file without improving throughput.
48
+ */
49
+ const INSERT_TRANSACTION_ROWS = 5000
50
+
51
+ /**
52
+ * Features between progress reports.
53
+ */
54
+ const PROGRESS_STRIDE = 5000
55
+
56
+ /**
57
+ * One observed vocabulary value: which scheme, which code, the publisher's own label for it, and how many rows carry
58
+ * it.
59
+ */
60
+ export type ObservedTerm = [scheme: string, code: string, label: string, rows: number]
61
+
62
+ /**
63
+ * One (authority, local code) pair and every generic type the publisher assigned to it.
64
+ */
65
+ export type CrosswalkPair = [authorityCode: string, localCode: string, crosswalkCodes: string[]]
66
+
67
+ /**
68
+ * What one chunk produced. Every field is JSON-serializable, because a chunk normally reports across a process
69
+ * boundary.
70
+ */
71
+ export interface ZoningChunkResult {
72
+ features: number
73
+ /**
74
+ * Features whose bounding box forced a resolution coarser than the target.
75
+ */
76
+ coarsened: number
77
+ /**
78
+ * Cell rows written, split by tier.
79
+ */
80
+ wholeCellRows: number
81
+ partialCellRows: number
82
+ /**
83
+ * `[coverageCell, polygonsReachingIt]` pairs — an array rather than a `Map` so it survives the process boundary.
84
+ */
85
+ observedByCoverageCell: Array<[number, number]>
86
+ /**
87
+ * Square metres. `signed` is the raw ring sum as published; `nested` is the per-polygon hole-aware reading;
88
+ * `allExterior` is what the same rings say read WITHOUT their holes.
89
+ */
90
+ area: { signedM2: number; nestedM2: number; allExteriorM2: number }
91
+ /**
92
+ * The ring-role census — the receipt that the orientation was read rather than assumed.
93
+ */
94
+ rings: {
95
+ total: number
96
+ exteriors: number
97
+ holes: number
98
+ nestedHoles: number
99
+ adjacentHoles: number
100
+ /**
101
+ * Features whose exterior was chosen by MAGNITUDE because no ring read as one by orientation — measured at one of
102
+ * 85,330. See `ResolvedRingRoles.exteriorByMagnitude`.
103
+ */
104
+ exteriorByMagnitude: number
105
+ }
106
+ /**
107
+ * The authorities this chunk saw, by their own code.
108
+ */
109
+ jurisdictions: Array<[code: string, name: string]>
110
+ /**
111
+ * The plans this chunk saw.
112
+ */
113
+ plans: Array<{
114
+ planID: string
115
+ authorityCode: string
116
+ name: string
117
+ level: string
118
+ from: string | null
119
+ to: string | null
120
+ currentPlan: number
121
+ }>
122
+ vocabulary: ObservedTerm[]
123
+ crosswalkPairs: CrosswalkPair[]
124
+ }
125
+
126
+ export interface IngestZoningChunkOptions {
127
+ source: ZoningFeatureSource
128
+ indexResolution: number
129
+ coverageResolution: number
130
+ onProgress?: (message: string) => void
131
+ }
132
+
133
+ /**
134
+ * Stream one chunk of the source into `database`.
135
+ *
136
+ * @throws {Error} On a feature the classifier or the ring-role resolver refuses.
137
+ */
138
+ export async function ingestZoningChunk(
139
+ database: DatabaseClient<ZoningDatabase>,
140
+ options: IngestZoningChunkOptions
141
+ ): Promise<ZoningChunkResult> {
142
+ const insertArea = database.prepare(
143
+ "INSERT INTO zoning_area (area_id, jurisdiction_id, plan_id, local_code, local_description, local_code_url, " +
144
+ "crosswalk_code, crosswalk_scheme, crosswalk_description, crosswalk_rollup, provenance_grade, " +
145
+ "min_lat, min_lon, max_lat, max_lon, ring_count, signed_area_m2, rings) " +
146
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
147
+ )
148
+
149
+ const insertCell = database.prepare(
150
+ "INSERT INTO zoning_cell (h3_cell, resolution, area_id, containment) VALUES (?, ?, ?, ?)"
151
+ )
152
+
153
+ const observedByCoverageCell = new Map<number, number>()
154
+ const jurisdictions = new Map<string, string>()
155
+ const plans = new Map<string, ZoningChunkResult["plans"][number]>()
156
+
157
+ // KEYED ON A NUL-JOINED PAIR AND NEVER SPLIT BACK APART. A local code is free text that routinely contains spaces —
158
+ // `Special Policy Area`, `RA - Rural Area` — so a key a reader had to re-split would mangle exactly the vocabulary
159
+ // this layer exists to carry verbatim. The parts ride on the value instead.
160
+ const vocabulary = new Map<string, { scheme: string; code: string; label: string; rows: number }>()
161
+ const crosswalkPairs = new Map<string, { authorityCode: string; localCode: string; codes: Set<string> }>()
162
+
163
+ let features = 0
164
+ let coarsened = 0
165
+ let wholeCellRows = 0
166
+ let partialCellRows = 0
167
+ let signedArea = 0
168
+ let nestedArea = 0
169
+ let allExteriorArea = 0
170
+ let ringsTotal = 0
171
+ let exteriors = 0
172
+ let holes = 0
173
+ let nestedHoles = 0
174
+ let exteriorByMagnitude = 0
175
+ let adjacentHoles = 0
176
+
177
+ /**
178
+ * Record one observed vocabulary value. The FIRST label wins, because a later row's description is the publisher's
179
+ * word for the same code and choosing between them would be this package editing the publisher's vocabulary.
180
+ */
181
+ const observe = (scheme: string, code: string, label: string): void => {
182
+ const key = `${scheme}\u0000${code}`
183
+ const existing = vocabulary.get(key)
184
+
185
+ if (existing) {
186
+ existing.rows++
187
+
188
+ return
189
+ }
190
+
191
+ vocabulary.set(key, { scheme, code, label, rows: 1 })
192
+ }
193
+
194
+ const batch = beginBatched(database, { rowsPerCommit: INSERT_TRANSACTION_ROWS })
195
+
196
+ try {
197
+ for await (const feature of options.source.features()) {
198
+ const bbox = ringsBoundingBox(feature.rings.polygons)
199
+ const areas = ringAreaReadings(feature.rings.polygons)
200
+
201
+ signedArea += feature.rings.signedAreaM2
202
+ nestedArea += areas.nested
203
+ allExteriorArea += areas.allExterior
204
+ ringsTotal += feature.rings.ringCount
205
+ exteriors += feature.rings.exteriorCount
206
+ holes += feature.rings.holeCount
207
+ nestedHoles += feature.rings.nestedHoles
208
+ exteriorByMagnitude += feature.rings.exteriorByMagnitude
209
+ adjacentHoles += feature.rings.adjacentHoles
210
+
211
+ insertArea.run(
212
+ feature.areaID,
213
+ feature.authorityCode,
214
+ feature.planID,
215
+ feature.localCode,
216
+ feature.localDescription,
217
+ feature.localCodeURL,
218
+ feature.crosswalkCode,
219
+ feature.crosswalkCode === null ? null : GZT_CROSSWALK_SCHEME,
220
+ feature.crosswalkDescription,
221
+ feature.crosswalkRollup,
222
+ // ONE GRADE PER CLAIM. Every row of THIS artifact is `authoritative` — a government department republishing
223
+ // local authorities' adopted plans — and an observed land-use layer is a different database with a different
224
+ // `layer_manifest.name`, never a row with a second grade in this table.
225
+ GZT_PROVENANCE_GRADE,
226
+ bbox.minLat,
227
+ bbox.minLon,
228
+ bbox.maxLat,
229
+ bbox.maxLon,
230
+ feature.rings.ringCount,
231
+ feature.rings.signedAreaM2,
232
+ encodeRings(feature.rings.polygons)
233
+ )
234
+
235
+ const classified = classifyFeatureCells(
236
+ feature.rings.polygons,
237
+ options.indexResolution,
238
+ feature.areaID,
239
+ "zoning cells"
240
+ )
241
+
242
+ if (classified.resolution !== options.indexResolution) {
243
+ coarsened++
244
+ }
245
+
246
+ for (const row of featureCellRows(classified)) {
247
+ insertCell.run(row.h3Cell, row.resolution, feature.areaID, row.containment)
248
+
249
+ if (row.containment === "whole") {
250
+ wholeCellRows++
251
+ } else {
252
+ partialCellRows++
253
+ }
254
+ }
255
+
256
+ // COVERAGE IS DERIVED FROM THE UNCOMPACTED CLASSIFICATION, not from the stored rows. A compacted parent spans
257
+ // several coverage cells and `addCoverageCells` handles that, but the fringe is where this product's cells almost
258
+ // all are — so counting off the stored rows and counting off the classification agree here, and the classification
259
+ // is the one that cannot be changed by a compaction decision.
260
+ const coverageCells = new Set<number>()
261
+
262
+ for (const cell of classified.whole) {
263
+ addCoverageCells(coverageCells, cell, classified.resolution, options.coverageResolution)
264
+ }
265
+
266
+ for (const cell of classified.partial) {
267
+ addCoverageCells(coverageCells, cell, classified.resolution, options.coverageResolution)
268
+ }
269
+
270
+ for (const coverageCell of coverageCells) {
271
+ observedByCoverageCell.set(coverageCell, (observedByCoverageCell.get(coverageCell) ?? 0) + 1)
272
+ }
273
+
274
+ jurisdictions.set(feature.authorityCode, feature.authorityName)
275
+
276
+ if (!plans.has(feature.planID)) {
277
+ plans.set(feature.planID, {
278
+ planID: feature.planID,
279
+ authorityCode: feature.authorityCode,
280
+ name: feature.planName,
281
+ level: feature.planLevel,
282
+ from: feature.planFrom,
283
+ to: feature.planTo,
284
+ currentPlan: feature.currentPlan,
285
+ })
286
+ }
287
+
288
+ // The local vocabulary is per AUTHORITY, because the codes collide across them: `Residential` means one thing in
289
+ // Cork County Council's plan and another in Westmeath's.
290
+ observe(localSchemeFor(feature.authorityCode), feature.localCode, feature.localDescription ?? feature.localCode)
291
+
292
+ if (feature.crosswalkCode !== null) {
293
+ observe(GZT_CROSSWALK_SCHEME, feature.crosswalkCode, feature.crosswalkDescription ?? feature.crosswalkCode)
294
+
295
+ const key = `${feature.authorityCode}\u0000${feature.localCode}`
296
+ const pair = crosswalkPairs.get(key)
297
+
298
+ if (pair) {
299
+ pair.codes.add(feature.crosswalkCode)
300
+ } else {
301
+ crosswalkPairs.set(key, {
302
+ authorityCode: feature.authorityCode,
303
+ localCode: feature.localCode,
304
+ codes: new Set([feature.crosswalkCode]),
305
+ })
306
+ }
307
+ }
308
+
309
+ if (feature.crosswalkRollup !== null) {
310
+ observe(GZT_ROLLUP_SCHEME, feature.crosswalkRollup, feature.crosswalkRollup)
311
+ }
312
+
313
+ features++
314
+
315
+ batch.rowWritten()
316
+
317
+ if (features % PROGRESS_STRIDE === 0) {
318
+ options.onProgress?.(`${features.toLocaleString()} features in this chunk`)
319
+ }
320
+ }
321
+
322
+ batch.commit()
323
+ } catch (error) {
324
+ batch.rollbackQuietly()
325
+
326
+ throw error
327
+ }
328
+
329
+ return {
330
+ features,
331
+ coarsened,
332
+ wholeCellRows,
333
+ partialCellRows,
334
+ observedByCoverageCell: [...observedByCoverageCell],
335
+ area: { signedM2: signedArea, nestedM2: nestedArea, allExteriorM2: allExteriorArea },
336
+ rings: { total: ringsTotal, exteriors, holes, nestedHoles, adjacentHoles, exteriorByMagnitude },
337
+ jurisdictions: [...jurisdictions],
338
+ plans: [...plans.values()],
339
+ vocabulary: [...vocabulary.values()].map(
340
+ (term) => [term.scheme, term.code, term.label, term.rows] satisfies ObservedTerm
341
+ ),
342
+ crosswalkPairs: [...crosswalkPairs.values()].map(
343
+ (pair) => [pair.authorityCode, pair.localCode, [...pair.codes].toSorted()] satisfies CrosswalkPair
344
+ ),
345
+ }
346
+ }
347
+
348
+ /**
349
+ * One feature's own contribution, for a caller that wants the numbers without a database — the fixture rung's
350
+ * arithmetic and nothing else.
351
+ */
352
+ export function featureAreaReadings(feature: ZoningSourceFeature): {
353
+ signed: number
354
+ nested: number
355
+ allExterior: number
356
+ } {
357
+ const areas = ringAreaReadings(feature.rings.polygons)
358
+
359
+ return { signed: feature.rings.signedAreaM2, nested: areas.nested, allExterior: areas.allExterior }
360
+ }