All files / src/math interpolation.ts

92.56% Statements 112/121
81.57% Branches 31/38
90% Functions 9/10
93.04% Lines 107/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 2411x             4x 4x 4x 4x 4x 4x 4x         94x 2x 92x 3x     89x           10x 1x 9x 1x     8x 8x 8x 8x 81x 81x 81x 8x 73x 25x   48x   73x             1x       7x 4x                     1x                 7x 1x   6x 1x   5x 1x       4x 4x 9x       4x 1x       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             1x 4x     4x         4x   4x 4x 9x     9x 8x     8x 1x 1x 1x               8x     3x     1x             3x   89x                 89x 1x       88x 88x 88x 175x 175x 175x 116x 59x 50x   9x     79x     79x 79x 79x            
import { ISafeNumber, SafeZero, createSafeNumber } from "../ISafeNumber";
 
/**
 * TODO: description of the method
 */
class CubicInterpolation {
  constructor(
    private firstX: ISafeNumber,
    private lastX: ISafeNumber,
    private firstY: ISafeNumber,
    private lastY: ISafeNumber,
    private firstSlope: ISafeNumber,
    private lastSlope: ISafeNumber,
    private fun: (x: ISafeNumber) => ISafeNumber
  ) {}
 
  public forX(x: ISafeNumber): ISafeNumber {
    // queries outside the range of points are matched by linear interpolation
    if (x.lt(this.firstX)) {
      return this.firstY.sub(this.firstSlope.mul(this.firstX.sub(x)));
    } else if (x.gt(this.lastX)) {
      return this.lastY.add(this.lastSlope.mul(x.sub(this.lastX)));
    } else {
      // we use the calculated cubic interpolation
      return this.fun(x);
    }
  }
 
  public forY(y: ISafeNumber, _precision: ISafeNumber): ISafeNumber {
    // queries outside the range of points are matched by linear interpolation
    if (y.lt(this.firstY)) {
      return this.firstX.sub(this.firstY.sub(y).div(this.firstSlope));
    } else if (y.gt(this.lastY)) {
      return this.lastX.add(y.sub(this.lastY).div(this.lastSlope));
    } else {
      // binary search for X for which Y is within the given precision
      let low = this.firstX,
        high = this.lastX,
        tries = 50;
      while (low <= high && tries > 0) {
        const midX = low.add(high).div(2);
        const midY = this.forX(midX);
        if (midY.sub(y).abs().lt(_precision)) {
          return midX;
        } else if (midY.lt(y)) {
          low = midX;
        } else {
          high = midX;
        }
        tries--;
      }
      throw new Error(`X was not found for given Y = ${y.toString()}`);
    }
  }
}
 
export const monotoneCubicInterpolation = (
  xs: ISafeNumber[],
  ys: ISafeNumber[]
): 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: ISafeNumber[],
  ys: ISafeNumber[]
): {
  fun: (x: ISafeNumber) => ISafeNumber;
  firstSlope: ISafeNumber;
  lastSlope: ISafeNumber;
} => {
  // 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) {
    return { fun: (_x) => ys[0], firstSlope: SafeZero, lastSlope: SafeZero };
  }
 
  // sorting points
  const indexes = [...Array(xs.length).keys()];
  indexes.sort(function (a, b) {
    return xs[a] < xs[b] ? -1 : 1;
  });
 
  // monotonicity check
  if (!isStrictlyMonotonic(indexes, ys)) {
    throw new Error("The given points are not monotonic");
  }
 
  // consecutive differences and slopes
  const dys = [],
    dxs = [],
    ms = [];
  for (let i = 0; i < xs.length - 1; i++) {
    const dx = xs[i + 1].sub(xs[i]),
      dy = ys[i + 1].sub(ys[i]);
    dxs[i] = dx;
    dys[i] = dy;
    ms[i] = dy.div(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.mul(mNext).lte(SafeZero)) {
      c1s.push(SafeZero);
    } else {
      const dx_ = dxs[i],
        dxNext = dxs[i + 1],
        common = dx_.add(dxNext);
      c1s.push(
        common
          .mul(3)
          .div(common.add(dxNext).div(m).add(common.add(dx_).div(mNext)))
      );
    }
  }
  c1s.push(ms[ms.length - 1]);
 
  // degree-2 and degree-3 coefficients
  const c2s: ISafeNumber[] = [],
    c3s: ISafeNumber[] = [];
  for (let i = 0; i < c1s.length - 1; i++) {
    const c1 = c1s[i],
      m = ms[i],
      invDx = createSafeNumber(1).div(dxs[i]),
      common = c1
        .add(c1s[i + 1])
        .sub(m)
        .sub(m);
    c2s.push(m.sub(c1).sub(common).mul(invDx));
    c3s.push(common.mul(invDx).mul(invDx));
  }
 
  return {
    fun: createInterpolantFunction(xs, ys, c1s, c2s, c3s),
    firstSlope: ms[0],
    lastSlope: ms[ms.length - 1],
  };
};
 
const isStrictlyMonotonic = (indexes: number[], ys: ISafeNumber[]) => {
  Iif (ys.length < 2) {
    return true;
  }
  Iif (indexes.length !== ys.length) {
    throw new Error("Different lengths of input arrays");
  }
 
  // direction of monotonicity
  let direction: "increasing" | "decreasing" | "undefined" = "undefined";
 
  let previous = ys[indexes[0]];
  for (let i = 1; i < ys.length; i++) {
    const current = ys[indexes[i]];
 
    // check monotonicity
    if (current.gt(previous)) {
      Iif (direction === "decreasing") {
        return false;
      }
      direction = "increasing";
    } else if (current.lt(previous)) {
      if (direction === "increasing") {
        return false;
      }
      direction = "decreasing";
    } else E{
      // equality, no strict monotonicity
      return false;
    }
 
    previous = current;
  }
 
  return true;
};
 
const createInterpolantFunction = (
  xs: ISafeNumber[],
  ys: ISafeNumber[],
  c1s: ISafeNumber[],
  c2s: ISafeNumber[],
  c3s: ISafeNumber[]
): ((x: ISafeNumber) => ISafeNumber) => {
  return (x: ISafeNumber) => {
    // checking whether the argument is from the appropriate range
    Iif (x.lt(xs[0]) || x.gt(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.eq(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 low = 0,
      high = c3s.length - 1;
    while (low <= high) {
      const mid = Math.floor(0.5 * (low + high));
      const middleX = xs[mid];
      if (middleX < x) {
        low = mid + 1;
      } else if (middleX > x) {
        high = mid - 1;
      } else {
        return ys[mid];
      }
    }
    const i = Math.max(0, high);
 
    // interpolate
    const diff = x.sub(xs[i]),
      diffSq = diff.mul(diff);
    return ys[i]
      .add(c1s[i].mul(diff))
      .add(c2s[i].mul(diffSq))
      .add(c3s[i].mul(diff).mul(diffSq));
  };
};