All files / if-run/builtins/interpolation index.ts

100% Statements 64/64
100% Branches 26/26
100% Functions 16/16
100% Lines 63/63

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 1874x 4x   4x 4x 4x   4x   4x     4x   4x   4x   15x 1x     14x               14x     14x       14x 14x         14x             12x   12x               12x               12x           11x   11x 11x 1x             10x                       4x 10x           10x           4x   10x     10x 10x   10x   40x 2x 2x 38x 7x 7x 7x     40x         10x           4x   10x     10x 10x 10x   10x           4x         10x     10x 10x   10x   40x   160x 120x   40x   40x     10x           4x 79x  
import Spline from 'typescript-cubic-spline';
import {z} from 'zod';
 
import {PluginParams, ConfigParams, Method} from '@grnsft/if-core/types';
import {PluginFactory} from '@grnsft/if-core/interfaces';
import {ERRORS} from '@grnsft/if-core/utils';
 
import {validate} from '../../../common/util/validations';
 
import {STRINGS} from '../../config';
 
const {X_Y_EQUAL, ARRAY_LENGTH_NON_EMPTY, WITHIN_THE_RANGE, MISSING_CONFIG} =
  STRINGS;
 
const {ConfigError} = ERRORS;
 
export const Interpolation = PluginFactory({
  configValidation: (config: ConfigParams) => {
    if (!config || !Object.keys(config)?.length) {
      throw new ConfigError(MISSING_CONFIG);
    }
 
    const schema = z
      .object({
        method: z.nativeEnum(Method),
        x: z.array(z.number()),
        y: z.array(z.number()),
        'input-parameter': z.string(),
        'output-parameter': z.string(),
      })
      .refine(data => data.x && data.y && data.x.length === data.y.length, {
        message: X_Y_EQUAL,
      })
      .refine(data => data.x.length > 1 && data.y.length > 1, {
        message: ARRAY_LENGTH_NON_EMPTY,
      });
 
    const defaultMethod = config.method ?? Method.LINEAR;
    const updatedConfig = Object.assign({}, {method: defaultMethod}, config, {
      x: sortPoints(config.x),
      y: sortPoints(config.y),
    });
 
    return validate<z.infer<typeof schema>>(schema, updatedConfig);
  },
  inputValidation: (
    input: PluginParams,
    config: ConfigParams,
    index: number | undefined
  ) => {
    const inputParameter = config['input-parameter'];
 
    const schema = z
      .object({
        timestamp: z.string().or(z.date()),
        duration: z.number(),
        [inputParameter]: z.number().gte(0).or(z.literal('off')),
      })
      .refine(
        data =>
          (data[inputParameter] >= config.x[0] &&
            data[inputParameter] <= config.x[config.x.length - 1]) ||
          data[inputParameter] === 'off',
        {
          message: WITHIN_THE_RANGE,
        }
      );
 
    return validate<z.infer<typeof schema>>(schema, input, index);
  },
  implementation: async (inputs: PluginParams[], config: ConfigParams) => {
    const {
      'input-parameter': inputParameter,
      'output-parameter': outputParameter,
    } = config;
 
    return inputs.map(input => {
      if (input[inputParameter] === 'off') {
        return {
          ...input,
          [inputParameter]: 0,
          [outputParameter]: 0,
        };
      }
 
      return {
        ...input,
        [outputParameter]: calculateResult(config, input),
      };
    });
  },
  allowArithmeticExpressions: ['input-parameter'],
});
 
/**
 * Calculates the appropriate interpolation value based on the specified method type in the config and input parameters.
 */
const calculateResult = (config: ConfigParams, input: PluginParams) => {
  const methodType: {[key: string]: number} = {
    linear: getLinearInterpolation(config, input),
    spline: getSplineInterpolation(config, input),
    polynomial: getPolynomialInterpolation(config, input),
  };
 
  return methodType[config.method];
};
 
/**
 * Calculates the interpolation when the method is linear.
 */
const getLinearInterpolation = (config: ConfigParams, input: PluginParams) => {
  const parameter =
    typeof config['input-parameter'] === 'number'
      ? config['input-parameter']
      : input[config['input-parameter']];
  const xPoints: number[] = config.x;
  const yPoints: number[] = config.y;
 
  const result = xPoints.reduce(
    (acc, xPoint, i) => {
      if (parameter === xPoint) {
        acc.baseCpu = xPoint;
        acc.baseRate = yPoints[i];
      } else if (parameter > xPoint && parameter < xPoints[i + 1]) {
        acc.baseCpu = xPoint;
        acc.baseRate = yPoints[i];
        acc.ratio = (yPoints[i + 1] - yPoints[i]) / (xPoints[i + 1] - xPoint);
      }
 
      return acc;
    },
    {baseRate: 0, baseCpu: 0, ratio: 0}
  );
 
  return result.baseRate + (parameter - result.baseCpu) * result.ratio;
};
 
/**
 * Calculates the interpolation when the method is spline.
 */
const getSplineInterpolation = (config: ConfigParams, input: PluginParams) => {
  const parameter =
    typeof config['input-parameter'] === 'number'
      ? config['input-parameter']
      : input[config['input-parameter']];
  const xPoints: number[] = config.x;
  const yPoints: number[] = config.y;
  const spline: any = new Spline(xPoints, yPoints);
 
  return spline.at(parameter);
};
 
/**
 * Calculates the interpolation when the method is polynomial.
 */
const getPolynomialInterpolation = (
  config: ConfigParams,
  input: PluginParams
) => {
  const parameter =
    typeof config['input-parameter'] === 'number'
      ? config['input-parameter']
      : input[config['input-parameter']];
  const xPoints: number[] = config.x;
  const yPoints: number[] = config.y;
 
  const result = xPoints.reduce((acc, x, i) => {
    const term =
      yPoints[i] *
      xPoints.reduce((prod, xPoint, j) => {
        if (j !== i) {
          return (prod * (parameter - xPoint)) / (x - xPoint);
        }
        return prod;
      }, 1);
    return acc + term;
  }, 0);
 
  return result;
};
 
/**
 * Sorts given point items in ascending order.
 */
const sortPoints = (items: number[]) =>
  items.sort((a: number, b: number) => a - b);