Files
web-nuxt/scripts/generate-mock.mjs

296 lines
9.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Generates deterministic demo data that follows CONTRACT.md.
// Run: npm run mock
// The output is checked in so the app renders before the Go API exists.
import { mkdir, writeFile } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const out = (path) => resolve(root, 'mock', path)
const BERLIN = 'Europe/Berlin'
const DEMO_NOW = '2026-11-14T08:12:00Z' // 09:12 in Heilbronn
const PLAN_START = '2026-11-15T23:00:00Z' // Mon 16 Nov 00:00 local
const PLAN_END = '2026-11-22T23:00:00Z' // Mon 23 Nov 00:00 local
const DATA_VERSION = '2026-11-14T03:00:00Z'
const MODEL_VERSION = 'histgb-2026-11-14'
const CONTEXT_VERSION = '2026-11-14T03:00:00Z'
const sensors = [
{ id: 'hn-stadtgalerie-01', name: 'Stadtgalerie', lat: 49.1427, lon: 9.2109, factor: 1.15 },
{ id: 'hn-kaiserstrasse-02', name: 'Kaiserstraße', lat: 49.1434, lon: 9.2142, factor: 1.05 },
{ id: 'hn-marktplatz-03', name: 'Marktplatz', lat: 49.1414, lon: 9.2163, factor: 1.0 },
{ id: 'hn-kilianskirche-04', name: 'Kilianskirche', lat: 49.1418, lon: 9.2188, factor: 0.88 },
{ id: 'hn-rathaus-05', name: 'Rathaus', lat: 49.1407, lon: 9.2196, factor: 0.82 },
{ id: 'hn-neckartor-06', name: 'Neckartor', lat: 49.1389, lon: 9.2172, factor: 0.9 },
{ id: 'hn-suelmerstrasse-07', name: 'Sülmerstraße', lat: 49.1451, lon: 9.2158, factor: 1.08 },
{ id: 'hn-harmonie-08', name: 'Harmonie', lat: 49.1397, lon: 9.213, factor: 0.76 },
]
// Local weather for 14 Nov (now) through 22 Nov. Deterministic demo context.
const weatherByDate = {
'2026-11-14': { temp: 10.2, precip: 0.2, cloud: 55, wind: 14, humidity: 74 },
'2026-11-15': { temp: 8.6, precip: 0.4, cloud: 70, wind: 12, humidity: 78 },
'2026-11-16': { temp: 7.0, precip: 0.8, cloud: 85, wind: 17, humidity: 82 },
'2026-11-17': { temp: 5.4, precip: 0.2, cloud: 75, wind: 11, humidity: 80 },
'2026-11-18': { temp: 6.2, precip: 0.0, cloud: 60, wind: 9, humidity: 72 },
'2026-11-19': { temp: 8.8, precip: 2.4, cloud: 90, wind: 20, humidity: 86 },
'2026-11-20': { temp: 9.6, precip: 0.6, cloud: 80, wind: 16, humidity: 84 },
'2026-11-21': { temp: 12.4, precip: 0.0, cloud: 25, wind: 8, humidity: 65 },
'2026-11-22': { temp: 8.1, precip: 0.0, cloud: 50, wind: 10, humidity: 71 },
}
const hourShape = [
0.12, 0.08, 0.06, 0.05, 0.05, 0.07, 0.12, 0.18, 0.25, 0.32,
0.55, 0.78, 0.95, 1.0, 0.88, 0.82, 0.86, 1.02, 1.12, 0.72,
0.48, 0.35, 0.24, 0.16,
]
// Monday = 0 ... Sunday = 6
const dayFactor = [0.78, 0.84, 0.9, 0.96, 1.08, 1.38, 0.7]
function mulberry32(seed) {
let a = seed
return function () {
a |= 0
a = (a + 0x6d2b79f5) | 0
let t = Math.imul(a ^ (a >>> 15), 1 | a)
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
const partsFormatter = new Intl.DateTimeFormat('en-CA', {
timeZone: BERLIN,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
hourCycle: 'h23',
})
function localParts(iso) {
const parts = Object.fromEntries(
partsFormatter.formatToParts(new Date(iso)).map((p) => [p.type, p.value]),
)
return {
date: `${parts.year}-${parts.month}-${parts.day}`,
hour: Number(parts.hour),
weekday: ((new Date(`${parts.year}-${parts.month}-${parts.day}T12:00:00Z`).getUTCDay() + 6) % 7),
}
}
function weatherFactor(date, hour, weekday) {
const w = weatherByDate[date] ?? weatherByDate['2026-11-16']
let factor = 1
if (w.precip >= 1) factor *= 0.86
else if (w.precip > 0) factor *= 0.95
if (w.cloud < 35 && (weekday === 5 || weekday === 6)) factor *= 1.08
if (w.temp < 6) factor *= 0.95
if (w.temp > 11) factor *= 1.03
return factor
}
function footfallAt(sensorIndex, iso) {
const { date, hour, weekday } = localParts(iso)
const rand = mulberry32(1000 + sensorIndex * 7919 + Math.floor(new Date(iso).getTime() / 3_600_000))
const noise = 0.92 + rand() * 0.16
const v = 110 * dayFactor[weekday] * hourShape[hour] * sensors[sensorIndex].factor
* weatherFactor(date, hour, weekday) * noise
return Math.max(4, Math.round(v))
}
function pointsFor(sensorIndex, fromIso, hours) {
const start = new Date(fromIso).getTime()
return Array.from({ length: hours }, (_, i) => {
const t = new Date(start + i * 3_600_000).toISOString().replace('.000Z', 'Z')
const v = footfallAt(sensorIndex, t)
return {
t,
v,
lo: Math.max(0, Math.round(v * 0.82)),
hi: Math.round(v * 1.18),
}
})
}
function meanOf(points) {
return Math.round((points.reduce((sum, p) => sum + p.v, 0) / points.length) * 10) / 10
}
function p95Of(points) {
const sorted = points.map((p) => p.v).sort((a, b) => a - b)
return sorted[Math.floor(sorted.length * 0.95)] ?? 0
}
function ring(points) {
return points.map(({ t, v }) => ({ t, v }))
}
function weatherAt(iso) {
const { date, hour } = localParts(iso)
const w = weatherByDate[date] ?? weatherByDate['2026-11-16']
const temp = Math.round((w.temp + 1.8 * Math.sin(((hour - 9) / 24) * Math.PI * 2)) * 10) / 10
const rainHours = w.precip > 0 ? (hour >= 6 && hour <= 9) || (hour >= 15 && hour <= 17) : false
const precip = rainHours ? Math.round((w.precip / 4) * 10) / 10 : 0
return {
t: iso,
temp_c: temp,
precip_mm: precip,
cloud_pct: w.cloud,
wind_kmh: w.wind,
humidity_pct: w.humidity,
}
}
function isoHour(fromIso, offset) {
return new Date(new Date(fromIso).getTime() + offset * 3_600_000).toISOString().replace('.000Z', 'Z')
}
await mkdir(out('forecast'), { recursive: true })
await mkdir(out('series'), { recursive: true })
const seriesBySensor = {}
for (const [index, sensor] of sensors.entries()) {
const series = pointsFor(index, '2026-11-07T00:00:00Z', 177)
seriesBySensor[sensor.id] = series
await writeFile(
out(`series/${sensor.id}.json`),
JSON.stringify({ sensor: sensor.id, step: '1h', points: ring(series) }, null, 2) + '\n',
)
const forecast = pointsFor(index, PLAN_START, 168)
await writeFile(
out(`forecast/${sensor.id}.json`),
JSON.stringify({
sensor: sensor.id,
horizon: '7d',
scenario: 'base',
points: forecast,
cached: false,
data_version: DATA_VERSION,
model_version: MODEL_VERSION,
context_version: CONTEXT_VERSION,
}, null, 2) + '\n',
)
sensor.mean = meanOf(series)
sensor.p95 = p95Of(series)
sensor.battery = 61 + ((index * 13) % 38)
delete sensor.factor
}
await writeFile(
out('sensors.json'),
JSON.stringify(sensors.map(({ id, name, lat, lon, mean, p95, battery }) => ({
id, name, lat, lon, mean, p95, battery,
})), null, 2) + '\n',
)
const weatherForecast = Array.from({ length: 168 }, (_, i) => weatherAt(isoHour('2026-11-14T09:00:00Z', i)))
await writeFile(
out('context.json'),
JSON.stringify({
weather: {
now: weatherAt('2026-11-14T08:00:00Z'),
forecast: weatherForecast,
},
holidays: [
{ date: '2026-01-01', name: 'Neujahr' },
{ date: '2026-01-06', name: 'Heilige Drei Könige' },
{ date: '2026-04-03', name: 'Karfreitag' },
{ date: '2026-04-06', name: 'Ostermontag' },
{ date: '2026-05-01', name: 'Tag der Arbeit' },
{ date: '2026-05-14', name: 'Christi Himmelfahrt' },
{ date: '2026-05-25', name: 'Pfingstmontag' },
{ date: '2026-06-04', name: 'Fronleichnam' },
{ date: '2026-10-03', name: 'Tag der Deutschen Einheit' },
{ date: '2026-11-01', name: 'Allerheiligen' },
{ date: '2026-12-25', name: '1. Weihnachtstag' },
{ date: '2026-12-26', name: '2. Weihnachtstag' },
],
updated_at: '2026-11-14T03:00:00Z',
cached: false,
}, null, 2) + '\n',
)
await writeFile(
out('meta.json'),
JSON.stringify({
data_version: DATA_VERSION,
model_version: MODEL_VERSION,
context_version: CONTEXT_VERSION,
coverage: {
sensors: 8,
from: '2025-10-16T21:00:00Z',
to: '2026-11-07T23:51:00Z',
cadence_min: 15,
},
metrics: {
model: 'weather',
mae: 3.36,
wape: 27.8,
r2: 0.779,
baseline_mae: 5.4,
baseline_wape: 44.7,
},
limits: [
'estimated devices, not people',
'8 sensors in a 580 m cluster',
'observed weather in training; forecast weather in scenarios',
],
}, null, 2) + '\n',
)
await writeFile(
out('scenario.json'),
JSON.stringify({
version: 3,
scenario: { scenario: 'base' },
at: DEMO_NOW,
}, null, 2) + '\n',
)
await writeFile(
out('scenarios.json'),
JSON.stringify([
{
id: 'base',
label: 'Base week',
short: 'Base',
description: 'Normal week, latest forecast weather.',
weather: { temp_delta_c: 0, precip_mm: 0 },
},
{
id: 'sunny-saturday-market',
label: 'Sunny Saturday + market',
short: 'Sun + market',
description: 'Dry, mild Saturday with a market event; assumes +20% Saturday footfall.',
weather: { temp_delta_c: 4, precip_mm: 0 },
event: { type: 'market', uplift: 0.2 },
},
{
id: 'rainy-saturday',
label: 'Rainy Saturday',
short: 'Rainy Sat',
description: 'Steady rain on Saturday; assumes −18% Saturday footfall.',
weather: { temp_delta_c: -2, precip_mm: 3.2 },
},
{
id: 'weekday-event',
label: 'Wednesday evening event',
short: 'Wed event',
description: 'Evening event nearby; assumes +25% footfall Wed 16:00–20:00.',
weather: { temp_delta_c: 0, precip_mm: 0 },
event: { type: 'concert', uplift: 0.25 },
},
], null, 2) + '\n',
)
await writeFile(
out('demo.json'),
JSON.stringify({ now: DEMO_NOW, plan_start: PLAN_START, plan_end: PLAN_END, timezone: BERLIN }, null, 2) + '\n',
)
console.log('mock data written to mock/')