hotspotAnalysis.test.ts
16.7 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
import { describe, expect, it } from 'vitest';
import { analyze, gridBoxSource, type AnalysisInput } from './hotspotAnalysis';
import type { AnalysisParams, HotspotRow, HotspotSort } from './types';
/**
* 黑点分析的单测。
*
* 这个模块的全部价值就在于「能区分真热点和随机堆积」,而这正是肉眼看不出来的东西 ——
* 30W 点的热力图里两者长得一样。所以单测不是走形式:把密集簇判成背景、或者把均匀散布
* 判成热点,功能就等于负作用。
*
* 用例全部用合成点集,不依赖真实数据,也不依赖 Worker / DOM。
*/
const PARAMS: AnalysisParams = {
cellMeters: 100,
smoothMeters: 250,
keepPercent: 8,
minCount: 15,
topN: 24,
// 与界面默认档位(store 的 DEFAULT_ANALYSIS)同一个:这份参数就是「用户一打开看到的那一档」。
// 兜底档、界面默认档、这里的基准参数三处必须一致,否则单测证明的是另一套参数的正确性。
sort: 'count',
};
const BOUNDS = { minLng: 113.75, minLat: 22.45, maxLng: 114.45, maxLat: 22.78 };
const T0 = 1_750_000_000;
const HALF_YEAR = 180 * 86_400;
function mulberry32(seed: number) {
let t = seed >>> 0;
return () => {
t = (t + 0x6d2b79f5) >>> 0;
let r = Math.imul(t ^ (t >>> 15), 1 | t);
r = (r + Math.imul(r ^ (r >>> 7), 61 | r)) ^ r;
return ((r ^ (r >>> 14)) >>> 0) / 4294967296;
};
}
interface Made extends AnalysisInput {
/** 每条点的原始经纬度,断言质心时用得上 */
raw: Array<{ lng: number; lat: number }>;
}
function make(count: number, put: (i: number, rnd: () => number) => [number, number]): Made {
const rnd = mulberry32(20261014);
const lng = new Int32Array(count);
const lat = new Int32Array(count);
const ts = new Uint32Array(count);
const d = new Uint8Array(count);
const s = new Uint16Array(count);
const mask = new Uint8Array(count);
const raw: Array<{ lng: number; lat: number }> = [];
for (let i = 0; i < count; i += 1) {
const [x, y] = put(i, rnd);
lng[i] = Math.round(x * 1e6);
lat[i] = Math.round(y * 1e6);
ts[i] = T0 + Math.floor(rnd() * HALF_YEAR);
d[i] = Math.floor(rnd() * 10);
s[i] = Math.floor(rnd() * 60);
mask[i] = 1;
raw.push({ lng: x, lat: y });
}
return {
n: count,
lng,
lat,
ts,
d,
s,
a: null,
mask,
matched: count,
dict: {
districts: Array.from({ length: 10 }, (_, i) => `区${i}`),
streets: Array.from({ length: 60 }, (_, i) => `区|街道${i}`),
addrDetails: [],
},
bounds: BOUNDS,
timeMin: T0,
timeMax: T0 + HALF_YEAR,
params: PARAMS,
raw,
};
}
/** 全市均匀散布。没有真正的热点,只有随机堆积 */
function uniform(count: number): Made {
return make(count, (_i, rnd) => [
BOUNDS.minLng + rnd() * (BOUNDS.maxLng - BOUNDS.minLng),
BOUNDS.minLat + rnd() * (BOUNDS.maxLat - BOUNDS.minLat),
]);
}
const CLUSTER: [number, number] = [114.06, 22.62];
/** 掩码里 1 的个数 = 渲染层认定「值得画」的格子数 */
function sumMask(mask: Uint8Array): number {
let s = 0;
for (let i = 0; i < mask.length; i += 1) s += mask[i];
return s;
}
/** 均匀背景 + 一处约 150m 半径的密集簇 */
function withCluster(background: number, clusterPoints: number): Made {
const m = make(background + clusterPoints, (i, rnd) => {
if (i < background) {
return [
BOUNDS.minLng + rnd() * (BOUNDS.maxLng - BOUNDS.minLng),
BOUNDS.minLat + rnd() * (BOUNDS.maxLat - BOUNDS.minLat),
];
}
// 簇用高散布点,模拟真实路口周边几百米内的报案
const a = rnd() * Math.PI * 2;
const r = Math.sqrt(rnd()) * 0.0016;
return [CLUSTER[0] + Math.cos(a) * r, CLUSTER[1] + Math.sin(a) * r * 0.92];
});
return m;
}
/** 均匀背景 + k 处真黑点,位置铺得开一点,免得连通域互相粘连 */
function withClusters(background: number, k: number, perCluster: number): Made {
const start = background;
return make(background + k * perCluster, (i, rnd) => {
if (i < background) {
return [
BOUNDS.minLng + rnd() * (BOUNDS.maxLng - BOUNDS.minLng),
BOUNDS.minLat + rnd() * (BOUNDS.maxLat - BOUNDS.minLat),
];
}
const j = Math.floor((i - start) / perCluster);
const cx = BOUNDS.minLng + 0.1 + (j % 4) * 0.16;
const cy = BOUNDS.minLat + 0.06 + Math.floor(j / 4) * 0.09;
const a = rnd() * Math.PI * 2;
const r = Math.sqrt(rnd()) * 0.0018;
return [cx + Math.cos(a) * r, cy + Math.sin(a) * r];
});
}
describe('analyze · 判据', () => {
it('均匀散布不会产出黑点:随机堆积必须被判成背景', () => {
// 两种密度都测:百分位阈值是相对口径,点越密、随机密团越容易过前 8% 的线,
// 只有绝对显著性(泊松 z)能挡住 —— 这是这个功能唯一不能出错的地方
for (const n of [12_000, 40_000]) {
const res = analyze(uniform(n));
expect(res.hotspots.length).toBe(0);
expect(res.keptDomains).toBe(0);
expect(res.note).toContain('未发现明显集中的区域');
// 掩码全 0 意味着渲染层拿不到任何显著格子,而不是「满屏假热点」
expect(sumMask(res.mask)).toBe(0);
}
});
it('密集簇被识别为黑点,且质心落在簇上', () => {
const res = analyze(withCluster(12_000, 600));
expect(res.hotspots.length).toBeGreaterThan(0);
const top = res.hotspots[0];
expect(top.count).toBeGreaterThanOrEqual(PARAMS.minCount);
// 0.01° ≈ 1.1km,簇半径约 180m,允许栅格与质心取整的误差
expect(Math.abs(top.lng - CLUSTER[0])).toBeLessThan(0.01);
expect(Math.abs(top.lat - CLUSTER[1])).toBeLessThan(0.01);
// 显著性:观察量必须明显高于「按全市平均密度该摊的数量」
expect(top.z).toBeGreaterThan(3);
expect(top.ratio).toBeGreaterThan(1.5);
expect(top.excess).toBeGreaterThan(0);
});
it('降噪是真的减点:背景点数 > 0 且热点覆盖了簇内点位', () => {
const m = withCluster(12_000, 600);
const res = analyze(m);
expect(res.backgroundPoints).toBeGreaterThan(0);
expect(res.backgroundPoints).toBeLessThan(m.matched);
expect(res.matched).toBe(m.matched);
// 掩码只覆盖显著格子:既不是「全亮」(那等于没降噪),也不是全灭
const ones = sumMask(res.mask);
expect(ones).toBeGreaterThan(0);
expect(ones).toBeLessThanOrEqual(res.significantCells);
expect(ones).toBeLessThan(res.mask.length);
});
it('跟着筛选走:把簇的点全部 mask 掉,黑点就不该出现', () => {
const m = withCluster(8_000, 600);
// 模拟时间/行政区筛选把簇内点位排除
for (let i = 8_000; i < m.n; i += 1) m.mask[i] = 0;
const res = analyze({ ...m, matched: 8_000 });
const near = res.hotspots.filter(
(h) => Math.abs(h.lng - CLUSTER[0]) < 0.01 && Math.abs(h.lat - CLUSTER[1]) < 0.01,
);
expect(near.length).toBe(0);
});
it('每一档排序只看它自己在清单上念出的那一个数', () => {
// 这组断言是「说明与名次必须互相印证」的机器版本:清单顶部写「按超出正常 X 起排」,
// 那一列就必须由高到低。曾经的 excess 档实际按 excess × z 排,界面上没有这个数,
// 榜上就念出 28、30、40、26 这种看不出规律的顺序 —— 排名第一的人只会问一句:
// 「这是什么逻辑」,然后整张清单都不敢用。所以四档逐档验单调,并留一条防回归。
// 档位只有这四个:界面上不显示的数不许用来定名次。每行右侧那列分数按要求撤下后,
// 原先按 z 排的「偏离幅度」档也一起删了 —— 留着就是拿一个看不见的神秘数字排名。
const keys: Array<[HotspotSort, (r: HotspotRow) => number]> = [
['count', (r) => r.count],
['excess', (r) => r.excess],
['recurrence', (r) => r.recurrencePeak],
['recent', (r) => r.recentCases],
];
// 四条埋点、每条约 420 起:榜上必须有多条才谈得上单调(只有一条时断言是空的)
const fixture = () => withClusters(9_000, 4, 420);
for (const [sort, pick] of keys) {
const res = analyze({ ...fixture(), params: { ...PARAMS, sort } });
expect(res.hotspots.length, `${sort} 档只出一条,验不出单调`).toBeGreaterThanOrEqual(2);
for (let i = 1; i < res.hotspots.length; i += 1) {
expect(pick(res.hotspots[i - 1]), `${sort} 档第 ${i} 行破坏了单调`).toBeGreaterThanOrEqual(
pick(res.hotspots[i]),
);
}
}
// 榜首具体是谁,两种说法必须给出同一处:按超出量排的榜首 = 全部结果里超出最多的那一处,
// 而不是「超出量 × 显著性」这个界面上读不出来的乘积第一名
const byExcess = analyze({ ...fixture(), params: { ...PARAMS, sort: 'excess' } });
expect(byExcess.hotspots[0].excess).toBe(Math.max(...byExcess.hotspots.map((h) => h.excess)));
// 行内三个数是一笔账的三种写法,读者拿任一列都能验算:实际 − 正常 = 超出,实际 ÷ 正常 = 倍数
for (const r of byExcess.hotspots) {
expect(r.excess).toBeCloseTo(r.count - r.expected, 6);
expect(r.ratio).toBeCloseTo(r.count / r.expected, 6);
}
});
it('topN 是硬上限,且 id 就是排名下标', () => {
const res = analyze({ ...withCluster(6_000, 900), params: { ...PARAMS, topN: 3 } });
expect(res.hotspots.length).toBeLessThanOrEqual(3);
res.hotspots.forEach((h, i) => expect(h.id).toBe(i));
});
it('零命中时返回空结论而不是崩溃', () => {
const m = uniform(500);
m.mask.fill(0);
const res = analyze({ ...m, matched: 0 });
expect(res.hotspots).toEqual([]);
expect(res.backgroundPoints).toBe(0);
expect(res.note).toContain('没有命中');
});
it('栅格尺寸兜底:cell 太小会自适应放大,不给几十万×几十万的数组', () => {
const res = analyze({ ...withCluster(4_000, 300), params: { ...PARAMS, cellMeters: 1 } });
expect(res.cellMeters).toBeGreaterThanOrEqual(30);
expect(res.grid.w * res.grid.h).toBeLessThanOrEqual(2_000_000);
});
});
/**
* 30 万点档。这一档才是这个功能存在的理由(几十万点铺开看不出重点),
* 所以它验证的不是「跑不跑得动」而是「量级上去以后判据还成立吗」:
* 候选格子从几万涨到几十万,多重比较会把弱判据的假阳性放大成一片,
* 而埋进去的真黑点必须一个不漏、一个不多地被挑出来。
*/
describe('analyze · 30 万点', () => {
it('均匀散布 30 万点:一个黑点都不产出,且一遍分析压在半秒内', () => {
const res = analyze(uniform(300_000));
expect(res.domains).toBeGreaterThan(0); // 连通域是有的,说明不是「没算」而是「没过判据」
expect(res.keptDomains).toBe(0);
expect(res.hotspots.length).toBe(0);
expect(res.note).toContain('未发现明显集中的区域');
expect(res.ms).toBeLessThan(1500);
});
it('埋 12 处真黑点:正好挑出 12 个,不多不少', () => {
const res = analyze(withClusters(300_000 - 12 * 800, 12, 800));
expect(res.keptDomains).toBe(12);
expect(res.hotspots.length).toBe(12);
// 榜首必须是被埋下的那一处,而不是随机密团:默认档按每行开头那个案件总数排,
// 埋进去的那几处每处 800 起,起数和超出量都必然压过任何随机堆积
expect(res.hotspots[0].z).toBeGreaterThan(6);
expect(res.hotspots[0].count).toBeGreaterThanOrEqual(500);
expect(res.hotspots[0].excess).toBeGreaterThan(500);
expect(res.ms).toBeLessThan(1500);
});
});
/**
* 栅格边界不可用。
*
* 这一组钉的是「不报错的假结论」:meta.bounds 若被算坏(±Infinity)、或被写成
* 零宽(半写入的导入记录就是这样),旧实现会照着它建出一个 1 格的栅格 ——
* 全城案件堆进同一格,基线 = 命中总数,每个域的泊松 z 恒为 0,
* 于是**一个黑点都不产出**,界面上那是一句「当前范围内未发现明显集中的区域」。
* 读的人只会以为这批案子真的散得很均匀,翻遍代码也看不出毛病;
* 更糟的是它只在某一次装载里发生,刷新一遍又好了。
*
* 现在坏框一律退回「命中点自己的外包框」,坏框至少能得出一个真结论。
*/
describe('analyze · 栅格边界不可用', () => {
const data = () => withCluster(3000, 800);
it('零宽边界(min = max):照样找出那处密集簇,而不是 0 处', () => {
const input = data();
const res = analyze({ ...input, bounds: { minLng: 0, maxLng: 0, minLat: 0, maxLat: 0 } });
expect(res.grid.w).toBeGreaterThan(1);
expect(res.grid.h).toBeGreaterThan(1);
expect(res.keptDomains).toBeGreaterThanOrEqual(1);
expect(res.hotspots.length).toBeGreaterThanOrEqual(1);
});
it('非有限边界(±Infinity / NaN):同样退回命中点外包框', () => {
const input = data();
for (const bounds of [
{ minLng: Infinity, maxLng: -Infinity, minLat: Infinity, maxLat: -Infinity },
{ minLng: NaN, maxLng: NaN, minLat: NaN, maxLat: NaN },
]) {
const res = analyze({ ...input, bounds });
expect(res.grid.w).toBeGreaterThan(1);
expect(res.keptDomains).toBeGreaterThanOrEqual(1);
}
});
it('一个点都没命中时不造框、也不报错:话术仍是「没有命中任何点位」', () => {
const input = data();
const res = analyze({
...input,
bounds: { minLng: 0, maxLng: 0, minLat: 0, maxLat: 0 },
mask: new Uint8Array(input.n),
matched: 0,
});
expect(res.keptDomains).toBe(0);
expect(res.note).toContain('没有命中任何点位');
});
/**
* 单位弄错的框(examples:bounds 存成了定点整数 1e8 量级,点位是度 1e2 量级)。
*
* 这种框有限、也有面积,体检第 1 道过得去,但盖不住任何一个点 —— 栅格化时每个点
* 都被夹到边界格,全城案件堆进同一格。第 2 道体检(框要盖住它统计的点)就是为它加的。
*/
it('框与点不在同一个量级(盖不住点)时也退回命中点外包框', () => {
const input = data();
const res = analyze({
...input,
bounds: {
minLng: 113_750_000,
maxLng: 114_450_000,
minLat: 22_450_000,
maxLat: 22_780_000,
},
});
expect(res.grid.w).toBeGreaterThan(1);
expect(res.keptDomains).toBeGreaterThanOrEqual(1);
// 栅格必须落在真实经纬度上,而不是 1e8 那一带
expect(res.grid.originLng).toBeGreaterThan(113);
expect(res.grid.originLng).toBeLessThan(115);
});
});
/**
* 加载前数据体检(gridBoxSource)。
*
* useBootstrap 在 transfer 掉 buffer 之前用它与正式分析同一套判定先验一遍 meta.bounds:
* 坏框返回 'points-fallback',界面据此写出 dataWarn;正常数据返回 'bounds',不告警。
* 这里的断言与 analyze 的「栅格边界不可用」组共用同一套判定,唯一区别是它只判读来源、
* 不建栅格,必须和 analyze 的结论一致 —— 否则体检说「没问题」、正式分析却默默退回外包框,
* 这个盖子就盖不住了。
*/
describe('gridBoxSource · 加载前体检', () => {
const data = () => withCluster(3000, 800);
it('正常边界:返回 bounds,不触发告警', () => {
const m = data();
expect(gridBoxSource(BOUNDS, m.n, m.lng, m.lat, m.matched)).toBe('bounds');
});
it('零宽 / 非有限 / 单位错 边界:返回 points-fallback', () => {
const m = data();
expect(
gridBoxSource({ minLng: 0, maxLng: 0, minLat: 0, maxLat: 0 }, m.n, m.lng, m.lat, m.matched),
).toBe('points-fallback');
expect(
gridBoxSource(
{ minLng: Infinity, maxLng: -Infinity, minLat: Infinity, maxLat: -Infinity },
m.n,
m.lng,
m.lat,
m.matched,
),
).toBe('points-fallback');
expect(
gridBoxSource(
{ minLng: 113_750_000, maxLng: 114_450_000, minLat: 22_450_000, maxLat: 22_780_000 },
m.n,
m.lng,
m.lat,
m.matched,
),
).toBe('points-fallback');
});
it('无命中点时不造框,来源记为 bounds(界面不展示告警)', () => {
const m = data();
expect(gridBoxSource(BOUNDS, m.n, m.lng, m.lat, 0)).toBe('bounds');
});
it('与 analyze 同款判定一致:同样的坏框,analyze 必退回外包框(w>1)', () => {
const m = data();
const bad = { minLng: 0, maxLng: 0, minLat: 0, maxLat: 0 };
expect(gridBoxSource(bad, m.n, m.lng, m.lat, m.matched)).toBe('points-fallback');
const res = analyze({ ...m, bounds: bad });
expect(res.gridSource).toBe('points-fallback');
expect(res.grid.w).toBeGreaterThan(1);
});
});