All files / src/math monotonic-cubic-spline.ts

96.69% Statements 117/121
91.42% Branches 32/35
100% Functions 10/10
96.52% Lines 111/115

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      2x   3x 3x 3x 3x 3x 3x 3x               56x 1x 55x 1x     54x                 10x 1x 9x 1x     8x 8x 8x 8x 50x 50x 4x     46x 46x 4x     42x 14x   28x   42x                           2x       8x 3x                     2x                 8x 1x   7x 1x   6x 1x       5x     5x 2x       3x 3x 3x 3x 7x 7x 7x 7x 7x       3x 3x 4x 4x 4x     4x 4x 4x 4x     3x     3x 3x 3x 7x 7x 7x 7x 7x 7x     3x             2x 5x 5x 11x     5x 5x 5x 16x 16x   5x           2x 5x         5x   5x 5x 11x     11x 9x 1x   8x 2x 2x 1x   1x     9x     3x       2x 3x   54x                 54x 1x         53x 82x 9x 73x 44x         44x 44x    
/**
 * The spline calculated during interpolation.
 */
export class CubicInterpolation {
  constructor(
    private firstX: number,
    private lastX: number,
    private firstY: number,
    private lastY: number,
    private firstSlope: number,
    private lastSlope: number,
    private fun: (x: number) => number
  ) {}
 
  /**
   * Returns the value of the function.
   */
  public forX(x: number): number {
    // queries outside the range of points are matched by linear interpolation
    if (x < this.firstX) {
      return this.firstY - this.firstSlope * (this.firstX - x);
    } else if (x > this.lastX) {
      return this.lastY + this.lastSlope * (x - this.lastX);
    } else {
      // we use the calculated cubic interpolation
      return this.fun(x);
    }
  }
 
  /**
   * Returns the approximate function argument for a given value.
   */
  public forY(y: number, precision: number): number {
    // queries outside the range of points are matched by linear interpolation
    if (y < this.firstY) {
      return this.firstX - (this.firstY - y) / this.firstSlope;
    } else if (y > this.lastY) {
      return this.lastX + (y - this.lastY) / this.lastSlope;
    } else {
      // binary search for X for which Y is within the given precision
      let lowX = this.firstX;
      let highX = this.lastX;
      let tries = 50;
      while (lowX <= highX && tries > 0) {
        const midX = (lowX + highX) / 2;
        if (Math.abs(highX - lowX) < precision) {
          return midX;
        }
 
        const midY = this.forX(midX);
        if (Math.abs(midY - y) < precision) {
          return midX;
        }
 
        if (midY < y) {
          lowX = midX;
        } else {
          highX = midX;
        }
        tries--;
      }
      throw new Error(`X was not found for Y = ${y.toString()}`);
    }
  }
}
 
/**
 * Interpolation of functions based on selected strictly monotonic points.
 * Interpolation returns a monotonic spline where each piece is a third-degree polynomial specified in Hermite form.
 *
 * Method based on https://en.wikipedia.org/wiki/Monotone_cubic_interpolation.
 * Method source code inspired by code in https://en.wikipedia.org/wiki/Monotone_cubic_interpolation#Example_implementation.
 */
export const monotoneCubicInterpolation = (
  xs: number[],
  ys: number[]
): CubicInterpolation => {
  const { fun, firstSlope, lastSlope } = createInterpolant(xs, ys);
  return new CubicInterpolation(
    xs[0],
    xs[xs.length - 1],
    ys[0],
    ys[ys.length - 1],
    firstSlope,
    lastSlope,
    fun
  );
};
 
const createInterpolant = (
  xs: number[],
  ys: number[]
): {
  fun: (x: number) => number;
  firstSlope: number;
  lastSlope: number;
} => {
  // checking the initial conditions
  if (xs.length != ys.length) {
    throw new Error("The number of xs and ys should be equal");
  }
  if (xs.length === 0) {
    throw new Error("Empty array of xs");
  }
  if (xs.length === 1) {
    throw new Error("Interpolation cannot be performed for a single point");
  }
 
  // sorting points
  const [sortedXs, sortedYs] = sortPoints(xs, ys);
 
  // monotonicity check
  if (!isMonotonic(sortedYs)) {
    throw new Error("The given points are not monotonic");
  }
 
  // consecutive differences and slopes
  const dys = [],
    dxs = [],
    ms = [];
  for (let i = 0; i < sortedXs.length - 1; i++) {
    const dx = sortedXs[i + 1] - sortedXs[i];
    const dy = sortedYs[i + 1] - sortedYs[i];
    dxs[i] = dx;
    dys[i] = dy;
    ms[i] = dy / dx;
  }
 
  // degree-1 coefficients
  const c1s = [ms[0]];
  for (let i = 0; i < dxs.length - 1; i++) {
    const m = ms[i],
      mNext = ms[i + 1];
    Iif (m * mNext <= 0) {
      c1s.push(0);
    } else {
      const dx = dxs[i],
        dxNext = dxs[i + 1],
        common = dx + dxNext;
      c1s.push((3 * common) / ((common + dxNext) / m + (common + dx) / mNext));
    }
  }
  c1s.push(ms[ms.length - 1]);
 
  // degree-2 and degree-3 coefficients
  const c2s = [],
    c3s = [];
  for (let i = 0; i < c1s.length - 1; i++) {
    const c1 = c1s[i],
      m = ms[i],
      invDx = 1 / dxs[i],
      common = c1 + c1s[i + 1] - 2 * m;
    c2s.push((m - c1 - common) * invDx);
    c3s.push(common * invDx * invDx);
  }
 
  return {
    fun: createInterpolantFunction(sortedXs, sortedYs, c1s, c2s, c3s),
    firstSlope: ms[0],
    lastSlope: ms[ms.length - 1],
  };
};
 
const sortPoints = (xs: number[], ys: number[]): [number[], number[]] => {
  const indexes = [...Array(xs.length).keys()];
  indexes.sort((a, b) => {
    return xs[a] - xs[b];
  });
 
  const sortedXs = [];
  const sortedYs = [];
  for (let i = 0; i < xs.length; i++) {
    sortedXs[i] = xs[indexes[i]];
    sortedYs[i] = ys[indexes[i]];
  }
  return [sortedXs, sortedYs];
};
 
/**
 * Whether the given list of values is monotonic.
 */
const isMonotonic = (ys: number[]) => {
  Iif (ys.length < 2) {
    return true;
  }
 
  // direction of monotonicity
  let direction: "increasing" | "decreasing" | "undefined" = "undefined";
 
  let previous = ys[0];
  for (let i = 1; i < ys.length; i++) {
    const current = ys[i];
 
    // check monotonicity
    if (current > previous) {
      if (direction === "decreasing") {
        return false;
      }
      direction = "increasing";
    } else if (current < previous) {
      if (direction === "increasing") {
        return false;
      }
      direction = "decreasing";
    }
 
    previous = current;
  }
 
  return true;
};
 
const createInterpolantFunction =
  (xs: number[], ys: number[], c1s: number[], c2s: number[], c3s: number[]) =>
  (x: number): number => {
    // checking whether the argument is from the appropriate range
    Iif (x < xs[0] || x > xs[xs.length - 1]) {
      throw new Error(
        `The function only handles arguments in the range [${xs[0].toString()},${xs[
          xs.length - 1
        ].toString()}]`
      );
    }
 
    // the rightmost point in the dataset should give an exact result
    if (x === xs[xs.length - 1]) {
      return ys[xs.length - 1];
    }
 
    // search for the interval x is in, returning the corresponding y if x is one of the original xs
    let i;
    for (i = 0; i < xs.length - 1; i++) {
      if (xs[i] === x) {
        return ys[i];
      } else if (xs[i] < x && x < xs[i + 1]) {
        break;
      }
    }
 
    // interpolate
    const diff = x - xs[i];
    return ys[i] + diff * (c1s[i] + diff * (c2s[i] + diff * c3s[i]));
  };