@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,402 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Read the Department's bulk export as a stream of WGS84 features, through ogr2ogr.
7
+ *
8
+ * OGR IS BUILD TOOLING, NEVER A SERVE DEPENDENCY (SCOPE invariant 6). It converts the authority's geometry
9
+ * into the structure the runtime probes, and nothing downstream of this module knows GDAL exists.
10
+ *
11
+ * THE STREAM IS WKT, NOT GEOJSON, AND THAT IS A CORRECTNESS CHOICE RATHER THAN A TASTE ONE. This service
12
+ * encodes hole roles by ring ORIENTATION — clockwise exterior, the inverse of RFC 7946 — and puts each ring
13
+ * in its own `MultiPolygon` part on the features that carry holes that way. GDAL's GeoJSON writer enforces
14
+ * the RFC 7946 winding unconditionally: `-lco RFC7946=NO` is not a GeoJSONSeq option, and
15
+ * `--config OGR_ORGANIZE_POLYGONS SKIP` changes nothing. Measured on the largest feature in the country,
16
+ * Meath's `RA - Rural Area`: through GeoJSONSeq it arrives as 107 counter-clockwise rings totalling
17
+ * 2,371.9 km², through CSV/WKT as the source's own 5 clockwise and 102 counter-clockwise totalling
18
+ * 2,223.1 km² against the Department's published 2,232.1 km². The GeoJSON path has silently turned 102
19
+ * holes into 102 zoned areas.
20
+ *
21
+ * AND THE TRANSPORT IS NOT THE SLOW HALF. Measured on this lab over the whole national export: ogr2ogr
22
+ * reprojects to 224,066,621 bytes of WKT CSV in 13.2 s, and `CSVSpliterator` plus the WKT parse reads
23
+ * 85,330 rows, 93,483 rings and 6,327,256 positions back out of it in 2.2 s.
24
+ *
25
+ * THE SOURCE IS NOT IN WGS84 AND SAYING SO IS THE CHECK. The bulk export is IRENET95 / Irish Transverse
26
+ * Mercator — metres, easting/northing, EPSG:2157 — declared in a top-level `crs` member RFC 7946 removed
27
+ * from the format. GDAL honours the legacy member; a strict reader ignores it and places Ireland's zoning
28
+ * at latitude 735,435. So the projection is asserted against the source's declared authority code before a
29
+ * single feature is read, and every reprojected vertex is asserted inside the Department's own declared
30
+ * extent — which is the check that catches a coordinate-order mistake the projection check cannot see.
31
+ *
32
+ * THE DATUM SHIFT NEEDS A GRID, AND ITS ABSENCE IS SILENT. PROJ substitutes a ballpark offset when the
33
+ * accurate transformation is unavailable and produces coordinates that are metres wrong and
34
+ * indistinguishable from correct ones. {@linkcode assertDatumTransformationAvailable} asks `projinfo` what
35
+ * PROJ would choose and refuses a ballpark; for this source it names
36
+ * `Inverse of Irish Transverse Mercator + IRENET95 to WGS 84 (1), 1 m`.
37
+ *
38
+ * THE PUBLISHER'S OWN AREA COLUMN IS NOT IN THE ARCHIVE. `Shape__Area` is a service field and the export
39
+ * drops it, so the area cross-check reads it from the live service instead — which makes it a genuine
40
+ * two-path check rather than the archive agreeing with itself. See `sdk/client.ts`.
41
+ */
42
+
43
+ import { assertRingsInsideExtent, requireArealPolygons } from "@mailwoman/spatial"
44
+ import { readOGRLayerIdentity } from "@mailwoman/spatial/tools/ogr"
45
+ import { spawnOGR2OGR } from "@mailwoman/spatial/tools/ogr-stream"
46
+ import { wellKnownGeometryToGeoJSON } from "@mailwoman/spatial/well-known-text"
47
+ import { CSVSpliterator } from "spliterator"
48
+
49
+ import { resolveRingRoles, type MultiPolygonRings, type ResolvedRingRoles } from "#rings"
50
+ import { GZT_DECLARED_BBOX, GZT_SOURCE_EPSG } from "#vocabulary"
51
+
52
+ /**
53
+ * The ring types and the PROJ guard, both re-exported from `@mailwoman/spatial`: neither is zoning-specific, and a
54
+ * second copy of the `projinfo` parse would be a second place for the ballpark check to stop refusing.
55
+ */
56
+ export { assessDatumTransformation, type DatumTransformationVerdict } from "@mailwoman/spatial/projection-transform"
57
+ export type { MultiPolygonRings, PolygonRings } from "#rings"
58
+
59
+ /**
60
+ * One zoning feature, reprojected to WGS84 with its hole roles resolved.
61
+ */
62
+ export interface ZoningSourceFeature {
63
+ /**
64
+ * The authority's own `OBJECTID`, as a string.
65
+ */
66
+ areaID: string
67
+ /**
68
+ * `LA_CODE`, verbatim — `Fl` for Fingal, and never repaired.
69
+ */
70
+ authorityCode: string
71
+ authorityName: string
72
+ planID: string
73
+ planName: string
74
+ planLevel: string
75
+ planFrom: string | null
76
+ planTo: string | null
77
+ currentPlan: number
78
+ /**
79
+ * `ZONE_ORIG`, verbatim, including case and any trailing space.
80
+ */
81
+ localCode: string
82
+ localDescription: string | null
83
+ localCodeURL: string | null
84
+ /**
85
+ * `ZONE_GZT` — the Department's national generic type for THIS polygon.
86
+ */
87
+ crosswalkCode: string | null
88
+ crosswalkDescription: string | null
89
+ /**
90
+ * `SZO` — the coarser national code, as published.
91
+ */
92
+ crosswalkRollup: string | null
93
+ /**
94
+ * The rings, with hole roles resolved from orientation, plus the receipt of that resolution.
95
+ */
96
+ rings: ResolvedRingRoles
97
+ }
98
+
99
+ /**
100
+ * What the ingest was pointed at.
101
+ */
102
+ export interface ZoningIngestOptions {
103
+ /**
104
+ * Path to the bulk GeoJSON export.
105
+ */
106
+ exportPath: string
107
+ /**
108
+ * Stop after this many features — the fixtures and smoke rungs use it; a full build does not set it.
109
+ */
110
+ limit?: number
111
+ /**
112
+ * The EPSG code the source must declare. A source declaring anything else is a product change, not a variation to
113
+ * absorb.
114
+ */
115
+ expectEPSG?: number
116
+ /**
117
+ * The extent every reprojected vertex must land inside. Defaults to the Department's own declaration.
118
+ */
119
+ declaredBBox?: readonly [number, number, number, number]
120
+ /**
121
+ * Read only the authority's feature ids in `[objectIDFrom, objectIDTo]`, inclusive.
122
+ *
123
+ * This is what makes a bounded build possible: h3's WASM heap cannot be reset from JavaScript, so the classification
124
+ * runs one child process per range of the authority's OWN ids. Ranges rather than an offset because `OBJECTID` is the
125
+ * source's stable key — a range names the same features on every run, which an offset into a result set does not.
126
+ *
127
+ * A NARROWER RANGE COSTS A WHOLE PASS. The source is one GeoJSON document rather than an indexed store, so ogr2ogr
128
+ * scans all 247 MB for every range. The national set fits inside one chunk at the default bound, so that cost is not
129
+ * paid on a full build.
130
+ */
131
+ objectIDFrom?: number
132
+ objectIDTo?: number
133
+ /**
134
+ * Restrict to one local authority's own `LA_CODE` — the smoke rung.
135
+ */
136
+ authorityCode?: string
137
+ }
138
+
139
+ /**
140
+ * What the source declares about itself, read before any feature is.
141
+ */
142
+ export interface ZoningSourceIdentity {
143
+ epsg: number
144
+ featureCount: number
145
+ layer: string
146
+ /**
147
+ * The source's own attribute field names. A `-select` naming a column this set does not hold makes ogr2ogr write an
148
+ * empty column rather than refuse, so the query is built from the set rather than from a schema read off a sibling
149
+ * publication.
150
+ */
151
+ fields: ReadonlySet<string>
152
+ }
153
+
154
+ /**
155
+ * Coordinate decimals ogr2ogr writes into the stream. Nine is ~0.1 mm at this latitude — far past the source's own
156
+ * precision, and chosen so the reprojection contributes nothing measurable to the area cross-check.
157
+ */
158
+ const COORDINATE_PRECISION = 9
159
+
160
+ /**
161
+ * How far outside the declared extent a vertex may fall before the ingest refuses.
162
+ *
163
+ * A declared extent is itself a rounded published value, so an exact test would be brittle; this margin is small enough
164
+ * that an unprojected or axis-swapped read — which lands degrees or whole hemispheres away — still fails.
165
+ */
166
+ const BBOX_MARGIN_DEGREES = 0.01
167
+
168
+ /**
169
+ * The attribute columns the ingest reads. Every one is required: this product publishes a single schema, and a column
170
+ * that vanished would be a product change rather than a variation to absorb.
171
+ */
172
+ export const ZONING_SOURCE_FIELDS: ReadonlyArray<string> = [
173
+ "OBJECTID",
174
+ "LA_CODE",
175
+ "LA_NAME",
176
+ "PLAN_ID",
177
+ "PLAN_NAME",
178
+ "PLAN_LEVEL",
179
+ "PLAN_FROM",
180
+ "PLAN_TO",
181
+ "CURRENT_PLAN",
182
+ "ZONE_ORIG",
183
+ "ZONE_DESC",
184
+ "ZONE_LINK",
185
+ "ZONE_GZT",
186
+ "GZT_DESC",
187
+ "SZO",
188
+ ]
189
+
190
+ /**
191
+ * What the source declares about itself: its authority code, its feature count and its field list.
192
+ *
193
+ * @throws {Error} When the export is unreadable, its declared EPSG is not `expectEPSG`, or it is missing a field the
194
+ * ingest reads.
195
+ */
196
+ export async function readZoningSourceIdentity(options: ZoningIngestOptions): Promise<ZoningSourceIdentity> {
197
+ const identity = await readOGRLayerIdentity({
198
+ path: options.exportPath,
199
+ expectEPSG: options.expectEPSG ?? GZT_SOURCE_EPSG,
200
+ context: "zoning ingest",
201
+ areaOfUse: "Ireland",
202
+ })
203
+
204
+ const missing = ZONING_SOURCE_FIELDS.filter((field) => field !== "OBJECTID" && !identity.fields.has(field))
205
+
206
+ // `-select` on a missing column makes ogr2ogr write an EMPTY column rather than refuse, so a schema change would
207
+ // arrive as a stream of nulls: every local code blank, every plan unnamed, and a well-formed artifact describing
208
+ // nothing. Refused here instead, by name.
209
+ if (missing.length) {
210
+ throw new Error(
211
+ `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`
212
+ )
213
+ }
214
+
215
+ return { epsg: identity.epsg, featureCount: identity.featureCount, layer: identity.layer, fields: identity.fields }
216
+ }
217
+
218
+ /**
219
+ * The `-where` predicate for a bounded chunk or a one-authority smoke run.
220
+ */
221
+ function whereClause(options: ZoningIngestOptions): string[] {
222
+ const bounds: string[] = []
223
+
224
+ if (options.objectIDFrom !== undefined) {
225
+ bounds.push(`OBJECTID >= ${options.objectIDFrom}`)
226
+ }
227
+
228
+ if (options.objectIDTo !== undefined) {
229
+ bounds.push(`OBJECTID <= ${options.objectIDTo}`)
230
+ }
231
+
232
+ if (options.authorityCode !== undefined) {
233
+ bounds.push(`LA_CODE = '${options.authorityCode.replaceAll("'", "''")}'`)
234
+ }
235
+
236
+ return bounds.length ? ["-where", bounds.join(" AND ")] : []
237
+ }
238
+
239
+ /**
240
+ * A published value, as a string or null. An EMPTY STRING IS NOT NULL HERE for the local code, which is the one column
241
+ * this layer exists to repeat: a blank one is refused by the ingest rather than stored.
242
+ */
243
+ function blankToNull(value: string | undefined): string | null {
244
+ if (value === undefined) return null
245
+
246
+ return value.length ? value : null
247
+ }
248
+
249
+ /**
250
+ * Stream the export through ogr2ogr as reprojected WKT, checking every vertex against the declared extent.
251
+ *
252
+ * A swapped coordinate order survives a projection check — both axes are still numbers in a plausible range — and shows
253
+ * up here immediately, before 85,330 polygons are written to the wrong side of the planet.
254
+ *
255
+ * @throws {Error} When ogr2ogr fails, when a feature carries no geometry, when a reprojected vertex falls outside the
256
+ * declared extent, or when a feature's rings cannot be resolved into at least one exterior.
257
+ */
258
+ export async function* readZoningFeatures(options: ZoningIngestOptions): AsyncGenerator<ZoningSourceFeature> {
259
+ const [minLon, minLat, maxLon, maxLat] = options.declaredBBox ?? GZT_DECLARED_BBOX
260
+
261
+ const args = [
262
+ "-f",
263
+ "CSV",
264
+ "/vsistdout/",
265
+ "-t_srs",
266
+ "EPSG:4326",
267
+ "-lco",
268
+ "GEOMETRY=AS_WKT",
269
+ "-lco",
270
+ "CREATE_CSVT=NO",
271
+ "-lco",
272
+ `COORDINATE_PRECISION=${COORDINATE_PRECISION}`,
273
+ "-select",
274
+ ZONING_SOURCE_FIELDS.join(","),
275
+ ...whereClause(options),
276
+ ...(options.limit === undefined ? [] : ["-limit", String(options.limit)]),
277
+ options.exportPath,
278
+ ]
279
+
280
+ const proc = spawnOGR2OGR(args, "zoning ingest")
281
+
282
+ try {
283
+ for await (const row of CSVSpliterator.fromAsync<Record<string, string>>(proc.stdout, {
284
+ mode: "object",
285
+ // Opt-in end-to-end quoting: the WKT column carries commas and spaces on every row, so a reader without it
286
+ // mis-splits every feature into hundreds of columns.
287
+ enableQuoteHandling: true,
288
+ })) {
289
+ const areaID = row.OBJECTID ?? ""
290
+
291
+ if (!areaID) {
292
+ throw new Error("zoning ingest: a row carries no OBJECTID — the authority's own key is the artifact's key")
293
+ }
294
+
295
+ const wkt = row.WKT
296
+
297
+ if (!wkt) {
298
+ throw new Error(`zoning ingest: feature ${areaID} carries no geometry`)
299
+ }
300
+
301
+ const polygons = normalizePolygons(wkt, `feature ${areaID}`)
302
+
303
+ assertRingsInsideExtent(
304
+ polygons,
305
+ `feature ${areaID}`,
306
+ { minLon, minLat, maxLon, maxLat },
307
+ BBOX_MARGIN_DEGREES,
308
+ "zoning ingest"
309
+ )
310
+
311
+ const localCode = row.ZONE_ORIG ?? ""
312
+
313
+ // The local code is what this layer exists to repeat, so a blank one is refused rather than stored: it would read
314
+ // as a zone the authority named nothing, which is not a reading the authority ever makes.
315
+ if (!localCode.trim()) {
316
+ throw new Error(
317
+ `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`
318
+ )
319
+ }
320
+
321
+ yield {
322
+ areaID,
323
+ authorityCode: row.LA_CODE ?? "",
324
+ authorityName: row.LA_NAME ?? "",
325
+ planID: row.PLAN_ID ?? "",
326
+ planName: row.PLAN_NAME ?? "",
327
+ planLevel: row.PLAN_LEVEL ?? "",
328
+ planFrom: blankToNull(row.PLAN_FROM),
329
+ planTo: blankToNull(row.PLAN_TO),
330
+ currentPlan: Number(row.CURRENT_PLAN ?? 0),
331
+ // VERBATIM, and deliberately un-trimmed: `Proposed Residential ` carries a trailing space in the source, and
332
+ // five of the 581 distinct strings collide with another only on case or that space.
333
+ localCode,
334
+ localDescription: blankToNull(row.ZONE_DESC),
335
+ localCodeURL: blankToNull(row.ZONE_LINK),
336
+ crosswalkCode: blankToNull(row.ZONE_GZT),
337
+ crosswalkDescription: blankToNull(row.GZT_DESC),
338
+ crosswalkRollup: blankToNull(row.SZO),
339
+ rings: resolveRingRoles(polygons, areaID),
340
+ }
341
+ }
342
+ } finally {
343
+ proc.kill()
344
+ }
345
+
346
+ await proc.settled
347
+ }
348
+
349
+ /**
350
+ * Parse one WKT geometry into the ring shape the rest of this package works in.
351
+ *
352
+ * @throws {Error} When the geometry is neither a `Polygon` nor a `MultiPolygon`.
353
+ */
354
+ function normalizePolygons(wkt: string, label: string): MultiPolygonRings {
355
+ const geometry = wellKnownGeometryToGeoJSON<{ type: string; coordinates: unknown }>(wkt)
356
+
357
+ return requireArealPolygons(geometry, label, "zoning ingest")
358
+ }
359
+
360
+ /**
361
+ * Where a build's features come from, and what the source declares about itself.
362
+ *
363
+ * The builder takes ONE of these rather than a path, which is what makes the fixture rung possible: hand-built geometry
364
+ * with no network and no GDAL still exercises the whole database half — the domain checks, the ring-role resolution,
365
+ * the cell classification, the coverage rows, the manifest and the seal. A fixture rung that could only run through
366
+ * ogr2ogr would test the conversion on the machines that have it and nothing at all on the ones that do not.
367
+ */
368
+ export interface ZoningFeatureSource {
369
+ /**
370
+ * What the source says it holds. The build compares its own streamed total against this, so a short read throws
371
+ * instead of building a smaller country.
372
+ */
373
+ declaredFeatureCount: number
374
+ epsg: number
375
+ /**
376
+ * A description of where these features came from, for the receipt.
377
+ */
378
+ origin: string
379
+ features: () => AsyncIterable<ZoningSourceFeature>
380
+ }
381
+
382
+ export interface ExportSourceOptions extends ZoningIngestOptions {
383
+ declaredFeatureCount?: number
384
+ }
385
+
386
+ /**
387
+ * The bulk export as a feature source — identity read up front, features streamed on demand.
388
+ */
389
+ export async function createExportFeatureSource(options: ExportSourceOptions): Promise<ZoningFeatureSource> {
390
+ const identity = await readZoningSourceIdentity(options)
391
+
392
+ return {
393
+ // A RANGE's or an authority's own count is supplied by the caller, because `ogrinfo` reports a layer's total and
394
+ // nothing narrower.
395
+ declaredFeatureCount:
396
+ options.declaredFeatureCount ??
397
+ (options.limit === undefined ? identity.featureCount : Math.min(options.limit, identity.featureCount)),
398
+ epsg: identity.epsg,
399
+ origin: options.exportPath,
400
+ features: () => readZoningFeatures(options),
401
+ }
402
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The index resolution is a MEASUREMENT this layer takes, not a number argued to — and for this subject the
7
+ * inherited size contract's own statistic is not the one that decides it.
8
+ *
9
+ * THE `partial` SHARE CARRIES NO SIGNAL HERE, AND THAT WAS MEASURED. Computed over all 85,330 Irish
10
+ * features, the median zoning polygon is 4,497 m² against an average res-9 cell of 105,333 m²: 95.7% of
11
+ * them are smaller than a res-9 cell, 75.1% smaller than a res-10 cell and 34.5% smaller than a res-11 one.
12
+ * So the `partial` share sits near 100% at every candidate and cannot choose between them.
13
+ *
14
+ * TWO NUMBERS CAN. CANDIDATES PER CELL is what a probe pays — a cell naming eight polygons is eight
15
+ * bounding-box tests and up to eight ray casts — and the POLYFILL-ONLY ZERO-CELL COUNT is how many features
16
+ * the obvious index would have dropped, each of which would read downstream as an absence of zoning. Both
17
+ * are reported per resolution and the `partial` share rides beside them.
18
+ *
19
+ * ONE STREAM, EVERY RESOLUTION. Re-reading the export per candidate costs a full pass each and buys
20
+ * nothing — the classification is per feature, so every candidate index folds the same feature in turn. The
21
+ * cost is memory: each resolution holds its own cell sets, and the finest candidate dominates. A caller that
22
+ * runs out of headroom runs the candidates in separate invocations.
23
+ */
24
+
25
+ import type { ResolutionMeasurementOptions } from "@mailwoman/core/layers"
26
+
27
+ import { polyfillFindsNothing, ZoningCellIndex, classifyFeatureCells, type CellIndexMeasurement } from "#sdk/cells"
28
+ import { readZoningFeatures, readZoningSourceIdentity, type ZoningIngestOptions } from "#sdk/ingest"
29
+
30
+ export interface MeasureResolutionsOptions extends ZoningIngestOptions, ResolutionMeasurementOptions {
31
+ /**
32
+ * Also run a centre-in-polygon polyfill per feature per resolution, to report what a polyfill-only index would have
33
+ * dropped. On by default: it is the column the resolution is chosen on, and its cost is one extra h3 call per
34
+ * feature.
35
+ */
36
+ measurePolyfill?: boolean
37
+ }
38
+
39
+ export interface ResolutionMeasurementReport {
40
+ features: number
41
+ /**
42
+ * The count the source declares for itself. A run whose streamed total differs read a truncated file.
43
+ */
44
+ declaredFeatureCount: number
45
+ measurements: CellIndexMeasurement[]
46
+ }
47
+
48
+ const DEFAULT_PROGRESS_EVERY = 5000
49
+
50
+ /**
51
+ * Measure every candidate resolution over the real source.
52
+ *
53
+ * @throws {Error} When the streamed feature count does not match the count the source declares. A short read produces a
54
+ * well-formed table describing a smaller country, which is the partial result that must throw.
55
+ */
56
+ export async function measureZoningCellResolutions(
57
+ options: MeasureResolutionsOptions
58
+ ): Promise<ResolutionMeasurementReport> {
59
+ const identity = await readZoningSourceIdentity(options)
60
+ const indexes = options.resolutions.map((resolution) => new ZoningCellIndex(resolution))
61
+ const progressEvery = options.progressEvery ?? DEFAULT_PROGRESS_EVERY
62
+ const measurePolyfill = options.measurePolyfill ?? true
63
+
64
+ let features = 0
65
+
66
+ for await (const feature of readZoningFeatures(options)) {
67
+ for (const index of indexes) {
68
+ index.add(classifyFeatureCells(feature.rings.polygons, index.resolution, feature.areaID, "zoning cells"))
69
+
70
+ if (measurePolyfill) {
71
+ index.addPolyfillProbe(polyfillFindsNothing(feature.rings.polygons, index.resolution))
72
+ }
73
+ }
74
+
75
+ features++
76
+
77
+ if (features % progressEvery === 0) {
78
+ options.onProgress?.(`${features.toLocaleString()} features classified`)
79
+ }
80
+ }
81
+
82
+ // A RANGE or an authority selector narrows the population on purpose, so the declared total is only a check on a whole
83
+ // pass. Narrowed runs report what they read and assert nothing about it.
84
+ const narrowed =
85
+ options.limit !== undefined || options.authorityCode !== undefined || options.objectIDFrom !== undefined
86
+
87
+ if (!narrowed && features !== identity.featureCount) {
88
+ throw new Error(
89
+ `zoning measure: streamed ${features} features, the source declares ${identity.featureCount} — a short read reports a smaller country rather than failing`
90
+ )
91
+ }
92
+
93
+ return {
94
+ features,
95
+ declaredFeatureCount: identity.featureCount,
96
+ measurements: indexes.map((index) => index.finish()),
97
+ }
98
+ }
99
+
100
+ export { formatResolutionRows } from "#sdk/cells"