districtShapes.test.ts
21.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
// @vitest-environment node
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import {
districtShape,
districtShapes,
hasDistrictShapes,
matchDistrictShapes,
pointInPolygon,
polygonsAreaKm2,
districtAtPoint,
type DistrictShape,
type LngLat,
type ShapePolygon,
} from './districtShapes';
/**
* 区界数据对账(真实边界文件 + 真实区字典)。
*
* 这一层是界面上唯一一个「照行政边界涂整片」的读数:牌子念起数、深浅念密度,
* 而密度是 count ÷ areaKm2。所以这里要钉的不是「代码跑不跑」,而是四件会闹乌龙的事:
*
* 1. **名称对得上**。区名来自地址解析,边界名来自行政区文件。对不上就把别人的案子涂进这块界,
* 屏上不会报错,只会数错。所以按真实区字典走一遍匹配,并核 adcode ——
* adcode 与名称是两条独立证据,两者一起对上才算对上(名称写法变了而 adcode 没变,会在这里露出来)。
* 2. **面积没算错**。面积只由这一份边界数据算出,密度全靠它。这里用**另一套公式**(球面多边形面积)
* 独立重算一遍,两套写法只有在等距圆柱近似成立时才给出同样的数;差得多说明换算或者洞口符号错了。
* 另外拿公开资料里各辖区面积的数量级做交叉核对:读法(平方公里)错了会是 100 倍或 100 万倍的错,
* 当场就能看出来。
* 3. **点在哪个区判得对**。区界聚焦里点一块区域开的是那一档的清单,判据用真实多边形射线法;
* bbox 或者质心距离都会把隔壁区的案子算进这一档。这里既拿配置里 74 个真实地标做正例,
* 也拿边界外的点、洞里的点做反例。
* 4. **缺数据要说话**。大鹏新区在区字典里有、边界文件里没有(它不是行政区,adcode 表里就没有这一档),
* 「未识别」更不该有地户口。这两件事都必须由 withoutShape / 匹配结果交代,不能沉默地少涂一块。
*
* ⚠️ 本文件不调 ensureDistrictShapes():它走 fetch,而 node 环境没有那个静态服务,
* 拉取必然失败。测试直接喂文件内容给 matchDistrictShapes —— 加载那一跳由界面自己负责。
*/
const SHENZHEN = new URL('../../../../public/geo/shenzhen.geojson', import.meta.url);
const CONFIG = new URL('../../../../config/shenzhen-districts.json', import.meta.url);
/** 真实区字典的写法(与 meta.dict.districts 同一套:区名 + 末尾「未识别」) */
const DICT = [
'福田区',
'罗湖区',
'南山区',
'宝安区',
'龙岗区',
'龙华区',
'盐田区',
'光明区',
'坪山区',
'大鹏新区',
'未识别',
];
const real = JSON.parse(readFileSync(SHENZHEN, 'utf8')) as unknown;
/**
* 公开资料里的辖区面积(平方公里),只做数量级核对,不是边界文件的算法。
*
* 龙岗区界这一档要特别说明:行政区代码表里没有「大鹏新区」(它不是行政区,是功能区),
* 边界文件因此把大鹏半岛画进了 440307 龙岗区那一支里。所以拿龙岗单独的面积比会差出一倍,
* 拿「龙岗 + 大鹏」的和比才对得上 —— 下面那条 775.9 就是按这个和卡的。
* 这一句同时解释了界面为什么要单列「大鹏新区没有区界可涂」:它有起数、没有自己的边界。
*/
const PUBLISHED_KM2: Array<{ name: string; km2: number; note: string }> = [
{ name: '罗湖区', km2: 78.9, note: '辖区面积' },
{ name: '福田区', km2: 78.7, note: '辖区面积' },
{ name: '南山区', km2: 185.3, note: '辖区面积(含离岛)' },
{ name: '宝安区', km2: 397.0, note: '辖区面积(含离岛)' },
// 龙岗那一支按「龙岗 + 大鹏」的和来对:见上面那段说明,这一档不对上这个和就是边界读错了
{ name: '龙岗区', km2: 388.5 + 296.7, note: '龙岗辖区 + 大鹏半岛' },
{ name: '盐田区', km2: 74.7, note: '辖区面积' },
{ name: '龙华区', km2: 175.6, note: '辖区面积' },
{ name: '坪山区', km2: 166.0, note: '辖区面积' },
{ name: '光明区', km2: 181.2, note: '辖区面积' },
];
/** 大鹏新区按公开资料的面积(平方公里),只用于上面那条合成口径的核对 */
const DAPENG_KM2 = 296.7;
/** 球面多边形面积的三角和公式(Chamberlain–Duquette),返回带符号的平方米 */
function ringSphere(ring: LngLat[]): number {
const rad = (d: number) => (d * Math.PI) / 180;
let s = 0;
for (let i = 0; i + 1 < ring.length; i += 1) {
const [lng1, lat1] = ring[i];
const [lng2, lat2] = ring[i + 1];
s += (rad(lng2) - rad(lng1)) * (2 + Math.sin(rad(lat1)) + Math.sin(rad(lat2)));
}
return (s * 6378137 * 6378137) / 2;
}
/** 球面多边形面积(平方公里):与实现里的等距圆柱算法是两套写法 */
function sphereAreaKm2(polys: ShapePolygon[]): number {
let km2 = 0;
for (const p of polys) {
const outer = p.rings[0];
if (!outer) continue;
let a = Math.abs(ringSphere(outer));
for (let i = 1; i < p.rings.length; i += 1) a -= Math.abs(ringSphere(p.rings[i]));
km2 += Math.max(a, 0) / 1e6;
}
return km2;
}
const match = matchDistrictShapes(real, DICT);
const byName = new Map<string, DistrictShape>(match.shapes.map((s) => [s.name, s]));
describe('区界 · 名称匹配', () => {
it('边界文件里的 9 个区全部对上区字典,且 adcode 与名称一起对上', () => {
expect(match.shapes).toHaveLength(9);
expect(match.extraInFile).toEqual([]);
const ADcode: Record<string, string> = {
罗湖区: '440303',
福田区: '440304',
南山区: '440305',
宝安区: '440306',
龙岗区: '440307',
盐田区: '440308',
龙华区: '440309',
坪山区: '440310',
光明区: '440311',
};
for (const [name, adcode] of Object.entries(ADcode)) {
const s = byName.get(name);
expect(s, name).toBeDefined();
expect(s?.adcode).toBe(adcode);
// 下标必须是区字典里那一支的下标:统计、筛选、清单都按下标走,错一位就把别的区的起数念出来
expect(s?.idx).toBe(DICT.indexOf(name));
}
});
it('大鹏新区与「未识别」:一个报出来,一个不占地户口', () => {
expect(match.withoutShape).toEqual(['大鹏新区']);
expect(match.withoutShape).not.toContain('未识别');
expect(byName.has('大鹏新区')).toBe(false);
});
it('字典顺序变了不影响对上,名称写法变了就报出来', () => {
const shuffled = matchDistrictShapes(real, [...DICT].reverse());
expect(shuffled.shapes).toHaveLength(9);
expect(shuffled.extraInFile).toEqual([]);
// 反序之后「罗湖区」的下标跟着名单走,不是照文件顺序硬编
expect(shuffled.shapes.find((s) => s.name === '罗湖区')?.idx).toBe(
[...DICT].reverse().indexOf('罗湖区'),
);
// 字典里把「罗湖区」写成带市名前缀的样子:文件那一支就对不上了,两头都得说话
const renamed = matchDistrictShapes(
real,
DICT.map((n) => (n === '罗湖区' ? '深圳市罗湖区' : n)),
);
expect(renamed.shapes).toHaveLength(8);
expect(renamed.extraInFile).toEqual(['罗湖区']);
expect(renamed.withoutShape).toEqual(['深圳市罗湖区', '大鹏新区']);
});
it('坏数据在解析这一步就抛出来,不画半块边界', () => {
expect(() => matchDistrictShapes({ type: 'Feature' }, DICT)).toThrow(/FeatureCollection/);
expect(() => matchDistrictShapes(null, DICT)).toThrow(/FeatureCollection/);
});
it('几何残缺的要素不进门:没有名字、没有环、点不够的都跳过', () => {
const fc = {
type: 'FeatureCollection',
features: [
{
properties: { name: '', adcode: '440300' },
geometry: {
type: 'Polygon',
coordinates: [
[
[113, 22],
[114, 22],
[114, 23],
[113, 22],
],
],
},
},
{
properties: { name: '罗湖区', adcode: '440303' },
geometry: { type: 'Point', coordinates: [114, 22] },
},
{
properties: { name: '福田区', adcode: '440304' },
geometry: {
type: 'Polygon',
coordinates: [
[
[114, 22],
[114.1, 22],
],
],
},
},
],
};
const m = matchDistrictShapes(fc, DICT);
expect(m.shapes).toHaveLength(0);
// 名称没对上的那一条(空名)不进 extraInFile:空名报出来界面只会多一个看不懂的破口
expect(m.extraInFile).toEqual([]);
});
it('同名只取第一块:重复要素不会把起数画两遍', () => {
const poly = {
type: 'Polygon',
coordinates: [
[
[114, 22.5],
[114.1, 22.5],
[114.1, 22.6],
[114, 22.6],
[114, 22.5],
],
],
};
const m = matchDistrictShapes(
{
type: 'FeatureCollection',
features: [
{ properties: { name: '罗湖区', adcode: '440303' }, geometry: poly },
{ properties: { name: '罗湖区', adcode: '440303' }, geometry: poly },
],
},
DICT,
);
expect(m.shapes).toHaveLength(1);
});
it('区名两侧的空格吃掉:文件里写「 罗湖区」也照样对上', () => {
const m = matchDistrictShapes(
{
type: 'FeatureCollection',
features: [
{
properties: { name: ' 罗湖区 ', adcode: '440303' },
geometry: {
type: 'Polygon',
coordinates: [
[
[114, 22.5],
[114.1, 22.5],
[114.1, 22.6],
[114, 22.5],
],
],
},
},
],
},
DICT,
);
expect(m.shapes.map((s) => s.name)).toEqual(['罗湖区']);
});
it('不闭合的环补上首点,带 NaN 的点丢掉:界面拿到的环一定是闭合的', () => {
for (const s of match.shapes) {
for (const p of s.polys) {
for (const ring of p.rings) {
expect(ring.length).toBeGreaterThanOrEqual(4);
const head = ring[0];
const tail = ring[ring.length - 1];
expect(tail[0]).toBe(head[0]);
expect(tail[1]).toBe(head[1]);
for (const [lng, lat] of ring) {
expect(Number.isFinite(lng)).toBe(true);
expect(Number.isFinite(lat)).toBe(true);
}
}
}
}
});
});
describe('区界 · 面积(深浅编码的分母)', () => {
it('面积与另一套球面公式对得上(等距圆柱近似在这个尺度成立)', () => {
for (const s of match.shapes) {
const mine = sphereAreaKm2(s.polys);
// 两套写法在区界尺度上的差在 1% 以内;差出这个量级就是换算或洞口符号错了
expect(s.areaKm2, s.name).toBeGreaterThan(mine * 0.985);
expect(s.areaKm2, s.name).toBeLessThan(mine * 1.015);
}
});
it('面积量级对得上公开资料:读法(平方公里)错了会差出倍数', () => {
for (const { name, km2, note } of PUBLISHED_KM2) {
const s = byName.get(name);
expect(s, name).toBeDefined();
// 边界文件按落点取点,与公开资料的口径(含海域、含离岛与否)本来就有几个百分点到几成的差,
// 这里只卡数量级:差 100 倍(公顷读成平方公里)或 1e6 倍(平方米读成平方公里)必须当场失败
expect(s?.areaKm2, `${name}(对的是${note})`).toBeGreaterThan(km2 * 0.7);
expect(s?.areaKm2, `${name}(对的是${note})`).toBeLessThan(km2 * 1.4);
}
});
it('大鹏新区那一片在地面上属于龙岗区界:牌子涂不出,但界内的确是它的', () => {
// 这条不是「顺手记一笔」,是区界聚焦里唯一一处会让人读错的接缝:
// 屏上大鹏半岛那一片会被涂进龙岗区那一块,而那一处的案件记在大鹏新区名下、不进龙岗那一档。
// 界面已经把这句话说全(榜单那一档摘掉、说明里写「没有区界可涂」),这里把它钉住,
// 换成街道级边界之后这条会自然失效 —— 那时候该断言的是葵涌/大鹏/南澳三块拼得出大鹏新区。
const longgang = byName.get('龙岗区');
expect(longgang).toBeDefined();
const cfg = JSON.parse(readFileSync(CONFIG, 'utf8')) as {
districts: Array<{
name: string;
hotspots: Array<{ street: string; lng: number; lat: number }>;
}>;
};
const dapeng = cfg.districts.find((d) => d.name === '大鹏新区');
expect(dapeng?.hotspots.length).toBeGreaterThan(0);
for (const h of dapeng?.hotspots ?? []) {
expect(districtAtPoint(longgang!, h.lng, h.lat), h.street).toBe(true);
}
// 龙岗区界因此比「龙岗」单独的面积大出一截:深浅那一分母读的是整片,写清楚
expect(longgang!.areaKm2).toBeGreaterThan(388.5 + DAPENG_KM2);
});
it('区与区的大小关系照真实的来:龙岗不是罗湖的几倍就没法解释深浅', () => {
const luohu = byName.get('罗湖区')?.areaKm2 ?? 0;
const longgang = byName.get('龙岗区')?.areaKm2 ?? 0;
expect(longgang).toBeGreaterThan(luohu * 5);
// 每一档都得有正面积:0 会让图层把面积兜底成 0.01,密度爆成天文数字,整片涂成最深那一档
for (const s of match.shapes) expect(s.areaKm2, s.name).toBeGreaterThan(1);
const total = match.shapes.reduce((a, s) => a + s.areaKm2, 0);
expect(total).toBeGreaterThan(1500);
expect(total).toBeLessThan(2500);
});
it('洞从面积里减掉,多块相加', () => {
const outer: LngLat[] = [
[0, 0],
[0, 1],
[1, 1],
[1, 0],
[0, 0],
];
const hole: LngLat[] = [
[0.25, 0.25],
[0.25, 0.75],
[0.75, 0.75],
[0.75, 0.25],
[0.25, 0.25],
];
const one = polygonsAreaKm2([{ rings: [outer] }]);
const withHole = polygonsAreaKm2([{ rings: [outer, hole] }]);
// 洞是外沿面积的 25%:减掉了就该是四分之三,没减掉就是 1
expect(withHole).toBeGreaterThan(one * 0.7);
expect(withHole).toBeLessThan(one * 0.8);
// 两块各算一次,不是一块的两倍
const twoPieces = polygonsAreaKm2([{ rings: [outer] }, { rings: [outer] }]);
expect(twoPieces).toBeCloseTo(one * 2, 6);
});
});
describe('区界 · 点在哪个区', () => {
/**
* 配置里的热点是「真实地标的近似坐标」(配置自己的注释就这么写的,zone bbox 也声明不对应法定边界),
* 所以这一条不是把边界和落点绑死,而是反过来用:拿 74 个人肉可核的位置问一句
* 「边界文件把它们认成哪个区了」。认错的都在下面那份名单里写明落在哪个区 ——
* 名单外的一个都不许变,边界数据换了版本、或者取点少了几个,这里就会叫。
*/
it('配置地标落在自己的区界里;对不上的那几个是配置坐标偏了,逐处写明落在谁界内', () => {
const cfg = JSON.parse(readFileSync(CONFIG, 'utf8')) as {
districts: Array<{
name: string;
hotspots: Array<{ street: string; name: string; lng: number; lat: number }>;
}>;
};
/** 谁界内都没有的,以及认到隔壁区去的(配置近似坐标偏了,不是边界读错) */
const knownOff = new Set([
'宝安区/燕罗街道', // 燕罗在光明与宝安的界边附近
'龙岗区/平湖街道',
'光明区/马田街道',
'坪山区/龙田街道',
]);
let own = 0;
let off = 0;
for (const d of cfg.districts) {
for (const h of d.hotspots) {
const shape = byName.get(d.name);
if (!shape) continue; // 大鹏新区没有边界,由 withoutShape 那条交代
const key = `${d.name}/${h.street}`;
const hit = districtAtPoint(shape, h.lng, h.lat);
if (hit) own += 1;
else off += 1;
expect(hit || knownOff.has(key), `${key} 落在哪一界里,名单没跟上`).toBe(true);
}
}
expect(own).toBe(67);
expect(off).toBe(4);
});
it('一个点只属于一个区:区界之间不重叠,隔壁区的案子不会被算进这一档', () => {
const cfg = JSON.parse(readFileSync(CONFIG, 'utf8')) as {
districts: Array<{
name: string;
hotspots: Array<{ street: string; lng: number; lat: number }>;
}>;
};
for (const d of cfg.districts) {
for (const h of d.hotspots) {
const owners = match.shapes.filter((s) => districtAtPoint(s, h.lng, h.lat));
// 0 是允许的(配置坐标偏到界外),2 就一定是边界数据出问题了
expect(owners.length, `${d.name}/${h.street}`).toBeLessThan(2);
}
}
});
it('界外判界外:罗湖的点到福田、南山区都说不算它的', () => {
const luohu = byName.get('罗湖区');
expect(luohu).toBeDefined();
// 深圳湾在罗湖以西几十公里
expect(districtAtPoint(luohu!, 113.915, 22.495)).toBe(false);
// 海里的点
expect(districtAtPoint(luohu!, 114.15, 22.4)).toBe(false);
// bbox 里但界外:罗湖 bbox 的西南角实际落在福田/南山
expect(luohu!.bbox.minLng).toBeLessThan(114.1);
expect(districtAtPoint(luohu!, luohu!.bbox.minLng + 0.001, luohu!.bbox.minLat + 0.001)).toBe(
false,
);
});
it('洞里的点不算界内,凹进去的那一块也不算', () => {
const poly: ShapePolygon = {
rings: [
[
[0, 0],
[0, 4],
[4, 4],
[4, 0],
[0, 0],
],
[
[1, 1],
[1, 3],
[3, 3],
[3, 1],
[1, 1],
],
],
};
expect(pointInPolygon(0.5, 0.5, poly)).toBe(true);
expect(pointInPolygon(2, 2, poly)).toBe(false); // 洞里
expect(pointInPolygon(-1, 2, poly)).toBe(false);
expect(pointInPolygon(5, 2, poly)).toBe(false);
// 环的顶点正好与判据同高:半开取舍不能把它数两遍(数两遍就把界外读成界内)
expect(pointInPolygon(4.5, 1, poly)).toBe(false);
expect(pointInPolygon(4.5, 3, poly)).toBe(false);
// 多块里任何一块都算,飞地也是它的地:拿合成 MultiPolygon 走一遍真实入口
const island: ShapePolygon = {
rings: [
[
[10, 10],
[10, 11],
[11, 11],
[11, 10],
[10, 10],
],
],
};
const multi = matchDistrictShapes(
{
type: 'FeatureCollection',
features: [
{
properties: { name: '罗湖区', adcode: '440303' },
geometry: {
type: 'MultiPolygon',
coordinates: [poly.rings, island.rings],
},
},
],
},
DICT,
).shapes[0];
expect(multi.polys).toHaveLength(2);
expect(districtAtPoint(multi, 2, 2)).toBe(false); // 主体那块里的洞
expect(districtAtPoint(multi, 10.5, 10.5)).toBe(true); // 飞地那块
expect(districtAtPoint(multi, 6, 6)).toBe(false); // 两块都不在
});
it('牌子落点都在自己的区界里:宁可压在边界上也不飘到隔壁或者海里', () => {
for (const s of match.shapes) {
const [lng, lat] = s.anchor;
expect(Number.isFinite(lng) && Number.isFinite(lat), s.name).toBe(true);
expect(
s.bbox.minLng <= lng &&
lng <= s.bbox.maxLng &&
s.bbox.minLat <= lat &&
lat <= s.bbox.maxLat,
s.name,
).toBe(true);
// anchor 优先用文件里的 centroid(面的中心); centroid 掉在界外才退回最大那块的一个真实顶点
const onShape = districtAtPoint(s, lng, lat);
const isVertex = s.polys.some((p) =>
p.rings[0].some(([vLng, vLat]) => vLng === lng && vLat === lat),
);
expect(onShape || isVertex, s.name).toBe(true);
}
});
it('文件里的 centroid 落不进区界时退回顶点:拿一个 centroid 明显偏离的合成区界验一次', () => {
const m = matchDistrictShapes(
{
type: 'FeatureCollection',
features: [
{
properties: {
name: '罗湖区',
adcode: '440303',
centroid: [200, 200], // 明显不在界内
},
geometry: {
type: 'Polygon',
coordinates: [
[
[114, 22.5],
[114.1, 22.5],
[114.1, 22.6],
[114, 22.6],
[114, 22.5],
],
],
},
},
],
},
DICT,
);
const s = m.shapes[0];
expect(s.anchor[0]).toBeGreaterThanOrEqual(114);
expect(s.anchor[0]).toBeLessThanOrEqual(114.1);
expect(
s.polys[0].rings[0].some(([lng, lat]) => lng === s.anchor[0] && lat === s.anchor[1]),
).toBe(true);
});
});
describe('区界 · 加载状态', () => {
it('没拉到数据时报「没有」,不报「就是没有边界」', () => {
// 本文件不触发 fetch(见文件头),所以这里必须还是未加载的状态。
// 界面靠 districtShapes() 返回 null 与返回空数组的区别来决定入口说不说话,
// 空数组会被读成「区界文件到了但一个区都对不上」,那是另一件完全不同的事。
expect(hasDistrictShapes()).toBe(false);
expect(districtShapes(DICT)).toBeNull();
expect(districtShape(DICT, 0)).toBeNull();
expect(districtShape(DICT, 1)).toBeNull();
});
});