generate-sample.mjs
17.4 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
#!/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 # 换种子
*
* 可选参数(默认值与历史行为完全一致,不传就跟以前一样跑):
* --from=2026-04-01 --to=2026-09-30 时间跨度(含首尾两天),默认近一年
* --out=<路径> 输出文件,默认 data/raw/incidents.sample.csv
* --format=csv|csv-bom|xlsx 默认 csv;csv-bom 便于 Excel 直接双击打开
* --time-format=slash|dash|serial 报案时间写法,默认 slash(2026/09/01 12:00:00);
* serial = Excel 日期序列号,与业务方导出的 xlsx 一致
* --profile=cfg|real real = 用 9 月真实导出件量出来的区权重 / 小时曲线 /
* 星期曲线 / 案件号前缀池,默认 cfg(配置文件里的权重)
* --trend=0.28 跨度内的线性量级爬坡,首尾对称(-T → +T):
* 0.28 = 末日日均量 = 首日 × (1.28/0.72) ≈ 1.78 倍,默认 0
*/
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'));
const FORMAT = arg('format', 'csv');
const TIME_FORMAT = arg('time-format', 'slash');
const PROFILE = arg('profile', 'cfg');
const TREND = Number(arg('trend', '0'));
const FROM = arg('from', '2025-10-14');
const TO = arg('to', '2026-10-13');
const OUT = arg('out', OUT_FILE);
if (!Number.isFinite(COUNT) || COUNT <= 0) {
console.error(`[gen] --count 非法:${arg('count', '')}`);
process.exit(1);
}
if (!['csv', 'csv-bom', 'xlsx'].includes(FORMAT)) {
console.error(`[gen] --format 只支持 csv / csv-bom / xlsx,当前=${FORMAT}`);
process.exit(1);
}
if (!['slash', 'dash', 'serial'].includes(TIME_FORMAT)) {
console.error(`[gen] --time-format 只支持 slash / dash / serial,当前=${TIME_FORMAT}`);
console.error(' serial(Excel 日期序列号)只在 --format=xlsx 时才有意义');
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);
}
/**
* 2026 年 9 月真实导出件(深圳车险出险位置-9月.xlsx,42,806 行)量出来的分布。
* 用来让压测数据在「区结构 / 报案时段曲线 / 案件号形态」上贴近业务方真实数据,
* 而不是配置文件里那套为演示调过的权重。
*
* 注意小时曲线:这是【报案时间】不是出险时间,所以凌晨 0-2 点与 17-19 点双峰、
* 午间 12-14 点是低谷 —— 这条曲线的形状直接决定 24 小时分布图长什么样,
* 用均匀分布去测等于没测。
*/
const REAL_PROFILE = {
districtWeights: {
龙岗区: 10009,
宝安区: 9536,
南山区: 5796,
龙华区: 5647,
福田区: 4621,
罗湖区: 2709,
光明区: 2274,
坪山区: 1589,
盐田区: 620,
// 9 月真实数据里大鹏新区一条没有;给一点点,保证区下拉框和边界不至于空
大鹏新区: 60,
},
// 0..23 点,按真实小时直方图归一化到和为 24
hourWeights: [
1.81, 1.73, 1.67, 1.53, 1.20, 1.00, 0.74, 0.46, 0.27, 0.16, 0.10, 0.06, 0.05, 0.06, 0.13,
0.59, 1.31, 1.65, 1.75, 1.64, 1.46, 1.27, 1.63, 1.79,
],
// Sun..Sat,真实值 [6000,6013,6160,6794,6169,5699,5971]
weekdayWeights: [0.98, 0.98, 1.01, 1.11, 1.01, 0.93, 0.97],
// 真实案件号 = 7 位机构前缀 + "28000" + 8 位流水号;取出现频次最高的前缀
casePrefixes: [
['9051616', 6876],
['9057800', 4450],
['9052800', 3781],
['9057300', 2359],
['9054068', 1987],
['9057900', 1874],
['9057600', 1678],
['9057200', 1599],
['9057400', 1524],
['9056000', 1241],
['9051600', 997],
['9052000', 814],
['9049800', 734],
['9051791', 548],
['9353900', 531],
['9355000', 448],
['9050200', 400],
['9041029', 380],
['9207800', 360],
['9059007', 340],
],
caseMid: '28000',
caseSerialLen: 8,
};
for (const d of geo.districts) {
d.box = buildSamplingBox(d);
d.weightSum = d.hotspots.reduce((s, h) => s + h.weight, 0);
}
const districtWeights =
PROFILE === 'real'
? geo.districts.map((d) => REAL_PROFILE.districtWeights[d.name] ?? 1)
: geo.districts.map((d) => d.weight);
/* --------------------------- 载荷:地址词素 --------------------------- */
const PLACE_SUFFIX = [
'科技大厦',
'工业园',
'交叉口',
'路口',
'公交站',
'停车场',
'居民小区',
'商业中心',
'购物广场',
'学校门口',
'医院',
'酒店',
'加油站',
'物流园',
'建材市场',
'批发市场',
'地铁站',
'立交桥',
'天桥',
'隧道口',
'充电站',
'汽配城',
'汽车销售服务店',
'汽修厂',
];
const BRANCH_PREFIX = ['深圳', '深圳市', ''];
const CASE_PREFIX_POOL = [
'904102928000',
'905280028000',
'905900728000',
'920780028000',
'905020028000',
'905790028000',
'905161628000',
'930260528000',
];
/* ------------------------------ 时间分布 ------------------------------ */
// --from / --to 都按【北京时间自然日】解释,含首尾两天
const TIME_START = Date.parse(`${FROM}T00:00:00+08:00`);
const DAY_MS = 86400000;
const DAY_COUNT = Math.round((Date.parse(`${TO}T00:00:00+08:00`) - TIME_START) / DAY_MS) + 1;
if (!Number.isFinite(TIME_START) || DAY_COUNT <= 0) {
console.error(`[gen] 时间窗非法:--from=${FROM} --to=${TO}`);
process.exit(1);
}
// 小时权重:凌晨 0-5 点事故率实际偏高,早晚高峰次之,平峰最低
const HOUR_WEIGHT_BASE = [
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_BASE = [1.0, 0.98, 1.0, 1.02, 1.12, 1.1, 1.0];
const HOUR_WEIGHT = PROFILE === 'real' ? REAL_PROFILE.hourWeights : HOUR_WEIGHT_BASE;
const WEEKDAY_WEIGHT = PROFILE === 'real' ? REAL_PROFILE.weekdayWeights : WEEKDAY_WEIGHT_BASE;
/**
* 逐日权重 = 趋势 × 星期效应 × 当日随机波动。
*
* 为什么预先算成权重表而不是老那样「随机取一天 + 按星期概率拒绝」:
* 拒绝采样最多试 8 次,试满就退回最后一次的结果,星期分布会被悄悄压平;
* 而且它没法表达「半年里量级逐月爬坡」这种真实趋势。
*/
const dayWeights = new Float64Array(DAY_COUNT);
for (let i = 0; i < DAY_COUNT; i += 1) {
// 北京时间星期几:TIME_START 是北京时间零点,用 UTC 读才不会受跑脚本的机器时区影响
const dow = new Date(TIME_START + i * DAY_MS).getUTCDay();
const trend = 1 + TREND * ((i / Math.max(1, DAY_COUNT - 1)) - 0.5) * 2;
const noise = 1 + 0.06 * gaussian();
dayWeights[i] = Math.max(0.05, WEEKDAY_WEIGHT[dow] * trend * noise);
}
function randomTimestamp() {
// 先按权重取日期,再按小时权重取小时——比"在时间轴上均匀取秒"更贴近真实分布
const day = pickWeighted(dayWeights);
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;
}
/**
* epoch 毫秒 → Excel 日期序列号。
*
* 业务方导出件里的序列号表达的是【北京墙钟】:整数部分是北京日历日,小数部分是
* 北京的时分秒(46284.6379166667 → 2026-09-01 15:18:36)。所以必须先把 epoch 抬
* 8 小时再除以一天,与 ingestCore 的反向换算 `epochSec = (serial-25569)*86400 - 8*3600`
* 严格互逆 —— 符号写反会让整份 xlsx 的时间整体偏 16 小时,而导入照样"成功",
* 只有跟报表对表才会发现,属于最难查的那类错。
*/
function toExcelSerial(epochMs) {
return (epochMs + 8 * 3600000) / 86400000 + 25569;
}
function formatTime(ms) {
const d = new Date(ms + 8 * 3600000); // 固定按 UTC+8 输出,不受运行机器时区影响
const p = (v, n = 2) => String(v).padStart(n, '0');
if (TIME_FORMAT === 'serial') return toExcelSerial(ms);
const sep = TIME_FORMAT === 'dash' ? '-' : '/';
return `${d.getUTCFullYear()}${sep}${p(d.getUTCMonth() + 1)}${sep}${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();
/** 案件号池:cfg 模式沿用配置文件时代的前缀;real 模式按真实导出件的前缀频次加权 */
const CASE_POOL =
PROFILE === 'real'
? { prefixes: REAL_PROFILE.casePrefixes.map((p) => p[0]), weights: REAL_PROFILE.casePrefixes.map((p) => p[1]), mid: REAL_PROFILE.caseMid, len: REAL_PROFILE.caseSerialLen }
: { prefixes: CASE_PREFIX_POOL.map((p) => p.slice(0, 7)), weights: CASE_PREFIX_POOL.map(() => 1), mid: '28000', len: 8 };
function buildCaseNo() {
// 结构:7 位机构前缀 + "28000" + 8 位流水号 = 20 位,与真实导出件完全一致
for (let attempt = 0; attempt < 64; attempt += 1) {
const prefix = CASE_POOL.prefixes[pickWeighted(CASE_POOL.weights)];
const serial = String(Math.floor(rand() * 1e8)).padStart(CASE_POOL.len, '0');
const no = `${prefix}${CASE_POOL.mid}${serial}`;
if (!caseNoSet.has(no)) {
caseNoSet.add(no);
return no;
}
}
throw new Error(
`案件号碰撞重试超限(当前 ${caseNoSet.size} 条 / 前缀数 ${CASE_POOL.prefixes.length}):请增大 --seed 或减少 --count`,
);
}
/** CSV 字段转义:地址里出现逗号时不转义会直接把列错位 */
function csvCell(v) {
const s = String(v);
return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
/* -------------------------------- 输出 -------------------------------- */
const t0 = Date.now();
const HEADER = ['案件号', '出险地点', '报案时间', '经度', '纬度'];
const aoa = [HEADER.slice()];
const perDistrict = new Map();
const perMonth = new Map();
let tsMin = Infinity;
let tsMax = -Infinity;
for (let i = 0; i < COUNT; i += 1) {
const s = samplePoint();
const caseNo = buildCaseNo();
const addr = buildAddress(s);
const ms = randomTimestamp();
const time = formatTime(ms);
// 与样本一致:保留 6 位小数,按 GCJ-02 坐标(高德)输出
const lngStr = s.lng.toFixed(6);
const latStr = s.lat.toFixed(6);
aoa.push([caseNo, addr, time, lngStr, latStr]);
perDistrict.set(s.district.name, (perDistrict.get(s.district.name) ?? 0) + 1);
const month = new Date(ms + 8 * 3600000).toISOString().slice(0, 7);
perMonth.set(month, (perMonth.get(month) ?? 0) + 1);
if (ms < tsMin) tsMin = ms;
if (ms > tsMax) tsMax = ms;
}
fs.mkdirSync(path.dirname(path.resolve(OUT)), { recursive: true });
if (FORMAT === 'xlsx') {
const { default: XLSX } = await import('xlsx');
// 报案时间用 Excel 序列号时,单元格必须是数字 —— 业务方的导出件就是这样,
// 序列号表达的是北京墙钟,所以换算时先减掉 8 小时偏移。
if (TIME_FORMAT === 'serial') {
for (let r = 1; r < aoa.length; r += 1) aoa[r][2] = Number(aoa[r][2]);
}
const ws = XLSX.utils.aoa_to_sheet(aoa, { cellDates: false });
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, '经纬度模拟数据');
// 30W 行不压缩会有 80MB+,压完通常 20~30MB;写盘多花不到 1 秒,值得
XLSX.writeFile(wb, OUT, { compression: true });
} else {
const text = aoa.map((r) => r.map(csvCell).join(',')).join('\r\n') + '\r\n';
// BOM:Excel 双击打开 CSV 时唯一能稳定认出 UTF-8 的方式;自研解析器会主动剥掉它
fs.writeFileSync(OUT, (FORMAT === 'csv-bom' ? '' : '') + text, 'utf8');
}
const sizeMB = (fs.statSync(OUT).size / 1024 / 1024).toFixed(2);
const fmtBJ = (ms) => new Date(ms + 8 * 3600000).toISOString().slice(0, 16).replace('T', ' ');
console.info(
`[gen] seed=${SEED} count=${COUNT} profile=${PROFILE} trend=${TREND} format=${FORMAT}/${TIME_FORMAT}`,
);
console.info(`[gen] 时间跨度(北京时间):${fmtBJ(tsMin)} ~ ${fmtBJ(tsMax)},共 ${DAY_COUNT} 天`);
console.info(`[gen] → ${OUT} ${sizeMB} MB,耗时 ${Date.now() - t0}ms`);
console.info('[gen] 按月:');
for (const [m, n] of [...perMonth.entries()].sort()) {
console.info(` ${m} ${String(n).padStart(7)} ${((n / COUNT) * 100).toFixed(1)}%`);
}
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)}%`);
}