generate-sample.mjs
9.46 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
#!/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)}%`);
}