feat: add live playground forecast console
ci / check (push) Successful in 1m20s

This commit is contained in:
Noel Sabia committed 2026-11-14 21:04:23 +01:00
1 parent 9ba70965ba
commit bcee6b2c68
9 files changed
+1931 -12

No files matched your search

+4 -2
View File
@@ -14,7 +14,9 @@ const usingMock = computed(() => {
return value === true || value === '1' || value === 'true' return value === true || value === '1' || value === 'true'
}) })
const isSensing = computed(() => route.path === '/' || route.path.startsWith('/sensors')) const isNewShell = computed(
() => route.path === '/' || route.path.startsWith('/sensors') || route.path.startsWith('/playground'),
)
const isCool = computed(() => route.path.startsWith('/cool')) const isCool = computed(() => route.path.startsWith('/cool'))
const isDarkPresentation = computed( const isDarkPresentation = computed(
() => route.path === '/stage' || route.path === '/live' || route.path === '/cool/stage', () => route.path === '/stage' || route.path === '/live' || route.path === '/cool/stage',
@@ -59,7 +61,7 @@ onBeforeUnmount(() => navRoleObserver?.disconnect())
</script> </script>
<template> <template>
<NuxtLayout v-if="isSensing"> <NuxtLayout v-if="isNewShell">
<NuxtPage /> <NuxtPage />
</NuxtLayout> </NuxtLayout>
+513
View File
@@ -0,0 +1,513 @@
<script setup lang="ts">
import type { Point } from '#shared/types'
import { formatNumber, formatShortDate, formatTime } from '~/utils/format'
const props = defineProps<{
observed: Point[]
forecast: Point[]
}>()
interface ChartTick {
x: number
line1: string
line2?: string
anchor: 'start' | 'middle' | 'end'
}
interface ChartGeometry {
width: number
height: number
pad: { top: number; right: number; bottom: number; left: number }
hasData: boolean
observedPath: string
forecastPath: string
bandPath: string
singleBand: { x: number; top: number; bottom: number } | null
observedSingle: { x: number; y: number } | null
forecastSingle: { x: number; y: number } | null
nowX: number
nowAnchor: 'start' | 'middle' | 'end'
peak: Point | null
peakX: number
peakY: number
peakLabel: string
peakLabelX: number
peakLabelY: number
peakLabelWidth: number
yTicks: Array<{ y: number; label: string }>
xTicks: ChartTick[]
}
function niceMax(value: number): number {
if (!Number.isFinite(value) || value <= 0) return 1
const magnitude = 10 ** Math.floor(Math.log10(value))
const residual = value / magnitude
const steps = [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]
const step = steps.find((candidate) => residual <= candidate) ?? 10
return step * magnitude
}
function sorted(points: Point[]): Point[] {
return [...points].sort((a, b) => Date.parse(a.t) - Date.parse(b.t))
}
function buildGeometry(width: number, height: number, compact: boolean): ChartGeometry {
const observed = sorted(props.observed)
const forecast = sorted(props.forecast)
const pad = compact
? { top: 26, right: 14, bottom: 42, left: 38 }
: { top: 28, right: 18, bottom: 44, left: 48 }
const plotWidth = width - pad.left - pad.right
const plotHeight = height - pad.top - pad.bottom
const times = [...observed, ...forecast]
.map((point) => Date.parse(point.t))
.filter((time) => Number.isFinite(time))
let start = times.length ? Math.min(...times) : Date.now()
let end = times.length ? Math.max(...times) : start + 3_600_000
if (end <= start) {
start -= 1_800_000
end += 1_800_000
}
const peakSource = [...observed.map((point) => point.v), ...forecast.map((point) => Math.max(point.v, point.hi ?? point.v))]
const yMax = niceMax(Math.max(...peakSource, 1) * 1.05)
const x = (iso: string) =>
pad.left + ((Date.parse(iso) - start) / (end - start)) * plotWidth
const y = (value: number) =>
pad.top + plotHeight - (Math.max(0, value) / yMax) * plotHeight
const linePath = (points: Point[]) =>
points
.map((point, index) => {
const command = index === 0 ? 'M' : 'L'
return `${command} ${x(point.t).toFixed(2)} ${y(point.v).toFixed(2)}`
})
.join(' ')
const bandPoints = forecast.map((point) => ({
x: x(point.t),
top: y(point.hi ?? point.v),
bottom: y(point.lo ?? point.v),
}))
let bandPath = ''
if (bandPoints.length >= 2) {
const top = bandPoints.map((point) => `${point.x.toFixed(2)} ${point.top.toFixed(2)}`)
const bottom = [...bandPoints]
.reverse()
.map((point) => `${point.x.toFixed(2)} ${point.bottom.toFixed(2)}`)
bandPath = `M ${top[0]} L ${top.slice(1).join(' L ')} L ${bottom.join(' L ')} Z`
}
let peak: Point | null = null
for (const point of forecast) {
if (!peak || point.v > peak.v) peak = point
}
const peakX = peak ? x(peak.t) : pad.left
const peakY = peak ? y(peak.v) : pad.top
const peakLabel = peak ? `Peak ${formatTime(peak.t)}` : ''
const peakLabelWidth = peak ? peakLabel.length * 5.6 + 14 : 0
const peakLabelX = peak
? Math.min(
Math.max(peakX - peakLabelWidth / 2, pad.left),
width - pad.right - peakLabelWidth,
)
: 0
const peakLabelY = peak ? Math.max(pad.top + 2, peakY - 25) : 0
const nowX = forecast.length
? x(forecast[0]!.t)
: observed.length
? x(observed.at(-1)!.t)
: pad.left + plotWidth
const nowAnchor: 'start' | 'middle' | 'end' =
nowX > width - pad.right - 24 ? 'end' : nowX < pad.left + 24 ? 'start' : 'middle'
const yTickCount = compact ? 3 : 4
const yTicks = Array.from({ length: yTickCount }, (_, index) => {
const value = (yMax / (yTickCount - 1)) * index
const labelValue = yMax <= 5 ? Math.round(value * 10) / 10 : Math.round(value)
return { y: y(value), label: formatNumber(labelValue) }
})
const spanHours = (end - start) / 3_600_000
const xTickCount = compact ? 4 : 6
const xTicks = Array.from({ length: xTickCount }, (_, index) => {
const fraction = index / (xTickCount - 1)
const time = start + (end - start) * fraction
const iso = new Date(time).toISOString()
const anchor: ChartTick['anchor'] =
index === 0 ? 'start' : index === xTickCount - 1 ? 'end' : 'middle'
return {
x: pad.left + plotWidth * fraction,
line1: spanHours <= 26 ? formatTime(iso) : formatShortDate(iso),
line2: spanHours <= 26 ? undefined : formatTime(iso),
anchor,
}
})
return {
width,
height,
pad,
hasData: observed.length > 0 || forecast.length > 0,
observedPath: linePath(observed),
forecastPath: linePath(forecast),
bandPath,
singleBand:
bandPoints.length === 1
? {
x: bandPoints[0]!.x,
top: bandPoints[0]!.top,
bottom: bandPoints[0]!.bottom,
}
: null,
observedSingle:
observed.length === 1
? { x: x(observed[0]!.t), y: y(observed[0]!.v) }
: null,
forecastSingle:
forecast.length === 1
? { x: x(forecast[0]!.t), y: y(forecast[0]!.v) }
: null,
nowX,
nowAnchor,
peak,
peakX,
peakY,
peakLabel,
peakLabelX,
peakLabelY,
peakLabelWidth,
yTicks,
xTicks,
}
}
const mobile = computed(() => buildGeometry(360, 236, true))
const desktop = computed(() => buildGeometry(760, 286, false))
</script>
<template>
<div class="w-full min-w-0">
<svg
class="w-full h-auto sm:hidden"
:viewBox="`0 0 ${mobile.width} ${mobile.height}`"
role="img"
aria-label="Observed history and forecast estimated devices per hour with an 80 percent band"
>
<g v-if="mobile.hasData">
<text x="8" y="13" fill="#94A3B8" font-size="9" font-family="Inter, sans-serif">
devices/hour
</text>
<g>
<line
v-for="tick in mobile.yTicks"
:key="`my-${tick.y}`"
:x1="mobile.pad.left"
:x2="mobile.width - mobile.pad.right"
:y1="tick.y"
:y2="tick.y"
stroke="#1e3a52"
stroke-dasharray="3 3"
/>
<text
v-for="tick in mobile.yTicks"
:key="`myl-${tick.y}`"
:x="mobile.pad.left - 7"
:y="tick.y + 3"
fill="#94A3B8"
font-size="9"
font-family="Inter, sans-serif"
text-anchor="end"
>
{{ tick.label }}
</text>
</g>
<path v-if="mobile.bandPath" :d="mobile.bandPath" fill="#00C3CD" fill-opacity="0.16" />
<rect
v-if="mobile.singleBand"
:x="mobile.singleBand.x - 3"
:y="mobile.singleBand.top"
width="6"
:height="Math.max(2, mobile.singleBand.bottom - mobile.singleBand.top)"
rx="2"
fill="#00C3CD"
fill-opacity="0.25"
/>
<path
v-if="mobile.observedPath"
:d="mobile.observedPath"
fill="none"
stroke="#FFFFFF"
stroke-width="2"
stroke-linejoin="round"
stroke-linecap="round"
/>
<circle
v-if="mobile.observedSingle"
:cx="mobile.observedSingle.x"
:cy="mobile.observedSingle.y"
r="3"
fill="#FFFFFF"
/>
<path
v-if="mobile.forecastPath"
:d="mobile.forecastPath"
fill="none"
stroke="#00C3CD"
stroke-width="2.4"
stroke-dasharray="6 4"
stroke-linejoin="round"
stroke-linecap="round"
/>
<circle
v-if="mobile.forecastSingle"
:cx="mobile.forecastSingle.x"
:cy="mobile.forecastSingle.y"
r="4"
fill="#00C3CD"
/>
<line
:x1="mobile.nowX"
:x2="mobile.nowX"
:y1="mobile.pad.top"
:y2="mobile.height - mobile.pad.bottom"
stroke="#94A3B8"
stroke-dasharray="3 4"
stroke-opacity="0.8"
/>
<text
:x="mobile.nowX"
:y="mobile.height - 4"
fill="#00C3CD"
font-size="9"
font-family="Inter, sans-serif"
:text-anchor="mobile.nowAnchor"
>
Now
</text>
<g v-if="mobile.peak">
<rect
:x="mobile.peakLabelX"
:y="mobile.peakLabelY - 11"
:width="mobile.peakLabelWidth"
height="16"
rx="4"
fill="#132b40"
stroke="#1e3a52"
/>
<text
:x="mobile.peakLabelX + mobile.peakLabelWidth / 2"
:y="mobile.peakLabelY"
fill="#00C3CD"
font-size="9"
font-family="Inter, sans-serif"
font-weight="600"
text-anchor="middle"
>
{{ mobile.peakLabel }}
</text>
<circle
:cx="mobile.peakX"
:cy="mobile.peakY"
r="4"
fill="#FFFFFF"
stroke="#00C3CD"
stroke-width="2"
/>
</g>
<g>
<text
v-for="tick in mobile.xTicks"
:key="`mx-${tick.x}`"
:x="tick.x"
:y="mobile.height - mobile.pad.bottom + (tick.line2 ? 15 : 20)"
fill="#94A3B8"
font-size="9"
font-family="Inter, sans-serif"
:text-anchor="tick.anchor"
>
{{ tick.line1 }}
<tspan
v-if="tick.line2"
:x="tick.x"
:dy="11"
fill="#64748B"
>
{{ tick.line2 }}
</tspan>
</text>
</g>
</g>
</svg>
<svg
class="hidden sm:block w-full h-auto"
:viewBox="`0 0 ${desktop.width} ${desktop.height}`"
role="img"
aria-label="Observed history and forecast estimated devices per hour with an 80 percent band"
>
<g v-if="desktop.hasData">
<text x="10" y="13" fill="#94A3B8" font-size="9" font-family="Inter, sans-serif">
devices/hour
</text>
<g>
<line
v-for="tick in desktop.yTicks"
:key="`dy-${tick.y}`"
:x1="desktop.pad.left"
:x2="desktop.width - desktop.pad.right"
:y1="tick.y"
:y2="tick.y"
stroke="#1e3a52"
stroke-dasharray="3 3"
/>
<text
v-for="tick in desktop.yTicks"
:key="`dyl-${tick.y}`"
:x="desktop.pad.left - 8"
:y="tick.y + 3"
fill="#94A3B8"
font-size="10"
font-family="Inter, sans-serif"
text-anchor="end"
>
{{ tick.label }}
</text>
</g>
<path v-if="desktop.bandPath" :d="desktop.bandPath" fill="#00C3CD" fill-opacity="0.16" />
<rect
v-if="desktop.singleBand"
:x="desktop.singleBand.x - 4"
:y="desktop.singleBand.top"
width="8"
:height="Math.max(2, desktop.singleBand.bottom - desktop.singleBand.top)"
rx="2"
fill="#00C3CD"
fill-opacity="0.25"
/>
<path
v-if="desktop.observedPath"
:d="desktop.observedPath"
fill="none"
stroke="#FFFFFF"
stroke-width="2.2"
stroke-linejoin="round"
stroke-linecap="round"
/>
<circle
v-if="desktop.observedSingle"
:cx="desktop.observedSingle.x"
:cy="desktop.observedSingle.y"
r="3"
fill="#FFFFFF"
/>
<path
v-if="desktop.forecastPath"
:d="desktop.forecastPath"
fill="none"
stroke="#00C3CD"
stroke-width="2.4"
stroke-dasharray="6 4"
stroke-linejoin="round"
stroke-linecap="round"
/>
<circle
v-if="desktop.forecastSingle"
:cx="desktop.forecastSingle.x"
:cy="desktop.forecastSingle.y"
r="4"
fill="#00C3CD"
/>
<line
:x1="desktop.nowX"
:x2="desktop.nowX"
:y1="desktop.pad.top"
:y2="desktop.height - desktop.pad.bottom"
stroke="#94A3B8"
stroke-dasharray="3 4"
stroke-opacity="0.8"
/>
<text
:x="desktop.nowX"
:y="desktop.height - 4"
fill="#00C3CD"
font-size="9"
font-family="Inter, sans-serif"
:text-anchor="desktop.nowAnchor"
>
Now
</text>
<g v-if="desktop.peak">
<rect
:x="desktop.peakLabelX"
:y="desktop.peakLabelY - 11"
:width="desktop.peakLabelWidth"
height="16"
rx="4"
fill="#132b40"
stroke="#1e3a52"
/>
<text
:x="desktop.peakLabelX + desktop.peakLabelWidth / 2"
:y="desktop.peakLabelY"
fill="#00C3CD"
font-size="9"
font-family="Inter, sans-serif"
font-weight="600"
text-anchor="middle"
>
{{ desktop.peakLabel }}
</text>
<circle
:cx="desktop.peakX"
:cy="desktop.peakY"
r="4.5"
fill="#FFFFFF"
stroke="#00C3CD"
stroke-width="2"
/>
</g>
<g>
<text
v-for="tick in desktop.xTicks"
:key="`dx-${tick.x}`"
:x="tick.x"
:y="desktop.height - desktop.pad.bottom + (tick.line2 ? 15 : 20)"
fill="#94A3B8"
font-size="10"
font-family="Inter, sans-serif"
:text-anchor="tick.anchor"
>
{{ tick.line1 }}
<tspan
v-if="tick.line2"
:x="tick.x"
:dy="12"
fill="#64748B"
>
{{ tick.line2 }}
</tspan>
</text>
</g>
</g>
</svg>
</div>
</template>
+12 -10
View File
@@ -5,6 +5,7 @@ const menuButton = ref<HTMLButtonElement | null>(null)
const engineActive = computed(() => route.path === '/') const engineActive = computed(() => route.path === '/')
const sensorsActive = computed(() => route.path.startsWith('/sensors')) const sensorsActive = computed(() => route.path.startsWith('/sensors'))
const playgroundActive = computed(() => route.path.startsWith('/playground'))
const navLinkClass = const navLinkClass =
'inline-flex h-16 items-center border-b-2 font-label-md transition-colors' 'inline-flex h-16 items-center border-b-2 font-label-md transition-colors'
@@ -86,13 +87,13 @@ watch(() => route.fullPath, closeMenu)
> >
Use cases Use cases
</span> </span>
<span <NuxtLink
class="inline-flex h-16 items-center border-b-2 border-transparent font-label-md text-[#94A3B8] cursor-not-allowed" to="/playground"
aria-disabled="true" :class="desktopLinkClass(playgroundActive)"
title="Coming soon" :aria-current="playgroundActive ? 'page' : undefined"
> >
Playground Playground
</span> </NuxtLink>
</nav> </nav>
<button <button
@@ -138,13 +139,14 @@ watch(() => route.fullPath, closeMenu)
> >
Use cases Use cases
</span> </span>
<span <NuxtLink
class="inline-flex h-12 items-center justify-center font-label-md text-[#94A3B8] cursor-not-allowed" to="/playground"
aria-disabled="true" :class="mobileLinkClassFor(playgroundActive)"
title="Coming soon" :aria-current="playgroundActive ? 'page' : undefined"
@click="closeMenu"
> >
Playground Playground
</span> </NuxtLink>
</nav> </nav>
</div> </div>
</header> </header>
+1000
View File
@@ -0,0 +1,1000 @@
<script setup lang="ts">
import { SCENARIO_PRESETS } from '#shared/scenarios'
import type {
Horizon,
MetaResponse,
PlaygroundForecastResponse,
Point,
Scenario,
ScenarioPreset,
Sensor,
SeriesResponse,
} from '#shared/types'
import { apiErrorMessage } from '~/utils/api-error'
import {
formatDate,
formatDateTime,
formatNumber,
formatPercent,
formatShortDate,
formatWeekdayShort,
} from '~/utils/format'
import {
buildHeatmap,
formatBand,
scenarioDelta,
summarizeForecast,
} from '~/utils/playground'
const DEFAULT_SENSOR = 'hn-stadtgalerie-01'
const DEFAULT_HORIZON: Horizon = '48h'
const DEFAULT_SCENARIO: Scenario = 'base'
const DEFAULT_TEMP_C = 22
const DEFAULT_PRECIP_MM = 0
const HORIZON_OPTIONS: Horizon[] = ['15m', '1h', '48h', '7d']
const sensorId = ref(DEFAULT_SENSOR)
const horizon = ref<Horizon>(DEFAULT_HORIZON)
const scenario = ref<Scenario>(DEFAULT_SCENARIO)
const tempOverride = ref(false)
const tempC = ref(DEFAULT_TEMP_C)
const precipOverride = ref(false)
const precipMm = ref(DEFAULT_PRECIP_MM)
const holiday = ref(false)
const {
data: sensors,
error: sensorsError,
} = await useFetch<Sensor[]>('/api/sensors', { key: 'playground-sensors' })
const { data: presets } = await useFetch<ScenarioPreset[]>('/api/scenarios', {
key: 'playground-scenarios',
})
const {
data: meta,
error: metaError,
refresh: refreshMeta,
pending: metaPending,
} = await useFetch<MetaResponse>('/api/meta', { key: 'playground-meta' })
if (sensors.value?.length && !sensors.value.some((sensor) => sensor.id === sensorId.value)) {
sensorId.value = sensors.value[0]!.id
}
function buildQuery(target: {
sensor: string
horizon: Horizon
scenario: Scenario
}): Record<string, string | number | boolean> {
const query: Record<string, string | number | boolean> = { ...target }
if (tempOverride.value) query.temp_c = tempC.value
if (precipOverride.value) query.precip_mm = precipMm.value
if (holiday.value) query.is_holiday = true
return query
}
interface InitialPlayground {
forecast: PlaygroundForecastResponse
observed: Point[]
observedError: string
}
const initialQuery = buildQuery({
sensor: sensorId.value,
horizon: DEFAULT_HORIZON,
scenario: DEFAULT_SCENARIO,
})
const {
data: initial,
error: initialError,
} = await useAsyncData<InitialPlayground>('playground-initial', async () => {
const [forecastResult, seriesResult] = await Promise.allSettled([
$fetch<PlaygroundForecastResponse>('/api/playground', { query: initialQuery }),
$fetch<SeriesResponse>('/api/series', {
query: { sensor: sensorId.value, step: '1h' },
}),
])
if (forecastResult.status === 'rejected') throw forecastResult.reason
return {
forecast: forecastResult.value,
observed: seriesResult.status === 'fulfilled' ? seriesResult.value.points : [],
observedError:
seriesResult.status === 'rejected'
? apiErrorMessage(seriesResult.reason, 'Observed series unavailable.')
: '',
}
})
const result = ref<PlaygroundForecastResponse | null>(initial.value?.forecast ?? null)
const observedPoints = ref<Point[]>(initial.value?.observed ?? [])
const observedError = ref(initial.value?.observedError ?? '')
const comparisonBase = ref<PlaygroundForecastResponse | null>(null)
const comparisonError = ref('')
const loading = ref(false)
const errorMessage = ref(
initialError.value
? apiErrorMessage(
initialError.value,
'The playground forecast is unavailable. Start the Go and Python services and retry.',
)
: '',
)
const presetList = computed(() =>
presets.value?.length ? presets.value : SCENARIO_PRESETS,
)
function scenarioLabel(id: Scenario | undefined): string {
if (!id) return '—'
return presetList.value.find((preset) => preset.id === id)?.label ?? id
}
const resultSensorName = computed(
() =>
sensors.value?.find((sensor) => sensor.id === result.value?.sensor)?.name ??
result.value?.sensor ??
'—',
)
const summary = computed(() => summarizeForecast(result.value?.points ?? []))
const baseSummary = computed(() =>
comparisonBase.value ? summarizeForecast(comparisonBase.value.points) : null,
)
const delta = computed(() =>
baseSummary.value ? scenarioDelta(summary.value, baseSummary.value) : null,
)
const heatmap = computed(() => buildHeatmap(result.value?.points ?? []))
const isBaseScenario = computed(() => result.value?.scenario === 'base')
const interpolated = computed(
() => result.value?.horizon === '15m' || result.value?.horizon === '1h',
)
const weatherSourceLabel = computed(() =>
result.value?.weather_source === 'override' ? 'Your weather override' : 'Forecast weather',
)
const holidayForced = computed(() => result.value?.request?.is_holiday === true)
const observedWindow = computed(() => {
const cutoff = Date.parse(result.value?.points[0]?.t ?? '')
const sorted = [...observedPoints.value].sort(
(a, b) => Date.parse(a.t) - Date.parse(b.t),
)
const before = Number.isFinite(cutoff)
? sorted.filter((point) => Date.parse(point.t) < cutoff)
: sorted
const last = before.at(-1)
if (!last || !Number.isFinite(cutoff)) return []
// Only draw observed history when it is contiguous with the forecast start.
// A multi-day gap would make the chart look like a continuous signal.
if (cutoff - Date.parse(last.t) > 24 * 60 * 60 * 1000) return []
return before.slice(-24)
})
const comparisonRows = computed(() => {
if (!comparisonBase.value || !baseSummary.value) return []
const selectedPeak = summary.value.peak?.v ?? 0
const basePeak = baseSummary.value.peak?.v ?? 0
const selectedMean = summary.value.mean
const baseMean = baseSummary.value.mean
return [
{
label: 'Peak devices/hour',
selected: selectedPeak,
base: basePeak,
max: Math.max(selectedPeak, basePeak, 1),
delta: delta.value?.peakDelta ?? 0,
pct: delta.value?.peakDeltaPct ?? null,
},
{
label: 'Mean devices/hour',
selected: selectedMean,
base: baseMean,
max: Math.max(selectedMean, baseMean, 1),
delta: delta.value?.meanDelta ?? 0,
pct: delta.value?.meanDeltaPct ?? null,
},
]
})
const metaErrorMessage = computed(() =>
metaError.value ? apiErrorMessage(metaError.value, 'Model metadata is unavailable.') : '',
)
const sensorsMessage = computed(() =>
sensorsError.value
? apiErrorMessage(sensorsError.value, 'The sensor list is unavailable.')
: '',
)
const statusMessage = computed(() => {
if (loading.value) return 'Running the live forecast model.'
if (errorMessage.value) return 'The latest run failed.'
if (!result.value) return 'No forecast loaded yet.'
return `${summary.value.count} forecast points loaded.`
})
function signed(value: number, suffix = ''): string {
const rounded = Math.round(value * 10) / 10
if (rounded === 0) return `0${suffix}`
return `${rounded > 0 ? '+' : ''}${formatNumber(rounded)}${suffix}`
}
async function run() {
if (loading.value) return
loading.value = true
errorMessage.value = ''
comparisonError.value = ''
const target = {
sensor: sensorId.value,
horizon: horizon.value,
scenario: scenario.value,
}
try {
const [selectedResult, seriesResult, baseResult] = await Promise.allSettled([
$fetch<PlaygroundForecastResponse>('/api/playground', {
query: buildQuery(target),
}),
$fetch<SeriesResponse>('/api/series', {
query: { sensor: target.sensor, step: '1h' },
}),
target.scenario === 'base'
? Promise.resolve<PlaygroundForecastResponse | null>(null)
: $fetch<PlaygroundForecastResponse>('/api/playground', {
query: buildQuery({ ...target, scenario: 'base' }),
}),
])
if (selectedResult.status === 'rejected') {
errorMessage.value = apiErrorMessage(
selectedResult.reason,
'The forecast API could not complete this run.',
)
return
}
result.value = selectedResult.value
if (seriesResult.status === 'fulfilled') {
observedPoints.value = seriesResult.value.points
observedError.value = ''
} else {
observedPoints.value = []
observedError.value = apiErrorMessage(
seriesResult.reason,
'Observed series unavailable.',
)
}
if (baseResult.status === 'fulfilled' && baseResult.value) {
comparisonBase.value = baseResult.value
} else {
comparisonBase.value = null
if (baseResult.status === 'rejected') {
comparisonError.value = apiErrorMessage(
baseResult.reason,
'The base comparison is unavailable.',
)
}
}
} finally {
loading.value = false
}
}
function resetDefaults() {
sensorId.value = sensors.value?.some((sensor) => sensor.id === DEFAULT_SENSOR)
? DEFAULT_SENSOR
: sensors.value?.[0]?.id ?? DEFAULT_SENSOR
horizon.value = DEFAULT_HORIZON
scenario.value = DEFAULT_SCENARIO
tempOverride.value = false
tempC.value = DEFAULT_TEMP_C
precipOverride.value = false
precipMm.value = DEFAULT_PRECIP_MM
holiday.value = false
comparisonBase.value = null
comparisonError.value = ''
void run()
}
</script>
<template>
<div class="min-h-dvh flex flex-col">
<main class="w-full flex-1 pt-16 bg-[#081723]">
<div class="max-w-[1200px] w-full mx-auto px-margin-desktop py-space-2xl flex flex-col gap-space-2xl">
<header class="flex flex-col gap-space-sm max-w-3xl">
<div class="flex flex-wrap items-center gap-space-sm">
<span class="font-label-sm text-[11px] leading-none tracking-[0.12em] text-[#00C3CD] uppercase font-semibold">
Section 04 / Interactive simulation
</span>
<span class="w-1.5 h-1.5 rounded-full bg-[#334e68]"></span>
<span class="inline-flex items-center gap-1.5 rounded-full bg-[#00C3CD]/10 border border-[#00C3CD]/25 px-2.5 py-1 font-label-sm text-[10px] leading-none text-[#00C3CD]">
<span class="w-1.5 h-1.5 rounded-full bg-[#00C3CD] animate-pulse"></span>
Live model inference
</span>
</div>
<h1 class="text-[32px] leading-[38px] sm:text-[44px] sm:leading-[50px] tracking-[-0.03em] font-semibold text-[#FFFFFF]">
Run the engine yourself.
</h1>
<p class="font-body-lg text-[16px] leading-relaxed text-[#94A3B8]">
Pick a sensor, horizon and scenario, then override the weather. Every point, band,
peak and version below is returned by the live forecast API or computed from its points.
</p>
</header>
<div class="grid grid-cols-1 lg:grid-cols-12 gap-gutter-desktop items-start">
<!-- Controls -->
<section
aria-labelledby="playground-controls-heading"
class="lg:col-span-4 min-w-0 flex flex-col gap-space-lg bg-[#0e2233] border border-[#1e3a52] rounded-xl p-space-lg shadow-sm"
>
<div class="flex items-center justify-between gap-2">
<div class="flex items-center gap-2 min-w-0">
<Icon name="material-symbols:tune" class="text-[20px] text-[#00C3CD] shrink-0" />
<h2 id="playground-controls-heading" class="font-headline-sm text-[16px] text-[#FFFFFF] font-semibold">
Simulation controls
</h2>
</div>
<button
type="button"
class="inline-flex items-center gap-1 font-label-sm text-[11px] text-[#94A3B8] hover:text-[#00C3CD] transition-colors disabled:opacity-50"
:disabled="loading"
@click="resetDefaults"
>
<Icon name="material-symbols:restart-alt" class="text-[15px]" />
Reset defaults
</button>
</div>
<p v-if="sensorsMessage" class="text-[10px] leading-snug text-[#fbbf24]">
{{ sensorsMessage }} Using {{ sensorId }}.
</p>
<div class="flex flex-col gap-space-md">
<div class="flex flex-col gap-1.5">
<label for="playground-sensor" class="font-label-sm text-[11px] text-[#94A3B8] uppercase tracking-wider">
Sensor
</label>
<select
id="playground-sensor"
v-model="sensorId"
class="w-full h-10 rounded-lg bg-[#132b40] border border-[#1e3a52] px-3 font-body-md text-[13px] text-[#FFFFFF] focus:outline-none focus:border-[#00C3CD] focus:ring-1 focus:ring-[#00C3CD] [color-scheme:dark]"
>
<option
v-for="sensor in sensors ?? []"
:key="sensor.id"
:value="sensor.id"
>
{{ sensor.name }}
</option>
<option v-if="!sensors?.length" :value="DEFAULT_SENSOR">
{{ DEFAULT_SENSOR }}
</option>
</select>
</div>
<fieldset class="flex flex-col gap-1.5">
<legend class="font-label-sm text-[11px] text-[#94A3B8] uppercase tracking-wider mb-1.5">
Horizon
</legend>
<div class="grid grid-cols-4 gap-1 bg-[#081723] p-1 rounded-lg border border-[#1e3a52]">
<button
v-for="option in HORIZON_OPTIONS"
:key="option"
type="button"
class="py-1.5 rounded font-label-sm text-[11px] transition-all focus:outline-none focus-visible:ring-1 focus-visible:ring-[#00C3CD]"
:class="
horizon === option
? 'bg-[#132b40] text-[#00C3CD] font-semibold border border-[#00C3CD]/30'
: 'text-[#94A3B8] hover:text-[#FFFFFF] border border-transparent'
"
:aria-pressed="horizon === option"
@click="horizon = option"
>
{{ option }}
</button>
</div>
</fieldset>
<div class="flex flex-col gap-1.5">
<label for="playground-scenario" class="font-label-sm text-[11px] text-[#94A3B8] uppercase tracking-wider">
Scenario
</label>
<select
id="playground-scenario"
v-model="scenario"
class="w-full h-10 rounded-lg bg-[#132b40] border border-[#1e3a52] px-3 font-body-md text-[13px] text-[#FFFFFF] focus:outline-none focus:border-[#00C3CD] focus:ring-1 focus:ring-[#00C3CD] [color-scheme:dark]"
>
<option v-for="preset in presetList" :key="preset.id" :value="preset.id">
{{ preset.label }}
</option>
</select>
</div>
<div class="flex flex-col gap-2 bg-[#132b40] border border-[#1e3a52] p-space-md rounded-lg">
<div class="flex items-center justify-between gap-2">
<label for="playground-temp-toggle" class="inline-flex items-center gap-2 font-label-sm text-[11px] text-[#94A3B8] cursor-pointer">
<input
id="playground-temp-toggle"
v-model="tempOverride"
type="checkbox"
class="h-4 w-4 accent-[#00C3CD] rounded border-[#1e3a52]"
/>
Override temperature
</label>
<span class="font-tabular-stat-md text-[13px] font-semibold text-[#00C3CD]">
{{ tempOverride ? `${tempC}°C` : 'Forecast' }}
</span>
</div>
<input
v-model.number="tempC"
type="range"
min="10"
max="35"
step="1"
:disabled="!tempOverride"
class="w-full h-1.5 accent-[#00C3CD] cursor-pointer disabled:opacity-35 disabled:cursor-not-allowed"
aria-label="Temperature override in degrees Celsius"
/>
<p class="text-[10px] leading-snug text-[#64748B]">
When off, the API uses its baked hourly weather forecast.
</p>
</div>
<div class="flex flex-col gap-2 bg-[#132b40] border border-[#1e3a52] p-space-md rounded-lg">
<div class="flex items-center justify-between gap-2">
<label for="playground-rain-toggle" class="inline-flex items-center gap-2 font-label-sm text-[11px] text-[#94A3B8] cursor-pointer">
<input
id="playground-rain-toggle"
v-model="precipOverride"
type="checkbox"
class="h-4 w-4 accent-[#00C3CD] rounded border-[#1e3a52]"
/>
Override rain
</label>
<span class="font-tabular-stat-md text-[13px] font-semibold text-[#00C3CD]">
{{ precipOverride ? `${precipMm} mm` : 'Forecast' }}
</span>
</div>
<input
v-model.number="precipMm"
type="range"
min="0"
max="10"
step="0.5"
:disabled="!precipOverride"
class="w-full h-1.5 accent-[#00C3CD] cursor-pointer disabled:opacity-35 disabled:cursor-not-allowed"
aria-label="Rain override in millimetres"
/>
<p class="text-[10px] leading-snug text-[#64748B]">
When off, the API uses its baked hourly weather forecast.
</p>
</div>
<label class="inline-flex items-start gap-2 font-label-sm text-[11px] leading-snug text-[#94A3B8] cursor-pointer">
<input
v-model="holiday"
type="checkbox"
class="mt-0.5 h-4 w-4 accent-[#00C3CD] rounded border-[#1e3a52]"
/>
Force public-holiday flag
</label>
</div>
<button
type="button"
class="w-full h-11 px-4 rounded-lg bg-[#00C3CD] hover:bg-[#3ddae4] text-[#081723] transition-all flex items-center justify-center gap-2 font-label-md text-[13px] font-bold shadow-md active:scale-[0.99] disabled:opacity-60 disabled:cursor-wait"
:disabled="loading"
@click="run"
>
<Icon
:name="loading ? 'material-symbols:progress-activity' : 'material-symbols:bolt'"
class="text-[18px]"
:class="loading ? 'animate-spin' : ''"
/>
{{ loading ? 'Running forecast…' : 'Run forecast' }}
</button>
<p class="flex items-center gap-1.5 text-[10px] leading-snug text-[#94A3B8] border-t border-[#1e3a52]/70 pt-space-sm">
<Icon name="material-symbols:verified" class="text-[14px] text-[#00C3CD] shrink-0" />
Live model · aggregate counts · no identifiers
</p>
</section>
<!-- Results -->
<section class="lg:col-span-8 min-w-0 flex flex-col gap-space-lg">
<p class="sr-only" role="status" aria-live="polite">{{ statusMessage }}</p>
<div
v-if="loading"
class="flex items-center gap-2 rounded-lg border border-[#00C3CD]/30 bg-[#00C3CD]/[0.06] px-space-md py-2.5 text-[12px] text-[#00C3CD]"
role="status"
>
<Icon name="material-symbols:progress-activity" class="text-[16px] animate-spin shrink-0" />
Running the live forecast model…
</div>
<div
v-if="errorMessage"
class="flex items-start gap-3 rounded-lg border border-[#fbbf24]/40 bg-[#fbbf24]/10 px-space-md py-3 text-[12px] text-[#fde68a]"
role="alert"
>
<Icon name="material-symbols:error" class="text-[18px] shrink-0 mt-0.5" />
<div class="min-w-0 flex-1">
<p class="font-semibold text-[#FFFFFF]">The forecast could not be completed.</p>
<p class="mt-0.5 leading-relaxed break-words">{{ errorMessage }}</p>
<p v-if="result" class="mt-1 text-[11px] text-[#fbbf24]">
Showing the last successful run below.
</p>
</div>
<button
type="button"
class="shrink-0 h-8 px-3 rounded-lg border border-[#fbbf24]/40 text-[11px] font-semibold text-[#FFFFFF] hover:bg-[#fbbf24]/20 transition-colors"
:disabled="loading"
@click="run"
>
Retry
</button>
</div>
<div
v-if="!result && !loading"
class="flex flex-col items-center gap-2 rounded-xl border border-dashed border-[#1e3a52] bg-[#0e2233] p-space-xl text-center"
>
<Icon name="material-symbols:cloud-off" class="text-[28px] text-[#94A3B8]" />
<p class="font-headline-sm text-[15px] text-[#FFFFFF]">No forecast available</p>
<p class="max-w-md text-[12px] leading-relaxed text-[#94A3B8]">
Start the Go and Python services, then retry. The page never substitutes demo
numbers for an unavailable model.
</p>
<button
type="button"
class="mt-1 h-9 px-4 rounded-lg bg-[#00C3CD] text-[#081723] font-label-md text-[12px] font-bold"
@click="run"
>
Try again
</button>
</div>
<template v-if="result">
<!-- Result summary -->
<article class="relative overflow-hidden rounded-xl border border-[#1e3a52] bg-[#0e2233] p-space-lg shadow-sm flex flex-col gap-space-md">
<div class="absolute inset-y-0 left-0 w-1.5 bg-[#00C3CD]"></div>
<div class="flex flex-col gap-2 pl-2 sm:flex-row sm:items-start sm:justify-between">
<div class="min-w-0">
<p class="font-label-sm text-[10px] uppercase tracking-wider text-[#00C3CD] font-semibold">
Selected forecast
</p>
<h2 class="font-headline-lg text-[24px] leading-[30px] tracking-tight text-[#FFFFFF] font-semibold mt-0.5 break-words">
{{ resultSensorName }}
</h2>
<div class="mt-1.5 flex flex-wrap items-center gap-1.5">
<span class="rounded bg-[#132b40] border border-[#1e3a52] px-2 py-0.5 text-[10px] text-[#FFFFFF] font-semibold">
{{ scenarioLabel(result.scenario) }}
</span>
<span class="rounded bg-[#132b40] border border-[#1e3a52] px-2 py-0.5 text-[10px] text-[#94A3B8] font-semibold">
{{ result.horizon }}
</span>
<span
class="inline-flex items-center gap-1 rounded border px-2 py-0.5 text-[10px] font-semibold"
:class="
result.weather_source === 'override'
? 'border-[#00C3CD]/35 bg-[#00C3CD]/10 text-[#00C3CD]'
: 'border-[#1e3a52] bg-[#132b40] text-[#94A3B8]'
"
>
<Icon
:name="result.weather_source === 'override' ? 'material-symbols:water-drop' : 'material-symbols:partly-cloudy-day'"
class="text-[13px]"
/>
{{ weatherSourceLabel }}
</span>
<span
v-if="holidayForced"
class="rounded border border-[#1e3a52] bg-[#132b40] px-2 py-0.5 text-[10px] text-[#94A3B8] font-semibold"
>
Holiday flag forced
</span>
<span
v-if="interpolated"
class="rounded border border-[#1e3a52] bg-[#132b40] px-2 py-0.5 text-[10px] text-[#94A3B8] font-semibold"
>
Interpolated from hourly model
</span>
</div>
</div>
<div class="shrink-0 rounded-lg border border-[#1e3a52] bg-[#132b40] px-3 py-2">
<p class="font-label-sm text-[9px] uppercase tracking-wider text-[#94A3B8]">Peak band</p>
<p class="font-tabular-stat-md text-[16px] text-[#00C3CD] font-semibold mt-0.5">
{{ formatBand(summary.peak?.lo, summary.peak?.hi) }}
</p>
<p class="text-[9px] text-[#64748B]">devices/hour</p>
</div>
</div>
<div v-if="result.points.length" class="grid grid-cols-2 lg:grid-cols-4 gap-space-sm pl-2">
<div class="flex flex-col rounded-lg border border-[#1e3a52] bg-[#132b40] px-3 py-2">
<span class="font-label-sm text-[10px] text-[#94A3B8]">Peak estimate</span>
<span class="font-tabular-stat-md text-[18px] text-[#FFFFFF] font-semibold mt-0.5">
{{ summary.peak ? formatNumber(summary.peak.v) : '—' }}
</span>
<span class="text-[10px] text-[#64748B]">devices/hour</span>
<span class="mt-1 text-[10px] text-[#00C3CD]">
{{ summary.peak ? formatDateTime(summary.peak.t) : 'No points' }}
</span>
</div>
<div class="flex flex-col rounded-lg border border-[#1e3a52] bg-[#132b40] px-3 py-2">
<span class="font-label-sm text-[10px] text-[#94A3B8]">Mean estimate</span>
<span class="font-tabular-stat-md text-[18px] text-[#FFFFFF] font-semibold mt-0.5">
{{ formatNumber(summary.mean) }}
</span>
<span class="text-[10px] text-[#64748B]">devices/hour</span>
<span class="mt-1 text-[10px] text-[#64748B]">{{ summary.count }} points</span>
</div>
<div class="flex flex-col rounded-lg border border-[#1e3a52] bg-[#132b40] px-3 py-2">
<span class="font-label-sm text-[10px] text-[#94A3B8]">Modeled device-hours</span>
<span class="font-tabular-stat-md text-[18px] text-[#FFFFFF] font-semibold mt-0.5">
{{ formatNumber(Math.round(summary.total)) }}
</span>
<span class="text-[10px] text-[#64748B]">aggregate estimate</span>
<span class="mt-1 text-[10px] text-[#64748B]">
Σ v × {{ summary.intervalHours }} h
</span>
</div>
<div class="flex flex-col rounded-lg border border-[#1e3a52] bg-[#132b40] px-3 py-2">
<span class="font-label-sm text-[10px] text-[#94A3B8]">Peak 80% band</span>
<span class="font-tabular-stat-md text-[18px] text-[#00C3CD] font-semibold mt-0.5">
{{ formatBand(summary.peak?.lo, summary.peak?.hi) }}
</span>
<span class="text-[10px] text-[#64748B]">devices/hour</span>
<span class="mt-1 text-[10px] text-[#64748B]">empirical residual range</span>
</div>
</div>
<p v-else class="pl-2 text-[12px] text-[#fbbf24]">
The API returned no points for this run. Change an input and try again.
</p>
<div class="grid grid-cols-1 sm:grid-cols-3 gap-2 border-t border-[#1e3a52]/70 pt-space-sm pl-2">
<div class="min-w-0">
<p class="font-label-sm text-[9px] uppercase tracking-wider text-[#94A3B8]">Model version</p>
<p class="mt-0.5 font-mono text-[10px] leading-snug text-[#FFFFFF] break-all">
{{ result.model_version || '—' }}
</p>
</div>
<div class="min-w-0">
<p class="font-label-sm text-[9px] uppercase tracking-wider text-[#94A3B8]">Data version</p>
<p class="mt-0.5 font-mono text-[10px] leading-snug text-[#FFFFFF] break-all">
{{ result.data_version || '—' }}
</p>
</div>
<div class="min-w-0">
<p class="font-label-sm text-[9px] uppercase tracking-wider text-[#94A3B8]">Context version</p>
<p class="mt-0.5 font-mono text-[10px] leading-snug text-[#FFFFFF] break-all">
{{ result.context_version || '—' }}
</p>
</div>
</div>
</article>
<!-- Chart -->
<article class="rounded-xl border border-[#1e3a52] bg-[#0e2233] p-space-lg shadow-sm flex flex-col gap-space-md min-w-0">
<div class="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
<div>
<h2 class="font-headline-sm text-[16px] text-[#FFFFFF] font-semibold">
Forecast with 80% band
</h2>
<p class="text-[12px] leading-relaxed text-[#94A3B8]">
Estimated devices per hour. Observed history is the last 24 hourly points
before the forecast starts.
</p>
</div>
<div class="flex flex-wrap items-center gap-3 font-label-sm text-[10px] text-[#94A3B8] shrink-0">
<span class="inline-flex items-center gap-1">
<span class="w-3 h-0.5 bg-[#FFFFFF]"></span>
Observed
</span>
<span class="inline-flex items-center gap-1">
<span class="w-3 h-0.5 bg-[#00C3CD]"></span>
Forecast
</span>
<span class="inline-flex items-center gap-1">
<span class="w-2.5 h-2.5 rounded-sm bg-[#00C3CD]/20 border border-[#00C3CD]/40"></span>
80% band
</span>
</div>
</div>
<div class="rounded-lg border border-[#1e3a52] bg-[#081723] p-2 min-w-0">
<PlaygroundChart
:observed="observedWindow"
:forecast="result.points"
/>
</div>
<p v-if="interpolated" class="text-[10px] leading-relaxed text-[#94A3B8]">
Interpolated from hourly model. The 15m and 1h horizons are resampled, not a
native quarter-hour model.
</p>
<p v-if="observedError" class="text-[10px] leading-relaxed text-[#fbbf24]">
Observed history unavailable: {{ observedError }}
</p>
<p
v-else-if="observedPoints.length && !observedWindow.length"
class="text-[10px] leading-relaxed text-[#94A3B8]"
>
No contiguous observed hours immediately before the forecast start; showing forecast only.
</p>
</article>
<!-- Heatmap + comparison -->
<div class="grid grid-cols-1 xl:grid-cols-2 gap-space-lg items-start min-w-0">
<article class="rounded-xl border border-[#1e3a52] bg-[#0e2233] p-space-lg shadow-sm flex flex-col gap-space-sm min-w-0">
<div>
<h2 class="font-headline-sm text-[16px] text-[#FFFFFF] font-semibold">
Weekday × hour heatmap
</h2>
<p class="text-[11px] leading-relaxed text-[#94A3B8]">
Mean forecast devices/hour by local Berlin weekday and hour.
</p>
</div>
<div v-if="heatmap.rows.length" class="overflow-x-auto pb-1">
<div class="min-w-[300px] grid grid-cols-[minmax(58px,1fr)_repeat(6,minmax(32px,1fr))] gap-1 items-center">
<span class="font-label-sm text-[9px] uppercase tracking-wider text-[#64748B]">Day</span>
<span
v-for="hour in heatmap.hours"
:key="`hh-${hour}`"
class="text-center font-label-sm text-[9px] text-[#94A3B8] uppercase"
>
{{ String(hour).padStart(2, '0') }}h
</span>
<template v-for="row in heatmap.rows" :key="row.date">
<span class="flex flex-col leading-tight">
<span class="font-label-sm text-[11px] text-[#FFFFFF] font-semibold">
{{ formatWeekdayShort(row.date) }}
</span>
<span class="text-[9px] text-[#64748B]">{{ formatShortDate(row.date) }}</span>
</span>
<div
v-for="cell in row.cells"
:key="`${row.date}-${cell.hour}`"
class="h-7 rounded border flex items-center justify-center text-[10px] font-semibold"
:class="
cell.value === null
? 'border-dashed border-[#1e3a52]/70'
: 'border-[#00C3CD]/30'
"
:style="
cell.value === null
? undefined
: {
backgroundColor: `rgba(0, 195, 205, ${0.06 + cell.intensity * 0.84})`,
color: cell.intensity > 0.55 ? '#081723' : '#FFFFFF',
}
"
:aria-label="
cell.value === null
? `No forecast at ${cell.hour}:00`
: `${formatNumber(Math.round(cell.value))} devices per hour at ${cell.hour}:00`
"
>
{{ cell.value === null ? '' : formatNumber(Math.round(cell.value)) }}
</div>
</template>
</div>
<div class="mt-2 flex items-center justify-between text-[9px] text-[#64748B]">
<span>Forecast window, not historical week 30.</span>
<span class="inline-flex items-center gap-1">
<span class="w-8 h-1.5 rounded bg-[linear-gradient(90deg,rgba(0,195,205,0.12),rgba(0,195,205,0.9))]"></span>
Low → peak
</span>
</div>
</div>
<p v-else class="text-[12px] text-[#94A3B8]">
No forecast points to bucket for this horizon.
</p>
</article>
<article class="rounded-xl border border-[#1e3a52] bg-[#0e2233] p-space-lg shadow-sm flex flex-col gap-space-sm min-w-0">
<div>
<h2 class="font-headline-sm text-[16px] text-[#FFFFFF] font-semibold">
Scenario comparison
</h2>
<p class="text-[11px] leading-relaxed text-[#94A3B8]">
Selected scenario against base on the same sensor, horizon and weather inputs.
</p>
</div>
<p
v-if="isBaseScenario"
class="rounded-lg border border-[#1e3a52] bg-[#132b40] px-space-md py-3 text-[12px] leading-relaxed text-[#94A3B8]"
>
Base is the reference. Choose another scenario to see a delta.
</p>
<template v-else-if="comparisonRows.length">
<div class="flex flex-col gap-space-sm">
<div
v-for="row in comparisonRows"
:key="row.label"
class="flex flex-col gap-1.5"
>
<div class="flex items-center justify-between gap-2 text-[11px]">
<span class="text-[#94A3B8]">{{ row.label }}</span>
<span class="font-semibold text-[#FFFFFF]">
{{ formatNumber(row.selected) }} vs {{ formatNumber(row.base) }}
</span>
</div>
<div class="flex flex-col gap-1">
<div class="w-full h-2 rounded-full bg-[#081723] border border-[#1e3a52] overflow-hidden">
<div
class="h-full rounded-full bg-[#00C3CD]"
:style="{ width: `${Math.max(2, (row.selected / row.max) * 100)}%` }"
></div>
</div>
<div class="w-full h-2 rounded-full bg-[#081723] border border-[#1e3a52] overflow-hidden">
<div
class="h-full rounded-full bg-[#64748B]"
:style="{ width: `${Math.max(2, (row.base / row.max) * 100)}%` }"
></div>
</div>
</div>
<div class="flex items-center justify-between gap-2 text-[10px]">
<span class="text-[#00C3CD]">Selected</span>
<span class="text-[#94A3B8]">Base</span>
<span
class="rounded border border-[#00C3CD]/30 bg-[#00C3CD]/10 px-1.5 py-0.5 font-semibold text-[#00C3CD]"
>
Δ {{ signed(row.delta) }} ({{ row.pct === null ? '—' : signed(row.pct, '%') }})
</span>
</div>
</div>
</div>
<p class="text-[10px] leading-relaxed text-[#64748B]">
Both requests use the same weather override, so the delta isolates the
scenario event uplift. Scenario presets are assumptions, not causal estimates.
</p>
</template>
<p
v-else-if="comparisonError"
class="rounded-lg border border-[#fbbf24]/40 bg-[#fbbf24]/10 px-space-md py-2 text-[11px] leading-relaxed text-[#fde68a]"
>
Comparison unavailable: {{ comparisonError }}
</p>
<p v-else class="text-[12px] text-[#94A3B8]">
Run the forecast again to load the base comparison.
</p>
</article>
</div>
<!-- Model context -->
<article class="rounded-xl border border-[#1e3a52] bg-[#0e2233] p-space-lg shadow-sm flex flex-col gap-space-md min-w-0">
<div class="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
<div>
<h2 class="font-headline-sm text-[16px] text-[#FFFFFF] font-semibold">Model context</h2>
<p class="text-[11px] leading-relaxed text-[#94A3B8]">
Metadata reported by <code class="text-[#FFFFFF]">/api/meta</code>, not a
marketing model card.
</p>
</div>
<NuxtLink
to="/sensors"
class="inline-flex items-center gap-1.5 font-label-sm text-[11px] text-[#00C3CD] hover:text-[#3ddae4] transition-colors"
>
<Icon name="material-symbols:shield-lock" class="text-[15px]" />
Privacy design
<Icon name="material-symbols:arrow-forward" class="text-[14px]" />
</NuxtLink>
</div>
<template v-if="meta">
<div class="grid grid-cols-1 sm:grid-cols-3 gap-2">
<div class="rounded-lg border border-[#1e3a52] bg-[#132b40] px-3 py-2 min-w-0">
<p class="font-label-sm text-[9px] uppercase tracking-wider text-[#94A3B8]">Model</p>
<p class="mt-0.5 font-mono text-[10px] text-[#FFFFFF] break-all">{{ meta.model_version }}</p>
</div>
<div class="rounded-lg border border-[#1e3a52] bg-[#132b40] px-3 py-2 min-w-0">
<p class="font-label-sm text-[9px] uppercase tracking-wider text-[#94A3B8]">Data</p>
<p class="mt-0.5 font-mono text-[10px] text-[#FFFFFF] break-all">{{ meta.data_version }}</p>
</div>
<div class="rounded-lg border border-[#1e3a52] bg-[#132b40] px-3 py-2 min-w-0">
<p class="font-label-sm text-[9px] uppercase tracking-wider text-[#94A3B8]">Context</p>
<p class="mt-0.5 font-mono text-[10px] text-[#FFFFFF] break-all">{{ meta.context_version }}</p>
</div>
</div>
<div class="grid grid-cols-2 lg:grid-cols-4 gap-2">
<div class="rounded-lg border border-[#1e3a52] bg-[#132b40] px-3 py-2">
<p class="font-label-sm text-[9px] uppercase tracking-wider text-[#94A3B8]">Coverage</p>
<p class="mt-0.5 text-[12px] font-semibold text-[#FFFFFF]">{{ meta.coverage.sensors }} sensors</p>
<p class="text-[10px] text-[#64748B]">{{ meta.coverage.cadence_min }} min cadence</p>
<p class="mt-0.5 text-[9px] leading-snug text-[#64748B]">
{{ formatDate(meta.coverage.from) }} – {{ formatDate(meta.coverage.to) }}
</p>
</div>
<div class="rounded-lg border border-[#1e3a52] bg-[#132b40] px-3 py-2">
<p class="font-label-sm text-[9px] uppercase tracking-wider text-[#94A3B8]">MAE</p>
<p class="mt-0.5 text-[12px] font-semibold text-[#FFFFFF]">{{ formatNumber(meta.metrics.mae) }}</p>
<p class="text-[10px] text-[#64748B]">vs {{ formatNumber(meta.metrics.baseline_mae) }} baseline</p>
<p class="mt-0.5 text-[9px] text-[#64748B]">Holdout, devices/hour</p>
</div>
<div class="rounded-lg border border-[#1e3a52] bg-[#132b40] px-3 py-2">
<p class="font-label-sm text-[9px] uppercase tracking-wider text-[#94A3B8]">WAPE</p>
<p class="mt-0.5 text-[12px] font-semibold text-[#FFFFFF]">{{ formatPercent(meta.metrics.wape, 1) }}</p>
<p class="text-[10px] text-[#64748B]">vs {{ formatPercent(meta.metrics.baseline_wape, 1) }} baseline</p>
<p class="mt-0.5 text-[9px] text-[#64748B]">Holdout, lower is better</p>
</div>
<div class="rounded-lg border border-[#1e3a52] bg-[#132b40] px-3 py-2">
<p class="font-label-sm text-[9px] uppercase tracking-wider text-[#94A3B8]">R²</p>
<p class="mt-0.5 text-[12px] font-semibold text-[#FFFFFF]">{{ meta.metrics.r2.toFixed(3) }}</p>
<p class="text-[10px] text-[#64748B]">Holdout fit</p>
<p class="mt-0.5 text-[9px] text-[#64748B]">{{ meta.metrics.model }} model</p>
</div>
</div>
<div v-if="meta.limits?.length" class="flex flex-col gap-1">
<p class="font-label-sm text-[9px] uppercase tracking-wider text-[#94A3B8]">Known limits</p>
<ul class="flex flex-col gap-1">
<li
v-for="limit in meta.limits"
:key="limit"
class="flex items-start gap-1.5 text-[10px] leading-snug text-[#94A3B8]"
>
<Icon name="material-symbols:info" class="text-[12px] text-[#00C3CD] shrink-0 mt-0.5" />
{{ limit }}
</li>
</ul>
</div>
</template>
<div v-else class="flex items-center justify-between gap-3 rounded-lg border border-[#1e3a52] bg-[#132b40] px-space-md py-3">
<p class="text-[11px] leading-relaxed text-[#94A3B8]">
{{ metaErrorMessage || 'Model metadata is unavailable.' }}
</p>
<button
type="button"
class="shrink-0 h-8 px-3 rounded-lg border border-[#1e3a52] text-[11px] font-semibold text-[#FFFFFF] hover:border-[#00C3CD] transition-colors disabled:opacity-50"
:disabled="metaPending"
@click="refreshMeta()"
>
{{ metaPending ? 'Loading…' : 'Retry' }}
</button>
</div>
</article>
<!-- Transparency -->
<article class="rounded-xl border border-[#1e3a52] bg-[#0e2233] p-space-md flex items-start gap-space-sm">
<Icon name="material-symbols:verified" class="text-[20px] text-[#00C3CD] shrink-0 mt-0.5" />
<div class="flex flex-col gap-1">
<h2 class="font-headline-sm text-[13px] text-[#FFFFFF] font-semibold">
What this forecast is, and is not
</h2>
<p class="text-[11px] leading-relaxed text-[#94A3B8]">
Aggregate estimated-device counts, not people. Eight sensors in a ~580 m
inner-city cluster. Weather is observed in training and forecast in this demo.
Scenario uplifts are explicit assumptions, not causal estimates. The 80% bands
are empirical residuals, not calibrated guarantees.
</p>
</div>
</article>
</template>
</section>
</div>
</div>
</main>
<footer class="mt-auto w-full bg-[#081723] border-t border-[#1e3a52]/50 py-3">
<div class="max-w-[1200px] mx-auto px-margin-desktop flex flex-col sm:flex-row items-center justify-between gap-1 sm:gap-space-lg text-[11px] font-body-sm text-[#94A3B8] opacity-50 hover:opacity-100 transition-opacity duration-200">
<span>© 2026 Schwarz Digits · Privacy by design</span>
<span>Aggregate counts · No identifiers</span>
</div>
</footer>
</div>
</template>
+165
View File
@@ -0,0 +1,165 @@
import type { Point } from '../../shared/types'
export const HEATMAP_HOURS = [8, 10, 12, 14, 16, 18] as const
const partsFormatter = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Europe/Berlin',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hourCycle: 'h23',
})
function berlinParts(iso: string): { date: string; hour: number; weekday: number } {
const parts = Object.fromEntries(
partsFormatter.formatToParts(new Date(iso)).map((part) => [part.type, part.value]),
)
const date = `${parts.year}-${parts.month}-${parts.day}`
return {
date,
hour: Number(parts.hour),
weekday: (new Date(`${date}T12:00:00Z`).getUTCDay() + 6) % 7,
}
}
export interface ForecastSummary {
count: number
peak: Point | null
mean: number
total: number
intervalHours: number
}
export interface HeatmapCell {
hour: number
value: number | null
intensity: number
}
export interface HeatmapRow {
date: string
weekday: number
cells: HeatmapCell[]
}
export interface Heatmap {
hours: number[]
rows: HeatmapRow[]
max: number
}
export interface ScenarioDelta {
peakDelta: number
peakDeltaPct: number | null
meanDelta: number
meanDeltaPct: number | null
}
export function summarizeForecast(points: Point[]): ForecastSummary {
if (!points.length) {
return { count: 0, peak: null, mean: 0, total: 0, intervalHours: 1 }
}
const sorted = [...points].sort((a, b) => Date.parse(a.t) - Date.parse(b.t))
const first = Date.parse(sorted[0]!.t)
const second = Date.parse(sorted[1]?.t ?? sorted[0]!.t)
const intervalHours = sorted.length > 1 && Number.isFinite(second - first) && second > first
? (second - first) / 3_600_000
: 1
let peak = sorted[0]!
let total = 0
for (const point of sorted) {
total += point.v
if (point.v > peak.v) peak = point
}
return {
count: sorted.length,
peak,
mean: total / sorted.length,
total: total * intervalHours,
intervalHours,
}
}
export function formatBand(lo?: number | null, hi?: number | null): string {
if (
lo === null ||
lo === undefined ||
hi === null ||
hi === undefined ||
!Number.isFinite(lo) ||
!Number.isFinite(hi)
) {
return '—'
}
const format = (value: number) => (Number.isInteger(value) ? String(value) : value.toFixed(1))
return `${format(lo)} – ${format(hi)}`
}
export function scenarioDelta(selected: ForecastSummary, base: ForecastSummary): ScenarioDelta {
const selectedPeak = selected.peak?.v ?? 0
const basePeak = base.peak?.v ?? 0
const peakDelta = selectedPeak - basePeak
const meanDelta = selected.mean - base.mean
return {
peakDelta,
peakDeltaPct: basePeak ? (peakDelta / basePeak) * 100 : null,
meanDelta,
meanDeltaPct: base.mean ? (meanDelta / base.mean) * 100 : null,
}
}
/** Group forecast points into local Berlin weekday × exact-hour cells. */
export function buildHeatmap(points: Point[]): Heatmap {
const buckets = new Map<string, { date: string; weekday: number; hour: number; sum: number; count: number }>()
for (const point of points) {
const local = berlinParts(point.t)
if (!HEATMAP_HOURS.includes(local.hour as (typeof HEATMAP_HOURS)[number])) continue
const key = `${local.date}|${local.hour}`
const bucket = buckets.get(key)
if (bucket) {
bucket.sum += point.v
bucket.count += 1
} else {
buckets.set(key, {
date: local.date,
weekday: local.weekday,
hour: local.hour,
sum: point.v,
count: 1,
})
}
}
const dates = [...new Set([...buckets.values()].map((bucket) => bucket.date))].sort()
let maximum = 0
for (const bucket of buckets.values()) {
maximum = Math.max(maximum, bucket.sum / bucket.count)
}
return {
hours: [...HEATMAP_HOURS],
max: maximum,
rows: dates.map((date) => {
const dayBuckets = [...buckets.values()].filter((bucket) => bucket.date === date)
return {
date,
weekday: dayBuckets[0]?.weekday ?? 0,
cells: HEATMAP_HOURS.map((hour) => {
const bucket = dayBuckets.find((item) => item.hour === hour)
const value = bucket ? bucket.sum / bucket.count : null
return {
hour,
value,
intensity: value === null || maximum <= 0 ? 0 : Math.min(1, value / maximum),
}
}),
}
}),
}
}
+7
View File
@@ -47,6 +47,13 @@ export default defineNuxtConfig({
'material-symbols:functions', 'material-symbols:functions',
'material-symbols:verified', 'material-symbols:verified',
'material-symbols:shield-with-heart', 'material-symbols:shield-with-heart',
'material-symbols:restart-alt',
'material-symbols:progress-activity',
'material-symbols:bolt',
'material-symbols:error',
'material-symbols:cloud-off',
'material-symbols:water-drop',
'material-symbols:info',
], ],
scan: true, scan: true,
}, },
+67
View File
@@ -0,0 +1,67 @@
import { HORIZONS, SCENARIOS } from '../../shared/types'
import type {
Horizon,
PlaygroundForecastResponse,
Scenario,
} from '../../shared/types'
import { apiRequest, enumParam, isMockMode, sensorParam } from '../utils/api'
function numberParam(
value: unknown,
name: string,
min: number,
max: number,
): number | undefined {
if (value === undefined || value === '') return undefined
const raw = Array.isArray(value) ? value[0] : value
const parsed = Number(raw)
if (!Number.isFinite(parsed)) {
throw createError({ statusCode: 400, statusMessage: `${name} must be a number` })
}
if (parsed < min || parsed > max) {
throw createError({
statusCode: 400,
statusMessage: `${name} must be between ${min} and ${max}`,
})
}
return parsed
}
function booleanParam(value: unknown, name: string): boolean | undefined {
if (value === undefined || value === '') return undefined
const raw = String(Array.isArray(value) ? value[0] : value).toLowerCase()
if (raw === 'true' || raw === '1') return true
if (raw === 'false' || raw === '0') return false
throw createError({ statusCode: 400, statusMessage: `${name} must be a boolean` })
}
// Browser-facing playground proxy. The page calls /api/playground; only this
// Nitro route talks to the public Go endpoint.
export default defineEventHandler(async (event) => {
const query = getQuery(event)
const sensor = sensorParam(query.sensor)
const horizon = enumParam<Horizon>(query.horizon, HORIZONS, 'horizon', '48h')
const scenario = enumParam<Scenario>(query.scenario, SCENARIOS, 'scenario', 'base')
const tempC = numberParam(query.temp_c, 'temp_c', -30, 50)
const precipMm = numberParam(query.precip_mm, 'precip_mm', 0, 50)
const isHoliday = booleanParam(query.is_holiday, 'is_holiday')
if (isMockMode()) {
throw createError({
statusCode: 503,
statusMessage:
'Mock mode is enabled, but the playground has no demo forecast. Start the real Python and Go services or unset NUXT_PUBLIC_USE_MOCK.',
})
}
return apiRequest<PlaygroundForecastResponse>('/api/playground/forecast', {
query: {
sensor,
horizon,
scenario,
...(tempC === undefined ? {} : { temp_c: tempC }),
...(precipMm === undefined ? {} : { precip_mm: precipMm }),
...(isHoliday === undefined ? {} : { is_holiday: isHoliday }),
},
})
})
+19
View File
@@ -166,6 +166,25 @@ export interface ScenarioPreset extends ScenarioDefinition {
description: string description: string
} }
export interface PlaygroundRequestContext {
temp_c?: number
precip_mm?: number
is_holiday?: boolean
}
/** Public playground forecast: the normal forecast plus the inputs the model saw. */
export interface PlaygroundForecastResponse {
sensor: string
horizon: Horizon
scenario: Scenario
points: Point[]
data_version: string
model_version: string
context_version: string
weather_source: 'forecast' | 'override'
request: PlaygroundRequestContext
}
export interface DemoClock { export interface DemoClock {
now: string now: string
plan_start: string plan_start: string
+144
View File
@@ -0,0 +1,144 @@
import { describe, expect, it } from 'vitest'
import type { Point } from '../shared/types'
import {
buildHeatmap,
formatBand,
scenarioDelta,
summarizeForecast,
} from '../app/utils/playground'
import type { ForecastSummary } from '../app/utils/playground'
const hourly: Point[] = [
{ t: '2026-11-16T07:00:00Z', v: 10, lo: 8, hi: 12 },
{ t: '2026-11-16T08:00:00Z', v: 20, lo: 16, hi: 24 },
{ t: '2026-11-16T09:00:00Z', v: 30, lo: 24, hi: 36 },
]
describe('summarizeForecast', () => {
it('returns peak, mean and modeled device-hours for hourly points', () => {
const summary = summarizeForecast(hourly)
expect(summary.count).toBe(3)
expect(summary.peak?.t).toBe('2026-11-16T09:00:00Z')
expect(summary.peak?.v).toBe(30)
expect(summary.mean).toBe(20)
expect(summary.total).toBe(60)
expect(summary.intervalHours).toBe(1)
})
it('scales total by the real 15-minute spacing', () => {
const points: Point[] = [
{ t: '2026-11-16T07:00:00Z', v: 10 },
{ t: '2026-11-16T07:15:00Z', v: 20 },
{ t: '2026-11-16T07:30:00Z', v: 30 },
]
const summary = summarizeForecast(points)
expect(summary.intervalHours).toBe(0.25)
expect(summary.total).toBe(15)
expect(summary.mean).toBe(20)
})
it('handles an empty forecast without inventing a point', () => {
const summary = summarizeForecast([])
expect(summary.count).toBe(0)
expect(summary.peak).toBeNull()
expect(summary.mean).toBe(0)
expect(summary.total).toBe(0)
})
})
describe('buildHeatmap', () => {
const points: Point[] = [
{ t: '2026-11-16T07:00:00Z', v: 10 },
{ t: '2026-11-16T09:00:00Z', v: 20 },
{ t: '2026-11-16T09:30:00Z', v: 40 },
{ t: '2026-11-17T07:00:00Z', v: 55 },
{ t: '2026-11-17T08:00:00Z', v: 99 },
]
it('groups by Berlin local date and hour and leaves gaps empty', () => {
const heatmap = buildHeatmap(points)
expect(heatmap.hours).toEqual([8, 10, 12, 14, 16, 18])
expect(heatmap.rows.map((row) => row.date)).toEqual([
'2026-11-16',
'2026-11-17',
])
const monday = heatmap.rows[0]!
expect(monday.cells.map((cell) => cell.value)).toEqual([
10,
30,
null,
null,
null,
null,
])
expect(monday.cells[2]!.value).toBeNull()
expect(monday.cells[2]!.intensity).toBe(0)
})
it('averages every point inside the same local hour bucket', () => {
const heatmap = buildHeatmap(points)
const mondayTen = heatmap.rows[0]!.cells[1]!
expect(mondayTen.hour).toBe(10)
expect(mondayTen.value).toBe(30)
})
it('scales intensity against the busiest filled bucket', () => {
const heatmap = buildHeatmap(points)
expect(heatmap.max).toBe(55)
expect(heatmap.rows[1]!.cells[0]!.intensity).toBe(1)
expect(heatmap.rows[0]!.cells[0]!.intensity).toBeCloseTo(10 / 55)
})
it('returns no rows for an empty forecast', () => {
const heatmap = buildHeatmap([])
expect(heatmap.rows).toEqual([])
expect(heatmap.max).toBe(0)
expect(heatmap.hours).toEqual([8, 10, 12, 14, 16, 18])
})
})
describe('formatBand', () => {
it('formats the empirical band with one optional decimal', () => {
expect(formatBand(9, 13)).toBe('9 – 13')
expect(formatBand(7.4, 17.2)).toBe('7.4 – 17.2')
expect(formatBand(undefined, 17.2)).toBe('—')
})
})
describe('scenarioDelta', () => {
function summary(peak: number, mean: number): ForecastSummary {
return {
count: 2,
peak: { t: '2026-11-16T09:00:00Z', v: peak },
mean,
total: mean * 2,
intervalHours: 1,
}
}
it('compares peak and mean against base', () => {
const delta = scenarioDelta(summary(120, 90), summary(100, 80))
expect(delta.peakDelta).toBe(20)
expect(delta.peakDeltaPct).toBeCloseTo(20)
expect(delta.meanDelta).toBe(10)
expect(delta.meanDeltaPct).toBeCloseTo(12.5)
})
it('returns a null percentage when base is zero', () => {
const delta = scenarioDelta(summary(12, 6), summary(0, 0))
expect(delta.peakDelta).toBe(12)
expect(delta.peakDeltaPct).toBeNull()
expect(delta.meanDelta).toBe(6)
expect(delta.meanDeltaPct).toBeNull()
})
})