All files / core/src metrics.ts

100% Statements 149/149
99.01% Branches 101/102
100% Functions 25/25
100% Lines 118/118

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                                                                                                                                                                  10x                       10x     188x 186x 12x 12x 7x 8x 6x 6x     1x                                 369429x 369429x 369429x   369429x     369429x                     141x 138x   138x 1569x 138x   32x 32x 1433x 1433x 1433x   55x 25x 3x 3x 3x       24616x 136x 136x 1569x 1569x 301368x 301368x 301368x 301368x 738858x 301368x 301368x 369429x   369429x   369429x       136x 136x 24616x 136x 136x 136x         83x         138x 136x     10551x 21102x   135x 20973x   135x 20838x 135x   138x 138x     270x 258x 258x 516x 516x 516x 516x 17096x 17096x 17096x 112x   104x 112x   17088x   17088x 17072x 324x 324x   16748x 16748x   168x   258x 258x 258x 158x 16194x 39858x 25x   133x   138x 138x 138x                           60x 59x 59x 60x 60x 60x                                               10x                           650x 250x               250x 50x 150x 150x   50x 50x 1421x 302283x 1540x             50x                                   450x 450x 450x                    
import { sampleIntensity, type IESProfile, type IESTilt } from './index.js';
 
/** Absolute candela on a horizontal-major angular grid. No metadata or lamp rating is required. */
export type PhotometricGrid = Pick<
  IESProfile,
  'photometricType' | 'verticalAngles' | 'horizontalAngles' | 'candelaValues'
> & { tilt?: IESTilt | null };
 
export type BeamAngleStatus = 'ok' | 'no-light' | 'no-crossing' | 'multiple-lobes';
 
export interface BeamAngles {
  /** Opposed-plane cut C-h / C-(h+180); full angle around the cut's peak, in degrees. */
  horizontalDegrees: number;
  peakDirectionDegrees: number;
  peakCandela: number;
  /** Nearest measured 50%-peak crossings bracketing the dominant lobe; null if not both present. */
  beamAngleDegrees: number | null;
  /** Nearest measured 10%-peak crossings bracketing the dominant lobe; null if not both present. */
  fieldAngleDegrees: number | null;
  beamAngleStatus: BeamAngleStatus;
  fieldAngleStatus: BeamAngleStatus;
  /** Unwrapped signed cut angle of the 50% crossing below the peak; may pass ±180° at zenith. Absent when not bracketed. */
  beamLeftDegrees?: number;
  /** Unwrapped signed cut angle of the 50% crossing above the peak. Absent when not bracketed. */
  beamRightDegrees?: number;
  /** Unwrapped signed cut angle of the 10% crossing below the peak. Absent when not bracketed. */
  fieldLeftDegrees?: number;
  /** Unwrapped signed cut angle of the 10% crossing above the peak. Absent when not bracketed. */
  fieldRightDegrees?: number;
}
 
export interface PhotometricMetrics {
  metricsSupported: boolean;
  metricsUnsupportedReason: string | null;
  /** Lamp rating × lamp count, not measured luminaire output. Null for absolute photometry. */
  declaredLampFluxLumens: number | null;
  /** Estimated luminaire output integrated from the angular intensity table. */
  integratedFluxLumens: number | null;
  /** Integrated luminaire flux / declared input watts. Null for zero power or unsupported type. */
  luminousEfficacyLumensPerWatt: number | null;
  /** Principal-plane estimates, not a certification of nominal beam axis or global extrema. */
  beamAngles: BeamAngles[];
  /** Lamp tilt applied to the intensity table when computing metrics (default 0°). */
  metricsTiltDegrees: number;
  /** Integrated flux below the horizontal (γ = 0…90°). */
  downwardFluxLumens: number | null;
  /** Integrated flux above the horizontal (γ = 90…180°). */
  upwardFluxLumens: number | null;
  /** Largest tabulated intensity after lamp tilt. Named apart from the summary's raw-table `peakCandela`. */
  peakIntensityCandela: number | null;
  /** First tabulated direction holding {@link PhotometricMetrics.peakIntensityCandela}. */
  peakDirection: { horizontalDegrees: number; verticalDegrees: number } | null;
  /** Intensity straight down (γ = 0). */
  nadirCandela: number | null;
  /** Light output ratio: integrated luminaire flux / declared lamp flux. Null without a lamp rating. */
  lightOutputRatio: number | null;
  /** Downward luminaire flux / declared lamp flux. */
  downwardLightOutputRatio: number | null;
  /** Upward luminaire flux / declared lamp flux. */
  upwardLightOutputRatio: number | null;
  /** Downward flux fraction (DFF): downward / total luminaire flux. */
  downwardFluxFraction: number | null;
  /**
   * CIE flux code N1–N5 as rounded percentages. N1–N3: flux within γ = 41.4°, 60°, 75.5° as % of
   * downward flux. N4, N5: downward and total flux as % of lamp flux (null without a lamp rating).
   */
  cieFluxCode: [number | null, number | null, number | null, number | null, number | null] | null;
  /** Integrated flux in standard polar zones. */
  zonalLumens: ZonalLumens[] | null;
}
 
export interface ZonalLumens {
  fromDegrees: number;
  toDegrees: number;
  lumens: number;
  /** Percentage of declared lamp flux; null without a lamp rating. */
  percentOfLamp: number | null;
  /** Percentage of integrated luminaire flux; null when the luminaire emits nothing. */
  percentOfLuminaire: number | null;
}
 
const zones: [number, number][] = [
  [0, 30],
  [0, 40],
  [0, 60],
  [0, 90],
  [90, 120],
  [90, 130],
  [90, 150],
  [90, 180],
  [0, 180],
];
 
const radians = Math.PI / 180;
 
function tiltFactor(tilt: IESTilt | null | undefined, tiltDegrees: number): number {
  if (!Number.isFinite(tiltDegrees)) throw new RangeError('Tilt angle must be finite');
  if (!tilt) return 1;
  const angle = Math.abs(tiltDegrees);
  if (angle <= tilt.angles[0]!) return tilt.factors[0]!;
  for (let i = 1; i < tilt.angles.length; i++) {
    if (angle <= tilt.angles[i]!) {
      const fraction = (angle - tilt.angles[i - 1]!) / (tilt.angles[i]! - tilt.angles[i - 1]!);
      return tilt.factors[i - 1]! + fraction * (tilt.factors[i]! - tilt.factors[i - 1]!);
    }
  }
  return tilt.factors.at(-1)!;
}
 
export interface FluxBreakdown {
  total: number;
  /** Flux below the horizontal, γ = 0…90°. */
  downward: number;
  /** Flux above the horizontal, γ = 90…180°. */
  upward: number;
  /** cumulative[g] is the flux from γ = 0 to γ = g degrees, g = 0…180. */
  cumulative: number[];
}
 
/** Integral of a linear segment I(θ) from (a, ia) to (b, ib) times sin θ, in radians. */
function segmentIntegral(a: number, b: number, ia: number, ib: number): number {
  // Exact integral of linear intensity × sin θ. A midpoint form avoids cancellation
  // in cos(a)-cos(b) and sin(h)/h-cos(h) on very narrow measured intervals.
  const half = (b - a) / 2;
  const middle = (a + b) / 2;
  const square = half * half;
  const slopeWeight =
    Math.abs(half) < 1e-3
      ? square * (1 / 3 + square * (-1 / 30 + square / 840))
      : Math.sin(half) / half - Math.cos(half);
  return (ia * 0.5 + ib * 0.5) * 2 * Math.sin(middle) * Math.sin(half) + (ib - ia) * Math.cos(middle) * slopeWeight;
}
 
/**
 * Integrate Type C I(θ,φ) sin(θ) dθ dφ in lumens, exactly for the sampler's piecewise-bilinear model,
 * splitting measured intervals at whole degrees to also return the 1° cumulative zonal flux.
 * Uses each actual angular interval, mirrors axial/quadrant/bilateral data, and closes a missing
 * azimuth seam once. Duplicate 0°/360° rows are endpoints, never extra angular bins. Unmeasured
 * vertical ranges are dark. Multipliers already present in candelaValues are not applied again.
 */
export function calculateFluxBreakdown(profile: PhotometricGrid, tiltDegrees = 0): FluxBreakdown {
  if (profile.photometricType !== 1) throw new Error('Flux integration supports Type C photometry only (type 1)');
  const correction = tiltFactor(profile.tilt, tiltDegrees);
  // Azimuth integration is linear in each row's polar integral, so reduce it to one weight per row.
  const horizontal = profile.horizontalAngles;
  const weights = horizontal.map(() => 0);
  if (horizontal.length === 1) weights[0] = 2 * Math.PI;
  else {
    const span = horizontal.at(-1)! - horizontal[0]!;
    for (let h = 1; h < horizontal.length; h++) {
      const half = (horizontal[h]! - horizontal[h - 1]!) * 0.5 * radians;
      weights[h - 1]! += half;
      weights[h]! += half;
    }
    if (span <= 180) for (let h = 0; h < weights.length; h++) weights[h]! *= 360 / span;
    else if (span < 360) {
      const seam = (360 - span) * 0.5 * radians;
      weights[0]! += seam;
      weights[weights.length - 1]! += seam;
    }
  }
  // bins[k] holds the flux in (k-1°, k°].
  const bins = Array.from({ length: 181 }, () => 0);
  const vertical = profile.verticalAngles;
  profile.candelaValues.forEach((row, h) => {
    const weight = weights[h]! * correction;
    for (let v = 1; v < vertical.length; v++) {
      const a = vertical[v - 1]!;
      const b = vertical[v]!;
      const ia = row[v - 1]!;
      const ib = row[v]!;
      const at = (angle: number) => ia + ((ib - ia) * (angle - a)) / (b - a);
      let start = a;
      while (start < b) {
        const end = Math.min(b, Math.floor(start) + 1);
        // Clamp keeps out-of-range hand-built grids in the total, as before the zonal split.
        bins[Math.min(180, Math.max(0, Math.ceil(end)))]! +=
          weight * segmentIntegral(start * radians, end * radians, at(start), at(end));
        start = end;
      }
    }
  });
  const cumulative: number[] = [];
  let sum = 0;
  for (const bin of bins) cumulative.push((sum += bin));
  const total = cumulative[180]!;
  const downward = cumulative[90]!;
  return { total, downward, upward: total - downward, cumulative };
}
 
/** Total luminous flux in lumens; see {@link calculateFluxBreakdown}. */
export function calculateLuminousFlux(profile: PhotometricGrid, tiltDegrees = 0): number {
  return calculateFluxBreakdown(profile, tiltDegrees).total;
}
 
/** Estimate widths of the dominant lobe in a complete opposed-plane cut, using measured knots. */
export function getBeamAngles(profile: IESProfile, horizontalDegrees = 0, tiltDegrees = 0): BeamAngles {
  if (profile.photometricType !== 1) throw new Error('Beam estimates support Type C photometry only (type 1)');
  if (![horizontalDegrees, tiltDegrees].every(Number.isFinite)) throw new RangeError('Beam angles must be finite');
  // Signed vertical directions traverse the two opposite meridians. Do not insert extrapolated
  // zero samples at a missing hemisphere boundary: that would invent a threshold crossing.
  const directions = [...profile.verticalAngles.toReversed().map((v) => -v), ...profile.verticalAngles].filter(
    (value, index, values) => index === 0 || value !== values[index - 1],
  );
  const intensities = directions.map((v) =>
    sampleIntensity(profile, Math.abs(v), horizontalDegrees + (v < 0 ? 180 : 0), tiltDegrees),
  );
  let peakIndex = 0;
  for (let i = 1; i < intensities.length; i++) if (intensities[i]! > intensities[peakIndex]!) peakIndex = i;
  const peak = intensities[peakIndex] ?? 0;
  // ±180° meet at zenith only when it is measured and the duplicate pole samples agree.
  const closed = profile.verticalAngles.at(-1) === 180 && intensities[0] === intensities.at(-1);
  const width = (
    fraction: number,
  ): { angle: number | null; status: BeamAngleStatus; left?: number; right?: number } => {
    if (peak <= 0) return { angle: null, status: 'no-light' };
    const threshold = peak * fraction;
    const crossing = (direction: -1 | 1): number | null => {
      let previous = peakIndex;
      let previousAngle = directions[previous]!;
      let offset = 0;
      for (let step = 1; step < intensities.length; step++) {
        let i = previous + direction;
        const wrapped = i < 0 || i >= intensities.length;
        if (wrapped) {
          if (!closed) return null;
          // Skip the duplicate zenith and continue in an unwrapped angular domain.
          i = direction === 1 ? 1 : intensities.length - 2;
          offset += direction * 360;
        }
        const angle = directions[i]! + offset;
        // Positive and negative sides have a gap if the measured range excludes nadir.
        if (!wrapped && directions[previous]! * directions[i]! < 0 && profile.verticalAngles[0] !== 0) return null;
        if (intensities[i]! <= threshold) {
          const t = (threshold - intensities[previous]!) / (intensities[i]! - intensities[previous]!);
          return previousAngle + t * (angle - previousAngle);
        }
        previous = i;
        previousAngle = angle;
      }
      return null;
    };
    const left = crossing(-1);
    const right = crossing(1);
    if (left === null || right === null) return { angle: null, status: 'no-crossing' };
    const outside = (angle: number) =>
      closed ? (((angle - left) % 360) + 360) % 360 > right - left : angle < left || angle > right;
    if (intensities.some((value, index) => value > threshold && outside(directions[index]!))) {
      return { angle: null, status: 'multiple-lobes', left, right };
    }
    return { angle: right - left, status: 'ok', left, right };
  };
  const beam = width(0.5);
  const field = width(0.1);
  return {
    horizontalDegrees: ((horizontalDegrees % 360) + 360) % 360,
    peakDirectionDegrees: directions[peakIndex] || 0,
    peakCandela: peak,
    beamAngleDegrees: beam.angle,
    fieldAngleDegrees: field.angle,
    beamAngleStatus: beam.status,
    fieldAngleStatus: field.status,
    ...(beam.left !== undefined && { beamLeftDegrees: beam.left, beamRightDegrees: beam.right }),
    ...(field.left !== undefined && { fieldLeftDegrees: field.left, fieldRightDegrees: field.right }),
  };
}
 
export function computePhotometricMetrics(profile: IESProfile, tiltDegrees = 0): PhotometricMetrics {
  if (!Number.isFinite(tiltDegrees)) throw new RangeError('Tilt angle must be finite');
  const supported = profile.photometricType === 1;
  const lamp = profile.lumensPerLamp < 0 ? null : profile.lampCount * profile.lumensPerLamp;
  const breakdown = supported ? calculateFluxBreakdown(profile, tiltDegrees) : null;
  const flux = breakdown?.total ?? null;
  return {
    metricsSupported: supported,
    metricsUnsupportedReason: supported ? null : 'Flux and beam calculations support Type C photometry only (type 1)',
    declaredLampFluxLumens: lamp,
    integratedFluxLumens: flux,
    luminousEfficacyLumensPerWatt: flux !== null && profile.inputWatts > 0 ? flux / profile.inputWatts : null,
    beamAngles: supported ? [getBeamAngles(profile, 0, tiltDegrees), getBeamAngles(profile, 90, tiltDegrees)] : [],
    metricsTiltDegrees: tiltDegrees,
    ...(breakdown ? extendedMetrics(profile, tiltDegrees, breakdown, lamp) : unsupportedExtendedMetrics),
  };
}
 
type ExtendedMetrics = Omit<
  PhotometricMetrics,
  | 'metricsSupported'
  | 'metricsUnsupportedReason'
  | 'declaredLampFluxLumens'
  | 'integratedFluxLumens'
  | 'luminousEfficacyLumensPerWatt'
  | 'beamAngles'
  | 'metricsTiltDegrees'
>;
 
/** Extended metric fields for unsupported coordinate systems or unselected lamp configurations. */
export const unsupportedExtendedMetrics: ExtendedMetrics = {
  downwardFluxLumens: null,
  upwardFluxLumens: null,
  peakIntensityCandela: null,
  peakDirection: null,
  nadirCandela: null,
  lightOutputRatio: null,
  downwardLightOutputRatio: null,
  upwardLightOutputRatio: null,
  downwardFluxFraction: null,
  cieFluxCode: null,
  zonalLumens: null,
};
 
const ratio = (part: number, whole: number) => (whole > 0 ? part / whole : null);
const percent = (fraction: number | null) => (fraction === null ? null : Math.round(fraction * 100));
 
function extendedMetrics(
  profile: IESProfile,
  tiltDegrees: number,
  { total, downward, upward, cumulative }: FluxBreakdown,
  lamp: number | null,
): ExtendedMetrics {
  const ofLamp = (flux: number) => (lamp ? flux / lamp : null);
  const cumulativeAt = (degrees: number) => {
    const low = Math.floor(degrees);
    return cumulative[low]! + (cumulative[low + 1]! - cumulative[low]!) * (degrees - low);
  };
  let peak = { candela: -Infinity, horizontalDegrees: 0, verticalDegrees: 0 };
  profile.candelaValues.forEach((row, h) =>
    row.forEach((candela, v) => {
      if (candela > peak.candela)
        peak = {
          candela,
          horizontalDegrees: profile.horizontalAngles[h]!,
          verticalDegrees: profile.verticalAngles[v]!,
        };
    }),
  );
  return {
    downwardFluxLumens: downward,
    upwardFluxLumens: upward,
    peakIntensityCandela: peak.candela * tiltFactor(profile.tilt, tiltDegrees),
    peakDirection: { horizontalDegrees: peak.horizontalDegrees, verticalDegrees: peak.verticalDegrees },
    nadirCandela: sampleIntensity(profile, 0, 0, tiltDegrees),
    lightOutputRatio: ofLamp(total),
    downwardLightOutputRatio: ofLamp(downward),
    upwardLightOutputRatio: ofLamp(upward),
    downwardFluxFraction: ratio(downward, total),
    cieFluxCode: [
      percent(ratio(cumulativeAt(41.4), downward)),
      percent(ratio(cumulativeAt(60), downward)),
      percent(ratio(cumulativeAt(75.5), downward)),
      percent(ofLamp(downward)),
      percent(ofLamp(total)),
    ],
    zonalLumens: zones.map(([fromDegrees, toDegrees]) => {
      const lumens = cumulative[toDegrees]! - cumulative[fromDegrees]!;
      const ofLuminaire = ratio(lumens, total);
      return {
        fromDegrees,
        toDegrees,
        lumens,
        percentOfLamp: lamp ? (lumens / lamp) * 100 : null,
        percentOfLuminaire: ofLuminaire === null ? null : ofLuminaire * 100,
      };
    }),
  };
}