hotspotCorrectness.test.ts 12.7 KB
import { describe, expect, it } from 'vitest';
import {
  analyze,
  gaussianSmooth,
  leaveOneOutBaseline,
  poissonUpperTail,
  type AnalysisInput,
} from './hotspotAnalysis';
import type { AnalysisParams, HotspotRow } from './types';

/**
 * 黑点「读数正确性」核验 —— 直接回应超人「上轮改完数据是不是变大了」的担忧。
 *
 * 上轮把期望值分母从「整个连通域格子数(含高斯光晕空格)」改成「域内有案格子数」,
 * 效果是让更多真实簇通过泊松 z 检验(修复前被压到 4σ 以下、静默 0 处的那批)。
 * 这个改动**只动「哪些域够格叫黑点」的门槛,不动每个域报出来的案件数** —— 域的 count
 * 是「该连通显著区里落了多少个点」的硬计数,与分母无关。
 *
 * 本文件用「已知规模的合成簇」把这件事钉死:
 *   1. 读数 = 真实簇规模(绝不会被放大,且贴近真实落入热区的点数);
 *   2. 均匀背景不产出假黑点(修复不能引入假阳性);
 *   3. 中等强度簇(修复前会被误杀)现在能被识别(回归保护);
 *   4. 多个不同规模簇同时存在时,各自独立计数、互不串味、不合并成一个巨无霸。
 */

const PARAMS: AnalysisParams = {
  cellMeters: 100,
  smoothMeters: 250,
  keepPercent: 8,
  minCount: 15,
  topN: 24,
  sort: 'count',
  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 ClusterSpec {
  cx: number;
  cy: number;
  size: number;
}

/** 均匀背景 + 若干已知规模、已知位置的真实簇 */
function makeMixed(clusters: ClusterSpec[], background: number): AnalysisInput {
  const rnd = mulberry32(20261104);
  const total = background + clusters.reduce((s, c) => s + c.size, 0);
  const lng = new Int32Array(total);
  const lat = new Int32Array(total);
  const ts = new Uint32Array(total);
  const d = new Uint8Array(total);
  const s = new Uint16Array(total);
  const mask = new Uint8Array(total);
  let i = 0;
  for (; i < background; i += 1) {
    const x = BOUNDS.minLng + rnd() * (BOUNDS.maxLng - BOUNDS.minLng);
    const y = BOUNDS.minLat + rnd() * (BOUNDS.maxLat - BOUNDS.minLat);
    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;
  }
  for (const c of clusters) {
    for (let k = 0; k < c.size; k += 1) {
      const a = rnd() * Math.PI * 2;
      const r = Math.sqrt(rnd()) * 0.0018; // ≈200m 半径内的真实报案散布
      const x = c.cx + Math.cos(a) * r;
      const y = c.cy + Math.sin(a) * r;
      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;
      i += 1;
    }
  }
  return {
    n: total,
    lng,
    lat,
    ts,
    d,
    s,
    a: null,
    mask,
    matched: total,
    dict: {
      districts: Array.from({ length: 10 }, (_, k) => `区${k}`),
      streets: Array.from({ length: 60 }, (_, k) => `区|街道${k}`),
      addrDetails: [],
    },
    bounds: BOUNDS,
    timeMin: T0,
    timeMax: T0 + HALF_YEAR,
    params: PARAMS,
  };
}

/** 找离 (cx,cy) 最近的那条黑点,断言簇规模用 */
function nearest(res: { hotspots: HotspotRow[] }, cx: number, cy: number): HotspotRow | null {
  let best: HotspotRow | null = null;
  let bestD = Infinity;
  for (const h of res.hotspots) {
    const dd = Math.abs(h.lng - cx) + Math.abs(h.lat - cy);
    if (dd < bestD) {
      bestD = dd;
      best = h;
    }
  }
  return best;
}

const CLUSTERS: ClusterSpec[] = [
  { cx: 113.9, cy: 22.55, size: 40 }, // 原来说的「几十起」
  { cx: 114.1, cy: 22.55, size: 120 }, // 一百上下
  { cx: 113.9, cy: 22.65, size: 300 }, // 几百
  { cx: 114.1, cy: 22.65, size: 600 }, // 几百(更密)
];

describe('黑点读数正确性 · 回应「数据变大了」', () => {
  it('读数 = 真实簇规模:不被放大,且贴近落入热区的点数', () => {
    const m = makeMixed(CLUSTERS, 7000);
    const res = analyze(m);
    expect(res.keptDomains).toBe(CLUSTERS.length);
    for (const c of CLUSTERS) {
      const h = nearest(res, c.cx, c.cy);
      expect(h, `簇(${c.cx},${c.cy}) 应被识别`).not.toBeNull();
      // 上限:黑点 count = 热区(连通显著区)内全部案件,会把极少数恰好落在热区里的背景点也算进来,
      // 所以允许比「放进的簇规模」略大;但绝不允许量级性膨胀(10x 那种才是真 bug)。2x 是留足余量的安全线。
      expect(h!.count, `簇规模 ${c.size} 却被报成 ${h!.count},疑似读数膨胀`).toBeLessThanOrEqual(
        Math.ceil(c.size * 2),
      );
      // 软下限:紧凑簇绝大多数点落在显著区,读数应贴近真实规模(>=60%)
      expect(h!.count, `簇规模 ${c.size} 但只读到 ${h!.count},疑似被压没`).toBeGreaterThanOrEqual(
        Math.floor(c.size * 0.6),
      );
      // 显著性必须成立:观察量明显高于按全市平均密度该有的量
      expect(h!.z).toBeGreaterThan(4);
    }
  });

  it('均匀背景不产出假黑点:修复不能引入假阳性', () => {
    // 和上面同样的背景量,但不放任何簇
    const m = makeMixed([], 7000);
    const res = analyze(m);
    expect(res.hotspots.length).toBe(0);
    expect(res.keptDomains).toBe(0);
    expect(res.note).toContain('未发现明显集中的区域');
  });

  it('中等强度簇(修复前会被误杀)现在能被识别 —— 这正是「区域变多」的来源', () => {
    // 纯背景 + 一处 50 起的簇:修复前按整连通域分母算,exp 被放大、z 压到 4σ 以下 → 0 处;
    // 修复后按有案格算,这处真实簇能浮上来。锁住这个回归,免得哪天又被人「顺手调参」改回去。
    const m = makeMixed([{ cx: 114.0, cy: 22.6, size: 50 }], 7000);
    const res = analyze(m);
    expect(res.keptDomains).toBeGreaterThanOrEqual(1);
    const h = nearest(res, 114.0, 22.6);
    expect(h).not.toBeNull();
    // 读数包含热区里极少量背景点,允许略高于放置的 50;但远不到「膨胀」的程度
    expect(h!.count).toBeLessThanOrEqual(80);
    expect(h!.count).toBeGreaterThanOrEqual(30);
  });

  it('多规模簇各自独立:不合并成一个巨无霸、读数互不串味', () => {
    const m = makeMixed(CLUSTERS, 7000);
    const res = analyze(m);
    // 4 个簇 → 4 处黑点,而不是被并成 1 个「几百+几十」的怪胎
    expect(res.keptDomains).toBe(CLUSTERS.length);
    expect(res.hotspots.length).toBe(CLUSTERS.length);
    // 被黑点覆盖的案件总数 ≈ 四簇之和(热区里少量背景点会让它略高于四簇之和,但应是同一量级)
    const inHot = res.hotspots.reduce((s, h) => s + h.count, 0);
    const expected = CLUSTERS.reduce((s, c) => s + c.size, 0);
    expect(inHot).toBeLessThanOrEqual(Math.ceil(expected * 1.5));
    expect(inHot).toBeGreaterThanOrEqual(Math.floor(expected * 0.7));
    // 榜首应是最大的那个簇(600 起),而不是把若干小簇并起来凑数
    expect(res.hotspots[0].count).toBeGreaterThanOrEqual(300);
  });

  it('diagnostic 实读:打印四簇的真实读数,便于人工核对是否「膨胀」', () => {
    const m = makeMixed(CLUSTERS, 7000);
    const res = analyze(m);
    // 这条日志只在跑测试时可见,作用是把「算法到底读出了什么」摊开给人看
    const lines = CLUSTERS.map((c) => {
      const h = nearest(res, c.cx, c.cy);
      return `  簇真值=${c.size} → 读出=${h?.count ?? '未识别'} z=${h?.z.toFixed(1) ?? '-'} ratio=${h?.ratio.toFixed(1) ?? '-'}`;
    });
    console.info(
      `[correctness] 背景=${res.background.toFixed(2)} 起/格 · 识别 ${res.keptDomains} 处\n${lines.join('\n')}`,
    );
    expect(res.keptDomains).toBe(CLUSTERS.length);
  });
});

/**
 * 高斯平滑的归一化不变量。
 *
 * 核按「整核权重和」归一化,但 x/y 靠边时只有界内那几个 tap 参与累加,等于把结果乘上
 * 「可用权重和」(角落里约 0.25)。于是整条数据外包框边界带的密度被系统性压低,
 * 贴边的真实黑点够不到分位阈值、整片漏识别。判据用「均匀场」最干净:
 * 全 1 的计数场经过任何归一化核,输出必须还是全 1,与像素在中心还是角落无关。
 */
describe('高斯平滑 · 边界重新归一化', () => {
  it('均匀场原样返回:角落与中心都是 1', () => {
    const gw = 15;
    const gh = 15;
    const src = new Int32Array(gw * gh).fill(1);
    const out = gaussianSmooth(src, gw, gh, 2.5);
    for (let i = 0; i < out.length; i += 1) expect(out[i]).toBeCloseTo(1, 5);
  });

  it('同一密度的簇贴边与居中给出同一量级的峰值', () => {
    const gw = 41;
    const gh = 41;
    const center = new Int32Array(gw * gh);
    const corner = new Int32Array(gw * gh);
    // 3×3 的同样「簇」,一处在正中,一处在左下角
    for (let dy = -1; dy <= 1; dy += 1) {
      for (let dx = -1; dx <= 1; dx += 1) {
        center[(20 + dy) * gw + (20 + dx)] = 4;
        corner[(Math.min(0, dy) + 1) * gw + (Math.min(0, dx) + 1)] = 4; // 落在 0..1 行/列
      }
    }
    const ci = gaussianSmooth(center, gw, gh, 2.5)[20 * gw + 20];
    const co = gaussianSmooth(corner, gw, gh, 2.5)[0];
    // 归一化后两者应同量级(旧写法角落只剩约 1/4)
    expect(co).toBeGreaterThan(ci * 0.6);
  });
});

/**
 * 基线的自我稀释与多重比较。
 *
 * 这两条都不是「参数调得对不对」,而是判据本身算错了:
 *   · 用含自身的平均去衡量自己 —— 一片独大时基线被它自己抬高,z 被压低,最大的问题点先被筛掉;
 *   · 每域 4σ 却没有按候选域数量校正 —— 候选域越多,「碰巧密」的机会越多。
 */
describe('黑点判据 · 留一基线与多重比较', () => {
  it('留一基线把这一域自己剔出分子分母', () => {
    // 全市 1000 起 / 100 个有案格 = 10 起/格;本域 500 起 / 10 格
    expect(leaveOneOutBaseline(1000, 100, 500, 10)).toBeCloseTo(500 / 90, 10);
    // 本域越大,基线被它自己抬得越少 —— 旧写法(含自身)恒等于 10
    expect(leaveOneOutBaseline(1000, 100, 900, 10)).toBeCloseTo(100 / 90, 10);
    // 剔掉 1 起 / 1 格的情形也不能退化成除以 0
    expect(Number.isFinite(leaveOneOutBaseline(1000, 100, 1, 1))).toBe(true);
  });

  it('全市只有这一片有案时退回全局基线,不出现除零', () => {
    expect(leaveOneOutBaseline(1000, 100, 1000, 100)).toBeCloseTo(10, 10);
    expect(leaveOneOutBaseline(0, 0, 0, 0)).toBe(0);
  });

  it('泊松上尾是逐项累加的精确值,不是 z 查正态表', () => {
    // 独立实现:从 0 项累到 k−1 得到 CDF,再取 1 − CDF
    const naive = (k: number, lambda: number) => {
      let term = Math.exp(-lambda);
      let cdf = term;
      for (let j = 1; j < k; j += 1) {
        term *= lambda / j;
        cdf += term;
      }
      return 1 - cdf;
    };
    for (const [k, lambda] of [
      [10, 2],
      [12, 3],
      [30, 12],
      [600, 500],
    ] as const) {
      expect(poissonUpperTail(k, lambda), `k=${k} λ=${lambda}`).toBeCloseTo(naive(k, lambda), 9);
    }
    // 小期望正是这条存在的理由:exp=3、obs=12 的真尾概率约 7e-5,
    // 而 z=5.2 查正态表给的是 1e-7 —— 差两三个数量级,「4σ」在那段参数上根本不是 3e-5 的 p
    expect(poissonUpperTail(12, 3)).toBeGreaterThan(1e-5);
    expect(poissonUpperTail(12, 3)).toBeLessThan(1e-4);
    // 低于期望的域不必真算尾和(p 必然大于 0.5,一律过不了阈值)
    expect(poissonUpperTail(3, 30)).toBe(1);
  });

  it('独大的一片不会因为自我稀释被筛掉', () => {
    // 一处 900 起、背景只有 900 起:本域占全市一半案件,含自身的基线会被它自己抬高
    const m = makeMixed([{ cx: 114.0, cy: 22.6, size: 900 }], 900);
    const res = analyze(m);
    expect(res.keptDomains).toBeGreaterThanOrEqual(1);
    const h = nearest(res, 114.0, 22.6);
    expect(h, '独大的一片必须留在榜上').not.toBeNull();
    expect(h!.z).toBeGreaterThan(4);
    // 报出来的期望值必须低于「按含自身的全局基线应有多少」—— 差的就是被剔掉的自身
    expect(h!.expected).toBeLessThan(res.background * h!.count);
  });
});