All files / src/utils geomap.ts

95.65% Statements 176/184
77.58% Branches 90/116
96.55% Functions 28/29
98.71% Lines 154/156

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394              16x                                                                                                 16x                                                                                               16x       16x     38x 37x       720x 720x 720x 720x 720x 720x 2160x 720x       99x         63x   61x     45x   63x 720x 63x       102x                           35x 34x 35x 35x 35x 34x   34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x         27x 27x 27x   400x 400x     27x           5x 5x 5x 5x         34x 34x 34x 34x 34x 15x 15x       28x 28x       33x 33x 38x 38x 38x   33x 30x 30x 30x   33x               33x 76x 76x   33x 38x 38x           33x 33x 38x 38x 38x 38x   38x 38x 38x     38x       38x       38x       38x       38x 38x   38x 38x 38x   38x                                   33x       45x 45x 82x 82x   45x 30x 30x 60x 60x 60x 60x 60x 60x   30x 30x 30x 27x 27x   30x 30x       44x 44x           12x 2x 2x 2x 8x 4x 4x 4x 1x   8x   2x 2x 8x 8x 4x 4x 4x 2x   8x   2x 2x 2x       2x 2x 4x         2x 2x 2x 2x 7x 7x 7x 7x 7x 7x   2x       2x 2x    
// File: src/utils/geomap.ts
import {
  COLOR_PALETTES,
  sampleColorPaletteById,
  type ColorPaletteId
} from '@ska-octopus-widget-sdk/widget-sdk';
 
export const ATTR = {
  preaduLevels: 'preaduLevels',
  adcpower: 'adcpower',
  PortsCurrentDraw: 'PortsCurrentDraw',
  PortBreakersTripped: 'PortBreakersTripped'
} as const;
 
export type LayoutRow = {
  id: string;
  station: string; // "s8-1"
  smartbox: string; // "sb05"
  smartbox_port: number; // 1..N
  label: string; // "sb05-09"
  tpm: string; // "tpm01"
  tpm_x_channel: number;
  tpm_y_channel: number;
  east: number | null;
  north: number | null;
  masked?: boolean;
};
 
export type Row = { device: string; name: string; value: any };
 
export type Antenna = {
  label: string;
  sb: string;
  port: number;
  tpmFull: string;
  chX: number | null;
  chY: number | null;
  pwr_x: number | null;
  pwr_y: number | null;
  atten_x: number | null;
  atten_y: number | null;
  fem_current: number | null;
  tripped: boolean | null;
  masked: boolean;
  east: number | null;
  north: number | null;
};
 
export type Pt = { x: number; y: number };
 
export type RGB = [number, number, number];
export type LegacyColorScaleName = 'Viridis' | 'Cividis' | 'Jet' | 'YlGnBu';
export type ColorScaleName = ColorPaletteId | LegacyColorScaleName;
 
/* ─────────────────────── Color scales & helpers ─────────────────────── */
 
const LEGACY_PALETTES: Record<LegacyColorScaleName, RGB[]> = {
  Viridis: [
    [68, 1, 84],
    [72, 40, 120],
    [59, 82, 139],
    [49, 104, 142],
    [38, 130, 142],
    [31, 158, 137],
    [53, 183, 121],
    [108, 206, 89],
    [180, 222, 44],
    [253, 231, 37]
  ],
  Cividis: [
    [0, 32, 76],
    [25, 45, 91],
    [44, 58, 102],
    [58, 72, 110],
    [73, 87, 117],
    [89, 103, 120],
    [107, 120, 121],
    [127, 139, 118],
    [152, 161, 109],
    [181, 185, 94],
    [213, 211, 79]
  ],
  Jet: [
    [0, 0, 131],
    [0, 60, 170],
    [5, 255, 255],
    [120, 255, 120],
    [255, 255, 0],
    [255, 170, 0],
    [250, 0, 0],
    [128, 0, 0]
  ],
  YlGnBu: [
    [255, 255, 204],
    [199, 233, 180],
    [127, 205, 187],
    [65, 182, 196],
    [29, 145, 192],
    [34, 94, 168],
    [12, 44, 132]
  ]
};
 
const DEFAULT_SDK_COLOR_SCHEME: ColorPaletteId = (
  Object.keys(COLOR_PALETTES).includes('scientificActon10')
    ? 'scientificActon10'
    : (Object.keys(COLOR_PALETTES)[0] ?? 'tableau10')
) as ColorPaletteId;
export const DEFAULT_COLOR_SCHEME: ColorScaleName = DEFAULT_SDK_COLOR_SCHEME;
 
export function getColorScaleLabel(scale: ColorScaleName): string {
  if (isLegacyScale(scale)) return scale;
  return COLOR_PALETTES[scale as ColorPaletteId]?.label ?? String(scale);
}
 
function hexToRgb(hex: string): RGB | null {
  const s = String(hex).trim().replace(/^#/, '');
  Iif (!/^[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(s)) return null;
  const rgb = s.slice(0, 6);
  const r = Number.parseInt(rgb.slice(0, 2), 16);
  const g = Number.parseInt(rgb.slice(2, 4), 16);
  const b = Number.parseInt(rgb.slice(4, 6), 16);
  Iif (![r, g, b].every((v) => Number.isFinite(v))) return null;
  return [r, g, b];
}
 
function isLegacyScale(scale: ColorScaleName): scale is LegacyColorScaleName {
  return scale in LEGACY_PALETTES;
}
 
/** If a custom palette is provided and non-empty, use it; otherwise fallback to SDK palette or legacy by name. */
export function getPalette(scale: ColorScaleName, customPalette?: RGB[]): RGB[] {
  if (Array.isArray(customPalette) && customPalette.length > 0) return customPalette;
 
  if (isLegacyScale(scale)) return LEGACY_PALETTES[scale] ?? LEGACY_PALETTES.Viridis;
 
  const paletteId = (
    COLOR_PALETTES[scale as ColorPaletteId] ? scale : DEFAULT_SDK_COLOR_SCHEME
  ) as ColorPaletteId;
  const sampled = sampleColorPaletteById(paletteId, 16);
  const rgb = sampled.map(hexToRgb).filter((x): x is RGB => Array.isArray(x));
  return rgb.length > 1 ? rgb : LEGACY_PALETTES.Viridis;
}
 
function lerp(a: number, b: number, t: number) {
  return a + (b - a) * t;
}
 
/**
 * Map a numeric value within [min,max] to a color from the chosen palette.
 * If customPalette is provided (non-empty), it overrides the builtin scale.
 */
export function colorForPower(
  val: number,
  min: number,
  max: number,
  scale: ColorScaleName = DEFAULT_SDK_COLOR_SCHEME,
  customPalette?: RGB[]
) {
  if (!isFinite(val)) return '#999';
  const lo = isFinite(min) ? min : 0;
  const hi = isFinite(max) && max !== min ? max : lo + 1;
  let t = (val - lo) / (hi - lo);
  Iif (!isFinite(t)) t = 0;
  t = Math.max(0, Math.min(1, t));
 
  const palette = getPalette(scale, customPalette);
  const n = Math.max(1, palette.length - 1);
  const x = t * n;
  const i = Math.floor(x);
  const f = Math.min(1, x - i);
  const [r1, g1, b1] = palette[Math.max(0, Math.min(i, n))];
  const [r2, g2, b2] = palette[Math.max(0, Math.min(i + 1, n))];
  const r = Math.round(lerp(r1, r2, f));
  const g = Math.round(lerp(g1, g2, f));
  const b = Math.round(lerp(b1, b2, f));
  return `rgb(${r}, ${g}, ${b})`;
}
 
/** Build a CSS linear-gradient for the legend (left→right). */
export function gradientCss(scale: ColorScaleName, customPalette?: RGB[]): string {
  const pal = getPalette(scale, customPalette);
  const n = Math.max(1, pal.length - 1);
  const stops = pal
    .map(([r, g, b], i) => {
      const pct = Math.round((i * 100) / n);
      return `rgb(${r}, ${g}, ${b}) ${pct}%`;
    })
    .join(', ');
  return `linear-gradient(to right, ${stops})`;
}
 
/* ───────────────────────── Array & math helpers ───────────────────────── */
 
export function chunk<T>(arr: T[], n: number): T[][] {
  const size = Math.max(1, Math.floor(n));
  const out: T[][] = [];
  for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
  return out;
}
 
/** Pixel-stable antenna radius; can be less than 1px if desired. */
export function radiusPx(attenDb: number | null | undefined, minPx: number, maxPx: number) {
  const clampMin = Math.max(0.1, minPx); // allow sub-1px, but keep >=0.1
  const clampMax = Math.max(clampMin, maxPx);
  const minDb = 0,
    maxDb = 32;
  if (attenDb == null || !isFinite(attenDb)) return (clampMin + clampMax) * 0.5;
  const t = Math.max(0, Math.min(1, (attenDb - minDb) / (maxDb - minDb)));
  return clampMin + (1 - t) * (clampMax - clampMin);
}
 
export function fmt2(v: number | null | undefined) {
  const n = Number(v);
  return isFinite(n) ? n.toFixed(2) : '—';
}
 
export function buildFullNames(smartboxes: string[], tpmIds: string[], stationId: string) {
  const names = new Set<string>();
  for (const sb of smartboxes) {
    const sbDev = `low-mccs/smartbox/${stationId}-${sb}`;
    names.add(`${sbDev}/${ATTR.PortsCurrentDraw}`);
    names.add(`${sbDev}/${ATTR.PortBreakersTripped}`);
  }
  for (const tpmId of tpmIds) {
    const tileDev = `low-mccs/tile/${tpmId}`;
    names.add(`${tileDev}/${ATTR.preaduLevels}`);
    names.add(`${tileDev}/${ATTR.adcpower}`);
  }
  return Array.from(names);
}
 
export function buildAntennas(
  layoutRows: LayoutRow[],
  byDev: Map<string, Map<string, any>>,
  stationId: string
): Antenna[] {
  const getSmartboxArr = (sbSuffix: string, key: string) => {
    const dev = `low-mccs/smartbox/${stationId}-${sbSuffix}`;
    return byDev.get(dev)?.get(key.toLowerCase()) as any[] | undefined;
  };
  const getTileArrs = (tpmFull: string) => {
    const dev = `low-mccs/tile/${tpmFull}`;
    return {
      pwr: byDev.get(dev)?.get(ATTR.adcpower.toLowerCase()) as number[] | undefined,
      pre: byDev.get(dev)?.get(ATTR.preaduLevels.toLowerCase()) as number[] | undefined
    };
  };
 
  const list: Antenna[] = [];
  for (const r of layoutRows) {
    const sb = String(r.smartbox).trim();
    const port = Number(r.smartbox_port);
    const label = r.label || `${sb}-${String(port).padStart(2, '0')}`;
    const tpmFull = `${stationId}-${String(r.tpm).trim()}`;
 
    const tile = getTileArrs(tpmFull);
    const chX = Number(r.tpm_x_channel);
    const chY = Number(r.tpm_y_channel);
 
    const pwr_x =
      Array.isArray(tile?.pwr) && chX >= 0 && chX < (tile?.pwr?.length ?? 0)
        ? Number(tile!.pwr![chX])
        : null;
    const pwr_y =
      Array.isArray(tile?.pwr) && chY >= 0 && chY < (tile?.pwr?.length ?? 0)
        ? Number(tile!.pwr![chY])
        : null;
    const atten_x =
      Array.isArray(tile?.pre) && chX >= 0 && chX < (tile?.pre?.length ?? 0)
        ? Number(tile!.pre![chX])
        : null;
    const atten_y =
      Array.isArray(tile?.pre) && chY >= 0 && chY < (tile?.pre?.length ?? 0)
        ? Number(tile!.pre![chY])
        : null;
 
    const curr = getSmartboxArr(sb, ATTR.PortsCurrentDraw);
    const brk = getSmartboxArr(sb, ATTR.PortBreakersTripped);
    const fem_current =
      Array.isArray(curr) && port - 1 < curr.length ? Number(curr[port - 1]) : null;
    const b = Array.isArray(brk) && port - 1 < brk.length ? brk[port - 1] : null;
    const tripped = b == null ? null : typeof b === 'boolean' ? b : Number(b) !== 0;
 
    list.push({
      label,
      sb,
      port,
      tpmFull,
      chX: isFinite(chX) ? chX : null,
      chY: isFinite(chY) ? chY : null,
      pwr_x,
      pwr_y,
      atten_x,
      atten_y,
      fem_current,
      tripped,
      masked: !!r.masked,
      east: r.east ?? null,
      north: r.north ?? null
    });
  }
  return list;
}
 
export function computePowerRange(antennas: Antenna[]) {
  const vals: number[] = [];
  for (const a of antennas) {
    const m = [a.pwr_x, a.pwr_y].filter((v) => isFinite(v as any)) as number[];
    Eif (m.length) vals.push(m.reduce((s, v) => s + v, 0) / m.length);
  }
  if (!vals.length) return { min: 0, max: 1 };
  vals.sort((a, b) => a - b);
  const q = (p: number) => {
    const pos = (vals.length - 1) * p,
      b = Math.floor(pos),
      r = pos - b;
    const v1 = vals[b],
      v2 = vals[Math.min(b + 1, vals.length - 1)];
    return v1 + r * (v2 - v1);
  };
  let lo = q(0.05),
    hi = q(0.95);
  if (!isFinite(lo) || !isFinite(hi) || hi <= lo) {
    lo = vals[0];
    hi = vals[vals.length - 1] || lo + 1e-6;
  }
  if (hi - lo < 1e-6) hi = lo + 1e-6;
  return { min: lo, max: hi };
}
 
export function computeTicks(range: { min: number; max: number }) {
  const step = (range.max - range.min) / 4;
  return [range.min, range.min + step, range.min + 2 * step, range.min + 3 * step, range.max];
}
 
/* ──────────────────────── Geometry helpers for grouping ───────────────────── */
 
export function convexHull(pts: Pt[]): Pt[] {
  const a = pts.slice().sort((p, q) => (p.x === q.x ? p.y - q.y : p.x - q.x));
  Iif (a.length <= 1) return a;
  const lower: Pt[] = [];
  for (const p of a) {
    while (lower.length >= 2) {
      const q = lower[lower.length - 1];
      const r = lower[lower.length - 2];
      if ((q.x - r.x) * (p.y - r.y) - (q.y - r.y) * (p.x - r.x) <= 0) lower.pop();
      else break;
    }
    lower.push(p);
  }
  const upper: Pt[] = [];
  for (let i = a.length - 1; i >= 0; i--) {
    const p = a[i];
    while (upper.length >= 2) {
      const q = upper[upper.length - 1];
      const r = upper[upper.length - 2];
      if ((q.x - r.x) * (p.y - r.y) - (q.y - r.y) * (p.x - r.x) <= 0) upper.pop();
      else break;
    }
    upper.push(p);
  }
  upper.pop();
  lower.pop();
  return lower.concat(upper);
}
 
export function pathFromPolygon(poly: Pt[]) {
  Iif (!poly.length) return '';
  const [h, ...t] = poly;
  return `M ${h.x} ${h.y}` + t.map((p) => ` L ${p.x} ${p.y}`).join('') + ' Z';
}
 
export function polygonCentroid(poly: Pt[]): Pt {
  // Area-weighted centroid for polygon; fall back to average if degenerate.
  let a = 0,
    cx = 0,
    cy = 0;
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
    const p = poly[i],
      q = poly[j];
    const f = p.x * q.y - q.x * p.y;
    a += f;
    cx += (p.x + q.x) * f;
    cy += (p.y + q.y) * f;
  }
  Iif (Math.abs(a) < 1e-9) {
    const s = poly.reduce((acc, p) => ({ x: acc.x + p.x, y: acc.y + p.y }), { x: 0, y: 0 });
    return { x: s.x / poly.length, y: s.y / poly.length };
  }
  a *= 0.5;
  return { x: cx / (6 * a), y: cy / (6 * a) };
}