All files / timesfm-core/src/helpers metrics.ts

100% Statements 140/140
97.75% Branches 87/89
100% Functions 8/8
100% Lines 140/140

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                                  1x 18x 1x 1x 18x 16x 16x 18x 52x 48x 48x 48x 52x 18x 18x             1x 6x 1x 1x 6x 4x 4x 6x 14x 10x 10x 10x 10x 14x 6x 6x                 1x 6x 1x 1x 6x 4x 4x 6x 12x 12x 11x 10x 12x 5x 5x 5x 12x 6x 6x                   1x 7x 1x 1x 7x 5x 5x 7x 13x 11x 11x 9x 9x 9x 11x 13x 7x 7x                 1x 5x 5x 5x 5x 5x 5x 5x 2x 2x                   1x 7x 1x 1x 7x   5x 5x 7x 19x 17x 17x 17x 19x 7x 4x   4x 4x 7x 17x 17x 17x 17x 17x 17x 17x   7x 3x 3x                 1x 6x 6x 6x 6x 6x 1x 1x 6x 4x 4x 6x 14x 12x 12x 12x 14x 6x 6x             1x 4x 1x 1x 4x 2x 2x 4x 7x 5x 5x 5x 7x 4x 4x  
/**
 * Time-series forecast evaluation metrics.
 *
 * Pure functions operating on Float32Array — zero dependencies,
 * zero allocations beyond the return value.
 *
 * Reference sources:
 *   - scikit-learn sklearn.metrics (BSD License)
 *   - Hyndman & Koehler (2006) "Another look at measures of forecast accuracy"
 *   - Google TimesFM evaluation harness
 */
 
/**
 * Mean Absolute Error.
 *
 * MAE = (1/n) * Σ|actual_i - predicted_i|
 */
export function mae(actual: Float32Array, predicted: Float32Array): number {
  if (actual.length !== predicted.length) {
    throw new RangeError(`Length mismatch: actual=${actual.length}, predicted=${predicted.length}`);
  }
  if (actual.length === 0) return 0;
  let sum = 0;
  let count = 0;
  for (let i = 0; i < actual.length; i++) {
    if (Number.isFinite(actual[i]) && Number.isFinite(predicted[i])) {
      sum += Math.abs(actual[i] - predicted[i]);
      count++;
    }
  }
  return count > 0 ? sum / count : 0;
}
 
/**
 * Root Mean Square Error.
 *
 * RMSE = sqrt((1/n) * Σ(actual_i - predicted_i)²)
 */
export function rmse(actual: Float32Array, predicted: Float32Array): number {
  if (actual.length !== predicted.length) {
    throw new RangeError(`Length mismatch: actual=${actual.length}, predicted=${predicted.length}`);
  }
  if (actual.length === 0) return 0;
  let sumSq = 0;
  let count = 0;
  for (let i = 0; i < actual.length; i++) {
    if (Number.isFinite(actual[i]) && Number.isFinite(predicted[i])) {
      const diff = actual[i] - predicted[i];
      sumSq += diff * diff;
      count++;
    }
  }
  return count > 0 ? Math.sqrt(sumSq / count) : 0;
}
 
/**
 * Mean Absolute Percentage Error.
 *
 * MAPE = (100/n) * Σ|(actual_i - predicted_i) / actual_i|
 *
 * Points where |actual_i| < 1e-10 are skipped to avoid division by zero.
 */
export function mape(actual: Float32Array, predicted: Float32Array): number {
  if (actual.length !== predicted.length) {
    throw new RangeError(`Length mismatch: actual=${actual.length}, predicted=${predicted.length}`);
  }
  if (actual.length === 0) return 0;
  let sum = 0;
  let count = 0;
  for (let i = 0; i < actual.length; i++) {
    if (
      Number.isFinite(actual[i]) &&
      Number.isFinite(predicted[i]) &&
      Math.abs(actual[i]) > 1e-10
    ) {
      sum += Math.abs((actual[i] - predicted[i]) / actual[i]);
      count++;
    }
  }
  return count > 0 ? (sum / count) * 100 : 0;
}
 
/**
 * Symmetric Mean Absolute Percentage Error.
 *
 * SMAPE = (100/n) * Σ 2 * |actual_i - predicted_i| / (|actual_i| + |predicted_i|)
 *
 * Range: [0, 200].  Symmetric — swapping actual and predicted yields
 * the same result.
 */
export function smape(actual: Float32Array, predicted: Float32Array): number {
  if (actual.length !== predicted.length) {
    throw new RangeError(`Length mismatch: actual=${actual.length}, predicted=${predicted.length}`);
  }
  if (actual.length === 0) return 0;
  let sum = 0;
  let count = 0;
  for (let i = 0; i < actual.length; i++) {
    if (Number.isFinite(actual[i]) && Number.isFinite(predicted[i])) {
      const denominator = Math.abs(actual[i]) + Math.abs(predicted[i]);
      if (denominator > 1e-10) {
        sum += (2 * Math.abs(actual[i] - predicted[i])) / denominator;
        count++;
      }
    }
  }
  return count > 0 ? (sum / count) * 100 : 0;
}
 
/**
 * Mean Absolute Scaled Error.
 *
 * MASE = MAE(model) / MAE(naive)
 *
 * Values < 1 indicate the model outperforms the naive (no-change) forecast.
 */
export function mase(
  actual: Float32Array,
  predicted: Float32Array,
  naiveForecast: Float32Array,
): number {
  const modelMAE = mae(actual, predicted);
  const naiveMAE = mae(actual, naiveForecast);
  if (naiveMAE < 1e-10) return modelMAE < 1e-10 ? 1 : Infinity;
  return modelMAE / naiveMAE;
}
 
/**
 * R² coefficient of determination.
 *
 * R² = 1 - SS_res / SS_tot
 *
 * Range: (-∞, 1].  1 = perfect fit, 0 = mean-predictor baseline,
 * negative = worse than the mean baseline.
 */
export function r2Score(actual: Float32Array, predicted: Float32Array): number {
  if (actual.length !== predicted.length) {
    throw new RangeError(`Length mismatch: actual=${actual.length}, predicted=${predicted.length}`);
  }
  if (actual.length === 0) return 0;
 
  let sumActual = 0;
  let n = 0;
  for (let i = 0; i < actual.length; i++) {
    if (Number.isFinite(actual[i])) {
      sumActual += actual[i];
      n++;
    }
  }
  if (n === 0) return 0;
  const meanActual = sumActual / n;
 
  let ssRes = 0;
  let ssTot = 0;
  for (let i = 0; i < actual.length; i++) {
    if (Number.isFinite(actual[i]) && Number.isFinite(predicted[i])) {
      const diffRes = actual[i] - predicted[i];
      const diffTot = actual[i] - meanActual;
      ssRes += diffRes * diffRes;
      ssTot += diffTot * diffTot;
    }
  }
 
  if (ssTot < 1e-10) return 1;
  return 1 - ssRes / ssTot;
}
 
/**
 * Prediction Interval Coverage.
 *
 * The fraction of actual values that fall within [lower, upper].
 *
 * Range: [0, 1].  1 = all values covered, 0 = none covered.
 */
export function picCoverage(
  actual: Float32Array,
  lower: Float32Array,
  upper: Float32Array,
): number {
  if (actual.length !== lower.length || actual.length !== upper.length) {
    throw new RangeError('Length mismatch between actual, lower, and upper arrays');
  }
  if (actual.length === 0) return 0;
  let covered = 0;
  let total = 0;
  for (let i = 0; i < actual.length; i++) {
    if (Number.isFinite(actual[i]) && Number.isFinite(lower[i]) && Number.isFinite(upper[i])) {
      if (actual[i] >= lower[i] && actual[i] <= upper[i]) covered++;
      total++;
    }
  }
  return total > 0 ? covered / total : 0;
}
 
/**
 * Average Prediction Interval Width.
 *
 * The mean width of the prediction interval across all time steps.
 */
export function piWidth(lower: Float32Array, upper: Float32Array): number {
  if (lower.length !== upper.length) {
    throw new RangeError(`Length mismatch: lower=${lower.length}, upper=${upper.length}`);
  }
  if (lower.length === 0) return 0;
  let sum = 0;
  let count = 0;
  for (let i = 0; i < lower.length; i++) {
    if (Number.isFinite(lower[i]) && Number.isFinite(upper[i])) {
      sum += upper[i] - lower[i];
      count++;
    }
  }
  return count > 0 ? sum / count : 0;
}