preprocess.mjs 15.1 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
#!/usr/bin/env node
/**
 * 离线数据管线:原始 CSV → 前端可直接消费的列式紧凑产物。
 *
 * 三条设计原则,都是为了 20W 量级下的首屏与筛选性能:
 *
 * 1) 列式 + 定点整数。
 *    行式 JSON 每条记录要重复一遍全部键名,20W 条光键名就上千万字符。改成
 *    {lng:[...], lat:[...], ts:[...]} 之后,gzip 能利用相邻数字的公共前缀,
 *    20W 条实测压到 2MB 量级 —— 比二进制 TypedArray 还小,而且保持可读可 diff。
 *
 * 2) 按「地图必需」与「详情才用」拆两个文件。
 *    画图只需要 lng/lat/ts/区/街道;案件号与详细地址只有点开弹窗才用得上。
 *    这两列恰是体积最大的字符串列,拆出去之后首屏请求体积直接砍掉约六成。
 *
 * 3) 高基数字符串走字典 + 索引。
 *    详细地址(如「光源四路贝特瑞新能源科技大厦」)重复率很高,去重存一份,
 *    点位上只留 2 字节索引。
 *
 * 用法:node scripts/preprocess.mjs
 */
import fs from 'node:fs';
import path from 'node:path';
import readline from 'node:readline';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
const SRC_CSV = path.join(ROOT, 'data/raw/incidents.sample.csv');
const GEO_FILE = path.join(ROOT, 'config/shenzhen-districts.json');
const GRID_FILE = path.join(ROOT, 'config/grid.json');
const OUT_DIR = path.join(ROOT, 'public/data');
const AGG_DIR = path.join(OUT_DIR, 'agg');

/** 契约样例缩放的档位:交付给后端作为聚合接口的返回样例 */
const CONTRACT_ZOOMS = [9, 11, 13, 15, 17];

const GRID_KEY_SHIFT = 2097152; // 2^21,见下方 bucketKey 注释

/* ------------------------------- 读取配置 ------------------------------- */

const geo = JSON.parse(fs.readFileSync(GEO_FILE, 'utf8'));
const gridCfg = JSON.parse(fs.readFileSync(GRID_FILE, 'utf8'));

/** 区 → 街道列表,用于把「区-街道+详细」拆成结构化字段 */
const streetByDistrict = new Map();
for (const d of geo.districts) {
  streetByDistrict.set(
    d.name,
    d.hotspots.map((h) => h.street),
  );
}
const districtNames = geo.districts.map((d) => d.name);
/** 长名优先匹配,避免「大鹏新区」被当成「大鹏街道」之类的误判 */
const districtNamesByLen = [...districtNames].sort((a, b) => b.length - a.length);

/* ------------------------------ 解析与校验 ------------------------------ */

const SANITY_BOX = { minLng: 113.6, maxLng: 114.7, minLat: 22.3, maxLat: 23.0 };

const stats = {
  total: 0,
  rejected: 0,
  rejectedReason: new Map(),
  districtUnknown: 0,
  streetUnknown: 0,
  timeMin: Infinity,
  timeMax: -Infinity,
  bounds: { minLng: Infinity, maxLng: -Infinity, minLat: Infinity, maxLat: -Infinity },
};

function reject(reason) {
  stats.rejected += 1;
  stats.rejectedReason.set(reason, (stats.rejectedReason.get(reason) ?? 0) + 1);
}

/** 解析一行 → 结构化记录;不合法返回 null 并计入拒收统计,绝不静默丢弃 */
function parseRow(fields, lineNo) {
  if (fields.length !== 5) {
    reject(`字段数不为 5(第 ${lineNo} 行)`);
    return null;
  }
  const [caseNo, address, timeText, lngText, latText] = fields.map((f) => f.trim());

  if (!/^\d{15,24}$/.test(caseNo)) {
    reject('案件号非纯数字或长度异常');
    return null;
  }

  const lng = Number(lngText);
  const lat = Number(latText);
  if (!Number.isFinite(lng) || !Number.isFinite(lat)) {
    reject('经纬度非数值');
    return null;
  }
  if (
    lng < SANITY_BOX.minLng ||
    lng > SANITY_BOX.maxLng ||
    lat < SANITY_BOX.minLat ||
    lat > SANITY_BOX.maxLat
  ) {
    reject('经纬度超出深圳合理范围');
    return null;
  }

  const ms = Date.parse(timeText.replace(/\//g, '-').replace(' ', 'T') + '+08:00');
  if (!Number.isFinite(ms)) {
    reject('报案时间无法解析');
    return null;
  }

  // 地址拆解:省-市-区-街道+详细
  //
  // 不能简单地取 parts[2]/parts[3] —— 数据来源不同,分段口径会漂:
  //   「广东省-深圳市-福田区-南园街道东园路」  → 区自占一段,街道在下一段
  //   「深圳市福田区南园街道东园路」            → 区与街道挤在同一段
  // 所以先扫出「区」落在哪一段,再决定街道+详细从哪里起算。
  const parts = address.split('-');
  let district = '';
  let rest = '';
  for (let i = 0; i < parts.length; i += 1) {
    const hit = districtNamesByLen.find((n) => parts[i].startsWith(n));
    if (!hit) continue;
    district = hit;
    const sameSegmentRest = parts[i].slice(hit.length);
    // 区自占一段时,街道与详细在后续段;用 '-' 回接以保留详细地址内部的连字符
    rest = sameSegmentRest || parts.slice(i + 1).join('-');
    break;
  }
  if (!district) {
    stats.districtUnknown += 1;
    district = '未识别';
    rest = address;
  }

  let street = '';
  let detail = rest;
  const streets = streetByDistrict.get(district) ?? [];
  const streetHit = [...streets].sort((a, b) => b.length - a.length).find((s) => rest.startsWith(s));
  if (streetHit) {
    street = streetHit;
    detail = rest.slice(streetHit.length);
  } else if (district !== '未识别') {
    stats.streetUnknown += 1;
    street = '未识别';
  } else {
    street = '未识别';
  }

  return {
    caseNo,
    district,
    street,
    detail: detail || rest || '(地址未提供)',
    ts: Math.floor(ms / 1000),
    lng: Math.round(lng * 1e6),
    lat: Math.round(lat * 1e6),
  };
}

/* -------------------------------- 分桶工具 -------------------------------- */

/**
 * 像素 → 经纬度网格边长。
 *
 * Web Mercator 下每度经度恒占 tileSize*2^z/360 像素;纬度方向要除以 cos(lat),
 * 因为墨卡托在高纬度拉伸。用当前数据纬度中心代入,使网格在屏幕上近似正方。
 */
function gridDegAtZoom(z, gridPx, latDeg) {
  const pxPerDegLng = (gridCfg.tileSize * Math.pow(2, z)) / 360;
  const pxPerDegLat = pxPerDegLng / Math.cos((latDeg * Math.PI) / 180);
  return { dLng: gridPx / pxPerDegLng, dLat: gridPx / pxPerDegLat };
}

/**
 * 桶 key:把二维网格坐标压成一个 number。
 * 用 2^21 作为经度方向的进制,保证 gy < 2^21 时不串位。
 * gy 上限 = 180/dLat,要 < 2097152 需要 dLat > 8.6e-5(约 9.5 米),
 * z18 + 64px 的 dLat ≈ 3.7e-4,余量两个数量级,安全。
 */
function bucketKey(gx, gy) {
  return gx * GRID_KEY_SHIFT + gy;
}

/* --------------------------------- 主流程 --------------------------------- */

if (!fs.existsSync(SRC_CSV)) {
  console.error(`[prep] 找不到源文件 ${path.relative(ROOT, SRC_CSV)}`);
  console.error('[prep] 请先执行:node scripts/generate-sample.mjs');
  process.exit(1);
}

const t0 = Date.now();

const caseNos = [];
const addrDetailIdx = [];
const lngs = [];
const lats = [];
const tsList = [];
const districtIdx = [];
const streetIdx = [];

const districtDict = [...districtNames, '未识别'];
const districtIndexMap = new Map(districtDict.map((n, i) => [n, i]));
const streetDict = [];
const streetIndexMap = new Map();

function internStreet(name) {
  let i = streetIndexMap.get(name);
  if (i === undefined) {
    i = streetDict.length;
    streetDict.push(name);
    streetIndexMap.set(name, i);
  }
  return i;
}

const addrDetails = [];
const addrDetailMap = new Map();

function internDetail(text) {
  let i = addrDetailMap.get(text);
  if (i === undefined) {
    i = addrDetails.length;
    addrDetails.push(text);
    addrDetailMap.set(text, i);
  }
  return i;
}

const rl = readline.createInterface({
  input: fs.createReadStream(SRC_CSV, 'utf8'),
  crlfDelay: Infinity,
});

let lineNo = 0;
let headerSkipped = false;

for await (const rawLine of rl) {
  lineNo += 1;
  const line = rawLine.replace(/^\uFEFF/, '').trim();
  if (!line) continue;
  if (!headerSkipped) {
    headerSkipped = true;
    if (line.startsWith('案件号')) continue;
  }

  const rec = parseRow(line.split(','), lineNo);
  if (!rec) continue;

  stats.total += 1;
  caseNos.push(rec.caseNo);
  addrDetailIdx.push(internDetail(rec.detail));
  lngs.push(rec.lng);
  lats.push(rec.lat);
  tsList.push(rec.ts);
  districtIdx.push(districtIndexMap.get(rec.district) ?? districtIndexMap.get('未识别'));
  streetIdx.push(internStreet(`${rec.district}|${rec.street}`));

  if (rec.ts < stats.timeMin) stats.timeMin = rec.ts;
  if (rec.ts > stats.timeMax) stats.timeMax = rec.ts;
  if (rec.lng / 1e6 < stats.bounds.minLng) stats.bounds.minLng = rec.lng / 1e6;
  if (rec.lng / 1e6 > stats.bounds.maxLng) stats.bounds.maxLng = rec.lng / 1e6;
  if (rec.lat / 1e6 < stats.bounds.minLat) stats.bounds.minLat = rec.lat / 1e6;
  if (rec.lat / 1e6 > stats.bounds.maxLat) stats.bounds.maxLat = rec.lat / 1e6;
}

if (stats.total === 0) {
  console.error('[prep] 没有任何有效记录,终止');
  process.exit(1);
}

const centerLat = (stats.bounds.minLat + stats.bounds.maxLat) / 2;

/* ---- 产物 1:地图必需列 ---- */

fs.mkdirSync(OUT_DIR, { recursive: true });

const incidents = { v: 1, n: stats.total, lng: lngs, lat: lats, ts: tsList, d: districtIdx, s: streetIdx };
fs.writeFileSync(path.join(OUT_DIR, 'incidents.json'), JSON.stringify(incidents), 'utf8');

/* ---- 产物 2:详情列(懒加载) ---- */

const detail = { v: 1, caseNo: caseNos, a: addrDetailIdx };
fs.writeFileSync(path.join(OUT_DIR, 'detail.json'), JSON.stringify(detail), 'utf8');

/* ---- 产物 3:元数据与字典 ---- */

const districtCount = new Map();
for (const i of districtIdx) {
  const n = districtDict[i];
  districtCount.set(n, (districtCount.get(n) ?? 0) + 1);
}

const meta = {
  v: 1,
  generatedAt: new Date().toISOString(),
  source: path.relative(ROOT, SRC_CSV).replace(/\\/g, '/'),
  count: stats.total,
  rejected: stats.rejected,
  rejectedReasons: Object.fromEntries(stats.rejectedReason),
  timeRange: { min: stats.timeMin, max: stats.timeMax },
  bounds: stats.bounds,
  center: { lng: (stats.bounds.minLng + stats.bounds.maxLng) / 2, lat: centerLat },
  coordScale: 1e6,
  coordSystem: 'GCJ-02',
  dict: {
    districts: districtDict,
    streets: streetDict,
    addrDetails,
  },
  districtCounts: Object.fromEntries(districtCount),
  grid: gridCfg,
  files: {
    incidents: { path: 'data/incidents.json', bytes: fs.statSync(path.join(OUT_DIR, 'incidents.json')).size },
    detail: { path: 'data/detail.json', bytes: fs.statSync(path.join(OUT_DIR, 'detail.json')).size },
  },
};
fs.writeFileSync(path.join(OUT_DIR, 'meta.json'), JSON.stringify(meta), 'utf8');

/* ---- 产物 4:分级聚合契约样例 ---- */

/**
 * 这里输出的聚合结果,形状与前端 Worker 的返回值完全一致,
 * 用途是给后端 / 深城交的实现方当接口契约样例:
 *   GET /api/heatmap/aggregate?z=13&bbox=minLng,minLat,maxLng,maxLat&from=&to=&districts=
 * 前端接入真实接口时只需把 dataSource 从「本地 Worker」切到「HTTP」,聚合结果的结构不用动。
 *
 * 注意:样例覆盖全城 bbox。运行期聚合层的 bbox 传的是当前视口,所以桶数量级是几百;
 * 下面这几个是「全城一次性聚合」的量级,两者不要混为一谈。
 */
const fullBbox = [
  Number(stats.bounds.minLng.toFixed(6)),
  Number(stats.bounds.minLat.toFixed(6)),
  Number(stats.bounds.maxLng.toFixed(6)),
  Number(stats.bounds.maxLat.toFixed(6)),
];

fs.mkdirSync(AGG_DIR, { recursive: true });

/** 一次遍历,同时按给定网格分桶;返回 [桶数组, 网格边长] */
function aggregateAll(dLng, dLat) {
  const buckets = new Map();
  for (let i = 0; i < stats.total; i += 1) {
    const lng = lngs[i] / 1e6;
    const lat = lats[i] / 1e6;
    const gx = Math.floor((lng + 180) / dLng);
    const gy = Math.floor((lat + 90) / dLat);
    const k = bucketKey(gx, gy);
    const b = buckets.get(k);
    if (b) {
      b[2] += 1;
      b[3] += lngs[i];
      b[4] += lats[i];
    } else {
      buckets.set(k, [gx, gy, 1, lngs[i], lats[i]]);
    }
  }
  const out = [];
  for (const b of buckets.values()) {
    const [gx, gy, count, lngSum, latSum] = b;
    // 桶中心取桶内点位均值而非网格几何中心:事故点在网格内极少均匀分布,
    // 用均值让圆圈落在真实重心上,视觉上贴合热力峰值。
    out.push([Math.round(lngSum / count), Math.round(latSum / count), count, gx, gy]);
  }
  return out;
}

/**
 * 分级聚合契约样例。
 *
 * 只产出【一份】桶集合:热力层与聚合圆圈层共用它。
 * 初版产出两套(cluster-z*.json 用 64px 网格 / heat-z*.json 用自适应放大的网格),
 * 运行期两层各按自己那份渲染,结果就是高缩放级别下桶中心互相错位。
 */
const aggSummary = [];

for (const z of CONTRACT_ZOOMS) {
  const c = gridDegAtZoom(z, gridCfg.gridPx, centerLat);
  const buckets = aggregateAll(c.dLng, c.dLat);
  buckets.sort((a, b) => b[2] - a[2]);
  fs.writeFileSync(
    path.join(AGG_DIR, `z${z}.json`),
    JSON.stringify({
      v: 1,
      query: {
        z,
        bbox: fullBbox,
        gridDegLng: c.dLng,
        gridDegLat: c.dLat,
        gridPx: gridCfg.gridPx,
        filters: null,
      },
      total: stats.total,
      bucketCount: buckets.length,
      maxCount: buckets.reduce((m, b) => Math.max(m, b[2]), 0),
      buckets,
    }),
    'utf8',
  );

  aggSummary.push({
    z,
    bucketCount: buckets.length,
    avgPerBucket: (stats.total / buckets.length).toFixed(1),
  });
}

/* --------------------------------- 报告 --------------------------------- */

const mb = (p) => (fs.statSync(p).size / 1024 / 1024).toFixed(2);
const pad = (s, n) => String(s).padEnd(n, ' ');

/** 报表日期统一按 UTC+8 输出,不用 toISOString()——后者会因时区把日期提前一天 */
function fmtDate(sec) {
  const d = new Date(sec * 1000 + 8 * 3600000);
  const p = (v) => String(v).padStart(2, '0');
  return `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())}`;
}

console.info(`[prep] 有效 ${stats.total} 条,拒收 ${stats.rejected} 条,耗时 ${Date.now() - t0}ms`);
if (stats.rejected > 0) {
  for (const [r, n] of stats.rejectedReason) console.info(`       拒收:${r} × ${n}`);
}
if (stats.districtUnknown > 0) console.info(`       区未识别 ${stats.districtUnknown} 条`);
if (stats.streetUnknown > 0) console.info(`       街道未识别 ${stats.streetUnknown} 条`);

console.info(`[prep] 时间范围 ${fmtDate(stats.timeMin)} ~ ${fmtDate(stats.timeMax)}`);
console.info(
  `[prep] 字典规模 区 ${districtDict.length} / 街道 ${streetDict.length} / 详细地点 ${addrDetails.length}`,
);

console.info(`[prep] 产物:`);
console.info(`       ${pad('incidents.json(首屏)', 34)} ${mb(path.join(OUT_DIR, 'incidents.json'))} MB`);
console.info(`       ${pad('detail.json(点开弹窗才用)', 34)} ${mb(path.join(OUT_DIR, 'detail.json'))} MB`);
console.info(`       ${pad('meta.json', 34)} ${mb(path.join(OUT_DIR, 'meta.json'))} MB`);

console.info('[prep] 分级聚合契约样例(全城口径,运行期两层共用同一份、且用视口 bbox):');
console.info(`       ${pad('zoom', 6)}${pad('桶数', 10)}${pad('网格px', 12)}均点/桶`);
for (const a of aggSummary) {
  console.info(`       ${pad(a.z, 6)}${pad(a.bucketCount, 10)}${pad(gridCfg.gridPx, 12)}${a.avgPerBucket}`);
}