File size: 10,643 Bytes
2be44dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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,
  };
}