hotspotAnalysis.test.ts 26.8 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 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
import { describe, expect, it } from 'vitest';
import { analyze, effectiveMinCount, gaussianSmooth, 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',
  // 默认口径:先看整批案件。营运 / 非营运的用例在下面单独构造 op 列
  dim: 'all',
};

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);
  });
});

/**
 * opTier:黑点(保留连通域)内部的营运 / 非营运 / 未填 三档起数。
 * 这是「黑点降噪」新加的一维统计 —— 卡片读的就是它,所以口径必须单测钉住:
 *   ① 三档严格三分(下标 1 = 非营运、2..6 = 营运、0 = 未填),互不包含;
 *   ② 三档之和 = 黑点内部全部起数(= 各热点 count 之和),差一个就说明漏计或多计。
 */
describe('analyze · opTier(黑点内营运/非营运/未填统计)', () => {
  it('opTier 把黑点内部的营运/非营运/未填三分,且三档和等于黑点总起数', () => {
    const m = withCluster(12_000, 600);
    // 背景 12000 点全给非营运(1);簇内 600 点:前 400 非营运、中间 150 营运(出租租赁=2)、后 50 未填(0)
    const op = new Uint16Array(m.n);
    for (let i = 0; i < m.n; i += 1) {
      if (i >= 12_000 && i < 12_400) op[i] = 1;
      else if (i >= 12_400 && i < 12_550) op[i] = 2;
      else if (i >= 12_550) op[i] = 0;
      else op[i] = 1; // 背景
    }
    const res = analyze({ ...m, op });
    expect(res.hotspots.length).toBeGreaterThan(0);

    // 黑点几乎全来自簇(背景均匀、进不了前 8% 的密格),所以 opTier 应≈簇内分布,
    // 允许少量边界格子把极个别背景点拉进连通域,用下限断言兜住
    const [opr, non, unf] = res.opTier;
    expect(opr).toBeGreaterThan(100); // 营运 150
    expect(non).toBeGreaterThan(350); // 非营运 400
    expect(unf).toBeGreaterThan(40); // 未填 50

    // 关键不变量:三档之和等于黑点内部全部起数。差一个就是漏计或多计
    const total = res.hotspots.reduce((a, h) => a + h.count, 0);
    expect(opr + non + unf).toBe(total);
  });

  it('缺 op 列时 opTier 全 0(界面据此不显示卡片,而非误报 0 起)', () => {
    const res = analyze(withCluster(12_000, 600));
    expect(res.opTier).toEqual([0, 0, 0]);
  });
});

/**
 * 统计维度(营运 / 非营运)是**判定口径**,不是过滤器。
 *
 * 两者的区别正好是这一组用例的全部内容:
 *   · 过滤器:黑点还是那几个,只是把某一类案件从每个黑点里剔掉 → 起数变小、位置不变;
 *   · 统计维度:只拿这一类案件重新做一遍判定 → 位置、数量、起数全都可以变。
 * 早先界面借 mapScope 干了前者,用户指着屏幕说「我要的是后者」。
 *
 * 这一组用两个形状相同的簇钉住它:A 全是营运,B 全是非营运,背景各半。
 * 若实现是「先判完再筛」,两个簇在「营运」口径下都会留下(B 只是起数变 0 或消失一栏);
 * 只有真正换输入集,B 才会连一片显著格子都不剩。
 */
describe('analyze · 统计维度(营运 / 非营运)', () => {
  const A: [number, number] = [114.06, 22.62];
  const B: [number, number] = [114.32, 22.7];
  const BG = 6000;
  const PER = 500;

  /** 均匀背景 + 两处等大的簇;A 簇全营运、B 簇全非营运、背景对半分 */
  function twoTierClusters(): Made {
    const m = make(BG + PER * 2, (i, rnd) => {
      if (i < BG) {
        return [
          BOUNDS.minLng + rnd() * (BOUNDS.maxLng - BOUNDS.minLng),
          BOUNDS.minLat + rnd() * (BOUNDS.maxLat - BOUNDS.minLat),
        ];
      }
      const c = i < BG + PER ? A : B;
      const a = rnd() * Math.PI * 2;
      const r = Math.sqrt(rnd()) * 0.0016;
      return [c[0] + Math.cos(a) * r, c[1] + Math.sin(a) * r * 0.92];
    });
    const op = new Uint16Array(m.n);
    for (let i = 0; i < m.n; i += 1) {
      if (i >= BG && i < BG + PER) op[i] = 2; // 出租/租赁 = 营运
      else if (i >= BG + PER) op[i] = 1; // 非营运
      else op[i] = i % 2 === 0 ? 2 : 1; // 背景对半分,两边基线一致
    }
    return { ...m, op };
  }

  /** 距离某点的度数(判断这一行落在哪个簇附近,200 米≈0.0018°) */
  const nearA = (lng: number, lat: number) => Math.abs(lng - A[0]) < 0.005 && Math.abs(lat - A[1]) < 0.005;
  const nearB = (lng: number, lat: number) => Math.abs(lng - B[0]) < 0.005 && Math.abs(lat - B[1]) < 0.005;

  it('「全部」口径下两处簇都识别出来(对照组:证明这份数据本来就有两个黑点)', () => {
    const res = analyze(twoTierClusters());
    expect(res.hotspots.some((h) => nearA(h.lng, h.lat))).toBe(true);
    expect(res.hotspots.some((h) => nearB(h.lng, h.lat))).toBe(true);
  });

  it('切到「营运」后只剩营运簇:B 那一片非营运的车不再形成任何黑点', () => {
    const m = twoTierClusters();
    const res = analyze({ ...m, params: { ...PARAMS, dim: 'operating' } });

    expect(res.hotspots.length).toBeGreaterThan(0);
    expect(res.hotspots.every((h) => !nearB(h.lng, h.lat))).toBe(true);
    expect(res.hotspots.some((h) => nearA(h.lng, h.lat))).toBe(true);
    // B 那片位置上连显著格子都不该剩(不是「起数变 0」,是根本没判成候选)
    const cellLng = 100 / (111_195 * Math.cos((22.6 * Math.PI) / 180));
    const cellLat = 100 / 110_700;
    const bx = Math.floor((B[0] - res.grid.originLng) / cellLng);
    const by = Math.floor((B[1] - res.grid.originLat) / cellLat);
    expect(res.mask[by * res.grid.w + bx]).toBe(0);
  });

  it('「营运」口径的分母是营运自己:judged 小于 matched,基线与 opTier 都按子集算', () => {
    const m = twoTierClusters();
    const all = analyze(m);
    const op = analyze({ ...m, params: { ...PARAMS, dim: 'operating' } });

    // 背景一半 + A 簇全部 = BG/2 + PER;不会等于完整命中的 BG + 2PER
    expect(op.matched).toBe(m.matched);
    expect(op.judged).toBeLessThan(op.matched);
    expect(op.judged).toBeGreaterThan(0);
    // 基线是「这一批每格平均几起」:营运只占一半,理应比全量低
    expect(op.background).toBeLessThan(all.background);
    // 三档里只有营运那一档有数,另两档必须是 0(它们没参与判定,不是「统计出来 0」)
    expect(op.opTier[0]).toBeGreaterThan(0);
    expect(op.opTier[1]).toBe(0);
    expect(op.opTier[2]).toBe(0);
    // 不变量:计入黑点 + 背景 = 参与判定
    const inHot = op.hotspots.reduce((a, h) => a + h.count, 0);
    expect(inHot + op.backgroundPoints).toBe(op.judged);
  });

  it('「非营运」口径是对称的:只剩 B 那片', () => {
    const m = twoTierClusters();
    const res = analyze({ ...m, params: { ...PARAMS, dim: 'nonOperating' } });
    expect(res.hotspots.some((h) => nearB(h.lng, h.lat))).toBe(true);
    expect(res.hotspots.every((h) => !nearA(h.lng, h.lat))).toBe(true);
  });

  it('缺 op 列却要按营运判定:直接说「没有营运区分列」,不静默退回全量', () => {
    const m = withCluster(6000, 500); // 没有 op 列
    const res = analyze({ ...m, params: { ...PARAMS, dim: 'operating' } });
    expect(res.hotspots).toEqual([]);
    expect(res.judged).toBe(0);
    expect(res.note).toContain('没有营运区分列');
  });

  it('该维度一起案子都没有:说「没有营运的车」,而不是「分布较为均匀」', () => {
    const m = twoTierClusters();
    // 全部改成非营运 → 营运这一档整体为空
    const op = new Uint16Array(m.n).fill(1);
    const res = analyze({ ...m, op, params: { ...PARAMS, dim: 'operating' } });
    expect(res.judged).toBe(0);
    expect(res.note).toContain('没有营运的车辆');
  });
});

/**
 * 单片最少案件数的折算。
 *
 * 钉三件事:随占比缩小、有下限、不会比用户设的更严。
 * 之所以要折算:营运只占全量的一小部分,同一个地理簇里营运车天然只有那么多,
 * 沿用全量的 15 起等于要求营运簇比非营运簇密一倍才配进清单。
 */
describe('effectiveMinCount · 按口径占比折算', () => {
  it('全部口径原样返回', () => {
    expect(effectiveMinCount(15, 42_803, 42_803)).toBe(15);
  });

  it('按占比折算:约 46% 时 15 → 7', () => {
    expect(effectiveMinCount(15, 19_700, 42_803)).toBe(7);
  });

  it('有下限 3:占比极低也不会掉到「两起案子就算一片」', () => {
    expect(effectiveMinCount(15, 100, 42_803)).toBe(3);
    expect(effectiveMinCount(5, 10, 42_803)).toBe(3);
  });

  it('不会超过基础值:四舍五入只往下松,绝不比用户设的更严', () => {
    expect(effectiveMinCount(5, 42_800, 42_803)).toBe(5);
  });
});

/**
 * 边界兜底的两个漏洞(2026-11-27 黑点降噪排查)。
 *
 * 前两条都是「兜底写了但兜不住」:normalizeParams 的 cell 加到 400 就停手,
 * 于是超出 MAX_CELLS 后照样建超大数组;resolveGridBox 的兜底框 padding 用度数写死
 * 1e-6(约 0.1 米),远小于一格(100 米),命中点挤在十几米内时仍退化成 1×1 栅格。
 * 第三条是导出函数的零 σ 除零(主链路 normalizeParams 保证 σ≥1,但导出函数不能假设)。
 */
describe('边界兜底 · 探针', () => {
  it('大范围时 cell 必须继续放大,真把栅格压到 MAX_CELLS 以内', () => {
    // 约 580km × 580km:cell=100 时 3.4e7 格,cell=400 时仍略超 2e6 格。
    const m = make(4, (_i, rnd) => [113.1 + rnd() * 0.01, 20.1 + rnd() * 0.01]);
    const res = analyze({
      ...m,
      bounds: { minLng: 113, maxLng: 118.6, minLat: 20, maxLat: 25.24 },
    });
    expect(res.grid.w * res.grid.h).toBeLessThanOrEqual(2_000_000);
    expect(res.cellMeters).toBeGreaterThan(400);
  });

  it('命中点挤在十几米内且边界失效时,兜底框不能退化成 1 格', () => {
    const m = make(120, (_i, rnd) => [114 + rnd() * 0.00008, 22.5 + rnd() * 0.00008]);
    const res = analyze({ ...m, bounds: { minLng: 0, maxLng: 0, minLat: 0, maxLat: 0 } });
    expect(res.gridSource).toBe('points-fallback');
    expect(res.grid.w * res.grid.h).toBeGreaterThan(1);
    expect(res.occupiedCells).toBeGreaterThan(1);
  });

  it('gaussianSmooth 的 σ=0 不能吐出 NaN', () => {
    const out = gaussianSmooth(new Int32Array(9).fill(1), 3, 3, 0);
    for (const v of out) expect(Number.isFinite(v)).toBe(true);
  });
});