eurometeo / src /utils /chartHelpers.ts
alexdum's picture
feat(charts): phase 2 climatological station chart & wind rose upgrade
2be44dc
Raw History Blame Contribute Delete
10.6 kB
import { HourlyRow, NON_NEGATIVE_PARAMS } from "@/utils/qc";
export interface ChartLegendItem {
label: string;
color: string;
variant?: "line" | "area" | "bar" | "dot" | "dashed";
}
export interface ReferenceLineSpec {
y: number;
label: string;
color: string;
showWhenNear?: number;
showWhenBelow?: number;
}
export interface TimeSeriesPoint {
timestampMs: number;
__isGap?: boolean;
[key: string]: number | boolean | null | undefined;
}
const UTC_TICK_FORMATTER = new Intl.DateTimeFormat("en-US", {
timeZone: "UTC",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
});
/** Format a UTC epoch millisecond timestamp consistently with an explicit UTC suffix. */
export function formatUtcTimestamp(ms: number): string {
if (!Number.isFinite(ms)) return "";
return `${UTC_TICK_FORMATTER.format(new Date(ms))} UTC`;
}
/** Format the closed UTC date/time span covered by an observation array. */
export function formatUtcDateRange(data: HourlyRow[]): string | undefined {
let minMs = Infinity;
let maxMs = -Infinity;
for (const row of data) {
const ms = Date.parse(row.datetime);
if (!Number.isFinite(ms)) continue;
if (ms < minMs) minMs = ms;
if (ms > maxMs) maxMs = ms;
}
if (!Number.isFinite(minMs) || !Number.isFinite(maxMs)) return undefined;
if (minMs === maxMs) return formatUtcTimestamp(minMs);
return `${formatUtcTimestamp(minMs)} – ${formatUtcTimestamp(maxMs)}`;
}
function isNonNegativeParam(key: string): boolean {
return NON_NEGATIVE_PARAMS.some((p) => key === p || key.startsWith(p));
}
function computeMedian(values: number[]): number {
if (values.length === 0) return 0;
const sorted = [...values].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
if (sorted.length % 2 === 1) return sorted[mid];
return (sorted[mid - 1] + sorted[mid]) / 2;
}
/**
* Convert raw hourly rows into a sorted numeric-time series without mutating input rows.
* Optionally inserts midpoint null gap rows when dt > 1.8 * median(dt) and marks
* isolated non-null observations (`__isolated_<key>`) so single/synoptic points render visible dots.
*/
export function buildTimeSeriesData(
data: HourlyRow[],
keys: string[],
options?: {
insertGapNulls?: boolean;
scaleByKey?: Record<string, number>;
}
): TimeSeriesPoint[] {
const nonNegativeFlags = keys.map(isNonNegativeParam);
const rawPoints: TimeSeriesPoint[] = [];
for (const row of data) {
const timestampMs = Date.parse(row.datetime);
if (!Number.isFinite(timestampMs)) continue;
const point: TimeSeriesPoint = { timestampMs };
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const raw = row[key];
if (typeof raw !== "number" || !Number.isFinite(raw)) {
point[key] = null;
continue;
}
if (raw < 0 && nonNegativeFlags[i]) {
point[key] = null;
continue;
}
const scale = options?.scaleByKey?.[key] ?? 1;
point[key] = raw * scale;
}
rawPoints.push(point);
}
rawPoints.sort((a, b) => a.timestampMs - b.timestampMs);
let points: TimeSeriesPoint[] = rawPoints;
if (options?.insertGapNulls !== false && rawPoints.length >= 2) {
const positiveDeltas: number[] = [];
for (let i = 1; i < rawPoints.length; i++) {
const dt = rawPoints[i].timestampMs - rawPoints[i - 1].timestampMs;
if (dt > 0) positiveDeltas.push(dt);
}
const medianDt = computeMedian(positiveDeltas);
if (medianDt > 0) {
const gapThreshold = 1.8 * medianDt;
const withGaps: TimeSeriesPoint[] = [];
for (let i = 0; i < rawPoints.length; i++) {
if (i > 0) {
const prev = rawPoints[i - 1];
const curr = rawPoints[i];
if (curr.timestampMs - prev.timestampMs > gapThreshold) {
const gapPoint: TimeSeriesPoint = {
timestampMs: Math.round((prev.timestampMs + curr.timestampMs) / 2),
__isGap: true,
};
for (const key of keys) {
gapPoint[key] = null;
}
withGaps.push(gapPoint);
}
}
withGaps.push(rawPoints[i]);
}
points = withGaps;
}
}
for (const key of keys) {
const isolatedFlag = `__isolated_${key}`;
for (let i = 0; i < points.length; i++) {
const currVal = points[i][key];
if (typeof currVal !== "number" || !Number.isFinite(currVal)) continue;
const prevVal = i > 0 ? points[i - 1][key] : null;
const nextVal = i < points.length - 1 ? points[i + 1][key] : null;
const prevEmpty = typeof prevVal !== "number" || !Number.isFinite(prevVal);
const nextEmpty = typeof nextVal !== "number" || !Number.isFinite(nextVal);
if (prevEmpty && nextEmpty) {
points[i][isolatedFlag] = true;
}
}
}
return points;
}
/** Return finite [min, max] bounds across the specified keys, ignoring gap sentinels. */
export function computeNumericBounds(
points: TimeSeriesPoint[],
keys: string[]
): { min: number; max: number } | null {
let min = Infinity;
let max = -Infinity;
for (const pt of points) {
if (pt.__isGap) continue;
for (const key of keys) {
const val = pt[key];
if (typeof val !== "number" || !Number.isFinite(val)) continue;
if (val < min) min = val;
if (val > max) max = val;
}
}
if (!Number.isFinite(min) || !Number.isFinite(max)) return null;
return { min, max };
}
/** Compute a non-degenerate continuous time domain for Recharts numerical XAxis. */
export function computeTimeDomain(
points: TimeSeriesPoint[]
): [number, number] | ["dataMin", "dataMax"] {
if (points.length === 0) return ["dataMin", "dataMax"];
const first = points[0].timestampMs;
const last = points[points.length - 1].timestampMs;
if (first === last) {
return [first - 1_800_000, last + 1_800_000];
}
return ["dataMin", "dataMax"];
}
/** Filter declarative ReferenceLineSpec rules against observed series bounds. */
export function filterActiveReferenceLines(
specs: ReferenceLineSpec[] | undefined,
bounds: { min: number; max: number } | null
): ReferenceLineSpec[] {
if (!specs?.length || !bounds) return [];
return specs.filter((spec) => {
if (spec.showWhenNear !== undefined) {
return bounds.min <= spec.y + spec.showWhenNear && bounds.max >= spec.y - spec.showWhenNear;
}
if (spec.showWhenBelow !== undefined) {
return bounds.min < spec.showWhenBelow;
}
return true;
});
}
export const WIND_ROSE_DIRECTIONS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] as const;
export const COMPASS_16 = [
"N", "NNE", "NE", "ENE",
"E", "ESE", "SE", "SSE",
"S", "SSW", "SW", "WSW",
"W", "WNW", "NW", "NNW",
] as const;
/** Map meteorological wind direction azimuth (degrees) to 16-point compass sector. */
export function degreesToCompass16(deg: number): string {
const norm = ((deg % 360) + 360) % 360;
const index = Math.floor(((norm + 11.25) % 360) / 22.5);
return COMPASS_16[index] ?? "N";
}
export const CALM_THRESHOLD_MS = 0.5;
export interface WindRoseClassSpec {
key: "c1" | "c2" | "c3" | "c4" | "c5";
minMs: number;
maxMs: number;
label: string;
shortLabel: string;
color: string;
}
export const WIND_ROSE_CLASSES: readonly WindRoseClassSpec[] = [
{ key: "c1", minMs: 0.5, maxMs: 3.4, label: "Light · 0.5–3.3 m/s (2–12 km/h)", shortLabel: "0.5–3.3 m/s", color: "#38bdf8" },
{ key: "c2", minMs: 3.4, maxMs: 8.0, label: "Gentle–Moderate · 3.4–7.9 m/s (12–28 km/h)", shortLabel: "3.4–7.9 m/s", color: "#fbbf24" },
{ key: "c3", minMs: 8.0, maxMs: 13.9, label: "Fresh–Strong · 8.0–13.8 m/s (29–50 km/h)", shortLabel: "8.0–13.8 m/s", color: "#fb923c" },
{ key: "c4", minMs: 13.9, maxMs: 20.8, label: "Near–Strong Gale · 13.9–20.7 m/s (50–75 km/h)", shortLabel: "13.9–20.7 m/s", color: "#f43f5e" },
{ key: "c5", minMs: 20.8, maxMs: Infinity, label: "Storm+ · ≥ 20.8 m/s (≥ 75 km/h)", shortLabel: "≥ 20.8 m/s", color: "#a855f7" },
] as const;
export interface WindRoseSectorDatum {
dir: (typeof WIND_ROSE_DIRECTIONS)[number];
c1: number;
c2: number;
c3: number;
c4: number;
c5: number;
total: number;
}
export interface WindRoseSummary {
dataPoints: WindRoseSectorDatum[];
totalValid: number;
calmCount: number;
calmPct: number;
maxSectorPct: number;
ringMaxPct: number;
}
/**
* Aggregate wind observations into Calm (< 0.5 m/s) + 8 compass sectors binned by WMO Beaufort intervals.
* Calm winds are excluded from directional petals even when reported at 0 degrees or with null direction.
*/
export function computeWindRoseData(data: HourlyRow[]): WindRoseSummary {
const counts = WIND_ROSE_DIRECTIONS.reduce(
(acc, dir) => {
acc[dir] = { c1: 0, c2: 0, c3: 0, c4: 0, c5: 0 };
return acc;
},
{} as Record<string, { c1: number; c2: number; c3: number; c4: number; c5: number }>
);
let totalValid = 0;
let calmCount = 0;
for (const row of data) {
const speed = row.windSpeed;
const dir = row.windDirection;
if (typeof speed !== "number" || !Number.isFinite(speed) || speed < 0) continue;
if (speed < CALM_THRESHOLD_MS) {
calmCount++;
totalValid++;
continue;
}
if (typeof dir !== "number" || !Number.isFinite(dir)) continue;
totalValid++;
const normalizedDir = ((dir % 360) + 360) % 360;
const sectorIndex = Math.floor(((normalizedDir + 22.5) % 360) / 45);
const sector = WIND_ROSE_DIRECTIONS[sectorIndex];
if (!sector || !counts[sector]) continue;
if (speed < 3.4) counts[sector].c1++;
else if (speed < 8.0) counts[sector].c2++;
else if (speed < 13.9) counts[sector].c3++;
else if (speed < 20.8) counts[sector].c4++;
else counts[sector].c5++;
}
const denom = totalValid || 1;
const dataPoints: WindRoseSectorDatum[] = WIND_ROSE_DIRECTIONS.map((dir) => {
const item = counts[dir];
const c1 = (item.c1 / denom) * 100;
const c2 = (item.c2 / denom) * 100;
const c3 = (item.c3 / denom) * 100;
const c4 = (item.c4 / denom) * 100;
const c5 = (item.c5 / denom) * 100;
return {
dir,
c1,
c2,
c3,
c4,
c5,
total: c1 + c2 + c3 + c4 + c5,
};
});
const calmPct = totalValid > 0 ? (calmCount / totalValid) * 100 : 0;
const maxSectorPct = Math.max(0, ...dataPoints.map((d) => d.total));
const ringMaxPct = Math.max(10, Math.ceil(maxSectorPct / 5) * 5);
return {
dataPoints,
totalValid,
calmCount,
calmPct,
maxSectorPct,
ringMaxPct,
};
}