All files / builtins/interpolation index.ts

100% Statements 68/68
100% Branches 16/16
100% Functions 17/17
100% Lines 67/67

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 1983x 3x 3x 3x             3x   3x   3x           3x   3x       8x 10x   7x 7x 6x   6x                   8x 6x           6x           8x       6x 6x 6x   6x   24x 1x 1x 23x 5x 5x 5x     24x         6x           8x       6x 6x 6x 6x   6x           8x       6x 6x 6x   6x   24x   96x 72x   24x   24x     6x             8x 10x 1x     9x               9x     9x       9x 9x                   9x     8x 18x 49x           8x 7x 7x               7x             7x     8x              
import Spline from 'typescript-cubic-spline';
import {z} from 'zod';
import {ERRORS} from '@grnsft/if-core/utils';
import {
  ExecutePlugin,
  PluginParams,
  ConfigParams,
  Method,
} from '@grnsft/if-core/types';
 
import {validate} from '../../util/validations';
 
import {STRINGS} from '../../config';
 
const {GlobalConfigError} = ERRORS;
const {
  MISSING_GLOBAL_CONFIG,
  X_Y_EQUAL,
  ARRAY_LENGTH_NON_EMPTY,
  WITHIN_THE_RANGE,
} = STRINGS;
 
export const Interpolation = (globalConfig: ConfigParams): ExecutePlugin => {
  /**
   * Executes the energy consumption calculation for an array of input parameters.
   */
  const execute = (inputs: PluginParams[]) => {
    const validatedConfig = validateConfig();
 
    return inputs.map((input, index) => {
      const safeInput = validateInput(input, index);
      const result = calculateResult(validatedConfig, safeInput);
 
      return {
        ...input,
        [validatedConfig['output-parameter']]: result,
      };
    });
  };
 
  /**
   * 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 = input[globalConfig['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 = input[globalConfig['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 = input[globalConfig['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;
  };
 
  /**
   * Validates global config parameters.
   * Sorts elements of `x` and `y`.
   */
  const validateConfig = () => {
    if (!globalConfig) {
      throw new GlobalConfigError(MISSING_GLOBAL_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 = globalConfig.method ?? Method.LINEAR;
    const updatedConfig = Object.assign(
      {},
      {method: defaultMethod},
      globalConfig,
      {
        x: sortPoints(globalConfig.x),
        y: sortPoints(globalConfig.y),
      }
    );
 
    return validate<z.infer<typeof schema>>(schema, updatedConfig);
  };
 
  const sortPoints = (items: number[]) =>
    items.sort((a: number, b: number) => {
      return a - b;
    });
 
  /**
   * Validates inputes parameters.
   */
  const validateInput = (input: PluginParams, index: number) => {
    const inputParameter = globalConfig['input-parameter'];
    const schema = z
      .object({
        timestamp: z.string().or(z.date()),
        duration: z.number(),
        [inputParameter]: z.number().gt(0),
      })
      .refine(
        data =>
          data[inputParameter] >= globalConfig.x[0] &&
          data[inputParameter] <= globalConfig.x[globalConfig.x.length - 1],
        {
          message: WITHIN_THE_RANGE,
        }
      );
 
    return validate<z.infer<typeof schema>>(schema, input, index);
  };
 
  return {
    metadata: {
      kind: 'execute',
    },
    execute,
  };
};