generate-sample.mjs 9.46 KB
#!/usr/bin/env node
/**
 * 生成模拟事故数据集(CSV),字段与业务方给出的样本严格一致:
 *   案件号 / 出险地点 / 报案时间 / 经度 / 纬度
 *
 * 为什么用「热点 + 高斯散布」而不是均匀随机:
 * 真实事故点位是强聚集的(商圈、口岸、工业园、主干道交叉口)。均匀随机生成的点
 * 在热力图上会呈现一片毫无层次的均匀淡色,既看不出热点也验证不了"聚合圆圈是否
 * 落在正确位置"——拿它验收等于没验收。所以按 区权重 → 热点权重 → 高斯散布
 * 三级采样,并保留一定比例的区域内均匀噪声作为背景底噪。
 *
 * 用法:
 *   node scripts/generate-sample.mjs                 # 默认 41234 条
 *   node scripts/generate-sample.mjs --count=200000  # 生成 20W 条压力测试数据
 *   node scripts/generate-sample.mjs --seed=2026     # 换种子
 */
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
const CONFIG_FILE = path.join(ROOT, 'config/shenzhen-districts.json');
const OUT_DIR = path.join(ROOT, 'data/raw');
const OUT_FILE = path.join(OUT_DIR, 'incidents.sample.csv');

/* ------------------------------- 参数解析 ------------------------------- */

function arg(name, fallback) {
  const hit = process.argv.find((a) => a.startsWith(`--${name}=`));
  return hit ? hit.slice(name.length + 3) : fallback;
}

const COUNT = Number(arg('count', '41234'));
const SEED = Number(arg('seed', '20261013'));

if (!Number.isFinite(COUNT) || COUNT <= 0) {
  console.error(`[gen] --count 非法:${arg('count', '')}`);
  process.exit(1);
}

/* ------------------------------ 随机数工具 ------------------------------ */

/** mulberry32:32 位整数状态的确定性伪随机数。同一 seed 必然产出同一份数据,便于复现问题 */
function mulberry32(seed) {
  let a = seed >>> 0;
  return function next() {
    a = (a + 0x6d2b79f5) >>> 0;
    let t = a;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

const rand = mulberry32(SEED);

/** Box-Muller 变换取标准正态分布 */
function gaussian() {
  let u = 0;
  let v = 0;
  while (u === 0) u = rand();
  while (v === 0) v = rand();
  return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}

/** 按权重表取下标 */
function pickWeighted(weights) {
  let total = 0;
  for (const w of weights) total += w;
  let r = rand() * total;
  for (let i = 0; i < weights.length; i += 1) {
    r -= weights[i];
    if (r <= 0) return i;
  }
  return weights.length - 1;
}

/* ------------------------------ 载荷:区划 ------------------------------ */

const geo = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));

/**
 * 区的采样矩形 = 该区全部热点的包络外扩。
 * 明确说明:这不等于法定行政边界,只用于约束"噪声点"落在该区附近,
 * 避免生成出跨区的离谱点位。真实边界需引入区界 GeoJSON 才能精确。
 */
function buildSamplingBox(district) {
  const lngs = district.hotspots.map((h) => h.lng);
  const lats = district.hotspots.map((h) => h.lat);
  const padLng = 0.02;
  const padLat = 0.015;
  return {
    minLng: Math.min(...lngs) - padLng,
    maxLng: Math.max(...lngs) + padLng,
    minLat: Math.min(...lats) - padLat,
    maxLat: Math.max(...lats) + padLat,
  };
}

for (const d of geo.districts) {
  d.box = buildSamplingBox(d);
  d.weightSum = d.hotspots.reduce((s, h) => s + h.weight, 0);
}

const districtWeights = geo.districts.map((d) => d.weight);

/* --------------------------- 载荷:地址词素 --------------------------- */

const PLACE_SUFFIX = [
  '科技大厦',
  '工业园',
  '交叉口',
  '路口',
  '公交站',
  '停车场',
  '居民小区',
  '商业中心',
  '购物广场',
  '学校门口',
  '医院',
  '酒店',
  '加油站',
  '物流园',
  '建材市场',
  '批发市场',
  '地铁站',
  '立交桥',
  '天桥',
  '隧道口',
  '充电站',
  '汽配城',
  '汽车销售服务店',
  '汽修厂',
];

const BRANCH_PREFIX = ['深圳', '深圳市', ''];

const CASE_PREFIX_POOL = [
  '904102928000',
  '905280028000',
  '905900728000',
  '920780028000',
  '905020028000',
  '905790028000',
  '905161628000',
  '930260528000',
];

/* ------------------------------ 时间分布 ------------------------------ */

// 覆盖近一年,与"报表口径按自然年/近一年统计"的常见习惯一致
const TIME_START = Date.parse('2025-10-14T00:00:00+08:00');
const TIME_END = Date.parse('2026-10-13T23:59:59+08:00');
const DAY_MS = 86400000;

// 小时权重:凌晨 0-5 点事故率实际偏高,早晚高峰次之,平峰最低
const HOUR_WEIGHT = [
  2.4, 2.6, 2.6, 2.3, 2.0, 1.7, 1.3, 1.6, 1.7, 1.3, 1.0, 1.1, 1.2, 1.1, 1.1, 1.3, 1.5, 1.8, 1.7,
  1.4, 1.2, 1.2, 1.4, 1.9,
];
// 周五/周六略高
const WEEKDAY_WEIGHT = [1.0, 0.98, 1.0, 1.02, 1.12, 1.1, 1.0];

function randomTimestamp() {
  // 先取日期,再按小时权重取小时——比"在时间轴上均匀取秒"更贴近真实分布
  const days = Math.floor((TIME_END - TIME_START) / DAY_MS);
  let day = 0;
  for (let attempt = 0; attempt < 8; attempt += 1) {
    day = Math.floor(rand() * days);
    const dow = new Date(TIME_START + day * DAY_MS).getDay();
    if (rand() < WEEKDAY_WEIGHT[dow]) break;
  }
  const hour = pickWeighted(HOUR_WEIGHT);
  const minute = Math.floor(rand() * 60);
  const second = Math.floor(rand() * 60);
  return TIME_START + day * DAY_MS + hour * 3600000 + minute * 60000 + second * 1000;
}

function formatTime(ms) {
  const d = new Date(ms + 8 * 3600000); // 固定按 UTC+8 输出,不受运行机器时区影响
  const p = (v, n = 2) => String(v).padStart(n, '0');
  return `${d.getUTCFullYear()}/${p(d.getUTCMonth() + 1)}/${p(d.getUTCDate())} ${p(d.getUTCHours())}:${p(d.getUTCMinutes())}:${p(d.getUTCSeconds())}`;
}

/* ------------------------------- 采样主流程 ------------------------------- */

function samplePoint() {
  const di = pickWeighted(districtWeights);
  const district = geo.districts[di];
  const box = district.box;

  // 噪声点:区域内均匀铺底,保证热力图不是几坨孤立的斑块
  if (rand() < district.noise) {
    return {
      district,
      street: district.hotspots[Math.floor(rand() * district.hotspots.length)].street,
      lng: box.minLng + rand() * (box.maxLng - box.minLng),
      lat: box.minLat + rand() * (box.maxLat - box.minLat),
      road: null,
      hotspot: null,
    };
  }

  const hi = pickWeighted(district.hotspots.map((h) => h.weight));
  const hs = district.hotspots[hi];
  let lng = hs.lng + gaussian() * hs.sigma;
  let lat = hs.lat + gaussian() * hs.sigma * 0.75; // 纬度方向略窄,贴合带状路网形态

  // 夹回区内,防止高斯长尾把点甩到隔壁区
  lng = Math.min(Math.max(lng, box.minLng), box.maxLng);
  lat = Math.min(Math.max(lat, box.minLat), box.maxLat);

  return { district, street: hs.street, lng, lat, road: hs.roads, hotspot: hs.name };
}

function buildAddress(sample) {
  const { district, street, road, hotspot } = sample;
  const r = rand();
  let detail;
  if (road && r < 0.62) {
    detail = `${road[Math.floor(rand() * road.length)]}${PLACE_SUFFIX[Math.floor(rand() * PLACE_SUFFIX.length)]}`;
  } else if (road && r < 0.85) {
    // 一部分只留路名,与样本中「航站四路」「英才路」这类纯路名记录一致
    detail = road[Math.floor(rand() * road.length)];
  } else if (hotspot) {
    const prefix = BRANCH_PREFIX[Math.floor(rand() * BRANCH_PREFIX.length)];
    detail = `${prefix}${hotspot}附近`;
  } else {
    detail = `无名路${Math.floor(rand() * 900) + 100}号`;
  }
  return `${geo.province}-${geo.city}-${district.name}-${street}${detail}`;
}

const caseNoSet = new Set();

function buildCaseNo() {
  for (let i = 0; i < 50; i += 1) {
    const prefix = CASE_PREFIX_POOL[Math.floor(rand() * CASE_PREFIX_POOL.length)];
    const serial = String(Math.floor(rand() * 1e8)).padStart(8, '0');
    const no = `${prefix}${serial}`;
    if (!caseNoSet.has(no)) {
      caseNoSet.add(no);
      return no;
    }
  }
  throw new Error('案件号空间耗尽(8 位流水号在 4W 量级下不应发生,请检查随机数种子)');
}

/* -------------------------------- 输出 -------------------------------- */

const t0 = Date.now();
const lines = ['案件号,出险地点,报案时间,经度,纬度'];

for (let i = 0; i < COUNT; i += 1) {
  const s = samplePoint();
  const caseNo = buildCaseNo();
  const addr = buildAddress(s);
  const time = formatTime(randomTimestamp());
  // 与样本一致:保留 6 位小数,按 GCJ-02 坐标(高德)输出
  lines.push(`${caseNo},${addr},${time},${s.lng.toFixed(6)},${s.lat.toFixed(6)}`);
}

fs.mkdirSync(OUT_DIR, { recursive: true });
fs.writeFileSync(OUT_FILE, `${lines.join('\r\n')}\r\n`, 'utf8');

const perDistrict = new Map();
for (const line of lines.slice(1)) {
  const name = line.split(',')[1].split('-')[2];
  perDistrict.set(name, (perDistrict.get(name) ?? 0) + 1);
}

console.info(`[gen] seed=${SEED} count=${COUNT} → ${path.relative(ROOT, OUT_FILE)}`);
console.info(`[gen] ${(fs.statSync(OUT_FILE).size / 1024 / 1024).toFixed(2)} MB, 耗时 ${Date.now() - t0}ms`);
console.info('[gen] 区分布:');
for (const [name, n] of [...perDistrict.entries()].sort((a, b) => b[1] - a[1])) {
  console.info(`        ${name.padEnd(6, ' ')} ${String(n).padStart(6)}  ${((n / COUNT) * 100).toFixed(1)}%`);
}