UNPKG

hyperformula

Version:

HyperFormula is a JavaScript engine for efficient processing of spreadsheet-like data and formulas

760 lines (618 loc) 24.6 kB
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } import "core-js/modules/es.array.reduce.js"; import "core-js/modules/es.object.get-prototype-of.js"; import "core-js/modules/es.reflect.construct.js"; import "core-js/modules/es.array.slice.js"; import "core-js/modules/es.object.to-string.js"; import "core-js/modules/es.function.name.js"; import "core-js/modules/es.array.from.js"; import "core-js/modules/es.string.iterator.js"; import "core-js/modules/es.symbol.js"; import "core-js/modules/es.symbol.description.js"; import "core-js/modules/es.symbol.iterator.js"; import "core-js/modules/es.array.iterator.js"; import "core-js/modules/web.dom-collections.iterator.js"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } /** * @license * Copyright (c) 2021 Handsoncode. All rights reserved. */ import { CellError, ErrorType } from '../../Cell'; import { ErrorMessage } from '../../error-message'; import { getRawValue, isExtendedNumber } from '../InterpreterValue'; import { centralF, chisquare, corrcoeff, covariance, geomean as _geomean, mean, normal, stdev, studentt, sumsqerr, variance } from './3rdparty/jstat/jstat'; import { ArgumentTypes, FunctionPlugin } from './FunctionPlugin'; export var StatisticalAggregationPlugin = /*#__PURE__*/function (_FunctionPlugin) { _inherits(StatisticalAggregationPlugin, _FunctionPlugin); var _super = _createSuper(StatisticalAggregationPlugin); function StatisticalAggregationPlugin() { _classCallCheck(this, StatisticalAggregationPlugin); return _super.apply(this, arguments); } _createClass(StatisticalAggregationPlugin, [{ key: "avedev", value: function avedev(ast, state) { var _this = this; return this.runFunction(ast.args, state, this.metadata('AVEDEV'), function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var coerced = _this.arithmeticHelper.coerceNumbersExactRanges(args); if (coerced instanceof CellError) { return coerced; } if (coerced.length === 0) { return new CellError(ErrorType.DIV_BY_ZERO); } var avg = mean(coerced); return coerced.reduce(function (a, b) { return a + Math.abs(b - avg); }, 0) / coerced.length; }); } }, { key: "devsq", value: function devsq(ast, state) { var _this2 = this; return this.runFunction(ast.args, state, this.metadata('DEVSQ'), function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } var coerced = _this2.arithmeticHelper.coerceNumbersExactRanges(args); if (coerced instanceof CellError) { return coerced; } if (coerced.length === 0) { return 0; } return sumsqerr(coerced); }); } }, { key: "geomean", value: function geomean(ast, state) { var _this3 = this; return this.runFunction(ast.args, state, this.metadata('GEOMEAN'), function () { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } var coerced = _this3.arithmeticHelper.coerceNumbersExactRanges(args); if (coerced instanceof CellError) { return coerced; } if (coerced.length === 0) { return new CellError(ErrorType.NUM, ErrorMessage.OneValue); } var _iterator = _createForOfIteratorHelper(coerced), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var val = _step.value; if (val <= 0) { return new CellError(ErrorType.NUM, ErrorMessage.ValueSmall); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return _geomean(coerced); }); } }, { key: "harmean", value: function harmean(ast, state) { var _this4 = this; return this.runFunction(ast.args, state, this.metadata('HARMEAN'), function () { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } var coerced = _this4.arithmeticHelper.coerceNumbersExactRanges(args); if (coerced instanceof CellError) { return coerced; } if (coerced.length === 0) { return new CellError(ErrorType.NUM, ErrorMessage.OneValue); } var _iterator2 = _createForOfIteratorHelper(coerced), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var val = _step2.value; if (val <= 0) { return new CellError(ErrorType.NUM, ErrorMessage.ValueSmall); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return coerced.length / coerced.reduce(function (a, b) { return a + 1 / b; }, 0); }); } }, { key: "correl", value: function correl(ast, state) { return this.runFunction(ast.args, state, this.metadata('CORREL'), function (dataX, dataY) { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new CellError(ErrorType.NA, ErrorMessage.EqualLength); } var ret = parseTwoArrays(dataX, dataY); if (ret instanceof CellError) { return ret; } var n = ret[0].length; if (n <= 1) { return new CellError(ErrorType.DIV_BY_ZERO, ErrorMessage.TwoValues); } return corrcoeff(ret[0], ret[1]); }); } }, { key: "rsq", value: function rsq(ast, state) { return this.runFunction(ast.args, state, this.metadata('RSQ'), function (dataX, dataY) { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new CellError(ErrorType.NA, ErrorMessage.EqualLength); } var ret = parseTwoArrays(dataX, dataY); if (ret instanceof CellError) { return ret; } var n = ret[0].length; if (n <= 1) { return new CellError(ErrorType.DIV_BY_ZERO, ErrorMessage.TwoValues); } return Math.pow(corrcoeff(ret[0], ret[1]), 2); }); } }, { key: "covariancep", value: function covariancep(ast, state) { return this.runFunction(ast.args, state, this.metadata('COVARIANCE.P'), function (dataX, dataY) { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new CellError(ErrorType.NA, ErrorMessage.EqualLength); } var ret = parseTwoArrays(dataX, dataY); if (ret instanceof CellError) { return ret; } var n = ret[0].length; if (n < 1) { return new CellError(ErrorType.DIV_BY_ZERO, ErrorMessage.OneValue); } if (n === 1) { return 0; } return covariance(ret[0], ret[1]) * (n - 1) / n; }); } }, { key: "covariances", value: function covariances(ast, state) { return this.runFunction(ast.args, state, this.metadata('COVARIANCE.S'), function (dataX, dataY) { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new CellError(ErrorType.NA, ErrorMessage.EqualLength); } var ret = parseTwoArrays(dataX, dataY); if (ret instanceof CellError) { return ret; } var n = ret[0].length; if (n <= 1) { return new CellError(ErrorType.DIV_BY_ZERO, ErrorMessage.TwoValues); } return covariance(ret[0], ret[1]); }); } }, { key: "ztest", value: function ztest(ast, state) { var _this5 = this; return this.runFunction(ast.args, state, this.metadata('Z.TEST'), function (range, x, sigma) { var vals = _this5.arithmeticHelper.manyToExactNumbers(range.valuesFromTopLeftCorner()); if (vals instanceof CellError) { return vals; } var n = vals.length; if (sigma === undefined) { if (n < 2) { return new CellError(ErrorType.DIV_BY_ZERO, ErrorMessage.TwoValues); } sigma = stdev(vals, true); } if (n < 1) { return new CellError(ErrorType.NA, ErrorMessage.OneValue); } if (sigma === 0) { return new CellError(ErrorType.DIV_BY_ZERO); } return 1 - normal.cdf((mean(vals) - x) / (sigma / Math.sqrt(n)), 0, 1); }); } }, { key: "ftest", value: function ftest(ast, state) { var _this6 = this; return this.runFunction(ast.args, state, this.metadata('F.TEST'), function (dataX, dataY) { var arrX = _this6.arithmeticHelper.manyToExactNumbers(dataX.valuesFromTopLeftCorner()); var arrY = _this6.arithmeticHelper.manyToExactNumbers(dataY.valuesFromTopLeftCorner()); if (arrX instanceof CellError) { return arrX; } if (arrY instanceof CellError) { return arrY; } if (arrX.length <= 1 || arrY.length <= 1) { return new CellError(ErrorType.DIV_BY_ZERO); } var vx = variance(arrX, true); var vy = variance(arrY, true); if (vx === 0 || vy === 0) { return new CellError(ErrorType.DIV_BY_ZERO); } var r = vx / vy; var v = centralF.cdf(r, arrX.length - 1, arrY.length - 1); return 2 * Math.min(v, 1 - v); }); } }, { key: "steyx", value: function steyx(ast, state) { return this.runFunction(ast.args, state, this.metadata('STEYX'), function (dataX, dataY) { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new CellError(ErrorType.NA, ErrorMessage.EqualLength); } var ret = parseTwoArrays(dataX, dataY); if (ret instanceof CellError) { return ret; } var n = ret[0].length; if (n <= 2) { return new CellError(ErrorType.DIV_BY_ZERO, ErrorMessage.ThreeValues); } return Math.sqrt((sumsqerr(ret[0]) - Math.pow(covariance(ret[0], ret[1]) * (n - 1), 2) / sumsqerr(ret[1])) / (n - 2)); }); } }, { key: "slope", value: function slope(ast, state) { return this.runFunction(ast.args, state, this.metadata('SLOPE'), function (dataX, dataY) { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new CellError(ErrorType.NA, ErrorMessage.EqualLength); } var ret = parseTwoArrays(dataX, dataY); if (ret instanceof CellError) { return ret; } var n = ret[0].length; if (n <= 1) { return new CellError(ErrorType.DIV_BY_ZERO, ErrorMessage.TwoValues); } return covariance(ret[0], ret[1]) * (n - 1) / sumsqerr(ret[1]); }); } }, { key: "chisqtest", value: function chisqtest(ast, state) { return this.runFunction(ast.args, state, this.metadata('CHISQ.TEST'), function (dataX, dataY) { var r = dataX.height(); var c = dataX.width(); if (dataY.height() !== r || dataY.width() !== c) { return new CellError(ErrorType.NA, ErrorMessage.EqualLength); } var ret = parseTwoArrays(dataX, dataY); if (ret instanceof CellError) { return ret; } if (ret[0].length <= 1) { return new CellError(ErrorType.DIV_BY_ZERO, ErrorMessage.TwoValues); } var sum = 0; for (var i = 0; i < ret[0].length; i++) { if (ret[1][i] === 0) { return new CellError(ErrorType.DIV_BY_ZERO); } sum += Math.pow(ret[0][i] - ret[1][i], 2) / ret[1][i]; } if (sum < 0) { return new CellError(ErrorType.NUM, ErrorMessage.NaN); } return 1 - chisquare.cdf(sum, r > 1 && c > 1 ? (r - 1) * (c - 1) : r * c - 1); }); } }, { key: "ttest", value: function ttest(ast, state) { var _this7 = this; return this.runFunction(ast.args, state, this.metadata('T.TEST'), function (dataX, dataY, tails, type) { var arrX = _this7.arithmeticHelper.manyToExactNumbers(dataX.valuesFromTopLeftCorner()); var arrY = _this7.arithmeticHelper.manyToExactNumbers(dataY.valuesFromTopLeftCorner()); if (arrX instanceof CellError) { return arrX; } if (arrY instanceof CellError) { return arrY; } var n = arrX.length; var m = arrY.length; if (type === 1) { if (m !== n) { return new CellError(ErrorType.NA, ErrorMessage.EqualLength); } if (n <= 1) { return new CellError(ErrorType.DIV_BY_ZERO, ErrorMessage.TwoValues); } var sub = Array(n); for (var i = 0; i < n; i++) { sub[i] = arrX[i] - arrY[i]; } var s = stdev(sub, true); if (s === 0) { return new CellError(ErrorType.DIV_BY_ZERO); } var t = Math.abs(Math.sqrt(n) * mean(sub) / s); return tails * (1 - studentt.cdf(t, n - 1)); } else if (type === 2) { if (n <= 1 || m <= 1) { return new CellError(ErrorType.DIV_BY_ZERO, ErrorMessage.TwoValues); } var _s = (sumsqerr(arrX) + sumsqerr(arrY)) / (n + m - 2); if (_s === 0) { return new CellError(ErrorType.DIV_BY_ZERO); } var _t = Math.abs((mean(arrX) - mean(arrY)) / Math.sqrt(_s * (1 / n + 1 / m))); return tails * (1 - studentt.cdf(_t, n + m - 2)); } else { //type === 3 if (n <= 1 || m <= 1) { return new CellError(ErrorType.DIV_BY_ZERO, ErrorMessage.TwoValues); } var sx = variance(arrX, true); var sy = variance(arrY, true); if (sx === 0 && sy === 0) { return new CellError(ErrorType.DIV_BY_ZERO); } var _t2 = Math.abs((mean(arrX) - mean(arrY)) / Math.sqrt(sx / n + sy / m)); var v = Math.pow(sx / n + sy / m, 2) / (Math.pow(sx / n, 2) / (n - 1) + Math.pow(sy / m, 2) / (m - 1)); return tails * (1 - studentt.cdf(_t2, v)); } }); } }, { key: "skew", value: function skew(ast, state) { var _this8 = this; return this.runFunction(ast.args, state, this.metadata('SKEW'), function () { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } var coerced = _this8.arithmeticHelper.coerceNumbersExactRanges(args); if (coerced instanceof CellError) { return coerced; } var n = coerced.length; if (n < 3) { return new CellError(ErrorType.DIV_BY_ZERO, ErrorMessage.ThreeValues); } var avg = mean(coerced); var s = stdev(coerced, true); if (s === 0) { return new CellError(ErrorType.DIV_BY_ZERO); } return coerced.reduce(function (a, b) { return a + Math.pow((b - avg) / s, 3); }, 0) * n / (n - 1) / (n - 2); }); } }, { key: "skewp", value: function skewp(ast, state) { var _this9 = this; return this.runFunction(ast.args, state, this.metadata('SKEW.P'), function () { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } var coerced = _this9.arithmeticHelper.coerceNumbersExactRanges(args); if (coerced instanceof CellError) { return coerced; } var n = coerced.length; if (n < 3) { return new CellError(ErrorType.DIV_BY_ZERO, ErrorMessage.ThreeValues); } var avg = mean(coerced); var s = stdev(coerced, false); if (s === 0) { return new CellError(ErrorType.DIV_BY_ZERO); } return coerced.reduce(function (a, b) { return a + Math.pow((b - avg) / s, 3); }, 0) / n; }); } }]); return StatisticalAggregationPlugin; }(FunctionPlugin); StatisticalAggregationPlugin.implementedFunctions = { 'AVEDEV': { method: 'avedev', parameters: [{ argumentType: ArgumentTypes.ANY }], repeatLastArgs: 1 }, 'DEVSQ': { method: 'devsq', parameters: [{ argumentType: ArgumentTypes.ANY }], repeatLastArgs: 1 }, 'GEOMEAN': { method: 'geomean', parameters: [{ argumentType: ArgumentTypes.ANY }], repeatLastArgs: 1 }, 'HARMEAN': { method: 'harmean', parameters: [{ argumentType: ArgumentTypes.ANY }], repeatLastArgs: 1 }, 'CORREL': { method: 'correl', parameters: [{ argumentType: ArgumentTypes.RANGE }, { argumentType: ArgumentTypes.RANGE }] }, 'RSQ': { method: 'rsq', parameters: [{ argumentType: ArgumentTypes.RANGE }, { argumentType: ArgumentTypes.RANGE }] }, 'COVARIANCE.P': { method: 'covariancep', parameters: [{ argumentType: ArgumentTypes.RANGE }, { argumentType: ArgumentTypes.RANGE }] }, 'COVARIANCE.S': { method: 'covariances', parameters: [{ argumentType: ArgumentTypes.RANGE }, { argumentType: ArgumentTypes.RANGE }] }, 'Z.TEST': { method: 'ztest', parameters: [{ argumentType: ArgumentTypes.RANGE }, { argumentType: ArgumentTypes.NUMBER }, { argumentType: ArgumentTypes.NUMBER, optionalArg: true }] }, 'F.TEST': { method: 'ftest', parameters: [{ argumentType: ArgumentTypes.RANGE }, { argumentType: ArgumentTypes.RANGE }] }, 'STEYX': { method: 'steyx', parameters: [{ argumentType: ArgumentTypes.RANGE }, { argumentType: ArgumentTypes.RANGE }] }, 'SLOPE': { method: 'slope', parameters: [{ argumentType: ArgumentTypes.RANGE }, { argumentType: ArgumentTypes.RANGE }] }, 'CHISQ.TEST': { method: 'chisqtest', parameters: [{ argumentType: ArgumentTypes.RANGE }, { argumentType: ArgumentTypes.RANGE }] }, 'T.TEST': { method: 'ttest', parameters: [{ argumentType: ArgumentTypes.RANGE }, { argumentType: ArgumentTypes.RANGE }, { argumentType: ArgumentTypes.INTEGER, minValue: 1, maxValue: 2 }, { argumentType: ArgumentTypes.INTEGER, minValue: 1, maxValue: 3 }] }, 'SKEW': { method: 'skew', parameters: [{ argumentType: ArgumentTypes.ANY }], repeatLastArgs: 1 }, 'SKEW.P': { method: 'skewp', parameters: [{ argumentType: ArgumentTypes.ANY }], repeatLastArgs: 1 } }; StatisticalAggregationPlugin.aliases = { COVAR: 'COVARIANCE.P', FTEST: 'F.TEST', PEARSON: 'CORREL', ZTEST: 'Z.TEST', CHITEST: 'CHISQ.TEST', TTEST: 'T.TEST', COVARIANCEP: 'COVARIANCE.P', COVARIANCES: 'COVARIANCE.S', SKEWP: 'SKEW.P' }; function parseTwoArrays(dataX, dataY) { var xit = dataX.iterateValuesFromTopLeftCorner(); var yit = dataY.iterateValuesFromTopLeftCorner(); var x, y; var arrX = []; var arrY = []; while (x = xit.next(), y = yit.next(), !x.done && !y.done) { var xval = x.value; var yval = y.value; if (xval instanceof CellError) { return xval; } else if (yval instanceof CellError) { return yval; } else if (isExtendedNumber(xval) && isExtendedNumber(yval)) { arrX.push(getRawValue(xval)); arrY.push(getRawValue(yval)); } } return [arrX, arrY]; }