@mailwoman/zoning 10.0.0 → 10.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 (101) hide show
  1. package/README.md +169 -163
  2. package/lib/index.ts +103 -135
  3. package/lib/paths.ts +24 -0
  4. package/lib/ring-roles.ts +30 -71
  5. package/lib/rings.ts +2 -13
  6. package/lib/schema.ts +98 -139
  7. package/lib/vocabulary.ts +52 -130
  8. package/out/index.d.ts +81 -101
  9. package/out/index.d.ts.map +1 -1
  10. package/out/index.js +37 -96
  11. package/out/index.js.map +1 -1
  12. package/out/paths.d.ts +19 -0
  13. package/out/paths.d.ts.map +1 -0
  14. package/out/paths.js +21 -0
  15. package/out/paths.js.map +1 -0
  16. package/out/ring-roles.d.ts +16 -50
  17. package/out/ring-roles.d.ts.map +1 -1
  18. package/out/ring-roles.js +18 -51
  19. package/out/ring-roles.js.map +1 -1
  20. package/out/rings.d.ts +2 -13
  21. package/out/rings.d.ts.map +1 -1
  22. package/out/rings.js +2 -13
  23. package/out/rings.js.map +1 -1
  24. package/out/schema.d.ts +90 -132
  25. package/out/schema.d.ts.map +1 -1
  26. package/out/schema.js +17 -45
  27. package/out/schema.js.map +1 -1
  28. package/out/sdk/build-zoning.d.ts +58 -111
  29. package/out/sdk/build-zoning.d.ts.map +1 -1
  30. package/out/sdk/build-zoning.js +50 -139
  31. package/out/sdk/build-zoning.js.map +1 -1
  32. package/out/sdk/cells.d.ts +21 -62
  33. package/out/sdk/cells.d.ts.map +1 -1
  34. package/out/sdk/cells.js +15 -52
  35. package/out/sdk/cells.js.map +1 -1
  36. package/out/sdk/client.d.ts +23 -67
  37. package/out/sdk/client.d.ts.map +1 -1
  38. package/out/sdk/client.js +29 -77
  39. package/out/sdk/client.js.map +1 -1
  40. package/out/sdk/download.d.ts +7 -27
  41. package/out/sdk/download.d.ts.map +1 -1
  42. package/out/sdk/download.js +8 -28
  43. package/out/sdk/download.js.map +1 -1
  44. package/out/sdk/ingest/chunk.d.ts +19 -43
  45. package/out/sdk/ingest/chunk.d.ts.map +1 -1
  46. package/out/sdk/ingest/chunk.js +19 -52
  47. package/out/sdk/ingest/chunk.js.map +1 -1
  48. package/out/sdk/ingest/worker.d.ts +9 -0
  49. package/out/sdk/ingest/worker.d.ts.map +1 -0
  50. package/out/{scripts/ingest-chunk.js → sdk/ingest/worker.js} +8 -10
  51. package/out/sdk/ingest/worker.js.map +1 -0
  52. package/out/sdk/ingest.d.ts +152 -0
  53. package/out/sdk/ingest.d.ts.map +1 -0
  54. package/out/sdk/ingest.js +200 -0
  55. package/out/sdk/ingest.js.map +1 -0
  56. package/out/sdk/measure-resolutions.d.ts +7 -34
  57. package/out/sdk/measure-resolutions.d.ts.map +1 -1
  58. package/out/sdk/measure-resolutions.js +5 -23
  59. package/out/sdk/measure-resolutions.js.map +1 -1
  60. package/out/sdk/test-kit.d.ts +75 -0
  61. package/out/sdk/test-kit.d.ts.map +1 -0
  62. package/out/{test-kit.js → sdk/test-kit.js} +20 -43
  63. package/out/sdk/test-kit.js.map +1 -0
  64. package/out/sdk/verify.d.ts +79 -80
  65. package/out/sdk/verify.d.ts.map +1 -1
  66. package/out/sdk/verify.js +83 -70
  67. package/out/sdk/verify.js.map +1 -1
  68. package/out/vocabulary.d.ts +52 -120
  69. package/out/vocabulary.d.ts.map +1 -1
  70. package/out/vocabulary.js +47 -125
  71. package/out/vocabulary.js.map +1 -1
  72. package/package.json +38 -162
  73. package/{lib/sdk → sdk}/build-zoning.ts +102 -188
  74. package/{lib/sdk → sdk}/cells.ts +27 -66
  75. package/{lib/sdk → sdk}/client.ts +34 -82
  76. package/sdk/download.ts +58 -0
  77. package/{lib/sdk → sdk}/ingest/chunk.ts +36 -65
  78. package/{lib/scripts/ingest-chunk.ts → sdk/ingest/worker.ts} +7 -9
  79. package/sdk/ingest.ts +354 -0
  80. package/sdk/measure-resolutions.ts +72 -0
  81. package/{lib → sdk}/test-kit.ts +21 -44
  82. package/sdk/verify.ts +367 -0
  83. package/lib/sdk/download.ts +0 -78
  84. package/lib/sdk/index.ts +0 -15
  85. package/lib/sdk/ingest/index.ts +0 -393
  86. package/lib/sdk/measure-resolutions.ts +0 -101
  87. package/lib/sdk/verify.ts +0 -357
  88. package/out/scripts/ingest-chunk.d.ts +0 -11
  89. package/out/scripts/ingest-chunk.d.ts.map +0 -1
  90. package/out/scripts/ingest-chunk.js.map +0 -1
  91. package/out/sdk/index.d.ts +0 -15
  92. package/out/sdk/index.d.ts.map +0 -1
  93. package/out/sdk/index.js +0 -15
  94. package/out/sdk/index.js.map +0 -1
  95. package/out/sdk/ingest/index.d.ts +0 -185
  96. package/out/sdk/ingest/index.d.ts.map +0 -1
  97. package/out/sdk/ingest/index.js +0 -232
  98. package/out/sdk/ingest/index.js.map +0 -1
  99. package/out/test-kit.d.ts +0 -96
  100. package/out/test-kit.d.ts.map +0 -1
  101. package/out/test-kit.js.map +0 -1
@@ -3,34 +3,7 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
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.
6
+ * The streaming pass, bounded to one process per range of the authority's own feature ids because h3's wasm heap cannot be reset from JavaScript and a build that completes only by luck is not reproducible.
34
7
  */
35
8
 
36
9
  import {
@@ -45,23 +18,22 @@ import { beginBatched } from "@mailwoman/sqlite/batched"
45
18
  import type { DatabaseClient } from "@mailwoman/sqlite/client"
46
19
 
47
20
  import type { ZoningDatabase } from "#schema"
48
- import type { ZoningFeatureSource, ZoningSourceFeature } from "#sdk/ingest/index"
21
+ import type { ZoningFeatureSource, ZoningSourceFeature } from "#sdk/ingest"
49
22
  import { GZT_CROSSWALK_SCHEME, GZT_PROVENANCE_GRADE, GZT_ROLLUP_SCHEME, localSchemeFor } from "#vocabulary"
50
23
 
51
24
  /**
52
- * Rows per bulk-insert transaction. Chosen for the geometry table, whose rows carry a blob: a larger transaction grows
53
- * the write-ahead file without improving throughput.
25
+ * Rows per bulk-insert transaction, chosen for the geometry table whose rows contain a blob
26
+ * because a larger transaction grows the write-ahead file without improving throughput.
54
27
  */
55
28
  const INSERT_TRANSACTION_ROWS = 5000
56
29
 
57
- /**
58
- * Features between progress reports.
59
- */
60
30
  const PROGRESS_STRIDE = 5000
61
31
 
62
32
  /**
63
- * One observed vocabulary value: which scheme, which code, the publisher's own label for it, and how many rows carry
64
- * it.
33
+ * One observed vocabulary value.
34
+ *
35
+ * It records the scheme and code.
36
+ * It also records the publisher's label and row count.
65
37
  */
66
38
  export type ObservedTerm = [scheme: string, code: string, label: string, rows: number]
67
39
 
@@ -71,8 +43,8 @@ export type ObservedTerm = [scheme: string, code: string, label: string, rows: n
71
43
  export type CrosswalkPair = [authorityCode: string, localCode: string, crosswalkCodes: string[]]
72
44
 
73
45
  /**
74
- * What one chunk produced. Every field is JSON-serializable, because a chunk normally reports across a process
75
- * boundary.
46
+ * What one chunk produced, every field JSON-serializable because a chunk normally
47
+ * reports across a process boundary.
76
48
  */
77
49
  export interface ZoningChunkResult {
78
50
  features: number
@@ -86,12 +58,17 @@ export interface ZoningChunkResult {
86
58
  wholeCellRows: number
87
59
  partialCellRows: number
88
60
  /**
89
- * `[coverageCell, polygonsReachingIt]` pairs — an array rather than a `Map` so it survives the process boundary.
61
+ * `[coverageCell, polygonsReachingIt]` pairs — an array rather than a `Map`
62
+ * so it survives the process boundary.
90
63
  */
91
64
  observedByCoverageCell: Array<[number, number]>
92
65
  /**
93
- * Square metres. `signed` is the raw ring sum as published; `nested` is the per-polygon hole-aware reading;
94
- * `allExterior` is what the same rings say read WITHOUT their holes.
66
+ * Square-meter area readings from the polygon rings.
67
+ *
68
+ * `signed` is the raw ring sum as published.
69
+ * `nested` accounts for holes in each polygon.
70
+ *
71
+ * `allExterior` reads the same rings as exterior boundaries without holes.
95
72
  */
96
73
  area: { signedM2: number; nestedM2: number; allExteriorM2: number }
97
74
  /**
@@ -104,8 +81,7 @@ export interface ZoningChunkResult {
104
81
  nestedHoles: number
105
82
  adjacentHoles: number
106
83
  /**
107
- * Features whose exterior was chosen by MAGNITUDE because no ring read as one by orientation — measured at one of
108
- * 85,330. See `ResolvedRingRoles.exteriorByMagnitude`.
84
+ * Features whose exterior was chosen by magnitude because no ring read as one by orientation.
109
85
  */
110
86
  exteriorByMagnitude: number
111
87
  }
@@ -113,9 +89,7 @@ export interface ZoningChunkResult {
113
89
  * The authorities this chunk saw, by their own code.
114
90
  */
115
91
  jurisdictions: Array<[code: string, name: string]>
116
- /**
117
- * The plans this chunk saw.
118
- */
92
+
119
93
  plans: Array<{
120
94
  planID: string
121
95
  authorityCode: string
@@ -160,9 +134,9 @@ export async function ingestZoningChunk(
160
134
  const jurisdictions = new Map<string, string>()
161
135
  const plans = new Map<string, ZoningChunkResult["plans"][number]>()
162
136
 
163
- // KEYED ON A NUL-JOINED PAIR AND NEVER SPLIT BACK APART. A local code is free text that routinely contains spaces —
164
- // `Special Policy Area`, `RA - Rural Area` — so a key a reader had to re-split would mangle exactly the vocabulary
165
- // this layer exists to carry verbatim. The parts ride on the value instead.
137
+ // Keyed on a NUL-joined pair and never split back apart, because a local code is
138
+ // free text that routinely contains spaces and a key a reader had to re-split
139
+ // would mangle the vocabulary this layer preserves verbatim.
166
140
  const vocabulary = new Map<string, { scheme: string; code: string; label: string; rows: number }>()
167
141
  const crosswalkPairs = new Map<string, { authorityCode: string; localCode: string; codes: Set<string> }>()
168
142
 
@@ -181,8 +155,8 @@ export async function ingestZoningChunk(
181
155
  let adjacentHoles = 0
182
156
 
183
157
  /**
184
- * Record one observed vocabulary value. The FIRST label wins, because a later row's description is the publisher's
185
- * word for the same code and choosing between them would be this package editing the publisher's vocabulary.
158
+ * Record one observed vocabulary value, keeping the first label so a later row's
159
+ * description leaves the publisher's vocabulary unchanged.
186
160
  */
187
161
  const observe = (scheme: string, code: string, label: string): void => {
188
162
  const key = `${scheme}\u0000${code}`
@@ -222,12 +196,12 @@ export async function ingestZoningChunk(
222
196
  feature.localDescription,
223
197
  feature.localCodeURL,
224
198
  feature.crosswalkCode,
225
- feature.crosswalkCode === null ? null : GZT_CROSSWALK_SCHEME,
199
+ feature.crosswalkCode ? GZT_CROSSWALK_SCHEME : null,
226
200
  feature.crosswalkDescription,
227
201
  feature.crosswalkRollup,
228
- // ONE GRADE PER CLAIM. Every row of THIS artifact is `authoritative` — a government department republishing
229
- // local authorities' adopted plans — and an observed land-use layer is a different database with a different
230
- // `layer_manifest.name`, never a row with a second grade in this table.
202
+ // One grade per claim: every row of this artifact is `authoritative`,
203
+ // and an observed land-use layer is a different database with a different
204
+ // `layer_manifest.name` rather than a row with a second grade in this table.
231
205
  GZT_PROVENANCE_GRADE,
232
206
  bbox.minLat,
233
207
  bbox.minLon,
@@ -259,10 +233,8 @@ export async function ingestZoningChunk(
259
233
  }
260
234
  }
261
235
 
262
- // COVERAGE IS DERIVED FROM THE UNCOMPACTED CLASSIFICATION, not from the stored rows. A compacted parent spans
263
- // several coverage cells and `addCoverageCells` handles that, but the fringe is where this product's cells almost
264
- // all are — so counting off the stored rows and counting off the classification agree here, and the classification
265
- // is the one that cannot be changed by a compaction decision.
236
+ // Coverage is derived from the uncompacted classification rather than the stored rows,
237
+ // since the classification is the one compaction cannot change.
266
238
  const coverageCells = new Set<number>()
267
239
 
268
240
  for (const cell of classified.whole) {
@@ -291,11 +263,10 @@ export async function ingestZoningChunk(
291
263
  })
292
264
  }
293
265
 
294
- // The local vocabulary is per AUTHORITY, because the codes collide across them: `Residential` means one thing in
295
- // Cork County Council's plan and another in Westmeath's.
266
+ // The local vocabulary is per authority, because codes collide across them.
296
267
  observe(localSchemeFor(feature.authorityCode), feature.localCode, feature.localDescription ?? feature.localCode)
297
268
 
298
- if (feature.crosswalkCode !== null) {
269
+ if (feature.crosswalkCode) {
299
270
  observe(GZT_CROSSWALK_SCHEME, feature.crosswalkCode, feature.crosswalkDescription ?? feature.crosswalkCode)
300
271
 
301
272
  const key = `${feature.authorityCode}\u0000${feature.localCode}`
@@ -312,7 +283,7 @@ export async function ingestZoningChunk(
312
283
  }
313
284
  }
314
285
 
315
- if (feature.crosswalkRollup !== null) {
286
+ if (feature.crosswalkRollup) {
316
287
  observe(GZT_ROLLUP_SCHEME, feature.crosswalkRollup, feature.crosswalkRollup)
317
288
  }
318
289
 
@@ -352,8 +323,8 @@ export async function ingestZoningChunk(
352
323
  }
353
324
 
354
325
  /**
355
- * One feature's own contribution, for a caller that wants the numbers without a database — the fixture rung's
356
- * arithmetic and nothing else.
326
+ * One feature's own contribution, for a caller that wants the numbers without a database —
327
+ * the fixture rung's arithmetic and no more.
357
328
  */
358
329
  export function featureAreaReadings(feature: ZoningSourceFeature): {
359
330
  signed: number
@@ -3,9 +3,7 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * One chunk of the zoning ingest, as its own process — spawned by `buildZoningDatabase`, never run by
7
- * hand. The process boundary and the stdout contract live with `runIngestChunkScript`; what stays here is
8
- * only this product's flags and its feature-source constructor.
6
+ * One chunk of the zoning ingest, as its own process — spawned by `buildZoningDatabase`, never run by hand.
9
7
  */
10
8
 
11
9
  import { requiredArgument } from "@mailwoman/core/scripting/arguments"
@@ -13,8 +11,8 @@ import { INGEST_CHUNK_FLAGS, runIngestChunkScript } from "@mailwoman/core/script
13
11
  import type { DatabaseClient } from "@mailwoman/sqlite/client"
14
12
 
15
13
  import type { ZoningDatabase } from "#schema"
14
+ import { createExportFeatureSource } from "#sdk/ingest"
16
15
  import { ingestZoningChunk } from "#sdk/ingest/chunk"
17
- import { createExportFeatureSource } from "#sdk/ingest/index"
18
16
 
19
17
  await runIngestChunkScript({
20
18
  context: "zoning ingest-chunk",
@@ -27,11 +25,11 @@ await runIngestChunkScript({
27
25
  run: async (database: DatabaseClient<ZoningDatabase>, values, chunk) =>
28
26
  ingestZoningChunk(database, {
29
27
  source: await createExportFeatureSource({
30
- exportPath: requiredArgument("zoning ingest-chunk", "export", values.export),
31
- ...(values["object-id-from"] === undefined ? {} : { objectIDFrom: Number(values["object-id-from"]) }),
32
- ...(values["object-id-to"] === undefined ? {} : { objectIDTo: Number(values["object-id-to"]) }),
33
- // A RANGE's own count is not knowable up front — the source reports a layer's total and nothing narrower — so
34
- // the chunk asserts nothing about its size and the PARENT checks the sum against the whole file.
28
+ exportPath: requiredArgument("zoning ingest-chunk", "export", values.export ?? null),
29
+ ...(values["object-id-from"] ? { objectIDFrom: Number(values["object-id-from"]) } : {}),
30
+ ...(values["object-id-to"] ? { objectIDTo: Number(values["object-id-to"]) } : {}),
31
+ // A range's count is not knowable up front: the source reports only the layer total,
32
+ // so the parent checks the sum against the whole file.
35
33
  declaredFeatureCount: 0,
36
34
  }),
37
35
  indexResolution: chunk.indexResolution,
package/sdk/ingest.ts ADDED
@@ -0,0 +1,354 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Streams the Department's bulk zoning export through ogr2ogr as reprojected WGS84 features.
7
+ *
8
+ * The stream uses CSV with WKT geometry because the source marks holes by ring orientation. GDAL's
9
+ * GeoJSON writer rewinds every ring to RFC 7946 order. That turns holes into zoned areas. The source is
10
+ * in EPSG:2157, declared in a legacy top-level `crs` member that GDAL honors.
11
+ */
12
+
13
+ import { declaredFeatureCount } from "@mailwoman/core/layers"
14
+ import { assertRingsInsideExtent, requireArealPolygons, type MultiPolygonRings } from "@mailwoman/spatial"
15
+ import { readOGRLayerIdentity, type OGRLayerSchema } from "@mailwoman/spatial/tools/ogr"
16
+ import { spawnOGR2OGR } from "@mailwoman/spatial/tools/ogr/stream"
17
+ import { wellKnownGeometryToGeoJSON } from "@mailwoman/spatial/well-known-text"
18
+ import { CSVSpliterator } from "spliterator"
19
+
20
+ import { resolveRingRoles, type ResolvedRingRoles } from "#rings"
21
+ import { GZT_DECLARED_BBOX, GZT_SOURCE_EPSG } from "#vocabulary"
22
+
23
+ /**
24
+ * One zoning feature, reprojected to WGS84 with its hole roles resolved.
25
+ */
26
+ export interface ZoningSourceFeature {
27
+ /**
28
+ * The authority's `objectid` as a string.
29
+ */
30
+ areaID: string
31
+ /**
32
+ * The `LA_CODE` value, verbatim.
33
+ * Fingal's unusual `Fl` code is kept as published.
34
+ */
35
+ authorityCode: string
36
+ authorityName: string
37
+ planID: string
38
+ planName: string
39
+ planLevel: string
40
+ planFrom: string | null
41
+ planTo: string | null
42
+ currentPlan: number
43
+ /**
44
+ * The `ZONE_ORIG` value, verbatim.
45
+ *
46
+ * Case and trailing spaces are kept because some codes differ only by them.
47
+ */
48
+ localCode: string
49
+ localDescription: string | null
50
+ localCodeURL: string | null
51
+ /**
52
+ * The `ZONE_GZT` value.
53
+ *
54
+ * It is the Department's national generic type for this polygon.
55
+ */
56
+ crosswalkCode: string | null
57
+ crosswalkDescription: string | null
58
+ /**
59
+ * The `SZO` value.
60
+ * It is the coarser national code as published.
61
+ */
62
+ crosswalkRollup: string | null
63
+ /**
64
+ * The rings with hole roles resolved from their orientation, plus a record of that resolution.
65
+ */
66
+ rings: ResolvedRingRoles
67
+ }
68
+
69
+ /**
70
+ * Options for reading the bulk export.
71
+ */
72
+ export interface ZoningIngestOptions {
73
+ /**
74
+ * The path of the bulk GeoJSON export.
75
+ */
76
+ exportPath: string
77
+ /**
78
+ * The maximum number of features to read.
79
+ * Fixture and smoke runs use it.
80
+ */
81
+ limit?: number
82
+ /**
83
+ * The EPSG code that the source must declare.
84
+ * A different code means the product has changed.
85
+ */
86
+ expectEPSG?: number
87
+ /**
88
+ * The extent that every reprojected vertex must fall inside.
89
+ *
90
+ * @defaultValue the Department's declared extent.
91
+ */
92
+ declaredBBox?: readonly [number, number, number, number]
93
+ /**
94
+ * The inclusive range of authority `objectid` values to read.
95
+ *
96
+ * The h3 wasm heap cannot be reset from JavaScript, so the build runs one child process per range.
97
+ * It uses `objectid` ranges because they select the same features on every run.
98
+ *
99
+ * Every range costs a full scan of the export, because the export is one GeoJSON document.
100
+ */
101
+ objectIDFrom?: number
102
+ objectIDTo?: number
103
+ /**
104
+ * Restricts the read to one local authority's `LA_CODE`, for smoke runs.
105
+ */
106
+ authorityCode?: string
107
+ }
108
+
109
+ /**
110
+ * The number of coordinate decimals that ogr2ogr writes.
111
+ * Nine decimals is far finer than the source's precision.
112
+ */
113
+ const COORDINATE_PRECISION = 9
114
+
115
+ /**
116
+ * The distance in degrees that a vertex may fall outside the declared extent.
117
+ *
118
+ * The published extent is rounded, so an exact test would fail on valid data.
119
+ * An unprojected or axis-swapped read lands much farther away and still fails.
120
+ */
121
+ const BBOX_MARGIN_DEGREES = 0.01
122
+
123
+ /**
124
+ * The attribute columns that the ingest reads.
125
+ * Every column is required.
126
+ */
127
+ export const ZONING_SOURCE_FIELDS: ReadonlyArray<string> = [
128
+ "OBJECTID",
129
+ "LA_CODE",
130
+ "LA_NAME",
131
+ "PLAN_ID",
132
+ "PLAN_NAME",
133
+ "PLAN_LEVEL",
134
+ "PLAN_FROM",
135
+ "PLAN_TO",
136
+ "CURRENT_PLAN",
137
+ "ZONE_ORIG",
138
+ "ZONE_DESC",
139
+ "ZONE_LINK",
140
+ "ZONE_GZT",
141
+ "GZT_DESC",
142
+ "SZO",
143
+ ]
144
+
145
+ /**
146
+ * Reads the source's declared projection, feature count and field list.
147
+ *
148
+ * @throws {Error} When the export is unreadable, when its declared EPSG code differs
149
+ * from `expectEPSG`, or when it lacks a field that the ingest reads.
150
+ */
151
+ export async function readZoningSourceIdentity(options: ZoningIngestOptions): Promise<OGRLayerSchema> {
152
+ const identity = await readOGRLayerIdentity({
153
+ path: options.exportPath,
154
+ expectEPSG: options.expectEPSG ?? GZT_SOURCE_EPSG,
155
+ context: "zoning ingest",
156
+ areaOfUse: "Ireland",
157
+ })
158
+
159
+ const missing = ZONING_SOURCE_FIELDS.filter((field) => field !== "OBJECTID" && !identity.fields.has(field))
160
+
161
+ // Given a missing column, `-select` makes ogr2ogr write an empty column without an error.
162
+ // This check turns a source schema change into an error that lists the missing columns.
163
+ if (missing.length) {
164
+ throw new Error(
165
+ `zoning ingest: ${options.exportPath} carries no ${missing.join(", ")} column(s) — ogr2ogr writes a missing column as empty rather than refusing, so a schema change would arrive as a stream of blank codes`
166
+ )
167
+ }
168
+
169
+ return { epsg: identity.epsg, featureCount: identity.featureCount, layer: identity.layer, fields: identity.fields }
170
+ }
171
+
172
+ /**
173
+ * Returns the `-where` arguments for a bounded chunk or a one-authority smoke run.
174
+ */
175
+ function whereClause(options: ZoningIngestOptions): string[] {
176
+ const bounds: string[] = []
177
+
178
+ if (options.objectIDFrom !== undefined) {
179
+ bounds.push(`OBJECTID >= ${options.objectIDFrom}`)
180
+ }
181
+
182
+ if (options.objectIDTo !== undefined) {
183
+ bounds.push(`OBJECTID <= ${options.objectIDTo}`)
184
+ }
185
+
186
+ if (options.authorityCode) {
187
+ bounds.push(`LA_CODE = '${options.authorityCode.replaceAll("'", "''")}'`)
188
+ }
189
+
190
+ return bounds.length ? ["-where", bounds.join(" AND ")] : []
191
+ }
192
+
193
+ /**
194
+ * Returns the value, or null when it is undefined or empty.
195
+ */
196
+ function blankToNull(value: string | null | undefined): string | null {
197
+ if (!value) return null
198
+
199
+ return value ?? null
200
+ }
201
+
202
+ /**
203
+ * Streams the export through ogr2ogr as reprojected WKT and checks every vertex against the declared extent.
204
+ *
205
+ * The extent check catches swapped coordinate axes.
206
+ * The projection check misses that error.
207
+ *
208
+ * @throws {Error} When ogr2ogr fails, when a feature has no geometry or a blank local code, when
209
+ * a reprojected vertex falls outside the declared extent, or when a feature's rings have no exterior.
210
+ */
211
+ export async function* readZoningFeatures(options: ZoningIngestOptions): AsyncGenerator<ZoningSourceFeature> {
212
+ const [minLon, minLat, maxLon, maxLat] = options.declaredBBox ?? GZT_DECLARED_BBOX
213
+
214
+ const args = [
215
+ "-f",
216
+ "CSV",
217
+ "/vsistdout/",
218
+ "-t_srs",
219
+ "EPSG:4326",
220
+ "-lco",
221
+ "GEOMETRY=AS_WKT",
222
+ "-lco",
223
+ "CREATE_CSVT=NO",
224
+ "-lco",
225
+ `COORDINATE_PRECISION=${COORDINATE_PRECISION}`,
226
+ "-select",
227
+ ZONING_SOURCE_FIELDS.join(","),
228
+ ...whereClause(options),
229
+ ...(options.limit === undefined ? [] : ["-limit", String(options.limit)]),
230
+ options.exportPath,
231
+ ]
232
+
233
+ const proc = spawnOGR2OGR(args, "zoning ingest")
234
+
235
+ try {
236
+ for await (const row of CSVSpliterator.fromAsync<Record<string, string>>(proc.stdout)) {
237
+ const areaID = row.objectid ?? ""
238
+
239
+ if (!areaID) {
240
+ throw new Error("zoning ingest: a row carries no OBJECTID — the authority's own key is the artifact's key")
241
+ }
242
+
243
+ const wkt = row.wkt
244
+
245
+ if (!wkt) {
246
+ throw new Error(`zoning ingest: feature ${areaID} carries no geometry`)
247
+ }
248
+
249
+ const polygons = normalizePolygons(wkt, `feature ${areaID}`)
250
+
251
+ assertRingsInsideExtent(
252
+ polygons,
253
+ `feature ${areaID}`,
254
+ { minLon, minLat, maxLon, maxLat },
255
+ BBOX_MARGIN_DEGREES,
256
+ "zoning ingest"
257
+ )
258
+
259
+ const localCode = row.zone_orig ?? ""
260
+
261
+ // The authority never publishes a zone without a code, so a blank code is an error.
262
+ if (!localCode) {
263
+ throw new Error(
264
+ `zoning ingest: feature ${areaID} carries a blank ZONE_ORIG — the authority's own code is the claim, so a blank is refused rather than stored`
265
+ )
266
+ }
267
+
268
+ yield {
269
+ areaID,
270
+ authorityCode: row.la_code ?? "",
271
+ authorityName: row.la_name ?? "",
272
+ planID: row.plan_id ?? "",
273
+ planName: row.plan_name ?? "",
274
+ planLevel: row.plan_level ?? "",
275
+ planFrom: blankToNull(row.plan_from),
276
+ planTo: blankToNull(row.plan_to),
277
+ currentPlan: Number(row.current_plan ?? 0),
278
+ // The code stays untrimmed because some distinct codes differ only by case or a trailing space.
279
+ localCode,
280
+ localDescription: blankToNull(row.zone_desc),
281
+ localCodeURL: blankToNull(row.zone_link),
282
+ crosswalkCode: blankToNull(row.zone_gzt),
283
+ crosswalkDescription: blankToNull(row.gzt_desc),
284
+ crosswalkRollup: blankToNull(row.szo),
285
+ rings: resolveRingRoles(polygons, areaID),
286
+ }
287
+ }
288
+ } finally {
289
+ proc.kill()
290
+ }
291
+
292
+ await proc.settled
293
+ }
294
+
295
+ /**
296
+ * Parses one WKT geometry into `MultiPolygon` rings.
297
+ *
298
+ * @throws {Error} When the geometry is neither a `Polygon` nor a `MultiPolygon`.
299
+ */
300
+ function normalizePolygons(wkt: string, label: string): MultiPolygonRings {
301
+ const geometry = wellKnownGeometryToGeoJSON<{ type: string; coordinates: unknown }>(wkt)
302
+
303
+ return requireArealPolygons(geometry, label, "zoning ingest")
304
+ }
305
+
306
+ /**
307
+ * Supplies a zoning build with its features and the source's declared identity.
308
+ *
309
+ * The builder takes this instead of a path so that fixtures can run the database
310
+ * build without network access or GDAL.
311
+ */
312
+ export interface ZoningFeatureSource {
313
+ /**
314
+ * The feature count that the source declares.
315
+ *
316
+ * The build throws when its streamed total differs from this count.
317
+ */
318
+ declaredFeatureCount: number
319
+ epsg: number
320
+ /**
321
+ * A description of where the features came from, such as the export path.
322
+ */
323
+ origin: string
324
+ features: () => AsyncIterable<ZoningSourceFeature>
325
+ }
326
+
327
+ /**
328
+ * Options for {@link createExportFeatureSource}.
329
+ */
330
+ export interface ExportSourceOptions extends ZoningIngestOptions {
331
+ declaredFeatureCount?: number
332
+ }
333
+
334
+ /**
335
+ * Creates a {@link ZoningFeatureSource} for the bulk export.
336
+ *
337
+ * It reads the export's identity immediately and streams features when asked.
338
+ */
339
+ export async function createExportFeatureSource(options: ExportSourceOptions): Promise<ZoningFeatureSource> {
340
+ const identity = await readZoningSourceIdentity(options)
341
+
342
+ return {
343
+ // The caller supplies the count for a range or one authority, because
344
+ // `ogrinfo` reports only the layer's total.
345
+ declaredFeatureCount: declaredFeatureCount({
346
+ declared: options.declaredFeatureCount,
347
+ limit: options.limit,
348
+ layerCount: identity.featureCount,
349
+ }),
350
+ epsg: identity.epsg,
351
+ origin: options.exportPath,
352
+ features: () => readZoningFeatures(options),
353
+ }
354
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The `partial` share cannot choose between candidate resolutions, so each is reported by candidates per cell and by the polyfill-only zero-cell count.
7
+ */
8
+
9
+ import type { ResolutionMeasurementOptions, ResolutionMeasurementReport } from "@mailwoman/core/layers"
10
+ import { classifyFeatureCells } from "@mailwoman/spatial"
11
+
12
+ import { polyfillFindsNothing, ZoningCellIndex, type CellIndexMeasurement } from "#sdk/cells"
13
+ import { readZoningFeatures, readZoningSourceIdentity, type ZoningIngestOptions } from "#sdk/ingest"
14
+
15
+ export interface MeasureResolutionsOptions extends ZoningIngestOptions, ResolutionMeasurementOptions {
16
+ /**
17
+ * Also runs a center-in-polygon polyfill per feature per resolution at the
18
+ * cost of one extra h3 call per feature.
19
+ */
20
+ measurePolyfill?: boolean
21
+ }
22
+
23
+ const DEFAULT_PROGRESS_EVERY = 5000
24
+
25
+ /**
26
+ * Measure every candidate resolution over the real source.
27
+ *
28
+ * @throws {Error} When the streamed feature count does not match the count the source declares.
29
+ */
30
+ export async function measureZoningCellResolutions(
31
+ options: MeasureResolutionsOptions
32
+ ): Promise<ResolutionMeasurementReport<CellIndexMeasurement>> {
33
+ const identity = await readZoningSourceIdentity(options)
34
+ const indexes = options.resolutions.map((resolution) => new ZoningCellIndex(resolution))
35
+ const progressEvery = options.progressEvery ?? DEFAULT_PROGRESS_EVERY
36
+ const measurePolyfill = options.measurePolyfill ?? true
37
+
38
+ let features = 0
39
+
40
+ for await (const feature of readZoningFeatures(options)) {
41
+ for (const index of indexes) {
42
+ index.add(classifyFeatureCells(feature.rings.polygons, index.resolution, feature.areaID, "zoning cells"))
43
+
44
+ if (measurePolyfill) {
45
+ index.addPolyfillProbe(polyfillFindsNothing(feature.rings.polygons, index.resolution))
46
+ }
47
+ }
48
+
49
+ features++
50
+
51
+ if (features % progressEvery === 0) {
52
+ options.onProgress?.(`${features.toLocaleString()} features classified`)
53
+ }
54
+ }
55
+
56
+ // A range or authority selector narrows the population on purpose,
57
+ // so the declared total is only checked on a whole pass.
58
+ const narrowed =
59
+ options.limit !== undefined || options.authorityCode !== undefined || options.objectIDFrom !== undefined
60
+
61
+ if (!narrowed && features !== identity.featureCount) {
62
+ throw new Error(
63
+ `zoning measure: streamed ${features} features, the source declares ${identity.featureCount} — a short read reports a smaller country rather than failing`
64
+ )
65
+ }
66
+
67
+ return {
68
+ features,
69
+ declaredFeatureCount: identity.featureCount,
70
+ measurements: indexes.map((index) => index.finish()),
71
+ }
72
+ }