From 35c5610aaab16082e9260d5e864603ee675218be Mon Sep 17 00:00:00 2001 From: cheminfo bot Date: Thu, 20 Jun 2019 08:05:42 +0000 Subject: [PATCH] Release v3.6.0 --- bower.json | 2 +- dist/ml.js | 36578 ++++++++++++++++++++++--------------------- dist/ml.js.map | 2 +- dist/ml.min.js | 4 +- dist/ml.min.js.map | 2 +- package-lock.json | 2 +- package.json | 46 +- 7 files changed, 18973 insertions(+), 17663 deletions(-) diff --git a/bower.json b/bower.json index 5e8c225..362cab8 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "ml", - "version": "3.4.0", + "version": "3.6.0", "main": [ "dist/ml.js", "dist/ml.min.js" diff --git a/dist/ml.js b/dist/ml.js index 6697917..83e3277 100644 --- a/dist/ml.js +++ b/dist/ml.js @@ -1,6 +1,6 @@ /** * ml - Machine learning tools - * @version v3.4.0 + * @version v3.6.0 * @link https://github.com/mljs/ml * @license MIT */ @@ -52,14 +52,34 @@ return /******/ (function(modules) { // webpackBootstrap /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { -/******/ configurable: false, -/******/ enumerable: true, -/******/ get: getter -/******/ }); +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? @@ -75,5525 +95,8500 @@ return /******/ (function(modules) { // webpackBootstrap /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ +/******/ /******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 57); +/******/ return __webpack_require__(__webpack_require__.s = 43); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +__webpack_require__.r(__webpack_exports__); +// EXTERNAL MODULE: ./node_modules/ml-array-rescale/lib-es6/index.js +var lib_es6 = __webpack_require__(13); -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _matrix = __webpack_require__(5); - -Object.defineProperty(exports, 'default', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_matrix).default; - } -}); -Object.defineProperty(exports, 'Matrix', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_matrix).default; - } -}); - -var _abstractMatrix = __webpack_require__(7); - -Object.defineProperty(exports, 'abstractMatrix', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_abstractMatrix).default; - } -}); - -var _wrap = __webpack_require__(68); - -Object.defineProperty(exports, 'wrap', { - enumerable: true, - get: function get() { - return _wrap.wrap; - } -}); +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/dc/lu.js -var _WrapperMatrix2D = __webpack_require__(22); +/** + * @class LuDecomposition + * @link https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs + * @param {Matrix} matrix + */ -Object.defineProperty(exports, 'WrapperMatrix2D', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_WrapperMatrix2D).default; - } -}); +class lu_LuDecomposition { + constructor(matrix) { + matrix = WrapperMatrix2D_WrapperMatrix2D.checkMatrix(matrix); + var lu = matrix.clone(); + var rows = lu.rows; + var columns = lu.columns; + var pivotVector = new Array(rows); + var pivotSign = 1; + var i, j, k, p, s, t, v; + var LUcolj, kmax; -var _WrapperMatrix1D = __webpack_require__(21); + for (i = 0; i < rows; i++) { + pivotVector[i] = i; + } -Object.defineProperty(exports, 'WrapperMatrix1D', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_WrapperMatrix1D).default; - } -}); + LUcolj = new Array(rows); -var _decompositions = __webpack_require__(69); + for (j = 0; j < columns; j++) { + for (i = 0; i < rows; i++) { + LUcolj[i] = lu.get(i, j); + } -Object.defineProperty(exports, 'solve', { - enumerable: true, - get: function get() { - return _decompositions.solve; - } -}); -Object.defineProperty(exports, 'inverse', { - enumerable: true, - get: function get() { - return _decompositions.inverse; - } -}); + for (i = 0; i < rows; i++) { + kmax = Math.min(i, j); + s = 0; -var _linearDependencies = __webpack_require__(70); + for (k = 0; k < kmax; k++) { + s += lu.get(i, k) * LUcolj[k]; + } -Object.defineProperty(exports, 'linearDependencies', { - enumerable: true, - get: function get() { - return _linearDependencies.linearDependencies; - } -}); + LUcolj[i] -= s; + lu.set(i, j, LUcolj[i]); + } -var _svd = __webpack_require__(9); + p = j; -Object.defineProperty(exports, 'SingularValueDecomposition', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_svd).default; - } -}); -Object.defineProperty(exports, 'SVD', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_svd).default; - } -}); + for (i = j + 1; i < rows; i++) { + if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) { + p = i; + } + } -var _evd = __webpack_require__(71); + if (p !== j) { + for (k = 0; k < columns; k++) { + t = lu.get(p, k); + lu.set(p, k, lu.get(j, k)); + lu.set(j, k, t); + } -Object.defineProperty(exports, 'EigenvalueDecomposition', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_evd).default; - } -}); -Object.defineProperty(exports, 'EVD', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_evd).default; - } -}); + v = pivotVector[p]; + pivotVector[p] = pivotVector[j]; + pivotVector[j] = v; + pivotSign = -pivotSign; + } -var _cholesky = __webpack_require__(72); + if (j < rows && lu.get(j, j) !== 0) { + for (i = j + 1; i < rows; i++) { + lu.set(i, j, lu.get(i, j) / lu.get(j, j)); + } + } + } -Object.defineProperty(exports, 'CholeskyDecomposition', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_cholesky).default; - } -}); -Object.defineProperty(exports, 'CHO', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_cholesky).default; + this.LU = lu; + this.pivotVector = pivotVector; + this.pivotSign = pivotSign; } -}); + /** + * + * @return {boolean} + */ -var _lu = __webpack_require__(12); -Object.defineProperty(exports, 'LuDecomposition', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_lu).default; - } -}); -Object.defineProperty(exports, 'LU', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_lu).default; - } -}); + isSingular() { + var data = this.LU; + var col = data.columns; -var _qr = __webpack_require__(23); + for (var j = 0; j < col; j++) { + if (data[j][j] === 0) { + return true; + } + } -Object.defineProperty(exports, 'QrDecomposition', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_qr).default; - } -}); -Object.defineProperty(exports, 'QR', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_qr).default; + return false; } -}); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * + * @param {Matrix} value + * @return {Matrix} + */ -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + solve(value) { + value = matrix_Matrix.checkMatrix(value); + var lu = this.LU; + var rows = lu.rows; + if (rows !== value.rows) { + throw new Error('Invalid matrix dimensions'); + } -function squaredEuclidean(p, q) { - var d = 0; - for (var i = 0; i < p.length; i++) { - d += (p[i] - q[i]) * (p[i] - q[i]); + if (this.isSingular()) { + throw new Error('LU matrix is singular'); } - return d; -} -function euclidean(p, q) { - return Math.sqrt(squaredEuclidean(p, q)); -} + var count = value.columns; + var X = value.subMatrixRow(this.pivotVector, 0, count - 1); + var columns = lu.columns; + var i, j, k; -module.exports = euclidean; -euclidean.squared = squaredEuclidean; + for (k = 0; k < columns; k++) { + for (i = k + 1; i < columns; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * lu[i][k]; + } + } + } -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { + for (k = columns - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + X[k][j] /= lu[k][k]; + } -"use strict"; + for (i = 0; i < k; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * lu[i][k]; + } + } + } + return X; + } + /** + * + * @return {number} + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -var _maybeToPrecision = __webpack_require__(122); + get determinant() { + var data = this.LU; -Object.defineProperty(exports, 'maybeToPrecision', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_maybeToPrecision).default; + if (!data.isSquare()) { + throw new Error('Matrix must be square'); } -}); -var _checkArrayLength = __webpack_require__(123); + var determinant = this.pivotSign; + var col = data.columns; -Object.defineProperty(exports, 'checkArrayLength', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_checkArrayLength).default; + for (var j = 0; j < col; j++) { + determinant *= data[j][j]; } -}); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return determinant; + } + /** + * + * @return {Matrix} + */ -class BaseRegression { - constructor() { - if (new.target === BaseRegression) { - throw new Error('BaseRegression must be subclassed'); - } - } - predict(x) { - if (typeof x === 'number') { - return this._predict(x); - } else if (Array.isArray(x)) { - var y = new Array(x.length); - for (var i = 0; i < x.length; i++) { - y[i] = this._predict(x[i]); - } - return y; + get lowerTriangularMatrix() { + var data = this.LU; + var rows = data.rows; + var columns = data.columns; + var X = new matrix_Matrix(rows, columns); + + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + if (i > j) { + X[i][j] = data[i][j]; + } else if (i === j) { + X[i][j] = 1; } else { - throw new TypeError('x must be a number or array'); + X[i][j] = 0; } + } } - _predict() { - throw new Error('_predict must be implemented'); - } - - train() { - //Do nothing for this package - } + return X; + } + /** + * + * @return {Matrix} + */ - toString() { - return ''; - } - toLaTeX() { - return ''; - } + get upperTriangularMatrix() { + var data = this.LU; + var rows = data.rows; + var columns = data.columns; + var X = new matrix_Matrix(rows, columns); - /** - * Return the correlation coefficient of determination (r) and chi-square. - * @param {Array} x - * @param {Array} y - * @return {object} - */ - score(x, y) { - if (!Array.isArray(x) || !Array.isArray(y) || x.length !== y.length) { - throw new Error('x and y must be arrays of the same length'); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + if (i <= j) { + X[i][j] = data[i][j]; + } else { + X[i][j] = 0; } + } + } - var n = x.length; - var y2 = new Array(n); - for (var i = 0; i < n; i++) { - y2[i] = this._predict(x[i]); - } + return X; + } + /** + * + * @return {Array} + */ - var xSum = 0; - var ySum = 0; - var chi2 = 0; - var rmsd = 0; - var xSquared = 0; - var ySquared = 0; - var xY = 0; - for (var _i = 0; _i < n; _i++) { - xSum += y2[_i]; - ySum += y[_i]; - xSquared += y2[_i] * y2[_i]; - ySquared += y[_i] * y[_i]; - xY += y2[_i] * y[_i]; - if (y[_i] !== 0) { - chi2 += (y[_i] - y2[_i]) * (y[_i] - y2[_i]) / y[_i]; - } - rmsd = (y[_i] - y2[_i]) * (y[_i] - y2[_i]); - } - var r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum)); + get pivotPermutationVector() { + return this.pivotVector.slice(); + } - return { - r: r, - r2: r * r, - chi2: chi2, - rmsd: rmsd * rmsd / n - }; - } } -exports.default = BaseRegression; - -/***/ }), -/* 3 */ -/***/ (function(module, exports, __webpack_require__) { +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/dc/util.js +function hypotenuse(a, b) { + var r = 0; -"use strict"; + if (Math.abs(a) > Math.abs(b)) { + r = b / a; + return Math.abs(a) * Math.sqrt(1 + r * r); + } + if (b !== 0) { + r = a / b; + return Math.abs(b) * Math.sqrt(1 + r * r); + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + return 0; +} +function getFilled2DArray(rows, columns, value) { + var array = new Array(rows); -var _abstractMatrix = __webpack_require__(7); + for (var i = 0; i < rows; i++) { + array[i] = new Array(columns); -var _abstractMatrix2 = _interopRequireDefault(_abstractMatrix); + for (var j = 0; j < columns; j++) { + array[i][j] = value; + } + } -var _matrix = __webpack_require__(5); + return array; +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/dc/svd.js -var _matrix2 = _interopRequireDefault(_matrix); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * @class SingularValueDecomposition + * @see https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs + * @param {Matrix} value + * @param {object} [options] + * @param {boolean} [options.computeLeftSingularVectors=true] + * @param {boolean} [options.computeRightSingularVectors=true] + * @param {boolean} [options.autoTranspose=false] + */ -class BaseView extends (0, _abstractMatrix2.default)() { - constructor(matrix, rows, columns) { - super(); - this.matrix = matrix; - this.rows = rows; - this.columns = columns; - } +class svd_SingularValueDecomposition { + constructor(value) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + value = WrapperMatrix2D_WrapperMatrix2D.checkMatrix(value); + var m = value.rows; + var n = value.columns; + const { + computeLeftSingularVectors = true, + computeRightSingularVectors = true, + autoTranspose = false + } = options; + var wantu = Boolean(computeLeftSingularVectors); + var wantv = Boolean(computeRightSingularVectors); + var swapped = false; + var a; - static get [Symbol.species]() { - return _matrix2.default; - } -} -exports.default = BaseView; + if (m < n) { + if (!autoTranspose) { + a = value.clone(); // eslint-disable-next-line no-console -/***/ }), -/* 4 */ -/***/ (function(module, exports, __webpack_require__) { + console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose'); + } else { + a = value.transpose(); + m = a.rows; + n = a.columns; + swapped = true; + var aux = wantu; + wantu = wantv; + wantv = aux; + } + } else { + a = value.clone(); + } -"use strict"; + var nu = Math.min(m, n); + var ni = Math.min(m + 1, n); + var s = new Array(ni); + var U = getFilled2DArray(m, nu, 0); + var V = getFilled2DArray(n, n, 0); + var e = new Array(n); + var work = new Array(m); + var si = new Array(ni); + for (let i = 0; i < ni; i++) si[i] = i; -exports.array = __webpack_require__(27); -exports.matrix = __webpack_require__(10); + var nct = Math.min(m - 1, n); + var nrt = Math.max(0, Math.min(n - 2, m)); + var mrc = Math.max(nct, nrt); -/***/ }), -/* 5 */ -/***/ (function(module, exports, __webpack_require__) { + for (let k = 0; k < mrc; k++) { + if (k < nct) { + s[k] = 0; -"use strict"; + for (let i = k; i < m; i++) { + s[k] = hypotenuse(s[k], a[i][k]); + } + if (s[k] !== 0) { + if (a[k][k] < 0) { + s[k] = -s[k]; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + for (let i = k; i < m; i++) { + a[i][k] /= s[k]; + } -var _abstractMatrix = __webpack_require__(7); + a[k][k] += 1; + } -var _abstractMatrix2 = _interopRequireDefault(_abstractMatrix); + s[k] = -s[k]; + } -var _util = __webpack_require__(6); + for (let j = k + 1; j < n; j++) { + if (k < nct && s[k] !== 0) { + let t = 0; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (let i = k; i < m; i++) { + t += a[i][k] * a[i][j]; + } -class Matrix extends (0, _abstractMatrix2.default)(Array) { - constructor(nRows, nColumns) { - var i; - if (arguments.length === 1 && typeof nRows === 'number') { - return new Array(nRows); - } - if (Matrix.isMatrix(nRows)) { - return nRows.clone(); - } else if (Number.isInteger(nRows) && nRows > 0) { - // Create an empty matrix - super(nRows); - if (Number.isInteger(nColumns) && nColumns > 0) { - for (i = 0; i < nRows; i++) { - this[i] = new Array(nColumns); + t = -t / a[k][k]; + + for (let i = k; i < m; i++) { + a[i][j] += t * a[i][k]; + } } - } else { - throw new TypeError('nColumns must be a positive integer'); - } - } else if (Array.isArray(nRows)) { - // Copy the values from the 2D array - var matrix = nRows; - nRows = matrix.length; - nColumns = matrix[0].length; - if (typeof nColumns !== 'number' || nColumns === 0) { - throw new TypeError('Data must be a 2D array with at least one element'); + + e[j] = a[k][j]; } - super(nRows); - for (i = 0; i < nRows; i++) { - if (matrix[i].length !== nColumns) { - throw new RangeError('Inconsistent array dimensions'); + + if (wantu && k < nct) { + for (let i = k; i < m; i++) { + U[i][k] = a[i][k]; } - this[i] = [].concat(matrix[i]); } - } else { - throw new TypeError('First argument must be a positive number or an array'); - } - this.rows = nRows; - this.columns = nColumns; - return this; - } - set(rowIndex, columnIndex, value) { - this[rowIndex][columnIndex] = value; - return this; - } + if (k < nrt) { + e[k] = 0; - get(rowIndex, columnIndex) { - return this[rowIndex][columnIndex]; - } + for (let i = k + 1; i < n; i++) { + e[k] = hypotenuse(e[k], e[i]); + } - /** - * Removes a row from the given index - * @param {number} index - Row index - * @return {Matrix} this - */ - removeRow(index) { - (0, _util.checkRowIndex)(this, index); - if (this.rows === 1) { - throw new RangeError('A matrix cannot have less than one row'); - } - this.splice(index, 1); - this.rows -= 1; - return this; - } + if (e[k] !== 0) { + if (e[k + 1] < 0) { + e[k] = 0 - e[k]; + } - /** - * Adds a row at the given index - * @param {number} [index = this.rows] - Row index - * @param {Array|Matrix} array - Array or vector - * @return {Matrix} this - */ - addRow(index, array) { - if (array === undefined) { - array = index; - index = this.rows; - } - (0, _util.checkRowIndex)(this, index, true); - array = (0, _util.checkRowVector)(this, array, true); - this.splice(index, 0, array); - this.rows += 1; - return this; - } + for (let i = k + 1; i < n; i++) { + e[i] /= e[k]; + } - /** - * Removes a column from the given index - * @param {number} index - Column index - * @return {Matrix} this - */ - removeColumn(index) { - (0, _util.checkColumnIndex)(this, index); - if (this.columns === 1) { - throw new RangeError('A matrix cannot have less than one column'); + e[k + 1] += 1; + } + + e[k] = -e[k]; + + if (k + 1 < m && e[k] !== 0) { + for (let i = k + 1; i < m; i++) { + work[i] = 0; + } + + for (let i = k + 1; i < m; i++) { + for (let j = k + 1; j < n; j++) { + work[i] += e[j] * a[i][j]; + } + } + + for (let j = k + 1; j < n; j++) { + let t = -e[j] / e[k + 1]; + + for (let i = k + 1; i < m; i++) { + a[i][j] += t * work[i]; + } + } + } + + if (wantv) { + for (let i = k + 1; i < n; i++) { + V[i][k] = e[i]; + } + } + } } - for (var i = 0; i < this.rows; i++) { - this[i].splice(index, 1); + + let p = Math.min(n, m + 1); + + if (nct < n) { + s[nct] = a[nct][nct]; } - this.columns -= 1; - return this; - } - /** - * Adds a column at the given index - * @param {number} [index = this.columns] - Column index - * @param {Array|Matrix} array - Array or vector - * @return {Matrix} this - */ - addColumn(index, array) { - if (typeof array === 'undefined') { - array = index; - index = this.columns; + if (m < p) { + s[p - 1] = 0; } - (0, _util.checkColumnIndex)(this, index, true); - array = (0, _util.checkColumnVector)(this, array); - for (var i = 0; i < this.rows; i++) { - this[i].splice(index, 0, array[i]); + + if (nrt + 1 < p) { + e[nrt] = a[nrt][p - 1]; } - this.columns += 1; - return this; - } -} -exports.default = Matrix; -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { + e[p - 1] = 0; -"use strict"; + if (wantu) { + for (let j = nct; j < nu; j++) { + for (let i = 0; i < m; i++) { + U[i][j] = 0; + } + U[j][j] = 1; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.checkRowIndex = checkRowIndex; -exports.checkColumnIndex = checkColumnIndex; -exports.checkRowVector = checkRowVector; -exports.checkColumnVector = checkColumnVector; -exports.checkIndices = checkIndices; -exports.checkRowIndices = checkRowIndices; -exports.checkColumnIndices = checkColumnIndices; -exports.checkRange = checkRange; -exports.getRange = getRange; -exports.sumByRow = sumByRow; -exports.sumByColumn = sumByColumn; -exports.sumAll = sumAll; + for (let k = nct - 1; k >= 0; k--) { + if (s[k] !== 0) { + for (let j = k + 1; j < nu; j++) { + let t = 0; -var _matrix = __webpack_require__(5); + for (let i = k; i < m; i++) { + t += U[i][k] * U[i][j]; + } -var _matrix2 = _interopRequireDefault(_matrix); + t = -t / U[k][k]; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (let i = k; i < m; i++) { + U[i][j] += t * U[i][k]; + } + } -/** - * @private - * Check that a row index is not out of bounds - * @param {Matrix} matrix - * @param {number} index - * @param {boolean} [outer] - */ -function checkRowIndex(matrix, index, outer) { - var max = outer ? matrix.rows : matrix.rows - 1; - if (index < 0 || index > max) { - throw new RangeError('Row index out of range'); - } -} + for (let i = k; i < m; i++) { + U[i][k] = -U[i][k]; + } -/** - * @private - * Check that a column index is not out of bounds - * @param {Matrix} matrix - * @param {number} index - * @param {boolean} [outer] - */ -function checkColumnIndex(matrix, index, outer) { - var max = outer ? matrix.columns : matrix.columns - 1; - if (index < 0 || index > max) { - throw new RangeError('Column index out of range'); - } -} + U[k][k] = 1 + U[k][k]; -/** - * @private - * Check that the provided vector is an array with the right length - * @param {Matrix} matrix - * @param {Array|Matrix} vector - * @return {Array} - * @throws {RangeError} - */ -function checkRowVector(matrix, vector) { - if (vector.to1DArray) { - vector = vector.to1DArray(); - } - if (vector.length !== matrix.columns) { - throw new RangeError('vector size must be the same as the number of columns'); - } - return vector; -} + for (let i = 0; i < k - 1; i++) { + U[i][k] = 0; + } + } else { + for (let i = 0; i < m; i++) { + U[i][k] = 0; + } -/** - * @private - * Check that the provided vector is an array with the right length - * @param {Matrix} matrix - * @param {Array|Matrix} vector - * @return {Array} - * @throws {RangeError} - */ -function checkColumnVector(matrix, vector) { - if (vector.to1DArray) { - vector = vector.to1DArray(); - } - if (vector.length !== matrix.rows) { - throw new RangeError('vector size must be the same as the number of rows'); - } - return vector; -} + U[k][k] = 1; + } + } + } -function checkIndices(matrix, rowIndices, columnIndices) { - return { - row: checkRowIndices(matrix, rowIndices), - column: checkColumnIndices(matrix, columnIndices) - }; -} + if (wantv) { + for (let k = n - 1; k >= 0; k--) { + if (k < nrt && e[k] !== 0) { + for (let j = k + 1; j < n; j++) { + let t = 0; -function checkRowIndices(matrix, rowIndices) { - if (typeof rowIndices !== 'object') { - throw new TypeError('unexpected type for row indices'); - } + for (let i = k + 1; i < n; i++) { + t += V[i][k] * V[i][j]; + } - var rowOut = rowIndices.some(r => { - return r < 0 || r >= matrix.rows; - }); + t = -t / V[k + 1][k]; - if (rowOut) { - throw new RangeError('row indices are out of range'); - } + for (let i = k + 1; i < n; i++) { + V[i][j] += t * V[i][k]; + } + } + } - if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices); + for (let i = 0; i < n; i++) { + V[i][k] = 0; + } - return rowIndices; -} + V[k][k] = 1; + } + } -function checkColumnIndices(matrix, columnIndices) { - if (typeof columnIndices !== 'object') { - throw new TypeError('unexpected type for column indices'); - } + var pp = p - 1; + var iter = 0; + var eps = Number.EPSILON; - var columnOut = columnIndices.some(c => { - return c < 0 || c >= matrix.columns; - }); + while (p > 0) { + let k, kase; - if (columnOut) { - throw new RangeError('column indices are out of range'); - } - if (!Array.isArray(columnIndices)) columnIndices = Array.from(columnIndices); + for (k = p - 2; k >= -1; k--) { + if (k === -1) { + break; + } - return columnIndices; -} + const alpha = Number.MIN_VALUE + eps * Math.abs(s[k] + Math.abs(s[k + 1])); -function checkRange(matrix, startRow, endRow, startColumn, endColumn) { - if (arguments.length !== 5) { - throw new RangeError('expected 4 arguments'); - } - checkNumber('startRow', startRow); - checkNumber('endRow', endRow); - checkNumber('startColumn', startColumn); - checkNumber('endColumn', endColumn); - if (startRow > endRow || startColumn > endColumn || startRow < 0 || startRow >= matrix.rows || endRow < 0 || endRow >= matrix.rows || startColumn < 0 || startColumn >= matrix.columns || endColumn < 0 || endColumn >= matrix.columns) { - throw new RangeError('Submatrix indices are out of range'); - } -} + if (Math.abs(e[k]) <= alpha || Number.isNaN(e[k])) { + e[k] = 0; + break; + } + } -function getRange(from, to) { - var arr = new Array(to - from + 1); - for (var i = 0; i < arr.length; i++) { - arr[i] = from + i; - } - return arr; -} + if (k === p - 2) { + kase = 4; + } else { + let ks; -function sumByRow(matrix) { - var sum = _matrix2.default.zeros(matrix.rows, 1); - for (var i = 0; i < matrix.rows; ++i) { - for (var j = 0; j < matrix.columns; ++j) { - sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j)); - } - } - return sum; -} + for (ks = p - 1; ks >= k; ks--) { + if (ks === k) { + break; + } -function sumByColumn(matrix) { - var sum = _matrix2.default.zeros(1, matrix.columns); - for (var i = 0; i < matrix.rows; ++i) { - for (var j = 0; j < matrix.columns; ++j) { - sum.set(0, j, sum.get(0, j) + matrix.get(i, j)); - } - } - return sum; -} + let t = (ks !== p ? Math.abs(e[ks]) : 0) + (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0); -function sumAll(matrix) { - var v = 0; - for (var i = 0; i < matrix.rows; i++) { - for (var j = 0; j < matrix.columns; j++) { - v += matrix.get(i, j); - } - } - return v; -} + if (Math.abs(s[ks]) <= eps * t) { + s[ks] = 0; + break; + } + } -function checkNumber(name, value) { - if (typeof value !== 'number') { - throw new TypeError(`${name} must be a number`); - } -} + if (ks === k) { + kase = 3; + } else if (ks === p - 1) { + kase = 1; + } else { + kase = 2; + k = ks; + } + } -/***/ }), -/* 7 */ -/***/ (function(module, exports, __webpack_require__) { + k++; -"use strict"; + switch (kase) { + case 1: + { + let f = e[p - 2]; + e[p - 2] = 0; + for (let j = p - 2; j >= k; j--) { + let t = hypotenuse(s[j], f); + let cs = s[j] / t; + let sn = f / t; + s[j] = t; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = AbstractMatrix; + if (j !== k) { + f = -sn * e[j - 1]; + e[j - 1] = cs * e[j - 1]; + } -var _mlArrayRescale = __webpack_require__(19); + if (wantv) { + for (let i = 0; i < n; i++) { + t = cs * V[i][j] + sn * V[i][p - 1]; + V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1]; + V[i][j] = t; + } + } + } -var _mlArrayRescale2 = _interopRequireDefault(_mlArrayRescale); + break; + } -var _lu = __webpack_require__(12); + case 2: + { + let f = e[k - 1]; + e[k - 1] = 0; -var _lu2 = _interopRequireDefault(_lu); + for (let j = k; j < p; j++) { + let t = hypotenuse(s[j], f); + let cs = s[j] / t; + let sn = f / t; + s[j] = t; + f = -sn * e[j]; + e[j] = cs * e[j]; -var _svd = __webpack_require__(9); + if (wantu) { + for (let i = 0; i < m; i++) { + t = cs * U[i][j] + sn * U[i][k - 1]; + U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1]; + U[i][j] = t; + } + } + } -var _svd2 = _interopRequireDefault(_svd); + break; + } -var _util = __webpack_require__(6); + case 3: + { + const scale = Math.max(Math.abs(s[p - 1]), Math.abs(s[p - 2]), Math.abs(e[p - 2]), Math.abs(s[k]), Math.abs(e[k])); + const sp = s[p - 1] / scale; + const spm1 = s[p - 2] / scale; + const epm1 = e[p - 2] / scale; + const sk = s[k] / scale; + const ek = e[k] / scale; + const b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2; + const c = sp * epm1 * (sp * epm1); + let shift = 0; -var _transpose = __webpack_require__(59); + if (b !== 0 || c !== 0) { + if (b < 0) { + shift = 0 - Math.sqrt(b * b + c); + } else { + shift = Math.sqrt(b * b + c); + } -var _transpose2 = _interopRequireDefault(_transpose); + shift = c / (b + shift); + } -var _row = __webpack_require__(60); + let f = (sk + sp) * (sk - sp) + shift; + let g = sk * ek; -var _row2 = _interopRequireDefault(_row); + for (let j = k; j < p - 1; j++) { + let t = hypotenuse(f, g); + if (t === 0) t = Number.MIN_VALUE; + let cs = f / t; + let sn = g / t; -var _sub = __webpack_require__(61); + if (j !== k) { + e[j - 1] = t; + } -var _sub2 = _interopRequireDefault(_sub); + f = cs * s[j] + sn * e[j]; + e[j] = cs * e[j] - sn * s[j]; + g = sn * s[j + 1]; + s[j + 1] = cs * s[j + 1]; -var _selection = __webpack_require__(62); + if (wantv) { + for (let i = 0; i < n; i++) { + t = cs * V[i][j] + sn * V[i][j + 1]; + V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1]; + V[i][j] = t; + } + } -var _selection2 = _interopRequireDefault(_selection); + t = hypotenuse(f, g); + if (t === 0) t = Number.MIN_VALUE; + cs = f / t; + sn = g / t; + s[j] = t; + f = cs * e[j] + sn * s[j + 1]; + s[j + 1] = -sn * e[j] + cs * s[j + 1]; + g = sn * e[j + 1]; + e[j + 1] = cs * e[j + 1]; + + if (wantu && j < m - 1) { + for (let i = 0; i < m; i++) { + t = cs * U[i][j] + sn * U[i][j + 1]; + U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1]; + U[i][j] = t; + } + } + } -var _rowSelection = __webpack_require__(63); + e[p - 2] = f; + iter = iter + 1; + break; + } -var _rowSelection2 = _interopRequireDefault(_rowSelection); + case 4: + { + if (s[k] <= 0) { + s[k] = s[k] < 0 ? -s[k] : 0; -var _columnSelection = __webpack_require__(64); + if (wantv) { + for (let i = 0; i <= pp; i++) { + V[i][k] = -V[i][k]; + } + } + } -var _columnSelection2 = _interopRequireDefault(_columnSelection); + while (k < pp) { + if (s[k] >= s[k + 1]) { + break; + } -var _column = __webpack_require__(65); + let t = s[k]; + s[k] = s[k + 1]; + s[k + 1] = t; -var _column2 = _interopRequireDefault(_column); + if (wantv && k < n - 1) { + for (let i = 0; i < n; i++) { + t = V[i][k + 1]; + V[i][k + 1] = V[i][k]; + V[i][k] = t; + } + } -var _flipRow = __webpack_require__(66); + if (wantu && k < m - 1) { + for (let i = 0; i < m; i++) { + t = U[i][k + 1]; + U[i][k + 1] = U[i][k]; + U[i][k] = t; + } + } -var _flipRow2 = _interopRequireDefault(_flipRow); + k++; + } -var _flipColumn = __webpack_require__(67); + iter = 0; + p--; + break; + } + // no default + } + } -var _flipColumn2 = _interopRequireDefault(_flipColumn); + if (swapped) { + var tmp = V; + V = U; + U = tmp; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + this.m = m; + this.n = n; + this.s = s; + this.U = U; + this.V = V; + } + /** + * Solve a problem of least square (Ax=b) by using the SVD. Useful when A is singular. When A is not singular, it would be better to use qr.solve(value). + * Example : We search to approximate x, with A matrix shape m*n, x vector size n, b vector size m (m > n). We will use : + * var svd = SingularValueDecomposition(A); + * var x = svd.solve(b); + * @param {Matrix} value - Matrix 1D which is the vector b (in the equation Ax = b) + * @return {Matrix} - The vector x + */ -function AbstractMatrix(superCtor) { - if (superCtor === undefined) superCtor = Object; - /** - * Real matrix - * @class Matrix - * @param {number|Array|Matrix} nRows - Number of rows of the new matrix, - * 2D array containing the data or Matrix instance to clone - * @param {number} [nColumns] - Number of columns of the new matrix - */ - class Matrix extends superCtor { - static get [Symbol.species]() { - return this; - } + solve(value) { + var Y = value; + var e = this.threshold; + var scols = this.s.length; + var Ls = matrix_Matrix.zeros(scols, scols); - /** - * Constructs a Matrix with the chosen dimensions from a 1D array - * @param {number} newRows - Number of rows - * @param {number} newColumns - Number of columns - * @param {Array} newData - A 1D array containing data for the matrix - * @return {Matrix} - The new matrix - */ - static from1DArray(newRows, newColumns, newData) { - var length = newRows * newColumns; - if (length !== newData.length) { - throw new RangeError('Data length does not match given dimensions'); - } - var newMatrix = new this(newRows, newColumns); - for (var row = 0; row < newRows; row++) { - for (var column = 0; column < newColumns; column++) { - newMatrix.set(row, column, newData[row * newColumns + column]); - } + for (let i = 0; i < scols; i++) { + if (Math.abs(this.s[i]) <= e) { + Ls[i][i] = 0; + } else { + Ls[i][i] = 1 / this.s[i]; } - return newMatrix; } - /** - * Creates a row vector, a matrix with only one row. - * @param {Array} newData - A 1D array containing data for the vector - * @return {Matrix} - The new matrix - */ - static rowVector(newData) { - var vector = new this(1, newData.length); - for (var i = 0; i < newData.length; i++) { - vector.set(0, i, newData[i]); - } - return vector; - } + var U = this.U; + var V = this.rightSingularVectors; + var VL = V.mmul(Ls); + var vrows = V.rows; + var urows = U.length; + var VLU = matrix_Matrix.zeros(vrows, urows); - /** - * Creates a column vector, a matrix with only one column. - * @param {Array} newData - A 1D array containing data for the vector - * @return {Matrix} - The new matrix - */ - static columnVector(newData) { - var vector = new this(newData.length, 1); - for (var i = 0; i < newData.length; i++) { - vector.set(i, 0, newData[i]); + for (let i = 0; i < vrows; i++) { + for (let j = 0; j < urows; j++) { + let sum = 0; + + for (let k = 0; k < scols; k++) { + sum += VL[i][k] * U[j][k]; + } + + VLU[i][j] = sum; } - return vector; } - /** - * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns). - * @param {number} rows - Number of rows - * @param {number} columns - Number of columns - * @return {Matrix} - The new matrix - */ - static empty(rows, columns) { - return new this(rows, columns); - } + return VLU.mmul(Y); + } + /** + * + * @param {Array} value + * @return {Matrix} + */ - /** - * Creates a matrix with the given dimensions. Values will be set to zero. - * @param {number} rows - Number of rows - * @param {number} columns - Number of columns - * @return {Matrix} - The new matrix - */ - static zeros(rows, columns) { - return this.empty(rows, columns).fill(0); - } - /** - * Creates a matrix with the given dimensions. Values will be set to one. - * @param {number} rows - Number of rows - * @param {number} columns - Number of columns - * @return {Matrix} - The new matrix - */ - static ones(rows, columns) { - return this.empty(rows, columns).fill(1); - } + solveForDiagonal(value) { + return this.solve(matrix_Matrix.diag(value)); + } + /** + * Get the inverse of the matrix. We compute the inverse of a matrix using SVD when this matrix is singular or ill-conditioned. Example : + * var svd = SingularValueDecomposition(A); + * var inverseA = svd.inverse(); + * @return {Matrix} - The approximation of the inverse of the matrix + */ - /** - * Creates a matrix with the given dimensions. Values will be randomly set. - * @param {number} rows - Number of rows - * @param {number} columns - Number of columns - * @param {function} [rng=Math.random] - Random number generator - * @return {Matrix} The new matrix - */ - static rand(rows, columns, rng) { - if (rng === undefined) rng = Math.random; - var matrix = this.empty(rows, columns); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - matrix.set(i, j, rng()); - } - } - return matrix; - } - /** - * Creates a matrix with the given dimensions. Values will be random integers. - * @param {number} rows - Number of rows - * @param {number} columns - Number of columns - * @param {number} [maxValue=1000] - Maximum value - * @param {function} [rng=Math.random] - Random number generator - * @return {Matrix} The new matrix - */ - static randInt(rows, columns, maxValue, rng) { - if (maxValue === undefined) maxValue = 1000; - if (rng === undefined) rng = Math.random; - var matrix = this.empty(rows, columns); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - var value = Math.floor(rng() * maxValue); - matrix.set(i, j, value); + inverse() { + var V = this.V; + var e = this.threshold; + var vrows = V.length; + var vcols = V[0].length; + var X = new matrix_Matrix(vrows, this.s.length); + + for (let i = 0; i < vrows; i++) { + for (let j = 0; j < vcols; j++) { + if (Math.abs(this.s[j]) > e) { + X[i][j] = V[i][j] / this.s[j]; + } else { + X[i][j] = 0; } } - return matrix; } - /** - * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0. - * @param {number} rows - Number of rows - * @param {number} [columns=rows] - Number of columns - * @param {number} [value=1] - Value to fill the diagonal with - * @return {Matrix} - The new identity matrix - */ - static eye(rows, columns, value) { - if (columns === undefined) columns = rows; - if (value === undefined) value = 1; - var min = Math.min(rows, columns); - var matrix = this.zeros(rows, columns); - for (var i = 0; i < min; i++) { - matrix.set(i, i, value); - } - return matrix; - } + var U = this.U; + var urows = U.length; + var ucols = U[0].length; + var Y = new matrix_Matrix(vrows, urows); - /** - * Creates a diagonal matrix based on the given array. - * @param {Array} data - Array containing the data for the diagonal - * @param {number} [rows] - Number of rows (Default: data.length) - * @param {number} [columns] - Number of columns (Default: rows) - * @return {Matrix} - The new diagonal matrix - */ - static diag(data, rows, columns) { - var l = data.length; - if (rows === undefined) rows = l; - if (columns === undefined) columns = rows; - var min = Math.min(l, rows, columns); - var matrix = this.zeros(rows, columns); - for (var i = 0; i < min; i++) { - matrix.set(i, i, data[i]); - } - return matrix; - } + for (let i = 0; i < vrows; i++) { + for (let j = 0; j < urows; j++) { + let sum = 0; - /** - * Returns a matrix whose elements are the minimum between matrix1 and matrix2 - * @param {Matrix} matrix1 - * @param {Matrix} matrix2 - * @return {Matrix} - */ - static min(matrix1, matrix2) { - matrix1 = this.checkMatrix(matrix1); - matrix2 = this.checkMatrix(matrix2); - var rows = matrix1.rows; - var columns = matrix1.columns; - var result = new this(rows, columns); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j))); + for (let k = 0; k < ucols; k++) { + sum += X[i][k] * U[j][k]; } - } - return result; - } - /** - * Returns a matrix whose elements are the maximum between matrix1 and matrix2 - * @param {Matrix} matrix1 - * @param {Matrix} matrix2 - * @return {Matrix} - */ - static max(matrix1, matrix2) { - matrix1 = this.checkMatrix(matrix1); - matrix2 = this.checkMatrix(matrix2); - var rows = matrix1.rows; - var columns = matrix1.columns; - var result = new this(rows, columns); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j))); - } + Y[i][j] = sum; } - return result; } - /** - * Check that the provided value is a Matrix and tries to instantiate one if not - * @param {*} value - The value to check - * @return {Matrix} - */ - static checkMatrix(value) { - return Matrix.isMatrix(value) ? value : new this(value); - } + return Y; + } + /** + * + * @return {number} + */ - /** - * Returns true if the argument is a Matrix, false otherwise - * @param {*} value - The value to check - * @return {boolean} - */ - static isMatrix(value) { - return value != null && value.klass === 'Matrix'; - } - /** - * @prop {number} size - The number of elements in the matrix. - */ - get size() { - return this.rows * this.columns; - } + get condition() { + return this.s[0] / this.s[Math.min(this.m, this.n) - 1]; + } + /** + * + * @return {number} + */ - /** - * Applies a callback for each element of the matrix. The function is called in the matrix (this) context. - * @param {function} callback - Function that will be called with two parameters : i (row) and j (column) - * @return {Matrix} this - */ - apply(callback) { - if (typeof callback !== 'function') { - throw new TypeError('callback must be a function'); - } - var ii = this.rows; - var jj = this.columns; - for (var i = 0; i < ii; i++) { - for (var j = 0; j < jj; j++) { - callback.call(this, i, j); - } - } - return this; - } - /** - * Returns a new 1D array filled row by row with the matrix values - * @return {Array} - */ - to1DArray() { - var array = new Array(this.size); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - array[i * this.columns + j] = this.get(i, j); - } - } - return array; - } + get norm2() { + return this.s[0]; + } + /** + * + * @return {number} + */ - /** - * Returns a 2D array containing a copy of the data - * @return {Array} - */ - to2DArray() { - var copy = new Array(this.rows); - for (var i = 0; i < this.rows; i++) { - copy[i] = new Array(this.columns); - for (var j = 0; j < this.columns; j++) { - copy[i][j] = this.get(i, j); - } + + get rank() { + var tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON; + var r = 0; + var s = this.s; + + for (var i = 0, ii = s.length; i < ii; i++) { + if (s[i] > tol) { + r++; } - return copy; } - /** - * @return {boolean} true if the matrix has one row - */ - isRowVector() { - return this.rows === 1; - } + return r; + } + /** + * + * @return {Array} + */ - /** - * @return {boolean} true if the matrix has one column - */ - isColumnVector() { - return this.columns === 1; - } - /** - * @return {boolean} true if the matrix has one row or one column - */ - isVector() { - return this.rows === 1 || this.columns === 1; - } + get diagonal() { + return this.s; + } + /** + * + * @return {number} + */ - /** - * @return {boolean} true if the matrix has the same number of rows and columns - */ - isSquare() { - return this.rows === this.columns; - } - /** - * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal - */ - isSymmetric() { - if (this.isSquare()) { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j <= i; j++) { - if (this.get(i, j) !== this.get(j, i)) { - return false; - } - } - } - return true; - } - return false; - } + get threshold() { + return Number.EPSILON / 2 * Math.max(this.m, this.n) * this.s[0]; + } + /** + * + * @return {Matrix} + */ - /** - * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1 - * @abstract - * @param {number} rowIndex - Index of the row - * @param {number} columnIndex - Index of the column - * @param {number} value - The new value for the element - * @return {Matrix} this - */ - set(rowIndex, columnIndex, value) { - // eslint-disable-line no-unused-vars - throw new Error('set method is unimplemented'); - } - /** - * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4] - * @abstract - * @param {number} rowIndex - Index of the row - * @param {number} columnIndex - Index of the column - * @return {number} - */ - get(rowIndex, columnIndex) { - // eslint-disable-line no-unused-vars - throw new Error('get method is unimplemented'); + get leftSingularVectors() { + if (!matrix_Matrix.isMatrix(this.U)) { + this.U = new matrix_Matrix(this.U); } - /** - * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of - * rows of the matrix, and colRep times the number of columns of the matrix - * @param {number} rowRep - Number of times the rows should be repeated - * @param {number} colRep - Number of times the columns should be re - * @return {Matrix} - * @example - * var matrix = new Matrix([[1,2]]); - * matrix.repeat(2); // [[1,2],[1,2]] - */ - repeat(rowRep, colRep) { - rowRep = rowRep || 1; - colRep = colRep || 1; - var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep); - for (var i = 0; i < rowRep; i++) { - for (var j = 0; j < colRep; j++) { - matrix.setSubMatrix(this, this.rows * i, this.columns * j); - } - } - return matrix; - } + return this.U; + } + /** + * + * @return {Matrix} + */ - /** - * Fills the matrix with a given value. All elements will be set to this value. - * @param {number} value - New value - * @return {Matrix} this - */ - fill(value) { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, value); - } - } - return this; - } - /** - * Negates the matrix. All elements will be multiplied by (-1) - * @return {Matrix} this - */ - neg() { - return this.mulS(-1); + get rightSingularVectors() { + if (!matrix_Matrix.isMatrix(this.V)) { + this.V = new matrix_Matrix(this.V); } - /** - * Returns a new array from the given row index - * @param {number} index - Row index - * @return {Array} - */ + return this.V; + } + /** + * + * @return {Matrix} + */ + + + get diagonalMatrix() { + return matrix_Matrix.diag(this.s); + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/util.js + +/** + * @private + * Check that a row index is not out of bounds + * @param {Matrix} matrix + * @param {number} index + * @param {boolean} [outer] + */ + +function checkRowIndex(matrix, index, outer) { + var max = outer ? matrix.rows : matrix.rows - 1; + + if (index < 0 || index > max) { + throw new RangeError('Row index out of range'); + } +} +/** + * @private + * Check that a column index is not out of bounds + * @param {Matrix} matrix + * @param {number} index + * @param {boolean} [outer] + */ + +function checkColumnIndex(matrix, index, outer) { + var max = outer ? matrix.columns : matrix.columns - 1; + + if (index < 0 || index > max) { + throw new RangeError('Column index out of range'); + } +} +/** + * @private + * Check that the provided vector is an array with the right length + * @param {Matrix} matrix + * @param {Array|Matrix} vector + * @return {Array} + * @throws {RangeError} + */ + +function checkRowVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); + } + + if (vector.length !== matrix.columns) { + throw new RangeError('vector size must be the same as the number of columns'); + } + + return vector; +} +/** + * @private + * Check that the provided vector is an array with the right length + * @param {Matrix} matrix + * @param {Array|Matrix} vector + * @return {Array} + * @throws {RangeError} + */ + +function checkColumnVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); + } + + if (vector.length !== matrix.rows) { + throw new RangeError('vector size must be the same as the number of rows'); + } + + return vector; +} +function checkIndices(matrix, rowIndices, columnIndices) { + return { + row: checkRowIndices(matrix, rowIndices), + column: checkColumnIndices(matrix, columnIndices) + }; +} +function checkRowIndices(matrix, rowIndices) { + if (typeof rowIndices !== 'object') { + throw new TypeError('unexpected type for row indices'); + } + + var rowOut = rowIndices.some(r => { + return r < 0 || r >= matrix.rows; + }); + + if (rowOut) { + throw new RangeError('row indices are out of range'); + } + + if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices); + return rowIndices; +} +function checkColumnIndices(matrix, columnIndices) { + if (typeof columnIndices !== 'object') { + throw new TypeError('unexpected type for column indices'); + } + + var columnOut = columnIndices.some(c => { + return c < 0 || c >= matrix.columns; + }); + + if (columnOut) { + throw new RangeError('column indices are out of range'); + } + + if (!Array.isArray(columnIndices)) columnIndices = Array.from(columnIndices); + return columnIndices; +} +function checkRange(matrix, startRow, endRow, startColumn, endColumn) { + if (arguments.length !== 5) { + throw new RangeError('expected 4 arguments'); + } + + checkNumber('startRow', startRow); + checkNumber('endRow', endRow); + checkNumber('startColumn', startColumn); + checkNumber('endColumn', endColumn); + + if (startRow > endRow || startColumn > endColumn || startRow < 0 || startRow >= matrix.rows || endRow < 0 || endRow >= matrix.rows || startColumn < 0 || startColumn >= matrix.columns || endColumn < 0 || endColumn >= matrix.columns) { + throw new RangeError('Submatrix indices are out of range'); + } +} +function getRange(from, to) { + var arr = new Array(to - from + 1); + + for (var i = 0; i < arr.length; i++) { + arr[i] = from + i; + } + + return arr; +} +function sumByRow(matrix) { + var sum = matrix_Matrix.zeros(matrix.rows, 1); + + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j)); + } + } + + return sum; +} +function sumByColumn(matrix) { + var sum = matrix_Matrix.zeros(1, matrix.columns); + + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum.set(0, j, sum.get(0, j) + matrix.get(i, j)); + } + } + + return sum; +} +function sumAll(matrix) { + var v = 0; + + for (var i = 0; i < matrix.rows; i++) { + for (var j = 0; j < matrix.columns; j++) { + v += matrix.get(i, j); + } + } + + return v; +} + +function checkNumber(name, value) { + if (typeof value !== 'number') { + throw new TypeError("".concat(name, " must be a number")); + } +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/views/base.js + + +class base_BaseView extends AbstractMatrix() { + constructor(matrix, rows, columns) { + super(); + this.matrix = matrix; + this.rows = rows; + this.columns = columns; + } + + static get [Symbol.species]() { + return matrix_Matrix; + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/views/transpose.js + +class transpose_MatrixTransposeView extends base_BaseView { + constructor(matrix) { + super(matrix, matrix.columns, matrix.rows); + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(columnIndex, rowIndex, value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(columnIndex, rowIndex); + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/views/row.js + +class row_MatrixRowView extends base_BaseView { + constructor(matrix, row) { + super(matrix, 1, matrix.columns); + this.row = row; + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(this.row, columnIndex, value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(this.row, columnIndex); + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/views/sub.js + + +class sub_MatrixSubView extends base_BaseView { + constructor(matrix, startRow, endRow, startColumn, endColumn) { + checkRange(matrix, startRow, endRow, startColumn, endColumn); + super(matrix, endRow - startRow + 1, endColumn - startColumn + 1); + this.startRow = startRow; + this.startColumn = startColumn; + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex, value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex); + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/views/selection.js + + +class selection_MatrixSelectionView extends base_BaseView { + constructor(matrix, rowIndices, columnIndices) { + var indices = checkIndices(matrix, rowIndices, columnIndices); + super(matrix, indices.row.length, indices.column.length); + this.rowIndices = indices.row; + this.columnIndices = indices.column; + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]); + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/views/rowSelection.js + + +class rowSelection_MatrixRowSelectionView extends base_BaseView { + constructor(matrix, rowIndices) { + rowIndices = checkRowIndices(matrix, rowIndices); + super(matrix, rowIndices.length, matrix.columns); + this.rowIndices = rowIndices; + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rowIndices[rowIndex], columnIndex, value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(this.rowIndices[rowIndex], columnIndex); + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/views/columnSelection.js + + +class columnSelection_MatrixColumnSelectionView extends base_BaseView { + constructor(matrix, columnIndices) { + columnIndices = checkColumnIndices(matrix, columnIndices); + super(matrix, matrix.rows, columnIndices.length); + this.columnIndices = columnIndices; + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.columnIndices[columnIndex], value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(rowIndex, this.columnIndices[columnIndex]); + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/views/column.js + +class column_MatrixColumnView extends base_BaseView { + constructor(matrix, column) { + super(matrix, matrix.rows, 1); + this.column = column; + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.column, value); + return this; + } + + get(rowIndex) { + return this.matrix.get(rowIndex, this.column); + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/views/flipRow.js + +class flipRow_MatrixFlipRowView extends base_BaseView { + constructor(matrix) { + super(matrix, matrix.rows, matrix.columns); + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rows - rowIndex - 1, columnIndex, value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(this.rows - rowIndex - 1, columnIndex); + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/views/flipColumn.js + +class flipColumn_MatrixFlipColumnView extends base_BaseView { + constructor(matrix) { + super(matrix, matrix.rows, matrix.columns); + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.columns - columnIndex - 1, value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(rowIndex, this.columns - columnIndex - 1); + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/abstractMatrix.js + + + + + + + + + + + + + +function AbstractMatrix(superCtor) { + if (superCtor === undefined) superCtor = Object; + /** + * Real matrix + * @class Matrix + * @param {number|Array|Matrix} nRows - Number of rows of the new matrix, + * 2D array containing the data or Matrix instance to clone + * @param {number} [nColumns] - Number of columns of the new matrix + */ + + class Matrix extends superCtor { + static get [Symbol.species]() { + return this; + } + /** + * Constructs a Matrix with the chosen dimensions from a 1D array + * @param {number} newRows - Number of rows + * @param {number} newColumns - Number of columns + * @param {Array} newData - A 1D array containing data for the matrix + * @return {Matrix} - The new matrix + */ + + + static from1DArray(newRows, newColumns, newData) { + var length = newRows * newColumns; + + if (length !== newData.length) { + throw new RangeError('Data length does not match given dimensions'); + } + + var newMatrix = new this(newRows, newColumns); + + for (var row = 0; row < newRows; row++) { + for (var column = 0; column < newColumns; column++) { + newMatrix.set(row, column, newData[row * newColumns + column]); + } + } + + return newMatrix; + } + /** + * Creates a row vector, a matrix with only one row. + * @param {Array} newData - A 1D array containing data for the vector + * @return {Matrix} - The new matrix + */ + + + static rowVector(newData) { + var vector = new this(1, newData.length); + + for (var i = 0; i < newData.length; i++) { + vector.set(0, i, newData[i]); + } + + return vector; + } + /** + * Creates a column vector, a matrix with only one column. + * @param {Array} newData - A 1D array containing data for the vector + * @return {Matrix} - The new matrix + */ + + + static columnVector(newData) { + var vector = new this(newData.length, 1); + + for (var i = 0; i < newData.length; i++) { + vector.set(i, 0, newData[i]); + } + + return vector; + } + /** + * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns). + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + + + static empty(rows, columns) { + return new this(rows, columns); + } + /** + * Creates a matrix with the given dimensions. Values will be set to zero. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + + + static zeros(rows, columns) { + return this.empty(rows, columns).fill(0); + } + /** + * Creates a matrix with the given dimensions. Values will be set to one. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + + + static ones(rows, columns) { + return this.empty(rows, columns).fill(1); + } + /** + * Creates a matrix with the given dimensions. Values will be randomly set. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @param {function} [rng=Math.random] - Random number generator + * @return {Matrix} The new matrix + */ + + + static rand(rows, columns, rng) { + if (rng === undefined) rng = Math.random; + var matrix = this.empty(rows, columns); + + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + matrix.set(i, j, rng()); + } + } + + return matrix; + } + /** + * Creates a matrix with the given dimensions. Values will be random integers. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @param {number} [maxValue=1000] - Maximum value + * @param {function} [rng=Math.random] - Random number generator + * @return {Matrix} The new matrix + */ + + + static randInt(rows, columns, maxValue, rng) { + if (maxValue === undefined) maxValue = 1000; + if (rng === undefined) rng = Math.random; + var matrix = this.empty(rows, columns); + + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + var value = Math.floor(rng() * maxValue); + matrix.set(i, j, value); + } + } + + return matrix; + } + /** + * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0. + * @param {number} rows - Number of rows + * @param {number} [columns=rows] - Number of columns + * @param {number} [value=1] - Value to fill the diagonal with + * @return {Matrix} - The new identity matrix + */ + + + static eye(rows, columns, value) { + if (columns === undefined) columns = rows; + if (value === undefined) value = 1; + var min = Math.min(rows, columns); + var matrix = this.zeros(rows, columns); + + for (var i = 0; i < min; i++) { + matrix.set(i, i, value); + } + + return matrix; + } + /** + * Creates a diagonal matrix based on the given array. + * @param {Array} data - Array containing the data for the diagonal + * @param {number} [rows] - Number of rows (Default: data.length) + * @param {number} [columns] - Number of columns (Default: rows) + * @return {Matrix} - The new diagonal matrix + */ + + + static diag(data, rows, columns) { + var l = data.length; + if (rows === undefined) rows = l; + if (columns === undefined) columns = rows; + var min = Math.min(l, rows, columns); + var matrix = this.zeros(rows, columns); + + for (var i = 0; i < min; i++) { + matrix.set(i, i, data[i]); + } + + return matrix; + } + /** + * Returns a matrix whose elements are the minimum between matrix1 and matrix2 + * @param {Matrix} matrix1 + * @param {Matrix} matrix2 + * @return {Matrix} + */ + + + static min(matrix1, matrix2) { + matrix1 = this.checkMatrix(matrix1); + matrix2 = this.checkMatrix(matrix2); + var rows = matrix1.rows; + var columns = matrix1.columns; + var result = new this(rows, columns); + + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j))); + } + } + + return result; + } + /** + * Returns a matrix whose elements are the maximum between matrix1 and matrix2 + * @param {Matrix} matrix1 + * @param {Matrix} matrix2 + * @return {Matrix} + */ + + + static max(matrix1, matrix2) { + matrix1 = this.checkMatrix(matrix1); + matrix2 = this.checkMatrix(matrix2); + var rows = matrix1.rows; + var columns = matrix1.columns; + var result = new this(rows, columns); + + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j))); + } + } + + return result; + } + /** + * Check that the provided value is a Matrix and tries to instantiate one if not + * @param {*} value - The value to check + * @return {Matrix} + */ + + + static checkMatrix(value) { + return Matrix.isMatrix(value) ? value : new this(value); + } + /** + * Returns true if the argument is a Matrix, false otherwise + * @param {*} value - The value to check + * @return {boolean} + */ + + + static isMatrix(value) { + return value != null && value.klass === 'Matrix'; + } + /** + * @prop {number} size - The number of elements in the matrix. + */ + + + get size() { + return this.rows * this.columns; + } + /** + * Applies a callback for each element of the matrix. The function is called in the matrix (this) context. + * @param {function} callback - Function that will be called with two parameters : i (row) and j (column) + * @return {Matrix} this + */ + + + apply(callback) { + if (typeof callback !== 'function') { + throw new TypeError('callback must be a function'); + } + + var ii = this.rows; + var jj = this.columns; + + for (var i = 0; i < ii; i++) { + for (var j = 0; j < jj; j++) { + callback.call(this, i, j); + } + } + + return this; + } + /** + * Returns a new 1D array filled row by row with the matrix values + * @return {Array} + */ + + + to1DArray() { + var array = new Array(this.size); + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + array[i * this.columns + j] = this.get(i, j); + } + } + + return array; + } + /** + * Returns a 2D array containing a copy of the data + * @return {Array} + */ + + + to2DArray() { + var copy = new Array(this.rows); + + for (var i = 0; i < this.rows; i++) { + copy[i] = new Array(this.columns); + + for (var j = 0; j < this.columns; j++) { + copy[i][j] = this.get(i, j); + } + } + + return copy; + } + /** + * @return {boolean} true if the matrix has one row + */ + + + isRowVector() { + return this.rows === 1; + } + /** + * @return {boolean} true if the matrix has one column + */ + + + isColumnVector() { + return this.columns === 1; + } + /** + * @return {boolean} true if the matrix has one row or one column + */ + + + isVector() { + return this.rows === 1 || this.columns === 1; + } + /** + * @return {boolean} true if the matrix has the same number of rows and columns + */ + + + isSquare() { + return this.rows === this.columns; + } + /** + * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal + */ + + + isSymmetric() { + if (this.isSquare()) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j <= i; j++) { + if (this.get(i, j) !== this.get(j, i)) { + return false; + } + } + } + + return true; + } + + return false; + } + /** + * @return true if the matrix is in echelon form + */ + + + isEchelonForm() { + let i = 0; + let j = 0; + let previousColumn = -1; + let isEchelonForm = true; + let checked = false; + + while (i < this.rows && isEchelonForm) { + j = 0; + checked = false; + + while (j < this.columns && checked === false) { + if (this.get(i, j) === 0) { + j++; + } else if (this.get(i, j) === 1 && j > previousColumn) { + checked = true; + previousColumn = j; + } else { + isEchelonForm = false; + checked = true; + } + } + + i++; + } + + return isEchelonForm; + } + /** + * @return true if the matrix is in reduced echelon form + */ + + + isReducedEchelonForm() { + let i = 0; + let j = 0; + let previousColumn = -1; + let isReducedEchelonForm = true; + let checked = false; + + while (i < this.rows && isReducedEchelonForm) { + j = 0; + checked = false; + + while (j < this.columns && checked === false) { + if (this.get(i, j) === 0) { + j++; + } else if (this.get(i, j) === 1 && j > previousColumn) { + checked = true; + previousColumn = j; + } else { + isReducedEchelonForm = false; + checked = true; + } + } + + for (let k = j + 1; k < this.rows; k++) { + if (this.get(i, k) !== 0) { + isReducedEchelonForm = false; + } + } + + i++; + } + + return isReducedEchelonForm; + } + /** + * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1 + * @abstract + * @param {number} rowIndex - Index of the row + * @param {number} columnIndex - Index of the column + * @param {number} value - The new value for the element + * @return {Matrix} this + */ + + + set(rowIndex, columnIndex, value) { + // eslint-disable-line no-unused-vars + throw new Error('set method is unimplemented'); + } + /** + * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4] + * @abstract + * @param {number} rowIndex - Index of the row + * @param {number} columnIndex - Index of the column + * @return {number} + */ + + + get(rowIndex, columnIndex) { + // eslint-disable-line no-unused-vars + throw new Error('get method is unimplemented'); + } + /** + * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of + * rows of the matrix, and colRep times the number of columns of the matrix + * @param {number} rowRep - Number of times the rows should be repeated + * @param {number} colRep - Number of times the columns should be re + * @return {Matrix} + * @example + * var matrix = new Matrix([[1,2]]); + * matrix.repeat(2); // [[1,2],[1,2]] + */ + + + repeat(rowRep, colRep) { + rowRep = rowRep || 1; + colRep = colRep || 1; + var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep); + + for (var i = 0; i < rowRep; i++) { + for (var j = 0; j < colRep; j++) { + matrix.setSubMatrix(this, this.rows * i, this.columns * j); + } + } + + return matrix; + } + /** + * Fills the matrix with a given value. All elements will be set to this value. + * @param {number} value - New value + * @return {Matrix} this + */ + + + fill(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, value); + } + } + + return this; + } + /** + * Negates the matrix. All elements will be multiplied by (-1) + * @return {Matrix} this + */ + + + neg() { + return this.mulS(-1); + } + /** + * Returns a new array from the given row index + * @param {number} index - Row index + * @return {Array} + */ + + getRow(index) { - (0, _util.checkRowIndex)(this, index); + checkRowIndex(this, index); var row = new Array(this.columns); + + for (var i = 0; i < this.columns; i++) { + row[i] = this.get(index, i); + } + + return row; + } + /** + * Returns a new row vector from the given row index + * @param {number} index - Row index + * @return {Matrix} + */ + + + getRowVector(index) { + return this.constructor.rowVector(this.getRow(index)); + } + /** + * Sets a row at the given index + * @param {number} index - Row index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + + + setRow(index, array) { + checkRowIndex(this, index); + array = checkRowVector(this, array); + + for (var i = 0; i < this.columns; i++) { + this.set(index, i, array[i]); + } + + return this; + } + /** + * Swaps two rows + * @param {number} row1 - First row index + * @param {number} row2 - Second row index + * @return {Matrix} this + */ + + + swapRows(row1, row2) { + checkRowIndex(this, row1); + checkRowIndex(this, row2); + + for (var i = 0; i < this.columns; i++) { + var temp = this.get(row1, i); + this.set(row1, i, this.get(row2, i)); + this.set(row2, i, temp); + } + + return this; + } + /** + * Returns a new array from the given column index + * @param {number} index - Column index + * @return {Array} + */ + + + getColumn(index) { + checkColumnIndex(this, index); + var column = new Array(this.rows); + + for (var i = 0; i < this.rows; i++) { + column[i] = this.get(i, index); + } + + return column; + } + /** + * Returns a new column vector from the given column index + * @param {number} index - Column index + * @return {Matrix} + */ + + + getColumnVector(index) { + return this.constructor.columnVector(this.getColumn(index)); + } + /** + * Sets a column at the given index + * @param {number} index - Column index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + + + setColumn(index, array) { + checkColumnIndex(this, index); + array = checkColumnVector(this, array); + + for (var i = 0; i < this.rows; i++) { + this.set(i, index, array[i]); + } + + return this; + } + /** + * Swaps two columns + * @param {number} column1 - First column index + * @param {number} column2 - Second column index + * @return {Matrix} this + */ + + + swapColumns(column1, column2) { + checkColumnIndex(this, column1); + checkColumnIndex(this, column2); + + for (var i = 0; i < this.rows; i++) { + var temp = this.get(i, column1); + this.set(i, column1, this.get(i, column2)); + this.set(i, column2, temp); + } + + return this; + } + /** + * Adds the values of a vector to each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + + + addRowVector(vector) { + vector = checkRowVector(this, vector); + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + vector[j]); + } + } + + return this; + } + /** + * Subtracts the values of a vector from each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + + + subRowVector(vector) { + vector = checkRowVector(this, vector); + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - vector[j]); + } + } + + return this; + } + /** + * Multiplies the values of a vector with each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + + + mulRowVector(vector) { + vector = checkRowVector(this, vector); + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * vector[j]); + } + } + + return this; + } + /** + * Divides the values of each row by those of a vector + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + + + divRowVector(vector) { + vector = checkRowVector(this, vector); + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) / vector[j]); + } + } + + return this; + } + /** + * Adds the values of a vector to each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + + + addColumnVector(vector) { + vector = checkColumnVector(this, vector); + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + vector[i]); + } + } + + return this; + } + /** + * Subtracts the values of a vector from each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + + + subColumnVector(vector) { + vector = checkColumnVector(this, vector); + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - vector[i]); + } + } + + return this; + } + /** + * Multiplies the values of a vector with each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + + + mulColumnVector(vector) { + vector = checkColumnVector(this, vector); + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * vector[i]); + } + } + + return this; + } + /** + * Divides the values of each column by those of a vector + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + + + divColumnVector(vector) { + vector = checkColumnVector(this, vector); + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) / vector[i]); + } + } + + return this; + } + /** + * Multiplies the values of a row with a scalar + * @param {number} index - Row index + * @param {number} value + * @return {Matrix} this + */ + + + mulRow(index, value) { + checkRowIndex(this, index); + + for (var i = 0; i < this.columns; i++) { + this.set(index, i, this.get(index, i) * value); + } + + return this; + } + /** + * Multiplies the values of a column with a scalar + * @param {number} index - Column index + * @param {number} value + * @return {Matrix} this + */ + + + mulColumn(index, value) { + checkColumnIndex(this, index); + + for (var i = 0; i < this.rows; i++) { + this.set(i, index, this.get(i, index) * value); + } + + return this; + } + /** + * Returns the maximum value of the matrix + * @return {number} + */ + + + max() { + var v = this.get(0, 0); + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) > v) { + v = this.get(i, j); + } + } + } + + return v; + } + /** + * Returns the index of the maximum value + * @return {Array} + */ + + + maxIndex() { + var v = this.get(0, 0); + var idx = [0, 0]; + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) > v) { + v = this.get(i, j); + idx[0] = i; + idx[1] = j; + } + } + } + + return idx; + } + /** + * Returns the minimum value of the matrix + * @return {number} + */ + + + min() { + var v = this.get(0, 0); + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) < v) { + v = this.get(i, j); + } + } + } + + return v; + } + /** + * Returns the index of the minimum value + * @return {Array} + */ + + + minIndex() { + var v = this.get(0, 0); + var idx = [0, 0]; + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) < v) { + v = this.get(i, j); + idx[0] = i; + idx[1] = j; + } + } + } + + return idx; + } + /** + * Returns the maximum value of one row + * @param {number} row - Row index + * @return {number} + */ + + + maxRow(row) { + checkRowIndex(this, row); + var v = this.get(row, 0); + + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) > v) { + v = this.get(row, i); + } + } + + return v; + } + /** + * Returns the index of the maximum value of one row + * @param {number} row - Row index + * @return {Array} + */ + + + maxRowIndex(row) { + checkRowIndex(this, row); + var v = this.get(row, 0); + var idx = [row, 0]; + + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) > v) { + v = this.get(row, i); + idx[1] = i; + } + } + + return idx; + } + /** + * Returns the minimum value of one row + * @param {number} row - Row index + * @return {number} + */ + + + minRow(row) { + checkRowIndex(this, row); + var v = this.get(row, 0); + + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) < v) { + v = this.get(row, i); + } + } + + return v; + } + /** + * Returns the index of the maximum value of one row + * @param {number} row - Row index + * @return {Array} + */ + + + minRowIndex(row) { + checkRowIndex(this, row); + var v = this.get(row, 0); + var idx = [row, 0]; + + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) < v) { + v = this.get(row, i); + idx[1] = i; + } + } + + return idx; + } + /** + * Returns the maximum value of one column + * @param {number} column - Column index + * @return {number} + */ + + + maxColumn(column) { + checkColumnIndex(this, column); + var v = this.get(0, column); + + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) > v) { + v = this.get(i, column); + } + } + + return v; + } + /** + * Returns the index of the maximum value of one column + * @param {number} column - Column index + * @return {Array} + */ + + + maxColumnIndex(column) { + checkColumnIndex(this, column); + var v = this.get(0, column); + var idx = [0, column]; + + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) > v) { + v = this.get(i, column); + idx[0] = i; + } + } + + return idx; + } + /** + * Returns the minimum value of one column + * @param {number} column - Column index + * @return {number} + */ + + + minColumn(column) { + checkColumnIndex(this, column); + var v = this.get(0, column); + + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) < v) { + v = this.get(i, column); + } + } + + return v; + } + /** + * Returns the index of the minimum value of one column + * @param {number} column - Column index + * @return {Array} + */ + + + minColumnIndex(column) { + checkColumnIndex(this, column); + var v = this.get(0, column); + var idx = [0, column]; + + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) < v) { + v = this.get(i, column); + idx[0] = i; + } + } + + return idx; + } + /** + * Returns an array containing the diagonal values of the matrix + * @return {Array} + */ + + + diag() { + var min = Math.min(this.rows, this.columns); + var diag = new Array(min); + + for (var i = 0; i < min; i++) { + diag[i] = this.get(i, i); + } + + return diag; + } + /** + * Returns the sum by the argument given, if no argument given, + * it returns the sum of all elements of the matrix. + * @param {string} by - sum by 'row' or 'column'. + * @return {Matrix|number} + */ + + + sum(by) { + switch (by) { + case 'row': + return sumByRow(this); + + case 'column': + return sumByColumn(this); + + default: + return sumAll(this); + } + } + /** + * Returns the mean of all elements of the matrix + * @return {number} + */ + + + mean() { + return this.sum() / this.size; + } + /** + * Returns the product of all elements of the matrix + * @return {number} + */ + + + prod() { + var prod = 1; + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + prod *= this.get(i, j); + } + } + + return prod; + } + /** + * Returns the norm of a matrix. + * @param {string} type - "frobenius" (default) or "max" return resp. the Frobenius norm and the max norm. + * @return {number} + */ + + + norm() { + let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'frobenius'; + var result = 0; + + if (type === 'max') { + return this.max(); + } else if (type === 'frobenius') { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + result = result + this.get(i, j) * this.get(i, j); + } + } + + return Math.sqrt(result); + } else { + throw new RangeError("unknown norm type: ".concat(type)); + } + } + /** + * Computes the cumulative sum of the matrix elements (in place, row by row) + * @return {Matrix} this + */ + + + cumulativeSum() { + var sum = 0; + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + sum += this.get(i, j); + this.set(i, j, sum); + } + } + + return this; + } + /** + * Computes the dot (scalar) product between the matrix and another + * @param {Matrix} vector2 vector + * @return {number} + */ + + + dot(vector2) { + if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray(); + var vector1 = this.to1DArray(); + + if (vector1.length !== vector2.length) { + throw new RangeError('vectors do not have the same size'); + } + + var dot = 0; + + for (var i = 0; i < vector1.length; i++) { + dot += vector1[i] * vector2[i]; + } + + return dot; + } + /** + * Returns the matrix product between this and other + * @param {Matrix} other + * @return {Matrix} + */ + + + mmul(other) { + other = this.constructor.checkMatrix(other); + + if (this.columns !== other.rows) { + // eslint-disable-next-line no-console + console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.'); + } + + var m = this.rows; + var n = this.columns; + var p = other.columns; + var result = new this.constructor[Symbol.species](m, p); + var Bcolj = new Array(n); + + for (var j = 0; j < p; j++) { + for (var k = 0; k < n; k++) { + Bcolj[k] = other.get(k, j); + } + + for (var i = 0; i < m; i++) { + var s = 0; + + for (k = 0; k < n; k++) { + s += this.get(i, k) * Bcolj[k]; + } + + result.set(i, j, s); + } + } + + return result; + } + + strassen2x2(other) { + var result = new this.constructor[Symbol.species](2, 2); + const a11 = this.get(0, 0); + const b11 = other.get(0, 0); + const a12 = this.get(0, 1); + const b12 = other.get(0, 1); + const a21 = this.get(1, 0); + const b21 = other.get(1, 0); + const a22 = this.get(1, 1); + const b22 = other.get(1, 1); // Compute intermediate values. + + const m1 = (a11 + a22) * (b11 + b22); + const m2 = (a21 + a22) * b11; + const m3 = a11 * (b12 - b22); + const m4 = a22 * (b21 - b11); + const m5 = (a11 + a12) * b22; + const m6 = (a21 - a11) * (b11 + b12); + const m7 = (a12 - a22) * (b21 + b22); // Combine intermediate values into the output. + + const c00 = m1 + m4 - m5 + m7; + const c01 = m3 + m5; + const c10 = m2 + m4; + const c11 = m1 - m2 + m3 + m6; + result.set(0, 0, c00); + result.set(0, 1, c01); + result.set(1, 0, c10); + result.set(1, 1, c11); + return result; + } + + strassen3x3(other) { + var result = new this.constructor[Symbol.species](3, 3); + const a00 = this.get(0, 0); + const a01 = this.get(0, 1); + const a02 = this.get(0, 2); + const a10 = this.get(1, 0); + const a11 = this.get(1, 1); + const a12 = this.get(1, 2); + const a20 = this.get(2, 0); + const a21 = this.get(2, 1); + const a22 = this.get(2, 2); + const b00 = other.get(0, 0); + const b01 = other.get(0, 1); + const b02 = other.get(0, 2); + const b10 = other.get(1, 0); + const b11 = other.get(1, 1); + const b12 = other.get(1, 2); + const b20 = other.get(2, 0); + const b21 = other.get(2, 1); + const b22 = other.get(2, 2); + const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11; + const m2 = (a00 - a10) * (-b01 + b11); + const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22); + const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11); + const m5 = (a10 + a11) * (-b00 + b01); + const m6 = a00 * b00; + const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12); + const m8 = (-a00 + a20) * (b02 - b12); + const m9 = (a20 + a21) * (-b00 + b02); + const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12; + const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21); + const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21); + const m13 = (a02 - a22) * (b11 - b21); + const m14 = a02 * b20; + const m15 = (a21 + a22) * (-b20 + b21); + const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22); + const m17 = (a02 - a12) * (b12 - b22); + const m18 = (a11 + a12) * (-b20 + b22); + const m19 = a01 * b10; + const m20 = a12 * b21; + const m21 = a10 * b02; + const m22 = a20 * b01; + const m23 = a22 * b22; + const c00 = m6 + m14 + m19; + const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15; + const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18; + const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17; + const c11 = m2 + m4 + m5 + m6 + m20; + const c12 = m14 + m16 + m17 + m18 + m21; + const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14; + const c21 = m12 + m13 + m14 + m15 + m22; + const c22 = m6 + m7 + m8 + m9 + m23; + result.set(0, 0, c00); + result.set(0, 1, c01); + result.set(0, 2, c02); + result.set(1, 0, c10); + result.set(1, 1, c11); + result.set(1, 2, c12); + result.set(2, 0, c20); + result.set(2, 1, c21); + result.set(2, 2, c22); + return result; + } + /** + * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000. + * @param {Matrix} y + * @return {Matrix} + */ + + + mmulStrassen(y) { + var x = this.clone(); + var r1 = x.rows; + var c1 = x.columns; + var r2 = y.rows; + var c2 = y.columns; + + if (c1 !== r2) { + // eslint-disable-next-line no-console + console.warn("Multiplying ".concat(r1, " x ").concat(c1, " and ").concat(r2, " x ").concat(c2, " matrix: dimensions do not match.")); + } // Put a matrix into the top left of a matrix of zeros. + // `rows` and `cols` are the dimensions of the output matrix. + + + function embed(mat, rows, cols) { + var r = mat.rows; + var c = mat.columns; + + if (r === rows && c === cols) { + return mat; + } else { + var resultat = Matrix.zeros(rows, cols); + resultat = resultat.setSubMatrix(mat, 0, 0); + return resultat; + } + } // Make sure both matrices are the same size. + // This is exclusively for simplicity: + // this algorithm can be implemented with matrices of different sizes. + + + var r = Math.max(r1, r2); + var c = Math.max(c1, c2); + x = embed(x, r, c); + y = embed(y, r, c); // Our recursive multiplication function. + + function blockMult(a, b, rows, cols) { + // For small matrices, resort to naive multiplication. + if (rows <= 512 || cols <= 512) { + return a.mmul(b); // a is equivalent to this + } // Apply dynamic padding. + + + if (rows % 2 === 1 && cols % 2 === 1) { + a = embed(a, rows + 1, cols + 1); + b = embed(b, rows + 1, cols + 1); + } else if (rows % 2 === 1) { + a = embed(a, rows + 1, cols); + b = embed(b, rows + 1, cols); + } else if (cols % 2 === 1) { + a = embed(a, rows, cols + 1); + b = embed(b, rows, cols + 1); + } + + var halfRows = parseInt(a.rows / 2, 10); + var halfCols = parseInt(a.columns / 2, 10); // Subdivide input matrices. + + var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1); + var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1); + var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1); + var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1); + var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1); + var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1); + var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1); + var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1); // Compute intermediate values. + + var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols); + var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols); + var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols); + var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols); + var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols); + var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols); + var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols); // Combine intermediate values into the output. + + var c11 = Matrix.add(m1, m4); + c11.sub(m5); + c11.add(m7); + var c12 = Matrix.add(m3, m5); + var c21 = Matrix.add(m2, m4); + var c22 = Matrix.sub(m1, m2); + c22.add(m3); + c22.add(m6); // Crop output to the desired size (undo dynamic padding). + + var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns); + resultat = resultat.setSubMatrix(c11, 0, 0); + resultat = resultat.setSubMatrix(c12, c11.rows, 0); + resultat = resultat.setSubMatrix(c21, 0, c11.columns); + resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns); + return resultat.subMatrix(0, rows - 1, 0, cols - 1); + } + + return blockMult(x, y, r, c); + } + /** + * Returns a row-by-row scaled matrix + * @param {number} [min=0] - Minimum scaled value + * @param {number} [max=1] - Maximum scaled value + * @return {Matrix} - The scaled matrix + */ + + + scaleRows(min, max) { + min = min === undefined ? 0 : min; + max = max === undefined ? 1 : max; + + if (min >= max) { + throw new RangeError('min should be strictly smaller than max'); + } + + var newMatrix = this.constructor.empty(this.rows, this.columns); + + for (var i = 0; i < this.rows; i++) { + var scaled = Object(lib_es6["default"])(this.getRow(i), { + min, + max + }); + newMatrix.setRow(i, scaled); + } + + return newMatrix; + } + /** + * Returns a new column-by-column scaled matrix + * @param {number} [min=0] - Minimum scaled value + * @param {number} [max=1] - Maximum scaled value + * @return {Matrix} - The new scaled matrix + * @example + * var matrix = new Matrix([[1,2],[-1,0]]); + * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]] + */ + + + scaleColumns(min, max) { + min = min === undefined ? 0 : min; + max = max === undefined ? 1 : max; + + if (min >= max) { + throw new RangeError('min should be strictly smaller than max'); + } + + var newMatrix = this.constructor.empty(this.rows, this.columns); + for (var i = 0; i < this.columns; i++) { - row[i] = this.get(index, i); + var scaled = Object(lib_es6["default"])(this.getColumn(i), { + min: min, + max: max + }); + newMatrix.setColumn(i, scaled); + } + + return newMatrix; + } + /** + * Returns the Kronecker product (also known as tensor product) between this and other + * See https://en.wikipedia.org/wiki/Kronecker_product + * @param {Matrix} other + * @return {Matrix} + */ + + + kroneckerProduct(other) { + other = this.constructor.checkMatrix(other); + var m = this.rows; + var n = this.columns; + var p = other.rows; + var q = other.columns; + var result = new this.constructor[Symbol.species](m * p, n * q); + + for (var i = 0; i < m; i++) { + for (var j = 0; j < n; j++) { + for (var k = 0; k < p; k++) { + for (var l = 0; l < q; l++) { + result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l); + } + } + } + } + + return result; + } + /** + * Transposes the matrix and returns a new one containing the result + * @return {Matrix} + */ + + + transpose() { + var result = new this.constructor[Symbol.species](this.columns, this.rows); + + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + result.set(j, i, this.get(i, j)); + } + } + + return result; + } + /** + * Sorts the rows (in place) + * @param {function} compareFunction - usual Array.prototype.sort comparison function + * @return {Matrix} this + */ + + + sortRows(compareFunction) { + if (compareFunction === undefined) compareFunction = compareNumbers; + + for (var i = 0; i < this.rows; i++) { + this.setRow(i, this.getRow(i).sort(compareFunction)); + } + + return this; + } + /** + * Sorts the columns (in place) + * @param {function} compareFunction - usual Array.prototype.sort comparison function + * @return {Matrix} this + */ + + + sortColumns(compareFunction) { + if (compareFunction === undefined) compareFunction = compareNumbers; + + for (var i = 0; i < this.columns; i++) { + this.setColumn(i, this.getColumn(i).sort(compareFunction)); + } + + return this; + } + /** + * Returns a subset of the matrix + * @param {number} startRow - First row index + * @param {number} endRow - Last row index + * @param {number} startColumn - First column index + * @param {number} endColumn - Last column index + * @return {Matrix} + */ + + + subMatrix(startRow, endRow, startColumn, endColumn) { + checkRange(this, startRow, endRow, startColumn, endColumn); + var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1); + + for (var i = startRow; i <= endRow; i++) { + for (var j = startColumn; j <= endColumn; j++) { + newMatrix[i - startRow][j - startColumn] = this.get(i, j); + } + } + + return newMatrix; + } + /** + * Returns a subset of the matrix based on an array of row indices + * @param {Array} indices - Array containing the row indices + * @param {number} [startColumn = 0] - First column index + * @param {number} [endColumn = this.columns-1] - Last column index + * @return {Matrix} + */ + + + subMatrixRow(indices, startColumn, endColumn) { + if (startColumn === undefined) startColumn = 0; + if (endColumn === undefined) endColumn = this.columns - 1; + + if (startColumn > endColumn || startColumn < 0 || startColumn >= this.columns || endColumn < 0 || endColumn >= this.columns) { + throw new RangeError('Argument out of range'); + } + + var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1); + + for (var i = 0; i < indices.length; i++) { + for (var j = startColumn; j <= endColumn; j++) { + if (indices[i] < 0 || indices[i] >= this.rows) { + throw new RangeError("Row index out of range: ".concat(indices[i])); + } + + newMatrix.set(i, j - startColumn, this.get(indices[i], j)); + } + } + + return newMatrix; + } + /** + * Returns a subset of the matrix based on an array of column indices + * @param {Array} indices - Array containing the column indices + * @param {number} [startRow = 0] - First row index + * @param {number} [endRow = this.rows-1] - Last row index + * @return {Matrix} + */ + + + subMatrixColumn(indices, startRow, endRow) { + if (startRow === undefined) startRow = 0; + if (endRow === undefined) endRow = this.rows - 1; + + if (startRow > endRow || startRow < 0 || startRow >= this.rows || endRow < 0 || endRow >= this.rows) { + throw new RangeError('Argument out of range'); + } + + var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length); + + for (var i = 0; i < indices.length; i++) { + for (var j = startRow; j <= endRow; j++) { + if (indices[i] < 0 || indices[i] >= this.columns) { + throw new RangeError("Column index out of range: ".concat(indices[i])); + } + + newMatrix.set(j - startRow, i, this.get(j, indices[i])); + } + } + + return newMatrix; + } + /** + * Set a part of the matrix to the given sub-matrix + * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values. + * @param {number} startRow - The index of the first row to set + * @param {number} startColumn - The index of the first column to set + * @return {Matrix} + */ + + + setSubMatrix(matrix, startRow, startColumn) { + matrix = this.constructor.checkMatrix(matrix); + var endRow = startRow + matrix.rows - 1; + var endColumn = startColumn + matrix.columns - 1; + checkRange(this, startRow, endRow, startColumn, endColumn); + + for (var i = 0; i < matrix.rows; i++) { + for (var j = 0; j < matrix.columns; j++) { + this[startRow + i][startColumn + j] = matrix.get(i, j); + } + } + + return this; + } + /** + * Return a new matrix based on a selection of rows and columns + * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once. + * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once. + * @return {Matrix} The new matrix + */ + + + selection(rowIndices, columnIndices) { + var indices = checkIndices(this, rowIndices, columnIndices); + var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length); + + for (var i = 0; i < indices.row.length; i++) { + var rowIndex = indices.row[i]; + + for (var j = 0; j < indices.column.length; j++) { + var columnIndex = indices.column[j]; + newMatrix[i][j] = this.get(rowIndex, columnIndex); + } + } + + return newMatrix; + } + /** + * Returns the trace of the matrix (sum of the diagonal elements) + * @return {number} + */ + + + trace() { + var min = Math.min(this.rows, this.columns); + var trace = 0; + + for (var i = 0; i < min; i++) { + trace += this.get(i, i); + } + + return trace; + } + /* + Matrix views + */ + + /** + * Returns a view of the transposition of the matrix + * @return {MatrixTransposeView} + */ + + + transposeView() { + return new transpose_MatrixTransposeView(this); + } + /** + * Returns a view of the row vector with the given index + * @param {number} row - row index of the vector + * @return {MatrixRowView} + */ + + + rowView(row) { + checkRowIndex(this, row); + return new row_MatrixRowView(this, row); + } + /** + * Returns a view of the column vector with the given index + * @param {number} column - column index of the vector + * @return {MatrixColumnView} + */ + + + columnView(column) { + checkColumnIndex(this, column); + return new column_MatrixColumnView(this, column); + } + /** + * Returns a view of the matrix flipped in the row axis + * @return {MatrixFlipRowView} + */ + + + flipRowView() { + return new flipRow_MatrixFlipRowView(this); + } + /** + * Returns a view of the matrix flipped in the column axis + * @return {MatrixFlipColumnView} + */ + + + flipColumnView() { + return new flipColumn_MatrixFlipColumnView(this); + } + /** + * Returns a view of a submatrix giving the index boundaries + * @param {number} startRow - first row index of the submatrix + * @param {number} endRow - last row index of the submatrix + * @param {number} startColumn - first column index of the submatrix + * @param {number} endColumn - last column index of the submatrix + * @return {MatrixSubView} + */ + + + subMatrixView(startRow, endRow, startColumn, endColumn) { + return new sub_MatrixSubView(this, startRow, endRow, startColumn, endColumn); + } + /** + * Returns a view of the cross of the row indices and the column indices + * @example + * // resulting vector is [[2], [2]] + * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1]) + * @param {Array} rowIndices + * @param {Array} columnIndices + * @return {MatrixSelectionView} + */ + + + selectionView(rowIndices, columnIndices) { + return new selection_MatrixSelectionView(this, rowIndices, columnIndices); + } + /** + * Returns a view of the row indices + * @example + * // resulting vector is [[1,2,3], [1,2,3]] + * var matrix = new Matrix([[1,2,3], [4,5,6]]).rowSelectionView([0, 0]) + * @param {Array} rowIndices + * @return {MatrixRowSelectionView} + */ + + + rowSelectionView(rowIndices) { + return new rowSelection_MatrixRowSelectionView(this, rowIndices); + } + /** + * Returns a view of the column indices + * @example + * // resulting vector is [[2, 2], [5, 5]] + * var matrix = new Matrix([[1,2,3], [4,5,6]]).columnSelectionView([1, 1]) + * @param {Array} columnIndices + * @return {MatrixColumnSelectionView} + */ + + + columnSelectionView(columnIndices) { + return new columnSelection_MatrixColumnSelectionView(this, columnIndices); + } + /** + * Calculates and returns the determinant of a matrix as a Number + * @example + * new Matrix([[1,2,3], [4,5,6]]).det() + * @return {number} + */ + + + det() { + if (this.isSquare()) { + var a, b, c, d; + + if (this.columns === 2) { + // 2 x 2 matrix + a = this.get(0, 0); + b = this.get(0, 1); + c = this.get(1, 0); + d = this.get(1, 1); + return a * d - b * c; + } else if (this.columns === 3) { + // 3 x 3 matrix + var subMatrix0, subMatrix1, subMatrix2; + subMatrix0 = this.selectionView([1, 2], [1, 2]); + subMatrix1 = this.selectionView([1, 2], [0, 2]); + subMatrix2 = this.selectionView([1, 2], [0, 1]); + a = this.get(0, 0); + b = this.get(0, 1); + c = this.get(0, 2); + return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det(); + } else { + // general purpose determinant using the LU decomposition + return new lu_LuDecomposition(this).determinant; + } + } else { + throw Error('Determinant can only be calculated for a square matrix.'); + } + } + /** + * Returns inverse of a matrix if it exists or the pseudoinverse + * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15) + * @return {Matrix} the (pseudo)inverted matrix. + */ + + + pseudoInverse(threshold) { + if (threshold === undefined) threshold = Number.EPSILON; + var svdSolution = new svd_SingularValueDecomposition(this, { + autoTranspose: true + }); + var U = svdSolution.leftSingularVectors; + var V = svdSolution.rightSingularVectors; + var s = svdSolution.diagonal; + + for (var i = 0; i < s.length; i++) { + if (Math.abs(s[i]) > threshold) { + s[i] = 1.0 / s[i]; + } else { + s[i] = 0.0; + } + } // convert list to diagonal + + + s = this.constructor[Symbol.species].diag(s); + return V.mmul(s.mmul(U.transposeView())); + } + /** + * Creates an exact and independent copy of the matrix + * @return {Matrix} + */ + + + clone() { + var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns); + + for (var row = 0; row < this.rows; row++) { + for (var column = 0; column < this.columns; column++) { + newMatrix.set(row, column, this.get(row, column)); + } + } + + return newMatrix; + } + + } + + Matrix.prototype.klass = 'Matrix'; + + function compareNumbers(a, b) { + return a - b; + } + /* + Synonyms + */ + + + Matrix.random = Matrix.rand; + Matrix.diagonal = Matrix.diag; + Matrix.prototype.diagonal = Matrix.prototype.diag; + Matrix.identity = Matrix.eye; + Matrix.prototype.negate = Matrix.prototype.neg; + Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct; + Matrix.prototype.determinant = Matrix.prototype.det; + /* + Add dynamically instance and static methods for mathematical operations + */ + + var inplaceOperator = "\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n"; + var inplaceOperatorScalar = "\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% value);\n }\n }\n return this;\n})\n"; + var inplaceOperatorMatrix = "\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% matrix.get(i, j));\n }\n }\n return this;\n})\n"; + var staticOperator = "\n(function %name%(matrix, value) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(value);\n})\n"; + var inplaceMethod = "\n(function %name%() {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j)));\n }\n }\n return this;\n})\n"; + var staticMethod = "\n(function %name%(matrix) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%();\n})\n"; + var inplaceMethodWithArgs = "\n(function %name%(%args%) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), %args%));\n }\n }\n return this;\n})\n"; + var staticMethodWithArgs = "\n(function %name%(matrix, %args%) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(%args%);\n})\n"; + var inplaceMethodWithOneArgScalar = "\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), value));\n }\n }\n return this;\n})\n"; + var inplaceMethodWithOneArgMatrix = "\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), matrix.get(i, j)));\n }\n }\n return this;\n})\n"; + var inplaceMethodWithOneArg = "\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n"; + var staticMethodWithOneArg = staticMethodWithArgs; + var operators = [// Arithmetic operators + ['+', 'add'], ['-', 'sub', 'subtract'], ['*', 'mul', 'multiply'], ['/', 'div', 'divide'], ['%', 'mod', 'modulus'], // Bitwise operators + ['&', 'and'], ['|', 'or'], ['^', 'xor'], ['<<', 'leftShift'], ['>>', 'signPropagatingRightShift'], ['>>>', 'rightShift', 'zeroFillRightShift']]; + var i; + var eval2 = eval; // eslint-disable-line no-eval + + for (var operator of operators) { + var inplaceOp = eval2(fillTemplateFunction(inplaceOperator, { + name: operator[1], + op: operator[0] + })); + var inplaceOpS = eval2(fillTemplateFunction(inplaceOperatorScalar, { + name: "".concat(operator[1], "S"), + op: operator[0] + })); + var inplaceOpM = eval2(fillTemplateFunction(inplaceOperatorMatrix, { + name: "".concat(operator[1], "M"), + op: operator[0] + })); + var staticOp = eval2(fillTemplateFunction(staticOperator, { + name: operator[1] + })); + + for (i = 1; i < operator.length; i++) { + Matrix.prototype[operator[i]] = inplaceOp; + Matrix.prototype["".concat(operator[i], "S")] = inplaceOpS; + Matrix.prototype["".concat(operator[i], "M")] = inplaceOpM; + Matrix[operator[i]] = staticOp; + } + } + + var methods = [['~', 'not']]; + ['abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil', 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p', 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'].forEach(function (mathMethod) { + methods.push(["Math.".concat(mathMethod), mathMethod]); + }); + + for (var method of methods) { + var inplaceMeth = eval2(fillTemplateFunction(inplaceMethod, { + name: method[1], + method: method[0] + })); + var staticMeth = eval2(fillTemplateFunction(staticMethod, { + name: method[1] + })); + + for (i = 1; i < method.length; i++) { + Matrix.prototype[method[i]] = inplaceMeth; + Matrix[method[i]] = staticMeth; + } + } + + var methodsWithArgs = [['Math.pow', 1, 'pow']]; + + for (var methodWithArg of methodsWithArgs) { + var args = 'arg0'; + + for (i = 1; i < methodWithArg[1]; i++) { + args += ", arg".concat(i); + } + + if (methodWithArg[1] !== 1) { + var inplaceMethWithArgs = eval2(fillTemplateFunction(inplaceMethodWithArgs, { + name: methodWithArg[2], + method: methodWithArg[0], + args: args + })); + var staticMethWithArgs = eval2(fillTemplateFunction(staticMethodWithArgs, { + name: methodWithArg[2], + args: args + })); + + for (i = 2; i < methodWithArg.length; i++) { + Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs; + Matrix[methodWithArg[i]] = staticMethWithArgs; + } + } else { + var tmplVar = { + name: methodWithArg[2], + args: args, + method: methodWithArg[0] + }; + var inplaceMethod2 = eval2(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar)); + var inplaceMethodS = eval2(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar)); + var inplaceMethodM = eval2(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar)); + var staticMethod2 = eval2(fillTemplateFunction(staticMethodWithOneArg, tmplVar)); + + for (i = 2; i < methodWithArg.length; i++) { + Matrix.prototype[methodWithArg[i]] = inplaceMethod2; + Matrix.prototype["".concat(methodWithArg[i], "M")] = inplaceMethodM; + Matrix.prototype["".concat(methodWithArg[i], "S")] = inplaceMethodS; + Matrix[methodWithArg[i]] = staticMethod2; + } + } + } + + function fillTemplateFunction(template, values) { + for (var value in values) { + template = template.replace(new RegExp("%".concat(value, "%"), 'g'), values[value]); + } + + return template; + } + + return Matrix; +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/matrix.js + + +class matrix_Matrix extends AbstractMatrix(Array) { + constructor(nRows, nColumns) { + var i; + + if (arguments.length === 1 && typeof nRows === 'number') { + return new Array(nRows); + } + + if (matrix_Matrix.isMatrix(nRows)) { + return nRows.clone(); + } else if (Number.isInteger(nRows) && nRows > 0) { + // Create an empty matrix + super(nRows); + + if (Number.isInteger(nColumns) && nColumns > 0) { + for (i = 0; i < nRows; i++) { + this[i] = new Array(nColumns); + } + } else { + throw new TypeError('nColumns must be a positive integer'); + } + } else if (Array.isArray(nRows)) { + // Copy the values from the 2D array + const matrix = nRows; + nRows = matrix.length; + nColumns = matrix[0].length; + + if (typeof nColumns !== 'number' || nColumns === 0) { + throw new TypeError('Data must be a 2D array with at least one element'); + } + + super(nRows); + + for (i = 0; i < nRows; i++) { + if (matrix[i].length !== nColumns) { + throw new RangeError('Inconsistent array dimensions'); + } + + this[i] = [].concat(matrix[i]); + } + } else { + throw new TypeError('First argument must be a positive number or an array'); + } + + this.rows = nRows; + this.columns = nColumns; + return this; + } + + set(rowIndex, columnIndex, value) { + this[rowIndex][columnIndex] = value; + return this; + } + + get(rowIndex, columnIndex) { + return this[rowIndex][columnIndex]; + } + /** + * Removes a row from the given index + * @param {number} index - Row index + * @return {Matrix} this + */ + + + removeRow(index) { + checkRowIndex(this, index); + + if (this.rows === 1) { + throw new RangeError('A matrix cannot have less than one row'); + } + + this.splice(index, 1); + this.rows -= 1; + return this; + } + /** + * Adds a row at the given index + * @param {number} [index = this.rows] - Row index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + + + addRow(index, array) { + if (array === undefined) { + array = index; + index = this.rows; + } + + checkRowIndex(this, index, true); + array = checkRowVector(this, array, true); + this.splice(index, 0, array); + this.rows += 1; + return this; + } + /** + * Removes a column from the given index + * @param {number} index - Column index + * @return {Matrix} this + */ + + + removeColumn(index) { + checkColumnIndex(this, index); + + if (this.columns === 1) { + throw new RangeError('A matrix cannot have less than one column'); + } + + for (var i = 0; i < this.rows; i++) { + this[i].splice(index, 1); + } + + this.columns -= 1; + return this; + } + /** + * Adds a column at the given index + * @param {number} [index = this.columns] - Column index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + + + addColumn(index, array) { + if (typeof array === 'undefined') { + array = index; + index = this.columns; + } + + checkColumnIndex(this, index, true); + array = checkColumnVector(this, array); + + for (var i = 0; i < this.rows; i++) { + this[i].splice(index, 0, array[i]); + } + + this.columns += 1; + return this; + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/wrap/WrapperMatrix1D.js + + +class WrapperMatrix1D_WrapperMatrix1D extends AbstractMatrix() { + /** + * @class WrapperMatrix1D + * @param {Array} data + * @param {object} [options] + * @param {object} [options.rows = 1] + */ + constructor(data) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const { + rows = 1 + } = options; + + if (data.length % rows !== 0) { + throw new Error('the data length is not divisible by the number of rows'); + } + + super(); + this.rows = rows; + this.columns = data.length / rows; + this.data = data; + } + + set(rowIndex, columnIndex, value) { + var index = this._calculateIndex(rowIndex, columnIndex); + + this.data[index] = value; + return this; + } + + get(rowIndex, columnIndex) { + var index = this._calculateIndex(rowIndex, columnIndex); + + return this.data[index]; + } + + _calculateIndex(row, column) { + return row * this.columns + column; + } + + static get [Symbol.species]() { + return matrix_Matrix; + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/wrap/WrapperMatrix2D.js + + +class WrapperMatrix2D_WrapperMatrix2D extends AbstractMatrix() { + /** + * @class WrapperMatrix2D + * @param {Array>} data + */ + constructor(data) { + super(); + this.data = data; + this.rows = data.length; + this.columns = data[0].length; + } + + set(rowIndex, columnIndex, value) { + this.data[rowIndex][columnIndex] = value; + return this; + } + + get(rowIndex, columnIndex) { + return this.data[rowIndex][columnIndex]; + } + + static get [Symbol.species]() { + return matrix_Matrix; + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/wrap/wrap.js + + +/** + * @param {Array>|Array} array + * @param {object} [options] + * @param {object} [options.rows = 1] + * @return {WrapperMatrix1D|WrapperMatrix2D} + */ + +function wrap(array, options) { + if (Array.isArray(array)) { + if (array[0] && Array.isArray(array[0])) { + return new WrapperMatrix2D_WrapperMatrix2D(array); + } else { + return new WrapperMatrix1D_WrapperMatrix1D(array, options); + } + } else { + throw new Error('the argument is not an array'); + } +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/dc/qr.js + + +/** + * @class QrDecomposition + * @link https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs + * @param {Matrix} value + */ + +class qr_QrDecomposition { + constructor(value) { + value = WrapperMatrix2D_WrapperMatrix2D.checkMatrix(value); + var qr = value.clone(); + var m = value.rows; + var n = value.columns; + var rdiag = new Array(n); + var i, j, k, s; + + for (k = 0; k < n; k++) { + var nrm = 0; + + for (i = k; i < m; i++) { + nrm = hypotenuse(nrm, qr.get(i, k)); + } + + if (nrm !== 0) { + if (qr.get(k, k) < 0) { + nrm = -nrm; + } + + for (i = k; i < m; i++) { + qr.set(i, k, qr.get(i, k) / nrm); + } + + qr.set(k, k, qr.get(k, k) + 1); + + for (j = k + 1; j < n; j++) { + s = 0; + + for (i = k; i < m; i++) { + s += qr.get(i, k) * qr.get(i, j); + } + + s = -s / qr.get(k, k); + + for (i = k; i < m; i++) { + qr.set(i, j, qr.get(i, j) + s * qr.get(i, k)); + } + } + } + + rdiag[k] = -nrm; + } + + this.QR = qr; + this.Rdiag = rdiag; + } + /** + * Solve a problem of least square (Ax=b) by using the QR decomposition. Useful when A is rectangular, but not working when A is singular. + * Example : We search to approximate x, with A matrix shape m*n, x vector size n, b vector size m (m > n). We will use : + * var qr = QrDecomposition(A); + * var x = qr.solve(b); + * @param {Matrix} value - Matrix 1D which is the vector b (in the equation Ax = b) + * @return {Matrix} - The vector x + */ + + + solve(value) { + value = matrix_Matrix.checkMatrix(value); + var qr = this.QR; + var m = qr.rows; + + if (value.rows !== m) { + throw new Error('Matrix row dimensions must agree'); + } + + if (!this.isFullRank()) { + throw new Error('Matrix is rank deficient'); + } + + var count = value.columns; + var X = value.clone(); + var n = qr.columns; + var i, j, k, s; + + for (k = 0; k < n; k++) { + for (j = 0; j < count; j++) { + s = 0; + + for (i = k; i < m; i++) { + s += qr[i][k] * X[i][j]; + } + + s = -s / qr[k][k]; + + for (i = k; i < m; i++) { + X[i][j] += s * qr[i][k]; + } + } + } + + for (k = n - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + X[k][j] /= this.Rdiag[k]; + } + + for (i = 0; i < k; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * qr[i][k]; + } + } + } + + return X.subMatrix(0, n - 1, 0, count - 1); + } + /** + * + * @return {boolean} + */ + + + isFullRank() { + var columns = this.QR.columns; + + for (var i = 0; i < columns; i++) { + if (this.Rdiag[i] === 0) { + return false; + } + } + + return true; + } + /** + * + * @return {Matrix} + */ + + + get upperTriangularMatrix() { + var qr = this.QR; + var n = qr.columns; + var X = new matrix_Matrix(n, n); + var i, j; + + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + if (i < j) { + X[i][j] = qr[i][j]; + } else if (i === j) { + X[i][j] = this.Rdiag[i]; + } else { + X[i][j] = 0; + } + } + } + + return X; + } + /** + * + * @return {Matrix} + */ + + + get orthogonalMatrix() { + var qr = this.QR; + var rows = qr.rows; + var columns = qr.columns; + var X = new matrix_Matrix(rows, columns); + var i, j, k, s; + + for (k = columns - 1; k >= 0; k--) { + for (i = 0; i < rows; i++) { + X[i][k] = 0; + } + + X[k][k] = 1; + + for (j = k; j < columns; j++) { + if (qr[k][k] !== 0) { + s = 0; + + for (i = k; i < rows; i++) { + s += qr[i][k] * X[i][j]; + } + + s = -s / qr[k][k]; + + for (i = k; i < rows; i++) { + X[i][j] += s * qr[i][k]; + } + } + } + } + + return X; + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/decompositions.js + + + + +/** + * Computes the inverse of a Matrix + * @param {Matrix} matrix + * @param {boolean} [useSVD=false] + * @return {Matrix} + */ + +function inverse(matrix) { + let useSVD = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + matrix = WrapperMatrix2D_WrapperMatrix2D.checkMatrix(matrix); + + if (useSVD) { + return new svd_SingularValueDecomposition(matrix).inverse(); + } else { + return solve(matrix, matrix_Matrix.eye(matrix.rows)); + } +} +/** + * + * @param {Matrix} leftHandSide + * @param {Matrix} rightHandSide + * @param {boolean} [useSVD = false] + * @return {Matrix} + */ + +function solve(leftHandSide, rightHandSide) { + let useSVD = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + leftHandSide = WrapperMatrix2D_WrapperMatrix2D.checkMatrix(leftHandSide); + rightHandSide = WrapperMatrix2D_WrapperMatrix2D.checkMatrix(rightHandSide); + + if (useSVD) { + return new svd_SingularValueDecomposition(leftHandSide).solve(rightHandSide); + } else { + return leftHandSide.isSquare() ? new lu_LuDecomposition(leftHandSide).solve(rightHandSide) : new qr_QrDecomposition(leftHandSide).solve(rightHandSide); + } +} +// EXTERNAL MODULE: ./node_modules/ml-array-max/lib-es6/index.js +var ml_array_max_lib_es6 = __webpack_require__(9); + +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/linearDependencies.js + + + // function used by rowsDependencies + +function xrange(n, exception) { + var range = []; + + for (var i = 0; i < n; i++) { + if (i !== exception) { + range.push(i); + } + } + + return range; +} // function used by rowsDependencies + + +function dependenciesOneRow(error, matrix, index) { + let thresholdValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 10e-10; + let thresholdError = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 10e-10; + + if (error > thresholdError) { + return new Array(matrix.rows + 1).fill(0); + } else { + var returnArray = matrix.addRow(index, [0]); + + for (var i = 0; i < returnArray.rows; i++) { + if (Math.abs(returnArray.get(i, 0)) < thresholdValue) { + returnArray.set(i, 0, 0); + } + } + + return returnArray.to1DArray(); + } +} +/** + * Creates a matrix which represents the dependencies between rows. + * If a row is a linear combination of others rows, the result will be a row with the coefficients of this combination. + * For example : for A = [[2, 0, 0, 1], [0, 1, 6, 0], [0, 3, 0, 1], [0, 0, 1, 0], [0, 1, 2, 0]], the result will be [[0, 0, 0, 0, 0], [0, 0, 0, 4, 1], [0, 0, 0, 0, 0], [0, 0.25, 0, 0, -0.25], [0, 1, 0, -4, 0]] + * @param {Matrix} matrix + * @param {Object} [options] includes thresholdValue and thresholdError. + * @param {number} [options.thresholdValue = 10e-10] If an absolute value is inferior to this threshold, it will equals zero. + * @param {number} [options.thresholdError = 10e-10] If the error is inferior to that threshold, the linear combination found is accepted and the row is dependent from other rows. + * @return {Matrix} the matrix which represents the dependencies between rows. + */ + + +function linearDependencies(matrix) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const { + thresholdValue = 10e-10, + thresholdError = 10e-10 + } = options; + var n = matrix.rows; + var results = new matrix_Matrix(n, n); + + for (var i = 0; i < n; i++) { + var b = matrix_Matrix.columnVector(matrix.getRow(i)); + var Abis = matrix.subMatrixRow(xrange(n, i)).transposeView(); + var svd = new svd_SingularValueDecomposition(Abis); + var x = svd.solve(b); + var error = Object(ml_array_max_lib_es6["default"])(matrix_Matrix.sub(b, Abis.mmul(x)).abs().to1DArray()); + results.setRow(i, dependenciesOneRow(error, x, i, thresholdValue, thresholdError)); + } + + return results; +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/dc/evd.js + + +/** + * @class EigenvalueDecomposition + * @link https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs + * @param {Matrix} matrix + * @param {object} [options] + * @param {boolean} [options.assumeSymmetric=false] + */ + +class evd_EigenvalueDecomposition { + constructor(matrix) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const { + assumeSymmetric = false + } = options; + matrix = WrapperMatrix2D_WrapperMatrix2D.checkMatrix(matrix); + + if (!matrix.isSquare()) { + throw new Error('Matrix is not a square matrix'); + } + + var n = matrix.columns; + var V = getFilled2DArray(n, n, 0); + var d = new Array(n); + var e = new Array(n); + var value = matrix; + var i, j; + var isSymmetric = false; + + if (assumeSymmetric) { + isSymmetric = true; + } else { + isSymmetric = matrix.isSymmetric(); + } + + if (isSymmetric) { + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V[i][j] = value.get(i, j); + } + } + + tred2(n, e, d, V); + tql2(n, e, d, V); + } else { + var H = getFilled2DArray(n, n, 0); + var ort = new Array(n); + + for (j = 0; j < n; j++) { + for (i = 0; i < n; i++) { + H[i][j] = value.get(i, j); + } + } + + orthes(n, H, ort, V); + hqr2(n, e, d, V, H); + } + + this.n = n; + this.e = e; + this.d = d; + this.V = V; + } + /** + * + * @return {Array} + */ + + + get realEigenvalues() { + return this.d; + } + /** + * + * @return {Array} + */ + + + get imaginaryEigenvalues() { + return this.e; + } + /** + * + * @return {Matrix} + */ + + + get eigenvectorMatrix() { + if (!matrix_Matrix.isMatrix(this.V)) { + this.V = new matrix_Matrix(this.V); + } + + return this.V; + } + /** + * + * @return {Matrix} + */ + + + get diagonalMatrix() { + var n = this.n; + var e = this.e; + var d = this.d; + var X = new matrix_Matrix(n, n); + var i, j; + + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + X[i][j] = 0; + } + + X[i][i] = d[i]; + + if (e[i] > 0) { + X[i][i + 1] = e[i]; + } else if (e[i] < 0) { + X[i][i - 1] = e[i]; + } + } + + return X; + } + +} + +function tred2(n, e, d, V) { + var f, g, h, i, j, k, hh, scale; + + for (j = 0; j < n; j++) { + d[j] = V[n - 1][j]; + } + + for (i = n - 1; i > 0; i--) { + scale = 0; + h = 0; + + for (k = 0; k < i; k++) { + scale = scale + Math.abs(d[k]); + } + + if (scale === 0) { + e[i] = d[i - 1]; + + for (j = 0; j < i; j++) { + d[j] = V[i - 1][j]; + V[i][j] = 0; + V[j][i] = 0; + } + } else { + for (k = 0; k < i; k++) { + d[k] /= scale; + h += d[k] * d[k]; + } + + f = d[i - 1]; + g = Math.sqrt(h); + + if (f > 0) { + g = -g; + } + + e[i] = scale * g; + h = h - f * g; + d[i - 1] = f - g; + + for (j = 0; j < i; j++) { + e[j] = 0; + } + + for (j = 0; j < i; j++) { + f = d[j]; + V[j][i] = f; + g = e[j] + V[j][j] * f; + + for (k = j + 1; k <= i - 1; k++) { + g += V[k][j] * d[k]; + e[k] += V[k][j] * f; + } + + e[j] = g; + } + + f = 0; + + for (j = 0; j < i; j++) { + e[j] /= h; + f += e[j] * d[j]; + } + + hh = f / (h + h); + + for (j = 0; j < i; j++) { + e[j] -= hh * d[j]; + } + + for (j = 0; j < i; j++) { + f = d[j]; + g = e[j]; + + for (k = j; k <= i - 1; k++) { + V[k][j] -= f * e[k] + g * d[k]; + } + + d[j] = V[i - 1][j]; + V[i][j] = 0; + } + } + + d[i] = h; + } + + for (i = 0; i < n - 1; i++) { + V[n - 1][i] = V[i][i]; + V[i][i] = 1; + h = d[i + 1]; + + if (h !== 0) { + for (k = 0; k <= i; k++) { + d[k] = V[k][i + 1] / h; + } + + for (j = 0; j <= i; j++) { + g = 0; + + for (k = 0; k <= i; k++) { + g += V[k][i + 1] * V[k][j]; + } + + for (k = 0; k <= i; k++) { + V[k][j] -= g * d[k]; + } + } + } + + for (k = 0; k <= i; k++) { + V[k][i + 1] = 0; + } + } + + for (j = 0; j < n; j++) { + d[j] = V[n - 1][j]; + V[n - 1][j] = 0; + } + + V[n - 1][n - 1] = 1; + e[0] = 0; +} + +function tql2(n, e, d, V) { + var g, h, i, j, k, l, m, p, r, dl1, c, c2, c3, el1, s, s2, iter; + + for (i = 1; i < n; i++) { + e[i - 1] = e[i]; + } + + e[n - 1] = 0; + var f = 0; + var tst1 = 0; + var eps = Number.EPSILON; + + for (l = 0; l < n; l++) { + tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l])); + m = l; + + while (m < n) { + if (Math.abs(e[m]) <= eps * tst1) { + break; + } + + m++; + } + + if (m > l) { + iter = 0; + + do { + iter = iter + 1; + g = d[l]; + p = (d[l + 1] - g) / (2 * e[l]); + r = hypotenuse(p, 1); + + if (p < 0) { + r = -r; + } + + d[l] = e[l] / (p + r); + d[l + 1] = e[l] * (p + r); + dl1 = d[l + 1]; + h = g - d[l]; + + for (i = l + 2; i < n; i++) { + d[i] -= h; + } + + f = f + h; + p = d[m]; + c = 1; + c2 = c; + c3 = c; + el1 = e[l + 1]; + s = 0; + s2 = 0; + + for (i = m - 1; i >= l; i--) { + c3 = c2; + c2 = c; + s2 = s; + g = c * e[i]; + h = c * p; + r = hypotenuse(p, e[i]); + e[i + 1] = s * r; + s = e[i] / r; + c = p / r; + p = c * d[i] - s * g; + d[i + 1] = h + s * (c * g + s * d[i]); + + for (k = 0; k < n; k++) { + h = V[k][i + 1]; + V[k][i + 1] = s * V[k][i] + c * h; + V[k][i] = c * V[k][i] - s * h; + } + } + + p = -s * s2 * c3 * el1 * e[l] / dl1; + e[l] = s * p; + d[l] = c * p; + } while (Math.abs(e[l]) > eps * tst1); + } + + d[l] = d[l] + f; + e[l] = 0; + } + + for (i = 0; i < n - 1; i++) { + k = i; + p = d[i]; + + for (j = i + 1; j < n; j++) { + if (d[j] < p) { + k = j; + p = d[j]; + } + } + + if (k !== i) { + d[k] = d[i]; + d[i] = p; + + for (j = 0; j < n; j++) { + p = V[j][i]; + V[j][i] = V[j][k]; + V[j][k] = p; + } + } + } +} + +function orthes(n, H, ort, V) { + var low = 0; + var high = n - 1; + var f, g, h, i, j, m; + var scale; + + for (m = low + 1; m <= high - 1; m++) { + scale = 0; + + for (i = m; i <= high; i++) { + scale = scale + Math.abs(H[i][m - 1]); + } + + if (scale !== 0) { + h = 0; + + for (i = high; i >= m; i--) { + ort[i] = H[i][m - 1] / scale; + h += ort[i] * ort[i]; + } + + g = Math.sqrt(h); + + if (ort[m] > 0) { + g = -g; + } + + h = h - ort[m] * g; + ort[m] = ort[m] - g; + + for (j = m; j < n; j++) { + f = 0; + + for (i = high; i >= m; i--) { + f += ort[i] * H[i][j]; + } + + f = f / h; + + for (i = m; i <= high; i++) { + H[i][j] -= f * ort[i]; + } + } + + for (i = 0; i <= high; i++) { + f = 0; + + for (j = high; j >= m; j--) { + f += ort[j] * H[i][j]; + } + + f = f / h; + + for (j = m; j <= high; j++) { + H[i][j] -= f * ort[j]; + } + } + + ort[m] = scale * ort[m]; + H[m][m - 1] = scale * g; + } + } + + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V[i][j] = i === j ? 1 : 0; + } + } + + for (m = high - 1; m >= low + 1; m--) { + if (H[m][m - 1] !== 0) { + for (i = m + 1; i <= high; i++) { + ort[i] = H[i][m - 1]; + } + + for (j = m; j <= high; j++) { + g = 0; + + for (i = m; i <= high; i++) { + g += ort[i] * V[i][j]; + } + + g = g / ort[m] / H[m][m - 1]; + + for (i = m; i <= high; i++) { + V[i][j] += g * ort[i]; + } + } + } + } +} + +function hqr2(nn, e, d, V, H) { + var n = nn - 1; + var low = 0; + var high = nn - 1; + var eps = Number.EPSILON; + var exshift = 0; + var norm = 0; + var p = 0; + var q = 0; + var r = 0; + var s = 0; + var z = 0; + var iter = 0; + var i, j, k, l, m, t, w, x, y; + var ra, sa, vr, vi; + var notlast, cdivres; + + for (i = 0; i < nn; i++) { + if (i < low || i > high) { + d[i] = H[i][i]; + e[i] = 0; + } + + for (j = Math.max(i - 1, 0); j < nn; j++) { + norm = norm + Math.abs(H[i][j]); + } + } + + while (n >= low) { + l = n; + + while (l > low) { + s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]); + + if (s === 0) { + s = norm; + } + + if (Math.abs(H[l][l - 1]) < eps * s) { + break; + } + + l--; + } + + if (l === n) { + H[n][n] = H[n][n] + exshift; + d[n] = H[n][n]; + e[n] = 0; + n--; + iter = 0; + } else if (l === n - 1) { + w = H[n][n - 1] * H[n - 1][n]; + p = (H[n - 1][n - 1] - H[n][n]) / 2; + q = p * p + w; + z = Math.sqrt(Math.abs(q)); + H[n][n] = H[n][n] + exshift; + H[n - 1][n - 1] = H[n - 1][n - 1] + exshift; + x = H[n][n]; + + if (q >= 0) { + z = p >= 0 ? p + z : p - z; + d[n - 1] = x + z; + d[n] = d[n - 1]; + + if (z !== 0) { + d[n] = x - w / z; + } + + e[n - 1] = 0; + e[n] = 0; + x = H[n][n - 1]; + s = Math.abs(x) + Math.abs(z); + p = x / s; + q = z / s; + r = Math.sqrt(p * p + q * q); + p = p / r; + q = q / r; + + for (j = n - 1; j < nn; j++) { + z = H[n - 1][j]; + H[n - 1][j] = q * z + p * H[n][j]; + H[n][j] = q * H[n][j] - p * z; + } + + for (i = 0; i <= n; i++) { + z = H[i][n - 1]; + H[i][n - 1] = q * z + p * H[i][n]; + H[i][n] = q * H[i][n] - p * z; + } + + for (i = low; i <= high; i++) { + z = V[i][n - 1]; + V[i][n - 1] = q * z + p * V[i][n]; + V[i][n] = q * V[i][n] - p * z; + } + } else { + d[n - 1] = x + p; + d[n] = x + p; + e[n - 1] = z; + e[n] = -z; + } + + n = n - 2; + iter = 0; + } else { + x = H[n][n]; + y = 0; + w = 0; + + if (l < n) { + y = H[n - 1][n - 1]; + w = H[n][n - 1] * H[n - 1][n]; + } + + if (iter === 10) { + exshift += x; + + for (i = low; i <= n; i++) { + H[i][i] -= x; + } + + s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]); + x = y = 0.75 * s; + w = -0.4375 * s * s; + } + + if (iter === 30) { + s = (y - x) / 2; + s = s * s + w; + + if (s > 0) { + s = Math.sqrt(s); + + if (y < x) { + s = -s; + } + + s = x - w / ((y - x) / 2 + s); + + for (i = low; i <= n; i++) { + H[i][i] -= s; + } + + exshift += s; + x = y = w = 0.964; + } + } + + iter = iter + 1; + m = n - 2; + + while (m >= l) { + z = H[m][m]; + r = x - z; + s = y - z; + p = (r * s - w) / H[m + 1][m] + H[m][m + 1]; + q = H[m + 1][m + 1] - z - r - s; + r = H[m + 2][m + 1]; + s = Math.abs(p) + Math.abs(q) + Math.abs(r); + p = p / s; + q = q / s; + r = r / s; + + if (m === l) { + break; + } + + if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) { + break; + } + + m--; + } + + for (i = m + 2; i <= n; i++) { + H[i][i - 2] = 0; + + if (i > m + 2) { + H[i][i - 3] = 0; + } + } + + for (k = m; k <= n - 1; k++) { + notlast = k !== n - 1; + + if (k !== m) { + p = H[k][k - 1]; + q = H[k + 1][k - 1]; + r = notlast ? H[k + 2][k - 1] : 0; + x = Math.abs(p) + Math.abs(q) + Math.abs(r); + + if (x !== 0) { + p = p / x; + q = q / x; + r = r / x; + } + } + + if (x === 0) { + break; + } + + s = Math.sqrt(p * p + q * q + r * r); + + if (p < 0) { + s = -s; + } + + if (s !== 0) { + if (k !== m) { + H[k][k - 1] = -s * x; + } else if (l !== m) { + H[k][k - 1] = -H[k][k - 1]; + } + + p = p + s; + x = p / s; + y = q / s; + z = r / s; + q = q / p; + r = r / p; + + for (j = k; j < nn; j++) { + p = H[k][j] + q * H[k + 1][j]; + + if (notlast) { + p = p + r * H[k + 2][j]; + H[k + 2][j] = H[k + 2][j] - p * z; + } + + H[k][j] = H[k][j] - p * x; + H[k + 1][j] = H[k + 1][j] - p * y; + } + + for (i = 0; i <= Math.min(n, k + 3); i++) { + p = x * H[i][k] + y * H[i][k + 1]; + + if (notlast) { + p = p + z * H[i][k + 2]; + H[i][k + 2] = H[i][k + 2] - p * r; + } + + H[i][k] = H[i][k] - p; + H[i][k + 1] = H[i][k + 1] - p * q; + } + + for (i = low; i <= high; i++) { + p = x * V[i][k] + y * V[i][k + 1]; + + if (notlast) { + p = p + z * V[i][k + 2]; + V[i][k + 2] = V[i][k + 2] - p * r; + } + + V[i][k] = V[i][k] - p; + V[i][k + 1] = V[i][k + 1] - p * q; + } + } } - return row; } + } - /** - * Returns a new row vector from the given row index - * @param {number} index - Row index - * @return {Matrix} - */ - getRowVector(index) { - return this.constructor.rowVector(this.getRow(index)); + if (norm === 0) { + return; + } + + for (n = nn - 1; n >= 0; n--) { + p = d[n]; + q = e[n]; + + if (q === 0) { + l = n; + H[n][n] = 1; + + for (i = n - 1; i >= 0; i--) { + w = H[i][i] - p; + r = 0; + + for (j = l; j <= n; j++) { + r = r + H[i][j] * H[j][n]; + } + + if (e[i] < 0) { + z = w; + s = r; + } else { + l = i; + + if (e[i] === 0) { + H[i][n] = w !== 0 ? -r / w : -r / (eps * norm); + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; + t = (x * s - z * r) / q; + H[i][n] = t; + H[i + 1][n] = Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z; + } + + t = Math.abs(H[i][n]); + + if (eps * t * t > 1) { + for (j = i; j <= n; j++) { + H[j][n] = H[j][n] / t; + } + } + } + } + } else if (q < 0) { + l = n - 1; + + if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) { + H[n - 1][n - 1] = q / H[n][n - 1]; + H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1]; + } else { + cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q); + H[n - 1][n - 1] = cdivres[0]; + H[n - 1][n] = cdivres[1]; + } + + H[n][n - 1] = 0; + H[n][n] = 1; + + for (i = n - 2; i >= 0; i--) { + ra = 0; + sa = 0; + + for (j = l; j <= n; j++) { + ra = ra + H[i][j] * H[j][n - 1]; + sa = sa + H[i][j] * H[j][n]; + } + + w = H[i][i] - p; + + if (e[i] < 0) { + z = w; + r = ra; + s = sa; + } else { + l = i; + + if (e[i] === 0) { + cdivres = cdiv(-ra, -sa, w, q); + H[i][n - 1] = cdivres[0]; + H[i][n] = cdivres[1]; + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; + vi = (d[i] - p) * 2 * q; + + if (vr === 0 && vi === 0) { + vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z)); + } + + cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); + H[i][n - 1] = cdivres[0]; + H[i][n] = cdivres[1]; + + if (Math.abs(x) > Math.abs(z) + Math.abs(q)) { + H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x; + H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x; + } else { + cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q); + H[i + 1][n - 1] = cdivres[0]; + H[i + 1][n] = cdivres[1]; + } + } + + t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n])); + + if (eps * t * t > 1) { + for (j = i; j <= n; j++) { + H[j][n - 1] = H[j][n - 1] / t; + H[j][n] = H[j][n] / t; + } + } + } + } } + } - /** - * Sets a row at the given index - * @param {number} index - Row index - * @param {Array|Matrix} array - Array or vector - * @return {Matrix} this - */ - setRow(index, array) { - (0, _util.checkRowIndex)(this, index); - array = (0, _util.checkRowVector)(this, array); - for (var i = 0; i < this.columns; i++) { - this.set(index, i, array[i]); + for (i = 0; i < nn; i++) { + if (i < low || i > high) { + for (j = i; j < nn; j++) { + V[i][j] = H[i][j]; } - return this; } + } - /** - * Swaps two rows - * @param {number} row1 - First row index - * @param {number} row2 - Second row index - * @return {Matrix} this - */ - swapRows(row1, row2) { - (0, _util.checkRowIndex)(this, row1); - (0, _util.checkRowIndex)(this, row2); - for (var i = 0; i < this.columns; i++) { - var temp = this.get(row1, i); - this.set(row1, i, this.get(row2, i)); - this.set(row2, i, temp); + for (j = nn - 1; j >= low; j--) { + for (i = low; i <= high; i++) { + z = 0; + + for (k = low; k <= Math.min(j, high); k++) { + z = z + V[i][k] * H[k][j]; + } + + V[i][j] = z; + } + } +} + +function cdiv(xr, xi, yr, yi) { + var r, d; + + if (Math.abs(yr) > Math.abs(yi)) { + r = yi / yr; + d = yr + r * yi; + return [(xr + r * xi) / d, (xi - r * xr) / d]; + } else { + r = yr / yi; + d = yi + r * yr; + return [(r * xr + xi) / d, (r * xi - xr) / d]; + } +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/dc/cholesky.js + +/** + * @class CholeskyDecomposition + * @link https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs + * @param {Matrix} value + */ + +class cholesky_CholeskyDecomposition { + constructor(value) { + value = WrapperMatrix2D_WrapperMatrix2D.checkMatrix(value); + + if (!value.isSymmetric()) { + throw new Error('Matrix is not symmetric'); + } + + var a = value; + var dimension = a.rows; + var l = new matrix_Matrix(dimension, dimension); + var positiveDefinite = true; + var i, j, k; + + for (j = 0; j < dimension; j++) { + var Lrowj = l[j]; + var d = 0; + + for (k = 0; k < j; k++) { + var Lrowk = l[k]; + var s = 0; + + for (i = 0; i < k; i++) { + s += Lrowk[i] * Lrowj[i]; + } + + Lrowj[k] = s = (a.get(j, k) - s) / l[k][k]; + d = d + s * s; } - return this; - } - /** - * Returns a new array from the given column index - * @param {number} index - Column index - * @return {Array} - */ - getColumn(index) { - (0, _util.checkColumnIndex)(this, index); - var column = new Array(this.rows); - for (var i = 0; i < this.rows; i++) { - column[i] = this.get(i, index); + d = a.get(j, j) - d; + positiveDefinite &= d > 0; + l[j][j] = Math.sqrt(Math.max(d, 0)); + + for (k = j + 1; k < dimension; k++) { + l[j][k] = 0; } - return column; } - /** - * Returns a new column vector from the given column index - * @param {number} index - Column index - * @return {Matrix} - */ - getColumnVector(index) { - return this.constructor.columnVector(this.getColumn(index)); + if (!positiveDefinite) { + throw new Error('Matrix is not positive definite'); } - /** - * Sets a column at the given index - * @param {number} index - Column index - * @param {Array|Matrix} array - Array or vector - * @return {Matrix} this - */ - setColumn(index, array) { - (0, _util.checkColumnIndex)(this, index); - array = (0, _util.checkColumnVector)(this, array); - for (var i = 0; i < this.rows; i++) { - this.set(i, index, array[i]); - } - return this; - } + this.L = l; + } + /** + * + * @param {Matrix} value + * @return {Matrix} + */ - /** - * Swaps two columns - * @param {number} column1 - First column index - * @param {number} column2 - Second column index - * @return {Matrix} this - */ - swapColumns(column1, column2) { - (0, _util.checkColumnIndex)(this, column1); - (0, _util.checkColumnIndex)(this, column2); - for (var i = 0; i < this.rows; i++) { - var temp = this.get(i, column1); - this.set(i, column1, this.get(i, column2)); - this.set(i, column2, temp); - } - return this; + + solve(value) { + value = WrapperMatrix2D_WrapperMatrix2D.checkMatrix(value); + var l = this.L; + var dimension = l.rows; + + if (value.rows !== dimension) { + throw new Error('Matrix dimensions do not match'); } - /** - * Adds the values of a vector to each row - * @param {Array|Matrix} vector - Array or vector - * @return {Matrix} this - */ - addRowVector(vector) { - vector = (0, _util.checkRowVector)(this, vector); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) + vector[j]); + var count = value.columns; + var B = value.clone(); + var i, j, k; + + for (k = 0; k < dimension; k++) { + for (j = 0; j < count; j++) { + for (i = 0; i < k; i++) { + B[k][j] -= B[i][j] * l[k][i]; } + + B[k][j] /= l[k][k]; } - return this; } - /** - * Subtracts the values of a vector from each row - * @param {Array|Matrix} vector - Array or vector - * @return {Matrix} this - */ - subRowVector(vector) { - vector = (0, _util.checkRowVector)(this, vector); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) - vector[j]); + for (k = dimension - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + for (i = k + 1; i < dimension; i++) { + B[k][j] -= B[i][j] * l[i][k]; } + + B[k][j] /= l[k][k]; } - return this; } - /** - * Multiplies the values of a vector with each row - * @param {Array|Matrix} vector - Array or vector - * @return {Matrix} this - */ - mulRowVector(vector) { - vector = (0, _util.checkRowVector)(this, vector); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) * vector[j]); - } - } - return this; + return B; + } + /** + * + * @return {Matrix} + */ + + + get lowerTriangularMatrix() { + return this.L; + } + +} +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/index.js +/* concated harmony reexport default */__webpack_require__.d(__webpack_exports__, "default", function() { return matrix_Matrix; }); +/* concated harmony reexport Matrix */__webpack_require__.d(__webpack_exports__, "Matrix", function() { return matrix_Matrix; }); +/* concated harmony reexport abstractMatrix */__webpack_require__.d(__webpack_exports__, "abstractMatrix", function() { return AbstractMatrix; }); +/* concated harmony reexport wrap */__webpack_require__.d(__webpack_exports__, "wrap", function() { return wrap; }); +/* concated harmony reexport WrapperMatrix2D */__webpack_require__.d(__webpack_exports__, "WrapperMatrix2D", function() { return WrapperMatrix2D_WrapperMatrix2D; }); +/* concated harmony reexport WrapperMatrix1D */__webpack_require__.d(__webpack_exports__, "WrapperMatrix1D", function() { return WrapperMatrix1D_WrapperMatrix1D; }); +/* concated harmony reexport solve */__webpack_require__.d(__webpack_exports__, "solve", function() { return solve; }); +/* concated harmony reexport inverse */__webpack_require__.d(__webpack_exports__, "inverse", function() { return inverse; }); +/* concated harmony reexport linearDependencies */__webpack_require__.d(__webpack_exports__, "linearDependencies", function() { return linearDependencies; }); +/* concated harmony reexport SingularValueDecomposition */__webpack_require__.d(__webpack_exports__, "SingularValueDecomposition", function() { return svd_SingularValueDecomposition; }); +/* concated harmony reexport SVD */__webpack_require__.d(__webpack_exports__, "SVD", function() { return svd_SingularValueDecomposition; }); +/* concated harmony reexport EigenvalueDecomposition */__webpack_require__.d(__webpack_exports__, "EigenvalueDecomposition", function() { return evd_EigenvalueDecomposition; }); +/* concated harmony reexport EVD */__webpack_require__.d(__webpack_exports__, "EVD", function() { return evd_EigenvalueDecomposition; }); +/* concated harmony reexport CholeskyDecomposition */__webpack_require__.d(__webpack_exports__, "CholeskyDecomposition", function() { return cholesky_CholeskyDecomposition; }); +/* concated harmony reexport CHO */__webpack_require__.d(__webpack_exports__, "CHO", function() { return cholesky_CholeskyDecomposition; }); +/* concated harmony reexport LuDecomposition */__webpack_require__.d(__webpack_exports__, "LuDecomposition", function() { return lu_LuDecomposition; }); +/* concated harmony reexport LU */__webpack_require__.d(__webpack_exports__, "LU", function() { return lu_LuDecomposition; }); +/* concated harmony reexport QrDecomposition */__webpack_require__.d(__webpack_exports__, "QrDecomposition", function() { return qr_QrDecomposition; }); +/* concated harmony reexport QR */__webpack_require__.d(__webpack_exports__, "QR", function() { return qr_QrDecomposition; }); + + + + + + + + + + + + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const toString = Object.prototype.toString; + +function isAnyArray(object) { + return toString.call(object).endsWith('Array]'); +} + +module.exports = isAnyArray; + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +function squaredEuclidean(p, q) { + var d = 0; + + for (var i = 0; i < p.length; i++) { + d += (p[i] - q[i]) * (p[i] - q[i]); + } + + return d; +} + +function euclidean(p, q) { + return Math.sqrt(squaredEuclidean(p, q)); +} + +module.exports = euclidean; +euclidean.squared = squaredEuclidean; + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.array = __webpack_require__(22); +exports.matrix = __webpack_require__(4); + +/***/ }), +/* 4 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var arrayStat = __webpack_require__(22); + +function compareNumbers(a, b) { + return a - b; +} + +exports.max = function max(matrix) { + var max = -Infinity; + + for (var i = 0; i < matrix.length; i++) { + for (var j = 0; j < matrix[i].length; j++) { + if (matrix[i][j] > max) max = matrix[i][j]; } + } - /** - * Divides the values of each row by those of a vector - * @param {Array|Matrix} vector - Array or vector - * @return {Matrix} this - */ - divRowVector(vector) { - vector = (0, _util.checkRowVector)(this, vector); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) / vector[j]); - } - } - return this; + return max; +}; + +exports.min = function min(matrix) { + var min = Infinity; + + for (var i = 0; i < matrix.length; i++) { + for (var j = 0; j < matrix[i].length; j++) { + if (matrix[i][j] < min) min = matrix[i][j]; } + } - /** - * Adds the values of a vector to each column - * @param {Array|Matrix} vector - Array or vector - * @return {Matrix} this - */ - addColumnVector(vector) { - vector = (0, _util.checkColumnVector)(this, vector); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) + vector[i]); - } + return min; +}; + +exports.minMax = function minMax(matrix) { + var min = Infinity; + var max = -Infinity; + + for (var i = 0; i < matrix.length; i++) { + for (var j = 0; j < matrix[i].length; j++) { + if (matrix[i][j] < min) min = matrix[i][j]; + if (matrix[i][j] > max) max = matrix[i][j]; + } + } + + return { + min: min, + max: max + }; +}; + +exports.entropy = function entropy(matrix, eps) { + if (typeof eps === 'undefined') { + eps = 0; + } + + var sum = 0, + l1 = matrix.length, + l2 = matrix[0].length; + + for (var i = 0; i < l1; i++) { + for (var j = 0; j < l2; j++) { + sum += matrix[i][j] * Math.log(matrix[i][j] + eps); + } + } + + return -sum; +}; + +exports.mean = function mean(matrix, dimension) { + if (typeof dimension === 'undefined') { + dimension = 0; + } + + var rows = matrix.length, + cols = matrix[0].length, + theMean, + N, + i, + j; + + if (dimension === -1) { + theMean = [0]; + N = rows * cols; + + for (i = 0; i < rows; i++) { + for (j = 0; j < cols; j++) { + theMean[0] += matrix[i][j]; } - return this; } - /** - * Subtracts the values of a vector from each column - * @param {Array|Matrix} vector - Array or vector - * @return {Matrix} this - */ - subColumnVector(vector) { - vector = (0, _util.checkColumnVector)(this, vector); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) - vector[i]); - } + theMean[0] /= N; + } else if (dimension === 0) { + theMean = new Array(cols); + N = rows; + + for (j = 0; j < cols; j++) { + theMean[j] = 0; + + for (i = 0; i < rows; i++) { + theMean[j] += matrix[i][j]; } - return this; + + theMean[j] /= N; } + } else if (dimension === 1) { + theMean = new Array(rows); + N = cols; - /** - * Multiplies the values of a vector with each column - * @param {Array|Matrix} vector - Array or vector - * @return {Matrix} this - */ - mulColumnVector(vector) { - vector = (0, _util.checkColumnVector)(this, vector); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) * vector[i]); - } + for (j = 0; j < rows; j++) { + theMean[j] = 0; + + for (i = 0; i < cols; i++) { + theMean[j] += matrix[j][i]; } - return this; + + theMean[j] /= N; } + } else { + throw new Error('Invalid dimension'); + } - /** - * Divides the values of each column by those of a vector - * @param {Array|Matrix} vector - Array or vector - * @return {Matrix} this - */ - divColumnVector(vector) { - vector = (0, _util.checkColumnVector)(this, vector); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) / vector[i]); - } + return theMean; +}; + +exports.sum = function sum(matrix, dimension) { + if (typeof dimension === 'undefined') { + dimension = 0; + } + + var rows = matrix.length, + cols = matrix[0].length, + theSum, + i, + j; + + if (dimension === -1) { + theSum = [0]; + + for (i = 0; i < rows; i++) { + for (j = 0; j < cols; j++) { + theSum[0] += matrix[i][j]; } - return this; } + } else if (dimension === 0) { + theSum = new Array(cols); - /** - * Multiplies the values of a row with a scalar - * @param {number} index - Row index - * @param {number} value - * @return {Matrix} this - */ - mulRow(index, value) { - (0, _util.checkRowIndex)(this, index); - for (var i = 0; i < this.columns; i++) { - this.set(index, i, this.get(index, i) * value); + for (j = 0; j < cols; j++) { + theSum[j] = 0; + + for (i = 0; i < rows; i++) { + theSum[j] += matrix[i][j]; } - return this; } + } else if (dimension === 1) { + theSum = new Array(rows); - /** - * Multiplies the values of a column with a scalar - * @param {number} index - Column index - * @param {number} value - * @return {Matrix} this - */ - mulColumn(index, value) { - (0, _util.checkColumnIndex)(this, index); - for (var i = 0; i < this.rows; i++) { - this.set(i, index, this.get(i, index) * value); + for (j = 0; j < rows; j++) { + theSum[j] = 0; + + for (i = 0; i < cols; i++) { + theSum[j] += matrix[j][i]; } - return this; } + } else { + throw new Error('Invalid dimension'); + } - /** - * Returns the maximum value of the matrix - * @return {number} - */ - max() { - var v = this.get(0, 0); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - if (this.get(i, j) > v) { - v = this.get(i, j); - } - } + return theSum; +}; + +exports.product = function product(matrix, dimension) { + if (typeof dimension === 'undefined') { + dimension = 0; + } + + var rows = matrix.length, + cols = matrix[0].length, + theProduct, + i, + j; + + if (dimension === -1) { + theProduct = [1]; + + for (i = 0; i < rows; i++) { + for (j = 0; j < cols; j++) { + theProduct[0] *= matrix[i][j]; } - return v; } + } else if (dimension === 0) { + theProduct = new Array(cols); - /** - * Returns the index of the maximum value - * @return {Array} - */ - maxIndex() { - var v = this.get(0, 0); - var idx = [0, 0]; - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - if (this.get(i, j) > v) { - v = this.get(i, j); - idx[0] = i; - idx[1] = j; - } - } + for (j = 0; j < cols; j++) { + theProduct[j] = 1; + + for (i = 0; i < rows; i++) { + theProduct[j] *= matrix[i][j]; } - return idx; } + } else if (dimension === 1) { + theProduct = new Array(rows); - /** - * Returns the minimum value of the matrix - * @return {number} - */ - min() { - var v = this.get(0, 0); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - if (this.get(i, j) < v) { - v = this.get(i, j); - } - } + for (j = 0; j < rows; j++) { + theProduct[j] = 1; + + for (i = 0; i < cols; i++) { + theProduct[j] *= matrix[j][i]; } - return v; } + } else { + throw new Error('Invalid dimension'); + } - /** - * Returns the index of the minimum value - * @return {Array} - */ - minIndex() { - var v = this.get(0, 0); - var idx = [0, 0]; - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - if (this.get(i, j) < v) { - v = this.get(i, j); - idx[0] = i; - idx[1] = j; - } - } - } - return idx; + return theProduct; +}; + +exports.standardDeviation = function standardDeviation(matrix, means, unbiased) { + var vari = exports.variance(matrix, means, unbiased), + l = vari.length; + + for (var i = 0; i < l; i++) { + vari[i] = Math.sqrt(vari[i]); + } + + return vari; +}; + +exports.variance = function variance(matrix, means, unbiased) { + if (typeof unbiased === 'undefined') { + unbiased = true; + } + + means = means || exports.mean(matrix); + var rows = matrix.length; + if (rows === 0) return []; + var cols = matrix[0].length; + var vari = new Array(cols); + + for (var j = 0; j < cols; j++) { + var sum1 = 0, + sum2 = 0, + x = 0; + + for (var i = 0; i < rows; i++) { + x = matrix[i][j] - means[j]; + sum1 += x; + sum2 += x * x; } - /** - * Returns the maximum value of one row - * @param {number} row - Row index - * @return {number} - */ - maxRow(row) { - (0, _util.checkRowIndex)(this, row); - var v = this.get(row, 0); - for (var i = 1; i < this.columns; i++) { - if (this.get(row, i) > v) { - v = this.get(row, i); - } - } - return v; + if (unbiased) { + vari[j] = (sum2 - sum1 * sum1 / rows) / (rows - 1); + } else { + vari[j] = (sum2 - sum1 * sum1 / rows) / rows; } + } - /** - * Returns the index of the maximum value of one row - * @param {number} row - Row index - * @return {Array} - */ - maxRowIndex(row) { - (0, _util.checkRowIndex)(this, row); - var v = this.get(row, 0); - var idx = [row, 0]; - for (var i = 1; i < this.columns; i++) { - if (this.get(row, i) > v) { - v = this.get(row, i); - idx[1] = i; - } - } - return idx; + return vari; +}; + +exports.median = function median(matrix) { + var rows = matrix.length, + cols = matrix[0].length; + var medians = new Array(cols); + + for (var i = 0; i < cols; i++) { + var data = new Array(rows); + + for (var j = 0; j < rows; j++) { + data[j] = matrix[j][i]; } - /** - * Returns the minimum value of one row - * @param {number} row - Row index - * @return {number} - */ - minRow(row) { - (0, _util.checkRowIndex)(this, row); - var v = this.get(row, 0); - for (var i = 1; i < this.columns; i++) { - if (this.get(row, i) < v) { - v = this.get(row, i); - } - } - return v; + data.sort(compareNumbers); + var N = data.length; + + if (N % 2 === 0) { + medians[i] = (data[N / 2] + data[N / 2 - 1]) * 0.5; + } else { + medians[i] = data[Math.floor(N / 2)]; } + } - /** - * Returns the index of the maximum value of one row - * @param {number} row - Row index - * @return {Array} - */ - minRowIndex(row) { - (0, _util.checkRowIndex)(this, row); - var v = this.get(row, 0); - var idx = [row, 0]; - for (var i = 1; i < this.columns; i++) { - if (this.get(row, i) < v) { - v = this.get(row, i); - idx[1] = i; - } - } - return idx; + return medians; +}; + +exports.mode = function mode(matrix) { + var rows = matrix.length, + cols = matrix[0].length, + modes = new Array(cols), + i, + j; + + for (i = 0; i < cols; i++) { + var itemCount = new Array(rows); + + for (var k = 0; k < rows; k++) { + itemCount[k] = 0; } - /** - * Returns the maximum value of one column - * @param {number} column - Column index - * @return {number} - */ - maxColumn(column) { - (0, _util.checkColumnIndex)(this, column); - var v = this.get(0, column); - for (var i = 1; i < this.rows; i++) { - if (this.get(i, column) > v) { - v = this.get(i, column); - } + var itemArray = new Array(rows); + var count = 0; + + for (j = 0; j < rows; j++) { + var index = itemArray.indexOf(matrix[j][i]); + + if (index >= 0) { + itemCount[index]++; + } else { + itemArray[count] = matrix[j][i]; + itemCount[count] = 1; + count++; } - return v; } - /** - * Returns the index of the maximum value of one column - * @param {number} column - Column index - * @return {Array} - */ - maxColumnIndex(column) { - (0, _util.checkColumnIndex)(this, column); - var v = this.get(0, column); - var idx = [0, column]; - for (var i = 1; i < this.rows; i++) { - if (this.get(i, column) > v) { - v = this.get(i, column); - idx[0] = i; - } + var maxValue = 0, + maxIndex = 0; + + for (j = 0; j < count; j++) { + if (itemCount[j] > maxValue) { + maxValue = itemCount[j]; + maxIndex = j; } - return idx; } - /** - * Returns the minimum value of one column - * @param {number} column - Column index - * @return {number} - */ - minColumn(column) { - (0, _util.checkColumnIndex)(this, column); - var v = this.get(0, column); - for (var i = 1; i < this.rows; i++) { - if (this.get(i, column) < v) { - v = this.get(i, column); - } - } - return v; + modes[i] = itemArray[maxIndex]; + } + + return modes; +}; + +exports.skewness = function skewness(matrix, unbiased) { + if (typeof unbiased === 'undefined') unbiased = true; + var means = exports.mean(matrix); + var n = matrix.length, + l = means.length; + var skew = new Array(l); + + for (var j = 0; j < l; j++) { + var s2 = 0, + s3 = 0; + + for (var i = 0; i < n; i++) { + var dev = matrix[i][j] - means[j]; + s2 += dev * dev; + s3 += dev * dev * dev; } - /** - * Returns the index of the minimum value of one column - * @param {number} column - Column index - * @return {Array} - */ - minColumnIndex(column) { - (0, _util.checkColumnIndex)(this, column); - var v = this.get(0, column); - var idx = [0, column]; - for (var i = 1; i < this.rows; i++) { - if (this.get(i, column) < v) { - v = this.get(i, column); - idx[0] = i; - } - } - return idx; + var m2 = s2 / n; + var m3 = s3 / n; + var g = m3 / Math.pow(m2, 3 / 2); + + if (unbiased) { + var a = Math.sqrt(n * (n - 1)); + var b = n - 2; + skew[j] = a / b * g; + } else { + skew[j] = g; + } + } + + return skew; +}; + +exports.kurtosis = function kurtosis(matrix, unbiased) { + if (typeof unbiased === 'undefined') unbiased = true; + var means = exports.mean(matrix); + var n = matrix.length, + m = matrix[0].length; + var kurt = new Array(m); + + for (var j = 0; j < m; j++) { + var s2 = 0, + s4 = 0; + + for (var i = 0; i < n; i++) { + var dev = matrix[i][j] - means[j]; + s2 += dev * dev; + s4 += dev * dev * dev * dev; + } + + var m2 = s2 / n; + var m4 = s4 / n; + + if (unbiased) { + var v = s2 / (n - 1); + var a = n * (n + 1) / ((n - 1) * (n - 2) * (n - 3)); + var b = s4 / (v * v); + var c = (n - 1) * (n - 1) / ((n - 2) * (n - 3)); + kurt[j] = a * b - 3 * c; + } else { + kurt[j] = m4 / (m2 * m2) - 3; + } + } + + return kurt; +}; + +exports.standardError = function standardError(matrix) { + var samples = matrix.length; + var standardDeviations = exports.standardDeviation(matrix); + var l = standardDeviations.length; + var standardErrors = new Array(l); + var sqrtN = Math.sqrt(samples); + + for (var i = 0; i < l; i++) { + standardErrors[i] = standardDeviations[i] / sqrtN; + } + + return standardErrors; +}; + +exports.covariance = function covariance(matrix, dimension) { + return exports.scatter(matrix, undefined, dimension); +}; + +exports.scatter = function scatter(matrix, divisor, dimension) { + if (typeof dimension === 'undefined') { + dimension = 0; + } + + if (typeof divisor === 'undefined') { + if (dimension === 0) { + divisor = matrix.length - 1; + } else if (dimension === 1) { + divisor = matrix[0].length - 1; } + } - /** - * Returns an array containing the diagonal values of the matrix - * @return {Array} - */ - diag() { - var min = Math.min(this.rows, this.columns); - var diag = new Array(min); - for (var i = 0; i < min; i++) { - diag[i] = this.get(i, i); - } - return diag; - } + var means = exports.mean(matrix, dimension); + var rows = matrix.length; - /** - * Returns the sum by the argument given, if no argument given, - * it returns the sum of all elements of the matrix. - * @param {string} by - sum by 'row' or 'column'. - * @return {Matrix|number} - */ - sum(by) { - switch (by) { - case 'row': - return (0, _util.sumByRow)(this); - case 'column': - return (0, _util.sumByColumn)(this); - default: - return (0, _util.sumAll)(this); - } - } + if (rows === 0) { + return [[]]; + } - /** - * Returns the mean of all elements of the matrix - * @return {number} - */ - mean() { - return this.sum() / this.size; - } + var cols = matrix[0].length, + cov, + i, + j, + s, + k; - /** - * Returns the product of all elements of the matrix - * @return {number} - */ - prod() { - var prod = 1; - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - prod *= this.get(i, j); - } - } - return prod; - } + if (dimension === 0) { + cov = new Array(cols); - /** - * Returns the norm of a matrix. - * @param {string} type - "frobenius" (default) or "max" return resp. the Frobenius norm and the max norm. - * @return {number} - */ - norm(type = 'frobenius') { - var result = 0; - if (type === 'max') { - return this.max(); - } else if (type === 'frobenius') { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - result = result + this.get(i, j) * this.get(i, j); - } - } - return Math.sqrt(result); - } else { - throw new RangeError(`unknown norm type: ${type}`); - } + for (i = 0; i < cols; i++) { + cov[i] = new Array(cols); } - /** - * Computes the cumulative sum of the matrix elements (in place, row by row) - * @return {Matrix} this - */ - cumulativeSum() { - var sum = 0; - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - sum += this.get(i, j); - this.set(i, j, sum); + for (i = 0; i < cols; i++) { + for (j = i; j < cols; j++) { + s = 0; + + for (k = 0; k < rows; k++) { + s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]); } - } - return this; - } - /** - * Computes the dot (scalar) product between the matrix and another - * @param {Matrix} vector2 vector - * @return {number} - */ - dot(vector2) { - if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray(); - var vector1 = this.to1DArray(); - if (vector1.length !== vector2.length) { - throw new RangeError('vectors do not have the same size'); - } - var dot = 0; - for (var i = 0; i < vector1.length; i++) { - dot += vector1[i] * vector2[i]; + s /= divisor; + cov[i][j] = s; + cov[j][i] = s; } - return dot; } + } else if (dimension === 1) { + cov = new Array(rows); - /** - * Returns the matrix product between this and other - * @param {Matrix} other - * @return {Matrix} - */ - mmul(other) { - other = this.constructor.checkMatrix(other); - if (this.columns !== other.rows) { - // eslint-disable-next-line no-console - console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.'); - } - - var m = this.rows; - var n = this.columns; - var p = other.columns; + for (i = 0; i < rows; i++) { + cov[i] = new Array(rows); + } - var result = new this.constructor[Symbol.species](m, p); + for (i = 0; i < rows; i++) { + for (j = i; j < rows; j++) { + s = 0; - var Bcolj = new Array(n); - for (var j = 0; j < p; j++) { - for (var k = 0; k < n; k++) { - Bcolj[k] = other.get(k, j); + for (k = 0; k < cols; k++) { + s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]); } - for (var i = 0; i < m; i++) { - var s = 0; - for (k = 0; k < n; k++) { - s += this.get(i, k) * Bcolj[k]; - } - - result.set(i, j, s); - } + s /= divisor; + cov[i][j] = s; + cov[j][i] = s; } - return result; } + } else { + throw new Error('Invalid dimension'); + } - strassen2x2(other) { - var result = new this.constructor[Symbol.species](2, 2); - var a11 = this.get(0, 0); - var b11 = other.get(0, 0); - var a12 = this.get(0, 1); - var b12 = other.get(0, 1); - var a21 = this.get(1, 0); - var b21 = other.get(1, 0); - var a22 = this.get(1, 1); - var b22 = other.get(1, 1); - - // Compute intermediate values. - var m1 = (a11 + a22) * (b11 + b22); - var m2 = (a21 + a22) * b11; - var m3 = a11 * (b12 - b22); - var m4 = a22 * (b21 - b11); - var m5 = (a11 + a12) * b22; - var m6 = (a21 - a11) * (b11 + b12); - var m7 = (a12 - a22) * (b21 + b22); - - // Combine intermediate values into the output. - var c00 = m1 + m4 - m5 + m7; - var c01 = m3 + m5; - var c10 = m2 + m4; - var c11 = m1 - m2 + m3 + m6; + return cov; +}; - result.set(0, 0, c00); - result.set(0, 1, c01); - result.set(1, 0, c10); - result.set(1, 1, c11); - return result; - } +exports.correlation = function correlation(matrix) { + var means = exports.mean(matrix), + standardDeviations = exports.standardDeviation(matrix, true, means), + scores = exports.zScores(matrix, means, standardDeviations), + rows = matrix.length, + cols = matrix[0].length, + i, + j; + var cor = new Array(cols); + + for (i = 0; i < cols; i++) { + cor[i] = new Array(cols); + } - strassen3x3(other) { - var result = new this.constructor[Symbol.species](3, 3); + for (i = 0; i < cols; i++) { + for (j = i; j < cols; j++) { + var c = 0; - var a00 = this.get(0, 0); - var a01 = this.get(0, 1); - var a02 = this.get(0, 2); - var a10 = this.get(1, 0); - var a11 = this.get(1, 1); - var a12 = this.get(1, 2); - var a20 = this.get(2, 0); - var a21 = this.get(2, 1); - var a22 = this.get(2, 2); - - var b00 = other.get(0, 0); - var b01 = other.get(0, 1); - var b02 = other.get(0, 2); - var b10 = other.get(1, 0); - var b11 = other.get(1, 1); - var b12 = other.get(1, 2); - var b20 = other.get(2, 0); - var b21 = other.get(2, 1); - var b22 = other.get(2, 2); - - var m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11; - var m2 = (a00 - a10) * (-b01 + b11); - var m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22); - var m4 = (-a00 + a10 + a11) * (b00 - b01 + b11); - var m5 = (a10 + a11) * (-b00 + b01); - var m6 = a00 * b00; - var m7 = (-a00 + a20 + a21) * (b00 - b02 + b12); - var m8 = (-a00 + a20) * (b02 - b12); - var m9 = (a20 + a21) * (-b00 + b02); - var m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12; - var m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21); - var m12 = (-a02 + a21 + a22) * (b11 + b20 - b21); - var m13 = (a02 - a22) * (b11 - b21); - var m14 = a02 * b20; - var m15 = (a21 + a22) * (-b20 + b21); - var m16 = (-a02 + a11 + a12) * (b12 + b20 - b22); - var m17 = (a02 - a12) * (b12 - b22); - var m18 = (a11 + a12) * (-b20 + b22); - var m19 = a01 * b10; - var m20 = a12 * b21; - var m21 = a10 * b02; - var m22 = a20 * b01; - var m23 = a22 * b22; - - var c00 = m6 + m14 + m19; - var c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15; - var c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18; - var c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17; - var c11 = m2 + m4 + m5 + m6 + m20; - var c12 = m14 + m16 + m17 + m18 + m21; - var c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14; - var c21 = m12 + m13 + m14 + m15 + m22; - var c22 = m6 + m7 + m8 + m9 + m23; + for (var k = 0, l = scores.length; k < l; k++) { + c += scores[k][j] * scores[k][i]; + } - result.set(0, 0, c00); - result.set(0, 1, c01); - result.set(0, 2, c02); - result.set(1, 0, c10); - result.set(1, 1, c11); - result.set(1, 2, c12); - result.set(2, 0, c20); - result.set(2, 1, c21); - result.set(2, 2, c22); - return result; + c /= rows - 1; + cor[i][j] = c; + cor[j][i] = c; } + } - /** - * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000. - * @param {Matrix} y - * @return {Matrix} - */ - mmulStrassen(y) { - var x = this.clone(); - var r1 = x.rows; - var c1 = x.columns; - var r2 = y.rows; - var c2 = y.columns; - if (c1 !== r2) { - // eslint-disable-next-line no-console - console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`); - } + return cor; +}; - // Put a matrix into the top left of a matrix of zeros. - // `rows` and `cols` are the dimensions of the output matrix. - function embed(mat, rows, cols) { - var r = mat.rows; - var c = mat.columns; - if (r === rows && c === cols) { - return mat; - } else { - var resultat = Matrix.zeros(rows, cols); - resultat = resultat.setSubMatrix(mat, 0, 0); - return resultat; - } - } +exports.zScores = function zScores(matrix, means, standardDeviations) { + means = means || exports.mean(matrix); + if (typeof standardDeviations === 'undefined') standardDeviations = exports.standardDeviation(matrix, true, means); + return exports.standardize(exports.center(matrix, means, false), standardDeviations, true); +}; - // Make sure both matrices are the same size. - // This is exclusively for simplicity: - // this algorithm can be implemented with matrices of different sizes. +exports.center = function center(matrix, means, inPlace) { + means = means || exports.mean(matrix); + var result = matrix, + l = matrix.length, + i, + j, + jj; - var r = Math.max(r1, r2); - var c = Math.max(c1, c2); - x = embed(x, r, c); - y = embed(y, r, c); + if (!inPlace) { + result = new Array(l); - // Our recursive multiplication function. - function blockMult(a, b, rows, cols) { - // For small matrices, resort to naive multiplication. - if (rows <= 512 || cols <= 512) { - return a.mmul(b); // a is equivalent to this - } + for (i = 0; i < l; i++) { + result[i] = new Array(matrix[i].length); + } + } - // Apply dynamic padding. - if (rows % 2 === 1 && cols % 2 === 1) { - a = embed(a, rows + 1, cols + 1); - b = embed(b, rows + 1, cols + 1); - } else if (rows % 2 === 1) { - a = embed(a, rows + 1, cols); - b = embed(b, rows + 1, cols); - } else if (cols % 2 === 1) { - a = embed(a, rows, cols + 1); - b = embed(b, rows, cols + 1); - } + for (i = 0; i < l; i++) { + var row = result[i]; - var halfRows = parseInt(a.rows / 2, 10); - var halfCols = parseInt(a.columns / 2, 10); - // Subdivide input matrices. - var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1); - var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1); + for (j = 0, jj = row.length; j < jj; j++) { + row[j] = matrix[i][j] - means[j]; + } + } - var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1); - var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1); + return result; +}; - var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1); - var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1); +exports.standardize = function standardize(matrix, standardDeviations, inPlace) { + if (typeof standardDeviations === 'undefined') standardDeviations = exports.standardDeviation(matrix); + var result = matrix, + l = matrix.length, + i, + j, + jj; - var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1); - var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1); + if (!inPlace) { + result = new Array(l); - // Compute intermediate values. - var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols); - var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols); - var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols); - var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols); - var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols); - var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols); - var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols); + for (i = 0; i < l; i++) { + result[i] = new Array(matrix[i].length); + } + } - // Combine intermediate values into the output. - var c11 = Matrix.add(m1, m4); - c11.sub(m5); - c11.add(m7); - var c12 = Matrix.add(m3, m5); - var c21 = Matrix.add(m2, m4); - var c22 = Matrix.sub(m1, m2); - c22.add(m3); - c22.add(m6); + for (i = 0; i < l; i++) { + var resultRow = result[i]; + var sourceRow = matrix[i]; - // Crop output to the desired size (undo dynamic padding). - var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns); - resultat = resultat.setSubMatrix(c11, 0, 0); - resultat = resultat.setSubMatrix(c12, c11.rows, 0); - resultat = resultat.setSubMatrix(c21, 0, c11.columns); - resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns); - return resultat.subMatrix(0, rows - 1, 0, cols - 1); + for (j = 0, jj = resultRow.length; j < jj; j++) { + if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) { + resultRow[j] = sourceRow[j] / standardDeviations[j]; } - return blockMult(x, y, r, c); } + } - /** - * Returns a row-by-row scaled matrix - * @param {number} [min=0] - Minimum scaled value - * @param {number} [max=1] - Maximum scaled value - * @return {Matrix} - The scaled matrix - */ - scaleRows(min, max) { - min = min === undefined ? 0 : min; - max = max === undefined ? 1 : max; - if (min >= max) { - throw new RangeError('min should be strictly smaller than max'); - } - var newMatrix = this.constructor.empty(this.rows, this.columns); - for (var i = 0; i < this.rows; i++) { - var scaled = (0, _mlArrayRescale2.default)(this.getRow(i), { min, max }); - newMatrix.setRow(i, scaled); - } - return newMatrix; - } + return result; +}; - /** - * Returns a new column-by-column scaled matrix - * @param {number} [min=0] - Minimum scaled value - * @param {number} [max=1] - Maximum scaled value - * @return {Matrix} - The new scaled matrix - * @example - * var matrix = new Matrix([[1,2],[-1,0]]); - * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]] - */ - scaleColumns(min, max) { - min = min === undefined ? 0 : min; - max = max === undefined ? 1 : max; - if (min >= max) { - throw new RangeError('min should be strictly smaller than max'); - } - var newMatrix = this.constructor.empty(this.rows, this.columns); - for (var i = 0; i < this.columns; i++) { - var scaled = (0, _mlArrayRescale2.default)(this.getColumn(i), { - min: min, - max: max - }); - newMatrix.setColumn(i, scaled); - } - return newMatrix; +exports.weightedVariance = function weightedVariance(matrix, weights) { + var means = exports.mean(matrix); + var rows = matrix.length; + if (rows === 0) return []; + var cols = matrix[0].length; + var vari = new Array(cols); + + for (var j = 0; j < cols; j++) { + var sum = 0; + var a = 0, + b = 0; + + for (var i = 0; i < rows; i++) { + var z = matrix[i][j] - means[j]; + var w = weights[i]; + sum += w * (z * z); + b += w; + a += w * w; } - /** - * Returns the Kronecker product (also known as tensor product) between this and other - * See https://en.wikipedia.org/wiki/Kronecker_product - * @param {Matrix} other - * @return {Matrix} - */ - kroneckerProduct(other) { - other = this.constructor.checkMatrix(other); + vari[j] = sum * (b / (b * b - a)); + } - var m = this.rows; - var n = this.columns; - var p = other.rows; - var q = other.columns; + return vari; +}; - var result = new this.constructor[Symbol.species](m * p, n * q); - for (var i = 0; i < m; i++) { - for (var j = 0; j < n; j++) { - for (var k = 0; k < p; k++) { - for (var l = 0; l < q; l++) { - result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l); - } - } - } - } - return result; +exports.weightedMean = function weightedMean(matrix, weights, dimension) { + if (typeof dimension === 'undefined') { + dimension = 0; + } + + var rows = matrix.length; + if (rows === 0) return []; + var cols = matrix[0].length, + means, + i, + ii, + j, + w, + row; + + if (dimension === 0) { + means = new Array(cols); + + for (i = 0; i < cols; i++) { + means[i] = 0; } - /** - * Transposes the matrix and returns a new one containing the result - * @return {Matrix} - */ - transpose() { - var result = new this.constructor[Symbol.species](this.columns, this.rows); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - result.set(j, i, this.get(i, j)); - } + for (i = 0; i < rows; i++) { + row = matrix[i]; + w = weights[i]; + + for (j = 0; j < cols; j++) { + means[j] += row[j] * w; } - return result; } + } else if (dimension === 1) { + means = new Array(rows); - /** - * Sorts the rows (in place) - * @param {function} compareFunction - usual Array.prototype.sort comparison function - * @return {Matrix} this - */ - sortRows(compareFunction) { - if (compareFunction === undefined) compareFunction = compareNumbers; - for (var i = 0; i < this.rows; i++) { - this.setRow(i, this.getRow(i).sort(compareFunction)); - } - return this; + for (i = 0; i < rows; i++) { + means[i] = 0; } - /** - * Sorts the columns (in place) - * @param {function} compareFunction - usual Array.prototype.sort comparison function - * @return {Matrix} this - */ - sortColumns(compareFunction) { - if (compareFunction === undefined) compareFunction = compareNumbers; - for (var i = 0; i < this.columns; i++) { - this.setColumn(i, this.getColumn(i).sort(compareFunction)); + for (j = 0; j < rows; j++) { + row = matrix[j]; + w = weights[j]; + + for (i = 0; i < cols; i++) { + means[j] += row[i] * w; } - return this; } + } else { + throw new Error('Invalid dimension'); + } - /** - * Returns a subset of the matrix - * @param {number} startRow - First row index - * @param {number} endRow - Last row index - * @param {number} startColumn - First column index - * @param {number} endColumn - Last column index - * @return {Matrix} - */ - subMatrix(startRow, endRow, startColumn, endColumn) { - (0, _util.checkRange)(this, startRow, endRow, startColumn, endColumn); - var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1); - for (var i = startRow; i <= endRow; i++) { - for (var j = startColumn; j <= endColumn; j++) { - newMatrix[i - startRow][j - startColumn] = this.get(i, j); - } - } - return newMatrix; + var weightSum = arrayStat.sum(weights); + + if (weightSum !== 0) { + for (i = 0, ii = means.length; i < ii; i++) { + means[i] /= weightSum; } + } - /** - * Returns a subset of the matrix based on an array of row indices - * @param {Array} indices - Array containing the row indices - * @param {number} [startColumn = 0] - First column index - * @param {number} [endColumn = this.columns-1] - Last column index - * @return {Matrix} - */ - subMatrixRow(indices, startColumn, endColumn) { - if (startColumn === undefined) startColumn = 0; - if (endColumn === undefined) endColumn = this.columns - 1; - if (startColumn > endColumn || startColumn < 0 || startColumn >= this.columns || endColumn < 0 || endColumn >= this.columns) { - throw new RangeError('Argument out of range'); - } + return means; +}; - var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1); - for (var i = 0; i < indices.length; i++) { - for (var j = startColumn; j <= endColumn; j++) { - if (indices[i] < 0 || indices[i] >= this.rows) { - throw new RangeError(`Row index out of range: ${indices[i]}`); - } - newMatrix.set(i, j - startColumn, this.get(indices[i], j)); - } - } - return newMatrix; +exports.weightedCovariance = function weightedCovariance(matrix, weights, means, dimension) { + dimension = dimension || 0; + means = means || exports.weightedMean(matrix, weights, dimension); + var s1 = 0, + s2 = 0; + + for (var i = 0, ii = weights.length; i < ii; i++) { + s1 += weights[i]; + s2 += weights[i] * weights[i]; + } + + var factor = s1 / (s1 * s1 - s2); + return exports.weightedScatter(matrix, weights, means, factor, dimension); +}; + +exports.weightedScatter = function weightedScatter(matrix, weights, means, factor, dimension) { + dimension = dimension || 0; + means = means || exports.weightedMean(matrix, weights, dimension); + + if (typeof factor === 'undefined') { + factor = 1; + } + + var rows = matrix.length; + + if (rows === 0) { + return [[]]; + } + + var cols = matrix[0].length, + cov, + i, + j, + k, + s; + + if (dimension === 0) { + cov = new Array(cols); + + for (i = 0; i < cols; i++) { + cov[i] = new Array(cols); } - /** - * Returns a subset of the matrix based on an array of column indices - * @param {Array} indices - Array containing the column indices - * @param {number} [startRow = 0] - First row index - * @param {number} [endRow = this.rows-1] - Last row index - * @return {Matrix} - */ - subMatrixColumn(indices, startRow, endRow) { - if (startRow === undefined) startRow = 0; - if (endRow === undefined) endRow = this.rows - 1; - if (startRow > endRow || startRow < 0 || startRow >= this.rows || endRow < 0 || endRow >= this.rows) { - throw new RangeError('Argument out of range'); - } + for (i = 0; i < cols; i++) { + for (j = i; j < cols; j++) { + s = 0; - var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length); - for (var i = 0; i < indices.length; i++) { - for (var j = startRow; j <= endRow; j++) { - if (indices[i] < 0 || indices[i] >= this.columns) { - throw new RangeError(`Column index out of range: ${indices[i]}`); - } - newMatrix.set(j - startRow, i, this.get(j, indices[i])); + for (k = 0; k < rows; k++) { + s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]); } + + cov[i][j] = s * factor; + cov[j][i] = s * factor; } - return newMatrix; } + } else if (dimension === 1) { + cov = new Array(rows); - /** - * Set a part of the matrix to the given sub-matrix - * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values. - * @param {number} startRow - The index of the first row to set - * @param {number} startColumn - The index of the first column to set - * @return {Matrix} - */ - setSubMatrix(matrix, startRow, startColumn) { - matrix = this.constructor.checkMatrix(matrix); - var endRow = startRow + matrix.rows - 1; - var endColumn = startColumn + matrix.columns - 1; - (0, _util.checkRange)(this, startRow, endRow, startColumn, endColumn); - for (var i = 0; i < matrix.rows; i++) { - for (var j = 0; j < matrix.columns; j++) { - this[startRow + i][startColumn + j] = matrix.get(i, j); - } - } - return this; + for (i = 0; i < rows; i++) { + cov[i] = new Array(rows); } - /** - * Return a new matrix based on a selection of rows and columns - * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once. - * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once. - * @return {Matrix} The new matrix - */ - selection(rowIndices, columnIndices) { - var indices = (0, _util.checkIndices)(this, rowIndices, columnIndices); - var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length); - for (var i = 0; i < indices.row.length; i++) { - var rowIndex = indices.row[i]; - for (var j = 0; j < indices.column.length; j++) { - var columnIndex = indices.column[j]; - newMatrix[i][j] = this.get(rowIndex, columnIndex); + for (i = 0; i < rows; i++) { + for (j = i; j < rows; j++) { + s = 0; + + for (k = 0; k < cols; k++) { + s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]); } - } - return newMatrix; - } - /** - * Returns the trace of the matrix (sum of the diagonal elements) - * @return {number} - */ - trace() { - var min = Math.min(this.rows, this.columns); - var trace = 0; - for (var i = 0; i < min; i++) { - trace += this.get(i, i); + cov[i][j] = s * factor; + cov[j][i] = s * factor; } - return trace; } + } else { + throw new Error('Invalid dimension'); + } - /* - Matrix views - */ + return cov; +}; - /** - * Returns a view of the transposition of the matrix - * @return {MatrixTransposeView} - */ - transposeView() { - return new _transpose2.default(this); - } +/***/ }), +/* 5 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - /** - * Returns a view of the row vector with the given index - * @param {number} row - row index of the vector - * @return {MatrixRowView} - */ - rowView(row) { - (0, _util.checkRowIndex)(this, row); - return new _row2.default(this, row); - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(is_any_array__WEBPACK_IMPORTED_MODULE_0__); - /** - * Returns a view of the column vector with the given index - * @param {number} column - column index of the vector - * @return {MatrixColumnView} - */ - columnView(column) { - (0, _util.checkColumnIndex)(this, column); - return new _column2.default(this, column); - } +/** + * Computes the mean of the given values + * @param {Array} input + * @return {number} + */ - /** - * Returns a view of the matrix flipped in the row axis - * @return {MatrixFlipRowView} - */ - flipRowView() { - return new _flipRow2.default(this); - } +function mean(input) { + if (!is_any_array__WEBPACK_IMPORTED_MODULE_0___default()(input)) { + throw new TypeError('input must be an array'); + } - /** - * Returns a view of the matrix flipped in the column axis - * @return {MatrixFlipColumnView} - */ - flipColumnView() { - return new _flipColumn2.default(this); - } + if (input.length === 0) { + throw new TypeError('input must not be empty'); + } - /** - * Returns a view of a submatrix giving the index boundaries - * @param {number} startRow - first row index of the submatrix - * @param {number} endRow - last row index of the submatrix - * @param {number} startColumn - first column index of the submatrix - * @param {number} endColumn - last column index of the submatrix - * @return {MatrixSubView} - */ - subMatrixView(startRow, endRow, startColumn, endColumn) { - return new _sub2.default(this, startRow, endRow, startColumn, endColumn); - } + var sum = 0; - /** - * Returns a view of the cross of the row indices and the column indices - * @example - * // resulting vector is [[2], [2]] - * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1]) - * @param {Array} rowIndices - * @param {Array} columnIndices - * @return {MatrixSelectionView} - */ - selectionView(rowIndices, columnIndices) { - return new _selection2.default(this, rowIndices, columnIndices); - } + for (var i = 0; i < input.length; i++) { + sum += input[i]; + } + + return sum / input.length; +} + +/* harmony default export */ __webpack_exports__["default"] = (mean); + +/***/ }), +/* 6 */ +/***/ (function(module, exports) { + +module.exports = function (haystack, needle, comparator, low, high) { + var mid, cmp; + if (low === undefined) low = 0;else { + low = low | 0; + if (low < 0 || low >= haystack.length) throw new RangeError("invalid lower bound"); + } + if (high === undefined) high = haystack.length - 1;else { + high = high | 0; + if (high < low || high >= haystack.length) throw new RangeError("invalid upper bound"); + } + + while (low <= high) { + /* Note that "(low + high) >>> 1" may overflow, and results in a typecast + * to double (which gives the wrong results). */ + mid = low + (high - low >> 1); + cmp = +comparator(haystack[mid], needle, mid, haystack); + /* Too low. */ + + if (cmp < 0.0) low = mid + 1; + /* Too high. */ + else if (cmp > 0.0) high = mid - 1; + /* Key found. */ + else return mid; + } + /* Key not found. */ + + + return ~low; +}; + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var numberIsNan = __webpack_require__(74); + +function assertNum(x) { + if (typeof x !== 'number' || numberIsNan(x)) { + throw new TypeError('Expected a number'); + } +} + +exports.asc = function (a, b) { + assertNum(a); + assertNum(b); + return a - b; +}; - /** - * Returns a view of the row indices - * @example - * // resulting vector is [[1,2,3], [1,2,3]] - * var matrix = new Matrix([[1,2,3], [4,5,6]]).rowSelectionView([0, 0]) - * @param {Array} rowIndices - * @return {MatrixRowSelectionView} - */ - rowSelectionView(rowIndices) { - return new _rowSelection2.default(this, rowIndices); - } +exports.desc = function (a, b) { + assertNum(a); + assertNum(b); + return b - a; +}; - /** - * Returns a view of the column indices - * @example - * // resulting vector is [[2, 2], [5, 5]] - * var matrix = new Matrix([[1,2,3], [4,5,6]]).columnSelectionView([1, 1]) - * @param {Array} columnIndices - * @return {MatrixColumnSelectionView} - */ - columnSelectionView(columnIndices) { - return new _columnSelection2.default(this, columnIndices); - } +/***/ }), +/* 8 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - /** - * Calculates and returns the determinant of a matrix as a Number - * @example - * new Matrix([[1,2,3], [4,5,6]]).det() - * @return {number} - */ - det() { - if (this.isSquare()) { - var a, b, c, d; - if (this.columns === 2) { - // 2 x 2 matrix - a = this.get(0, 0); - b = this.get(0, 1); - c = this.get(1, 0); - d = this.get(1, 1); +"use strict"; +__webpack_require__.r(__webpack_exports__); - return a * d - b * c; - } else if (this.columns === 3) { - // 3 x 3 matrix - var subMatrix0, subMatrix1, subMatrix2; - subMatrix0 = this.selectionView([1, 2], [1, 2]); - subMatrix1 = this.selectionView([1, 2], [0, 2]); - subMatrix2 = this.selectionView([1, 2], [0, 1]); - a = this.get(0, 0); - b = this.get(0, 1); - c = this.get(0, 2); +// EXTERNAL MODULE: ./node_modules/ml-matrix/src/index.js + 24 modules +var src = __webpack_require__(0); - return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det(); - } else { - // general purpose determinant using the LU decomposition - return new _lu2.default(this).determinant; - } - } else { - throw Error('Determinant can only be calculated for a square matrix.'); - } - } +// EXTERNAL MODULE: ./node_modules/ml-array-mean/lib-es6/index.js +var lib_es6 = __webpack_require__(5); - /** - * Returns inverse of a matrix if it exists or the pseudoinverse - * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15) - * @return {Matrix} the (pseudo)inverted matrix. - */ - pseudoInverse(threshold) { - if (threshold === undefined) threshold = Number.EPSILON; - var svdSolution = new _svd2.default(this, { autoTranspose: true }); +// CONCATENATED MODULE: ./node_modules/ml-cart/src/utils.js - var U = svdSolution.leftSingularVectors; - var V = svdSolution.rightSingularVectors; - var s = svdSolution.diagonal; - for (var i = 0; i < s.length; i++) { - if (Math.abs(s[i]) > threshold) { - s[i] = 1.0 / s[i]; - } else { - s[i] = 0.0; - } - } +/** + * @private + * return an array of probabilities of each class + * @param {Array} array - contains the classes + * @param {number} numberOfClasses + * @return {Matrix} - rowVector of probabilities. + */ - // convert list to diagonal - s = this.constructor[Symbol.species].diag(s); - return V.mmul(s.mmul(U.transposeView())); - } +function toDiscreteDistribution(array, numberOfClasses) { + var counts = new Array(numberOfClasses).fill(0); - /** - * Creates an exact and independent copy of the matrix - * @return {Matrix} - */ - clone() { - var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns); - for (var row = 0; row < this.rows; row++) { - for (var column = 0; column < this.columns; column++) { - newMatrix.set(row, column, this.get(row, column)); - } - } - return newMatrix; - } + for (var i = 0; i < array.length; ++i) { + counts[array[i]] += 1 / array.length; } - Matrix.prototype.klass = 'Matrix'; + return src["default"].rowVector(counts); +} +/** + * @private + * Retrieves the impurity of array of predictions + * @param {Array} array - predictions. + * @return {number} Gini impurity + */ - function compareNumbers(a, b) { - return a - b; +function giniImpurity(array) { + if (array.length === 0) { + return 0; } - /* - Synonyms - */ - - Matrix.random = Matrix.rand; - Matrix.diagonal = Matrix.diag; - Matrix.prototype.diagonal = Matrix.prototype.diag; - Matrix.identity = Matrix.eye; - Matrix.prototype.negate = Matrix.prototype.neg; - Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct; - Matrix.prototype.determinant = Matrix.prototype.det; + var probabilities = toDiscreteDistribution(array, getNumberOfClasses(array))[0]; + var sum = 0.0; - /* - Add dynamically instance and static methods for mathematical operations - */ + for (var i = 0; i < probabilities.length; ++i) { + sum += probabilities[i] * probabilities[i]; + } - var inplaceOperator = ` -(function %name%(value) { - if (typeof value === 'number') return this.%name%S(value); - return this.%name%M(value); -}) -`; + return 1 - sum; +} +/** + * @private + * Return the number of classes given the array of predictions. + * @param {Array} array - predictions. + * @return {number} Number of classes. + */ - var inplaceOperatorScalar = ` -(function %name%S(value) { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) %op% value); - } - } - return this; -}) -`; +function getNumberOfClasses(array) { + return array.filter(function (val, i, arr) { + return arr.indexOf(val) === i; + }).length; +} +/** + * @private + * Calculates the Gini Gain of an array of predictions and those predictions splitted by a feature. + * @para {Array} array - Predictions + * @param {object} splitted - Object with elements "greater" and "lesser" that contains an array of predictions splitted. + * @return {number} - Gini Gain. + */ - var inplaceOperatorMatrix = ` -(function %name%M(matrix) { - matrix = this.constructor.checkMatrix(matrix); - if (this.rows !== matrix.rows || - this.columns !== matrix.columns) { - throw new RangeError('Matrices dimensions must be equal'); - } - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) %op% matrix.get(i, j)); - } - } - return this; -}) -`; - - var staticOperator = ` -(function %name%(matrix, value) { - var newMatrix = new this[Symbol.species](matrix); - return newMatrix.%name%(value); -}) -`; - - var inplaceMethod = ` -(function %name%() { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, %method%(this.get(i, j))); - } - } - return this; -}) -`; - - var staticMethod = ` -(function %name%(matrix) { - var newMatrix = new this[Symbol.species](matrix); - return newMatrix.%name%(); -}) -`; - - var inplaceMethodWithArgs = ` -(function %name%(%args%) { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, %method%(this.get(i, j), %args%)); - } - } - return this; -}) -`; - - var staticMethodWithArgs = ` -(function %name%(matrix, %args%) { - var newMatrix = new this[Symbol.species](matrix); - return newMatrix.%name%(%args%); -}) -`; - - var inplaceMethodWithOneArgScalar = ` -(function %name%S(value) { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, %method%(this.get(i, j), value)); - } - } - return this; -}) -`; - var inplaceMethodWithOneArgMatrix = ` -(function %name%M(matrix) { - matrix = this.constructor.checkMatrix(matrix); - if (this.rows !== matrix.rows || - this.columns !== matrix.columns) { - throw new RangeError('Matrices dimensions must be equal'); - } - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, %method%(this.get(i, j), matrix.get(i, j))); - } - } - return this; -}) -`; +function giniGain(array, splitted) { + var splitsImpurity = 0.0; + var splits = ['greater', 'lesser']; - var inplaceMethodWithOneArg = ` -(function %name%(value) { - if (typeof value === 'number') return this.%name%S(value); - return this.%name%M(value); -}) -`; + for (var i = 0; i < splits.length; ++i) { + var currentSplit = splitted[splits[i]]; + splitsImpurity += giniImpurity(currentSplit) * currentSplit.length / array.length; + } - var staticMethodWithOneArg = staticMethodWithArgs; + return giniImpurity(array) - splitsImpurity; +} +/** + * @private + * Calculates the squared error of a predictions values. + * @param {Array} array - predictions values + * @return {number} squared error. + */ - var operators = [ - // Arithmetic operators - ['+', 'add'], ['-', 'sub', 'subtract'], ['*', 'mul', 'multiply'], ['/', 'div', 'divide'], ['%', 'mod', 'modulus'], - // Bitwise operators - ['&', 'and'], ['|', 'or'], ['^', 'xor'], ['<<', 'leftShift'], ['>>', 'signPropagatingRightShift'], ['>>>', 'rightShift', 'zeroFillRightShift']]; +function utils_squaredError(array) { + var l = array.length; + var m = Object(lib_es6["default"])(array); + var squaredError = 0.0; - var i; - var eval2 = eval; // eslint-disable-line no-eval - for (var operator of operators) { - var inplaceOp = eval2(fillTemplateFunction(inplaceOperator, { name: operator[1], op: operator[0] })); - var inplaceOpS = eval2(fillTemplateFunction(inplaceOperatorScalar, { name: `${operator[1]}S`, op: operator[0] })); - var inplaceOpM = eval2(fillTemplateFunction(inplaceOperatorMatrix, { name: `${operator[1]}M`, op: operator[0] })); - var staticOp = eval2(fillTemplateFunction(staticOperator, { name: operator[1] })); - for (i = 1; i < operator.length; i++) { - Matrix.prototype[operator[i]] = inplaceOp; - Matrix.prototype[`${operator[i]}S`] = inplaceOpS; - Matrix.prototype[`${operator[i]}M`] = inplaceOpM; - Matrix[operator[i]] = staticOp; - } + for (var i = 0; i < l; ++i) { + var currentElement = array[i]; + squaredError += (currentElement - m) * (currentElement - m); } - var methods = [['~', 'not']]; + return squaredError; +} +/** + * @private + * Calculates the sum of squared error of the two arrays that contains the splitted values. + * @param {Array} array - this argument is no necessary but is used to fit with the main interface. + * @param {object} splitted - Object with elements "greater" and "lesser" that contains an array of predictions splitted. + * @return {number} - sum of squared errors. + */ - ['abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil', 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p', 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'].forEach(function (mathMethod) { - methods.push([`Math.${mathMethod}`, mathMethod]); - }); +function regressionError(array, splitted) { + var error = 0.0; + var splits = ['greater', 'lesser']; - for (var method of methods) { - var inplaceMeth = eval2(fillTemplateFunction(inplaceMethod, { name: method[1], method: method[0] })); - var staticMeth = eval2(fillTemplateFunction(staticMethod, { name: method[1] })); - for (i = 1; i < method.length; i++) { - Matrix.prototype[method[i]] = inplaceMeth; - Matrix[method[i]] = staticMeth; - } + for (var i = 0; i < splits.length; ++i) { + var currentSplit = splitted[splits[i]]; + error += utils_squaredError(currentSplit); } - var methodsWithArgs = [['Math.pow', 1, 'pow']]; + return error; +} +/** + * @private + * Split the training set and values from a given column of the training set if is less than a value + * @param {Matrix} X - Training set. + * @param {Array} y - Training values. + * @param {number} column - Column to split. + * @param {number} value - value to split the Training set and values. + * @return {object} - Object that contains the splitted values. + */ - for (var methodWithArg of methodsWithArgs) { - var args = 'arg0'; - for (i = 1; i < methodWithArg[1]; i++) { - args += `, arg${i}`; - } - if (methodWithArg[1] !== 1) { - var inplaceMethWithArgs = eval2(fillTemplateFunction(inplaceMethodWithArgs, { - name: methodWithArg[2], - method: methodWithArg[0], - args: args - })); - var staticMethWithArgs = eval2(fillTemplateFunction(staticMethodWithArgs, { name: methodWithArg[2], args: args })); - for (i = 2; i < methodWithArg.length; i++) { - Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs; - Matrix[methodWithArg[i]] = staticMethWithArgs; - } +function matrixSplitter(X, y, column, value) { + var lesserX = []; + var greaterX = []; + var lesserY = []; + var greaterY = []; + + for (var i = 0; i < X.rows; ++i) { + if (X[i][column] < value) { + lesserX.push(X[i]); + lesserY.push(y[i]); } else { - var tmplVar = { - name: methodWithArg[2], - args: args, - method: methodWithArg[0] - }; - var inplaceMethod2 = eval2(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar)); - var inplaceMethodS = eval2(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar)); - var inplaceMethodM = eval2(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar)); - var staticMethod2 = eval2(fillTemplateFunction(staticMethodWithOneArg, tmplVar)); - for (i = 2; i < methodWithArg.length; i++) { - Matrix.prototype[methodWithArg[i]] = inplaceMethod2; - Matrix.prototype[`${methodWithArg[i]}M`] = inplaceMethodM; - Matrix.prototype[`${methodWithArg[i]}S`] = inplaceMethodS; - Matrix[methodWithArg[i]] = staticMethod2; - } - } - } - - function fillTemplateFunction(template, values) { - for (var value in values) { - template = template.replace(new RegExp(`%${value}%`, 'g'), values[value]); + greaterX.push(X[i]); + greaterY.push(y[i]); } - return template; } - return Matrix; + return { + greaterX: greaterX, + greaterY: greaterY, + lesserX: lesserX, + lesserY: lesserY + }; } +/** + * @private + * Calculates the mean between two values + * @param {number} a + * @param {number} b + * @return {number} + */ -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +function mean(a, b) { + return (a + b) / 2; +} +/** + * @private + * Returns a list of tuples that contains the i-th element of each array. + * @param {Array} a + * @param {Array} b + * @return {Array} list of tuples. + */ +function zip(a, b) { + if (a.length !== b.length) { + throw new TypeError('Error on zip: the size of a: ' + a.length + ' is different from b: ' + b.length); + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = mean; -/** - * Computes the mean of the given values - * @param {Array} input - * @return {number} - */ -function mean(input) { - if (!Array.isArray(input)) { - throw new Error('input must be an array'); - } + var ret = new Array(a.length); - if (input.length === 0) { - throw new Error('input must not be empty'); - } + for (var i = 0; i < a.length; ++i) { + ret[i] = [a[i], b[i]]; + } - var sum = 0; - for (var i = 0; i < input.length; i++) { - sum += input[i]; - } - return sum / input.length; + return ret; } +// CONCATENATED MODULE: ./node_modules/ml-cart/src/TreeNode.js -/***/ }), -/* 9 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +const gainFunctions = { + gini: giniGain, + regression: regressionError +}; +const splitFunctions = { + mean: mean +}; +class TreeNode_TreeNode { + /** + * @private + * Constructor for a tree node given the options received on the main classes (DecisionTreeClassifier, DecisionTreeRegression) + * @param {object|TreeNode} options for loading + * @constructor + */ + constructor(options) { + // options parameters + this.kind = options.kind; + this.gainFunction = options.gainFunction; + this.splitFunction = options.splitFunction; + this.minNumSamples = options.minNumSamples; + this.maxDepth = options.maxDepth; + } + /** + * @private + * Function that retrieve the best feature to make the split. + * @param {Matrix} XTranspose - Training set transposed + * @param {Array} y - labels or values (depending of the decision tree) + * @return {object} - return tree values, the best gain, column and the split value. + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -var _index = __webpack_require__(0); + bestSplit(XTranspose, y) { + // Depending in the node tree class, we set the variables to check information gain (to classify) + // or error (for regression) + var bestGain = this.kind === 'classifier' ? -Infinity : Infinity; + var check = this.kind === 'classifier' ? (a, b) => a > b : (a, b) => a < b; + var maxColumn; + var maxValue; -var _util = __webpack_require__(13); + for (var i = 0; i < XTranspose.rows; ++i) { + var currentFeature = XTranspose[i]; + var splitValues = this.featureSplit(currentFeature, y); -/** - * @class SingularValueDecomposition - * @see https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs - * @param {Matrix} value - * @param {object} [options] - * @param {boolean} [options.computeLeftSingularVectors=true] - * @param {boolean} [options.computeRightSingularVectors=true] - * @param {boolean} [options.autoTranspose=false] - */ -class SingularValueDecomposition { - constructor(value, options = {}) { - value = _index.WrapperMatrix2D.checkMatrix(value); + for (var j = 0; j < splitValues.length; ++j) { + var currentSplitVal = splitValues[j]; + var splitted = this.split(currentFeature, y, currentSplitVal); + var gain = gainFunctions[this.gainFunction](y, splitted); - var m = value.rows; - var n = value.columns; + if (check(gain, bestGain)) { + maxColumn = i; + maxValue = currentSplitVal; + bestGain = gain; + } + } + } - var _options$computeLeftS = options.computeLeftSingularVectors, - computeLeftSingularVectors = _options$computeLeftS === undefined ? true : _options$computeLeftS, - _options$computeRight = options.computeRightSingularVectors, - computeRightSingularVectors = _options$computeRight === undefined ? true : _options$computeRight, - _options$autoTranspos = options.autoTranspose, - autoTranspose = _options$autoTranspos === undefined ? false : _options$autoTranspos; + return { + maxGain: bestGain, + maxColumn: maxColumn, + maxValue: maxValue + }; + } + /** + * @private + * Makes the split of the training labels or values from the training set feature given a split value. + * @param {Array} x - Training set feature + * @param {Array} y - Training set value or label + * @param {number} splitValue + * @return {object} + */ - var wantu = Boolean(computeLeftSingularVectors); - var wantv = Boolean(computeRightSingularVectors); + split(x, y, splitValue) { + var lesser = []; + var greater = []; - var swapped = false; - var a; - if (m < n) { - if (!autoTranspose) { - a = value.clone(); - // eslint-disable-next-line no-console - console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose'); + for (var i = 0; i < x.length; ++i) { + if (x[i] < splitValue) { + lesser.push(y[i]); } else { - a = value.transpose(); - m = a.rows; - n = a.columns; - swapped = true; - var aux = wantu; - wantu = wantv; - wantv = aux; + greater.push(y[i]); } - } else { - a = value.clone(); } - var nu = Math.min(m, n); - var ni = Math.min(m + 1, n); - var s = new Array(ni); - var U = (0, _util.getFilled2DArray)(m, nu, 0); - var V = (0, _util.getFilled2DArray)(n, n, 0); + return { + greater: greater, + lesser: lesser + }; + } + /** + * @private + * Calculates the possible points to split over the tree given a training set feature and corresponding labels or values. + * @param {Array} x - Training set feature + * @param {Array} y - Training set value or label + * @return {Array} possible split values. + */ - var e = new Array(n); - var work = new Array(m); - var si = new Array(ni); - for (var i = 0; i < ni; i++) { - si[i] = i; - }var nct = Math.min(m - 1, n); - var nrt = Math.max(0, Math.min(n - 2, m)); - var mrc = Math.max(nct, nrt); + featureSplit(x, y) { + var splitValues = []; + var arr = zip(x, y); + arr.sort(function (a, b) { + return a[0] - b[0]; + }); - for (var k = 0; k < mrc; k++) { - if (k < nct) { - s[k] = 0; - for (var _i = k; _i < m; _i++) { - s[k] = (0, _util.hypotenuse)(s[k], a[_i][k]); - } - if (s[k] !== 0) { - if (a[k][k] < 0) { - s[k] = -s[k]; - } - for (var _i2 = k; _i2 < m; _i2++) { - a[_i2][k] /= s[k]; - } - a[k][k] += 1; - } - s[k] = -s[k]; + for (var i = 1; i < arr.length; ++i) { + if (arr[i - 1][1] !== arr[i][1]) { + splitValues.push(splitFunctions[this.splitFunction](arr[i - 1][0], arr[i][0])); } + } - for (var j = k + 1; j < n; j++) { - if (k < nct && s[k] !== 0) { - var t = 0; - for (var _i3 = k; _i3 < m; _i3++) { - t += a[_i3][k] * a[_i3][j]; - } - t = -t / a[k][k]; - for (var _i4 = k; _i4 < m; _i4++) { - a[_i4][j] += t * a[_i4][k]; - } - } - e[j] = a[k][j]; - } + return splitValues; + } + /** + * @private + * Calculate the predictions of a leaf tree node given the training labels or values + * @param {Array} y + */ - if (wantu && k < nct) { - for (var _i5 = k; _i5 < m; _i5++) { - U[_i5][k] = a[_i5][k]; - } - } - if (k < nrt) { - e[k] = 0; - for (var _i6 = k + 1; _i6 < n; _i6++) { - e[k] = (0, _util.hypotenuse)(e[k], e[_i6]); - } - if (e[k] !== 0) { - if (e[k + 1] < 0) { - e[k] = 0 - e[k]; - } - for (var _i7 = k + 1; _i7 < n; _i7++) { - e[_i7] /= e[k]; - } - e[k + 1] += 1; - } - e[k] = -e[k]; - if (k + 1 < m && e[k] !== 0) { - for (var _i8 = k + 1; _i8 < m; _i8++) { - work[_i8] = 0; - } - for (var _i9 = k + 1; _i9 < m; _i9++) { - for (var _j = k + 1; _j < n; _j++) { - work[_i9] += e[_j] * a[_i9][_j]; - } - } - for (var _j2 = k + 1; _j2 < n; _j2++) { - var _t = -e[_j2] / e[k + 1]; - for (var _i10 = k + 1; _i10 < m; _i10++) { - a[_i10][_j2] += _t * work[_i10]; - } - } - } - if (wantv) { - for (var _i11 = k + 1; _i11 < n; _i11++) { - V[_i11][k] = e[_i11]; - } - } + calculatePrediction(y) { + if (this.kind === 'classifier') { + this.distribution = toDiscreteDistribution(y, getNumberOfClasses(y)); + + if (this.distribution.columns === 0) { + throw new TypeError('Error on calculate the prediction'); } + } else { + this.distribution = Object(lib_es6["default"])(y); } + } + /** + * @private + * Train a node given the training set and labels, because it trains recursively, it also receive + * the current depth of the node, parent gain to avoid infinite recursion and boolean value to check if + * the training set is transposed. + * @param {Matrix} X - Training set (could be transposed or not given transposed). + * @param {Array} y - Training labels or values. + * @param {number} currentDepth - Current depth of the node. + * @param {number} parentGain - parent node gain or error. + */ - var p = Math.min(n, m + 1); - if (nct < n) { - s[nct] = a[nct][nct]; - } - if (m < p) { - s[p - 1] = 0; - } - if (nrt + 1 < p) { - e[nrt] = a[nrt][p - 1]; + + train(X, y, currentDepth, parentGain) { + if (X.rows <= this.minNumSamples) { + this.calculatePrediction(y); + return; } - e[p - 1] = 0; - if (wantu) { - for (var _j3 = nct; _j3 < nu; _j3++) { - for (var _i12 = 0; _i12 < m; _i12++) { - U[_i12][_j3] = 0; - } - U[_j3][_j3] = 1; - } - for (var _k = nct - 1; _k >= 0; _k--) { - if (s[_k] !== 0) { - for (var _j4 = _k + 1; _j4 < nu; _j4++) { - var _t2 = 0; - for (var _i13 = _k; _i13 < m; _i13++) { - _t2 += U[_i13][_k] * U[_i13][_j4]; - } - _t2 = -_t2 / U[_k][_k]; - for (var _i14 = _k; _i14 < m; _i14++) { - U[_i14][_j4] += _t2 * U[_i14][_k]; - } - } - for (var _i15 = _k; _i15 < m; _i15++) { - U[_i15][_k] = -U[_i15][_k]; - } - U[_k][_k] = 1 + U[_k][_k]; - for (var _i16 = 0; _i16 < _k - 1; _i16++) { - U[_i16][_k] = 0; - } - } else { - for (var _i17 = 0; _i17 < m; _i17++) { - U[_i17][_k] = 0; - } - U[_k][_k] = 1; - } - } + if (parentGain === undefined) parentGain = 0.0; + var XTranspose = X.transpose(); + var split = this.bestSplit(XTranspose, y); + this.splitValue = split.maxValue; + this.splitColumn = split.maxColumn; + this.gain = split.maxGain; + var splittedMatrix = matrixSplitter(X, y, this.splitColumn, this.splitValue); + + if (currentDepth < this.maxDepth && this.gain > 0.01 && this.gain !== parentGain && splittedMatrix.lesserX.length > 0 && splittedMatrix.greaterX.length > 0) { + this.left = new TreeNode_TreeNode(this); + this.right = new TreeNode_TreeNode(this); + var lesserX = new src["default"](splittedMatrix.lesserX); + var greaterX = new src["default"](splittedMatrix.greaterX); + this.left.train(lesserX, splittedMatrix.lesserY, currentDepth + 1, this.gain); + this.right.train(greaterX, splittedMatrix.greaterY, currentDepth + 1, this.gain); + } else { + this.calculatePrediction(y); } + } + /** + * @private + * Calculates the prediction of a given element. + * @param {Array} row + * @return {number|Array} prediction + * * if a node is a classifier returns an array of probabilities of each class. + * * if a node is for regression returns a number with the prediction. + */ - if (wantv) { - for (var _k2 = n - 1; _k2 >= 0; _k2--) { - if (_k2 < nrt && e[_k2] !== 0) { - for (var _j5 = _k2 + 1; _j5 < n; _j5++) { - var _t3 = 0; - for (var _i18 = _k2 + 1; _i18 < n; _i18++) { - _t3 += V[_i18][_k2] * V[_i18][_j5]; - } - _t3 = -_t3 / V[_k2 + 1][_k2]; - for (var _i19 = _k2 + 1; _i19 < n; _i19++) { - V[_i19][_j5] += _t3 * V[_i19][_k2]; - } - } - } - for (var _i20 = 0; _i20 < n; _i20++) { - V[_i20][_k2] = 0; - } - V[_k2][_k2] = 1; + + classify(row) { + if (this.right && this.left) { + if (row[this.splitColumn] < this.splitValue) { + return this.left.classify(row); + } else { + return this.right.classify(row); } } - var pp = p - 1; - var iter = 0; - var eps = Number.EPSILON; - while (p > 0) { - var _k3 = void 0, - kase = void 0; - for (_k3 = p - 2; _k3 >= -1; _k3--) { - if (_k3 === -1) { - break; - } - var alpha = Number.MIN_VALUE + eps * Math.abs(s[_k3] + Math.abs(s[_k3 + 1])); - if (Math.abs(e[_k3]) <= alpha || Number.isNaN(e[_k3])) { - e[_k3] = 0; - break; - } + return this.distribution; + } + /** + * @private + * Set the parameter of the current node and their children. + * @param {object} node - parameters of the current node and the children. + */ + + + setNodeParameters(node) { + if (node.distribution !== undefined) { + this.distribution = node.distribution.constructor === Array ? new src["default"](node.distribution) : node.distribution; + } else { + this.distribution = undefined; + this.splitValue = node.splitValue; + this.splitColumn = node.splitColumn; + this.gain = node.gain; + this.left = new TreeNode_TreeNode(this); + this.right = new TreeNode_TreeNode(this); + + if (node.left !== {}) { + this.left.setNodeParameters(node.left); } - if (_k3 === p - 2) { - kase = 4; - } else { - var ks = void 0; - for (ks = p - 1; ks >= _k3; ks--) { - if (ks === _k3) { - break; - } - var _t4 = (ks !== p ? Math.abs(e[ks]) : 0) + (ks !== _k3 + 1 ? Math.abs(e[ks - 1]) : 0); - if (Math.abs(s[ks]) <= eps * _t4) { - s[ks] = 0; - break; - } - } - if (ks === _k3) { - kase = 3; - } else if (ks === p - 1) { - kase = 1; - } else { - kase = 2; - _k3 = ks; - } + + if (node.right !== {}) { + this.right.setNodeParameters(node.right); } + } + } - _k3++; +} +// CONCATENATED MODULE: ./node_modules/ml-cart/src/DecisionTreeClassifier.js - switch (kase) { - case 1: - { - var f = e[p - 2]; - e[p - 2] = 0; - for (var _j6 = p - 2; _j6 >= _k3; _j6--) { - var _t5 = (0, _util.hypotenuse)(s[_j6], f); - var cs = s[_j6] / _t5; - var sn = f / _t5; - s[_j6] = _t5; - if (_j6 !== _k3) { - f = -sn * e[_j6 - 1]; - e[_j6 - 1] = cs * e[_j6 - 1]; - } - if (wantv) { - for (var _i21 = 0; _i21 < n; _i21++) { - _t5 = cs * V[_i21][_j6] + sn * V[_i21][p - 1]; - V[_i21][p - 1] = -sn * V[_i21][_j6] + cs * V[_i21][p - 1]; - V[_i21][_j6] = _t5; - } - } - } - break; - } - case 2: - { - var _f = e[_k3 - 1]; - e[_k3 - 1] = 0; - for (var _j7 = _k3; _j7 < p; _j7++) { - var _t6 = (0, _util.hypotenuse)(s[_j7], _f); - var _cs = s[_j7] / _t6; - var _sn = _f / _t6; - s[_j7] = _t6; - _f = -_sn * e[_j7]; - e[_j7] = _cs * e[_j7]; - if (wantu) { - for (var _i22 = 0; _i22 < m; _i22++) { - _t6 = _cs * U[_i22][_j7] + _sn * U[_i22][_k3 - 1]; - U[_i22][_k3 - 1] = -_sn * U[_i22][_j7] + _cs * U[_i22][_k3 - 1]; - U[_i22][_j7] = _t6; - } - } - } - break; - } - case 3: - { - var scale = Math.max(Math.abs(s[p - 1]), Math.abs(s[p - 2]), Math.abs(e[p - 2]), Math.abs(s[_k3]), Math.abs(e[_k3])); - var sp = s[p - 1] / scale; - var spm1 = s[p - 2] / scale; - var epm1 = e[p - 2] / scale; - var sk = s[_k3] / scale; - var ek = e[_k3] / scale; - var b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2; - var c = sp * epm1 * (sp * epm1); - var shift = 0; - if (b !== 0 || c !== 0) { - if (b < 0) { - shift = 0 - Math.sqrt(b * b + c); - } else { - shift = Math.sqrt(b * b + c); - } - shift = c / (b + shift); - } - var _f2 = (sk + sp) * (sk - sp) + shift; - var g = sk * ek; - for (var _j8 = _k3; _j8 < p - 1; _j8++) { - var _t7 = (0, _util.hypotenuse)(_f2, g); - if (_t7 === 0) _t7 = Number.MIN_VALUE; - var _cs2 = _f2 / _t7; - var _sn2 = g / _t7; - if (_j8 !== _k3) { - e[_j8 - 1] = _t7; - } - _f2 = _cs2 * s[_j8] + _sn2 * e[_j8]; - e[_j8] = _cs2 * e[_j8] - _sn2 * s[_j8]; - g = _sn2 * s[_j8 + 1]; - s[_j8 + 1] = _cs2 * s[_j8 + 1]; - if (wantv) { - for (var _i23 = 0; _i23 < n; _i23++) { - _t7 = _cs2 * V[_i23][_j8] + _sn2 * V[_i23][_j8 + 1]; - V[_i23][_j8 + 1] = -_sn2 * V[_i23][_j8] + _cs2 * V[_i23][_j8 + 1]; - V[_i23][_j8] = _t7; - } - } - _t7 = (0, _util.hypotenuse)(_f2, g); - if (_t7 === 0) _t7 = Number.MIN_VALUE; - _cs2 = _f2 / _t7; - _sn2 = g / _t7; - s[_j8] = _t7; - _f2 = _cs2 * e[_j8] + _sn2 * s[_j8 + 1]; - s[_j8 + 1] = -_sn2 * e[_j8] + _cs2 * s[_j8 + 1]; - g = _sn2 * e[_j8 + 1]; - e[_j8 + 1] = _cs2 * e[_j8 + 1]; - if (wantu && _j8 < m - 1) { - for (var _i24 = 0; _i24 < m; _i24++) { - _t7 = _cs2 * U[_i24][_j8] + _sn2 * U[_i24][_j8 + 1]; - U[_i24][_j8 + 1] = -_sn2 * U[_i24][_j8] + _cs2 * U[_i24][_j8 + 1]; - U[_i24][_j8] = _t7; - } - } - } - e[p - 2] = _f2; - iter = iter + 1; - break; - } - case 4: - { - if (s[_k3] <= 0) { - s[_k3] = s[_k3] < 0 ? -s[_k3] : 0; - if (wantv) { - for (var _i25 = 0; _i25 <= pp; _i25++) { - V[_i25][_k3] = -V[_i25][_k3]; - } - } - } - while (_k3 < pp) { - if (s[_k3] >= s[_k3 + 1]) { - break; - } - var _t8 = s[_k3]; - s[_k3] = s[_k3 + 1]; - s[_k3 + 1] = _t8; - if (wantv && _k3 < n - 1) { - for (var _i26 = 0; _i26 < n; _i26++) { - _t8 = V[_i26][_k3 + 1]; - V[_i26][_k3 + 1] = V[_i26][_k3]; - V[_i26][_k3] = _t8; - } - } - if (wantu && _k3 < m - 1) { - for (var _i27 = 0; _i27 < m; _i27++) { - _t8 = U[_i27][_k3 + 1]; - U[_i27][_k3 + 1] = U[_i27][_k3]; - U[_i27][_k3] = _t8; - } - } - _k3++; - } - iter = 0; - p--; - break; - } - // no default - } + +const defaultOptions = { + gainFunction: 'gini', + splitFunction: 'mean', + minNumSamples: 3, + maxDepth: Infinity +}; +class DecisionTreeClassifier_DecisionTreeClassifier { + /** + * Create new Decision Tree Classifier with CART implementation with the given options + * @param {object} options + * @param {string} [options.gainFunction="gini"] - gain function to get the best split, "gini" the only one supported. + * @param {string} [options.splitFunction="mean"] - given two integers from a split feature, get the value to split, "mean" the only one supported. + * @param {number} [options.minNumSamples=3] - minimum number of samples to create a leaf node to decide a class. + * @param {number} [options.maxDepth=Infinity] - Max depth of the tree. + * @param {object} model - for load purposes. + * @constructor + */ + constructor(options, model) { + if (options === true) { + this.options = model.options; + this.root = new TreeNode_TreeNode(model.options); + this.root.setNodeParameters(model.root); + } else { + this.options = Object.assign({}, defaultOptions, options); + this.options.kind = 'classifier'; } + } + /** + * Train the decision tree with the given training set and labels. + * @param {Matrix|MatrixTransposeView|Array} trainingSet + * @param {Array} trainingLabels + */ - if (swapped) { - var tmp = V; - V = U; - U = tmp; + + train(trainingSet, trainingLabels) { + this.root = new TreeNode_TreeNode(this.options); + trainingSet = src["default"].checkMatrix(trainingSet); + this.root.train(trainingSet, trainingLabels, 0, null); + } + /** + * Predicts the output given the matrix to predict. + * @param {Matrix|MatrixTransposeView|Array} toPredict + * @return {Array} predictions + */ + + + predict(toPredict) { + toPredict = src["default"].checkMatrix(toPredict); + var predictions = new Array(toPredict.rows); + + for (var i = 0; i < toPredict.rows; ++i) { + predictions[i] = this.root.classify(toPredict.getRow(i)).maxRowIndex(0)[1]; } - this.m = m; - this.n = n; - this.s = s; - this.U = U; - this.V = V; + return predictions; } + /** + * Export the current model to JSON. + * @return {object} - Current model. + */ + + toJSON() { + return { + options: this.options, + root: this.root, + name: 'DTClassifier' + }; + } /** - * Solve a problem of least square (Ax=b) by using the SVD. Useful when A is singular. When A is not singular, it would be better to use qr.solve(value). - * Example : We search to approximate x, with A matrix shape m*n, x vector size n, b vector size m (m > n). We will use : - * var svd = SingularValueDecomposition(A); - * var x = svd.solve(b); - * @param {Matrix} value - Matrix 1D which is the vector b (in the equation Ax = b) - * @return {Matrix} - The vector x + * Load a Decision tree classifier with the given model. + * @param {object} model + * @return {DecisionTreeClassifier} */ - solve(value) { - var Y = value; - var e = this.threshold; - var scols = this.s.length; - var Ls = _index.Matrix.zeros(scols, scols); - for (var i = 0; i < scols; i++) { - if (Math.abs(this.s[i]) <= e) { - Ls[i][i] = 0; - } else { - Ls[i][i] = 1 / this.s[i]; - } + + static load(model) { + if (model.name !== 'DTClassifier') { + throw new RangeError('Invalid model: ' + model.name); } - var U = this.U; - var V = this.rightSingularVectors; + return new DecisionTreeClassifier_DecisionTreeClassifier(true, model); + } - var VL = V.mmul(Ls); - var vrows = V.rows; - var urows = U.length; - var VLU = _index.Matrix.zeros(vrows, urows); +} +// CONCATENATED MODULE: ./node_modules/ml-cart/src/DecisionTreeRegression.js - for (var _i28 = 0; _i28 < vrows; _i28++) { - for (var j = 0; j < urows; j++) { - var sum = 0; - for (var k = 0; k < scols; k++) { - sum += VL[_i28][k] * U[j][k]; - } - VLU[_i28][j] = sum; - } - } - return VLU.mmul(Y); +const DecisionTreeRegression_defaultOptions = { + gainFunction: 'regression', + splitFunction: 'mean', + minNumSamples: 3, + maxDepth: Infinity +}; +class DecisionTreeRegression_DecisionTreeRegression { + /** + * Create new Decision Tree Regression with CART implementation with the given options. + * @param {object} options + * @param {string} [options.gainFunction="regression"] - gain function to get the best split, "regression" the only one supported. + * @param {string} [options.splitFunction="mean"] - given two integers from a split feature, get the value to split, "mean" the only one supported. + * @param {number} [options.minNumSamples=3] - minimum number of samples to create a leaf node to decide a class. + * @param {number} [options.maxDepth=Infinity] - Max depth of the tree. + * @param {object} model - for load purposes. + */ + constructor(options, model) { + if (options === true) { + this.options = model.options; + this.root = new TreeNode_TreeNode(model.options); + this.root.setNodeParameters(model.root); + } else { + this.options = Object.assign({}, DecisionTreeRegression_defaultOptions, options); + this.options.kind = 'regression'; + } } + /** + * Train the decision tree with the given training set and values. + * @param {Matrix|MatrixTransposeView|Array} trainingSet + * @param {Array} trainingValues + */ + + train(trainingSet, trainingValues) { + this.root = new TreeNode_TreeNode(this.options); + if (trainingSet[0].length === undefined) trainingSet = src["default"].columnVector(trainingSet); + trainingSet = src["default"].checkMatrix(trainingSet); + this.root.train(trainingSet, trainingValues, 0); + } /** - * - * @param {Array} value - * @return {Matrix} + * Predicts the values given the matrix to predict. + * @param {Matrix|MatrixTransposeView|Array} toPredict + * @return {Array} predictions */ - solveForDiagonal(value) { - return this.solve(_index.Matrix.diag(value)); + + + predict(toPredict) { + if (toPredict[0] !== undefined && toPredict[0].length === undefined) toPredict = src["default"].columnVector(toPredict); + toPredict = src["default"].checkMatrix(toPredict); + var predictions = new Array(toPredict.rows); + + for (var i = 0; i < toPredict.rows; ++i) { + predictions[i] = this.root.classify(toPredict.getRow(i)); + } + + return predictions; } + /** + * Export the current model to JSON. + * @return {object} - Current model. + */ + + toJSON() { + return { + options: this.options, + root: this.root, + name: 'DTRegression' + }; + } /** - * Get the inverse of the matrix. We compute the inverse of a matrix using SVD when this matrix is singular or ill-conditioned. Example : - * var svd = SingularValueDecomposition(A); - * var inverseA = svd.inverse(); - * @return {Matrix} - The approximation of the inverse of the matrix + * Load a Decision tree regression with the given model. + * @param {object} model + * @return {DecisionTreeRegression} */ - inverse() { - var V = this.V; - var e = this.threshold; - var vrows = V.length; - var vcols = V[0].length; - var X = new _index.Matrix(vrows, this.s.length); - for (var i = 0; i < vrows; i++) { - for (var j = 0; j < vcols; j++) { - if (Math.abs(this.s[j]) > e) { - X[i][j] = V[i][j] / this.s[j]; - } else { - X[i][j] = 0; - } + + static load(model) { + if (model.name !== 'DTRegression') { + throw new RangeError('Invalid model:' + model.name); + } + + return new DecisionTreeRegression_DecisionTreeRegression(true, model); + } + +} +// CONCATENATED MODULE: ./node_modules/ml-cart/src/index.js +/* concated harmony reexport DecisionTreeClassifier */__webpack_require__.d(__webpack_exports__, "DecisionTreeClassifier", function() { return DecisionTreeClassifier_DecisionTreeClassifier; }); +/* concated harmony reexport DecisionTreeRegression */__webpack_require__.d(__webpack_exports__, "DecisionTreeRegression", function() { return DecisionTreeRegression_DecisionTreeRegression; }); + + + +/***/ }), +/* 9 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(is_any_array__WEBPACK_IMPORTED_MODULE_0__); + +/** + * Computes the maximum of the given values + * @param {Array} input + * @return {number} + */ + +function max(input) { + if (!is_any_array__WEBPACK_IMPORTED_MODULE_0___default()(input)) { + throw new TypeError('input must be an array'); + } + + if (input.length === 0) { + throw new TypeError('input must not be empty'); + } + + var max = input[0]; + + for (var i = 1; i < input.length; i++) { + if (input[i] > max) max = input[i]; + } + + return max; +} + +/* harmony default export */ __webpack_exports__["default"] = (max); + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const Matrix = __webpack_require__(0).Matrix; + +const GaussianKernel = __webpack_require__(55); + +const PolynomialKernel = __webpack_require__(56); + +const ANOVAKernel = __webpack_require__(57); + +const CauchyKernel = __webpack_require__(58); + +const ExponentialKernel = __webpack_require__(59); + +const HistogramKernel = __webpack_require__(60); + +const LaplacianKernel = __webpack_require__(61); + +const MultiquadraticKernel = __webpack_require__(62); + +const RationalKernel = __webpack_require__(63); + +const SigmoidKernel = __webpack_require__(64); + +const kernelType = { + gaussian: GaussianKernel, + rbf: GaussianKernel, + polynomial: PolynomialKernel, + poly: PolynomialKernel, + anova: ANOVAKernel, + cauchy: CauchyKernel, + exponential: ExponentialKernel, + histogram: HistogramKernel, + min: HistogramKernel, + laplacian: LaplacianKernel, + multiquadratic: MultiquadraticKernel, + rational: RationalKernel, + sigmoid: SigmoidKernel, + mlp: SigmoidKernel +}; + +class Kernel { + constructor(type, options) { + this.kernelType = type; + if (type === 'linear') return; + + if (typeof type === 'string') { + type = type.toLowerCase(); + var KernelConstructor = kernelType[type]; + + if (KernelConstructor) { + this.kernelFunction = new KernelConstructor(options); + } else { + throw new Error('unsupported kernel type: ' + type); } + } else if (typeof type === 'object' && typeof type.compute === 'function') { + this.kernelFunction = type; + } else { + throw new TypeError('first argument must be a valid kernel type or instance'); } + } - var U = this.U; + compute(inputs, landmarks) { + if (landmarks === undefined) { + landmarks = inputs; + } - var urows = U.length; - var ucols = U[0].length; - var Y = new _index.Matrix(vrows, urows); + if (this.kernelType === 'linear') { + var matrix = new Matrix(inputs); + return matrix.mmul(new Matrix(landmarks).transposeView()); + } + + const kernelMatrix = new Matrix(inputs.length, landmarks.length); + var i, j; - for (var _i29 = 0; _i29 < vrows; _i29++) { - for (var _j9 = 0; _j9 < urows; _j9++) { - var sum = 0; - for (var k = 0; k < ucols; k++) { - sum += X[_i29][k] * U[_j9][k]; + if (inputs === landmarks) { + // fast path, matrix is symmetric + for (i = 0; i < inputs.length; i++) { + for (j = i; j < inputs.length; j++) { + kernelMatrix[i][j] = kernelMatrix[j][i] = this.kernelFunction.compute(inputs[i], inputs[j]); + } + } + } else { + for (i = 0; i < inputs.length; i++) { + for (j = 0; j < landmarks.length; j++) { + kernelMatrix[i][j] = this.kernelFunction.compute(inputs[i], landmarks[j]); } - Y[_i29][_j9] = sum; } } - return Y; + return kernelMatrix; } - /** - * - * @return {number} - */ - get condition() { - return this.s[0] / this.s[Math.min(this.m, this.n) - 1]; +} + +module.exports = Kernel; + +/***/ }), +/* 11 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + +// EXTERNAL MODULE: ./node_modules/ml-xsadd/lib-es6/xsadd.js +var lib_es6_xsadd = __webpack_require__(19); + +// CONCATENATED MODULE: ./node_modules/ml-random/lib-es6/choice.js +const PROB_TOLERANCE = 0.00000001; + +function randomChoice(values) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + let random = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Math.random; + const { + size = 1, + replace = false, + probabilities + } = options; + let valuesArr; + let cumSum; + + if (typeof values === 'number') { + valuesArr = getArray(values); + } else { + valuesArr = values.slice(); } - /** - * - * @return {number} - */ - get norm2() { - return this.s[0]; + if (probabilities) { + if (!replace) { + throw new Error('choice with probabilities and no replacement is not implemented'); + } // check input is sane + + + if (probabilities.length !== valuesArr.length) { + throw new Error('the length of probabilities option should be equal to the number of choices'); + } + + cumSum = [probabilities[0]]; + + for (let i = 1; i < probabilities.length; i++) { + cumSum[i] = cumSum[i - 1] + probabilities[i]; + } + + if (Math.abs(1 - cumSum[cumSum.length - 1]) > PROB_TOLERANCE) { + throw new Error("probabilities should sum to 1, but instead sums to ".concat(cumSum[cumSum.length - 1])); + } } - /** - * - * @return {number} - */ - get rank() { - var tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON; - var r = 0; - var s = this.s; - for (var i = 0, ii = s.length; i < ii; i++) { - if (s[i] > tol) { - r++; - } + if (replace === false && size > valuesArr.length) { + throw new Error('size option is too large'); + } + + const result = []; + + for (let i = 0; i < size; i++) { + const index = randomIndex(valuesArr.length, random, cumSum); + result.push(valuesArr[index]); + + if (!replace) { + valuesArr.splice(index, 1); } - return r; } - /** - * - * @return {Array} - */ - get diagonal() { - return this.s; + return result; +} + +function getArray(n) { + const arr = []; + + for (let i = 0; i < n; i++) { + arr.push(i); } - /** - * - * @return {number} - */ - get threshold() { - return Number.EPSILON / 2 * Math.max(this.m, this.n) * this.s[0]; + return arr; +} + +function randomIndex(n, random, cumSum) { + const rand = random(); + + if (!cumSum) { + return Math.floor(rand * n); + } else { + let idx = 0; + + while (rand > cumSum[idx]) { + idx++; + } + + return idx; } +} + +/* harmony default export */ var choice = (randomChoice); +// CONCATENATED MODULE: ./node_modules/ml-random/lib-es6/index.js +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return lib_es6_Random; }); +// tslint:disable-next-line + + +/** + * @classdesc Random class + */ +class lib_es6_Random { /** - * - * @return {Matrix} + * @param [seedOrRandom=Math.random] - Control the random number generator used by the Random class instance. Pass a random number generator function with a uniform distribution over the half-open interval [0, 1[. If seed will pass it to ml-xsadd to create a seeded random number generator. If undefined will use Math.random. */ - get leftSingularVectors() { - if (!_index.Matrix.isMatrix(this.U)) { - this.U = new _index.Matrix(this.U); + constructor() { + let seedOrRandom = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Math.random; + + if (typeof seedOrRandom === 'number') { + const xsadd = new lib_es6_xsadd["default"](seedOrRandom); + this.randomGenerator = xsadd.random; + } else { + this.randomGenerator = seedOrRandom; + } + } + + choice(values, options) { + if (typeof values === 'number') { + return choice(values, options, this.randomGenerator); } - return this.U; + + return choice(values, options, this.randomGenerator); } + /** + * Draw a random number from a uniform distribution on [0,1) + * @return The random number + */ + + random() { + return this.randomGenerator(); + } /** - * - * @return {Matrix} + * Draw a random integer from a uniform distribution on [low, high). If only low is specified, the number is drawn on [0, low) + * @param low - The lower bound of the uniform distribution interval. + * @param high - The higher bound of the uniform distribution interval. */ - get rightSingularVectors() { - if (!_index.Matrix.isMatrix(this.V)) { - this.V = new _index.Matrix(this.V); + + + randInt(low, high) { + if (high === undefined) { + high = low; + low = 0; } - return this.V; - } + return low + Math.floor(this.randomGenerator() * (high - low)); + } /** - * - * @return {Matrix} + * Draw several random number from a uniform distribution on [0, 1) + * @param size - The number of number to draw + * @return - The list of drawn numbers. */ - get diagonalMatrix() { - return _index.Matrix.diag(this.s); - } -} -exports.default = SingularValueDecomposition; -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + randomSample(size) { + const result = []; + for (let i = 0; i < size; i++) { + result.push(this.random()); + } -var arrayStat = __webpack_require__(27); + return result; + } -function compareNumbers(a, b) { - return a - b; } -exports.max = function max(matrix) { - var max = -Infinity; - for (var i = 0; i < matrix.length; i++) { - for (var j = 0; j < matrix[i].length; j++) { - if (matrix[i][j] > max) max = matrix[i][j]; - } - } - return max; -}; - -exports.min = function min(matrix) { - var min = Infinity; - for (var i = 0; i < matrix.length; i++) { - for (var j = 0; j < matrix[i].length; j++) { - if (matrix[i][j] < min) min = matrix[i][j]; - } - } - return min; -}; +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { -exports.minMax = function minMax(matrix) { - var min = Infinity; - var max = -Infinity; - for (var i = 0; i < matrix.length; i++) { - for (var j = 0; j < matrix[i].length; j++) { - if (matrix[i][j] < min) min = matrix[i][j]; - if (matrix[i][j] > max) max = matrix[i][j]; - } - } - return { - min: min, - max: max - }; -}; +var __WEBPACK_AMD_DEFINE_RESULT__;/*jshint eqnull:true*/ +(function (root) { + "use strict"; -exports.entropy = function entropy(matrix, eps) { - if (typeof eps === 'undefined') { - eps = 0; - } - var sum = 0, - l1 = matrix.length, - l2 = matrix[0].length; - for (var i = 0; i < l1; i++) { - for (var j = 0; j < l2; j++) { - sum += matrix[i][j] * Math.log(matrix[i][j] + eps); - } - } - return -sum; -}; + var GLOBAL_KEY = "Random"; + var imul = typeof Math.imul !== "function" || Math.imul(0xffffffff, 5) !== -5 ? function (a, b) { + var ah = a >>> 16 & 0xffff; + var al = a & 0xffff; + var bh = b >>> 16 & 0xffff; + var bl = b & 0xffff; // the shift by 0 fixes the sign on the high part + // the final |0 converts the unsigned value into a signed value -exports.mean = function mean(matrix, dimension) { - if (typeof dimension === 'undefined') { - dimension = 0; - } - var rows = matrix.length, - cols = matrix[0].length, - theMean, - N, - i, - j; - - if (dimension === -1) { - theMean = [0]; - N = rows * cols; - for (i = 0; i < rows; i++) { - for (j = 0; j < cols; j++) { - theMean[0] += matrix[i][j]; - } - } - theMean[0] /= N; - } else if (dimension === 0) { - theMean = new Array(cols); - N = rows; - for (j = 0; j < cols; j++) { - theMean[j] = 0; - for (i = 0; i < rows; i++) { - theMean[j] += matrix[i][j]; - } - theMean[j] /= N; - } - } else if (dimension === 1) { - theMean = new Array(rows); - N = cols; - for (j = 0; j < rows; j++) { - theMean[j] = 0; - for (i = 0; i < cols; i++) { - theMean[j] += matrix[j][i]; - } - theMean[j] /= N; - } - } else { - throw new Error('Invalid dimension'); - } - return theMean; -}; + return al * bl + (ah * bl + al * bh << 16 >>> 0) | 0; + } : Math.imul; + var stringRepeat = typeof String.prototype.repeat === "function" && "x".repeat(3) === "xxx" ? function (x, y) { + return x.repeat(y); + } : function (pattern, count) { + var result = ""; -exports.sum = function sum(matrix, dimension) { - if (typeof dimension === 'undefined') { - dimension = 0; - } - var rows = matrix.length, - cols = matrix[0].length, - theSum, - i, - j; - - if (dimension === -1) { - theSum = [0]; - for (i = 0; i < rows; i++) { - for (j = 0; j < cols; j++) { - theSum[0] += matrix[i][j]; - } - } - } else if (dimension === 0) { - theSum = new Array(cols); - for (j = 0; j < cols; j++) { - theSum[j] = 0; - for (i = 0; i < rows; i++) { - theSum[j] += matrix[i][j]; - } - } - } else if (dimension === 1) { - theSum = new Array(rows); - for (j = 0; j < rows; j++) { - theSum[j] = 0; - for (i = 0; i < cols; i++) { - theSum[j] += matrix[j][i]; - } - } - } else { - throw new Error('Invalid dimension'); - } - return theSum; -}; + while (count > 0) { + if (count & 1) { + result += pattern; + } -exports.product = function product(matrix, dimension) { - if (typeof dimension === 'undefined') { - dimension = 0; - } - var rows = matrix.length, - cols = matrix[0].length, - theProduct, - i, - j; - - if (dimension === -1) { - theProduct = [1]; - for (i = 0; i < rows; i++) { - for (j = 0; j < cols; j++) { - theProduct[0] *= matrix[i][j]; - } - } - } else if (dimension === 0) { - theProduct = new Array(cols); - for (j = 0; j < cols; j++) { - theProduct[j] = 1; - for (i = 0; i < rows; i++) { - theProduct[j] *= matrix[i][j]; - } - } - } else if (dimension === 1) { - theProduct = new Array(rows); - for (j = 0; j < rows; j++) { - theProduct[j] = 1; - for (i = 0; i < cols; i++) { - theProduct[j] *= matrix[j][i]; - } - } - } else { - throw new Error('Invalid dimension'); + count >>= 1; + pattern += pattern; } - return theProduct; -}; -exports.standardDeviation = function standardDeviation(matrix, means, unbiased) { - var vari = exports.variance(matrix, means, unbiased), - l = vari.length; - for (var i = 0; i < l; i++) { - vari[i] = Math.sqrt(vari[i]); - } - return vari; -}; + return result; + }; -exports.variance = function variance(matrix, means, unbiased) { - if (typeof unbiased === 'undefined') { - unbiased = true; - } - means = means || exports.mean(matrix); - var rows = matrix.length; - if (rows === 0) return []; - var cols = matrix[0].length; - var vari = new Array(cols); - - for (var j = 0; j < cols; j++) { - var sum1 = 0, - sum2 = 0, - x = 0; - for (var i = 0; i < rows; i++) { - x = matrix[i][j] - means[j]; - sum1 += x; - sum2 += x * x; - } - if (unbiased) { - vari[j] = (sum2 - sum1 * sum1 / rows) / (rows - 1); - } else { - vari[j] = (sum2 - sum1 * sum1 / rows) / rows; - } + function Random(engine) { + if (!(this instanceof Random)) { + return new Random(engine); } - return vari; -}; -exports.median = function median(matrix) { - var rows = matrix.length, - cols = matrix[0].length; - var medians = new Array(cols); - - for (var i = 0; i < cols; i++) { - var data = new Array(rows); - for (var j = 0; j < rows; j++) { - data[j] = matrix[j][i]; - } - data.sort(compareNumbers); - var N = data.length; - if (N % 2 === 0) { - medians[i] = (data[N / 2] + data[N / 2 - 1]) * 0.5; - } else { - medians[i] = data[Math.floor(N / 2)]; - } + if (engine == null) { + engine = Random.engines.nativeMath; + } else if (typeof engine !== "function") { + throw new TypeError("Expected engine to be a function, got " + typeof engine); } - return medians; -}; - -exports.mode = function mode(matrix) { - var rows = matrix.length, - cols = matrix[0].length, - modes = new Array(cols), - i, - j; - for (i = 0; i < cols; i++) { - var itemCount = new Array(rows); - for (var k = 0; k < rows; k++) { - itemCount[k] = 0; - } - var itemArray = new Array(rows); - var count = 0; - - for (j = 0; j < rows; j++) { - var index = itemArray.indexOf(matrix[j][i]); - if (index >= 0) { - itemCount[index]++; - } else { - itemArray[count] = matrix[j][i]; - itemCount[count] = 1; - count++; - } - } - var maxValue = 0, - maxIndex = 0; - for (j = 0; j < count; j++) { - if (itemCount[j] > maxValue) { - maxValue = itemCount[j]; - maxIndex = j; - } - } + this.engine = engine; + } - modes[i] = itemArray[maxIndex]; - } - return modes; -}; + var proto = Random.prototype; + Random.engines = { + nativeMath: function nativeMath() { + return Math.random() * 0x100000000 | 0; + }, + mt19937: function (Int32Array) { + // http://en.wikipedia.org/wiki/Mersenne_twister + function refreshData(data) { + var k = 0; + var tmp = 0; -exports.skewness = function skewness(matrix, unbiased) { - if (typeof unbiased === 'undefined') unbiased = true; - var means = exports.mean(matrix); - var n = matrix.length, - l = means.length; - var skew = new Array(l); - - for (var j = 0; j < l; j++) { - var s2 = 0, - s3 = 0; - for (var i = 0; i < n; i++) { - var dev = matrix[i][j] - means[j]; - s2 += dev * dev; - s3 += dev * dev * dev; + for (; (k | 0) < 227; k = k + 1 | 0) { + tmp = data[k] & 0x80000000 | data[k + 1 | 0] & 0x7fffffff; + data[k] = data[k + 397 | 0] ^ tmp >>> 1 ^ (tmp & 0x1 ? 0x9908b0df : 0); } - var m2 = s2 / n; - var m3 = s3 / n; - var g = m3 / Math.pow(m2, 3 / 2); - - if (unbiased) { - var a = Math.sqrt(n * (n - 1)); - var b = n - 2; - skew[j] = a / b * g; - } else { - skew[j] = g; + for (; (k | 0) < 623; k = k + 1 | 0) { + tmp = data[k] & 0x80000000 | data[k + 1 | 0] & 0x7fffffff; + data[k] = data[k - 227 | 0] ^ tmp >>> 1 ^ (tmp & 0x1 ? 0x9908b0df : 0); } - } - return skew; -}; -exports.kurtosis = function kurtosis(matrix, unbiased) { - if (typeof unbiased === 'undefined') unbiased = true; - var means = exports.mean(matrix); - var n = matrix.length, - m = matrix[0].length; - var kurt = new Array(m); - - for (var j = 0; j < m; j++) { - var s2 = 0, - s4 = 0; - for (var i = 0; i < n; i++) { - var dev = matrix[i][j] - means[j]; - s2 += dev * dev; - s4 += dev * dev * dev * dev; - } - var m2 = s2 / n; - var m4 = s4 / n; - - if (unbiased) { - var v = s2 / (n - 1); - var a = n * (n + 1) / ((n - 1) * (n - 2) * (n - 3)); - var b = s4 / (v * v); - var c = (n - 1) * (n - 1) / ((n - 2) * (n - 3)); - kurt[j] = a * b - 3 * c; - } else { - kurt[j] = m4 / (m2 * m2) - 3; - } - } - return kurt; -}; + tmp = data[623] & 0x80000000 | data[0] & 0x7fffffff; + data[623] = data[396] ^ tmp >>> 1 ^ (tmp & 0x1 ? 0x9908b0df : 0); + } -exports.standardError = function standardError(matrix) { - var samples = matrix.length; - var standardDeviations = exports.standardDeviation(matrix); - var l = standardDeviations.length; - var standardErrors = new Array(l); - var sqrtN = Math.sqrt(samples); + function temper(value) { + value ^= value >>> 11; + value ^= value << 7 & 0x9d2c5680; + value ^= value << 15 & 0xefc60000; + return value ^ value >>> 18; + } - for (var i = 0; i < l; i++) { - standardErrors[i] = standardDeviations[i] / sqrtN; - } - return standardErrors; -}; + function seedWithArray(data, source) { + var i = 1; + var j = 0; + var sourceLength = source.length; + var k = Math.max(sourceLength, 624) | 0; + var previous = data[0] | 0; -exports.covariance = function covariance(matrix, dimension) { - return exports.scatter(matrix, undefined, dimension); -}; + for (; (k | 0) > 0; --k) { + data[i] = previous = (data[i] ^ imul(previous ^ previous >>> 30, 0x0019660d)) + (source[j] | 0) + (j | 0) | 0; + i = i + 1 | 0; + ++j; -exports.scatter = function scatter(matrix, divisor, dimension) { - if (typeof dimension === 'undefined') { - dimension = 0; - } - if (typeof divisor === 'undefined') { - if (dimension === 0) { - divisor = matrix.length - 1; - } else if (dimension === 1) { - divisor = matrix[0].length - 1; - } - } - var means = exports.mean(matrix, dimension); - var rows = matrix.length; - if (rows === 0) { - return [[]]; - } - var cols = matrix[0].length, - cov, - i, - j, - s, - k; + if ((i | 0) > 623) { + data[0] = data[623]; + i = 1; + } - if (dimension === 0) { - cov = new Array(cols); - for (i = 0; i < cols; i++) { - cov[i] = new Array(cols); - } - for (i = 0; i < cols; i++) { - for (j = i; j < cols; j++) { - s = 0; - for (k = 0; k < rows; k++) { - s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]); - } - s /= divisor; - cov[i][j] = s; - cov[j][i] = s; - } - } - } else if (dimension === 1) { - cov = new Array(rows); - for (i = 0; i < rows; i++) { - cov[i] = new Array(rows); - } - for (i = 0; i < rows; i++) { - for (j = i; j < rows; j++) { - s = 0; - for (k = 0; k < cols; k++) { - s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]); - } - s /= divisor; - cov[i][j] = s; - cov[j][i] = s; - } + if (j >= sourceLength) { + j = 0; + } } - } else { - throw new Error('Invalid dimension'); - } - return cov; -}; + for (k = 623; (k | 0) > 0; --k) { + data[i] = previous = (data[i] ^ imul(previous ^ previous >>> 30, 0x5d588b65)) - i | 0; + i = i + 1 | 0; -exports.correlation = function correlation(matrix) { - var means = exports.mean(matrix), - standardDeviations = exports.standardDeviation(matrix, true, means), - scores = exports.zScores(matrix, means, standardDeviations), - rows = matrix.length, - cols = matrix[0].length, - i, - j; - - var cor = new Array(cols); - for (i = 0; i < cols; i++) { - cor[i] = new Array(cols); - } - for (i = 0; i < cols; i++) { - for (j = i; j < cols; j++) { - var c = 0; - for (var k = 0, l = scores.length; k < l; k++) { - c += scores[k][j] * scores[k][i]; - } - c /= rows - 1; - cor[i][j] = c; - cor[j][i] = c; + if ((i | 0) > 623) { + data[0] = data[623]; + i = 1; + } } - } - return cor; -}; -exports.zScores = function zScores(matrix, means, standardDeviations) { - means = means || exports.mean(matrix); - if (typeof standardDeviations === 'undefined') standardDeviations = exports.standardDeviation(matrix, true, means); - return exports.standardize(exports.center(matrix, means, false), standardDeviations, true); -}; + data[0] = 0x80000000; + } -exports.center = function center(matrix, means, inPlace) { - means = means || exports.mean(matrix); - var result = matrix, - l = matrix.length, - i, - j, - jj; - - if (!inPlace) { - result = new Array(l); - for (i = 0; i < l; i++) { - result[i] = new Array(matrix[i].length); - } - } + function mt19937() { + var data = new Int32Array(624); + var index = 0; + var uses = 0; - for (i = 0; i < l; i++) { - var row = result[i]; - for (j = 0, jj = row.length; j < jj; j++) { - row[j] = matrix[i][j] - means[j]; - } - } - return result; -}; + function next() { + if ((index | 0) >= 624) { + refreshData(data); + index = 0; + } -exports.standardize = function standardize(matrix, standardDeviations, inPlace) { - if (typeof standardDeviations === 'undefined') standardDeviations = exports.standardDeviation(matrix); - var result = matrix, - l = matrix.length, - i, - j, - jj; - - if (!inPlace) { - result = new Array(l); - for (i = 0; i < l; i++) { - result[i] = new Array(matrix[i].length); + var value = data[index]; + index = index + 1 | 0; + uses += 1; + return temper(value) | 0; } - } - for (i = 0; i < l; i++) { - var resultRow = result[i]; - var sourceRow = matrix[i]; - for (j = 0, jj = resultRow.length; j < jj; j++) { - if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) { - resultRow[j] = sourceRow[j] / standardDeviations[j]; - } - } - } - return result; -}; + next.getUseCount = function () { + return uses; + }; -exports.weightedVariance = function weightedVariance(matrix, weights) { - var means = exports.mean(matrix); - var rows = matrix.length; - if (rows === 0) return []; - var cols = matrix[0].length; - var vari = new Array(cols); - - for (var j = 0; j < cols; j++) { - var sum = 0; - var a = 0, - b = 0; - - for (var i = 0; i < rows; i++) { - var z = matrix[i][j] - means[j]; - var w = weights[i]; - - sum += w * (z * z); - b += w; - a += w * w; - } + next.discard = function (count) { + uses += count; - vari[j] = sum * (b / (b * b - a)); - } + if ((index | 0) >= 624) { + refreshData(data); + index = 0; + } - return vari; -}; + while (count - index > 624) { + count -= 624 - index; + refreshData(data); + index = 0; + } -exports.weightedMean = function weightedMean(matrix, weights, dimension) { - if (typeof dimension === 'undefined') { - dimension = 0; - } - var rows = matrix.length; - if (rows === 0) return []; - var cols = matrix[0].length, - means, - i, - ii, - j, - w, - row; + index = index + count | 0; + return next; + }; - if (dimension === 0) { - means = new Array(cols); - for (i = 0; i < cols; i++) { - means[i] = 0; - } - for (i = 0; i < rows; i++) { - row = matrix[i]; - w = weights[i]; - for (j = 0; j < cols; j++) { - means[j] += row[j] * w; - } - } - } else if (dimension === 1) { - means = new Array(rows); - for (i = 0; i < rows; i++) { - means[i] = 0; - } - for (j = 0; j < rows; j++) { - row = matrix[j]; - w = weights[j]; - for (i = 0; i < cols; i++) { - means[j] += row[i] * w; - } - } - } else { - throw new Error('Invalid dimension'); - } + next.seed = function (initial) { + var previous = 0; + data[0] = previous = initial | 0; - var weightSum = arrayStat.sum(weights); - if (weightSum !== 0) { - for (i = 0, ii = means.length; i < ii; i++) { - means[i] /= weightSum; - } - } - return means; -}; + for (var i = 1; i < 624; i = i + 1 | 0) { + data[i] = previous = imul(previous ^ previous >>> 30, 0x6c078965) + i | 0; + } -exports.weightedCovariance = function weightedCovariance(matrix, weights, means, dimension) { - dimension = dimension || 0; - means = means || exports.weightedMean(matrix, weights, dimension); - var s1 = 0, - s2 = 0; - for (var i = 0, ii = weights.length; i < ii; i++) { - s1 += weights[i]; - s2 += weights[i] * weights[i]; - } - var factor = s1 / (s1 * s1 - s2); - return exports.weightedScatter(matrix, weights, means, factor, dimension); -}; + index = 624; + uses = 0; + return next; + }; -exports.weightedScatter = function weightedScatter(matrix, weights, means, factor, dimension) { - dimension = dimension || 0; - means = means || exports.weightedMean(matrix, weights, dimension); - if (typeof factor === 'undefined') { - factor = 1; - } - var rows = matrix.length; - if (rows === 0) { - return [[]]; - } - var cols = matrix[0].length, - cov, - i, - j, - k, - s; + next.seedWithArray = function (source) { + next.seed(0x012bd6aa); + seedWithArray(data, source); + return next; + }; - if (dimension === 0) { - cov = new Array(cols); - for (i = 0; i < cols; i++) { - cov[i] = new Array(cols); - } - for (i = 0; i < cols; i++) { - for (j = i; j < cols; j++) { - s = 0; - for (k = 0; k < rows; k++) { - s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]); - } - cov[i][j] = s * factor; - cov[j][i] = s * factor; - } - } - } else if (dimension === 1) { - cov = new Array(rows); - for (i = 0; i < rows; i++) { - cov[i] = new Array(rows); - } - for (i = 0; i < rows; i++) { - for (j = i; j < rows; j++) { - s = 0; - for (k = 0; k < cols; k++) { - s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]); - } - cov[i][j] = s * factor; - cov[j][i] = s * factor; - } - } - } else { - throw new Error('Invalid dimension'); - } + next.autoSeed = function () { + return next.seedWithArray(Random.generateEntropyArray()); + }; - return cov; -}; + return next; + } -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { + return mt19937; + }(typeof Int32Array === "function" ? Int32Array : Array), + browserCrypto: typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function" && typeof Int32Array === "function" ? function () { + var data = null; + var index = 128; + return function () { + if (index >= 128) { + if (data === null) { + data = new Int32Array(128); + } -"use strict"; + crypto.getRandomValues(data); + index = 0; + } + return data[index++] | 0; + }; + }() : null + }; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = max; -/** - * Computes the maximum of the given values - * @param {Array} input - * @return {number} - */ -function max(input) { - if (!Array.isArray(input)) { - throw new Error('input must be an array'); - } + Random.generateEntropyArray = function () { + var array = []; + var engine = Random.engines.nativeMath; - if (input.length === 0) { - throw new Error('input must not be empty'); + for (var i = 0; i < 16; ++i) { + array[i] = engine() | 0; } - var max = input[0]; - for (var i = 1; i < input.length; i++) { - if (input[i] > max) max = input[i]; - } - return max; -} + array.push(new Date().getTime() | 0); + return array; + }; -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { + function returnValue(value) { + return function () { + return value; + }; + } // [-0x80000000, 0x7fffffff] -"use strict"; + Random.int32 = function (engine) { + return engine() | 0; + }; + + proto.int32 = function () { + return Random.int32(this.engine); + }; // [0, 0xffffffff] -Object.defineProperty(exports, "__esModule", { - value: true -}); -var _index = __webpack_require__(0); + Random.uint32 = function (engine) { + return engine() >>> 0; + }; -/** - * @class LuDecomposition - * @link https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs - * @param {Matrix} matrix - */ -class LuDecomposition { - constructor(matrix) { - matrix = _index.WrapperMatrix2D.checkMatrix(matrix); + proto.uint32 = function () { + return Random.uint32(this.engine); + }; // [0, 0x1fffffffffffff] - var lu = matrix.clone(); - var rows = lu.rows; - var columns = lu.columns; - var pivotVector = new Array(rows); - var pivotSign = 1; - var i, j, k, p, s, t, v; - var LUcolj, kmax; - for (i = 0; i < rows; i++) { - pivotVector[i] = i; - } + Random.uint53 = function (engine) { + var high = engine() & 0x1fffff; + var low = engine() >>> 0; + return high * 0x100000000 + low; + }; - LUcolj = new Array(rows); + proto.uint53 = function () { + return Random.uint53(this.engine); + }; // [0, 0x20000000000000] - for (j = 0; j < columns; j++) { - for (i = 0; i < rows; i++) { - LUcolj[i] = lu.get(i, j); - } - for (i = 0; i < rows; i++) { - kmax = Math.min(i, j); - s = 0; - for (k = 0; k < kmax; k++) { - s += lu.get(i, k) * LUcolj[k]; - } - LUcolj[i] -= s; - lu.set(i, j, LUcolj[i]); - } + Random.uint53Full = function (engine) { + while (true) { + var high = engine() | 0; - p = j; - for (i = j + 1; i < rows; i++) { - if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) { - p = i; + if (high & 0x200000) { + if ((high & 0x3fffff) === 0x200000 && (engine() | 0) === 0) { + return 0x20000000000000; } + } else { + var low = engine() >>> 0; + return (high & 0x1fffff) * 0x100000000 + low; } + } + }; - if (p !== j) { - for (k = 0; k < columns; k++) { - t = lu.get(p, k); - lu.set(p, k, lu.get(j, k)); - lu.set(j, k, t); - } + proto.uint53Full = function () { + return Random.uint53Full(this.engine); + }; // [-0x20000000000000, 0x1fffffffffffff] - v = pivotVector[p]; - pivotVector[p] = pivotVector[j]; - pivotVector[j] = v; - pivotSign = -pivotSign; - } + Random.int53 = function (engine) { + var high = engine() | 0; + var low = engine() >>> 0; + return (high & 0x1fffff) * 0x100000000 + low + (high & 0x200000 ? -0x20000000000000 : 0); + }; - if (j < rows && lu.get(j, j) !== 0) { - for (i = j + 1; i < rows; i++) { - lu.set(i, j, lu.get(i, j) / lu.get(j, j)); + proto.int53 = function () { + return Random.int53(this.engine); + }; // [-0x20000000000000, 0x20000000000000] + + + Random.int53Full = function (engine) { + while (true) { + var high = engine() | 0; + + if (high & 0x400000) { + if ((high & 0x7fffff) === 0x400000 && (engine() | 0) === 0) { + return 0x20000000000000; } + } else { + var low = engine() >>> 0; + return (high & 0x1fffff) * 0x100000000 + low + (high & 0x200000 ? -0x20000000000000 : 0); } } + }; - this.LU = lu; - this.pivotVector = pivotVector; - this.pivotSign = pivotSign; + proto.int53Full = function () { + return Random.int53Full(this.engine); + }; + + function add(generate, addend) { + if (addend === 0) { + return generate; + } else { + return function (engine) { + return generate(engine) + addend; + }; + } } - /** - * - * @return {boolean} - */ - isSingular() { - var data = this.LU; - var col = data.columns; - for (var j = 0; j < col; j++) { - if (data[j][j] === 0) { - return true; - } + Random.integer = function () { + function isPowerOfTwoMinusOne(value) { + return (value + 1 & value) === 0; + } + + function bitmask(masking) { + return function (engine) { + return engine() & masking; + }; } - return false; - } - /** - * - * @param {Matrix} value - * @return {Matrix} - */ - solve(value) { - value = _index.Matrix.checkMatrix(value); + function downscaleToLoopCheckedRange(range) { + var extendedRange = range + 1; + var maximum = extendedRange * Math.floor(0x100000000 / extendedRange); + return function (engine) { + var value = 0; - var lu = this.LU; - var rows = lu.rows; + do { + value = engine() >>> 0; + } while (value >= maximum); - if (rows !== value.rows) { - throw new Error('Invalid matrix dimensions'); - } - if (this.isSingular()) { - throw new Error('LU matrix is singular'); + return value % extendedRange; + }; } - var count = value.columns; - var X = value.subMatrixRow(this.pivotVector, 0, count - 1); - var columns = lu.columns; - var i, j, k; - - for (k = 0; k < columns; k++) { - for (i = k + 1; i < columns; i++) { - for (j = 0; j < count; j++) { - X[i][j] -= X[k][j] * lu[i][k]; - } + function downscaleToRange(range) { + if (isPowerOfTwoMinusOne(range)) { + return bitmask(range); + } else { + return downscaleToLoopCheckedRange(range); } } - for (k = columns - 1; k >= 0; k--) { - for (j = 0; j < count; j++) { - X[k][j] /= lu[k][k]; - } - for (i = 0; i < k; i++) { - for (j = 0; j < count; j++) { - X[i][j] -= X[k][j] * lu[i][k]; - } - } + + function isEvenlyDivisibleByMaxInt32(value) { + return (value | 0) === 0; } - return X; - } - /** - * - * @return {number} - */ - get determinant() { - var data = this.LU; - if (!data.isSquare()) { - throw new Error('Matrix must be square'); + function upscaleWithHighMasking(masking) { + return function (engine) { + var high = engine() & masking; + var low = engine() >>> 0; + return high * 0x100000000 + low; + }; } - var determinant = this.pivotSign; - var col = data.columns; - for (var j = 0; j < col; j++) { - determinant *= data[j][j]; + + function upscaleToLoopCheckedRange(extendedRange) { + var maximum = extendedRange * Math.floor(0x20000000000000 / extendedRange); + return function (engine) { + var ret = 0; + + do { + var high = engine() & 0x1fffff; + var low = engine() >>> 0; + ret = high * 0x100000000 + low; + } while (ret >= maximum); + + return ret % extendedRange; + }; } - return determinant; - } - /** - * - * @return {Matrix} - */ - get lowerTriangularMatrix() { - var data = this.LU; - var rows = data.rows; - var columns = data.columns; - var X = new _index.Matrix(rows, columns); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - if (i > j) { - X[i][j] = data[i][j]; - } else if (i === j) { - X[i][j] = 1; - } else { - X[i][j] = 0; + function upscaleWithinU53(range) { + var extendedRange = range + 1; + + if (isEvenlyDivisibleByMaxInt32(extendedRange)) { + var highRange = (extendedRange / 0x100000000 | 0) - 1; + + if (isPowerOfTwoMinusOne(highRange)) { + return upscaleWithHighMasking(highRange); } } + + return upscaleToLoopCheckedRange(extendedRange); } - return X; - } - /** - * - * @return {Matrix} - */ - get upperTriangularMatrix() { - var data = this.LU; - var rows = data.rows; - var columns = data.columns; - var X = new _index.Matrix(rows, columns); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - if (i <= j) { - X[i][j] = data[i][j]; - } else { - X[i][j] = 0; - } - } + function upscaleWithinI53AndLoopCheck(min, max) { + return function (engine) { + var ret = 0; + + do { + var high = engine() | 0; + var low = engine() >>> 0; + ret = (high & 0x1fffff) * 0x100000000 + low + (high & 0x200000 ? -0x20000000000000 : 0); + } while (ret < min || ret > max); + + return ret; + }; } - return X; - } - /** - * - * @return {Array} - */ - get pivotPermutationVector() { - return this.pivotVector.slice(); - } -} -exports.default = LuDecomposition; + return function (min, max) { + min = Math.floor(min); + max = Math.floor(max); -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { + if (min < -0x20000000000000 || !isFinite(min)) { + throw new RangeError("Expected min to be at least " + -0x20000000000000); + } else if (max > 0x20000000000000 || !isFinite(max)) { + throw new RangeError("Expected max to be at most " + 0x20000000000000); + } -"use strict"; + var range = max - min; + if (range <= 0 || !isFinite(range)) { + return returnValue(min); + } else if (range === 0xffffffff) { + if (min === 0) { + return Random.uint32; + } else { + return add(Random.int32, min + 0x80000000); + } + } else if (range < 0xffffffff) { + return add(downscaleToRange(range), min); + } else if (range === 0x1fffffffffffff) { + return add(Random.uint53, min); + } else if (range < 0x1fffffffffffff) { + return add(upscaleWithinU53(range), min); + } else if (max - 1 - min === 0x1fffffffffffff) { + return add(Random.uint53Full, min); + } else if (min === -0x20000000000000 && max === 0x20000000000000) { + return Random.int53Full; + } else if (min === -0x20000000000000 && max === 0x1fffffffffffff) { + return Random.int53; + } else if (min === -0x1fffffffffffff && max === 0x20000000000000) { + return add(Random.int53, 1); + } else if (max === 0x20000000000000) { + return add(upscaleWithinI53AndLoopCheck(min - 1, max - 1), 1); + } else { + return upscaleWithinI53AndLoopCheck(min, max); + } + }; + }(); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.hypotenuse = hypotenuse; -exports.getFilled2DArray = getFilled2DArray; -function hypotenuse(a, b) { - var r = 0; - if (Math.abs(a) > Math.abs(b)) { - r = b / a; - return Math.abs(a) * Math.sqrt(1 + r * r); - } - if (b !== 0) { - r = a / b; - return Math.abs(b) * Math.sqrt(1 + r * r); - } - return 0; -} + proto.integer = function (min, max) { + return Random.integer(min, max)(this.engine); + }; // [0, 1] (floating point) -function getFilled2DArray(rows, columns, value) { - var array = new Array(rows); - for (var i = 0; i < rows; i++) { - array[i] = new Array(columns); - for (var j = 0; j < columns; j++) { - array[i][j] = value; - } - } - return array; -} -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { + Random.realZeroToOneInclusive = function (engine) { + return Random.uint53Full(engine) / 0x20000000000000; + }; -"use strict"; + proto.realZeroToOneInclusive = function () { + return Random.realZeroToOneInclusive(this.engine); + }; // [0, 1) (floating point) -var Heap = __webpack_require__(84); + Random.realZeroToOneExclusive = function (engine) { + return Random.uint53(engine) / 0x20000000000000; + }; -function Cluster() { - this.children = []; - this.distance = -1; - this.index = []; -} + proto.realZeroToOneExclusive = function () { + return Random.realZeroToOneExclusive(this.engine); + }; -/** - * Creates an array of values where maximum distance smaller than the threshold - * @param {number} threshold - * @return {Array } - */ -Cluster.prototype.cut = function (threshold) { - if (threshold < 0) throw new RangeError('Threshold too small'); - var root = new Cluster(); - root.children = this.children; - root.distance = this.distance; - root.index = this.index; - var list = [root]; - var ans = []; - while (list.length > 0) { - var aux = list.shift(); - if (threshold >= aux.distance) { - ans.push(aux); - } else { - list = list.concat(aux.children); - } + Random.real = function () { + function multiply(generate, multiplier) { + if (multiplier === 1) { + return generate; + } else if (multiplier === 0) { + return function () { + return 0; + }; + } else { + return function (engine) { + return generate(engine) * multiplier; + }; + } } - return ans; -}; -/** - * Merge the leaves in the minimum way to have 'minGroups' number of clusters - * @param {number} minGroups - Them minimum number of children the first level of the tree should have - * @return {Cluster} - */ -Cluster.prototype.group = function (minGroups) { - if (!Number.isInteger(minGroups) || minGroups < 1) throw new RangeError('Number of groups must be a positive integer'); + return function (left, right, inclusive) { + if (!isFinite(left)) { + throw new RangeError("Expected left to be a finite number"); + } else if (!isFinite(right)) { + throw new RangeError("Expected right to be a finite number"); + } - var heap = new Heap(function (a, b) { - return b.distance - a.distance; - }); + return add(multiply(inclusive ? Random.realZeroToOneInclusive : Random.realZeroToOneExclusive, right - left), left); + }; + }(); - heap.push(this); + proto.real = function (min, max, inclusive) { + return Random.real(min, max, inclusive)(this.engine); + }; - while (heap.size() < minGroups) { - var first = heap.pop(); - if (first.children.length === 0) { - break; - } - first.children.forEach(child => heap.push(child)); + Random.bool = function () { + function isLeastBitTrue(engine) { + return (engine() & 1) === 1; } - var root = new Cluster(); - root.children = heap.toArray(); - root.distance = this.distance; + function lessThan(generate, value) { + return function (engine) { + return generate(engine) < value; + }; + } - return root; -}; + function probability(percentage) { + if (percentage <= 0) { + return returnValue(false); + } else if (percentage >= 1) { + return returnValue(true); + } else { + var scaled = percentage * 0x100000000; -/** - * Traverses the tree depth-first and provide callback to be called on each individual node - * @param {function} cb - The callback to be called on each node encounter - * @type {Cluster} - */ -Cluster.prototype.traverse = function (cb) { - function visit(root, callback) { - callback(root); - if (root.children) { - for (var i = root.children.length - 1; i >= 0; i--) { - visit(root.children[i], callback); - } + if (scaled % 1 === 0) { + return lessThan(Random.int32, scaled - 0x80000000 | 0); + } else { + return lessThan(Random.uint53, Math.round(percentage * 0x20000000000000)); } + } } - visit(this, cb); -}; -module.exports = Cluster; + return function (numerator, denominator) { + if (denominator == null) { + if (numerator == null) { + return isLeastBitTrue; + } -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { + return probability(numerator); + } else { + if (numerator <= 0) { + return returnValue(false); + } else if (numerator >= denominator) { + return returnValue(true); + } -"use strict"; + return lessThan(Random.integer(0, denominator - 1), numerator); + } + }; + }(); + proto.bool = function (numerator, denominator) { + return Random.bool(numerator, denominator)(this.engine); + }; -var Matrix = __webpack_require__(0).Matrix; + function toInteger(value) { + var number = +value; -var GaussianKernel = __webpack_require__(98); -var PolynomialKernel = __webpack_require__(99); -var ANOVAKernel = __webpack_require__(100); -var CauchyKernel = __webpack_require__(101); -var ExponentialKernel = __webpack_require__(102); -var HistogramKernel = __webpack_require__(103); -var LaplacianKernel = __webpack_require__(104); -var MultiquadraticKernel = __webpack_require__(105); -var RationalKernel = __webpack_require__(106); -var SigmoidKernel = __webpack_require__(107); - -var kernelType = { - gaussian: GaussianKernel, - rbf: GaussianKernel, - polynomial: PolynomialKernel, - poly: PolynomialKernel, - anova: ANOVAKernel, - cauchy: CauchyKernel, - exponential: ExponentialKernel, - histogram: HistogramKernel, - min: HistogramKernel, - laplacian: LaplacianKernel, - multiquadratic: MultiquadraticKernel, - rational: RationalKernel, - sigmoid: SigmoidKernel, - mlp: SigmoidKernel -}; + if (number < 0) { + return Math.ceil(number); + } else { + return Math.floor(number); + } + } -class Kernel { - constructor(type, options) { - this.kernelType = type; - if (type === 'linear') return; + function convertSliceArgument(value, length) { + if (value < 0) { + return Math.max(value + length, 0); + } else { + return Math.min(value, length); + } + } - if (typeof type === 'string') { - type = type.toLowerCase(); + Random.pick = function (engine, array, begin, end) { + var length = array.length; + var start = begin == null ? 0 : convertSliceArgument(toInteger(begin), length); + var finish = end === void 0 ? length : convertSliceArgument(toInteger(end), length); - var KernelConstructor = kernelType[type]; - if (KernelConstructor) { - this.kernelFunction = new KernelConstructor(options); - } else { - throw new Error('unsupported kernel type: ' + type); - } - } else if (typeof type === 'object' && typeof type.compute === 'function') { - this.kernelFunction = type; - } else { - throw new TypeError('first argument must be a valid kernel type or instance'); - } + if (start >= finish) { + return void 0; } - compute(inputs, landmarks) { - if (landmarks === undefined) { - landmarks = inputs; - } - - if (this.kernelType === 'linear') { - var matrix = new Matrix(inputs); - return matrix.mmul(new Matrix(landmarks).transposeView()); - } + var distribution = Random.integer(start, finish - 1); + return array[distribution(engine)]; + }; - var kernelMatrix = new Matrix(inputs.length, landmarks.length); - var i, j; - if (inputs === landmarks) { - // fast path, matrix is symmetric - for (i = 0; i < inputs.length; i++) { - for (j = i; j < inputs.length; j++) { - kernelMatrix[i][j] = kernelMatrix[j][i] = this.kernelFunction.compute(inputs[i], inputs[j]); - } - } - } else { - for (i = 0; i < inputs.length; i++) { - for (j = 0; j < landmarks.length; j++) { - kernelMatrix[i][j] = this.kernelFunction.compute(inputs[i], landmarks[j]); - } - } - } - return kernelMatrix; - } -} + proto.pick = function (array, begin, end) { + return Random.pick(this.engine, array, begin, end); + }; -module.exports = Kernel; + function returnUndefined() { + return void 0; + } -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { + var slice = Array.prototype.slice; -"use strict"; + Random.picker = function (array, begin, end) { + var clone = slice.call(array, begin, end); + if (!clone.length) { + return returnUndefined; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + var distribution = Random.integer(0, clone.length - 1); + return function (engine) { + return clone[distribution(engine)]; + }; + }; -var _mlRegressionBase = __webpack_require__(2); + Random.shuffle = function (engine, array, downTo) { + var length = array.length; -var _mlRegressionBase2 = _interopRequireDefault(_mlRegressionBase); + if (length) { + if (downTo == null) { + downTo = 0; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (var i = length - 1 >>> 0; i > downTo; --i) { + var distribution = Random.integer(0, i); + var j = distribution(engine); -class SimpleLinearRegression extends _mlRegressionBase2.default { - constructor(x, y) { - super(); - if (x === true) { - this.slope = y.slope; - this.intercept = y.intercept; - this.coefficients = [y.intercept, y.slope]; - } else { - (0, _mlRegressionBase.checkArrayLength)(x, y); - regress(this, x, y); + if (i !== j) { + var tmp = array[i]; + array[i] = array[j]; + array[j] = tmp; } + } } - toJSON() { - return { - name: 'simpleLinearRegression', - slope: this.slope, - intercept: this.intercept - }; - } + return array; + }; - _predict(x) { - return this.slope * x + this.intercept; - } + proto.shuffle = function (array) { + return Random.shuffle(this.engine, array); + }; - computeX(y) { - return (y - this.intercept) / this.slope; + Random.sample = function (engine, population, sampleSize) { + if (sampleSize < 0 || sampleSize > population.length || !isFinite(sampleSize)) { + throw new RangeError("Expected sampleSize to be within 0 and the length of the population"); } - toString(precision) { - var result = 'f(x) = '; - if (this.slope !== 0) { - var xFactor = (0, _mlRegressionBase.maybeToPrecision)(this.slope, precision); - result += (xFactor === '1' ? '' : xFactor + ' * ') + 'x'; - if (this.intercept) { - var absIntercept = Math.abs(this.intercept); - var operator = absIntercept === this.intercept ? '+' : '-'; - result += ` ${operator} ${(0, _mlRegressionBase.maybeToPrecision)(absIntercept, precision)}`; - } - } else { - result += (0, _mlRegressionBase.maybeToPrecision)(this.intercept, precision); - } - return result; + if (sampleSize === 0) { + return []; } - toLaTeX(precision) { - return this.toString(precision); - } + var clone = slice.call(population); + var length = clone.length; - static load(json) { - if (json.name !== 'simpleLinearRegression') { - throw new TypeError('not a SLR model'); - } - return new SimpleLinearRegression(true, json); + if (length === sampleSize) { + return Random.shuffle(engine, clone, 0); } -} -exports.default = SimpleLinearRegression; -function regress(slr, x, y) { - var n = x.length; - var xSum = 0; - var ySum = 0; + var tailLength = length - sampleSize; + return Random.shuffle(engine, clone, tailLength - 1).slice(tailLength); + }; + + proto.sample = function (population, sampleSize) { + return Random.sample(this.engine, population, sampleSize); + }; - var xSquared = 0; - var xY = 0; + Random.die = function (sideCount) { + return Random.integer(1, sideCount); + }; - for (var i = 0; i < n; i++) { - xSum += x[i]; - ySum += y[i]; - xSquared += x[i] * x[i]; - xY += x[i] * y[i]; - } + proto.die = function (sideCount) { + return Random.die(sideCount)(this.engine); + }; - var numerator = n * xY - xSum * ySum; - slr.slope = numerator / (n * xSquared - xSum * xSum); - slr.intercept = 1 / n * ySum - slr.slope * (1 / n) * xSum; - slr.coefficients = [slr.intercept, slr.slope]; -} + Random.dice = function (sideCount, dieCount) { + var distribution = Random.die(sideCount); + return function (engine) { + var result = []; + result.length = dieCount; -/***/ }), -/* 17 */ -/***/ (function(module, exports, __webpack_require__) { + for (var i = 0; i < dieCount; ++i) { + result[i] = distribution(engine); + } -"use strict"; + return result; + }; + }; + proto.dice = function (sideCount, dieCount) { + return Random.dice(sideCount, dieCount)(this.engine); + }; // http://en.wikipedia.org/wiki/Universally_unique_identifier -var hasOwn = Object.prototype.hasOwnProperty; -var toStr = Object.prototype.toString; -var defineProperty = Object.defineProperty; -var gOPD = Object.getOwnPropertyDescriptor; -var isArray = function isArray(arr) { - if (typeof Array.isArray === 'function') { - return Array.isArray(arr); - } + Random.uuid4 = function () { + function zeroPad(string, zeroCount) { + return stringRepeat("0", zeroCount - string.length) + string; + } - return toStr.call(arr) === '[object Array]'; -}; + return function (engine) { + var a = engine() >>> 0; + var b = engine() | 0; + var c = engine() | 0; + var d = engine() >>> 0; + return zeroPad(a.toString(16), 8) + "-" + zeroPad((b & 0xffff).toString(16), 4) + "-" + zeroPad((b >> 4 & 0x0fff | 0x4000).toString(16), 4) + "-" + zeroPad((c & 0x3fff | 0x8000).toString(16), 4) + "-" + zeroPad((c >> 4 & 0xffff).toString(16), 4) + zeroPad(d.toString(16), 8); + }; + }(); -var isPlainObject = function isPlainObject(obj) { - if (!obj || toStr.call(obj) !== '[object Object]') { - return false; - } - - var hasOwnConstructor = hasOwn.call(obj, 'constructor'); - var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); - // Not own constructor property must be Object - if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - var key; - for (key in obj) {/**/} - - return typeof key === 'undefined' || hasOwn.call(obj, key); -}; + proto.uuid4 = function () { + return Random.uuid4(this.engine); + }; -// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target -var setProperty = function setProperty(target, options) { - if (defineProperty && options.name === '__proto__') { - defineProperty(target, options.name, { - enumerable: true, - configurable: true, - value: options.newValue, - writable: true - }); - } else { - target[options.name] = options.newValue; - } -}; + Random.string = function () { + // has 2**x chars, for faster uniform distribution + var DEFAULT_STRING_POOL = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"; + return function (pool) { + if (pool == null) { + pool = DEFAULT_STRING_POOL; + } + + var length = pool.length; + + if (!length) { + throw new Error("Expected pool not to be an empty string"); + } -// Return undefined instead of __proto__ if '__proto__' is not an own property -var getProperty = function getProperty(obj, name) { - if (name === '__proto__') { - if (!hasOwn.call(obj, name)) { - return void 0; - } else if (gOPD) { - // In early versions of node, obj['__proto__'] is buggy when obj has - // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. - return gOPD(obj, name).value; - } - } - - return obj[name]; -}; + var distribution = Random.integer(0, length - 1); + return function (engine, length) { + var result = ""; -module.exports = function extend() { - var options, name, src, copy, copyIsArray, clone; - var target = arguments[0]; - var i = 1; - var length = arguments.length; - var deep = false; - - // Handle a deep copy situation - if (typeof target === 'boolean') { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - if (target == null || typeof target !== 'object' && typeof target !== 'function') { - target = {}; - } - - for (; i < length; ++i) { - options = arguments[i]; - // Only deal with non-null/undefined values - if (options != null) { - // Extend the base object - for (name in options) { - src = getProperty(target, name); - copy = getProperty(options, name); - - // Prevent never-ending loop - if (target !== copy) { - // Recurse if we're merging plain objects or arrays - if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && isArray(src) ? src : []; - } else { - clone = src && isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); - - // Don't bring in undefined values - } else if (typeof copy !== 'undefined') { - setProperty(target, { name: name, newValue: copy }); - } - } - } - } - } - - // Return the modified object - return target; -}; + for (var i = 0; i < length; ++i) { + var j = distribution(engine); + result += pool.charAt(j); + } -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { + return result; + }; + }; + }(); -"use strict"; + proto.string = function (length, pool) { + return Random.string(pool)(this.engine, length); + }; + Random.hex = function () { + var LOWER_HEX_POOL = "0123456789abcdef"; + var lowerHex = Random.string(LOWER_HEX_POOL); + var upperHex = Random.string(LOWER_HEX_POOL.toUpperCase()); + return function (upper) { + if (upper) { + return upperHex; + } else { + return lowerHex; + } + }; + }(); -Object.defineProperty(exports, "__esModule", { - value: true -}); + proto.hex = function (length, upper) { + return Random.hex(upper)(this.engine, length); + }; -var _DecisionTreeClassifier = __webpack_require__(58); + Random.date = function (start, end) { + if (!(start instanceof Date)) { + throw new TypeError("Expected start to be a Date, got " + typeof start); + } else if (!(end instanceof Date)) { + throw new TypeError("Expected end to be a Date, got " + typeof end); + } -Object.defineProperty(exports, 'DecisionTreeClassifier', { - enumerable: true, - get: function get() { - return _DecisionTreeClassifier.DecisionTreeClassifier; - } -}); + var distribution = Random.integer(start.getTime(), end.getTime()); + return function (engine) { + return new Date(distribution(engine)); + }; + }; -var _DecisionTreeRegression = __webpack_require__(74); + proto.date = function (start, end) { + return Random.date(start, end)(this.engine); + }; -Object.defineProperty(exports, 'DecisionTreeRegression', { - enumerable: true, - get: function get() { - return _DecisionTreeRegression.DecisionTreeRegression; - } -}); + if (true) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { + return Random; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +})(this); /***/ }), -/* 19 */ -/***/ (function(module, exports, __webpack_require__) { +/* 13 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var ml_array_max__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); +/* harmony import */ var ml_array_min__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(is_any_array__WEBPACK_IMPORTED_MODULE_2__); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = rescale; - -var _mlArrayMax = __webpack_require__(11); -var _mlArrayMax2 = _interopRequireDefault(_mlArrayMax); -var _mlArrayMin = __webpack_require__(20); +function rescale(input) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; -var _mlArrayMin2 = _interopRequireDefault(_mlArrayMin); + if (!is_any_array__WEBPACK_IMPORTED_MODULE_2___default()(input)) { + throw new TypeError('input must be an array'); + } else if (input.length === 0) { + throw new TypeError('input must not be empty'); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var output; -function rescale(input, options = {}) { - if (!Array.isArray(input)) { - throw new TypeError('input must be an array'); - } else if (input.length === 0) { - throw new TypeError('input must not be empty'); + if (options.output !== undefined) { + if (!is_any_array__WEBPACK_IMPORTED_MODULE_2___default()(options.output)) { + throw new TypeError('output option must be an array if specified'); } - var output = void 0; - if (options.output !== undefined) { - if (!Array.isArray(options.output)) { - throw new TypeError('output option must be an array if specified'); - } - output = options.output; - } else { - output = new Array(input.length); - } + output = options.output; + } else { + output = new Array(input.length); + } - var currentMin = (0, _mlArrayMin2.default)(input); - var currentMax = (0, _mlArrayMax2.default)(input); + var currentMin = Object(ml_array_min__WEBPACK_IMPORTED_MODULE_1__["default"])(input); + var currentMax = Object(ml_array_max__WEBPACK_IMPORTED_MODULE_0__["default"])(input); - if (currentMin === currentMax) { - throw new RangeError('minimum and maximum input values are equal. Cannot rescale a constant array'); - } + if (currentMin === currentMax) { + throw new RangeError('minimum and maximum input values are equal. Cannot rescale a constant array'); + } - var _options$min = options.min, - minValue = _options$min === undefined ? options.autoMinMax ? currentMin : 0 : _options$min, - _options$max = options.max, - maxValue = _options$max === undefined ? options.autoMinMax ? currentMax : 1 : _options$max; + var _options$min = options.min, + minValue = _options$min === void 0 ? options.autoMinMax ? currentMin : 0 : _options$min, + _options$max = options.max, + maxValue = _options$max === void 0 ? options.autoMinMax ? currentMax : 1 : _options$max; + if (minValue >= maxValue) { + throw new RangeError('min option must be smaller than max option'); + } - if (minValue >= maxValue) { - throw new RangeError('min option must be smaller than max option'); - } + var factor = (maxValue - minValue) / (currentMax - currentMin); - var factor = (maxValue - minValue) / (currentMax - currentMin); - for (var i = 0; i < input.length; i++) { - output[i] = (input[i] - currentMin) * factor + minValue; - } + for (var i = 0; i < input.length; i++) { + output[i] = (input[i] - currentMin) * factor + minValue; + } - return output; + return output; } +/* harmony default export */ __webpack_exports__["default"] = (rescale); + /***/ }), -/* 20 */ +/* 14 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = min; -/** - * Computes the minimum of the given values - * @param {Array} input - * @return {number} - */ -function min(input) { - if (!Array.isArray(input)) { - throw new Error('input must be an array'); - } - - if (input.length === 0) { - throw new Error('input must not be empty'); - } - - var min = input[0]; - for (var i = 1; i < input.length; i++) { - if (input[i] < min) min = input[i]; - } - return min; -} +const newArray = __webpack_require__(72); -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { +const primeFinder = __webpack_require__(73); -"use strict"; +const nextPrime = primeFinder.nextPrime; +const largestPrime = primeFinder.largestPrime; +const FREE = 0; +const FULL = 1; +const REMOVED = 2; +const defaultInitialCapacity = 150; +const defaultMinLoadFactor = 1 / 6; +const defaultMaxLoadFactor = 2 / 3; +class HashTable { + constructor() { + let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + if (options instanceof HashTable) { + this.table = options.table.slice(); + this.values = options.values.slice(); + this.state = options.state.slice(); + this.minLoadFactor = options.minLoadFactor; + this.maxLoadFactor = options.maxLoadFactor; + this.distinct = options.distinct; + this.freeEntries = options.freeEntries; + this.lowWaterMark = options.lowWaterMark; + this.highWaterMark = options.maxLoadFactor; + return; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + const initialCapacity = options.initialCapacity === undefined ? defaultInitialCapacity : options.initialCapacity; -var _abstractMatrix = __webpack_require__(7); + if (initialCapacity < 0) { + throw new RangeError("initial capacity must not be less than zero: ".concat(initialCapacity)); + } -var _abstractMatrix2 = _interopRequireDefault(_abstractMatrix); + const minLoadFactor = options.minLoadFactor === undefined ? defaultMinLoadFactor : options.minLoadFactor; + const maxLoadFactor = options.maxLoadFactor === undefined ? defaultMaxLoadFactor : options.maxLoadFactor; -var _matrix = __webpack_require__(5); + if (minLoadFactor < 0 || minLoadFactor >= 1) { + throw new RangeError("invalid minLoadFactor: ".concat(minLoadFactor)); + } -var _matrix2 = _interopRequireDefault(_matrix); + if (maxLoadFactor <= 0 || maxLoadFactor >= 1) { + throw new RangeError("invalid maxLoadFactor: ".concat(maxLoadFactor)); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (minLoadFactor >= maxLoadFactor) { + throw new RangeError("minLoadFactor (".concat(minLoadFactor, ") must be smaller than maxLoadFactor (").concat(maxLoadFactor, ")")); + } -class WrapperMatrix1D extends (0, _abstractMatrix2.default)() { - /** - * @class WrapperMatrix1D - * @param {Array} data - * @param {object} [options] - * @param {object} [options.rows = 1] - */ - constructor(data, options = {}) { - var _options$rows = options.rows, - rows = _options$rows === undefined ? 1 : _options$rows; + let capacity = initialCapacity; // User wants to put at least capacity elements. We need to choose the size based on the maxLoadFactor to + // avoid the need to rehash before this capacity is reached. + // actualCapacity * maxLoadFactor >= capacity + capacity = capacity / maxLoadFactor | 0; + capacity = nextPrime(capacity); + if (capacity === 0) capacity = 1; + this.table = newArray(capacity, 0); + this.values = newArray(capacity, 0); + this.state = newArray(capacity, 0); + this.minLoadFactor = minLoadFactor; - if (data.length % rows !== 0) { - throw new Error('the data length is not divisible by the number of rows'); + if (capacity === largestPrime) { + this.maxLoadFactor = 1; + } else { + this.maxLoadFactor = maxLoadFactor; } - super(); - this.rows = rows; - this.columns = data.length / rows; - this.data = data; - } - set(rowIndex, columnIndex, value) { - var index = this._calculateIndex(rowIndex, columnIndex); - this.data[index] = value; - return this; + this.distinct = 0; + this.freeEntries = capacity; + this.lowWaterMark = 0; + this.highWaterMark = chooseHighWaterMark(capacity, this.maxLoadFactor); } - get(rowIndex, columnIndex) { - var index = this._calculateIndex(rowIndex, columnIndex); - return this.data[index]; + clone() { + return new HashTable(this); } - _calculateIndex(row, column) { - return row * this.columns + column; + get size() { + return this.distinct; } - static get [Symbol.species]() { - return _matrix2.default; + get(key) { + const i = this.indexOfKey(key); + if (i < 0) return 0; + return this.values[i]; } -} -exports.default = WrapperMatrix1D; - -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -var _abstractMatrix = __webpack_require__(7); + set(key, value) { + let i = this.indexOfInsertion(key); -var _abstractMatrix2 = _interopRequireDefault(_abstractMatrix); + if (i < 0) { + i = -i - 1; + this.values[i] = value; + return false; + } -var _matrix = __webpack_require__(5); + if (this.distinct > this.highWaterMark) { + const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor); + this.rehash(newCapacity); + return this.set(key, value); + } -var _matrix2 = _interopRequireDefault(_matrix); + this.table[i] = key; + this.values[i] = value; + if (this.state[i] === FREE) this.freeEntries--; + this.state[i] = FULL; + this.distinct++; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (this.freeEntries < 1) { + const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor); + this.rehash(newCapacity); + } -class WrapperMatrix2D extends (0, _abstractMatrix2.default)() { - /** - * @class WrapperMatrix2D - * @param {Array>} data - */ - constructor(data) { - super(); - this.data = data; - this.rows = data.length; - this.columns = data[0].length; + return true; } - set(rowIndex, columnIndex, value) { - this.data[rowIndex][columnIndex] = value; - return this; + remove(key, noRehash) { + const i = this.indexOfKey(key); + if (i < 0) return false; + this.state[i] = REMOVED; + this.distinct--; + if (!noRehash) this.maybeShrinkCapacity(); + return true; } - get(rowIndex, columnIndex) { - return this.data[rowIndex][columnIndex]; + delete(key, noRehash) { + const i = this.indexOfKey(key); + if (i < 0) return false; + this.state[i] = FREE; + this.distinct--; + if (!noRehash) this.maybeShrinkCapacity(); + return true; } - static get [Symbol.species]() { - return _matrix2.default; + maybeShrinkCapacity() { + if (this.distinct < this.lowWaterMark) { + const newCapacity = chooseShrinkCapacity(this.distinct, this.minLoadFactor, this.maxLoadFactor); + this.rehash(newCapacity); + } } -} -exports.default = WrapperMatrix2D; - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + containsKey(key) { + return this.indexOfKey(key) >= 0; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + indexOfKey(key) { + const table = this.table; + const state = this.state; + const length = this.table.length; + const hash = key & 0x7fffffff; + let i = hash % length; + let decrement = hash % (length - 2); + if (decrement === 0) decrement = 1; -var _index = __webpack_require__(0); + while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) { + i -= decrement; + if (i < 0) i += length; + } -var _util = __webpack_require__(13); + if (state[i] === FREE) return -1; + return i; + } -/** - * @class QrDecomposition - * @link https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs - * @param {Matrix} value - */ -class QrDecomposition { - constructor(value) { - value = _index.WrapperMatrix2D.checkMatrix(value); + containsValue(value) { + return this.indexOfValue(value) >= 0; + } - var qr = value.clone(); - var m = value.rows; - var n = value.columns; - var rdiag = new Array(n); - var i, j, k, s; + indexOfValue(value) { + const values = this.values; + const state = this.state; - for (k = 0; k < n; k++) { - var nrm = 0; - for (i = k; i < m; i++) { - nrm = (0, _util.hypotenuse)(nrm, qr.get(i, k)); - } - if (nrm !== 0) { - if (qr.get(k, k) < 0) { - nrm = -nrm; - } - for (i = k; i < m; i++) { - qr.set(i, k, qr.get(i, k) / nrm); - } - qr.set(k, k, qr.get(k, k) + 1); - for (j = k + 1; j < n; j++) { - s = 0; - for (i = k; i < m; i++) { - s += qr.get(i, k) * qr.get(i, j); - } - s = -s / qr.get(k, k); - for (i = k; i < m; i++) { - qr.set(i, j, qr.get(i, j) + s * qr.get(i, k)); - } - } + for (var i = 0; i < state.length; i++) { + if (state[i] === FULL && values[i] === value) { + return i; } - rdiag[k] = -nrm; } - this.QR = qr; - this.Rdiag = rdiag; + return -1; } - /** - * Solve a problem of least square (Ax=b) by using the QR decomposition. Useful when A is rectangular, but not working when A is singular. - * Example : We search to approximate x, with A matrix shape m*n, x vector size n, b vector size m (m > n). We will use : - * var qr = QrDecomposition(A); - * var x = qr.solve(b); - * @param {Matrix} value - Matrix 1D which is the vector b (in the equation Ax = b) - * @return {Matrix} - The vector x - */ - solve(value) { - value = _index.Matrix.checkMatrix(value); - - var qr = this.QR; - var m = qr.rows; + indexOfInsertion(key) { + const table = this.table; + const state = this.state; + const length = table.length; + const hash = key & 0x7fffffff; + let i = hash % length; + let decrement = hash % (length - 2); + if (decrement === 0) decrement = 1; - if (value.rows !== m) { - throw new Error('Matrix row dimensions must agree'); - } - if (!this.isFullRank()) { - throw new Error('Matrix is rank deficient'); + while (state[i] === FULL && table[i] !== key) { + i -= decrement; + if (i < 0) i += length; } - var count = value.columns; - var X = value.clone(); - var n = qr.columns; - var i, j, k, s; + if (state[i] === REMOVED) { + const j = i; - for (k = 0; k < n; k++) { - for (j = 0; j < count; j++) { - s = 0; - for (i = k; i < m; i++) { - s += qr[i][k] * X[i][j]; - } - s = -s / qr[k][k]; - for (i = k; i < m; i++) { - X[i][j] += s * qr[i][k]; - } - } - } - for (k = n - 1; k >= 0; k--) { - for (j = 0; j < count; j++) { - X[k][j] /= this.Rdiag[k]; - } - for (i = 0; i < k; i++) { - for (j = 0; j < count; j++) { - X[i][j] -= X[k][j] * qr[i][k]; - } + while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) { + i -= decrement; + if (i < 0) i += length; } + + if (state[i] === FREE) i = j; } - return X.subMatrix(0, n - 1, 0, count - 1); - } + if (state[i] === FULL) { + return -i - 1; + } - /** - * - * @return {boolean} - */ - isFullRank() { - var columns = this.QR.columns; - for (var i = 0; i < columns; i++) { - if (this.Rdiag[i] === 0) { - return false; - } + return i; + } + + ensureCapacity(minCapacity) { + if (this.table.length < minCapacity) { + const newCapacity = nextPrime(minCapacity); + this.rehash(newCapacity); } - return true; } - /** - * - * @return {Matrix} - */ - get upperTriangularMatrix() { - var qr = this.QR; - var n = qr.columns; - var X = new _index.Matrix(n, n); - var i, j; - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - if (i < j) { - X[i][j] = qr[i][j]; - } else if (i === j) { - X[i][j] = this.Rdiag[i]; - } else { - X[i][j] = 0; - } + rehash(newCapacity) { + const oldCapacity = this.table.length; + if (newCapacity <= this.distinct) throw new Error('Unexpected'); + const oldTable = this.table; + const oldValues = this.values; + const oldState = this.state; + const newTable = newArray(newCapacity, 0); + const newValues = newArray(newCapacity, 0); + const newState = newArray(newCapacity, 0); + this.lowWaterMark = chooseLowWaterMark(newCapacity, this.minLoadFactor); + this.highWaterMark = chooseHighWaterMark(newCapacity, this.maxLoadFactor); + this.table = newTable; + this.values = newValues; + this.state = newState; + this.freeEntries = newCapacity - this.distinct; + + for (var i = 0; i < oldCapacity; i++) { + if (oldState[i] === FULL) { + var element = oldTable[i]; + var index = this.indexOfInsertion(element); + newTable[index] = element; + newValues[index] = oldValues[i]; + newState[index] = FULL; } } - return X; } - /** - * - * @return {Matrix} - */ - get orthogonalMatrix() { - var qr = this.QR; - var rows = qr.rows; - var columns = qr.columns; - var X = new _index.Matrix(rows, columns); - var i, j, k, s; + forEachKey(callback) { + for (var i = 0; i < this.state.length; i++) { + if (this.state[i] === FULL) { + if (!callback(this.table[i])) return false; + } + } - for (k = columns - 1; k >= 0; k--) { - for (i = 0; i < rows; i++) { - X[i][k] = 0; + return true; + } + + forEachValue(callback) { + for (var i = 0; i < this.state.length; i++) { + if (this.state[i] === FULL) { + if (!callback(this.values[i])) return false; } - X[k][k] = 1; - for (j = k; j < columns; j++) { - if (qr[k][k] !== 0) { - s = 0; - for (i = k; i < rows; i++) { - s += qr[i][k] * X[i][j]; - } + } - s = -s / qr[k][k]; + return true; + } - for (i = k; i < rows; i++) { - X[i][j] += s * qr[i][k]; - } - } + forEachPair(callback) { + for (var i = 0; i < this.state.length; i++) { + if (this.state[i] === FULL) { + if (!callback(this.table[i], this.values[i])) return false; } } - return X; + + return true; } + +} + +module.exports = HashTable; + +function chooseLowWaterMark(capacity, minLoad) { + return capacity * minLoad | 0; +} + +function chooseHighWaterMark(capacity, maxLoad) { + return Math.min(capacity - 2, capacity * maxLoad | 0); +} + +function chooseGrowCapacity(size, minLoad, maxLoad) { + return nextPrime(Math.max(size + 1, 4 * size / (3 * minLoad + maxLoad) | 0)); +} + +function chooseShrinkCapacity(size, minLoad, maxLoad) { + return nextPrime(Math.max(size + 1, 4 * size / (minLoad + 3 * maxLoad) | 0)); } -exports.default = QrDecomposition; /***/ }), -/* 24 */ +/* 15 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); +const Heap = __webpack_require__(47); -var _mlMatrix = __webpack_require__(0); +function Cluster() { + this.children = []; + this.distance = -1; + this.index = []; +} +/** + * Creates an array of values where maximum distance smaller than the threshold + * @param {number} threshold + * @return {Array } + */ -var _mlMatrix2 = _interopRequireDefault(_mlMatrix); -var _utils = __webpack_require__(73); +Cluster.prototype.cut = function (threshold) { + if (threshold < 0) throw new RangeError('Threshold too small'); + var root = new Cluster(); + root.children = this.children; + root.distance = this.distance; + root.index = this.index; + var list = [root]; + var ans = []; + + while (list.length > 0) { + var aux = list.shift(); + + if (threshold >= aux.distance) { + ans.push(aux); + } else { + list = list.concat(aux.children); + } + } -var Utils = _interopRequireWildcard(_utils); + return ans; +}; +/** + * Merge the leaves in the minimum way to have 'minGroups' number of clusters + * @param {number} minGroups - Them minimum number of children the first level of the tree should have + * @return {Cluster} + */ -var _mlArrayMean = __webpack_require__(8); -var _mlArrayMean2 = _interopRequireDefault(_mlArrayMean); +Cluster.prototype.group = function (minGroups) { + if (!Number.isInteger(minGroups) || minGroups < 1) throw new RangeError('Number of groups must be a positive integer'); + const heap = new Heap(function (a, b) { + return b.distance - a.distance; + }); + heap.push(this); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + while (heap.size() < minGroups) { + var first = heap.pop(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (first.children.length === 0) { + break; + } -var gainFunctions = { - gini: Utils.giniGain, - regression: Utils.regressionError -}; + first.children.forEach(child => heap.push(child)); + } -var splitFunctions = { - mean: Utils.mean + var root = new Cluster(); + root.children = heap.toArray(); + root.distance = this.distance; + return root; }; +/** + * Traverses the tree depth-first and provide callback to be called on each individual node + * @param {function} cb - The callback to be called on each node encounter + * @type {Cluster} + */ -class TreeNode { - /** - * @private - * Constructor for a tree node given the options received on the main classes (DecisionTreeClassifier, DecisionTreeRegression) - * @param {object|TreeNode} options for loading - * @constructor - */ - constructor(options) { - // options parameters - this.kind = options.kind; - this.gainFunction = options.gainFunction; - this.splitFunction = options.splitFunction; - this.minNumSamples = options.minNumSamples; - this.maxDepth = options.maxDepth; +Cluster.prototype.traverse = function (cb) { + function visit(root, callback) { + callback(root); + + if (root.children) { + for (var i = root.children.length - 1; i >= 0; i--) { + visit(root.children[i], callback); + } } + } - /** - * @private - * Function that retrieve the best feature to make the split. - * @param {Matrix} XTranspose - Training set transposed - * @param {Array} y - labels or values (depending of the decision tree) - * @return {object} - return tree values, the best gain, column and the split value. - */ - bestSplit(XTranspose, y) { + visit(this, cb); +}; - // Depending in the node tree class, we set the variables to check information gain (to classify) - // or error (for regression) +module.exports = Cluster; - var bestGain = this.kind === 'classifier' ? -Infinity : Infinity; - var check = this.kind === 'classifier' ? (a, b) => a > b : (a, b) => a < b; +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { - var maxColumn; - var maxValue; +"use strict"; - for (var i = 0; i < XTranspose.rows; ++i) { - var currentFeature = XTranspose[i]; - var splitValues = this.featureSplit(currentFeature, y); - for (var j = 0; j < splitValues.length; ++j) { - var currentSplitVal = splitValues[j]; - var splitted = this.split(currentFeature, y, currentSplitVal); - var gain = gainFunctions[this.gainFunction](y, splitted); - if (check(gain, bestGain)) { - maxColumn = i; - maxValue = currentSplitVal; - bestGain = gain; - } - } - } +var hasOwn = Object.prototype.hasOwnProperty; +var toStr = Object.prototype.toString; +var defineProperty = Object.defineProperty; +var gOPD = Object.getOwnPropertyDescriptor; - return { - maxGain: bestGain, - maxColumn: maxColumn, - maxValue: maxValue - }; - } +var isArray = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr); + } - /** - * @private - * Makes the split of the training labels or values from the training set feature given a split value. - * @param {Array} x - Training set feature - * @param {Array} y - Training set value or label - * @param {number} splitValue - * @return {object} - */ + return toStr.call(arr) === '[object Array]'; +}; - split(x, y, splitValue) { - var lesser = []; - var greater = []; +var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false; + } - for (var i = 0; i < x.length; ++i) { - if (x[i] < splitValue) { - lesser.push(y[i]); - } else { - greater.push(y[i]); - } - } + var hasOwnConstructor = hasOwn.call(obj, 'constructor'); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); // Not own constructor property must be Object - return { - greater: greater, - lesser: lesser - }; - } + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; + } // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. - /** - * @private - * Calculates the possible points to split over the tree given a training set feature and corresponding labels or values. - * @param {Array} x - Training set feature - * @param {Array} y - Training set value or label - * @return {Array} possible split values. - */ - featureSplit(x, y) { - var splitValues = []; - var arr = Utils.zip(x, y); - arr.sort(function (a, b) { - return a[0] - b[0]; - }); - for (var i = 1; i < arr.length; ++i) { - if (arr[i - 1][1] !== arr[i][1]) { - splitValues.push(splitFunctions[this.splitFunction](arr[i - 1][0], arr[i][0])); - } - } + var key; + + for (key in obj) { + /**/ + } + + return typeof key === 'undefined' || hasOwn.call(obj, key); +}; // If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target + + +var setProperty = function setProperty(target, options) { + if (defineProperty && options.name === '__proto__') { + defineProperty(target, options.name, { + enumerable: true, + configurable: true, + value: options.newValue, + writable: true + }); + } else { + target[options.name] = options.newValue; + } +}; // Return undefined instead of __proto__ if '__proto__' is not an own property - return splitValues; + +var getProperty = function getProperty(obj, name) { + if (name === '__proto__') { + if (!hasOwn.call(obj, name)) { + return void 0; + } else if (gOPD) { + // In early versions of node, obj['__proto__'] is buggy when obj has + // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. + return gOPD(obj, name).value; } + } - /** - * @private - * Calculate the predictions of a leaf tree node given the training labels or values - * @param {Array} y - */ - calculatePrediction(y) { - if (this.kind === 'classifier') { - this.distribution = Utils.toDiscreteDistribution(y, Utils.getNumberOfClasses(y)); - if (this.distribution.columns === 0) { - throw new TypeError('Error on calculate the prediction'); - } - } else { - this.distribution = (0, _mlArrayMean2.default)(y); + return obj[name]; +}; + +module.exports = function extend() { + var options, name, src, copy, copyIsArray, clone; + var target = arguments[0]; + var i = 1; + var length = arguments.length; + var deep = false; // Handle a deep copy situation + + if (typeof target === 'boolean') { + deep = target; + target = arguments[1] || {}; // skip the boolean and the target + + i = 2; + } + + if (target == null || typeof target !== 'object' && typeof target !== 'function') { + target = {}; + } + + for (; i < length; ++i) { + options = arguments[i]; // Only deal with non-null/undefined values + + if (options != null) { + // Extend the base object + for (name in options) { + src = getProperty(target, name); + copy = getProperty(options, name); // Prevent never-ending loop + + if (target !== copy) { + // Recurse if we're merging plain objects or arrays + if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && isArray(src) ? src : []; + } else { + clone = src && isPlainObject(src) ? src : {}; + } // Never move original objects, clone them + + + setProperty(target, { + name: name, + newValue: extend(deep, clone, copy) + }); // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + setProperty(target, { + name: name, + newValue: copy + }); + } } + } } + } // Return the modified object - /** - * @private - * Train a node given the training set and labels, because it trains recursively, it also receive - * the current depth of the node, parent gain to avoid infinite recursion and boolean value to check if - * the training set is transposed. - * @param {Matrix} X - Training set (could be transposed or not given transposed). - * @param {Array} y - Training labels or values. - * @param {number} currentDepth - Current depth of the node. - * @param {number} parentGain - parent node gain or error. - */ - train(X, y, currentDepth, parentGain) { - if (X.rows <= this.minNumSamples) { - this.calculatePrediction(y); - return; - } - if (parentGain === undefined) parentGain = 0.0; - var XTranspose = X.transpose(); - var split = this.bestSplit(XTranspose, y); + return target; +}; + +/***/ }), +/* 17 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(is_any_array__WEBPACK_IMPORTED_MODULE_0__); + +/** + * Computes the minimum of the given values + * @param {Array} input + * @return {number} + */ + +function min(input) { + if (!is_any_array__WEBPACK_IMPORTED_MODULE_0___default()(input)) { + throw new TypeError('input must be an array'); + } - this.splitValue = split.maxValue; - this.splitColumn = split.maxColumn; - this.gain = split.maxGain; + if (input.length === 0) { + throw new TypeError('input must not be empty'); + } - var splittedMatrix = Utils.matrixSplitter(X, y, this.splitColumn, this.splitValue); + var min = input[0]; - if (currentDepth < this.maxDepth && this.gain > 0.01 && this.gain !== parentGain && splittedMatrix.lesserX.length > 0 && splittedMatrix.greaterX.length > 0) { - this.left = new TreeNode(this); - this.right = new TreeNode(this); + for (var i = 1; i < input.length; i++) { + if (input[i] < min) min = input[i]; + } - var lesserX = new _mlMatrix2.default(splittedMatrix.lesserX); - var greaterX = new _mlMatrix2.default(splittedMatrix.greaterX); + return min; +} - this.left.train(lesserX, splittedMatrix.lesserY, currentDepth + 1, this.gain); - this.right.train(greaterX, splittedMatrix.greaterY, currentDepth + 1, this.gain); - } else { - this.calculatePrediction(y); - } - } +/* harmony default export */ __webpack_exports__["default"] = (min); - /** - * @private - * Calculates the prediction of a given element. - * @param {Array} row - * @return {number|Array} prediction - * * if a node is a classifier returns an array of probabilities of each class. - * * if a node is for regression returns a number with the prediction. - */ - classify(row) { - if (this.right && this.left) { - if (row[this.splitColumn] < this.splitValue) { - return this.left.classify(row); - } else { - return this.right.classify(row); - } - } +/***/ }), +/* 18 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - return this.distribution; - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var median_quickselect__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(42); +/* harmony import */ var median_quickselect__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(median_quickselect__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(is_any_array__WEBPACK_IMPORTED_MODULE_1__); - /** - * @private - * Set the parameter of the current node and their children. - * @param {object} node - parameters of the current node and the children. - */ - setNodeParameters(node) { - if (node.distribution !== undefined) { - this.distribution = node.distribution.constructor === Array ? new _mlMatrix2.default(node.distribution) : node.distribution; - } else { - this.distribution = undefined; - this.splitValue = node.splitValue; - this.splitColumn = node.splitColumn; - this.gain = node.gain; - this.left = new TreeNode(this); - this.right = new TreeNode(this); +/** + * Computes the median of the given values + * @param {Array} input + * @return {number} + */ - if (node.left !== {}) { - this.left.setNodeParameters(node.left); - } - if (node.right !== {}) { - this.right.setNodeParameters(node.right); - } - } - } +function median(input) { + if (!is_any_array__WEBPACK_IMPORTED_MODULE_1___default()(input)) { + throw new TypeError('input must be an array'); + } + + if (input.length === 0) { + throw new TypeError('input must not be empty'); + } + + return median_quickselect__WEBPACK_IMPORTED_MODULE_0___default()(input.slice()); } -exports.default = TreeNode; + +/* harmony default export */ __webpack_exports__["default"] = (median); /***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { +/* 19 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return XSadd; }); +const LOOP = 8; +const FLOAT_MUL = 1 / 16777216; +const sh1 = 15; +const sh2 = 18; +const sh3 = 11; + +function multiply_uint32(n, m) { + n >>>= 0; + m >>>= 0; + const nlo = n & 0xffff; + const nhi = n - nlo; + return (nhi * m >>> 0) + nlo * m >>> 0; +} + +class XSadd { + constructor() { + let seed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Date.now(); + this.state = new Uint32Array(4); + this.init(seed); + this.random = this.getFloat.bind(this); + } + /** + * Returns a 32-bit integer r (0 <= r < 2^32) + */ + + + getUint32() { + this.nextState(); + return this.state[3] + this.state[2] >>> 0; + } + /** + * Returns a floating point number r (0.0 <= r < 1.0) + */ + + + getFloat() { + return (this.getUint32() >>> 8) * FLOAT_MUL; + } + + init(seed) { + if (!Number.isInteger(seed)) { + throw new TypeError('seed must be an integer'); + } + + this.state[0] = seed; + this.state[1] = 0; + this.state[2] = 0; + this.state[3] = 0; + + for (let i = 1; i < LOOP; i++) { + this.state[i & 3] ^= i + multiply_uint32(1812433253, this.state[i - 1 & 3] ^ this.state[i - 1 & 3] >>> 30 >>> 0) >>> 0; + } + + this.periodCertification(); + + for (let i = 0; i < LOOP; i++) { + this.nextState(); + } + } -"use strict"; + periodCertification() { + if (this.state[0] === 0 && this.state[1] === 0 && this.state[2] === 0 && this.state[3] === 0) { + this.state[0] = 88; // X + this.state[1] = 83; // S -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RandomForestBase = undefined; + this.state[2] = 65; // A -var _mlCart = __webpack_require__(18); + this.state[3] = 68; // D + } + } -var _mlMatrix = __webpack_require__(0); + nextState() { + let t = this.state[0]; + t ^= t << sh1; + t ^= t >>> sh2; + t ^= this.state[3] << sh3; + this.state[0] = this.state[1]; + this.state[1] = this.state[2]; + this.state[2] = this.state[3]; + this.state[3] = t; + } -var _utils = __webpack_require__(77); +} -var Utils = _interopRequireWildcard(_utils); +/***/ }), +/* 20 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(is_any_array__WEBPACK_IMPORTED_MODULE_0__); -/** - * @class RandomForestBase - */ -class RandomForestBase { - /** - * Create a new base random forest for a classifier or regression model. - * @constructor - * @param {object} options - * @param {number|String} [options.maxFeatures] - the number of features used on each estimator. - * * if is an integer it selects maxFeatures elements over the sample features. - * * if is a float between (0, 1), it takes the percentage of features. - * @param {boolean} [options.replacement] - use replacement over the sample features. - * @param {number} [options.seed] - seed for feature and samples selection, must be a 32-bit integer. - * @param {number} [options.nEstimators] - number of estimator to use. - * @param {object} [options.treeOptions] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/} - * @param {boolean} [options.isClassifier] - boolean to check if is a classifier or regression model (used by subclasses). - * @param {boolean} [options.useSampleBagging] - use bagging over training samples. - * @param {object} model - for load purposes. - */ - constructor(options, model) { - if (options === true) { - this.replacement = model.replacement; - this.maxFeatures = model.maxFeatures; - this.nEstimators = model.nEstimators; - this.treeOptions = model.treeOptions; - this.isClassifier = model.isClassifier; - this.seed = model.seed; - this.n = model.n; - this.indexes = model.indexes; - this.useSampleBagging = model.useSampleBagging; - var Estimator = this.isClassifier ? _mlCart.DecisionTreeClassifier : _mlCart.DecisionTreeRegression; - this.estimators = model.estimators.map(est => Estimator.load(est)); - } else { - this.replacement = options.replacement; - this.maxFeatures = options.maxFeatures; - this.nEstimators = options.nEstimators; - this.treeOptions = options.treeOptions; - this.isClassifier = options.isClassifier; - this.seed = options.seed; - this.useSampleBagging = options.useSampleBagging; - } +function _typeof(obj) { + 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; + }; } - /** - * Train the decision tree with the given training set and labels. - * @param {Matrix|Array} trainingSet - * @param {Array} trainingValues - */ - train(trainingSet, trainingValues) { - trainingSet = _mlMatrix.Matrix.checkMatrix(trainingSet); - - this.maxFeatures = this.maxFeatures || trainingSet.columns; + return _typeof(obj); +} +/** + * Fill an array with sequential numbers + * @param {Array} [input] - optional destination array (if not provided a new array will be created) + * @param {object} [options={}] + * @param {number} [options.from=0] - first value in the array + * @param {number} [options.to=10] - last value in the array + * @param {number} [options.size=input.length] - size of the array (if not provided calculated from step) + * @param {number} [options.step] - if not provided calculated from size + * @return {Array} + */ - if (Utils.checkFloat(this.maxFeatures)) { - this.n = Math.floor(trainingSet.columns * this.maxFeatures); - } else if (Number.isInteger(this.maxFeatures)) { - if (this.maxFeatures > trainingSet.columns) { - throw new RangeError(`The maxFeatures parameter should be less than ${trainingSet.columns}`); - } else { - this.n = this.maxFeatures; - } - } else { - throw new RangeError(`Cannot process the maxFeatures parameter ${this.maxFeatures}`); - } - if (this.isClassifier) { - var Estimator = _mlCart.DecisionTreeClassifier; - } else { - Estimator = _mlCart.DecisionTreeRegression; - } +function sequentialFill() { + var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - this.estimators = new Array(this.nEstimators); - this.indexes = new Array(this.nEstimators); + if (_typeof(input) === 'object' && !is_any_array__WEBPACK_IMPORTED_MODULE_0___default()(input)) { + options = input; + input = []; + } - for (var i = 0; i < this.nEstimators; ++i) { - var res = this.useSampleBagging ? Utils.examplesBaggingWithReplacement(trainingSet, trainingValues, this.seed) : { X: trainingSet, y: trainingValues }; - var X = res.X; - var y = res.y; + if (!is_any_array__WEBPACK_IMPORTED_MODULE_0___default()(input)) { + throw new TypeError('input must be an array'); + } - res = Utils.featureBagging(X, this.n, this.replacement, this.seed); - X = res.X; + var _options = options, + _options$from = _options.from, + from = _options$from === void 0 ? 0 : _options$from, + _options$to = _options.to, + to = _options$to === void 0 ? 10 : _options$to, + _options$size = _options.size, + size = _options$size === void 0 ? input.length : _options$size, + step = _options.step; + + if (size && step) { + throw new Error('step is defined by the array size'); + } - this.indexes[i] = res.usedIndex; - this.estimators[i] = new Estimator(this.treeOptions); - this.estimators[i].train(X, y); + if (!size) { + if (step) { + size = Math.floor((to - from) / step) + 1; + } else { + size = to - from + 1; } } - /** - * Method that returns the way the algorithm generates the predictions, for example, in classification - * you can return the mode of all predictions retrieved by the trees, or in case of regression you can - * use the mean or the median. - * @abstract - * @param {Array} values - predictions of the estimators. - * @return {number} prediction. - */ - // eslint-disable-next-line no-unused-vars - selection(values) { - throw new Error('Abstract method \'selection\' not implemented!'); + if (!step && size) { + step = (to - from) / (size - 1); } - /** - * Predicts the output given the matrix to predict. - * @param {Matrix|Array} toPredict - * @return {Array} predictions - */ - predict(toPredict) { - var predictionValues = new Array(this.nEstimators); - toPredict = _mlMatrix.Matrix.checkMatrix(toPredict); - for (var i = 0; i < this.nEstimators; ++i) { - var X = toPredict.columnSelectionView(this.indexes[i]); // get features for estimator - predictionValues[i] = this.estimators[i].predict(X); - } + if (Array.isArray(input)) { + input.length = 0; // only works with normal array - predictionValues = new _mlMatrix.WrapperMatrix2D(predictionValues).transposeView(); - var predictions = new Array(predictionValues.rows); - for (i = 0; i < predictionValues.rows; ++i) { - predictions[i] = this.selection(predictionValues.getRow(i)); + for (var i = 0; i < size; i++) { + input.push(from); + from += step; + } + } else { + if (input.length !== size) { + throw new Error('sequentialFill typed array must have the correct length'); } - return predictions; + for (var _i = 0; _i < size; _i++) { + input[_i] = from; + from += step; + } } - /** - * Export the current model to JSON. - * @return {object} - Current model. - */ - toJSON() { - return { - indexes: this.indexes, - n: this.n, - replacement: this.replacement, - maxFeatures: this.maxFeatures, - nEstimators: this.nEstimators, - treeOptions: this.treeOptions, - isClassifier: this.isClassifier, - seed: this.seed, - estimators: this.estimators.map(est => est.toJSON()), - useSampleBagging: this.useSampleBagging - }; - } + return input; } -exports.RandomForestBase = RandomForestBase; + +/* harmony default export */ __webpack_exports__["default"] = (sequentialFill); /***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { +/* 21 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var ml_array_mean__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(is_any_array__WEBPACK_IMPORTED_MODULE_1__); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = median; - -var _medianQuickselect = __webpack_require__(80); - -var _medianQuickselect2 = _interopRequireDefault(_medianQuickselect); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - /** - * Computes the median of the given values - * @param {Array} input + * Computes the variance of the given values + * @param {Array} values + * @param {object} [options] + * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n. + * @param {number} [options.mean = arrayMean] - precalculated mean, if any. * @return {number} */ -function median(input) { - if (!Array.isArray(input)) { - throw new Error('input must be an array'); - } - if (input.length === 0) { - throw new Error('input must not be empty'); - } +function variance(values) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!is_any_array__WEBPACK_IMPORTED_MODULE_1___default()(values)) { + throw new TypeError('input must be an array'); + } + + var _options$unbiased = options.unbiased, + unbiased = _options$unbiased === void 0 ? true : _options$unbiased, + _options$mean = options.mean, + mean = _options$mean === void 0 ? Object(ml_array_mean__WEBPACK_IMPORTED_MODULE_0__["default"])(values) : _options$mean; + var sqrError = 0; + + for (var i = 0; i < values.length; i++) { + var x = values[i] - mean; + sqrError += x * x; + } - return (0, _medianQuickselect2.default)(input.slice()); + if (unbiased) { + return sqrError / (values.length - 1); + } else { + return sqrError / values.length; + } } +/* harmony default export */ __webpack_exports__["default"] = (variance); + /***/ }), -/* 27 */ +/* 22 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function compareNumbers(a, b) { - return a - b; + return a - b; } - /** * Computes the sum of the given values * @param {Array} values * @returns {number} */ + + exports.sum = function sum(values) { - var sum = 0; - for (var i = 0; i < values.length; i++) { - sum += values[i]; - } - return sum; -}; + var sum = 0; + + for (var i = 0; i < values.length; i++) { + sum += values[i]; + } + return sum; +}; /** * Computes the maximum of the given values * @param {Array} values * @returns {number} */ + + exports.max = function max(values) { - var max = values[0]; - var l = values.length; - for (var i = 1; i < l; i++) { - if (values[i] > max) max = values[i]; - } - return max; -}; + var max = values[0]; + var l = values.length; + + for (var i = 1; i < l; i++) { + if (values[i] > max) max = values[i]; + } + return max; +}; /** * Computes the minimum of the given values * @param {Array} values * @returns {number} */ + + exports.min = function min(values) { - var min = values[0]; - var l = values.length; - for (var i = 1; i < l; i++) { - if (values[i] < min) min = values[i]; - } - return min; -}; + var min = values[0]; + var l = values.length; + + for (var i = 1; i < l; i++) { + if (values[i] < min) min = values[i]; + } + return min; +}; /** * Computes the min and max of the given values * @param {Array} values * @returns {{min: number, max: number}} */ + + exports.minMax = function minMax(values) { - var min = values[0]; - var max = values[0]; - var l = values.length; - for (var i = 1; i < l; i++) { - if (values[i] < min) min = values[i]; - if (values[i] > max) max = values[i]; - } - return { - min: min, - max: max - }; -}; + var min = values[0]; + var max = values[0]; + var l = values.length; + + for (var i = 1; i < l; i++) { + if (values[i] < min) min = values[i]; + if (values[i] > max) max = values[i]; + } + return { + min: min, + max: max + }; +}; /** * Computes the arithmetic mean of the given values * @param {Array} values * @returns {number} */ + + exports.arithmeticMean = function arithmeticMean(values) { - var sum = 0; - var l = values.length; - for (var i = 0; i < l; i++) { - sum += values[i]; - } - return sum / l; -}; + var sum = 0; + var l = values.length; + + for (var i = 0; i < l; i++) { + sum += values[i]; + } + return sum / l; +}; /** * {@link arithmeticMean} */ -exports.mean = exports.arithmeticMean; + +exports.mean = exports.arithmeticMean; /** * Computes the geometric mean of the given values * @param {Array} values * @returns {number} */ + exports.geometricMean = function geometricMean(values) { - var mul = 1; - var l = values.length; - for (var i = 0; i < l; i++) { - mul *= values[i]; - } - return Math.pow(mul, 1 / l); -}; + var mul = 1; + var l = values.length; + for (var i = 0; i < l; i++) { + mul *= values[i]; + } + + return Math.pow(mul, 1 / l); +}; /** * Computes the mean of the log of the given values * If the return value is exponentiated, it gives the same result as the @@ -5601,32 +8596,38 @@ exports.geometricMean = function geometricMean(values) { * @param {Array} values * @returns {number} */ + + exports.logMean = function logMean(values) { - var lnsum = 0; - var l = values.length; - for (var i = 0; i < l; i++) { - lnsum += Math.log(values[i]); - } - return lnsum / l; -}; + var lnsum = 0; + var l = values.length; + + for (var i = 0; i < l; i++) { + lnsum += Math.log(values[i]); + } + return lnsum / l; +}; /** * Computes the weighted grand mean for a list of means and sample sizes * @param {Array} means - Mean values for each set of samples * @param {Array} samples - Number of original values for each set of samples * @returns {number} */ + + exports.grandMean = function grandMean(means, samples) { - var sum = 0; - var n = 0; - var l = means.length; - for (var i = 0; i < l; i++) { - sum += samples[i] * means[i]; - n += samples[i]; - } - return sum / n; -}; + var sum = 0; + var n = 0; + var l = means.length; + + for (var i = 0; i < l; i++) { + sum += samples[i] * means[i]; + n += samples[i]; + } + return sum / n; +}; /** * Computes the truncated mean of the given values using a given percentage * @param {Array} values @@ -5634,1264 +8635,891 @@ exports.grandMean = function grandMean(means, samples) { * @param {boolean} [alreadySorted=false] * @returns {number} */ + + exports.truncatedMean = function truncatedMean(values, percent, alreadySorted) { - if (alreadySorted === undefined) alreadySorted = false; - if (!alreadySorted) { - values = [].concat(values).sort(compareNumbers); - } - var l = values.length; - var k = Math.floor(l * percent); - var sum = 0; - for (var i = k; i < l - k; i++) { - sum += values[i]; - } - return sum / (l - 2 * k); -}; + if (alreadySorted === undefined) alreadySorted = false; + + if (!alreadySorted) { + values = [].concat(values).sort(compareNumbers); + } + + var l = values.length; + var k = Math.floor(l * percent); + var sum = 0; + for (var i = k; i < l - k; i++) { + sum += values[i]; + } + + return sum / (l - 2 * k); +}; /** * Computes the harmonic mean of the given values * @param {Array} values * @returns {number} */ + + exports.harmonicMean = function harmonicMean(values) { - var sum = 0; - var l = values.length; - for (var i = 0; i < l; i++) { - if (values[i] === 0) { - throw new RangeError('value at index ' + i + 'is zero'); - } - sum += 1 / values[i]; + var sum = 0; + var l = values.length; + + for (var i = 0; i < l; i++) { + if (values[i] === 0) { + throw new RangeError('value at index ' + i + 'is zero'); } - return l / sum; -}; + sum += 1 / values[i]; + } + + return l / sum; +}; /** * Computes the contraharmonic mean of the given values * @param {Array} values * @returns {number} */ + + exports.contraHarmonicMean = function contraHarmonicMean(values) { - var r1 = 0; - var r2 = 0; - var l = values.length; - for (var i = 0; i < l; i++) { - r1 += values[i] * values[i]; - r2 += values[i]; - } - if (r2 < 0) { - throw new RangeError('sum of values is negative'); - } - return r1 / r2; -}; + var r1 = 0; + var r2 = 0; + var l = values.length; + for (var i = 0; i < l; i++) { + r1 += values[i] * values[i]; + r2 += values[i]; + } + + if (r2 < 0) { + throw new RangeError('sum of values is negative'); + } + + return r1 / r2; +}; /** * Computes the median of the given values * @param {Array} values * @param {boolean} [alreadySorted=false] * @returns {number} */ + + exports.median = function median(values, alreadySorted) { - if (alreadySorted === undefined) alreadySorted = false; - if (!alreadySorted) { - values = [].concat(values).sort(compareNumbers); - } - var l = values.length; - var half = Math.floor(l / 2); - if (l % 2 === 0) { - return (values[half - 1] + values[half]) * 0.5; - } else { - return values[half]; - } -}; + if (alreadySorted === undefined) alreadySorted = false; + + if (!alreadySorted) { + values = [].concat(values).sort(compareNumbers); + } + + var l = values.length; + var half = Math.floor(l / 2); + if (l % 2 === 0) { + return (values[half - 1] + values[half]) * 0.5; + } else { + return values[half]; + } +}; /** * Computes the variance of the given values * @param {Array} values * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n. * @returns {number} */ + + exports.variance = function variance(values, unbiased) { - if (unbiased === undefined) unbiased = true; - var theMean = exports.mean(values); - var theVariance = 0; - var l = values.length; + if (unbiased === undefined) unbiased = true; + var theMean = exports.mean(values); + var theVariance = 0; + var l = values.length; - for (var i = 0; i < l; i++) { - var x = values[i] - theMean; - theVariance += x * x; - } + for (var i = 0; i < l; i++) { + var x = values[i] - theMean; + theVariance += x * x; + } - if (unbiased) { - return theVariance / (l - 1); - } else { - return theVariance / l; - } + if (unbiased) { + return theVariance / (l - 1); + } else { + return theVariance / l; + } }; - /** * Computes the standard deviation of the given values * @param {Array} values * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n. * @returns {number} */ + + exports.standardDeviation = function standardDeviation(values, unbiased) { - return Math.sqrt(exports.variance(values, unbiased)); + return Math.sqrt(exports.variance(values, unbiased)); }; exports.standardError = function standardError(values) { - return exports.standardDeviation(values) / Math.sqrt(values.length); + return exports.standardDeviation(values) / Math.sqrt(values.length); }; - /** * IEEE Transactions on biomedical engineering, vol. 52, no. 1, january 2005, p. 76- * Calculate the standard deviation via the Median of the absolute deviation * The formula for the standard deviation only holds for Gaussian random variables. * @returns {{mean: number, stdev: number}} */ + + exports.robustMeanAndStdev = function robustMeanAndStdev(y) { - var mean = 0, - stdev = 0; - var length = y.length, - i = 0; - for (i = 0; i < length; i++) { - mean += y[i]; - } - mean /= length; - var averageDeviations = new Array(length); - for (i = 0; i < length; i++) { - averageDeviations[i] = Math.abs(y[i] - mean); - }averageDeviations.sort(compareNumbers); - if (length % 2 === 1) { - stdev = averageDeviations[(length - 1) / 2] / 0.6745; - } else { - stdev = 0.5 * (averageDeviations[length / 2] + averageDeviations[length / 2 - 1]) / 0.6745; - } + var mean = 0, + stdev = 0; + var length = y.length, + i = 0; - return { - mean: mean, - stdev: stdev - }; + for (i = 0; i < length; i++) { + mean += y[i]; + } + + mean /= length; + var averageDeviations = new Array(length); + + for (i = 0; i < length; i++) averageDeviations[i] = Math.abs(y[i] - mean); + + averageDeviations.sort(compareNumbers); + + if (length % 2 === 1) { + stdev = averageDeviations[(length - 1) / 2] / 0.6745; + } else { + stdev = 0.5 * (averageDeviations[length / 2] + averageDeviations[length / 2 - 1]) / 0.6745; + } + + return { + mean: mean, + stdev: stdev + }; }; exports.quartiles = function quartiles(values, alreadySorted) { - if (typeof alreadySorted === 'undefined') alreadySorted = false; - if (!alreadySorted) { - values = [].concat(values).sort(compareNumbers); - } + if (typeof alreadySorted === 'undefined') alreadySorted = false; - var quart = values.length / 4; - var q1 = values[Math.ceil(quart) - 1]; - var q2 = exports.median(values, true); - var q3 = values[Math.ceil(quart * 3) - 1]; + if (!alreadySorted) { + values = [].concat(values).sort(compareNumbers); + } - return { q1: q1, q2: q2, q3: q3 }; + var quart = values.length / 4; + var q1 = values[Math.ceil(quart) - 1]; + var q2 = exports.median(values, true); + var q3 = values[Math.ceil(quart * 3) - 1]; + return { + q1: q1, + q2: q2, + q3: q3 + }; }; exports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) { - return Math.sqrt(exports.pooledVariance(samples, unbiased)); + return Math.sqrt(exports.pooledVariance(samples, unbiased)); }; exports.pooledVariance = function pooledVariance(samples, unbiased) { - if (typeof unbiased === 'undefined') unbiased = true; - var sum = 0; - var length = 0, - l = samples.length; - for (var i = 0; i < l; i++) { - var values = samples[i]; - var vari = exports.variance(values); + if (typeof unbiased === 'undefined') unbiased = true; + var sum = 0; + var length = 0, + l = samples.length; - sum += (values.length - 1) * vari; + for (var i = 0; i < l; i++) { + var values = samples[i]; + var vari = exports.variance(values); + sum += (values.length - 1) * vari; + if (unbiased) length += values.length - 1;else length += values.length; + } - if (unbiased) length += values.length - 1;else length += values.length; - } - return sum / length; + return sum / length; }; exports.mode = function mode(values) { - var l = values.length, - itemCount = new Array(l), - i; - for (i = 0; i < l; i++) { - itemCount[i] = 0; - } - var itemArray = new Array(l); - var count = 0; + var l = values.length, + itemCount = new Array(l), + i; - for (i = 0; i < l; i++) { - var index = itemArray.indexOf(values[i]); - if (index >= 0) itemCount[index]++;else { - itemArray[count] = values[i]; - itemCount[count] = 1; - count++; - } + for (i = 0; i < l; i++) { + itemCount[i] = 0; + } + + var itemArray = new Array(l); + var count = 0; + + for (i = 0; i < l; i++) { + var index = itemArray.indexOf(values[i]); + if (index >= 0) itemCount[index]++;else { + itemArray[count] = values[i]; + itemCount[count] = 1; + count++; } + } - var maxValue = 0, - maxIndex = 0; - for (i = 0; i < count; i++) { - if (itemCount[i] > maxValue) { - maxValue = itemCount[i]; - maxIndex = i; - } + var maxValue = 0, + maxIndex = 0; + + for (i = 0; i < count; i++) { + if (itemCount[i] > maxValue) { + maxValue = itemCount[i]; + maxIndex = i; } + } - return itemArray[maxIndex]; + return itemArray[maxIndex]; }; exports.covariance = function covariance(vector1, vector2, unbiased) { - if (typeof unbiased === 'undefined') unbiased = true; - var mean1 = exports.mean(vector1); - var mean2 = exports.mean(vector2); - - if (vector1.length !== vector2.length) throw 'Vectors do not have the same dimensions'; + if (typeof unbiased === 'undefined') unbiased = true; + var mean1 = exports.mean(vector1); + var mean2 = exports.mean(vector2); + if (vector1.length !== vector2.length) throw 'Vectors do not have the same dimensions'; + var cov = 0, + l = vector1.length; - var cov = 0, - l = vector1.length; - for (var i = 0; i < l; i++) { - var x = vector1[i] - mean1; - var y = vector2[i] - mean2; - cov += x * y; - } + for (var i = 0; i < l; i++) { + var x = vector1[i] - mean1; + var y = vector2[i] - mean2; + cov += x * y; + } - if (unbiased) return cov / (l - 1);else return cov / l; + if (unbiased) return cov / (l - 1);else return cov / l; }; exports.skewness = function skewness(values, unbiased) { - if (typeof unbiased === 'undefined') unbiased = true; - var theMean = exports.mean(values); + if (typeof unbiased === 'undefined') unbiased = true; + var theMean = exports.mean(values); + var s2 = 0, + s3 = 0, + l = values.length; - var s2 = 0, - s3 = 0, - l = values.length; - for (var i = 0; i < l; i++) { - var dev = values[i] - theMean; - s2 += dev * dev; - s3 += dev * dev * dev; - } - var m2 = s2 / l; - var m3 = s3 / l; + for (var i = 0; i < l; i++) { + var dev = values[i] - theMean; + s2 += dev * dev; + s3 += dev * dev * dev; + } - var g = m3 / Math.pow(m2, 3 / 2.0); - if (unbiased) { - var a = Math.sqrt(l * (l - 1)); - var b = l - 2; - return a / b * g; - } else { - return g; - } + var m2 = s2 / l; + var m3 = s3 / l; + var g = m3 / Math.pow(m2, 3 / 2.0); + + if (unbiased) { + var a = Math.sqrt(l * (l - 1)); + var b = l - 2; + return a / b * g; + } else { + return g; + } }; exports.kurtosis = function kurtosis(values, unbiased) { - if (typeof unbiased === 'undefined') unbiased = true; - var theMean = exports.mean(values); - var n = values.length, - s2 = 0, - s4 = 0; + if (typeof unbiased === 'undefined') unbiased = true; + var theMean = exports.mean(values); + var n = values.length, + s2 = 0, + s4 = 0; - for (var i = 0; i < n; i++) { - var dev = values[i] - theMean; - s2 += dev * dev; - s4 += dev * dev * dev * dev; - } - var m2 = s2 / n; - var m4 = s4 / n; + for (var i = 0; i < n; i++) { + var dev = values[i] - theMean; + s2 += dev * dev; + s4 += dev * dev * dev * dev; + } - if (unbiased) { - var v = s2 / (n - 1); - var a = n * (n + 1) / ((n - 1) * (n - 2) * (n - 3)); - var b = s4 / (v * v); - var c = (n - 1) * (n - 1) / ((n - 2) * (n - 3)); + var m2 = s2 / n; + var m4 = s4 / n; - return a * b - 3 * c; - } else { - return m4 / (m2 * m2) - 3; - } + if (unbiased) { + var v = s2 / (n - 1); + var a = n * (n + 1) / ((n - 1) * (n - 2) * (n - 3)); + var b = s4 / (v * v); + var c = (n - 1) * (n - 1) / ((n - 2) * (n - 3)); + return a * b - 3 * c; + } else { + return m4 / (m2 * m2) - 3; + } }; exports.entropy = function entropy(values, eps) { - if (typeof eps === 'undefined') eps = 0; - var sum = 0, - l = values.length; - for (var i = 0; i < l; i++) { - sum += values[i] * Math.log(values[i] + eps); - }return -sum; + if (typeof eps === 'undefined') eps = 0; + var sum = 0, + l = values.length; + + for (var i = 0; i < l; i++) sum += values[i] * Math.log(values[i] + eps); + + return -sum; }; exports.weightedMean = function weightedMean(values, weights) { - var sum = 0, - l = values.length; - for (var i = 0; i < l; i++) { - sum += values[i] * weights[i]; - }return sum; + var sum = 0, + l = values.length; + + for (var i = 0; i < l; i++) sum += values[i] * weights[i]; + + return sum; }; exports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) { - return Math.sqrt(exports.weightedVariance(values, weights)); + return Math.sqrt(exports.weightedVariance(values, weights)); }; exports.weightedVariance = function weightedVariance(values, weights) { - var theMean = exports.weightedMean(values, weights); - var vari = 0, - l = values.length; - var a = 0, - b = 0; + var theMean = exports.weightedMean(values, weights); + var vari = 0, + l = values.length; + var a = 0, + b = 0; - for (var i = 0; i < l; i++) { - var z = values[i] - theMean; - var w = weights[i]; - - vari += w * (z * z); - b += w; - a += w * w; - } + for (var i = 0; i < l; i++) { + var z = values[i] - theMean; + var w = weights[i]; + vari += w * (z * z); + b += w; + a += w * w; + } - return vari * (b / (b * b - a)); + return vari * (b / (b * b - a)); }; exports.center = function center(values, inPlace) { - if (typeof inPlace === 'undefined') inPlace = false; - - var result = values; - if (!inPlace) result = [].concat(values); - - var theMean = exports.mean(result), - l = result.length; - for (var i = 0; i < l; i++) { - result[i] -= theMean; - } -}; - -exports.standardize = function standardize(values, standardDev, inPlace) { - if (typeof standardDev === 'undefined') standardDev = exports.standardDeviation(values); - if (typeof inPlace === 'undefined') inPlace = false; - var l = values.length; - var result = inPlace ? values : new Array(l); - for (var i = 0; i < l; i++) { - result[i] = values[i] / standardDev; - }return result; -}; + if (typeof inPlace === 'undefined') inPlace = false; + var result = values; + if (!inPlace) result = [].concat(values); + var theMean = exports.mean(result), + l = result.length; -exports.cumulativeSum = function cumulativeSum(array) { - var l = array.length; - var result = new Array(l); - result[0] = array[0]; - for (var i = 1; i < l; i++) { - result[i] = result[i - 1] + array[i]; - }return result; + for (var i = 0; i < l; i++) result[i] -= theMean; }; -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var Cluster = __webpack_require__(14); -var util = __webpack_require__(86); - -function ClusterLeaf(index) { - Cluster.call(this); - this.index = index; - this.distance = 0; - this.children = []; -} - -util.inherits(ClusterLeaf, Cluster); - -module.exports = ClusterLeaf; - -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/** - * Computes a distance/similarity matrix given an array of data and a distance/similarity function. - * @param {Array} data An array of data - * @param {function} distanceFn A function that accepts two arguments and computes a distance/similarity between them - * @return {Array} The similarity matrix. The similarity matrix is square and has a size equal to the length of - * the data array - */ - -function distanceMatrix(data, distanceFn) { - var length = data.length; - var result = Array.from({ length }).map(() => Array.from({ length })); - - // Compute upper distance matrix - for (var i = 0; i < length; i++) { - for (var j = 0; j <= i; j++) { - result[i][j] = distanceFn(data[i], data[j]); - } - } - - // Copy to lower distance matrix - for (var _i = 0; _i < length; _i++) { - for (var _j = _i + 1; _j < length; _j++) { - result[_i][_j] = result[_j][_i]; - } - } - - return result; -} - -module.exports = distanceMatrix; - -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.calculateDistanceMatrix = calculateDistanceMatrix; -exports.updateClusterID = updateClusterID; -exports.updateCenters = updateCenters; -exports.hasConverged = hasConverged; - -var _mlNearestVector = __webpack_require__(93); - -var _mlNearestVector2 = _interopRequireDefault(_mlNearestVector); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Calculates the distance matrix for a given array of points - * @ignore - * @param {Array>} data - the [x,y,z,...] points to cluster - * @param {function} distance - Distance function to use between the points - * @return {Array>} - matrix with the distance values - */ -function calculateDistanceMatrix(data, distance) { - var distanceMatrix = new Array(data.length); - for (var i = 0; i < data.length; ++i) { - for (var j = i; j < data.length; ++j) { - if (!distanceMatrix[i]) { - distanceMatrix[i] = new Array(data.length); - } - if (!distanceMatrix[j]) { - distanceMatrix[j] = new Array(data.length); - } - var dist = distance(data[i], data[j]); - distanceMatrix[i][j] = dist; - distanceMatrix[j][i] = dist; - } - } - return distanceMatrix; -} - -/** - * Updates the cluster identifier based in the new data - * @ignore - * @param {Array>} data - the [x,y,z,...] points to cluster - * @param {Array>} centers - the K centers in format [x,y,z,...] - * @param {Array } clusterID - the cluster identifier for each data dot - * @param {function} distance - Distance function to use between the points - * @return {Array} the cluster identifier for each data dot - */ -function updateClusterID(data, centers, clusterID, distance) { - for (var i = 0; i < data.length; i++) { - clusterID[i] = (0, _mlNearestVector2.default)(centers, data[i], { - distanceFunction: distance - }); - } - return clusterID; -} - -/** - * Update the center values based in the new configurations of the clusters - * @ignore - * @param {Array>} prevCenters - Centroids from the previous iteration - * @param {Array >} data - the [x,y,z,...] points to cluster - * @param {Array } clusterID - the cluster identifier for each data dot - * @param {number} K - Number of clusters - * @return {Array} he K centers in format [x,y,z,...] - */ -function updateCenters(prevCenters, data, clusterID, K) { - var nDim = data[0].length; - - // copy previous centers - var centers = new Array(K); - var centersLen = new Array(K); - for (var i = 0; i < K; i++) { - centers[i] = new Array(nDim); - centersLen[i] = 0; - for (var j = 0; j < nDim; j++) { - centers[i][j] = 0; - } - } - - // add the value for all dimensions of the point - for (var l = 0; l < data.length; l++) { - centersLen[clusterID[l]]++; - for (var dim = 0; dim < nDim; dim++) { - centers[clusterID[l]][dim] += data[l][dim]; - } - } +exports.standardize = function standardize(values, standardDev, inPlace) { + if (typeof standardDev === 'undefined') standardDev = exports.standardDeviation(values); + if (typeof inPlace === 'undefined') inPlace = false; + var l = values.length; + var result = inPlace ? values : new Array(l); - // divides by length - for (var id = 0; id < K; id++) { - for (var d = 0; d < nDim; d++) { - if (centersLen[id]) { - centers[id][d] /= centersLen[id]; - } else { - centers[id][d] = prevCenters[id][d]; - } - } - } - return centers; -} + for (var i = 0; i < l; i++) result[i] = values[i] / standardDev; -/** - * The centers have moved more than the tolerance value? - * @ignore - * @param {Array>} centers - the K centers in format [x,y,z,...] - * @param {Array>} oldCenters - the K old centers in format [x,y,z,...] - * @param {function} distanceFunction - Distance function to use between the points - * @param {number} tolerance - Allowed distance for the centroids to move - * @return {boolean} - */ -function hasConverged(centers, oldCenters, distanceFunction, tolerance) { - for (var i = 0; i < centers.length; i++) { - if (distanceFunction(centers[i], oldCenters[i]) > tolerance) { - return false; - } - } - return true; -} + return result; +}; + +exports.cumulativeSum = function cumulativeSum(array) { + var l = array.length; + var result = new Array(l); + result[0] = array[0]; + + for (var i = 1; i < l; i++) result[i] = result[i - 1] + array[i]; + + return result; +}; /***/ }), -/* 31 */ +/* 23 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); +const Cluster = __webpack_require__(15); -var _choice = __webpack_require__(95); +const util = __webpack_require__(49); + +function ClusterLeaf(index) { + Cluster.call(this); + this.index = index; + this.distance = 0; + this.children = []; +} -var _choice2 = _interopRequireDefault(_choice); +util.inherits(ClusterLeaf, Cluster); +module.exports = ClusterLeaf; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { -// tslint:disable-next-line -var XSAdd = __webpack_require__(32); +"use strict"; /** - * @classdesc Random class + * Computes a distance/similarity matrix given an array of data and a distance/similarity function. + * @param {Array} data An array of data + * @param {function} distanceFn A function that accepts two arguments and computes a distance/similarity between them + * @return {Array} The similarity matrix. The similarity matrix is square and has a size equal to the length of + * the data array */ -class Random { - /** - * @param [seedOrRandom=Math.random] - Control the random number generator used by the Random class instance. Pass a random number generator function with a uniform distribution over the half-open interval [0, 1[. If seed will pass it to ml-xsadd to create a seeded random number generator. If undefined will use Math.random. - */ - constructor(seedOrRandom = Math.random) { - if (typeof seedOrRandom === 'number') { - var xsadd = new XSAdd(seedOrRandom); - this.randomGenerator = xsadd.random; - } else { - this.randomGenerator = seedOrRandom; - } - } - choice(values, options) { - if (typeof values === 'number') { - return (0, _choice2.default)(values, options, this.randomGenerator); - } - return (0, _choice2.default)(values, options, this.randomGenerator); - } - /** - * Draw a random number from a uniform distribution on [0,1) - * @return The random number - */ - random() { - return this.randomGenerator(); - } - /** - * Draw a random integer from a uniform distribution on [low, high). If only low is specified, the number is drawn on [0, low) - * @param low - The lower bound of the uniform distribution interval. - * @param high - The higher bound of the uniform distribution interval. - */ - randInt(low, high) { - if (high === undefined) { - high = low; - low = 0; - } - return low + Math.floor(this.randomGenerator() * (high - low)); - } - /** - * Draw several random number from a uniform distribution on [0, 1) - * @param size - The number of number to draw - * @return - The list of drawn numbers. - */ - randomSample(size) { - var result = []; - for (var i = 0; i < size; i++) { - result.push(this.random()); - } - return result; + +function distanceMatrix(data, distanceFn) { + const length = data.length; + let result = Array.from({ + length + }).map(() => Array.from({ + length + })); // Compute upper distance matrix + + for (let i = 0; i < length; i++) { + for (let j = 0; j <= i; j++) { + result[i][j] = distanceFn(data[i], data[j]); } -} -exports.default = Random; + } // Copy to lower distance matrix -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + for (let i = 0; i < length; i++) { + for (let j = i + 1; j < length; j++) { + result[i][j] = result[j][i]; + } + } + return result; +} -Object.defineProperty(exports, "__esModule", { - value: true -}); +module.exports = distanceMatrix; -var _createClass = 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); - } - }return function (Constructor, protoProps, staticProps) { - if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor; - }; -}(); +/***/ }), +/* 25 */ +/***/ (function(module, exports) { -function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); +/** + * Constructs a confusion matrix + * @class ConfusionMatrix + * @example + * const CM = new ConfusionMatrix([[13, 2], [10, 5]], ['cat', 'dog']) + * @param {Array>} matrix - The confusion matrix, a 2D Array. Rows represent the actual label and columns + * the predicted label. + * @param {Array} labels - Labels of the confusion matrix, a 1D Array + */ +class ConfusionMatrix { + constructor(matrix, labels) { + if (matrix.length !== matrix[0].length) { + throw new Error('Confusion matrix must be square'); } -} -var LOOP = 8; -var FLOAT_MUL = 1 / 16777216; + if (labels.length !== matrix.length) { + throw new Error('Confusion matrix and labels should have the same length'); + } -function multiply_uint32(n, m) { - n >>>= 0; - m >>>= 0; - var nlo = n & 0xffff; - var nhi = n - nlo; - return (nhi * m >>> 0) + nlo * m >>> 0; -} + this.labels = labels; + this.matrix = matrix; + } + /** + * Construct confusion matrix from the predicted and actual labels (classes). Be sure to provide the arguments in + * the correct order! + * @param {Array} actual - The predicted labels of the classification + * @param {Array} predicted - The actual labels of the classification. Has to be of same length as + * predicted. + * @param {object} [options] - Additional options + * @param {Array} [options.labels] - The list of labels that should be used. If not provided the distinct set + * of labels present in predicted and actual is used. Labels are compared using the strict equality operator + * '===' + * @return {ConfusionMatrix} - Confusion matrix + */ -var XSadd = function () { - function XSadd() { - var seed = arguments.length <= 0 || arguments[0] === undefined ? Date.now() : arguments[0]; - _classCallCheck(this, XSadd); + static fromLabels(actual, predicted) { + let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - this.state = new Uint32Array(4); - this.init(seed); + if (predicted.length !== actual.length) { + throw new Error('predicted and actual must have the same length'); } - _createClass(XSadd, [{ - key: "init", - value: function init(seed) { - this.state[0] = seed; - this.state[1] = 0; - this.state[2] = 0; - this.state[3] = 0; - for (var i = 1; i < LOOP; i++) { - this.state[i & 3] ^= i + multiply_uint32(1812433253, this.state[i - 1 & 3] ^ this.state[i - 1 & 3] >>> 30 >>> 0) >>> 0; - } - period_certification(this); - for (var i = 0; i < LOOP; i++) { - next_state(this); - } - } + let distinctLabels; - /** - * Returns a 32-bit integer r (0 <= r < 2^32) - */ - }, { - key: "getUint32", - value: function getUint32() { - next_state(this); - return this.state[3] + this.state[2] >>> 0; - } + if (options.labels) { + distinctLabels = new Set(options.labels); + } else { + distinctLabels = new Set([...actual, ...predicted]); + } - /** - * Returns a floating point number r (0.0 <= r < 1.0) - */ - }, { - key: "getFloat", - value: function getFloat() { - return (this.getUint32() >>> 8) * FLOAT_MUL; - } - }, { - key: "random", - get: function get() { - if (!this._random) { - this._random = this.getFloat.bind(this); - } - return this._random; - } - }]); + distinctLabels = Array.from(distinctLabels); + + if (options.sort) { + distinctLabels.sort(options.sort); + } // Create confusion matrix and fill with 0's - return XSadd; -}(); -exports["default"] = XSadd; + const matrix = Array.from({ + length: distinctLabels.length + }); -function period_certification(xsadd) { - if (xsadd.state[0] === 0 && xsadd.state[1] === 0 && xsadd.state[2] === 0 && xsadd.state[3] === 0) { - xsadd.state[0] = 88; // X - xsadd.state[1] = 83; // S - xsadd.state[2] = 65; // A - xsadd.state[3] = 68; // D + for (let i = 0; i < matrix.length; i++) { + matrix[i] = new Array(matrix.length); + matrix[i].fill(0); } -} -var sh1 = 15; -var sh2 = 18; -var sh3 = 11; -function next_state(xsadd) { - var t = xsadd.state[0]; - t ^= t << sh1; - t ^= t >>> sh2; - t ^= xsadd.state[3] << sh3; - xsadd.state[0] = xsadd.state[1]; - xsadd.state[1] = xsadd.state[2]; - xsadd.state[2] = xsadd.state[3]; - xsadd.state[3] = t; -} -module.exports = exports["default"]; + for (let i = 0; i < predicted.length; i++) { + const actualIdx = distinctLabels.indexOf(actual[i]); + const predictedIdx = distinctLabels.indexOf(predicted[i]); -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { + if (actualIdx >= 0 && predictedIdx >= 0) { + matrix[actualIdx][predictedIdx]++; + } + } -"use strict"; + return new ConfusionMatrix(matrix, distinctLabels); + } + /** + * Get the confusion matrix + * @return {Array >} + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.separateClasses = separateClasses; + getMatrix() { + return this.matrix; + } -var _mlMatrix = __webpack_require__(0); + getLabels() { + return this.labels; + } + /** + * Get the total number of samples + * @return {number} + */ -var _mlMatrix2 = _interopRequireDefault(_mlMatrix); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + getTotalCount() { + let predicted = 0; -/** - * @private - * Function that retuns an array of matrices of the cases that belong to each class. - * @param {Matrix} X - dataset - * @param {Array} y - predictions - * @return {Array} - */ -function separateClasses(X, y) { - var features = X.columns; - - var classes = 0; - var totalPerClasses = new Array(10000); // max upperbound of classes - for (var i = 0; i < y.length; i++) { - if (totalPerClasses[y[i]] === undefined) { - totalPerClasses[y[i]] = 0; - classes++; - } - totalPerClasses[y[i]]++; - } - var separatedClasses = new Array(classes); - var currentIndex = new Array(classes); - for (i = 0; i < classes; ++i) { - separatedClasses[i] = new _mlMatrix2.default(totalPerClasses[i], features); - currentIndex[i] = 0; + for (var i = 0; i < this.matrix.length; i++) { + for (var j = 0; j < this.matrix.length; j++) { + predicted += this.matrix[i][j]; + } } - for (i = 0; i < X.rows; ++i) { - separatedClasses[y[i]].setRow(currentIndex[y[i]], X.getRow(i)); - currentIndex[y[i]]++; + + return predicted; + } + /** + * Get the total number of true predictions + * @return {number} + */ + + + getTrueCount() { + var count = 0; + + for (var i = 0; i < this.matrix.length; i++) { + count += this.matrix[i][i]; } - return separatedClasses; -} -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { + return count; + } + /** + * Get the total number of false predictions. + * @return {number} + */ -"use strict"; + + getFalseCount() { + return this.getTotalCount() - this.getTrueCount(); + } + /** + * Get the number of true positive predictions. + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.norm = norm; -exports.pow2array = pow2array; -exports.featureNormalize = featureNormalize; -exports.initializeMatrices = initializeMatrices; + getTruePositiveCount(label) { + const index = this.getIndex(label); + return this.matrix[index][index]; + } + /** + * Get the number of true negative predictions + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ + -var _mlMatrix = __webpack_require__(0); + getTrueNegativeCount(label) { + const index = this.getIndex(label); + var count = 0; + + for (var i = 0; i < this.matrix.length; i++) { + for (var j = 0; j < this.matrix.length; j++) { + if (i !== index && j !== index) { + count += this.matrix[i][j]; + } + } + } -var _mlMatrix2 = _interopRequireDefault(_mlMatrix); + return count; + } + /** + * Get the number of false positive predictions. + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ -var _matrix = __webpack_require__(10); -var _matrix2 = _interopRequireDefault(_matrix); + getFalsePositiveCount(label) { + const index = this.getIndex(label); + var count = 0; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (var i = 0; i < this.matrix.length; i++) { + if (i !== index) { + count += this.matrix[i][index]; + } + } -/** - * @private - * Function that given vector, returns his norm - * @param {Vector} X - * @return {number} Norm of the vector - */ -function norm(X) { - return Math.sqrt(X.clone().apply(pow2array).sum()); -} + return count; + } + /** + * Get the number of false negative predictions. + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ -/** - * @private - * Function that pow 2 each element of a Matrix or a Vector, - * used in the apply method of the Matrix object - * @param {number} i - index i. - * @param {number} j - index j. - * @return {Matrix} The Matrix object modified at the index i, j. - * */ -function pow2array(i, j) { - this[i][j] = this[i][j] * this[i][j]; - return this; -} -/** - * @private - * Function that normalize the dataset and return the means and - * standard deviation of each feature. - * @param {Matrix} dataset - * @return {object} dataset normalized, means and standard deviations - */ -function featureNormalize(dataset) { - var means = _matrix2.default.mean(dataset); - var std = _matrix2.default.standardDeviation(dataset, means, true); - var result = _mlMatrix2.default.checkMatrix(dataset).subRowVector(means); - return { result: result.divRowVector(std), means: means, std: std }; -} + getFalseNegativeCount(label) { + const index = this.getIndex(label); + var count = 0; -/** - * @private - * Function that initialize an array of matrices. - * @param {Array} array - * @param {boolean} isMatrix - * @return {Array} array with the matrices initialized. - */ -function initializeMatrices(array, isMatrix) { - if (isMatrix) { - for (var i = 0; i < array.length; ++i) { - for (var j = 0; j < array[i].length; ++j) { - var elem = array[i][j]; - array[i][j] = elem !== null ? new _mlMatrix2.default(array[i][j]) : undefined; - } - } - } else { - for (i = 0; i < array.length; ++i) { - array[i] = new _mlMatrix2.default(array[i]); - } + for (var i = 0; i < this.matrix.length; i++) { + if (i !== index) { + count += this.matrix[index][i]; + } } - return array; -} + return count; + } + /** + * Get the number of real positive samples. + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ + + + getPositiveCount(label) { + return this.getTruePositiveCount(label) + this.getFalseNegativeCount(label); + } + /** + * Get the number of real negative samples. + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ + -/***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { + getNegativeCount(label) { + return this.getTrueNegativeCount(label) + this.getFalsePositiveCount(label); + } + /** + * Get the index in the confusion matrix that corresponds to the given label + * @param {any} label - The label to search for + * @throws if the label is not found + * @return {number} + */ -"use strict"; + getIndex(label) { + const index = this.labels.indexOf(label); + if (index === -1) throw new Error('The label does not exist'); + return index; + } + /** + * Get the true positive rate a.k.a. sensitivity. Computes the ratio between the number of true positive predictions and the total number of positive samples. + * {@link https://en.wikipedia.org/wiki/Sensitivity_and_specificity} + * @param {any} label - The label that should be considered "positive" + * @return {number} - The true positive rate [0-1] + */ -/** - * Constructs a confusion matrix - * @class ConfusionMatrix - * @example - * const CM = new ConfusionMatrix([[13, 2], [10, 5]], ['cat', 'dog']) - * @param {Array>} matrix - The confusion matrix, a 2D Array. Rows represent the actual label and columns - * the predicted label. - * @param {Array} labels - Labels of the confusion matrix, a 1D Array - */ -class ConfusionMatrix { - constructor(matrix, labels) { - if (matrix.length !== matrix[0].length) { - throw new Error('Confusion matrix must be square'); - } - if (labels.length !== matrix.length) { - throw new Error('Confusion matrix and labels should have the same length'); - } - this.labels = labels; - this.matrix = matrix; - } - /** - * Construct confusion matrix from the predicted and actual labels (classes). Be sure to provide the arguments in - * the correct order! - * @param {Array} actual - The predicted labels of the classification - * @param {Array} predicted - The actual labels of the classification. Has to be of same length as - * predicted. - * @param {object} [options] - Additional options - * @param {Array} [options.labels] - The list of labels that should be used. If not provided the distinct set - * of labels present in predicted and actual is used. Labels are compared using the strict equality operator - * '===' - * @return {ConfusionMatrix} - Confusion matrix - */ - static fromLabels(actual, predicted, options = {}) { - if (predicted.length !== actual.length) { - throw new Error('predicted and actual must have the same length'); - } - var distinctLabels = void 0; - if (options.labels) { - distinctLabels = new Set(options.labels); - } else { - distinctLabels = new Set([...actual, ...predicted]); - } - distinctLabels = Array.from(distinctLabels); - if (options.sort) { - distinctLabels.sort(options.sort); - } + getTruePositiveRate(label) { + return this.getTruePositiveCount(label) / this.getPositiveCount(label); + } + /** + * Get the true negative rate a.k.a. specificity. Computes the ration between the number of true negative predictions and the total number of negative samples. + * {@link https://en.wikipedia.org/wiki/Sensitivity_and_specificity} + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - // Create confusion matrix and fill with 0's - var matrix = Array.from({ length: distinctLabels.length }); - for (var i = 0; i < matrix.length; i++) { - matrix[i] = new Array(matrix.length); - matrix[i].fill(0); - } - for (var _i = 0; _i < predicted.length; _i++) { - var actualIdx = distinctLabels.indexOf(actual[_i]); - var predictedIdx = distinctLabels.indexOf(predicted[_i]); - if (actualIdx >= 0 && predictedIdx >= 0) { - matrix[actualIdx][predictedIdx]++; - } - } + getTrueNegativeRate(label) { + return this.getTrueNegativeCount(label) / this.getNegativeCount(label); + } + /** + * Get the positive predictive value a.k.a. precision. Computes TP / (TP + FP) + * {@link https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values} + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - return new ConfusionMatrix(matrix, distinctLabels); - } - /** - * Get the confusion matrix - * @return {Array >} - */ - getMatrix() { - return this.matrix; - } + getPositivePredictiveValue(label) { + const TP = this.getTruePositiveCount(label); + return TP / (TP + this.getFalsePositiveCount(label)); + } + /** + * Negative predictive value + * {@link https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values} + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - getLabels() { - return this.labels; - } - /** - * Get the total number of samples - * @return {number} - */ - getTotalCount() { - var predicted = 0; - for (var i = 0; i < this.matrix.length; i++) { - for (var j = 0; j < this.matrix.length; j++) { - predicted += this.matrix[i][j]; - } - } - return predicted; - } + getNegativePredictiveValue(label) { + const TN = this.getTrueNegativeCount(label); + return TN / (TN + this.getFalseNegativeCount(label)); + } + /** + * False negative rate a.k.a. miss rate. + * {@link https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#False_positive_and_false_negative_rates} + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - /** - * Get the total number of true predictions - * @return {number} - */ - getTrueCount() { - var count = 0; - for (var i = 0; i < this.matrix.length; i++) { - count += this.matrix[i][i]; - } - return count; - } - /** - * Get the total number of false predictions. - * @return {number} - */ - getFalseCount() { - return this.getTotalCount() - this.getTrueCount(); - } + getFalseNegativeRate(label) { + return 1 - this.getTruePositiveRate(label); + } + /** + * False positive rate a.k.a. fall-out rate. + * {@link https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#False_positive_and_false_negative_rates} + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - /** - * Get the number of true positive predictions. - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getTruePositiveCount(label) { - var index = this.getIndex(label); - return this.matrix[index][index]; - } - /** - * Get the number of true negative predictions - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getTrueNegativeCount(label) { - var index = this.getIndex(label); - var count = 0; - for (var i = 0; i < this.matrix.length; i++) { - for (var j = 0; j < this.matrix.length; j++) { - if (i !== index && j !== index) { - count += this.matrix[i][j]; - } - } - } - return count; - } + getFalsePositiveRate(label) { + return 1 - this.getTrueNegativeRate(label); + } + /** + * False discovery rate (FDR) + * {@link https://en.wikipedia.org/wiki/False_discovery_rate} + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - /** - * Get the number of false positive predictions. - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getFalsePositiveCount(label) { - var index = this.getIndex(label); - var count = 0; - for (var i = 0; i < this.matrix.length; i++) { - if (i !== index) { - count += this.matrix[i][index]; - } - } - return count; - } - /** - * Get the number of false negative predictions. - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getFalseNegativeCount(label) { - var index = this.getIndex(label); - var count = 0; - for (var i = 0; i < this.matrix.length; i++) { - if (i !== index) { - count += this.matrix[index][i]; - } - } - return count; - } + getFalseDiscoveryRate(label) { + const FP = this.getFalsePositiveCount(label); + return FP / (FP + this.getTruePositiveCount(label)); + } + /** + * False omission rate (FOR) + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - /** - * Get the number of real positive samples. - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getPositiveCount(label) { - return this.getTruePositiveCount(label) + this.getFalseNegativeCount(label); - } - /** - * Get the number of real negative samples. - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getNegativeCount(label) { - return this.getTrueNegativeCount(label) + this.getFalsePositiveCount(label); - } + getFalseOmissionRate(label) { + const FN = this.getFalseNegativeCount(label); + return FN / (FN + this.getTruePositiveCount(label)); + } + /** + * F1 score + * {@link https://en.wikipedia.org/wiki/F1_score} + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - /** - * Get the index in the confusion matrix that corresponds to the given label - * @param {any} label - The label to search for - * @throws if the label is not found - * @return {number} - */ - getIndex(label) { - var index = this.labels.indexOf(label); - if (index === -1) throw new Error('The label does not exist'); - return index; - } - /** - * Get the true positive rate a.k.a. sensitivity. Computes the ratio between the number of true positive predictions and the total number of positive samples. - * {@link https://en.wikipedia.org/wiki/Sensitivity_and_specificity} - * @param {any} label - The label that should be considered "positive" - * @return {number} - The true positive rate [0-1] - */ - getTruePositiveRate(label) { - return this.getTruePositiveCount(label) / this.getPositiveCount(label); - } + getF1Score(label) { + const TP = this.getTruePositiveCount(label); + return 2 * TP / (2 * TP + this.getFalsePositiveCount(label) + this.getFalseNegativeCount(label)); + } + /** + * Matthews correlation coefficient (MCC) + * {@link https://en.wikipedia.org/wiki/Matthews_correlation_coefficient} + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - /** - * Get the true negative rate a.k.a. specificity. Computes the ration between the number of true negative predictions and the total number of negative samples. - * {@link https://en.wikipedia.org/wiki/Sensitivity_and_specificity} - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getTrueNegativeRate(label) { - return this.getTrueNegativeCount(label) / this.getNegativeCount(label); - } - /** - * Get the positive predictive value a.k.a. precision. Computes TP / (TP + FP) - * {@link https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values} - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getPositivePredictiveValue(label) { - var TP = this.getTruePositiveCount(label); - return TP / (TP + this.getFalsePositiveCount(label)); - } + getMatthewsCorrelationCoefficient(label) { + const TP = this.getTruePositiveCount(label); + const TN = this.getTrueNegativeCount(label); + const FP = this.getFalsePositiveCount(label); + const FN = this.getFalseNegativeCount(label); + return (TP * TN - FP * FN) / Math.sqrt((TP + FP) * (TP + FN) * (TN + FP) * (TN + FN)); + } + /** + * Informedness + * {@link https://en.wikipedia.org/wiki/Youden%27s_J_statistic} + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - /** - * Negative predictive value - * {@link https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values} - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getNegativePredictiveValue(label) { - var TN = this.getTrueNegativeCount(label); - return TN / (TN + this.getFalseNegativeCount(label)); - } - /** - * False negative rate a.k.a. miss rate. - * {@link https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#False_positive_and_false_negative_rates} - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getFalseNegativeRate(label) { - return 1 - this.getTruePositiveRate(label); - } + getInformedness(label) { + return this.getTruePositiveRate(label) + this.getTrueNegativeRate(label) - 1; + } + /** + * Markedness + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - /** - * False positive rate a.k.a. fall-out rate. - * {@link https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#False_positive_and_false_negative_rates} - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getFalsePositiveRate(label) { - return 1 - this.getTrueNegativeRate(label); - } - /** - * False discovery rate (FDR) - * {@link https://en.wikipedia.org/wiki/False_discovery_rate} - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getFalseDiscoveryRate(label) { - var FP = this.getFalsePositiveCount(label); - return FP / (FP + this.getTruePositiveCount(label)); - } + getMarkedness(label) { + return this.getPositivePredictiveValue(label) + this.getNegativePredictiveValue(label) - 1; + } + /** + * Get the confusion table. + * @param {any} label - The label that should be considered "positive" + * @return {Array >} - The 2x2 confusion table. [[TP, FN], [FP, TN]] + */ - /** - * False omission rate (FOR) - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getFalseOmissionRate(label) { - var FN = this.getFalseNegativeCount(label); - return FN / (FN + this.getTruePositiveCount(label)); - } - /** - * F1 score - * {@link https://en.wikipedia.org/wiki/F1_score} - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getF1Score(label) { - var TP = this.getTruePositiveCount(label); - return 2 * TP / (2 * TP + this.getFalsePositiveCount(label) + this.getFalseNegativeCount(label)); - } + getConfusionTable(label) { + return [[this.getTruePositiveCount(label), this.getFalseNegativeCount(label)], [this.getFalsePositiveCount(label), this.getTrueNegativeCount(label)]]; + } + /** + * Get total accuracy. + * @return {number} - The ratio between the number of true predictions and total number of classifications ([0-1]) + */ - /** - * Matthews correlation coefficient (MCC) - * {@link https://en.wikipedia.org/wiki/Matthews_correlation_coefficient} - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getMatthewsCorrelationCoefficient(label) { - var TP = this.getTruePositiveCount(label); - var TN = this.getTrueNegativeCount(label); - var FP = this.getFalsePositiveCount(label); - var FN = this.getFalseNegativeCount(label); - return (TP * TN - FP * FN) / Math.sqrt((TP + FP) * (TP + FN) * (TN + FP) * (TN + FN)); - } - /** - * Informedness - * {@link https://en.wikipedia.org/wiki/Youden%27s_J_statistic} - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getInformedness(label) { - return this.getTruePositiveRate(label) + this.getTrueNegativeRate(label) - 1; - } + getAccuracy() { + let correct = 0; + let incorrect = 0; - /** - * Markedness - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - getMarkedness(label) { - return this.getPositivePredictiveValue(label) + this.getNegativePredictiveValue(label) - 1; + for (var i = 0; i < this.matrix.length; i++) { + for (var j = 0; j < this.matrix.length; j++) { + if (i === j) correct += this.matrix[i][j];else incorrect += this.matrix[i][j]; + } } - /** - * Get the confusion table. - * @param {any} label - The label that should be considered "positive" - * @return {Array >} - The 2x2 confusion table. [[TP, FN], [FP, TN]] - */ - getConfusionTable(label) { - return [[this.getTruePositiveCount(label), this.getFalseNegativeCount(label)], [this.getFalsePositiveCount(label), this.getTrueNegativeCount(label)]]; - } + return correct / (correct + incorrect); + } + /** + * Returns the element in the confusion matrix that corresponds to the given actual and predicted labels. + * @param {any} actual - The true label + * @param {any} predicted - The predicted label + * @return {number} - The element in the confusion matrix + */ - /** - * Get total accuracy. - * @return {number} - The ratio between the number of true predictions and total number of classifications ([0-1]) - */ - getAccuracy() { - var correct = 0; - var incorrect = 0; - for (var i = 0; i < this.matrix.length; i++) { - for (var j = 0; j < this.matrix.length; j++) { - if (i === j) correct += this.matrix[i][j];else incorrect += this.matrix[i][j]; - } - } - return correct / (correct + incorrect); - } - /** - * Returns the element in the confusion matrix that corresponds to the given actual and predicted labels. - * @param {any} actual - The true label - * @param {any} predicted - The predicted label - * @return {number} - The element in the confusion matrix - */ - getCount(actual, predicted) { - var actualIndex = this.getIndex(actual); - var predictedIndex = this.getIndex(predicted); - return this.matrix[actualIndex][predictedIndex]; - } + getCount(actual, predicted) { + const actualIndex = this.getIndex(actual); + const predictedIndex = this.getIndex(predicted); + return this.matrix[actualIndex][predictedIndex]; + } + /** + * Compute the general prediction accuracy + * @deprecated Use getAccuracy + * @return {number} - The prediction accuracy ([0-1] + */ - /** - * Compute the general prediction accuracy - * @deprecated Use getAccuracy - * @return {number} - The prediction accuracy ([0-1] - */ - get accuracy() { - return this.getAccuracy(); - } - /** - * Compute the number of predicted observations - * @deprecated Use getTotalCount - * @return {number} - */ - get total() { - return this.getTotalCount(); - } + get accuracy() { + return this.getAccuracy(); + } + /** + * Compute the number of predicted observations + * @deprecated Use getTotalCount + * @return {number} + */ + + + get total() { + return this.getTotalCount(); + } + } module.exports = ConfusionMatrix; /***/ }), -/* 36 */ +/* 26 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -6899,172 +9527,180 @@ module.exports = ConfusionMatrix; var Matrix = __webpack_require__(0).Matrix; -var Utils = __webpack_require__(37); -var ACTIVATION_FUNCTIONS = __webpack_require__(38); +var Utils = __webpack_require__(27); -class Layer { - /** - * @private - * Create a new layer with the given options - * @param {object} options - * @param {number} [options.inputSize] - Number of conections that enter the neurons. - * @param {number} [options.outputSize] - Number of conections that leave the neurons. - * @param {number} [options.regularization] - Regularization parameter. - * @param {number} [options.epsilon] - Learning rate parameter. - * @param {string} [options.activation] - Activation function parameter from the FeedForwardNeuralNetwork class. - * @param {number} [options.activationParam] - Activation parameter if needed. - */ - constructor(options) { - this.inputSize = options.inputSize; - this.outputSize = options.outputSize; - this.regularization = options.regularization; - this.epsilon = options.epsilon; - this.activation = options.activation; - this.activationParam = options.activationParam; - - var selectedFunction = ACTIVATION_FUNCTIONS[options.activation]; - var params = selectedFunction.activation.length; - - var actFunction = params > 1 ? val => selectedFunction.activation(val, options.activationParam) : selectedFunction.activation; - var derFunction = params > 1 ? val => selectedFunction.derivate(val, options.activationParam) : selectedFunction.derivate; - - this.activationFunction = function (i, j) { - this[i][j] = actFunction(this[i][j]); - }; - this.derivate = function (i, j) { - this[i][j] = derFunction(this[i][j]); - }; +const ACTIVATION_FUNCTIONS = __webpack_require__(28); - if (options.model) { - // load model - this.W = Matrix.checkMatrix(options.W); - this.b = Matrix.checkMatrix(options.b); - } else { - // default constructor +class Layer { + /** + * @private + * Create a new layer with the given options + * @param {object} options + * @param {number} [options.inputSize] - Number of conections that enter the neurons. + * @param {number} [options.outputSize] - Number of conections that leave the neurons. + * @param {number} [options.regularization] - Regularization parameter. + * @param {number} [options.epsilon] - Learning rate parameter. + * @param {string} [options.activation] - Activation function parameter from the FeedForwardNeuralNetwork class. + * @param {number} [options.activationParam] - Activation parameter if needed. + */ + constructor(options) { + this.inputSize = options.inputSize; + this.outputSize = options.outputSize; + this.regularization = options.regularization; + this.epsilon = options.epsilon; + this.activation = options.activation; + this.activationParam = options.activationParam; + var selectedFunction = ACTIVATION_FUNCTIONS[options.activation]; + var params = selectedFunction.activation.length; + var actFunction = params > 1 ? val => selectedFunction.activation(val, options.activationParam) : selectedFunction.activation; + var derFunction = params > 1 ? val => selectedFunction.derivate(val, options.activationParam) : selectedFunction.derivate; + + this.activationFunction = function (i, j) { + this[i][j] = actFunction(this[i][j]); + }; - this.W = Matrix.rand(this.inputSize, this.outputSize); - this.b = Matrix.zeros(1, this.outputSize); + this.derivate = function (i, j) { + this[i][j] = derFunction(this[i][j]); + }; - this.W.apply(function (i, j) { - this[i][j] /= Math.sqrt(options.inputSize); - }); - } + if (options.model) { + // load model + this.W = Matrix.checkMatrix(options.W); + this.b = Matrix.checkMatrix(options.b); + } else { + // default constructor + this.W = Matrix.rand(this.inputSize, this.outputSize); + this.b = Matrix.zeros(1, this.outputSize); + this.W.apply(function (i, j) { + this[i][j] /= Math.sqrt(options.inputSize); + }); } + } + /** + * @private + * propagate the given input through the current layer. + * @param {Matrix} X - input. + * @return {Matrix} output at the current layer. + */ - /** - * @private - * propagate the given input through the current layer. - * @param {Matrix} X - input. - * @return {Matrix} output at the current layer. - */ - forward(X) { - var z = X.mmul(this.W).addRowVector(this.b); - z.apply(this.activationFunction); - this.a = z.clone(); - return z; - } - /** - * @private - * apply backpropagation algorithm at the current layer - * @param {Matrix} delta - delta values estimated at the following layer. - * @param {Matrix} a - 'a' values from the following layer. - * @return {Matrix} the new delta values for the next layer. - */ - backpropagation(delta, a) { - this.dW = a.transposeView().mmul(delta); - this.db = Utils.sumCol(delta); + forward(X) { + var z = X.mmul(this.W).addRowVector(this.b); + z.apply(this.activationFunction); + this.a = z.clone(); + return z; + } + /** + * @private + * apply backpropagation algorithm at the current layer + * @param {Matrix} delta - delta values estimated at the following layer. + * @param {Matrix} a - 'a' values from the following layer. + * @return {Matrix} the new delta values for the next layer. + */ - var aCopy = a.clone(); - return delta.mmul(this.W.transposeView()).mul(aCopy.apply(this.derivate)); - } - /** - * @private - * Function that updates the weights at the current layer with the derivatives. - */ - update() { - this.dW.add(this.W.clone().mul(this.regularization)); - this.W.add(this.dW.mul(-this.epsilon)); - this.b.add(this.db.mul(-this.epsilon)); - } + backpropagation(delta, a) { + this.dW = a.transposeView().mmul(delta); + this.db = Utils.sumCol(delta); + var aCopy = a.clone(); + return delta.mmul(this.W.transposeView()).mul(aCopy.apply(this.derivate)); + } + /** + * @private + * Function that updates the weights at the current layer with the derivatives. + */ - /** - * @private - * Export the current layer to JSON. - * @return {object} model - */ - toJSON() { - return { - model: 'Layer', - inputSize: this.inputSize, - outputSize: this.outputSize, - regularization: this.regularization, - epsilon: this.epsilon, - activation: this.activation, - W: this.W, - b: this.b - }; - } - /** - * @private - * Creates a new Layer with the given model. - * @param {object} model - * @return {Layer} - */ - static load(model) { - if (model.model !== 'Layer') { - throw new RangeError('the current model is not a Layer model'); - } - return new Layer(model); + update() { + this.dW.add(this.W.clone().mul(this.regularization)); + this.W.add(this.dW.mul(-this.epsilon)); + this.b.add(this.db.mul(-this.epsilon)); + } + /** + * @private + * Export the current layer to JSON. + * @return {object} model + */ + + + toJSON() { + return { + model: 'Layer', + inputSize: this.inputSize, + outputSize: this.outputSize, + regularization: this.regularization, + epsilon: this.epsilon, + activation: this.activation, + W: this.W, + b: this.b + }; + } + /** + * @private + * Creates a new Layer with the given model. + * @param {object} model + * @return {Layer} + */ + + + static load(model) { + if (model.model !== 'Layer') { + throw new RangeError('the current model is not a Layer model'); } + return new Layer(model); + } + } module.exports = Layer; /***/ }), -/* 37 */ +/* 27 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Matrix = __webpack_require__(0).Matrix; - /** * @private * Retrieves the sum at each row of the given matrix. * @param {Matrix} matrix * @return {Matrix} */ + + function sumRow(matrix) { - var sum = Matrix.zeros(matrix.rows, 1); - for (var i = 0; i < matrix.rows; ++i) { - for (var j = 0; j < matrix.columns; ++j) { - sum[i][0] += matrix[i][j]; - } + var sum = Matrix.zeros(matrix.rows, 1); + + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum[i][0] += matrix[i][j]; } - return sum; -} + } + return sum; +} /** * @private * Retrieves the sum at each column of the given matrix. * @param {Matrix} matrix * @return {Matrix} */ + + function sumCol(matrix) { - var sum = Matrix.zeros(1, matrix.columns); - for (var i = 0; i < matrix.rows; ++i) { - for (var j = 0; j < matrix.columns; ++j) { - sum[0][j] += matrix[i][j]; - } + var sum = Matrix.zeros(1, matrix.columns); + + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum[0][j] += matrix[i][j]; } - return sum; -} + } + return sum; +} /** * @private * Method that given an array of labels(predictions), returns two dictionaries, one to transform from labels to @@ -7072,10629 +9708,8989 @@ function sumCol(matrix) { * @param {Array} array * @return {object} */ + + function dictOutputs(array) { - var inputs = {}; - var outputs = {}; - var index = 0; - for (var i = 0; i < array.length; i += 1) { - if (inputs[array[i]] === undefined) { - inputs[array[i]] = index; - outputs[index] = array[i]; - index++; - } + var inputs = {}; + var outputs = {}; + var index = 0; + + for (var i = 0; i < array.length; i += 1) { + if (inputs[array[i]] === undefined) { + inputs[array[i]] = index; + outputs[index] = array[i]; + index++; } + } - return { - inputs: inputs, - outputs: outputs - }; + return { + inputs: inputs, + outputs: outputs + }; } module.exports = { - dictOutputs: dictOutputs, - sumCol: sumCol, - sumRow: sumRow + dictOutputs: dictOutputs, + sumCol: sumCol, + sumRow: sumRow }; /***/ }), -/* 38 */ +/* 28 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function logistic(val) { - return 1 / (1 + Math.exp(-val)); + return 1 / (1 + Math.exp(-val)); } function expELU(val, param) { - return val < 0 ? param * (Math.exp(val) - 1) : val; + return val < 0 ? param * (Math.exp(val) - 1) : val; } function softExponential(val, param) { - if (param < 0) { - return -Math.log(1 - param * (val + param)) / param; - } - if (param > 0) { - return (Math.exp(param * val) - 1) / param + param; - } - return val; + if (param < 0) { + return -Math.log(1 - param * (val + param)) / param; + } + + if (param > 0) { + return (Math.exp(param * val) - 1) / param + param; + } + + return val; } function softExponentialPrime(val, param) { - if (param < 0) { - return 1 / (1 - param * (param + val)); - } else { - return Math.exp(param * val); - } + if (param < 0) { + return 1 / (1 - param * (param + val)); + } else { + return Math.exp(param * val); + } } -var ACTIVATION_FUNCTIONS = { - tanh: { - activation: Math.tanh, - derivate: val => 1 - val * val - }, - identity: { - activation: val => val, - derivate: () => 1 - }, - logistic: { - activation: logistic, - derivate: val => logistic(val) * (1 - logistic(val)) - }, - arctan: { - activation: Math.atan, - derivate: val => 1 / (val * val + 1) - }, - softsign: { - activation: val => val / (1 + Math.abs(val)), - derivate: val => 1 / ((1 + Math.abs(val)) * (1 + Math.abs(val))) - }, - relu: { - activation: val => val < 0 ? 0 : val, - derivate: val => val < 0 ? 0 : 1 - }, - softplus: { - activation: val => Math.log(1 + Math.exp(val)), - derivate: val => 1 / (1 + Math.exp(-val)) - }, - bent: { - activation: val => (Math.sqrt(val * val + 1) - 1) / 2 + val, - derivate: val => val / (2 * Math.sqrt(val * val + 1)) + 1 - }, - sinusoid: { - activation: Math.sin, - derivate: Math.cos - }, - sinc: { - activation: val => val === 0 ? 1 : Math.sin(val) / val, - derivate: val => val === 0 ? 0 : Math.cos(val) / val - Math.sin(val) / (val * val) - }, - gaussian: { - activation: val => Math.exp(-(val * val)), - derivate: val => -2 * val * Math.exp(-(val * val)) - }, - 'parametric-relu': { - activation: (val, param) => val < 0 ? param * val : val, - derivate: (val, param) => val < 0 ? param : 1 - }, - 'exponential-elu': { - activation: expELU, - derivate: (val, param) => val < 0 ? expELU(val, param) + param : 1 - }, - 'soft-exponential': { - activation: softExponential, - derivate: softExponentialPrime - } +const ACTIVATION_FUNCTIONS = { + tanh: { + activation: Math.tanh, + derivate: val => 1 - val * val + }, + identity: { + activation: val => val, + derivate: () => 1 + }, + logistic: { + activation: logistic, + derivate: val => logistic(val) * (1 - logistic(val)) + }, + arctan: { + activation: Math.atan, + derivate: val => 1 / (val * val + 1) + }, + softsign: { + activation: val => val / (1 + Math.abs(val)), + derivate: val => 1 / ((1 + Math.abs(val)) * (1 + Math.abs(val))) + }, + relu: { + activation: val => val < 0 ? 0 : val, + derivate: val => val < 0 ? 0 : 1 + }, + softplus: { + activation: val => Math.log(1 + Math.exp(val)), + derivate: val => 1 / (1 + Math.exp(-val)) + }, + bent: { + activation: val => (Math.sqrt(val * val + 1) - 1) / 2 + val, + derivate: val => val / (2 * Math.sqrt(val * val + 1)) + 1 + }, + sinusoid: { + activation: Math.sin, + derivate: Math.cos + }, + sinc: { + activation: val => val === 0 ? 1 : Math.sin(val) / val, + derivate: val => val === 0 ? 0 : Math.cos(val) / val - Math.sin(val) / (val * val) + }, + gaussian: { + activation: val => Math.exp(-(val * val)), + derivate: val => -2 * val * Math.exp(-(val * val)) + }, + 'parametric-relu': { + activation: (val, param) => val < 0 ? param * val : val, + derivate: (val, param) => val < 0 ? param : 1 + }, + 'exponential-elu': { + activation: expELU, + derivate: (val, param) => val < 0 ? expELU(val, param) + param : 1 + }, + 'soft-exponential': { + activation: softExponential, + derivate: softExponentialPrime + } }; - module.exports = ACTIVATION_FUNCTIONS; /***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - +/* 29 */ +/***/ (function(module, exports) { function NodeSquare(x, y, weights, som) { - this.x = x; - this.y = y; - this.weights = weights; - this.som = som; - this.neighbors = {}; + this.x = x; + this.y = y; + this.weights = weights; + this.som = som; + this.neighbors = {}; } NodeSquare.prototype.adjustWeights = function adjustWeights(target, learningRate, influence) { - for (var i = 0, ii = this.weights.length; i < ii; i++) { - this.weights[i] += learningRate * influence * (target[i] - this.weights[i]); - } + for (var i = 0, ii = this.weights.length; i < ii; i++) { + this.weights[i] += learningRate * influence * (target[i] - this.weights[i]); + } }; NodeSquare.prototype.getDistance = function getDistance(otherNode) { - return Math.max(Math.abs(this.x - otherNode.x), Math.abs(this.y - otherNode.y)); + return Math.max(Math.abs(this.x - otherNode.x), Math.abs(this.y - otherNode.y)); }; NodeSquare.prototype.getDistanceTorus = function getDistanceTorus(otherNode) { - var distX = Math.abs(this.x - otherNode.x), - distY = Math.abs(this.y - otherNode.y); - return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY)); + var distX = Math.abs(this.x - otherNode.x), + distY = Math.abs(this.y - otherNode.y); + return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY)); }; NodeSquare.prototype.getNeighbors = function getNeighbors(xy) { - if (!this.neighbors[xy]) { - this.neighbors[xy] = new Array(2); - - // left or bottom neighbor - var v; - if (this[xy] > 0) { - v = this[xy] - 1; - } else if (this.som.torus) { - v = this.som.gridDim[xy] - 1; + if (!this.neighbors[xy]) { + this.neighbors[xy] = new Array(2); // left or bottom neighbor + + var v; + + if (this[xy] > 0) { + v = this[xy] - 1; + } else if (this.som.torus) { + v = this.som.gridDim[xy] - 1; + } + + if (typeof v !== 'undefined') { + var x, y; + + if (xy === 'x') { + x = v; + y = this.y; + } else { + x = this.x; + y = v; + } + + this.neighbors[xy][0] = this.som.nodes[x][y]; + } // top or right neighbor + + + var w; + + if (this[xy] < this.som.gridDim[xy] - 1) { + w = this[xy] + 1; + } else if (this.som.torus) { + w = 0; + } + + if (typeof w !== 'undefined') { + if (xy === 'x') { + x = w; + y = this.y; + } else { + x = this.x; + y = w; + } + + this.neighbors[xy][1] = this.som.nodes[x][y]; + } + } + + return this.neighbors[xy]; +}; + +NodeSquare.prototype.getPos = function getPos(xy, element) { + var neighbors = this.getNeighbors(xy), + distance = this.som.distance, + bestNeighbor, + direction; + + if (neighbors[0]) { + if (neighbors[1]) { + var dist1 = distance(element, neighbors[0].weights), + dist2 = distance(element, neighbors[1].weights); + + if (dist1 < dist2) { + bestNeighbor = neighbors[0]; + direction = -1; + } else { + bestNeighbor = neighbors[1]; + direction = 1; + } + } else { + bestNeighbor = neighbors[0]; + direction = -1; + } + } else { + bestNeighbor = neighbors[1]; + direction = 1; + } + + var simA = 1 - distance(element, this.weights), + simB = 1 - distance(element, bestNeighbor.weights); + var factor = (simA - simB) / (2 - simA - simB); + return 0.5 + 0.5 * factor * direction; +}; + +NodeSquare.prototype.getPosition = function getPosition(element) { + return [this.getPos('x', element), this.getPos('y', element)]; +}; + +module.exports = NodeSquare; + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.distance = __webpack_require__(75); +exports.similarity = __webpack_require__(112); + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = function czekanowskiSimilarity(a, b) { + var up = 0; + var down = 0; + + for (var i = 0; i < a.length; i++) { + up += Math.min(a[i], b[i]); + down += a[i] + b[i]; + } + + return 2 * up / down; +}; + +/***/ }), +/* 32 */ +/***/ (function(module, exports) { + +module.exports = function dice(a, b) { + var ii = a.length, + p = 0, + q1 = 0, + q2 = 0; + + for (var i = 0; i < ii; i++) { + p += a[i] * a[i]; + q1 += b[i] * b[i]; + q2 += (a[i] - b[i]) * (a[i] - b[i]); + } + + return q2 / (p + q1); +}; + +/***/ }), +/* 33 */ +/***/ (function(module, exports) { + +module.exports = function intersection(a, b) { + var ii = a.length, + ans = 0; + + for (var i = 0; i < ii; i++) { + ans += Math.min(a[i], b[i]); + } + + return 1 - ans; +}; + +/***/ }), +/* 34 */ +/***/ (function(module, exports) { + +module.exports = function jaccard(a, b) { + var ii = a.length, + p1 = 0, + p2 = 0, + q1 = 0, + q2 = 0; + + for (var i = 0; i < ii; i++) { + p1 += a[i] * b[i]; + p2 += a[i] * a[i]; + q1 += b[i] * b[i]; + q2 += (a[i] - b[i]) * (a[i] - b[i]); + } + + return q2 / (p2 + q1 - p1); +}; + +/***/ }), +/* 35 */ +/***/ (function(module, exports) { + +module.exports = function kulczynski(a, b) { + var ii = a.length, + up = 0, + down = 0; + + for (var i = 0; i < ii; i++) { + up += Math.abs(a[i] - b[i]); + down += Math.min(a[i], b[i]); + } + + return up / down; +}; + +/***/ }), +/* 36 */ +/***/ (function(module, exports) { + +module.exports = function motyka(a, b) { + var ii = a.length, + up = 0, + down = 0; + + for (var i = 0; i < ii; i++) { + up += Math.min(a[i], b[i]); + down += a[i] + b[i]; + } + + return 1 - up / down; +}; + +/***/ }), +/* 37 */ +/***/ (function(module, exports) { + +module.exports = function squaredChord(a, b) { + var ii = a.length, + ans = 0; + + for (var i = 0; i < ii; i++) { + ans += (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i])); + } + + return ans; +}; + +/***/ }), +/* 38 */ +/***/ (function(module, exports) { + +module.exports = function tanimoto(a, b, bitvector) { + if (bitvector) { + var inter = 0, + union = 0; + + for (var j = 0; j < a.length; j++) { + inter += a[j] && b[j]; + union += a[j] || b[j]; + } + + if (union === 0) return 1; + return inter / union; + } else { + var ii = a.length, + p = 0, + q = 0, + m = 0; + + for (var i = 0; i < ii; i++) { + p += a[i]; + q += b[i]; + m += Math.min(a[i], b[i]); + } + + return 1 - (p + q - 2 * m) / (p + q - m); + } +}; + +/***/ }), +/* 39 */ +/***/ (function(module, exports) { + +module.exports = function cosine(a, b) { + var ii = a.length, + p = 0, + p2 = 0, + q2 = 0; + + for (var i = 0; i < ii; i++) { + p += a[i] * b[i]; + p2 += a[i] * a[i]; + q2 += b[i] * b[i]; + } + + return p / (Math.sqrt(p2) * Math.sqrt(q2)); +}; + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var extend = __webpack_require__(16); + +var defaultOptions = { + size: 1, + value: 0 +}; +/** + * Case when the entry is an array + * @param data + * @param options + * @returns {Array} + */ + +function arrayCase(data, options) { + var len = data.length; + if (typeof options.size === 'number') options.size = [options.size, options.size]; + var cond = len + options.size[0] + options.size[1]; + var output; + + if (options.output) { + if (options.output.length !== cond) throw new RangeError('Wrong output size'); + output = options.output; + } else output = new Array(cond); + + var i; // circular option + + if (options.value === 'circular') { + for (i = 0; i < cond; i++) { + if (i < options.size[0]) output[i] = data[(len - options.size[0] % len + i) % len];else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];else output[i] = data[(i - options.size[0]) % len]; + } + } // replicate option + else if (options.value === 'replicate') { + for (i = 0; i < cond; i++) { + if (i < options.size[0]) output[i] = data[0];else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];else output[i] = data[len - 1]; + } + } // symmetric option + else if (options.value === 'symmetric') { + if (options.size[0] > len || options.size[1] > len) throw new RangeError('expanded value should not be bigger than the data length'); + + for (i = 0; i < cond; i++) { + if (i < options.size[0]) output[i] = data[options.size[0] - 1 - i];else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];else output[i] = data[2 * len + options.size[0] - i - 1]; } - if (typeof v !== 'undefined') { - var x, y; - if (xy === 'x') { - x = v; - y = this.y; - } else { - x = this.x; - y = v; - } - this.neighbors[xy][0] = this.som.nodes[x][y]; + } // default option + else { + for (i = 0; i < cond; i++) { + if (i < options.size[0]) output[i] = options.value;else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];else output[i] = options.value; + } } - // top or right neighbor - var w; - if (this[xy] < this.som.gridDim[xy] - 1) { - w = this[xy] + 1; - } else if (this.som.torus) { - w = 0; - } - if (typeof w !== 'undefined') { - if (xy === 'x') { - x = w; - y = this.y; - } else { - x = this.x; - y = w; - } - this.neighbors[xy][1] = this.som.nodes[x][y]; - } - } - return this.neighbors[xy]; -}; + return output; +} +/** + * Case when the entry is a matrix + * @param data + * @param options + * @returns {Array} + */ + + +function matrixCase(data, options) { + var row = data.length; + var col = data[0].length; + if (options.size[0] === undefined) options.size = [options.size, options.size, options.size, options.size]; + throw new Error('matrix not supported yet, sorry'); +} +/** + * Pads and array + * @param {Array } data + * @param {object} options + */ + -NodeSquare.prototype.getPos = function getPos(xy, element) { - var neighbors = this.getNeighbors(xy), - distance = this.som.distance, - bestNeighbor, - direction; - if (neighbors[0]) { - if (neighbors[1]) { - var dist1 = distance(element, neighbors[0].weights), - dist2 = distance(element, neighbors[1].weights); - if (dist1 < dist2) { - bestNeighbor = neighbors[0]; - direction = -1; - } else { - bestNeighbor = neighbors[1]; - direction = 1; - } - } else { - bestNeighbor = neighbors[0]; - direction = -1; - } - } else { - bestNeighbor = neighbors[1]; - direction = 1; - } - var simA = 1 - distance(element, this.weights), - simB = 1 - distance(element, bestNeighbor.weights); - var factor = (simA - simB) / (2 - simA - simB); - return 0.5 + 0.5 * factor * direction; -}; +function padArray(data, options) { + options = extend({}, defaultOptions, options); -NodeSquare.prototype.getPosition = function getPosition(element) { - return [this.getPos('x', element), this.getPos('y', element)]; -}; + if (Array.isArray(data)) { + if (Array.isArray(data[0])) return matrixCase(data, options);else return arrayCase(data, options); + } else throw new TypeError('data should be an array'); +} -module.exports = NodeSquare; +module.exports = padArray; /***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { +/* 41 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +__webpack_require__.r(__webpack_exports__); +// CONCATENATED MODULE: ./node_modules/ml-regression-base/src/maybeToPrecision.js +function maybeToPrecision(value, digits) { + if (value < 0) { + value = 0 - value; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RobustPolynomialRegression = exports.TheilSenRegression = exports.PolinomialFitting2D = exports.KRR = exports.KernelRidgeRegression = exports.NonLinearRegression = exports.NLR = exports.MultivariateLinearRegression = exports.PowerRegression = exports.ExponentialRegression = exports.PolynomialRegression = exports.SLR = exports.SimpleLinearRegression = undefined; - -var _mlRegressionSimpleLinear = __webpack_require__(16); - -Object.defineProperty(exports, 'SimpleLinearRegression', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_mlRegressionSimpleLinear).default; + if (typeof digits === 'number') { + return '- ' + value.toPrecision(digits); + } else { + return '- ' + value.toString(); } -}); -Object.defineProperty(exports, 'SLR', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_mlRegressionSimpleLinear).default; + } else { + if (typeof digits === 'number') { + return value.toPrecision(digits); + } else { + return value.toString(); } -}); - -var _mlRegressionPolynomial = __webpack_require__(41); + } +} +// CONCATENATED MODULE: ./node_modules/ml-regression-base/src/checkArrayLength.js +function checkArraySize(x, y) { + if (!Array.isArray(x) || !Array.isArray(y)) { + throw new TypeError('x and y must be arrays'); + } -Object.defineProperty(exports, 'PolynomialRegression', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_mlRegressionPolynomial).default; - } -}); + if (x.length !== y.length) { + throw new RangeError('x and y arrays must have the same length'); + } +} +// CONCATENATED MODULE: ./node_modules/ml-regression-base/src/index.js -var _mlRegressionExponential = __webpack_require__(124); -Object.defineProperty(exports, 'ExponentialRegression', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_mlRegressionExponential).default; +class BaseRegression { + constructor() { + if (new.target === BaseRegression) { + throw new Error('BaseRegression must be subclassed'); } -}); - -var _mlRegressionPower = __webpack_require__(125); + } -Object.defineProperty(exports, 'PowerRegression', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_mlRegressionPower).default; - } -}); + predict(x) { + if (typeof x === 'number') { + return this._predict(x); + } else if (Array.isArray(x)) { + const y = new Array(x.length); -var _mlRegressionMultivariateLinear = __webpack_require__(126); + for (let i = 0; i < x.length; i++) { + y[i] = this._predict(x[i]); + } -Object.defineProperty(exports, 'MultivariateLinearRegression', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_mlRegressionMultivariateLinear).default; + return y; + } else { + throw new TypeError('x must be a number or array'); } -}); + } -var _kernelRidgeRegression = __webpack_require__(127); + _predict() { + throw new Error('_predict must be implemented'); + } -Object.defineProperty(exports, 'KernelRidgeRegression', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_kernelRidgeRegression).default; - } -}); -Object.defineProperty(exports, 'KRR', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_kernelRidgeRegression).default; - } -}); + train() {//Do nothing for this package + } -var _polyFitRegression2d = __webpack_require__(128); + toString() { + return ''; + } -Object.defineProperty(exports, 'PolinomialFitting2D', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_polyFitRegression2d).default; - } -}); + toLaTeX() { + return ''; + } + /** + * Return the correlation coefficient of determination (r) and chi-square. + * @param {Array} x + * @param {Array} y + * @return {object} + */ -var _mlRegressionTheilSen = __webpack_require__(129); -Object.defineProperty(exports, 'TheilSenRegression', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_mlRegressionTheilSen).default; + score(x, y) { + if (!Array.isArray(x) || !Array.isArray(y) || x.length !== y.length) { + throw new Error('x and y must be arrays of the same length'); } -}); -var _mlRegressionRobustPolynomial = __webpack_require__(130); + const n = x.length; + const y2 = new Array(n); -Object.defineProperty(exports, 'RobustPolynomialRegression', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_mlRegressionRobustPolynomial).default; + for (let i = 0; i < n; i++) { + y2[i] = this._predict(x[i]); } -}); -var _potentialRegression = __webpack_require__(131); + let xSum = 0; + let ySum = 0; + let chi2 = 0; + let rmsd = 0; + let xSquared = 0; + let ySquared = 0; + let xY = 0; -var _potentialRegression2 = _interopRequireDefault(_potentialRegression); + for (let i = 0; i < n; i++) { + xSum += y2[i]; + ySum += y[i]; + xSquared += y2[i] * y2[i]; + ySquared += y[i] * y[i]; + xY += y2[i] * y[i]; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (y[i] !== 0) { + chi2 += (y[i] - y2[i]) * (y[i] - y2[i]) / y[i]; + } -var NLR = { - PotentialRegression: _potentialRegression2.default -}; -exports.NLR = NLR; -exports.NonLinearRegression = NLR; + rmsd = (y[i] - y2[i]) * (y[i] - y2[i]); + } -/***/ }), -/* 41 */ -/***/ (function(module, exports, __webpack_require__) { + const r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum)); + return { + r: r, + r2: r * r, + chi2: chi2, + rmsd: rmsd * rmsd / n + }; + } -"use strict"; +} +// CONCATENATED MODULE: ./node_modules/ml-regression-simple-linear/src/index.js +class src_SimpleLinearRegression extends BaseRegression { + constructor(x, y) { + super(); -Object.defineProperty(exports, "__esModule", { - value: true -}); + if (x === true) { + this.slope = y.slope; + this.intercept = y.intercept; + this.coefficients = [y.intercept, y.slope]; + } else { + checkArraySize(x, y); + regress(this, x, y); + } + } -var _mlRegressionBase = __webpack_require__(2); + toJSON() { + return { + name: 'simpleLinearRegression', + slope: this.slope, + intercept: this.intercept + }; + } -var _mlRegressionBase2 = _interopRequireDefault(_mlRegressionBase); + _predict(x) { + return this.slope * x + this.intercept; + } -var _mlMatrix = __webpack_require__(0); + computeX(y) { + return (y - this.intercept) / this.slope; + } -var _mlMatrix2 = _interopRequireDefault(_mlMatrix); + toString(precision) { + let result = 'f(x) = '; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (this.slope !== 0) { + const xFactor = maybeToPrecision(this.slope, precision); + result += (xFactor === '1' ? '' : xFactor + ' * ') + 'x'; -class PolynomialRegression extends _mlRegressionBase2.default { - constructor(x, y, degree) { - super(); - if (x === true) { - this.degree = y.degree; - this.powers = y.powers; - this.coefficients = y.coefficients; - } else { - (0, _mlRegressionBase.checkArrayLength)(x, y); - regress(this, x, y, degree); - } + if (this.intercept) { + const absIntercept = Math.abs(this.intercept); + const operator = absIntercept === this.intercept ? '+' : '-'; + result += " ".concat(operator, " ").concat(maybeToPrecision(absIntercept, precision)); + } + } else { + result += maybeToPrecision(this.intercept, precision); } - _predict(x) { - var y = 0; - for (var k = 0; k < this.powers.length; k++) { - y += this.coefficients[k] * Math.pow(x, this.powers[k]); - } - return y; - } + return result; + } - toJSON() { - return { - name: 'polynomialRegression', - degree: this.degree, - powers: this.powers, - coefficients: this.coefficients - }; - } + toLaTeX(precision) { + return this.toString(precision); + } - toString(precision) { - return this._toFormula(precision, false); + static load(json) { + if (json.name !== 'simpleLinearRegression') { + throw new TypeError('not a SLR model'); } - toLaTeX(precision) { - return this._toFormula(precision, true); - } + return new src_SimpleLinearRegression(true, json); + } - _toFormula(precision, isLaTeX) { - var sup = '^'; - var closeSup = ''; - var times = ' * '; - if (isLaTeX) { - sup = '^{'; - closeSup = '}'; - times = ''; - } +} - var fn = ''; - var str = ''; - for (var k = 0; k < this.coefficients.length; k++) { - str = ''; - if (this.coefficients[k] !== 0) { - if (this.powers[k] === 0) { - str = (0, _mlRegressionBase.maybeToPrecision)(this.coefficients[k], precision); - } else { - if (this.powers[k] === 1) { - str = (0, _mlRegressionBase.maybeToPrecision)(this.coefficients[k], precision) + times + 'x'; - } else { - str = (0, _mlRegressionBase.maybeToPrecision)(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup; - } - } +function regress(slr, x, y) { + const n = x.length; + let xSum = 0; + let ySum = 0; + let xSquared = 0; + let xY = 0; + + for (let i = 0; i < n; i++) { + xSum += x[i]; + ySum += y[i]; + xSquared += x[i] * x[i]; + xY += x[i] * y[i]; + } - if (this.coefficients[k] > 0 && k !== this.coefficients.length - 1) { - str = ' + ' + str; - } else if (k !== this.coefficients.length - 1) { - str = ' ' + str; - } - } - fn = str + fn; - } - if (fn.charAt(0) === '+') { - fn = fn.slice(1); - } + const numerator = n * xY - xSum * ySum; + slr.slope = numerator / (n * xSquared - xSum * xSum); + slr.intercept = 1 / n * ySum - slr.slope * (1 / n) * xSum; + slr.coefficients = [slr.intercept, slr.slope]; +} +// EXTERNAL MODULE: ./node_modules/ml-matrix/src/index.js + 24 modules +var src = __webpack_require__(0); - return 'f(x) = ' + fn; - } +// CONCATENATED MODULE: ./node_modules/ml-regression-polynomial/src/index.js - static load(json) { - if (json.name !== 'polynomialRegression') { - throw new TypeError('not a polynomial regression model'); - } - return new PolynomialRegression(true, json); - } -} -exports.default = PolynomialRegression; -function regress(pr, x, y, degree) { - var n = x.length; - var powers = void 0; - if (Array.isArray(degree)) { - powers = degree; - degree = powers.length; +class src_PolynomialRegression extends BaseRegression { + constructor(x, y, degree) { + super(); + + if (x === true) { + this.degree = y.degree; + this.powers = y.powers; + this.coefficients = y.coefficients; } else { - degree++; - powers = new Array(degree); - for (var k = 0; k < degree; k++) { - powers[k] = k; - } + checkArraySize(x, y); + src_regress(this, x, y, degree); } - var F = new _mlMatrix2.default(n, degree); - var Y = new _mlMatrix2.default([y]); - for (var _k = 0; _k < degree; _k++) { - for (var i = 0; i < n; i++) { - if (powers[_k] === 0) { - F[i][_k] = 1; - } else { - F[i][_k] = Math.pow(x[i], powers[_k]); - } - } - } - - var FT = F.transposeView(); - var A = FT.mmul(F); - var B = FT.mmul(Y.transposeView()); - - pr.degree = degree - 1; - pr.powers = powers; - pr.coefficients = (0, _mlMatrix.solve)(A, B).to1DArray(); -} + } -/***/ }), -/* 42 */ -/***/ (function(module, exports, __webpack_require__) { + _predict(x) { + let y = 0; -"use strict"; + for (let k = 0; k < this.powers.length; k++) { + y += this.coefficients[k] * Math.pow(x, this.powers[k]); + } + return y; + } -var newArray = __webpack_require__(134); + toJSON() { + return { + name: 'polynomialRegression', + degree: this.degree, + powers: this.powers, + coefficients: this.coefficients + }; + } -var primeFinder = __webpack_require__(135); -var nextPrime = primeFinder.nextPrime; -var largestPrime = primeFinder.largestPrime; + toString(precision) { + return this._toFormula(precision, false); + } -var FREE = 0; -var FULL = 1; -var REMOVED = 2; + toLaTeX(precision) { + return this._toFormula(precision, true); + } -var defaultInitialCapacity = 150; -var defaultMinLoadFactor = 1 / 6; -var defaultMaxLoadFactor = 2 / 3; + _toFormula(precision, isLaTeX) { + let sup = '^'; + let closeSup = ''; + let times = ' * '; -class HashTable { - constructor(options = {}) { - if (options instanceof HashTable) { - this.table = options.table.slice(); - this.values = options.values.slice(); - this.state = options.state.slice(); - this.minLoadFactor = options.minLoadFactor; - this.maxLoadFactor = options.maxLoadFactor; - this.distinct = options.distinct; - this.freeEntries = options.freeEntries; - this.lowWaterMark = options.lowWaterMark; - this.highWaterMark = options.maxLoadFactor; - return; - } + if (isLaTeX) { + sup = '^{'; + closeSup = '}'; + times = ''; + } - var initialCapacity = options.initialCapacity === undefined ? defaultInitialCapacity : options.initialCapacity; - if (initialCapacity < 0) { - throw new RangeError(`initial capacity must not be less than zero: ${initialCapacity}`); - } + let fn = ''; + let str = ''; - var minLoadFactor = options.minLoadFactor === undefined ? defaultMinLoadFactor : options.minLoadFactor; - var maxLoadFactor = options.maxLoadFactor === undefined ? defaultMaxLoadFactor : options.maxLoadFactor; - if (minLoadFactor < 0 || minLoadFactor >= 1) { - throw new RangeError(`invalid minLoadFactor: ${minLoadFactor}`); - } - if (maxLoadFactor <= 0 || maxLoadFactor >= 1) { - throw new RangeError(`invalid maxLoadFactor: ${maxLoadFactor}`); - } - if (minLoadFactor >= maxLoadFactor) { - throw new RangeError(`minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`); - } + for (let k = 0; k < this.coefficients.length; k++) { + str = ''; - var capacity = initialCapacity; - // User wants to put at least capacity elements. We need to choose the size based on the maxLoadFactor to - // avoid the need to rehash before this capacity is reached. - // actualCapacity * maxLoadFactor >= capacity - capacity = capacity / maxLoadFactor | 0; - capacity = nextPrime(capacity); - if (capacity === 0) capacity = 1; - - this.table = newArray(capacity, 0); - this.values = newArray(capacity, 0); - this.state = newArray(capacity, 0); - - this.minLoadFactor = minLoadFactor; - if (capacity === largestPrime) { - this.maxLoadFactor = 1; + if (this.coefficients[k] !== 0) { + if (this.powers[k] === 0) { + str = maybeToPrecision(this.coefficients[k], precision); } else { - this.maxLoadFactor = maxLoadFactor; + if (this.powers[k] === 1) { + str = maybeToPrecision(this.coefficients[k], precision) + times + 'x'; + } else { + str = maybeToPrecision(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup; + } } - this.distinct = 0; - this.freeEntries = capacity; + if (this.coefficients[k] > 0 && k !== this.coefficients.length - 1) { + str = ' + ' + str; + } else if (k !== this.coefficients.length - 1) { + str = ' ' + str; + } + } - this.lowWaterMark = 0; - this.highWaterMark = chooseHighWaterMark(capacity, this.maxLoadFactor); + fn = str + fn; } - clone() { - return new HashTable(this); + if (fn.charAt(0) === '+') { + fn = fn.slice(1); } - get size() { - return this.distinct; - } + return 'f(x) = ' + fn; + } - get(key) { - var i = this.indexOfKey(key); - if (i < 0) return 0; - return this.values[i]; + static load(json) { + if (json.name !== 'polynomialRegression') { + throw new TypeError('not a polynomial regression model'); } - set(key, value) { - var i = this.indexOfInsertion(key); - if (i < 0) { - i = -i - 1; - this.values[i] = value; - return false; - } + return new src_PolynomialRegression(true, json); + } - if (this.distinct > this.highWaterMark) { - var newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor); - this.rehash(newCapacity); - return this.set(key, value); - } +} - this.table[i] = key; - this.values[i] = value; - if (this.state[i] === FREE) this.freeEntries--; - this.state[i] = FULL; - this.distinct++; +function src_regress(pr, x, y, degree) { + const n = x.length; + let powers; - if (this.freeEntries < 1) { - var _newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor); - this.rehash(_newCapacity); - } + if (Array.isArray(degree)) { + powers = degree; + degree = powers.length; + } else { + degree++; + powers = new Array(degree); - return true; + for (let k = 0; k < degree; k++) { + powers[k] = k; } + } - remove(key, noRehash) { - var i = this.indexOfKey(key); - if (i < 0) return false; - - this.state[i] = REMOVED; - this.distinct--; - - if (!noRehash) this.maybeShrinkCapacity(); + const F = new src["default"](n, degree); + const Y = new src["default"]([y]); - return true; + for (let k = 0; k < degree; k++) { + for (let i = 0; i < n; i++) { + if (powers[k] === 0) { + F[i][k] = 1; + } else { + F[i][k] = Math.pow(x[i], powers[k]); + } } + } - delete(key, noRehash) { - var i = this.indexOfKey(key); - if (i < 0) return false; - - this.state[i] = FREE; - this.distinct--; - - if (!noRehash) this.maybeShrinkCapacity(); + const FT = F.transposeView(); + const A = FT.mmul(F); + const B = FT.mmul(Y.transposeView()); + pr.degree = degree - 1; + pr.powers = powers; + pr.coefficients = Object(src["solve"])(A, B).to1DArray(); +} +// CONCATENATED MODULE: ./node_modules/ml-regression-exponential/src/index.js - return true; - } - maybeShrinkCapacity() { - if (this.distinct < this.lowWaterMark) { - var newCapacity = chooseShrinkCapacity(this.distinct, this.minLoadFactor, this.maxLoadFactor); - this.rehash(newCapacity); - } - } +class src_ExponentialRegression extends BaseRegression { + constructor(x, y) { + super(); - containsKey(key) { - return this.indexOfKey(key) >= 0; + if (x === true) { + this.A = y.A; + this.B = y.B; + } else { + checkArraySize(x, y); + ml_regression_exponential_src_regress(this, x, y); } + } - indexOfKey(key) { - var table = this.table; - var state = this.state; - var length = this.table.length; + _predict(input) { + return this.B * Math.exp(input * this.A); + } - var hash = key & 0x7fffffff; - var i = hash % length; - var decrement = hash % (length - 2); - if (decrement === 0) decrement = 1; + toJSON() { + return { + name: 'exponentialRegression', + A: this.A, + B: this.B + }; + } - while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) { - i -= decrement; - if (i < 0) i += length; - } + toString(precision) { + return 'f(x) = ' + maybeToPrecision(this.B, precision) + ' * e^(' + maybeToPrecision(this.A, precision) + ' * x)'; + } - if (state[i] === FREE) return -1; - return i; + toLaTeX(precision) { + if (this.A >= 0) { + return 'f(x) = ' + maybeToPrecision(this.B, precision) + 'e^{' + maybeToPrecision(this.A, precision) + 'x}'; + } else { + return 'f(x) = \\frac{' + maybeToPrecision(this.B, precision) + '}{e^{' + maybeToPrecision(-this.A, precision) + 'x}}'; } + } - containsValue(value) { - return this.indexOfValue(value) >= 0; + static load(json) { + if (json.name !== 'exponentialRegression') { + throw new TypeError('not a exponential regression model'); } - indexOfValue(value) { - var values = this.values; - var state = this.state; - - for (var i = 0; i < state.length; i++) { - if (state[i] === FULL && values[i] === value) { - return i; - } - } - - return -1; - } + return new src_ExponentialRegression(true, json); + } - indexOfInsertion(key) { - var table = this.table; - var state = this.state; - var length = table.length; +} - var hash = key & 0x7fffffff; - var i = hash % length; - var decrement = hash % (length - 2); - if (decrement === 0) decrement = 1; +function ml_regression_exponential_src_regress(er, x, y) { + const n = x.length; + const yl = new Array(n); - while (state[i] === FULL && table[i] !== key) { - i -= decrement; - if (i < 0) i += length; - } + for (let i = 0; i < n; i++) { + yl[i] = Math.log(y[i]); + } - if (state[i] === REMOVED) { - var j = i; - while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) { - i -= decrement; - if (i < 0) i += length; - } - if (state[i] === FREE) i = j; - } + const linear = new src_SimpleLinearRegression(x, yl); + er.A = linear.slope; + er.B = Math.exp(linear.intercept); +} +// CONCATENATED MODULE: ./node_modules/ml-regression-power/src/index.js - if (state[i] === FULL) { - return -i - 1; - } - return i; - } +class src_PowerRegression extends BaseRegression { + constructor(x, y) { + super(); - ensureCapacity(minCapacity) { - if (this.table.length < minCapacity) { - var newCapacity = nextPrime(minCapacity); - this.rehash(newCapacity); - } + if (x === true) { + // reloading model + this.A = y.A; + this.B = y.B; + } else { + checkArraySize(x, y); + ml_regression_power_src_regress(this, x, y); } + } - rehash(newCapacity) { - var oldCapacity = this.table.length; - - if (newCapacity <= this.distinct) throw new Error('Unexpected'); - - var oldTable = this.table; - var oldValues = this.values; - var oldState = this.state; - - var newTable = newArray(newCapacity, 0); - var newValues = newArray(newCapacity, 0); - var newState = newArray(newCapacity, 0); - - this.lowWaterMark = chooseLowWaterMark(newCapacity, this.minLoadFactor); - this.highWaterMark = chooseHighWaterMark(newCapacity, this.maxLoadFactor); - - this.table = newTable; - this.values = newValues; - this.state = newState; - this.freeEntries = newCapacity - this.distinct; + _predict(newInputs) { + return this.A * Math.pow(newInputs, this.B); + } - for (var i = 0; i < oldCapacity; i++) { - if (oldState[i] === FULL) { - var element = oldTable[i]; - var index = this.indexOfInsertion(element); - newTable[index] = element; - newValues[index] = oldValues[i]; - newState[index] = FULL; - } - } - } + toJSON() { + return { + name: 'powerRegression', + A: this.A, + B: this.B + }; + } - forEachKey(callback) { - for (var i = 0; i < this.state.length; i++) { - if (this.state[i] === FULL) { - if (!callback(this.table[i])) return false; - } - } - return true; - } + toString(precision) { + return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + maybeToPrecision(this.B, precision); + } - forEachValue(callback) { - for (var i = 0; i < this.state.length; i++) { - if (this.state[i] === FULL) { - if (!callback(this.values[i])) return false; - } - } - return true; + toLaTeX(precision) { + if (this.B >= 0) { + return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + maybeToPrecision(this.B, precision) + '}'; + } else { + return 'f(x) = \\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + maybeToPrecision(-this.B, precision) + '}}'; } + } - forEachPair(callback) { - for (var i = 0; i < this.state.length; i++) { - if (this.state[i] === FULL) { - if (!callback(this.table[i], this.values[i])) return false; - } - } - return true; + static load(json) { + if (json.name !== 'powerRegression') { + throw new TypeError('not a power regression model'); } -} -module.exports = HashTable; + return new src_PowerRegression(true, json); + } -function chooseLowWaterMark(capacity, minLoad) { - return capacity * minLoad | 0; } -function chooseHighWaterMark(capacity, maxLoad) { - return Math.min(capacity - 2, capacity * maxLoad | 0); -} +function ml_regression_power_src_regress(pr, x, y) { + const n = x.length; + const xl = new Array(n); + const yl = new Array(n); -function chooseGrowCapacity(size, minLoad, maxLoad) { - return nextPrime(Math.max(size + 1, 4 * size / (3 * minLoad + maxLoad) | 0)); -} + for (let i = 0; i < n; i++) { + xl[i] = Math.log(x[i]); + yl[i] = Math.log(y[i]); + } -function chooseShrinkCapacity(size, minLoad, maxLoad) { - return nextPrime(Math.max(size + 1, 4 * size / (minLoad + 3 * maxLoad) | 0)); + const linear = new src_SimpleLinearRegression(xl, yl); + pr.A = Math.exp(linear.intercept); + pr.B = linear.slope; } +// CONCATENATED MODULE: ./node_modules/ml-regression-multivariate-linear/src/index.js -/***/ }), -/* 43 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +class src_MultivariateLinearRegression extends BaseRegression { + constructor(x, y) { + let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + const { + intercept = true, + statistics = true + } = options; + super(); + this.statistics = statistics; + if (x === true) { + this.weights = y.weights; + this.inputs = y.inputs; + this.outputs = y.outputs; + this.intercept = y.intercept; + } else { + x = new src["default"](x); -module.exports = function (haystack, needle, comparator, low, high) { - var mid, cmp; + if (intercept) { + x.addColumn(new Array(x.length).fill(1)); + } - if (low === undefined) low = 0;else { - low = low | 0; - if (low < 0 || low >= haystack.length) throw new RangeError("invalid lower bound"); - } + const beta = new src["SVD"](x, { + autoTranspose: true + }).solve(y); + this.weights = beta.to2DArray(); + this.inputs = x[0].length; + this.outputs = y[0].length; + if (intercept) this.inputs--; + this.intercept = intercept; - if (high === undefined) high = haystack.length - 1;else { - high = high | 0; - if (high < low || high >= haystack.length) throw new RangeError("invalid upper bound"); + if (statistics) { + /* + * Let's add some basic statistics about the beta's to be able to interpret them. + * source: http://dept.stat.lsa.umich.edu/~kshedden/Courses/Stat401/Notes/401-multreg.pdf + * validated against Excel Regression AddIn + * test: "datamining statistics test" + */ + const fittedValues = x.mmul(beta); + const residuals = new src["default"](y).addM(fittedValues.neg()); + const variance = residuals.to2DArray().map(ri => Math.pow(ri[0], 2)).reduce((a, b) => a + b) / (y.length - x.columns); + this.stdError = Math.sqrt(variance); + this.stdErrorMatrix = x.transposeView().mmul(x).pseudoInverse().mul(variance); + this.stdErrors = this.stdErrorMatrix.diagonal().map(d => Math.sqrt(d)); + this.tStats = this.weights.map((d, i) => this.stdErrors[i] === 0 ? 0 : d[0] / this.stdErrors[i]); + } + } } - while (low <= high) { - /* Note that "(low + high) >>> 1" may overflow, and results in a typecast - * to double (which gives the wrong results). */ - mid = low + (high - low >> 1); - cmp = +comparator(haystack[mid], needle, mid, haystack); + predict(x) { + if (Array.isArray(x)) { + if (typeof x[0] === 'number') { + return this._predict(x); + } else if (Array.isArray(x[0])) { + const y = new Array(x.length); - /* Too low. */ - if (cmp < 0.0) low = mid + 1; + for (let i = 0; i < x.length; i++) { + y[i] = this._predict(x[i]); + } - /* Too high. */ - else if (cmp > 0.0) high = mid - 1; + return y; + } + } - /* Key found. */ - else return mid; + throw new TypeError('x must be a matrix or array of numbers'); } - /* Key not found. */ - return ~low; -}; + _predict(x) { + const result = new Array(this.outputs); -/***/ }), -/* 44 */ -/***/ (function(module, exports, __webpack_require__) { + if (this.intercept) { + for (let i = 0; i < this.outputs; i++) { + result[i] = this.weights[this.inputs][i]; + } + } else { + result.fill(0); + } -"use strict"; + for (let i = 0; i < this.inputs; i++) { + for (let j = 0; j < this.outputs; j++) { + result[j] += this.weights[i][j] * x[i]; + } + } + return result; + } -var numberIsNan = __webpack_require__(136); + score() { + throw new Error('score method is not implemented yet'); + } -function assertNum(x) { - if (typeof x !== 'number' || numberIsNan(x)) { - throw new TypeError('Expected a number'); - } -} + toJSON() { + return { + name: 'multivariateLinearRegression', + weights: this.weights, + inputs: this.inputs, + outputs: this.outputs, + intercept: this.intercept, + summary: this.statistics ? { + regressionStatistics: { + standardError: this.stdError, + observations: this.outputs + }, + variables: this.weights.map((d, i) => { + return { + label: i === this.weights.length - 1 ? 'Intercept' : "X Variable ".concat(i + 1), + coefficients: d, + standardError: this.stdErrors[i], + tStat: this.tStats[i] + }; + }) + } : undefined + }; + } -exports.asc = function (a, b) { - assertNum(a); - assertNum(b); - return a - b; -}; + static load(model) { + if (model.name !== 'multivariateLinearRegression') { + throw new Error('not a MLR model'); + } -exports.desc = function (a, b) { - assertNum(a); - assertNum(b); - return b - a; -}; + return new src_MultivariateLinearRegression(true, model); + } -/***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { +} +// CONCATENATED MODULE: ./node_modules/ml-regression/src/regression/potential-regression.js -"use strict"; -exports.distance = __webpack_require__(137); -exports.similarity = __webpack_require__(174); +/* + * Function that calculate the potential fit in the form f(x) = A*x^M + * with a given M and return de A coefficient. + * + * @param {Vector} X - Vector of the x positions of the points. + * @param {Vector} Y - Vector of the x positions of the points. + * @param {Number} M - The exponent of the potential fit. + * @return {Number} A - The A coefficient of the potential fit. + */ -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { +class potential_regression_PotentialRegression extends BaseRegression { + /** + * @constructor + * @param x: Independent variable + * @param y: Dependent variable + * @param M + */ + constructor(x, y, M) { + super(); -"use strict"; + if (x === true) { + // reloading model + this.A = y.A; + this.M = y.M; + } else { + var n = x.length; + if (n !== y.length) { + throw new RangeError('input and output array have a different length'); + } -module.exports = function czekanowskiSimilarity(a, b) { - var up = 0; - var down = 0; - for (var i = 0; i < a.length; i++) { - up += Math.min(a[i], b[i]); - down += a[i] + b[i]; + var linear = new src_PolynomialRegression(x, y, [M]); + this.A = linear.coefficients[0]; + this.M = M; } - return 2 * up / down; -}; + } -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { + _predict(x) { + return this.A * Math.pow(x, this.M); + } -"use strict"; + toJSON() { + return { + name: 'potentialRegression', + A: this.A, + M: this.M + }; + } + toString(precision) { + return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + this.M; + } -module.exports = function dice(a, b) { - var ii = a.length, - p = 0, - q1 = 0, - q2 = 0; - for (var i = 0; i < ii; i++) { - p += a[i] * a[i]; - q1 += b[i] * b[i]; - q2 += (a[i] - b[i]) * (a[i] - b[i]); + toLaTeX(precision) { + if (this.M >= 0) { + return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + this.M + '}'; + } else { + return 'f(x) = \\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + -this.M + '}}'; } - return q2 / (p + q1); -}; - -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - + } -module.exports = function intersection(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += Math.min(a[i], b[i]); + static load(json) { + if (json.name !== 'potentialRegression') { + throw new TypeError('not a potential regression model'); } - return 1 - ans; -}; -/***/ }), -/* 49 */ -/***/ (function(module, exports, __webpack_require__) { + return new potential_regression_PotentialRegression(true, json); + } -"use strict"; +} +// EXTERNAL MODULE: ./node_modules/ml-kernel/src/kernel.js +var kernel = __webpack_require__(10); +var kernel_default = /*#__PURE__*/__webpack_require__.n(kernel); +// CONCATENATED MODULE: ./node_modules/ml-regression/src/regression/kernel-ridge-regression.js -module.exports = function jaccard(a, b) { - var ii = a.length, - p1 = 0, - p2 = 0, - q1 = 0, - q2 = 0; - for (var i = 0; i < ii; i++) { - p1 += a[i] * b[i]; - p2 += a[i] * a[i]; - q1 += b[i] * b[i]; - q2 += (a[i] - b[i]) * (a[i] - b[i]); - } - return q2 / (p2 + q1 - p1); -}; -/***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +const defaultOptions = { + lambda: 0.1, + kernelType: 'gaussian', + kernelOptions: {}, + computeCoefficient: false +}; // Implements the Kernel ridge regression algorithm. +// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf +class kernel_ridge_regression_KernelRidgeRegression extends BaseRegression { + constructor(inputs, outputs, options) { + super(); -module.exports = function kulczynski(a, b) { - var ii = a.length, - up = 0, - down = 0; - for (var i = 0; i < ii; i++) { - up += Math.abs(a[i] - b[i]); - down += Math.min(a[i], b[i]); + if (inputs === true) { + // reloading model + this.alpha = outputs.alpha; + this.inputs = outputs.inputs; + this.kernelType = outputs.kernelType; + this.kernelOptions = outputs.kernelOptions; + this.kernel = new kernel_default.a(outputs.kernelType, outputs.kernelOptions); + } else { + options = Object.assign({}, defaultOptions, options); + const kernelFunction = new kernel_default.a(options.kernelType, options.kernelOptions); + const K = kernelFunction.compute(inputs); + const n = inputs.length; + K.add(src["Matrix"].eye(n, n).mul(options.lambda)); + this.alpha = Object(src["solve"])(K, outputs); + this.inputs = inputs; + this.kernelType = options.kernelType; + this.kernelOptions = options.kernelOptions; + this.kernel = kernelFunction; } - return up / down; -}; - -/***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { + } -"use strict"; + _predict(newInputs) { + return this.kernel.compute([newInputs], this.inputs).mmul(this.alpha)[0]; + } + toJSON() { + return { + name: 'kernelRidgeRegression', + alpha: this.alpha, + inputs: this.inputs, + kernelType: this.kernelType, + kernelOptions: this.kernelOptions + }; + } -module.exports = function motyka(a, b) { - var ii = a.length, - up = 0, - down = 0; - for (var i = 0; i < ii; i++) { - up += Math.min(a[i], b[i]); - down += a[i] + b[i]; + static load(json) { + if (json.name !== 'kernelRidgeRegression') { + throw new TypeError('not a KRR model'); } - return 1 - up / down; -}; -/***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { + return new kernel_ridge_regression_KernelRidgeRegression(true, json); + } -"use strict"; +} +// CONCATENATED MODULE: ./node_modules/ml-regression/src/regression/poly-fit-regression2d.js -module.exports = function squaredChord(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i])); - } - return ans; -}; +const poly_fit_regression2d_defaultOptions = { + order: 2 +}; // Implements the Kernel ridge regression algorithm. +// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf -/***/ }), -/* 53 */ -/***/ (function(module, exports, __webpack_require__) { +class poly_fit_regression2d_PolynomialFitRegression2D extends BaseRegression { + /** + * Constructor for the 2D polynomial fitting + * + * @param inputs + * @param outputs + * @param options + * @constructor + */ + constructor(inputs, outputs, options) { + super(); -"use strict"; + if (inputs === true) { + // reloading model + this.coefficients = src["Matrix"].columnVector(outputs.coefficients); + this.order = outputs.order; + if (outputs.r) { + this.r = outputs.r; + this.r2 = outputs.r2; + } -module.exports = function tanimoto(a, b, bitvector) { - if (bitvector) { - var inter = 0, - union = 0; - for (var j = 0; j < a.length; j++) { - inter += a[j] && b[j]; - union += a[j] || b[j]; - } - if (union === 0) return 1; - return inter / union; + if (outputs.chi2) { + this.chi2 = outputs.chi2; + } } else { - var ii = a.length, - p = 0, - q = 0, - m = 0; - for (var i = 0; i < ii; i++) { - p += a[i]; - q += b[i]; - m += Math.min(a[i], b[i]); - } - return 1 - (p + q - 2 * m) / (p + q - m); + options = Object.assign({}, poly_fit_regression2d_defaultOptions, options); + this.order = options.order; + this.coefficients = []; + this.X = inputs; + this.y = outputs; + this.train(this.X, this.y, options); } -}; + } + /** + * Function that fits the model given the data(X) and predictions(y). + * The third argument is an object with the following options: + * * order: order of the polynomial to fit. + * + * @param {Matrix} X - A matrix with n rows and 2 columns. + * @param {Matrix} y - A vector of the prediction values. + */ -/***/ }), -/* 54 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + train(X, y) { + if (!src["Matrix"].isMatrix(X)) X = new src["Matrix"](X); + if (!src["Matrix"].isMatrix(y)) y = src["Matrix"].columnVector(y); + if (y.rows !== X.rows) { + y = y.transpose(); + } -module.exports = function cosine(a, b) { - var ii = a.length, - p = 0, - p2 = 0, - q2 = 0; - for (var i = 0; i < ii; i++) { - p += a[i] * b[i]; - p2 += a[i] * a[i]; - q2 += b[i] * b[i]; + if (X.columns !== 2) { + throw new RangeError('You give X with ' + X.columns + ' columns and it must be 2'); + } + + if (X.rows !== y.rows) { + throw new RangeError('X and y must have the same rows'); } - return p / (Math.sqrt(p2) * Math.sqrt(q2)); -}; -/***/ }), -/* 55 */ -/***/ (function(module, exports, __webpack_require__) { + var examples = X.rows; + var coefficients = (this.order + 2) * (this.order + 1) / 2; + this.coefficients = new Array(coefficients); + var x1 = X.getColumnVector(0); + var x2 = X.getColumnVector(1); + var scaleX1 = 1.0 / x1.clone().apply(abs).max(); + var scaleX2 = 1.0 / x2.clone().apply(abs).max(); + var scaleY = 1.0 / y.clone().apply(abs).max(); + x1.mulColumn(0, scaleX1); + x2.mulColumn(0, scaleX2); + y.mulColumn(0, scaleY); + var A = new src["Matrix"](examples, coefficients); + var col = 0; -"use strict"; + for (var i = 0; i <= this.order; ++i) { + var limit = this.order - i; + for (var j = 0; j <= limit; ++j) { + var result = powColVector(x1, i).mulColumnVector(powColVector(x2, j)); + A.setColumn(col, result); + col++; + } + } -var extend = __webpack_require__(17); + var svd = new src["SVD"](A.transpose(), { + computeLeftSingularVectors: true, + computeRightSingularVectors: true, + autoTranspose: false + }); + var qqs = src["Matrix"].rowVector(svd.diagonal); + qqs = qqs.apply(function (i, j) { + if (this[i][j] >= 1e-15) this[i][j] = 1 / this[i][j];else this[i][j] = 0; + }); + var qqs1 = src["Matrix"].zeros(examples, coefficients); -var defaultOptions = { - size: 1, - value: 0 -}; + for (i = 0; i < coefficients; ++i) { + qqs1[i][i] = qqs[0][i]; + } -/** - * Case when the entry is an array - * @param data - * @param options - * @returns {Array} - */ -function arrayCase(data, options) { - var len = data.length; - if (typeof options.size === 'number') options.size = [options.size, options.size]; + qqs = qqs1; + var U = svd.rightSingularVectors; + var V = svd.leftSingularVectors; + this.coefficients = V.mmul(qqs.transpose()).mmul(U.transpose()).mmul(y); + col = 0; - var cond = len + options.size[0] + options.size[1]; + for (i = 0; i <= coefficients; ++i) { + limit = this.order - i; - var output; - if (options.output) { - if (options.output.length !== cond) throw new RangeError('Wrong output size'); - output = options.output; - } else output = new Array(cond); + for (j = 0; j <= limit; ++j) { + this.coefficients[col][0] = this.coefficients[col][0] * Math.pow(scaleX1, i) * Math.pow(scaleX2, j) / scaleY; + col++; + } + } + } - var i; + _predict(newInputs) { + var x1 = newInputs[0]; + var x2 = newInputs[1]; + var y = 0; + var column = 0; - // circular option - if (options.value === 'circular') { - for (i = 0; i < cond; i++) { - if (i < options.size[0]) output[i] = data[(len - options.size[0] % len + i) % len];else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];else output[i] = data[(i - options.size[0]) % len]; - } + for (var i = 0; i <= this.order; i++) { + for (var j = 0; j <= this.order - i; j++) { + y += Math.pow(x1, i) * Math.pow(x2, j) * this.coefficients[column][0]; + column++; + } } - // replicate option - else if (options.value === 'replicate') { - for (i = 0; i < cond; i++) { - if (i < options.size[0]) output[i] = data[0];else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];else output[i] = data[len - 1]; - } - } + return y; + } - // symmetric option - else if (options.value === 'symmetric') { - if (options.size[0] > len || options.size[1] > len) throw new RangeError('expanded value should not be bigger than the data length'); - for (i = 0; i < cond; i++) { - if (i < options.size[0]) output[i] = data[options.size[0] - 1 - i];else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];else output[i] = data[2 * len + options.size[0] - i - 1]; - } - } + toJSON() { + return { + name: 'polyfit2D', + order: this.order, + coefficients: this.coefficients + }; + } - // default option - else { - for (i = 0; i < cond; i++) { - if (i < options.size[0]) output[i] = options.value;else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];else output[i] = options.value; - } - } + static load(json) { + if (json.name !== 'polyfit2D') { + throw new TypeError('not a polyfit2D model'); + } - return output; -} + return new poly_fit_regression2d_PolynomialFitRegression2D(true, json); + } -/** - * Case when the entry is a matrix - * @param data - * @param options - * @returns {Array} - */ -function matrixCase(data, options) { - var row = data.length; - var col = data[0].length; - if (options.size[0] === undefined) options.size = [options.size, options.size, options.size, options.size]; - throw new Error('matrix not supported yet, sorry'); } - /** - * Pads and array - * @param {Array } data - * @param {object} options + * Function that given a column vector return this: vector^power + * + * @param x - Column vector. + * @param power - Pow number. + * @return {Suite|Matrix} */ -function padArray(data, options) { - options = extend({}, defaultOptions, options); - - if (Array.isArray(data)) { - if (Array.isArray(data[0])) return matrixCase(data, options);else return arrayCase(data, options); - } else throw new TypeError('data should be an array'); -} -module.exports = padArray; +function powColVector(x, power) { + var result = x.clone(); -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { + for (var i = 0; i < x.rows; ++i) { + result[i][0] = Math.pow(result[i][0], power); + } -"use strict"; + return result; +} +/** + * Function to use in the apply method to get the absolute value + * of each element of the matrix + * + * @param i - current row. + * @param j - current column. + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); +function abs(i, j) { + this[i][j] = Math.abs(this[i][j]); +} +// EXTERNAL MODULE: ./node_modules/ml-stat/index.js +var ml_stat = __webpack_require__(3); -exports.default = function (values, options = {}) { - var _options$unbiased = options.unbiased, - unbiased = _options$unbiased === undefined ? true : _options$unbiased, - _options$mean = options.mean, - mean = _options$mean === undefined ? (0, _mlArrayMean2.default)(values) : _options$mean; +// CONCATENATED MODULE: ./node_modules/ml-regression-theil-sen/src/index.js - var sqrError = 0; - for (var i = 0; i < values.length; i++) { - var x = values[i] - mean; - sqrError += x * x; - } +const median = ml_stat["array"].median; +class src_TheilSenRegression extends BaseRegression { + /** + * Theil–Sen estimator + * https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator + * @param {Array|boolean} x + * @param {Array|object} y + * @constructor + */ + constructor(x, y) { + super(); - if (unbiased) { - return sqrError / (values.length - 1); + if (x === true) { + // loads the model + this.slope = y.slope; + this.intercept = y.intercept; + this.coefficients = y.coefficients; } else { - return sqrError / values.length; + // creates the model + checkArraySize(x, y); + theilSen(this, x, y); } -}; - -var _mlArrayMean = __webpack_require__(8); + } -var _mlArrayMean2 = _interopRequireDefault(_mlArrayMean); + toJSON() { + return { + name: 'TheilSenRegression', + slope: this.slope, + intercept: this.intercept + }; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + _predict(input) { + return this.slope * input + this.intercept; + } -/***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { + computeX(input) { + return (input - this.intercept) / this.slope; + } -"use strict"; + toString(precision) { + var result = 'f(x) = '; + if (this.slope) { + var xFactor = maybeToPrecision(this.slope, precision); + result += (Math.abs(xFactor - 1) < 1e-5 ? '' : xFactor + ' * ') + 'x'; -var mlCart = __webpack_require__(18); -var mlRandomForest = __webpack_require__(75); + if (this.intercept) { + var absIntercept = Math.abs(this.intercept); + var operator = absIntercept === this.intercept ? '+' : '-'; + result += ' ' + operator + ' ' + maybeToPrecision(absIntercept, precision); + } + } else { + result += maybeToPrecision(this.intercept, precision); + } -var ML = exports; + return result; + } -// Try to keep this list in the same structure as the README. + toLaTeX(precision) { + return this.toString(precision); + } -// Unsupervised learning -ML.PCA = __webpack_require__(81); -ML.HClust = __webpack_require__(82); -ML.KMeans = __webpack_require__(92); - -// Supervised learning -ML.SVM = __webpack_require__(97); -ML.NaiveBayes = __webpack_require__(108); -ML.KNN = __webpack_require__(111); -ML.PLS = __webpack_require__(113); -ML.CrossValidation = __webpack_require__(116); -ML.ConfusionMatrix = __webpack_require__(35); -ML.DecisionTreeClassifier = mlCart.DecisionTreeClassifier; -ML.RandomForestClassifier = mlRandomForest.RandomForestClassifier; + static load(json) { + if (json.name !== 'TheilSenRegression') { + throw new TypeError('not a Theil-Sen model'); + } -// Artificial neural networks -ML.FNN = __webpack_require__(118); -ML.SOM = __webpack_require__(120); + return new src_TheilSenRegression(true, json); + } -// Regression -var Regression = __webpack_require__(40); -ML.SimpleLinearRegression = Regression.SimpleLinearRegression; -ML.PolynomialRegression = Regression.PolynomialRegression; -ML.MultivariateLinearRegression = Regression.MultivariateLinearRegression; -ML.PowerRegression = Regression.PowerRegression; -ML.ExponentialRegression = Regression.ExponentialRegression; -ML.TheilSenRegression = Regression.TheilSenRegression; -ML.RobustPolynomialRegression = Regression.RobustPolynomialRegression; -ML.DecisionTreeRegression = mlCart.DecisionTreeRegression; -ML.RandomForestRegression = mlRandomForest.RandomForestRegression; +} -// Optimization -ML.levenbergMarquardt = __webpack_require__(132); +function theilSen(regression, x, y) { + let len = x.length; + let slopes = new Array(len * len); + let count = 0; + + for (let i = 0; i < len; ++i) { + for (let j = i + 1; j < len; ++j) { + if (x[i] !== x[j]) { + slopes[count++] = (y[j] - y[i]) / (x[j] - x[i]); + } + } + } -// Math -var Matrix = __webpack_require__(0); -ML.Matrix = Matrix.Matrix; -ML.SVD = Matrix.SVD; -ML.EVD = Matrix.EVD; -ML.CholeskyDecomposition = Matrix.CholeskyDecomposition; -ML.LuDecomposition = Matrix.LuDecomposition; -ML.QrDecomposition = Matrix.QrDecomposition; + slopes.length = count; + let medianSlope = median(slopes); + let cuts = new Array(len); -ML.SparseMatrix = __webpack_require__(133); -ML.Kernel = __webpack_require__(15); -ML.Distance = __webpack_require__(45).distance; -ML.Similarity = __webpack_require__(45).similarity; -ML.distanceMatrix = __webpack_require__(29); -ML.XSadd = __webpack_require__(32); - -// Statistics -ML.Performance = __webpack_require__(182); - -// Data preprocessing -ML.savitzkyGolay = __webpack_require__(184); -ML.savitzkyGolayGeneralized = __webpack_require__(185); - -// Utility -ML.BitArray = __webpack_require__(186); -ML.HashTable = __webpack_require__(42); -ML.padArray = __webpack_require__(55); -ML.binarySearch = __webpack_require__(43); -ML.numSort = __webpack_require__(44); -ML.Random = __webpack_require__(31); - -// Undocumented/deprecated packages -ML.ArrayUtils = __webpack_require__(188); -ML.Regression = __webpack_require__(40); -ML.MatrixUtil = __webpack_require__(0); -ML.ArrayStat = __webpack_require__(4).array; -ML.MatrixStat = __webpack_require__(4).matrix; + for (let i = 0; i < len; ++i) { + cuts[i] = y[i] - medianSlope * x[i]; + } -ML.Array = { - min: __webpack_require__(20).default, - max: __webpack_require__(11).default, - median: __webpack_require__(26).default, - mean: __webpack_require__(8).default, - mode: __webpack_require__(192).default, - rescale: __webpack_require__(19).default, - standardDeviation: __webpack_require__(193).default, - variance: __webpack_require__(56).default -}; + regression.slope = medianSlope; + regression.intercept = median(cuts); + regression.coefficients = [regression.intercept, regression.slope]; +} +// CONCATENATED MODULE: ./node_modules/ml-regression-robust-polynomial/src/index.js -/***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +class src_RobustPolynomialRegression extends BaseRegression { + constructor(x, y, degree) { + super(); + if (x === true) { + this.degree = y.degree; + this.powers = y.powers; + this.coefficients = y.coefficients; + } else { + checkArraySize(x, y); + robustPolynomial(this, x, y, degree); + } + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.DecisionTreeClassifier = undefined; + toJSON() { + return { + name: 'robustPolynomialRegression', + degree: this.degree, + powers: this.powers, + coefficients: this.coefficients + }; + } -var _mlMatrix = __webpack_require__(0); + _predict(x) { + return predict(x, this.powers, this.coefficients); + } -var _mlMatrix2 = _interopRequireDefault(_mlMatrix); + toString(precision) { + return this._toFormula(precision, false); + } -var _TreeNode = __webpack_require__(24); + toLaTeX(precision) { + return this._toFormula(precision, true); + } -var _TreeNode2 = _interopRequireDefault(_TreeNode); + _toFormula(precision, isLaTeX) { + let sup = '^'; + let closeSup = ''; + let times = ' * '; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (isLaTeX) { + sup = '^{'; + closeSup = '}'; + times = ''; + } -var defaultOptions = { - gainFunction: 'gini', - splitFunction: 'mean', - minNumSamples: 3, - maxDepth: Infinity -}; + let fn = ''; + let str = ''; -class DecisionTreeClassifier { + for (let k = 0; k < this.coefficients.length; k++) { + str = ''; - /** - * Create new Decision Tree Classifier with CART implementation with the given options - * @param {object} options - * @param {string} [options.gainFunction="gini"] - gain function to get the best split, "gini" the only one supported. - * @param {string} [options.splitFunction="mean"] - given two integers from a split feature, get the value to split, "mean" the only one supported. - * @param {number} [options.minNumSamples=3] - minimum number of samples to create a leaf node to decide a class. - * @param {number} [options.maxDepth=Infinity] - Max depth of the tree. - * @param {object} model - for load purposes. - * @constructor - */ - constructor(options, model) { - if (options === true) { - this.options = model.options; - this.root = new _TreeNode2.default(model.options); - this.root.setNodeParameters(model.root); + if (this.coefficients[k] !== 0) { + if (this.powers[k] === 0) { + str = maybeToPrecision(this.coefficients[k], precision); } else { - this.options = Object.assign({}, defaultOptions, options); - this.options.kind = 'classifier'; + if (this.powers[k] === 1) { + str = maybeToPrecision(this.coefficients[k], precision) + times + 'x'; + } else { + str = maybeToPrecision(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup; + } } - } - - /** - * Train the decision tree with the given training set and labels. - * @param {Matrix|MatrixTransposeView|Array} trainingSet - * @param {Array} trainingLabels - */ - train(trainingSet, trainingLabels) { - this.root = new _TreeNode2.default(this.options); - trainingSet = _mlMatrix2.default.checkMatrix(trainingSet); - this.root.train(trainingSet, trainingLabels, 0, null); - } - - /** - * Predicts the output given the matrix to predict. - * @param {Matrix|MatrixTransposeView|Array} toPredict - * @return {Array} predictions - */ - predict(toPredict) { - toPredict = _mlMatrix2.default.checkMatrix(toPredict); - var predictions = new Array(toPredict.rows); - for (var i = 0; i < toPredict.rows; ++i) { - predictions[i] = this.root.classify(toPredict.getRow(i)).maxRowIndex(0)[1]; + if (this.coefficients[k] > 0 && k !== this.coefficients.length - 1) { + str = ' + ' + str; + } else if (k !== this.coefficients.length - 1) { + str = ' ' + str; } + } - return predictions; + fn = str + fn; } - /** - * Export the current model to JSON. - * @return {object} - Current model. - */ - toJSON() { - return { - options: this.options, - root: this.root, - name: 'DTClassifier' - }; + if (fn.charAt(0) === '+') { + fn = fn.slice(1); } - /** - * Load a Decision tree classifier with the given model. - * @param {object} model - * @return {DecisionTreeClassifier} - */ - static load(model) { - if (model.name !== 'DTClassifier') { - throw new RangeError('Invalid model: ' + model.name); - } + return 'f(x) = ' + fn; + } - return new DecisionTreeClassifier(true, model); + static load(json) { + if (json.name !== 'robustPolynomialRegression') { + throw new TypeError('not a RobustPolynomialRegression model'); } -} -exports.DecisionTreeClassifier = DecisionTreeClassifier; -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { + return new src_RobustPolynomialRegression(true, json); + } -"use strict"; +} +function robustPolynomial(regression, x, y, degree) { + let powers = new Array(degree); -Object.defineProperty(exports, "__esModule", { - value: true -}); + for (let k = 0; k < degree; k++) { + powers[k] = k; + } -var _base = __webpack_require__(3); + const tuples = getRandomTuples(x, y, degree); + var min; -var _base2 = _interopRequireDefault(_base); + for (var i = 0; i < tuples.length; i++) { + var tuple = tuples[i]; + var coefficients = calcCoefficients(tuple, powers); + var residuals = x.slice(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (var j = 0; j < x.length; j++) { + residuals[j] = y[j] - predict(x[j], powers, coefficients); + residuals[j] = { + residual: residuals[j] * residuals[j], + coefficients + }; + } -class MatrixTransposeView extends _base2.default { - constructor(matrix) { - super(matrix, matrix.columns, matrix.rows); - } + var median = residualsMedian(residuals); - set(rowIndex, columnIndex, value) { - this.matrix.set(columnIndex, rowIndex, value); - return this; + if (!min || median.residual < min.residual) { + min = median; + } } - get(rowIndex, columnIndex) { - return this.matrix.get(columnIndex, rowIndex); - } + regression.degree = degree; + regression.powers = powers; + regression.coefficients = min.coefficients; } -exports.default = MatrixTransposeView; +/** + * @ignore + * @param {Array} x + * @param {Array} y + * @param {number} degree + * @return {Array<{x:number,y:number}>} + */ -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +function getRandomTuples(x, y, degree) { + var len = Math.floor(x.length / degree); + var tuples = new Array(len); + + for (var i = 0; i < x.length; i++) { + var pos = Math.floor(Math.random() * len); + var counter = 0; + + while (counter < x.length) { + if (!tuples[pos]) { + tuples[pos] = [{ + x: x[i], + y: y[i] + }]; + break; + } else if (tuples[pos].length < degree) { + tuples[pos].push({ + x: x[i], + y: y[i] + }); + break; + } else { + counter++; + pos = (pos + 1) % len; + } + } + if (counter === x.length) { + return tuples; + } + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + return tuples; +} +/** + * @ignore + * @param {{x:number,y:number}} tuple + * @param {Array} powers + * @return {Array} + */ -var _base = __webpack_require__(3); -var _base2 = _interopRequireDefault(_base); +function calcCoefficients(tuple, powers) { + var X = tuple.slice(); + var Y = tuple.slice(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (var i = 0; i < X.length; i++) { + Y[i] = [tuple[i].y]; + X[i] = new Array(powers.length); -class MatrixRowView extends _base2.default { - constructor(matrix, row) { - super(matrix, 1, matrix.columns); - this.row = row; + for (var j = 0; j < powers.length; j++) { + X[i][j] = Math.pow(tuple[i].x, powers[j]); + } } - set(rowIndex, columnIndex, value) { - this.matrix.set(this.row, columnIndex, value); - return this; + return Object(src["solve"])(X, Y).to1DArray(); +} + +function predict(x, powers, coefficients) { + let y = 0; + + for (let k = 0; k < powers.length; k++) { + y += coefficients[k] * Math.pow(x, powers[k]); } - get(rowIndex, columnIndex) { - return this.matrix.get(this.row, columnIndex); + return y; +} + +function residualsMedian(residuals) { + residuals.sort((a, b) => a.residual - b.residual); + var l = residuals.length; + var half = Math.floor(l / 2); + + if (l % 2 === 0) { + return residuals[half - 1]; + } else { + return residuals[half]; } } -exports.default = MatrixRowView; +// CONCATENATED MODULE: ./node_modules/ml-regression/src/index.js +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NLR", function() { return NLR; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NonLinearRegression", function() { return NLR; }); +/* concated harmony reexport SimpleLinearRegression */__webpack_require__.d(__webpack_exports__, "SimpleLinearRegression", function() { return src_SimpleLinearRegression; }); +/* concated harmony reexport SLR */__webpack_require__.d(__webpack_exports__, "SLR", function() { return src_SimpleLinearRegression; }); +/* concated harmony reexport PolynomialRegression */__webpack_require__.d(__webpack_exports__, "PolynomialRegression", function() { return src_PolynomialRegression; }); +/* concated harmony reexport ExponentialRegression */__webpack_require__.d(__webpack_exports__, "ExponentialRegression", function() { return src_ExponentialRegression; }); +/* concated harmony reexport PowerRegression */__webpack_require__.d(__webpack_exports__, "PowerRegression", function() { return src_PowerRegression; }); +/* concated harmony reexport MultivariateLinearRegression */__webpack_require__.d(__webpack_exports__, "MultivariateLinearRegression", function() { return src_MultivariateLinearRegression; }); +/* concated harmony reexport KernelRidgeRegression */__webpack_require__.d(__webpack_exports__, "KernelRidgeRegression", function() { return kernel_ridge_regression_KernelRidgeRegression; }); +/* concated harmony reexport KRR */__webpack_require__.d(__webpack_exports__, "KRR", function() { return kernel_ridge_regression_KernelRidgeRegression; }); +/* concated harmony reexport PolinomialFitting2D */__webpack_require__.d(__webpack_exports__, "PolinomialFitting2D", function() { return poly_fit_regression2d_PolynomialFitRegression2D; }); +/* concated harmony reexport TheilSenRegression */__webpack_require__.d(__webpack_exports__, "TheilSenRegression", function() { return src_TheilSenRegression; }); +/* concated harmony reexport RobustPolynomialRegression */__webpack_require__.d(__webpack_exports__, "RobustPolynomialRegression", function() { return src_RobustPolynomialRegression; }); + + + + + + +const NLR = { + PotentialRegression: potential_regression_PotentialRegression +}; -/***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + // robust regressions -Object.defineProperty(exports, "__esModule", { - value: true -}); -var _util = __webpack_require__(6); -var _base = __webpack_require__(3); +/***/ }), +/* 42 */ +/***/ (function(module, exports, __webpack_require__) { -var _base2 = _interopRequireDefault(_base); +(function () { + function a(d) { + for (var e = 0, f = d.length - 1, g = void 0, h = void 0, i = void 0, j = c(e, f); !0;) { + if (f <= e) return d[j]; + if (f == e + 1) return d[e] > d[f] && b(d, e, f), d[j]; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (g = c(e, f), d[g] > d[f] && b(d, g, f), d[e] > d[f] && b(d, e, f), d[g] > d[e] && b(d, g, e), b(d, g, e + 1), h = e + 1, i = f; !0;) { + do h++; while (d[e] > d[h]); -class MatrixSubView extends _base2.default { - constructor(matrix, startRow, endRow, startColumn, endColumn) { - (0, _util.checkRange)(matrix, startRow, endRow, startColumn, endColumn); - super(matrix, endRow - startRow + 1, endColumn - startColumn + 1); - this.startRow = startRow; - this.startColumn = startColumn; - } + do i--; while (d[i] > d[e]); - set(rowIndex, columnIndex, value) { - this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex, value); - return this; - } + if (i < h) break; + b(d, h, i); + } - get(rowIndex, columnIndex) { - return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex); + b(d, e, i), i <= j && (e = h), i >= j && (f = i - 1); + } } -} -exports.default = MatrixSubView; + + var b = function b(d, e, f) { + var _ref; + + return _ref = [d[f], d[e]], d[e] = _ref[0], d[f] = _ref[1], _ref; + }, + c = function c(d, e) { + return ~~((d + e) / 2); + }; + + true && module.exports ? module.exports = a : window.median = a; +})(); /***/ }), -/* 62 */ +/* 43 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); +const mlCart = __webpack_require__(8); -var _util = __webpack_require__(6); +const mlRandomForest = __webpack_require__(141); -var _base = __webpack_require__(3); +const ML = exports; // Try to keep this list in the same structure as the README. +// Unsupervised learning -var _base2 = _interopRequireDefault(_base); +ML.PCA = __webpack_require__(44); +ML.HClust = __webpack_require__(45); +ML.KMeans = __webpack_require__(140); // Supervised learning -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +ML.SVM = __webpack_require__(54); +ML.NaiveBayes = __webpack_require__(143); +ML.KNN = __webpack_require__(147); +ML.PLS = __webpack_require__(144); +ML.CrossValidation = __webpack_require__(65); +ML.ConfusionMatrix = __webpack_require__(25); +ML.DecisionTreeClassifier = mlCart.DecisionTreeClassifier; +ML.RandomForestClassifier = mlRandomForest.RandomForestClassifier; // Artificial neural networks -class MatrixSelectionView extends _base2.default { - constructor(matrix, rowIndices, columnIndices) { - var indices = (0, _util.checkIndices)(matrix, rowIndices, columnIndices); - super(matrix, indices.row.length, indices.column.length); - this.rowIndices = indices.row; - this.columnIndices = indices.column; - } +ML.FNN = __webpack_require__(67); +ML.SOM = __webpack_require__(69); // Regression - set(rowIndex, columnIndex, value) { - this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value); - return this; - } +const Regression = __webpack_require__(41); - get(rowIndex, columnIndex) { - return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]); - } -} -exports.default = MatrixSelectionView; +ML.SimpleLinearRegression = Regression.SimpleLinearRegression; +ML.PolynomialRegression = Regression.PolynomialRegression; +ML.MultivariateLinearRegression = Regression.MultivariateLinearRegression; +ML.PowerRegression = Regression.PowerRegression; +ML.ExponentialRegression = Regression.ExponentialRegression; +ML.TheilSenRegression = Regression.TheilSenRegression; +ML.RobustPolynomialRegression = Regression.RobustPolynomialRegression; +ML.DecisionTreeRegression = mlCart.DecisionTreeRegression; +ML.RandomForestRegression = mlRandomForest.RandomForestRegression; // Optimization + +ML.levenbergMarquardt = __webpack_require__(145); // Math + +const Matrix = __webpack_require__(0); + +ML.Matrix = Matrix.Matrix; +ML.SVD = Matrix.SVD; +ML.EVD = Matrix.EVD; +ML.CholeskyDecomposition = Matrix.CholeskyDecomposition; +ML.LuDecomposition = Matrix.LuDecomposition; +ML.QrDecomposition = Matrix.QrDecomposition; +ML.SparseMatrix = __webpack_require__(71); +ML.Kernel = __webpack_require__(10); +ML.Distance = __webpack_require__(30).distance; +ML.Similarity = __webpack_require__(30).similarity; +ML.distanceMatrix = __webpack_require__(24); +ML.XSadd = __webpack_require__(19).default; // Statistics + +ML.Performance = __webpack_require__(120); // Data preprocessing + +ML.savitzkyGolay = __webpack_require__(122); +ML.savitzkyGolayGeneralized = __webpack_require__(123); // Utility + +ML.BitArray = __webpack_require__(124); +ML.HashTable = __webpack_require__(14); +ML.padArray = __webpack_require__(40); +ML.binarySearch = __webpack_require__(6); +ML.numSort = __webpack_require__(7); +ML.Random = __webpack_require__(11).default; // Undocumented/deprecated packages + +ML.ArrayUtils = __webpack_require__(126); +ML.Regression = __webpack_require__(41); +ML.MatrixUtil = __webpack_require__(0); +ML.ArrayStat = __webpack_require__(3).array; +ML.MatrixStat = __webpack_require__(3).matrix; +ML.Array = { + min: __webpack_require__(17).default, + max: __webpack_require__(9).default, + median: __webpack_require__(18).default, + mean: __webpack_require__(5).default, + mode: __webpack_require__(130).default, + normed: __webpack_require__(131).default, + rescale: __webpack_require__(13).default, + sequentialFill: __webpack_require__(20).default, + standardDeviation: __webpack_require__(132).default, + variance: __webpack_require__(21).default +}; +ML.ArrayXY = { + centroidsMerge: __webpack_require__(133).default, + closestX: __webpack_require__(134).default, + maxMerge: __webpack_require__(135).default, + maxY: __webpack_require__(136).default, + sortX: __webpack_require__(137).default, + uniqueX: __webpack_require__(138).default, + weightedMerge: __webpack_require__(139).default, + equallySpaced: __webpack_require__(142).default, + filterX: __webpack_require__(146).default +}; /***/ }), -/* 63 */ +/* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); +const matrixLib = __webpack_require__(0); -var _util = __webpack_require__(6); +const Matrix = matrixLib.Matrix; +const EVD = matrixLib.EVD; +const SVD = matrixLib.SVD; -var _base = __webpack_require__(3); +const Stat = __webpack_require__(4); -var _base2 = _interopRequireDefault(_base); +const mean = Stat.mean; +const stdev = Stat.standardDeviation; +const defaultOptions = { + isCovarianceMatrix: false, + center: true, + scale: false +}; +/** + * Creates new PCA (Principal Component Analysis) from the dataset + * @param {Matrix} dataset - dataset or covariance matrix + * @param {Object} options + * @param {boolean} [options.isCovarianceMatrix=false] - true if the dataset is a covariance matrix + * @param {boolean} [options.center=true] - should the data be centered (subtract the mean) + * @param {boolean} [options.scale=false] - should the data be scaled (divide by the standard deviation) + * */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +class PCA { + constructor(dataset, options) { + if (dataset === true) { + const model = options; + this.center = model.center; + this.scale = model.scale; + this.means = model.means; + this.stdevs = model.stdevs; + this.U = Matrix.checkMatrix(model.U); + this.S = model.S; + return; + } -class MatrixRowSelectionView extends _base2.default { - constructor(matrix, rowIndices) { - rowIndices = (0, _util.checkRowIndices)(matrix, rowIndices); - super(matrix, rowIndices.length, matrix.columns); - this.rowIndices = rowIndices; - } + options = Object.assign({}, defaultOptions, options); + this.center = false; + this.scale = false; + this.means = null; + this.stdevs = null; - set(rowIndex, columnIndex, value) { - this.matrix.set(this.rowIndices[rowIndex], columnIndex, value); - return this; - } + if (options.isCovarianceMatrix) { + // user provided a covariance matrix instead of dataset + this._computeFromCovarianceMatrix(dataset); - get(rowIndex, columnIndex) { - return this.matrix.get(this.rowIndices[rowIndex], columnIndex); - } -} -exports.default = MatrixRowSelectionView; + return; + } -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { + var useCovarianceMatrix; -"use strict"; + if (typeof options.useCovarianceMatrix === 'boolean') { + useCovarianceMatrix = options.useCovarianceMatrix; + } else { + useCovarianceMatrix = dataset.length > dataset[0].length; + } + if (useCovarianceMatrix) { + // user provided a dataset but wants us to compute and use the covariance matrix + dataset = this._adjust(dataset, options); + const covarianceMatrix = dataset.transposeView().mmul(dataset).div(dataset.rows - 1); -Object.defineProperty(exports, "__esModule", { - value: true -}); + this._computeFromCovarianceMatrix(covarianceMatrix); + } else { + dataset = this._adjust(dataset, options); + var svd = new SVD(dataset, { + computeLeftSingularVectors: false, + computeRightSingularVectors: true, + autoTranspose: true + }); + this.U = svd.rightSingularVectors; + const singularValues = svd.diagonal; + const eigenvalues = new Array(singularValues.length); + + for (var i = 0; i < singularValues.length; i++) { + eigenvalues[i] = singularValues[i] * singularValues[i] / (dataset.length - 1); + } + + this.S = eigenvalues; + } + } + /** + * Load a PCA model from JSON + * @param {Object} model + * @return {PCA} + */ -var _util = __webpack_require__(6); -var _base = __webpack_require__(3); + static load(model) { + if (model.name !== 'PCA') throw new RangeError('Invalid model: ' + model.name); + return new PCA(true, model); + } + /** + * Project the dataset into the PCA space + * @param {Matrix} dataset + * @param {Object} options + * @return {Matrix} dataset projected in the PCA space + */ -var _base2 = _interopRequireDefault(_base); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + predict(dataset) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const { + nComponents = this.U.columns + } = options; + dataset = new Matrix(dataset); -class MatrixColumnSelectionView extends _base2.default { - constructor(matrix, columnIndices) { - columnIndices = (0, _util.checkColumnIndices)(matrix, columnIndices); - super(matrix, matrix.rows, columnIndices.length); - this.columnIndices = columnIndices; - } + if (this.center) { + dataset.subRowVector(this.means); - set(rowIndex, columnIndex, value) { - this.matrix.set(rowIndex, this.columnIndices[columnIndex], value); - return this; - } + if (this.scale) { + dataset.divRowVector(this.stdevs); + } + } - get(rowIndex, columnIndex) { - return this.matrix.get(rowIndex, this.columnIndices[columnIndex]); + var predictions = dataset.mmul(this.U); + return predictions.subMatrix(0, predictions.rows - 1, 0, nComponents - 1); } -} -exports.default = MatrixColumnSelectionView; + /** + * Returns the proportion of variance for each component + * @return {[number]} + */ -/***/ }), -/* 65 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + getExplainedVariance() { + var sum = 0; + for (var i = 0; i < this.S.length; i++) { + sum += this.S[i]; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + return this.S.map(value => value / sum); + } + /** + * Returns the cumulative proportion of variance + * @return {[number]} + */ -var _base = __webpack_require__(3); -var _base2 = _interopRequireDefault(_base); + getCumulativeVariance() { + var explained = this.getExplainedVariance(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (var i = 1; i < explained.length; i++) { + explained[i] += explained[i - 1]; + } -class MatrixColumnView extends _base2.default { - constructor(matrix, column) { - super(matrix, matrix.rows, 1); - this.column = column; + return explained; } + /** + * Returns the Eigenvectors of the covariance matrix + * @returns {Matrix} + */ - set(rowIndex, columnIndex, value) { - this.matrix.set(rowIndex, this.column, value); - return this; - } - get(rowIndex) { - return this.matrix.get(rowIndex, this.column); + getEigenvectors() { + return this.U; } -} -exports.default = MatrixColumnView; + /** + * Returns the Eigenvalues (on the diagonal) + * @returns {[number]} + */ -/***/ }), -/* 66 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + getEigenvalues() { + return this.S; + } + /** + * Returns the standard deviations of the principal components + * @returns {[number]} + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); + getStandardDeviations() { + return this.S.map(x => Math.sqrt(x)); + } + /** + * Returns the loadings matrix + * @return {Matrix} + */ -var _base = __webpack_require__(3); -var _base2 = _interopRequireDefault(_base); + getLoadings() { + return this.U.transpose(); + } + /** + * Export the current model to a JSON object + * @return {Object} model + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -class MatrixFlipRowView extends _base2.default { - constructor(matrix) { - super(matrix, matrix.rows, matrix.columns); + toJSON() { + return { + name: 'PCA', + center: this.center, + scale: this.scale, + means: this.means, + stdevs: this.stdevs, + U: this.U, + S: this.S + }; } - set(rowIndex, columnIndex, value) { - this.matrix.set(this.rows - rowIndex - 1, columnIndex, value); - return this; + _adjust(dataset, options) { + this.center = !!options.center; + this.scale = !!options.scale; + dataset = new Matrix(dataset); + + if (this.center) { + const means = mean(dataset); + const stdevs = this.scale ? stdev(dataset, means, true) : null; + this.means = means; + dataset.subRowVector(means); + + if (this.scale) { + for (var i = 0; i < stdevs.length; i++) { + if (stdevs[i] === 0) { + throw new RangeError('Cannot scale the dataset (standard deviation is zero at index ' + i); + } + } + + this.stdevs = stdevs; + dataset.divRowVector(stdevs); + } + } + + return dataset; } - get(rowIndex, columnIndex) { - return this.matrix.get(this.rows - rowIndex - 1, columnIndex); + _computeFromCovarianceMatrix(dataset) { + const evd = new EVD(dataset, { + assumeSymmetric: true + }); + this.U = evd.eigenvectorMatrix; + + for (var i = 0; i < this.U.length; i++) { + this.U[i].reverse(); + } + + this.S = evd.realEigenvalues.reverse(); } + } -exports.default = MatrixFlipRowView; + +module.exports = PCA; /***/ }), -/* 67 */ +/* 45 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _base = __webpack_require__(3); +exports.agnes = __webpack_require__(46); +exports.diana = __webpack_require__(53); //exports.birch = require('./birch'); +//exports.cure = require('./cure'); +//exports.chameleon = require('./chameleon'); -var _base2 = _interopRequireDefault(_base); +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +"use strict"; -class MatrixFlipColumnView extends _base2.default { - constructor(matrix) { - super(matrix, matrix.rows, matrix.columns); - } - set(rowIndex, columnIndex, value) { - this.matrix.set(rowIndex, this.columns - columnIndex - 1, value); - return this; - } +const euclidean = __webpack_require__(2); - get(rowIndex, columnIndex) { - return this.matrix.get(rowIndex, this.columns - columnIndex - 1); - } -} -exports.default = MatrixFlipColumnView; +const ClusterLeaf = __webpack_require__(23); -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { +const Cluster = __webpack_require__(15); -"use strict"; +const distanceMatrix = __webpack_require__(24); +/** + * @private + * @param cluster1 + * @param cluster2 + * @param disFun + * @returns {number} + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.wrap = wrap; +function simpleLink(cluster1, cluster2, disFun) { + var m = 10e100; -var _WrapperMatrix1D = __webpack_require__(21); + for (var i = 0; i < cluster1.length; i++) { + for (var j = 0; j < cluster2.length; j++) { + var d = disFun[cluster1[i]][cluster2[j]]; + m = Math.min(d, m); + } + } -var _WrapperMatrix1D2 = _interopRequireDefault(_WrapperMatrix1D); + return m; +} +/** + * @private + * @param cluster1 + * @param cluster2 + * @param disFun + * @returns {number} + */ -var _WrapperMatrix2D = __webpack_require__(22); -var _WrapperMatrix2D2 = _interopRequireDefault(_WrapperMatrix2D); +function completeLink(cluster1, cluster2, disFun) { + var m = -1; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (var i = 0; i < cluster1.length; i++) { + for (var j = 0; j < cluster2.length; j++) { + var d = disFun[cluster1[i]][cluster2[j]]; + m = Math.max(d, m); + } + } + return m; +} /** - * @param {Array>|Array} array - * @param {object} [options] - * @param {object} [options.rows = 1] - * @return {WrapperMatrix1D|WrapperMatrix2D} - */ -function wrap(array, options) { - if (Array.isArray(array)) { - if (array[0] && Array.isArray(array[0])) { - return new _WrapperMatrix2D2.default(array); - } else { - return new _WrapperMatrix1D2.default(array, options); + * @private + * @param cluster1 + * @param cluster2 + * @param disFun + * @returns {number} + */ + + +function averageLink(cluster1, cluster2, disFun) { + var m = 0; + + for (var i = 0; i < cluster1.length; i++) { + for (var j = 0; j < cluster2.length; j++) { + m += disFun[cluster1[i]][cluster2[j]]; } - } else { - throw new Error('the argument is not an array'); } -} - -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + return m / (cluster1.length * cluster2.length); +} +/** + * @private + * @param cluster1 + * @param cluster2 + * @param disFun + * @returns {*} + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.inverse = inverse; -exports.solve = solve; +function centroidLink(cluster1, cluster2, disFun) { + var dist = new Array(cluster1.length * cluster2.length); -var _lu = __webpack_require__(12); + for (var i = 0; i < cluster1.length; i++) { + for (var j = 0; j < cluster2.length; j++) { + dist[i * cluster2.length + j] = disFun[cluster1[i]][cluster2[j]]; + } + } -var _lu2 = _interopRequireDefault(_lu); + return median(dist); +} +/** + * @private + * @param cluster1 + * @param cluster2 + * @param disFun + * @returns {number} + */ -var _qr = __webpack_require__(23); -var _qr2 = _interopRequireDefault(_qr); +function wardLink(cluster1, cluster2, disFun) { + return centroidLink(cluster1, cluster2, disFun) * cluster1.length * cluster2.length / (cluster1.length + cluster2.length); +} -var _svd = __webpack_require__(9); +function compareNumbers(a, b) { + return a - b; +} -var _svd2 = _interopRequireDefault(_svd); +function median(values, alreadySorted) { + if (alreadySorted === undefined) alreadySorted = false; -var _index = __webpack_require__(0); + if (!alreadySorted) { + values = [].concat(values).sort(compareNumbers); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var l = values.length; + var half = Math.floor(l / 2); -/** - * Computes the inverse of a Matrix - * @param {Matrix} matrix - * @param {boolean} [useSVD=false] - * @return {Matrix} - */ -function inverse(matrix, useSVD = false) { - matrix = _index.WrapperMatrix2D.checkMatrix(matrix); - if (useSVD) { - return new _svd2.default(matrix).inverse(); + if (l % 2 === 0) { + return (values[half - 1] + values[half]) * 0.5; } else { - return solve(matrix, _index.Matrix.eye(matrix.rows)); + return values[half]; } } +var defaultOptions = { + disFunc: euclidean, + kind: 'single', + isDistanceMatrix: false +}; /** - * - * @param {Matrix} leftHandSide - * @param {Matrix} rightHandSide - * @param {boolean} [useSVD = false] - * @return {Matrix} + * Continuously merge nodes that have the least dissimilarity + * @param {Array >} distance - Array of points to be clustered + * @param {json} options + * @option isDistanceMatrix: Is the input a distance matrix? + * @constructor */ -function solve(leftHandSide, rightHandSide, useSVD = false) { - leftHandSide = _index.WrapperMatrix2D.checkMatrix(leftHandSide); - rightHandSide = _index.WrapperMatrix2D.checkMatrix(rightHandSide); - if (useSVD) { - return new _svd2.default(leftHandSide).solve(rightHandSide); - } else { - return leftHandSide.isSquare() ? new _lu2.default(leftHandSide).solve(rightHandSide) : new _qr2.default(leftHandSide).solve(rightHandSide); - } -} - -/***/ }), -/* 70 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.linearDependencies = linearDependencies; -var _mlArrayMax = __webpack_require__(11); +function agnes(data, options) { + options = Object.assign({}, defaultOptions, options); + var len = data.length; + var distance = data; //If source -var _mlArrayMax2 = _interopRequireDefault(_mlArrayMax); + if (!options.isDistanceMatrix) { + distance = distanceMatrix(data, options.disFunc); + } // allows to use a string or a given function -var _matrix = __webpack_require__(5); -var _matrix2 = _interopRequireDefault(_matrix); + if (typeof options.kind === 'string') { + switch (options.kind) { + case 'single': + options.kind = simpleLink; + break; -var _svd = __webpack_require__(9); + case 'complete': + options.kind = completeLink; + break; -var _svd2 = _interopRequireDefault(_svd); + case 'average': + options.kind = averageLink; + break; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + case 'centroid': + options.kind = centroidLink; + break; -// function used by rowsDependencies -function xrange(n, exception) { - var range = []; - for (var i = 0; i < n; i++) { - if (i !== exception) { - range.push(i); - } - } - return range; -} + case 'ward': + options.kind = wardLink; + break; -// function used by rowsDependencies -function dependenciesOneRow(error, matrix, index, thresholdValue = 10e-10, thresholdError = 10e-10) { - if (error > thresholdError) { - return new Array(matrix.rows + 1).fill(0); - } else { - var returnArray = matrix.addRow(index, [0]); - for (var i = 0; i < returnArray.rows; i++) { - if (Math.abs(returnArray.get(i, 0)) < thresholdValue) { - returnArray.set(i, 0, 0); - } + default: + throw new RangeError('Unknown kind of similarity'); } - return returnArray.to1DArray(); + } else if (typeof options.kind !== 'function') { + throw new TypeError('Undefined kind of similarity'); } -} -/** - * Creates a matrix which represents the dependencies between rows. - * If a row is a linear combination of others rows, the result will be a row with the coefficients of this combination. - * For example : for A = [[2, 0, 0, 1], [0, 1, 6, 0], [0, 3, 0, 1], [0, 0, 1, 0], [0, 1, 2, 0]], the result will be [[0, 0, 0, 0, 0], [0, 0, 0, 4, 1], [0, 0, 0, 0, 0], [0, 0.25, 0, 0, -0.25], [0, 1, 0, -4, 0]] - * @param {Matrix} matrix - * @param {Object} [options] includes thresholdValue and thresholdError. - * @param {number} [options.thresholdValue = 10e-10] If an absolute value is inferior to this threshold, it will equals zero. - * @param {number} [options.thresholdError = 10e-10] If the error is inferior to that threshold, the linear combination found is accepted and the row is dependent from other rows. - * @return {Matrix} the matrix which represents the dependencies between rows. - */ + var list = new Array(len); -function linearDependencies(matrix, options = {}) { - var _options$thresholdVal = options.thresholdValue, - thresholdValue = _options$thresholdVal === undefined ? 10e-10 : _options$thresholdVal, - _options$thresholdErr = options.thresholdError, - thresholdError = _options$thresholdErr === undefined ? 10e-10 : _options$thresholdErr; + for (var i = 0; i < distance.length; i++) { + list[i] = new ClusterLeaf(i); + } + var min = 10e5, + d = {}, + dis = 0; - var n = matrix.rows; - var results = new _matrix2.default(n, n); + while (list.length > 1) { + // calculates the minimum distance + d = {}; + min = 10e5; - for (var i = 0; i < n; i++) { - var b = _matrix2.default.columnVector(matrix.getRow(i)); - var Abis = matrix.subMatrixRow(xrange(n, i)).transposeView(); - var svd = new _svd2.default(Abis); - var x = svd.solve(b); - var error = (0, _mlArrayMax2.default)(_matrix2.default.sub(b, Abis.mmul(x)).abs().to1DArray()); - results.setRow(i, dependenciesOneRow(error, x, i, thresholdValue, thresholdError)); - } - return results; -} + for (var j = 0; j < list.length; j++) { + for (var k = j + 1; k < list.length; k++) { + var fdistance, sdistance; -/***/ }), -/* 71 */ -/***/ (function(module, exports, __webpack_require__) { + if (list[j] instanceof ClusterLeaf) { + fdistance = [list[j].index]; + } else { + fdistance = new Array(list[j].index.length); -"use strict"; + for (var e = 0; e < fdistance.length; e++) { + fdistance[e] = list[j].index[e].index; + } + } + if (list[k] instanceof ClusterLeaf) { + sdistance = [list[k].index]; + } else { + sdistance = new Array(list[k].index.length); -Object.defineProperty(exports, "__esModule", { - value: true -}); + for (var f = 0; f < sdistance.length; f++) { + sdistance[f] = list[k].index[f].index; + } + } -var _index = __webpack_require__(0); + dis = options.kind(fdistance, sdistance, distance).toFixed(4); -var _util = __webpack_require__(13); + if (dis in d) { + d[dis].push([list[j], list[k]]); + } else { + d[dis] = [[list[j], list[k]]]; + } -/** - * @class EigenvalueDecomposition - * @link https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs - * @param {Matrix} matrix - * @param {object} [options] - * @param {boolean} [options.assumeSymmetric=false] - */ -class EigenvalueDecomposition { - constructor(matrix, options = {}) { - var _options$assumeSymmet = options.assumeSymmetric, - assumeSymmetric = _options$assumeSymmet === undefined ? false : _options$assumeSymmet; + min = Math.min(dis, min); + } + } // cluster dots - matrix = _index.WrapperMatrix2D.checkMatrix(matrix); - if (!matrix.isSquare()) { - throw new Error('Matrix is not a square matrix'); - } + var dmin = d[min.toFixed(4)]; + var clustered = new Array(dmin.length); + var aux, + count = 0; - var n = matrix.columns; - var V = (0, _util.getFilled2DArray)(n, n, 0); - var d = new Array(n); - var e = new Array(n); - var value = matrix; - var i, j; + while (dmin.length > 0) { + aux = dmin.shift(); - var isSymmetric = false; - if (assumeSymmetric) { - isSymmetric = true; - } else { - isSymmetric = matrix.isSymmetric(); - } + for (var q = 0; q < dmin.length; q++) { + var int = dmin[q].filter(function (n) { + //noinspection JSReferencingMutableVariableFromClosure + return aux.indexOf(n) !== -1; + }); - if (isSymmetric) { - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - V[i][j] = value.get(i, j); - } - } - tred2(n, e, d, V); - tql2(n, e, d, V); - } else { - var H = (0, _util.getFilled2DArray)(n, n, 0); - var ort = new Array(n); - for (j = 0; j < n; j++) { - for (i = 0; i < n; i++) { - H[i][j] = value.get(i, j); + if (int.length > 0) { + var diff = dmin[q].filter(function (n) { + //noinspection JSReferencingMutableVariableFromClosure + return aux.indexOf(n) === -1; + }); + aux = aux.concat(diff); + dmin.splice(q--, 1); } } - orthes(n, H, ort, V); - hqr2(n, e, d, V, H); - } - this.n = n; - this.e = e; - this.d = d; - this.V = V; - } + clustered[count++] = aux; + } - /** - * - * @return {Array} - */ - get realEigenvalues() { - return this.d; - } + clustered.length = count; - /** - * - * @return {Array} - */ - get imaginaryEigenvalues() { - return this.e; - } + for (var ii = 0; ii < clustered.length; ii++) { + var obj = new Cluster(); + obj.children = clustered[ii].concat(); + obj.distance = min; + obj.index = new Array(len); + var indCount = 0; - /** - * - * @return {Matrix} - */ - get eigenvectorMatrix() { - if (!_index.Matrix.isMatrix(this.V)) { - this.V = new _index.Matrix(this.V); - } - return this.V; - } + for (var jj = 0; jj < clustered[ii].length; jj++) { + if (clustered[ii][jj] instanceof ClusterLeaf) { + obj.index[indCount++] = clustered[ii][jj]; + } else { + indCount += clustered[ii][jj].index.length; + obj.index = clustered[ii][jj].index.concat(obj.index); + } - /** - * - * @return {Matrix} - */ - get diagonalMatrix() { - var n = this.n; - var e = this.e; - var d = this.d; - var X = new _index.Matrix(n, n); - var i, j; - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - X[i][j] = 0; - } - X[i][i] = d[i]; - if (e[i] > 0) { - X[i][i + 1] = e[i]; - } else if (e[i] < 0) { - X[i][i - 1] = e[i]; + list.splice(list.indexOf(clustered[ii][jj]), 1); } + + obj.index.length = indCount; + list.push(obj); } - return X; } + + return list[0]; } -exports.default = EigenvalueDecomposition; -function tred2(n, e, d, V) { - var f, g, h, i, j, k, hh, scale; +module.exports = agnes; - for (j = 0; j < n; j++) { - d[j] = V[n - 1][j]; - } +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { - for (i = n - 1; i > 0; i--) { - scale = 0; - h = 0; - for (k = 0; k < i; k++) { - scale = scale + Math.abs(d[k]); +module.exports = __webpack_require__(48); + +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Generated by CoffeeScript 1.8.0 +(function () { + var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup; + + floor = Math.floor, min = Math.min; + /* + Default comparison function to be used + */ + + defaultCmp = function defaultCmp(x, y) { + if (x < y) { + return -1; } - if (scale === 0) { - e[i] = d[i - 1]; - for (j = 0; j < i; j++) { - d[j] = V[i - 1][j]; - V[i][j] = 0; - V[j][i] = 0; - } - } else { - for (k = 0; k < i; k++) { - d[k] /= scale; - h += d[k] * d[k]; - } + if (x > y) { + return 1; + } + + return 0; + }; + /* + Insert item x in list a, and keep it sorted assuming a is sorted. + + If x is already in a, insert it to the right of the rightmost x. + + Optional args lo (default 0) and hi (default a.length) bound the slice + of a to be searched. + */ - f = d[i - 1]; - g = Math.sqrt(h); - if (f > 0) { - g = -g; - } - e[i] = scale * g; - h = h - f * g; - d[i - 1] = f - g; - for (j = 0; j < i; j++) { - e[j] = 0; - } + insort = function insort(a, x, lo, hi, cmp) { + var mid; - for (j = 0; j < i; j++) { - f = d[j]; - V[j][i] = f; - g = e[j] + V[j][j] * f; - for (k = j + 1; k <= i - 1; k++) { - g += V[k][j] * d[k]; - e[k] += V[k][j] * f; - } - e[j] = g; - } + if (lo == null) { + lo = 0; + } - f = 0; - for (j = 0; j < i; j++) { - e[j] /= h; - f += e[j] * d[j]; - } + if (cmp == null) { + cmp = defaultCmp; + } - hh = f / (h + h); - for (j = 0; j < i; j++) { - e[j] -= hh * d[j]; - } + if (lo < 0) { + throw new Error('lo must be non-negative'); + } - for (j = 0; j < i; j++) { - f = d[j]; - g = e[j]; - for (k = j; k <= i - 1; k++) { - V[k][j] -= f * e[k] + g * d[k]; - } - d[j] = V[i - 1][j]; - V[i][j] = 0; - } + if (hi == null) { + hi = a.length; } - d[i] = h; - } - for (i = 0; i < n - 1; i++) { - V[n - 1][i] = V[i][i]; - V[i][i] = 1; - h = d[i + 1]; - if (h !== 0) { - for (k = 0; k <= i; k++) { - d[k] = V[k][i + 1] / h; - } + while (lo < hi) { + mid = floor((lo + hi) / 2); - for (j = 0; j <= i; j++) { - g = 0; - for (k = 0; k <= i; k++) { - g += V[k][i + 1] * V[k][j]; - } - for (k = 0; k <= i; k++) { - V[k][j] -= g * d[k]; - } + if (cmp(x, a[mid]) < 0) { + hi = mid; + } else { + lo = mid + 1; } } - for (k = 0; k <= i; k++) { - V[k][i + 1] = 0; + return [].splice.apply(a, [lo, lo - lo].concat(x)), x; + }; + /* + Push item onto heap, maintaining the heap invariant. + */ + + + heappush = function heappush(array, item, cmp) { + if (cmp == null) { + cmp = defaultCmp; } - } - for (j = 0; j < n; j++) { - d[j] = V[n - 1][j]; - V[n - 1][j] = 0; - } + array.push(item); + return _siftdown(array, 0, array.length - 1, cmp); + }; + /* + Pop the smallest item off the heap, maintaining the heap invariant. + */ - V[n - 1][n - 1] = 1; - e[0] = 0; -} -function tql2(n, e, d, V) { - var g, h, i, j, k, l, m, p, r, dl1, c, c2, c3, el1, s, s2, iter; + heappop = function heappop(array, cmp) { + var lastelt, returnitem; - for (i = 1; i < n; i++) { - e[i - 1] = e[i]; - } + if (cmp == null) { + cmp = defaultCmp; + } - e[n - 1] = 0; + lastelt = array.pop(); - var f = 0; - var tst1 = 0; - var eps = Number.EPSILON; + if (array.length) { + returnitem = array[0]; + array[0] = lastelt; - for (l = 0; l < n; l++) { - tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l])); - m = l; - while (m < n) { - if (Math.abs(e[m]) <= eps * tst1) { - break; - } - m++; + _siftup(array, 0, cmp); + } else { + returnitem = lastelt; } - if (m > l) { - iter = 0; - do { - iter = iter + 1; + return returnitem; + }; + /* + Pop and return the current smallest value, and add the new item. + + This is more efficient than heappop() followed by heappush(), and can be + more appropriate when using a fixed size heap. Note that the value + returned may be larger than item! That constrains reasonable use of + this routine unless written as part of a conditional replacement: + if item > array[0] + item = heapreplace(array, item) + */ - g = d[l]; - p = (d[l + 1] - g) / (2 * e[l]); - r = (0, _util.hypotenuse)(p, 1); - if (p < 0) { - r = -r; - } - d[l] = e[l] / (p + r); - d[l + 1] = e[l] * (p + r); - dl1 = d[l + 1]; - h = g - d[l]; - for (i = l + 2; i < n; i++) { - d[i] -= h; - } + heapreplace = function heapreplace(array, item, cmp) { + var returnitem; - f = f + h; + if (cmp == null) { + cmp = defaultCmp; + } - p = d[m]; - c = 1; - c2 = c; - c3 = c; - el1 = e[l + 1]; - s = 0; - s2 = 0; - for (i = m - 1; i >= l; i--) { - c3 = c2; - c2 = c; - s2 = s; - g = c * e[i]; - h = c * p; - r = (0, _util.hypotenuse)(p, e[i]); - e[i + 1] = s * r; - s = e[i] / r; - c = p / r; - p = c * d[i] - s * g; - d[i + 1] = h + s * (c * g + s * d[i]); + returnitem = array[0]; + array[0] = item; - for (k = 0; k < n; k++) { - h = V[k][i + 1]; - V[k][i + 1] = s * V[k][i] + c * h; - V[k][i] = c * V[k][i] - s * h; - } - } + _siftup(array, 0, cmp); - p = -s * s2 * c3 * el1 * e[l] / dl1; - e[l] = s * p; - d[l] = c * p; - } while (Math.abs(e[l]) > eps * tst1); - } - d[l] = d[l] + f; - e[l] = 0; - } + return returnitem; + }; + /* + Fast version of a heappush followed by a heappop. + */ - for (i = 0; i < n - 1; i++) { - k = i; - p = d[i]; - for (j = i + 1; j < n; j++) { - if (d[j] < p) { - k = j; - p = d[j]; - } - } - if (k !== i) { - d[k] = d[i]; - d[i] = p; - for (j = 0; j < n; j++) { - p = V[j][i]; - V[j][i] = V[j][k]; - V[j][k] = p; - } + heappushpop = function heappushpop(array, item, cmp) { + var _ref; + + if (cmp == null) { + cmp = defaultCmp; } - } -} -function orthes(n, H, ort, V) { - var low = 0; - var high = n - 1; - var f, g, h, i, j, m; - var scale; + if (array.length && cmp(array[0], item) < 0) { + _ref = [array[0], item], item = _ref[0], array[0] = _ref[1]; - for (m = low + 1; m <= high - 1; m++) { - scale = 0; - for (i = m; i <= high; i++) { - scale = scale + Math.abs(H[i][m - 1]); + _siftup(array, 0, cmp); } - if (scale !== 0) { - h = 0; - for (i = high; i >= m; i--) { - ort[i] = H[i][m - 1] / scale; - h += ort[i] * ort[i]; - } + return item; + }; + /* + Transform list into a heap, in-place, in O(array.length) time. + */ - g = Math.sqrt(h); - if (ort[m] > 0) { - g = -g; - } - h = h - ort[m] * g; - ort[m] = ort[m] - g; + heapify = function heapify(array, cmp) { + var i, _i, _j, _len, _ref, _ref1, _results, _results1; - for (j = m; j < n; j++) { - f = 0; - for (i = high; i >= m; i--) { - f += ort[i] * H[i][j]; - } + if (cmp == null) { + cmp = defaultCmp; + } - f = f / h; - for (i = m; i <= high; i++) { - H[i][j] -= f * ort[i]; - } + _ref1 = function () { + _results1 = []; + + for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--) { + _results1.push(_j); } - for (i = 0; i <= high; i++) { - f = 0; - for (j = high; j >= m; j--) { - f += ort[j] * H[i][j]; - } + return _results1; + }.apply(this).reverse(); - f = f / h; - for (j = m; j <= high; j++) { - H[i][j] -= f * ort[j]; - } - } + _results = []; - ort[m] = scale * ort[m]; - H[m][m - 1] = scale * g; - } - } + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + i = _ref1[_i]; - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - V[i][j] = i === j ? 1 : 0; + _results.push(_siftup(array, i, cmp)); } - } - for (m = high - 1; m >= low + 1; m--) { - if (H[m][m - 1] !== 0) { - for (i = m + 1; i <= high; i++) { - ort[i] = H[i][m - 1]; - } + return _results; + }; + /* + Update the position of the given item in the heap. + This function should be called every time the item is being modified. + */ - for (j = m; j <= high; j++) { - g = 0; - for (i = m; i <= high; i++) { - g += ort[i] * V[i][j]; - } - g = g / ort[m] / H[m][m - 1]; - for (i = m; i <= high; i++) { - V[i][j] += g * ort[i]; - } - } + updateItem = function updateItem(array, item, cmp) { + var pos; + + if (cmp == null) { + cmp = defaultCmp; } - } -} -function hqr2(nn, e, d, V, H) { - var n = nn - 1; - var low = 0; - var high = nn - 1; - var eps = Number.EPSILON; - var exshift = 0; - var norm = 0; - var p = 0; - var q = 0; - var r = 0; - var s = 0; - var z = 0; - var iter = 0; - var i, j, k, l, m, t, w, x, y; - var ra, sa, vr, vi; - var notlast, cdivres; + pos = array.indexOf(item); - for (i = 0; i < nn; i++) { - if (i < low || i > high) { - d[i] = H[i][i]; - e[i] = 0; + if (pos === -1) { + return; } - for (j = Math.max(i - 1, 0); j < nn; j++) { - norm = norm + Math.abs(H[i][j]); - } - } + _siftdown(array, 0, pos, cmp); - while (n >= low) { - l = n; - while (l > low) { - s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]); - if (s === 0) { - s = norm; - } - if (Math.abs(H[l][l - 1]) < eps * s) { - break; - } - l--; - } + return _siftup(array, pos, cmp); + }; + /* + Find the n largest elements in a dataset. + */ - if (l === n) { - H[n][n] = H[n][n] + exshift; - d[n] = H[n][n]; - e[n] = 0; - n--; - iter = 0; - } else if (l === n - 1) { - w = H[n][n - 1] * H[n - 1][n]; - p = (H[n - 1][n - 1] - H[n][n]) / 2; - q = p * p + w; - z = Math.sqrt(Math.abs(q)); - H[n][n] = H[n][n] + exshift; - H[n - 1][n - 1] = H[n - 1][n - 1] + exshift; - x = H[n][n]; - if (q >= 0) { - z = p >= 0 ? p + z : p - z; - d[n - 1] = x + z; - d[n] = d[n - 1]; - if (z !== 0) { - d[n] = x - w / z; - } - e[n - 1] = 0; - e[n] = 0; - x = H[n][n - 1]; - s = Math.abs(x) + Math.abs(z); - p = x / s; - q = z / s; - r = Math.sqrt(p * p + q * q); - p = p / r; - q = q / r; + nlargest = function nlargest(array, n, cmp) { + var elem, result, _i, _len, _ref; - for (j = n - 1; j < nn; j++) { - z = H[n - 1][j]; - H[n - 1][j] = q * z + p * H[n][j]; - H[n][j] = q * H[n][j] - p * z; - } + if (cmp == null) { + cmp = defaultCmp; + } - for (i = 0; i <= n; i++) { - z = H[i][n - 1]; - H[i][n - 1] = q * z + p * H[i][n]; - H[i][n] = q * H[i][n] - p * z; - } + result = array.slice(0, n); - for (i = low; i <= high; i++) { - z = V[i][n - 1]; - V[i][n - 1] = q * z + p * V[i][n]; - V[i][n] = q * V[i][n] - p * z; - } - } else { - d[n - 1] = x + p; - d[n] = x + p; - e[n - 1] = z; - e[n] = -z; - } + if (!result.length) { + return result; + } - n = n - 2; - iter = 0; - } else { - x = H[n][n]; - y = 0; - w = 0; - if (l < n) { - y = H[n - 1][n - 1]; - w = H[n][n - 1] * H[n - 1][n]; - } + heapify(result, cmp); + _ref = array.slice(n); - if (iter === 10) { - exshift += x; - for (i = low; i <= n; i++) { - H[i][i] -= x; - } - s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]); - x = y = 0.75 * s; - w = -0.4375 * s * s; - } + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + elem = _ref[_i]; + heappushpop(result, elem, cmp); + } - if (iter === 30) { - s = (y - x) / 2; - s = s * s + w; - if (s > 0) { - s = Math.sqrt(s); - if (y < x) { - s = -s; - } - s = x - w / ((y - x) / 2 + s); - for (i = low; i <= n; i++) { - H[i][i] -= s; - } - exshift += s; - x = y = w = 0.964; - } - } + return result.sort(cmp).reverse(); + }; + /* + Find the n smallest elements in a dataset. + */ - iter = iter + 1; - m = n - 2; - while (m >= l) { - z = H[m][m]; - r = x - z; - s = y - z; - p = (r * s - w) / H[m + 1][m] + H[m][m + 1]; - q = H[m + 1][m + 1] - z - r - s; - r = H[m + 2][m + 1]; - s = Math.abs(p) + Math.abs(q) + Math.abs(r); - p = p / s; - q = q / s; - r = r / s; - if (m === l) { - break; - } - if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) { - break; - } - m--; - } + nsmallest = function nsmallest(array, n, cmp) { + var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results; + + if (cmp == null) { + cmp = defaultCmp; + } - for (i = m + 2; i <= n; i++) { - H[i][i - 2] = 0; - if (i > m + 2) { - H[i][i - 3] = 0; - } + if (n * 10 <= array.length) { + result = array.slice(0, n).sort(cmp); + + if (!result.length) { + return result; } - for (k = m; k <= n - 1; k++) { - notlast = k !== n - 1; - if (k !== m) { - p = H[k][k - 1]; - q = H[k + 1][k - 1]; - r = notlast ? H[k + 2][k - 1] : 0; - x = Math.abs(p) + Math.abs(q) + Math.abs(r); - if (x !== 0) { - p = p / x; - q = q / x; - r = r / x; - } - } + los = result[result.length - 1]; + _ref = array.slice(n); - if (x === 0) { - break; - } + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + elem = _ref[_i]; - s = Math.sqrt(p * p + q * q + r * r); - if (p < 0) { - s = -s; + if (cmp(elem, los) < 0) { + insort(result, elem, 0, null, cmp); + result.pop(); + los = result[result.length - 1]; } + } - if (s !== 0) { - if (k !== m) { - H[k][k - 1] = -s * x; - } else if (l !== m) { - H[k][k - 1] = -H[k][k - 1]; - } + return result; + } - p = p + s; - x = p / s; - y = q / s; - z = r / s; - q = q / p; - r = r / p; + heapify(array, cmp); + _results = []; - for (j = k; j < nn; j++) { - p = H[k][j] + q * H[k + 1][j]; - if (notlast) { - p = p + r * H[k + 2][j]; - H[k + 2][j] = H[k + 2][j] - p * z; - } + for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) { + _results.push(heappop(array, cmp)); + } - H[k][j] = H[k][j] - p * x; - H[k + 1][j] = H[k + 1][j] - p * y; - } + return _results; + }; - for (i = 0; i <= Math.min(n, k + 3); i++) { - p = x * H[i][k] + y * H[i][k + 1]; - if (notlast) { - p = p + z * H[i][k + 2]; - H[i][k + 2] = H[i][k + 2] - p * r; - } + _siftdown = function _siftdown(array, startpos, pos, cmp) { + var newitem, parent, parentpos; - H[i][k] = H[i][k] - p; - H[i][k + 1] = H[i][k + 1] - p * q; - } + if (cmp == null) { + cmp = defaultCmp; + } - for (i = low; i <= high; i++) { - p = x * V[i][k] + y * V[i][k + 1]; - if (notlast) { - p = p + z * V[i][k + 2]; - V[i][k + 2] = V[i][k + 2] - p * r; - } + newitem = array[pos]; - V[i][k] = V[i][k] - p; - V[i][k + 1] = V[i][k + 1] - p * q; - } - } + while (pos > startpos) { + parentpos = pos - 1 >> 1; + parent = array[parentpos]; + + if (cmp(newitem, parent) < 0) { + array[pos] = parent; + pos = parentpos; + continue; } + + break; } - } - if (norm === 0) { - return; - } + return array[pos] = newitem; + }; - for (n = nn - 1; n >= 0; n--) { - p = d[n]; - q = e[n]; + _siftup = function _siftup(array, pos, cmp) { + var childpos, endpos, newitem, rightpos, startpos; - if (q === 0) { - l = n; - H[n][n] = 1; - for (i = n - 1; i >= 0; i--) { - w = H[i][i] - p; - r = 0; - for (j = l; j <= n; j++) { - r = r + H[i][j] * H[j][n]; - } + if (cmp == null) { + cmp = defaultCmp; + } - if (e[i] < 0) { - z = w; - s = r; - } else { - l = i; - if (e[i] === 0) { - H[i][n] = w !== 0 ? -r / w : -r / (eps * norm); - } else { - x = H[i][i + 1]; - y = H[i + 1][i]; - q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; - t = (x * s - z * r) / q; - H[i][n] = t; - H[i + 1][n] = Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z; - } + endpos = array.length; + startpos = pos; + newitem = array[pos]; + childpos = 2 * pos + 1; - t = Math.abs(H[i][n]); - if (eps * t * t > 1) { - for (j = i; j <= n; j++) { - H[j][n] = H[j][n] / t; - } - } - } - } - } else if (q < 0) { - l = n - 1; + while (childpos < endpos) { + rightpos = childpos + 1; - if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) { - H[n - 1][n - 1] = q / H[n][n - 1]; - H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1]; - } else { - cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q); - H[n - 1][n - 1] = cdivres[0]; - H[n - 1][n] = cdivres[1]; + if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) { + childpos = rightpos; } - H[n][n - 1] = 0; - H[n][n] = 1; - for (i = n - 2; i >= 0; i--) { - ra = 0; - sa = 0; - for (j = l; j <= n; j++) { - ra = ra + H[i][j] * H[j][n - 1]; - sa = sa + H[i][j] * H[j][n]; - } + array[pos] = array[childpos]; + pos = childpos; + childpos = 2 * pos + 1; + } - w = H[i][i] - p; + array[pos] = newitem; + return _siftdown(array, startpos, pos, cmp); + }; - if (e[i] < 0) { - z = w; - r = ra; - s = sa; - } else { - l = i; - if (e[i] === 0) { - cdivres = cdiv(-ra, -sa, w, q); - H[i][n - 1] = cdivres[0]; - H[i][n] = cdivres[1]; - } else { - x = H[i][i + 1]; - y = H[i + 1][i]; - vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; - vi = (d[i] - p) * 2 * q; - if (vr === 0 && vi === 0) { - vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z)); - } - cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); - H[i][n - 1] = cdivres[0]; - H[i][n] = cdivres[1]; - if (Math.abs(x) > Math.abs(z) + Math.abs(q)) { - H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x; - H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x; - } else { - cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q); - H[i + 1][n - 1] = cdivres[0]; - H[i + 1][n] = cdivres[1]; - } - } + Heap = function () { + Heap.push = heappush; + Heap.pop = heappop; + Heap.replace = heapreplace; + Heap.pushpop = heappushpop; + Heap.heapify = heapify; + Heap.updateItem = updateItem; + Heap.nlargest = nlargest; + Heap.nsmallest = nsmallest; - t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n])); - if (eps * t * t > 1) { - for (j = i; j <= n; j++) { - H[j][n - 1] = H[j][n - 1] / t; - H[j][n] = H[j][n] / t; - } - } - } - } + function Heap(cmp) { + this.cmp = cmp != null ? cmp : defaultCmp; + this.nodes = []; } - } - for (i = 0; i < nn; i++) { - if (i < low || i > high) { - for (j = i; j < nn; j++) { - V[i][j] = H[i][j]; - } - } - } + Heap.prototype.push = function (x) { + return heappush(this.nodes, x, this.cmp); + }; + + Heap.prototype.pop = function () { + return heappop(this.nodes, this.cmp); + }; + + Heap.prototype.peek = function () { + return this.nodes[0]; + }; + + Heap.prototype.contains = function (x) { + return this.nodes.indexOf(x) !== -1; + }; - for (j = nn - 1; j >= low; j--) { - for (i = low; i <= high; i++) { - z = 0; - for (k = low; k <= Math.min(j, high); k++) { - z = z + V[i][k] * H[k][j]; - } - V[i][j] = z; - } - } -} + Heap.prototype.replace = function (x) { + return heapreplace(this.nodes, x, this.cmp); + }; -function cdiv(xr, xi, yr, yi) { - var r, d; - if (Math.abs(yr) > Math.abs(yi)) { - r = yi / yr; - d = yr + r * yi; - return [(xr + r * xi) / d, (xi - r * xr) / d]; - } else { - r = yr / yi; - d = yi + r * yr; - return [(r * xr + xi) / d, (r * xi - xr) / d]; - } -} + Heap.prototype.pushpop = function (x) { + return heappushpop(this.nodes, x, this.cmp); + }; -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { + Heap.prototype.heapify = function () { + return heapify(this.nodes, this.cmp); + }; -"use strict"; + Heap.prototype.updateItem = function (x) { + return updateItem(this.nodes, x, this.cmp); + }; + Heap.prototype.clear = function () { + return this.nodes = []; + }; -Object.defineProperty(exports, "__esModule", { - value: true -}); + Heap.prototype.empty = function () { + return this.nodes.length === 0; + }; -var _index = __webpack_require__(0); + Heap.prototype.size = function () { + return this.nodes.length; + }; -/** - * @class CholeskyDecomposition - * @link https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs - * @param {Matrix} value - */ -class CholeskyDecomposition { - constructor(value) { - value = _index.WrapperMatrix2D.checkMatrix(value); - if (!value.isSymmetric()) { - throw new Error('Matrix is not symmetric'); - } + Heap.prototype.clone = function () { + var heap; + heap = new Heap(); + heap.nodes = this.nodes.slice(0); + return heap; + }; - var a = value; - var dimension = a.rows; - var l = new _index.Matrix(dimension, dimension); - var positiveDefinite = true; - var i, j, k; + Heap.prototype.toArray = function () { + return this.nodes.slice(0); + }; - for (j = 0; j < dimension; j++) { - var Lrowj = l[j]; - var d = 0; - for (k = 0; k < j; k++) { - var Lrowk = l[k]; - var s = 0; - for (i = 0; i < k; i++) { - s += Lrowk[i] * Lrowj[i]; - } - Lrowj[k] = s = (a.get(j, k) - s) / l[k][k]; - d = d + s * s; - } + Heap.prototype.insert = Heap.prototype.push; + Heap.prototype.top = Heap.prototype.peek; + Heap.prototype.front = Heap.prototype.peek; + Heap.prototype.has = Heap.prototype.contains; + Heap.prototype.copy = Heap.prototype.clone; + return Heap; + }(); - d = a.get(j, j) - d; + (function (root, factory) { + if (true) { + return !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} + })(this, function () { + return Heap; + }); +}).call(this); - positiveDefinite &= d > 0; - l[j][j] = Math.sqrt(Math.max(d, 0)); - for (k = j + 1; k < dimension; k++) { - l[j][k] = 0; - } - } +/***/ }), +/* 49 */ +/***/ (function(module, exports, __webpack_require__) { - if (!positiveDefinite) { - throw new Error('Matrix is not positive definite'); - } +/* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(obj) { + var keys = Object.keys(obj); + var descriptors = {}; - this.L = l; + for (var i = 0; i < keys.length; i++) { + descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); } - /** - * - * @param {Matrix} value - * @return {Matrix} - */ - solve(value) { - value = _index.WrapperMatrix2D.checkMatrix(value); + return descriptors; +}; - var l = this.L; - var dimension = l.rows; +var formatRegExp = /%[sdj%]/g; - if (value.rows !== dimension) { - throw new Error('Matrix dimensions do not match'); +exports.format = function (f) { + if (!isString(f)) { + var objects = []; + + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); } - var count = value.columns; - var B = value.clone(); - var i, j, k; + return objects.join(' '); + } - for (k = 0; k < dimension; k++) { - for (j = 0; j < count; j++) { - for (i = 0; i < k; i++) { - B[k][j] -= B[i][j] * l[k][i]; - } - B[k][j] /= l[k][k]; - } - } + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function (x) { + if (x === '%%') return '%'; + if (i >= len) return x; - for (k = dimension - 1; k >= 0; k--) { - for (j = 0; j < count; j++) { - for (i = k + 1; i < dimension; i++) { - B[k][j] -= B[i][j] * l[i][k]; + switch (x) { + case '%s': + return String(args[i++]); + + case '%d': + return Number(args[i++]); + + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; } - B[k][j] /= l[k][k]; - } + + default: + return x; } + }); - return B; + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } } - /** - * - * @return {Matrix} - */ - get lowerTriangularMatrix() { - return this.L; - } -} -exports.default = CholeskyDecomposition; + return str; +}; // Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. -/***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +exports.deprecate = function (fn, msg) { + if (typeof process !== 'undefined' && process.noDeprecation === true) { + return fn; + } // Allow for deprecating things in the process of starting up. -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.toDiscreteDistribution = toDiscreteDistribution; -exports.giniImpurity = giniImpurity; -exports.getNumberOfClasses = getNumberOfClasses; -exports.giniGain = giniGain; -exports.squaredError = squaredError; -exports.regressionError = regressionError; -exports.matrixSplitter = matrixSplitter; -exports.mean = mean; -exports.zip = zip; + if (typeof process === 'undefined') { + return function () { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + var warned = false; + + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + + warned = true; + } -var _mlMatrix = __webpack_require__(0); + return fn.apply(this, arguments); + } -var _mlMatrix2 = _interopRequireDefault(_mlMatrix); + return deprecated; +}; -var _mlArrayMean = __webpack_require__(8); +var debugs = {}; +var debugEnviron; -var _mlArrayMean2 = _interopRequireDefault(_mlArrayMean); +exports.debuglog = function (set) { + if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; -/** - * @private - * return an array of probabilities of each class - * @param {Array} array - contains the classes - * @param {number} numberOfClasses - * @return {Matrix} - rowVector of probabilities. - */ -function toDiscreteDistribution(array, numberOfClasses) { - var counts = new Array(numberOfClasses).fill(0); - for (var i = 0; i < array.length; ++i) { - counts[array[i]] += 1 / array.length; + debugs[set] = function () { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function () {}; } + } - return _mlMatrix2.default.rowVector(counts); -} - + return debugs[set]; +}; /** - * @private - * Retrieves the impurity of array of predictions - * @param {Array} array - predictions. - * @return {number} Gini impurity + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. */ -function giniImpurity(array) { - if (array.length === 0) { - return 0; - } - - var probabilities = toDiscreteDistribution(array, getNumberOfClasses(array))[0]; - var sum = 0.0; - for (var i = 0; i < probabilities.length; ++i) { - sum += probabilities[i] * probabilities[i]; - } +/* legacy: obj, showHidden, depth, colors*/ - return 1 - sum; -} -/** - * @private - * Return the number of classes given the array of predictions. - * @param {Array} array - predictions. - * @return {number} Number of classes. - */ -function getNumberOfClasses(array) { - return array.filter(function (val, i, arr) { - return arr.indexOf(val) === i; - }).length; -} +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; // legacy... -/** - * @private - * Calculates the Gini Gain of an array of predictions and those predictions splitted by a feature. - * @para {Array} array - Predictions - * @param {object} splitted - Object with elements "greater" and "lesser" that contains an array of predictions splitted. - * @return {number} - Gini Gain. - */ + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; -function giniGain(array, splitted) { - var splitsImpurity = 0.0; - var splits = ['greater', 'lesser']; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } // set default options - for (var i = 0; i < splits.length; ++i) { - var currentSplit = splitted[splits[i]]; - splitsImpurity += giniImpurity(currentSplit) * currentSplit.length / array.length; - } - return giniImpurity(array) - splitsImpurity; + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); } -/** - * @private - * Calculates the squared error of a predictions values. - * @param {Array} array - predictions values - * @return {number} squared error. - */ -function squaredError(array) { - var l = array.length; - - var m = (0, _mlArrayMean2.default)(array); - var squaredError = 0.0; +exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - for (var i = 0; i < l; ++i) { - var currentElement = array[i]; - squaredError += (currentElement - m) * (currentElement - m); - } +inspect.colors = { + 'bold': [1, 22], + 'italic': [3, 23], + 'underline': [4, 24], + 'inverse': [7, 27], + 'white': [37, 39], + 'grey': [90, 39], + 'black': [30, 39], + 'blue': [34, 39], + 'cyan': [36, 39], + 'green': [32, 39], + 'magenta': [35, 39], + 'red': [31, 39], + 'yellow': [33, 39] +}; // Don't use 'blue' not visible on cmd.exe - return squaredError; -} +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; -/** - * @private - * Calculates the sum of squared error of the two arrays that contains the splitted values. - * @param {Array} array - this argument is no necessary but is used to fit with the main interface. - * @param {object} splitted - Object with elements "greater" and "lesser" that contains an array of predictions splitted. - * @return {number} - sum of squared errors. - */ -function regressionError(array, splitted) { - var error = 0.0; - var splits = ['greater', 'lesser']; +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; - for (var i = 0; i < splits.length; ++i) { - var currentSplit = splitted[splits[i]]; - error += squaredError(currentSplit); - } - return error; + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } } -/** - * @private - * Split the training set and values from a given column of the training set if is less than a value - * @param {Matrix} X - Training set. - * @param {Array} y - Training values. - * @param {number} column - Column to split. - * @param {number} value - value to split the Training set and values. - * @return {object} - Object that contains the splitted values. - */ -function matrixSplitter(X, y, column, value) { - var lesserX = []; - var greaterX = []; - var lesserY = []; - var greaterY = []; - - for (var i = 0; i < X.rows; ++i) { - if (X[i][column] < value) { - lesserX.push(X[i]); - lesserY.push(y[i]); - } else { - greaterX.push(X[i]); - greaterY.push(y[i]); - } - } - - return { - greaterX: greaterX, - greaterY: greaterY, - lesserX: lesserX, - lesserY: lesserY - }; +function stylizeNoColor(str, styleType) { + return str; } -/** - * @private - * Calculates the mean between two values - * @param {number} a - * @param {number} b - * @return {number} - */ -function mean(a, b) { - return (a + b) / 2; +function arrayToHash(array) { + var hash = {}; + array.forEach(function (val, idx) { + hash[val] = true; + }); + return hash; } -/** - * @private - * Returns a list of tuples that contains the i-th element of each array. - * @param {Array} a - * @param {Array} b - * @return {Array} list of tuples. - */ -function zip(a, b) { - if (a.length !== b.length) { - throw new TypeError('Error on zip: the size of a: ' + a.length + ' is different from b: ' + b.length); - } +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); - var ret = new Array(a.length); - for (var i = 0; i < a.length; ++i) { - ret[i] = [a[i], b[i]]; + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); } return ret; -} - -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { + } // Primitive types cannot have properties -"use strict"; + var primitive = formatPrimitive(ctx, value); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.DecisionTreeRegression = undefined; + if (primitive) { + return primitive; + } // Look up the keys of the object. -var _mlMatrix = __webpack_require__(0); -var _mlMatrix2 = _interopRequireDefault(_mlMatrix); + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); -var _TreeNode = __webpack_require__(24); + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx -var _TreeNode2 = _interopRequireDefault(_TreeNode); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } // Some type of object without properties can be shortcutted. -var defaultOptions = { - gainFunction: 'regression', - splitFunction: 'mean', - minNumSamples: 3, - maxDepth: Infinity -}; -class DecisionTreeRegression { + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } - /** - * Create new Decision Tree Regression with CART implementation with the given options. - * @param {object} options - * @param {string} [options.gainFunction="regression"] - gain function to get the best split, "regression" the only one supported. - * @param {string} [options.splitFunction="mean"] - given two integers from a split feature, get the value to split, "mean" the only one supported. - * @param {number} [options.minNumSamples=3] - minimum number of samples to create a leaf node to decide a class. - * @param {number} [options.maxDepth=Infinity] - Max depth of the tree. - * @param {object} model - for load purposes. - */ - constructor(options, model) { - if (options === true) { - this.options = model.options; - this.root = new _TreeNode2.default(model.options); - this.root.setNodeParameters(model.root); - } else { - this.options = Object.assign({}, defaultOptions, options); - this.options.kind = 'regression'; - } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } - /** - * Train the decision tree with the given training set and values. - * @param {Matrix|MatrixTransposeView|Array} trainingSet - * @param {Array} trainingValues - */ - train(trainingSet, trainingValues) { - this.root = new _TreeNode2.default(this.options); + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } - if (trainingSet[0].length === undefined) trainingSet = _mlMatrix2.default.columnVector(trainingSet); - trainingSet = _mlMatrix2.default.checkMatrix(trainingSet); - this.root.train(trainingSet, trainingValues, 0); + if (isError(value)) { + return formatError(value); } + } - /** - * Predicts the values given the matrix to predict. - * @param {Matrix|MatrixTransposeView|Array} toPredict - * @return {Array} predictions - */ - predict(toPredict) { - if (toPredict[0] !== undefined && toPredict[0].length === undefined) toPredict = _mlMatrix2.default.columnVector(toPredict); - toPredict = _mlMatrix2.default.checkMatrix(toPredict); + var base = '', + array = false, + braces = ['{', '}']; // Make Array say that they are Array - var predictions = new Array(toPredict.rows); - for (var i = 0; i < toPredict.rows; ++i) { - predictions[i] = this.root.classify(toPredict.getRow(i)); - } + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } // Make functions say that they are functions - return predictions; - } - /** - * Export the current model to JSON. - * @return {object} - Current model. - */ - toJSON() { - return { - options: this.options, - root: this.root, - name: 'DTRegression' - }; - } + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } // Make RegExps say that they are RegExps - /** - * Load a Decision tree regression with the given model. - * @param {object} model - * @return {DecisionTreeRegression} - */ - static load(model) { - if (model.name !== 'DTRegression') { - throw new RangeError('Invalid model:' + model.name); - } - return new DecisionTreeRegression(true, model); - } -} -exports.DecisionTreeRegression = DecisionTreeRegression; + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } // Make dates with properties first say the date -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } // Make error with message first say the error + + + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function (key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + ctx.seen.pop(); + return reduceToSingleString(output, base, braces); +} -var _RandomForestClassifier = __webpack_require__(76); +function formatPrimitive(ctx, value) { + if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); -Object.defineProperty(exports, 'RandomForestClassifier', { - enumerable: true, - get: function get() { - return _RandomForestClassifier.RandomForestClassifier; + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); } -}); - -var _RandomForestRegression = __webpack_require__(79); -Object.defineProperty(exports, 'RandomForestRegression', { - enumerable: true, - get: function get() { - return _RandomForestRegression.RandomForestRegression; - } -}); + if (isNumber(value)) return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. -/***/ }), -/* 76 */ -/***/ (function(module, exports, __webpack_require__) { + if (isNull(value)) return ctx.stylize('null', 'null'); +} -"use strict"; +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RandomForestClassifier = undefined; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); + } else { + output.push(''); + } + } -var _RandomForestBase = __webpack_require__(25); + keys.forEach(function (key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); + } + }); + return output; +} -var defaultOptions = { - maxFeatures: 1.0, - replacement: true, - nEstimators: 10, - seed: 42, - useSampleBagging: false -}; +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { + value: value[key] + }; -/** - * @class RandomForestClassifier - * @augments RandomForestBase - */ -class RandomForestClassifier extends _RandomForestBase.RandomForestBase { - /** - * Create a new base random forest for a classifier or regression model. - * @constructor - * @param {object} options - * @param {number} [options.maxFeatures=1.0] - the number of features used on each estimator. - * * if is an integer it selects maxFeatures elements over the sample features. - * * if is a float between (0, 1), it takes the percentage of features. - * @param {boolean} [options.replacement=true] - use replacement over the sample features. - * @param {number} [options.seed=42] - seed for feature and samples selection, must be a 32-bit integer. - * @param {number} [options.nEstimators=10] - number of estimator to use. - * @param {object} [options.treeOptions={}] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/} - * @param {boolean} [options.useSampleBagging=false] - use bagging over training samples. - * @param {object} model - for load purposes. - */ - constructor(options, model) { - if (options === true) { - super(true, model.baseModel); + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); } else { - options = Object.assign({}, defaultOptions, options); - options.isClassifier = true; - super(options); + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); } } - /** - * retrieve the prediction given the selection method. - * @param {Array} values - predictions of the estimators. - * @return {number} prediction - */ - selection(values) { - return mode(values); + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; } - /** - * Export the current model to JSON. - * @return {object} - Current model. - */ - toJSON() { - var baseModel = super.toJSON(); - return { - baseModel: baseModel, - name: 'RFClassifier' - }; + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function (line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function (line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } } - /** - * Load a Decision tree classifier with the given model. - * @param {object} model - * @return {RandomForestClassifier} - */ - static load(model) { - if (model.name !== 'RFClassifier') { - throw new RangeError(`Invalid model: ${model.name}`); + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; } - return new RandomForestClassifier(true, model); - } -} + name = JSON.stringify('' + key); -exports.RandomForestClassifier = RandomForestClassifier; /** - * Return the most repeated element on the array. - * @param {Array} arr - * @return {number} mode - */ + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } -function mode(arr) { - return arr.sort((a, b) => arr.filter(v => v === a).length - arr.filter(v => v === b).length).pop(); + return name + ': ' + str; } -/***/ }), -/* 77 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function (prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + if (length > 60) { + return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.checkFloat = checkFloat; -exports.examplesBaggingWithReplacement = examplesBaggingWithReplacement; -exports.featureBagging = featureBagging; + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} // NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. -var _randomJs = __webpack_require__(78); -var _randomJs2 = _interopRequireDefault(_randomJs); +function isArray(ar) { + return Array.isArray(ar); +} -var _mlMatrix = __webpack_require__(0); +exports.isArray = isArray; -var _mlMatrix2 = _interopRequireDefault(_mlMatrix); +function isBoolean(arg) { + return typeof arg === 'boolean'; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +exports.isBoolean = isBoolean; -function checkFloat(n) { - return n > 0.0 && n <= 1.0; +function isNull(arg) { + return arg === null; } -/** - * Select n with replacement elements on the training set and values, where n is the size of the training set. - * @ignore - * @param {Matrix} trainingSet - * @param {Array} trainingValue - * @param {number} seed - seed for the random selection, must be a 32-bit integer. - * @return {object} with new X and y. - */ -function examplesBaggingWithReplacement(trainingSet, trainingValue, seed) { - var engine = _randomJs2.default.engines.mt19937(); - var distribution = _randomJs2.default.integer(0, trainingSet.rows - 1); - if (seed === undefined) { - engine = engine.autoSeed(); - } else if (Number.isInteger(seed)) { - engine = engine.seed(seed); - } else { - throw new RangeError(`Expected seed must be undefined or integer not ${seed}`); - } +exports.isNull = isNull; - var Xr = new Array(trainingSet.rows); - var yr = new Array(trainingSet.rows); +function isNullOrUndefined(arg) { + return arg == null; +} - for (var i = 0; i < trainingSet.rows; ++i) { - var index = distribution(engine); - Xr[i] = trainingSet[index]; - yr[i] = trainingValue[index]; - } +exports.isNullOrUndefined = isNullOrUndefined; - return { - X: new _mlMatrix2.default(Xr), - y: yr - }; +function isNumber(arg) { + return typeof arg === 'number'; } -/** - * selects n features from the training set with or without replacement, returns the new training set and the indexes used. - * @ignore - * @param {Matrix} trainingSet - * @param {number} n - features. - * @param {boolean} replacement - * @param {number} seed - seed for the random selection, must be a 32-bit integer. - * @return {object} - */ -function featureBagging(trainingSet, n, replacement, seed) { - if (trainingSet.columns < n) { - throw new RangeError('N should be less or equal to the number of columns of X'); - } - - var distribution = _randomJs2.default.integer(0, trainingSet.columns - 1); - var engine = _randomJs2.default.engines.mt19937(); - if (seed === undefined) { - engine = engine.autoSeed(); - } else if (Number.isInteger(seed)) { - engine = engine.seed(seed); - } else { - throw new RangeError(`Expected seed must be undefined or integer not ${seed}`); - } +exports.isNumber = isNumber; - var toRet = new _mlMatrix2.default(trainingSet.rows, n); +function isString(arg) { + return typeof arg === 'string'; +} - if (replacement) { - var usedIndex = new Array(n); - for (var i = 0; i < n; ++i) { - var index = distribution(engine); - usedIndex[i] = index; - toRet.setColumn(i, trainingSet.getColumn(index)); - } - } else { - usedIndex = new Set(); - index = distribution(engine); - for (i = 0; i < n; ++i) { - while (usedIndex.has(index)) { - index = distribution(engine); - } - toRet.setColumn(i, trainingSet.getColumn(index)); - usedIndex.add(index); - } - usedIndex = Array.from(usedIndex); - } +exports.isString = isString; - return { - X: toRet, - usedIndex: usedIndex - }; +function isSymbol(arg) { + return typeof arg === 'symbol'; } -/***/ }), -/* 78 */ -/***/ (function(module, exports, __webpack_require__) { +exports.isSymbol = isSymbol; -"use strict"; -var __WEBPACK_AMD_DEFINE_RESULT__; +function isUndefined(arg) { + return arg === void 0; +} -/*jshint eqnull:true*/ -(function (root) { - "use strict"; +exports.isUndefined = isUndefined; - var GLOBAL_KEY = "Random"; +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} - var imul = typeof Math.imul !== "function" || Math.imul(0xffffffff, 5) !== -5 ? function (a, b) { - var ah = a >>> 16 & 0xffff; - var al = a & 0xffff; - var bh = b >>> 16 & 0xffff; - var bl = b & 0xffff; - // the shift by 0 fixes the sign on the high part - // the final |0 converts the unsigned value into a signed value - return al * bl + (ah * bl + al * bh << 16 >>> 0) | 0; - } : Math.imul; +exports.isRegExp = isRegExp; - var stringRepeat = typeof String.prototype.repeat === "function" && "x".repeat(3) === "xxx" ? function (x, y) { - return x.repeat(y); - } : function (pattern, count) { - var result = ""; - while (count > 0) { - if (count & 1) { - result += pattern; - } - count >>= 1; - pattern += pattern; - } - return result; - }; +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} - function Random(engine) { - if (!(this instanceof Random)) { - return new Random(engine); - } +exports.isObject = isObject; - if (engine == null) { - engine = Random.engines.nativeMath; - } else if (typeof engine !== "function") { - throw new TypeError("Expected engine to be a function, got " + typeof engine); - } - this.engine = engine; - } - var proto = Random.prototype; +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} - Random.engines = { - nativeMath: function nativeMath() { - return Math.random() * 0x100000000 | 0; - }, - mt19937: function (Int32Array) { - // http://en.wikipedia.org/wiki/Mersenne_twister - function refreshData(data) { - var k = 0; - var tmp = 0; - for (; (k | 0) < 227; k = k + 1 | 0) { - tmp = data[k] & 0x80000000 | data[k + 1 | 0] & 0x7fffffff; - data[k] = data[k + 397 | 0] ^ tmp >>> 1 ^ (tmp & 0x1 ? 0x9908b0df : 0); - } +exports.isDate = isDate; - for (; (k | 0) < 623; k = k + 1 | 0) { - tmp = data[k] & 0x80000000 | data[k + 1 | 0] & 0x7fffffff; - data[k] = data[k - 227 | 0] ^ tmp >>> 1 ^ (tmp & 0x1 ? 0x9908b0df : 0); - } +function isError(e) { + return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); +} - tmp = data[623] & 0x80000000 | data[0] & 0x7fffffff; - data[623] = data[396] ^ tmp >>> 1 ^ (tmp & 0x1 ? 0x9908b0df : 0); - } +exports.isError = isError; - function temper(value) { - value ^= value >>> 11; - value ^= value << 7 & 0x9d2c5680; - value ^= value << 15 & 0xefc60000; - return value ^ value >>> 18; - } +function isFunction(arg) { + return typeof arg === 'function'; +} - function seedWithArray(data, source) { - var i = 1; - var j = 0; - var sourceLength = source.length; - var k = Math.max(sourceLength, 624) | 0; - var previous = data[0] | 0; - for (; (k | 0) > 0; --k) { - data[i] = previous = (data[i] ^ imul(previous ^ previous >>> 30, 0x0019660d)) + (source[j] | 0) + (j | 0) | 0; - i = i + 1 | 0; - ++j; - if ((i | 0) > 623) { - data[0] = data[623]; - i = 1; - } - if (j >= sourceLength) { - j = 0; - } - } - for (k = 623; (k | 0) > 0; --k) { - data[i] = previous = (data[i] ^ imul(previous ^ previous >>> 30, 0x5d588b65)) - i | 0; - i = i + 1 | 0; - if ((i | 0) > 623) { - data[0] = data[623]; - i = 1; - } - } - data[0] = 0x80000000; - } +exports.isFunction = isFunction; - function mt19937() { - var data = new Int32Array(624); - var index = 0; - var uses = 0; +function isPrimitive(arg) { + return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} - function next() { - if ((index | 0) >= 624) { - refreshData(data); - index = 0; - } +exports.isPrimitive = isPrimitive; +exports.isBuffer = __webpack_require__(51); - var value = data[index]; - index = index + 1 | 0; - uses += 1; - return temper(value) | 0; - } - next.getUseCount = function () { - return uses; - }; - next.discard = function (count) { - uses += count; - if ((index | 0) >= 624) { - refreshData(data); - index = 0; - } - while (count - index > 624) { - count -= 624 - index; - refreshData(data); - index = 0; - } - index = index + count | 0; - return next; - }; - next.seed = function (initial) { - var previous = 0; - data[0] = previous = initial | 0; +function objectToString(o) { + return Object.prototype.toString.call(o); +} - for (var i = 1; i < 624; i = i + 1 | 0) { - data[i] = previous = imul(previous ^ previous >>> 30, 0x6c078965) + i | 0; - } - index = 624; - uses = 0; - return next; - }; - next.seedWithArray = function (source) { - next.seed(0x012bd6aa); - seedWithArray(data, source); - return next; - }; - next.autoSeed = function () { - return next.seedWithArray(Random.generateEntropyArray()); - }; - return next; - } +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} - return mt19937; - }(typeof Int32Array === "function" ? Int32Array : Array), - browserCrypto: typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function" && typeof Int32Array === "function" ? function () { - var data = null; - var index = 128; +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 - return function () { - if (index >= 128) { - if (data === null) { - data = new Int32Array(128); - } - crypto.getRandomValues(data); - index = 0; - } +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} // log is just a thin wrapper to console.log that prepends a timestamp - return data[index++] | 0; - }; - }() : null - }; - Random.generateEntropyArray = function () { - var array = []; - var engine = Random.engines.nativeMath; - for (var i = 0; i < 16; ++i) { - array[i] = engine() | 0; - } - array.push(new Date().getTime() | 0); - return array; - }; +exports.log = function () { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ - function returnValue(value) { - return function () { - return value; - }; + +exports.inherits = __webpack_require__(52); + +exports._extend = function (origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + var keys = Object.keys(add); + var i = keys.length; + + while (i--) { + origin[keys[i]] = add[keys[i]]; } - // [-0x80000000, 0x7fffffff] - Random.int32 = function (engine) { - return engine() | 0; - }; - proto.int32 = function () { - return Random.int32(this.engine); - }; + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} - // [0, 0xffffffff] - Random.uint32 = function (engine) { - return engine() >>> 0; - }; - proto.uint32 = function () { - return Random.uint32(this.engine); - }; +var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; - // [0, 0x1fffffffffffff] - Random.uint53 = function (engine) { - var high = engine() & 0x1fffff; - var low = engine() >>> 0; - return high * 0x100000000 + low; - }; - proto.uint53 = function () { - return Random.uint53(this.engine); - }; +exports.promisify = function promisify(original) { + if (typeof original !== 'function') throw new TypeError('The "original" argument must be of type Function'); - // [0, 0x20000000000000] - Random.uint53Full = function (engine) { - while (true) { - var high = engine() | 0; - if (high & 0x200000) { - if ((high & 0x3fffff) === 0x200000 && (engine() | 0) === 0) { - return 0x20000000000000; - } - } else { - var low = engine() >>> 0; - return (high & 0x1fffff) * 0x100000000 + low; - } + if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { + var fn = original[kCustomPromisifiedSymbol]; + + if (typeof fn !== 'function') { + throw new TypeError('The "util.promisify.custom" argument must be of type Function'); } - }; - proto.uint53Full = function () { - return Random.uint53Full(this.engine); - }; - // [-0x20000000000000, 0x1fffffffffffff] - Random.int53 = function (engine) { - var high = engine() | 0; - var low = engine() >>> 0; - return (high & 0x1fffff) * 0x100000000 + low + (high & 0x200000 ? -0x20000000000000 : 0); - }; - proto.int53 = function () { - return Random.int53(this.engine); - }; + Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, + enumerable: false, + writable: false, + configurable: true + }); + return fn; + } - // [-0x20000000000000, 0x20000000000000] - Random.int53Full = function (engine) { - while (true) { - var high = engine() | 0; - if (high & 0x400000) { - if ((high & 0x7fffff) === 0x400000 && (engine() | 0) === 0) { - return 0x20000000000000; - } + function fn() { + var promiseResolve, promiseReject; + var promise = new Promise(function (resolve, reject) { + promiseResolve = resolve; + promiseReject = reject; + }); + var args = []; + + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + + args.push(function (err, value) { + if (err) { + promiseReject(err); } else { - var low = engine() >>> 0; - return (high & 0x1fffff) * 0x100000000 + low + (high & 0x200000 ? -0x20000000000000 : 0); + promiseResolve(value); } - } - }; - proto.int53Full = function () { - return Random.int53Full(this.engine); - }; + }); - function add(generate, addend) { - if (addend === 0) { - return generate; - } else { - return function (engine) { - return generate(engine) + addend; - }; + try { + original.apply(this, args); + } catch (err) { + promiseReject(err); } + + return promise; } - Random.integer = function () { - function isPowerOfTwoMinusOne(value) { - return (value + 1 & value) === 0; - } + Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); + if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, + enumerable: false, + writable: false, + configurable: true + }); + return Object.defineProperties(fn, getOwnPropertyDescriptors(original)); +}; - function bitmask(masking) { - return function (engine) { - return engine() & masking; - }; - } +exports.promisify.custom = kCustomPromisifiedSymbol; + +function callbackifyOnRejected(reason, cb) { + // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). + // Because `null` is a special error value in callbacks which means "no error + // occurred", we error-wrap so the callback consumer can distinguish between + // "the promise rejected with null" or "the promise fulfilled with undefined". + if (!reason) { + var newReason = new Error('Promise was rejected with a falsy value'); + newReason.reason = reason; + reason = newReason; + } - function downscaleToLoopCheckedRange(range) { - var extendedRange = range + 1; - var maximum = extendedRange * Math.floor(0x100000000 / extendedRange); - return function (engine) { - var value = 0; - do { - value = engine() >>> 0; - } while (value >= maximum); - return value % extendedRange; - }; - } + return cb(reason); +} - function downscaleToRange(range) { - if (isPowerOfTwoMinusOne(range)) { - return bitmask(range); - } else { - return downscaleToLoopCheckedRange(range); - } - } +function callbackify(original) { + if (typeof original !== 'function') { + throw new TypeError('The "original" argument must be of type Function'); + } // We DO NOT return the promise as it gives the user a false sense that + // the promise is actually somehow related to the callback's execution + // and that the callback throwing will reject the promise. - function isEvenlyDivisibleByMaxInt32(value) { - return (value | 0) === 0; - } - function upscaleWithHighMasking(masking) { - return function (engine) { - var high = engine() & masking; - var low = engine() >>> 0; - return high * 0x100000000 + low; - }; - } + function callbackified() { + var args = []; - function upscaleToLoopCheckedRange(extendedRange) { - var maximum = extendedRange * Math.floor(0x20000000000000 / extendedRange); - return function (engine) { - var ret = 0; - do { - var high = engine() & 0x1fffff; - var low = engine() >>> 0; - ret = high * 0x100000000 + low; - } while (ret >= maximum); - return ret % extendedRange; - }; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); } - function upscaleWithinU53(range) { - var extendedRange = range + 1; - if (isEvenlyDivisibleByMaxInt32(extendedRange)) { - var highRange = (extendedRange / 0x100000000 | 0) - 1; - if (isPowerOfTwoMinusOne(highRange)) { - return upscaleWithHighMasking(highRange); - } - } - return upscaleToLoopCheckedRange(extendedRange); - } + var maybeCb = args.pop(); - function upscaleWithinI53AndLoopCheck(min, max) { - return function (engine) { - var ret = 0; - do { - var high = engine() | 0; - var low = engine() >>> 0; - ret = (high & 0x1fffff) * 0x100000000 + low + (high & 0x200000 ? -0x20000000000000 : 0); - } while (ret < min || ret > max); - return ret; - }; + if (typeof maybeCb !== 'function') { + throw new TypeError('The last argument must be of type Function'); } - return function (min, max) { - min = Math.floor(min); - max = Math.floor(max); - if (min < -0x20000000000000 || !isFinite(min)) { - throw new RangeError("Expected min to be at least " + -0x20000000000000); - } else if (max > 0x20000000000000 || !isFinite(max)) { - throw new RangeError("Expected max to be at most " + 0x20000000000000); - } + var self = this; - var range = max - min; - if (range <= 0 || !isFinite(range)) { - return returnValue(min); - } else if (range === 0xffffffff) { - if (min === 0) { - return Random.uint32; - } else { - return add(Random.int32, min + 0x80000000); - } - } else if (range < 0xffffffff) { - return add(downscaleToRange(range), min); - } else if (range === 0x1fffffffffffff) { - return add(Random.uint53, min); - } else if (range < 0x1fffffffffffff) { - return add(upscaleWithinU53(range), min); - } else if (max - 1 - min === 0x1fffffffffffff) { - return add(Random.uint53Full, min); - } else if (min === -0x20000000000000 && max === 0x20000000000000) { - return Random.int53Full; - } else if (min === -0x20000000000000 && max === 0x1fffffffffffff) { - return Random.int53; - } else if (min === -0x1fffffffffffff && max === 0x20000000000000) { - return add(Random.int53, 1); - } else if (max === 0x20000000000000) { - return add(upscaleWithinI53AndLoopCheck(min - 1, max - 1), 1); - } else { - return upscaleWithinI53AndLoopCheck(min, max); - } - }; - }(); - proto.integer = function (min, max) { - return Random.integer(min, max)(this.engine); - }; + var cb = function cb() { + return maybeCb.apply(self, arguments); + }; // In true node style we process the callback on `nextTick` with all the + // implications (stack, `uncaughtException`, `async_hooks`) - // [0, 1] (floating point) - Random.realZeroToOneInclusive = function (engine) { - return Random.uint53Full(engine) / 0x20000000000000; - }; - proto.realZeroToOneInclusive = function () { - return Random.realZeroToOneInclusive(this.engine); - }; - // [0, 1) (floating point) - Random.realZeroToOneExclusive = function (engine) { - return Random.uint53(engine) / 0x20000000000000; - }; - proto.realZeroToOneExclusive = function () { - return Random.realZeroToOneExclusive(this.engine); - }; + original.apply(this, args).then(function (ret) { + process.nextTick(cb, null, ret); + }, function (rej) { + process.nextTick(callbackifyOnRejected, rej, cb); + }); + } - Random.real = function () { - function multiply(generate, multiplier) { - if (multiplier === 1) { - return generate; - } else if (multiplier === 0) { - return function () { - return 0; - }; - } else { - return function (engine) { - return generate(engine) * multiplier; - }; - } - } + Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); + Object.defineProperties(callbackified, getOwnPropertyDescriptors(original)); + return callbackified; +} - return function (left, right, inclusive) { - if (!isFinite(left)) { - throw new RangeError("Expected left to be a finite number"); - } else if (!isFinite(right)) { - throw new RangeError("Expected right to be a finite number"); - } - return add(multiply(inclusive ? Random.realZeroToOneInclusive : Random.realZeroToOneExclusive, right - left), left); - }; - }(); - proto.real = function (min, max, inclusive) { - return Random.real(min, max, inclusive)(this.engine); - }; +exports.callbackify = callbackify; +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(50))) - Random.bool = function () { - function isLeastBitTrue(engine) { - return (engine() & 1) === 1; - } +/***/ }), +/* 50 */ +/***/ (function(module, exports) { - function lessThan(generate, value) { - return function (engine) { - return generate(engine) < value; - }; - } +// shim for using process in browser +var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. - function probability(percentage) { - if (percentage <= 0) { - return returnValue(false); - } else if (percentage >= 1) { - return returnValue(true); - } else { - var scaled = percentage * 0x100000000; - if (scaled % 1 === 0) { - return lessThan(Random.int32, scaled - 0x80000000 | 0); - } else { - return lessThan(Random.uint53, Math.round(percentage * 0x20000000000000)); - } - } - } +var cachedSetTimeout; +var cachedClearTimeout; - return function (numerator, denominator) { - if (denominator == null) { - if (numerator == null) { - return isLeastBitTrue; - } - return probability(numerator); - } else { - if (numerator <= 0) { - return returnValue(false); - } else if (numerator >= denominator) { - return returnValue(true); - } - return lessThan(Random.integer(0, denominator - 1), numerator); - } - }; - }(); - proto.bool = function (numerator, denominator) { - return Random.bool(numerator, denominator)(this.engine); - }; +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} - function toInteger(value) { - var number = +value; - if (number < 0) { - return Math.ceil(number); +function defaultClearTimeout() { + throw new Error('clearTimeout has not been defined'); +} + +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; } else { - return Math.floor(number); + cachedSetTimeout = defaultSetTimout; } + } catch (e) { + cachedSetTimeout = defaultSetTimout; } - function convertSliceArgument(value, length) { - if (value < 0) { - return Math.max(value + length, 0); + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; } else { - return Math.min(value, length); + cachedClearTimeout = defaultClearTimeout; } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; } - Random.pick = function (engine, array, begin, end) { - var length = array.length; - var start = begin == null ? 0 : convertSliceArgument(toInteger(begin), length); - var finish = end === void 0 ? length : convertSliceArgument(toInteger(end), length); - if (start >= finish) { - return void 0; +})(); + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } // if setTimeout wasn't available but was latter defined + + + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); } - var distribution = Random.integer(start, finish - 1); - return array[distribution(engine)]; - }; - proto.pick = function (array, begin, end) { - return Random.pick(this.engine, array, begin, end); - }; + } +} - function returnUndefined() { - return void 0; +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } // if clearTimeout wasn't available but was latter defined + + + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); } - var slice = Array.prototype.slice; - Random.picker = function (array, begin, end) { - var clone = slice.call(array, begin, end); - if (!clone.length) { - return returnUndefined; + + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); } - var distribution = Random.integer(0, clone.length - 1); - return function (engine) { - return clone[distribution(engine)]; - }; - }; + } +} - Random.shuffle = function (engine, array, downTo) { - var length = array.length; - if (length) { - if (downTo == null) { - downTo = 0; - } - for (var i = length - 1 >>> 0; i > downTo; --i) { - var distribution = Random.integer(0, i); - var j = distribution(engine); - if (i !== j) { - var tmp = array[i]; - array[i] = array[j]; - array[j] = tmp; - } +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + + draining = false; + + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + + var timeout = runTimeout(cleanUpNextTick); + draining = true; + var len = queue.length; + + while (len) { + currentQueue = queue; + queue = []; + + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); } } - return array; + + queueIndex = -1; + len = queue.length; + } + + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + + queue.push(new Item(fun, args)); + + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; // v8 likes predictible objects + + +function Item(fun, array) { + this.fun = fun; + this.array = array; +} + +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; + +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues + +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { + return []; +}; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { + return '/'; +}; + +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; + +process.umask = function () { + return 0; +}; + +/***/ }), +/* 51 */ +/***/ (function(module, exports) { + +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; +}; + +/***/ }), +/* 52 */ +/***/ (function(module, exports) { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); }; - proto.shuffle = function (array) { - return Random.shuffle(this.engine, array); +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + + var TempCtor = function TempCtor() {}; + + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; }; +} - Random.sample = function (engine, population, sampleSize) { - if (sampleSize < 0 || sampleSize > population.length || !isFinite(sampleSize)) { - throw new RangeError("Expected sampleSize to be within 0 and the length of the population"); - } +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { - if (sampleSize === 0) { - return []; +"use strict"; + + +const euclidean = __webpack_require__(2); + +const ClusterLeaf = __webpack_require__(23); + +const Cluster = __webpack_require__(15); +/** + * @private + * @param {Array >} cluster1 + * @param {Array >} cluster2 + * @param {function} disFun + * @returns {number} + */ + + +function simpleLink(cluster1, cluster2, disFun) { + var m = 10e100; + + for (var i = 0; i < cluster1.length; i++) { + for (var j = i; j < cluster2.length; j++) { + var d = disFun(cluster1[i], cluster2[j]); + m = Math.min(d, m); } + } - var clone = slice.call(population); - var length = clone.length; - if (length === sampleSize) { - return Random.shuffle(engine, clone, 0); + return m; +} +/** + * @private + * @param {Array >} cluster1 + * @param {Array >} cluster2 + * @param {function} disFun + * @returns {number} + */ + + +function completeLink(cluster1, cluster2, disFun) { + var m = -1; + + for (var i = 0; i < cluster1.length; i++) { + for (var j = i; j < cluster2.length; j++) { + var d = disFun(cluster1[i], cluster2[j]); + m = Math.max(d, m); } - var tailLength = length - sampleSize; - return Random.shuffle(engine, clone, tailLength - 1).slice(tailLength); - }; - proto.sample = function (population, sampleSize) { - return Random.sample(this.engine, population, sampleSize); - }; + } - Random.die = function (sideCount) { - return Random.integer(1, sideCount); - }; - proto.die = function (sideCount) { - return Random.die(sideCount)(this.engine); - }; + return m; +} +/** + * @private + * @param {Array >} cluster1 + * @param {Array >} cluster2 + * @param {function} disFun + * @returns {number} + */ - Random.dice = function (sideCount, dieCount) { - var distribution = Random.die(sideCount); - return function (engine) { - var result = []; - result.length = dieCount; - for (var i = 0; i < dieCount; ++i) { - result[i] = distribution(engine); - } - return result; - }; - }; - proto.dice = function (sideCount, dieCount) { - return Random.dice(sideCount, dieCount)(this.engine); - }; - // http://en.wikipedia.org/wiki/Universally_unique_identifier - Random.uuid4 = function () { - function zeroPad(string, zeroCount) { - return stringRepeat("0", zeroCount - string.length) + string; +function averageLink(cluster1, cluster2, disFun) { + var m = 0; + + for (var i = 0; i < cluster1.length; i++) { + for (var j = 0; j < cluster2.length; j++) { + m += disFun(cluster1[i], cluster2[j]); } + } - return function (engine) { - var a = engine() >>> 0; - var b = engine() | 0; - var c = engine() | 0; - var d = engine() >>> 0; + return m / (cluster1.length * cluster2.length); +} +/** + * @private + * @param {Array >} cluster1 + * @param {Array >} cluster2 + * @param {function} disFun + * @returns {number} + */ - return zeroPad(a.toString(16), 8) + "-" + zeroPad((b & 0xffff).toString(16), 4) + "-" + zeroPad((b >> 4 & 0x0fff | 0x4000).toString(16), 4) + "-" + zeroPad((c & 0x3fff | 0x8000).toString(16), 4) + "-" + zeroPad((c >> 4 & 0xffff).toString(16), 4) + zeroPad(d.toString(16), 8); - }; - }(); - proto.uuid4 = function () { - return Random.uuid4(this.engine); - }; - Random.string = function () { - // has 2**x chars, for faster uniform distribution - var DEFAULT_STRING_POOL = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"; +function centroidLink(cluster1, cluster2, disFun) { + var x1 = 0, + y1 = 0, + x2 = 0, + y2 = 0; + + for (var i = 0; i < cluster1.length; i++) { + x1 += cluster1[i][0]; + y1 += cluster1[i][1]; + } - return function (pool) { - if (pool == null) { - pool = DEFAULT_STRING_POOL; - } + for (var j = 0; j < cluster2.length; j++) { + x2 += cluster2[j][0]; + y2 += cluster2[j][1]; + } - var length = pool.length; - if (!length) { - throw new Error("Expected pool not to be an empty string"); - } + x1 /= cluster1.length; + y1 /= cluster1.length; + x2 /= cluster2.length; + y2 /= cluster2.length; + return disFun([x1, y1], [x2, y2]); +} +/** + * @private + * @param {Array >} cluster1 + * @param {Array >} cluster2 + * @param {function} disFun + * @returns {number} + */ - var distribution = Random.integer(0, length - 1); - return function (engine, length) { - var result = ""; - for (var i = 0; i < length; ++i) { - var j = distribution(engine); - result += pool.charAt(j); - } - return result; - }; - }; - }(); - proto.string = function (length, pool) { - return Random.string(pool)(this.engine, length); - }; - Random.hex = function () { - var LOWER_HEX_POOL = "0123456789abcdef"; - var lowerHex = Random.string(LOWER_HEX_POOL); - var upperHex = Random.string(LOWER_HEX_POOL.toUpperCase()); +function wardLink(cluster1, cluster2, disFun) { + var x1 = 0, + y1 = 0, + x2 = 0, + y2 = 0; + + for (var i = 0; i < cluster1.length; i++) { + x1 += cluster1[i][0]; + y1 += cluster1[i][1]; + } - return function (upper) { - if (upper) { - return upperHex; - } else { - return lowerHex; - } - }; - }(); - proto.hex = function (length, upper) { - return Random.hex(upper)(this.engine, length); - }; + for (var j = 0; j < cluster2.length; j++) { + x2 += cluster2[j][0]; + y2 += cluster2[j][1]; + } - Random.date = function (start, end) { - if (!(start instanceof Date)) { - throw new TypeError("Expected start to be a Date, got " + typeof start); - } else if (!(end instanceof Date)) { - throw new TypeError("Expected end to be a Date, got " + typeof end); - } - var distribution = Random.integer(start.getTime(), end.getTime()); - return function (engine) { - return new Date(distribution(engine)); - }; - }; - proto.date = function (start, end) { - return Random.date(start, end)(this.engine); + x1 /= cluster1.length; + y1 /= cluster1.length; + x2 /= cluster2.length; + y2 /= cluster2.length; + return disFun([x1, y1], [x2, y2]) * cluster1.length * cluster2.length / (cluster1.length + cluster2.length); +} +/** + * @private + * Returns the most distant point and his distance + * @param {Array >} splitting - Clusters to split + * @param {Array >} data - Original data + * @param {function} disFun - Distance function + * @returns {{d: number, p: number}} - d: maximum difference between points, p: the point more distant + */ + + +function diff(splitting, data, disFun) { + var ans = { + d: 0, + p: 0 }; + var Ci = new Array(splitting[0].length); - if (true) { - !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { - return Random; - }).call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else if (typeof module !== "undefined" && typeof require === "function") { - module.exports = Random; - } else { - (function () { - var oldGlobal = root[GLOBAL_KEY]; - Random.noConflict = function () { - root[GLOBAL_KEY] = oldGlobal; - return this; - }; - })(); - root[GLOBAL_KEY] = Random; + for (var e = 0; e < splitting[0].length; e++) { + Ci[e] = data[splitting[0][e]]; } -})(undefined); - -/***/ }), -/* 79 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + var Cj = new Array(splitting[1].length); + for (var f = 0; f < splitting[1].length; f++) { + Cj[f] = data[splitting[1][f]]; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RandomForestRegression = undefined; + var dist, ndist; -var _mlArrayMean = __webpack_require__(8); + for (var i = 0; i < Ci.length; i++) { + dist = 0; -var _mlArrayMean2 = _interopRequireDefault(_mlArrayMean); + for (var j = 0; j < Ci.length; j++) { + if (i !== j) { + dist += disFun(Ci[i], Ci[j]); + } + } -var _mlArrayMedian = __webpack_require__(26); + dist /= Ci.length - 1; + ndist = 0; -var _mlArrayMedian2 = _interopRequireDefault(_mlArrayMedian); + for (var k = 0; k < Cj.length; k++) { + ndist += disFun(Ci[i], Cj[k]); + } -var _RandomForestBase = __webpack_require__(25); + ndist /= Cj.length; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (dist - ndist > ans.d) { + ans.d = dist - ndist; + ans.p = i; + } + } -var selectionMethods = { - mean: _mlArrayMean2.default, - median: _mlArrayMedian2.default -}; + return ans; +} var defaultOptions = { - maxFeatures: 1.0, - replacement: false, - nEstimators: 10, - treeOptions: {}, - selectionMethod: 'mean', - seed: 42, - useSampleBagging: false + dist: euclidean, + kind: 'single' }; +/** + * @private + * Intra-cluster distance + * @param {Array} index + * @param {Array} data + * @param {function} disFun + * @returns {number} + */ + +function intrDist(index, data, disFun) { + var dist = 0, + count = 0; + for (var i = 0; i < index.length; i++) { + for (var j = i; j < index.length; j++) { + dist += disFun(data[index[i].index], data[index[j].index]); + count++; + } + } + + return dist / count; +} /** - * @class RandomForestRegression - * @augments RandomForestBase + * Splits the higher level clusters + * @param {Array >} data - Array of points to be clustered + * @param {json} options + * @constructor */ -class RandomForestRegression extends _RandomForestBase.RandomForestBase { - /** - * Create a new base random forest for a classifier or regression model. - * @constructor - * @param {object} options - * @param {number} [options.maxFeatures=1.0] - the number of features used on each estimator. - * * if is an integer it selects maxFeatures elements over the sample features. - * * if is a float between (0, 1), it takes the percentage of features. - * @param {boolean} [options.replacement=true] - use replacement over the sample features. - * @param {number} [options.seed=42] - seed for feature and samples selection, must be a 32-bit integer. - * @param {number} [options.nEstimators=10] - number of estimator to use. - * @param {object} [options.treeOptions={}] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/} - * @param {string} [options.selectionMethod="mean"] - the way to calculate the prediction from estimators, "mean" and "median" are supported. - * @param {boolean} [options.useSampleBagging=false] - use bagging over training samples. - * @param {object} model - for load purposes. - */ - constructor(options, model) { - if (options === true) { - super(true, model.baseModel); - this.selectionMethod = model.selectionMethod; - } else { - options = Object.assign({}, defaultOptions, options); - if (!(options.selectionMethod === 'mean' || options.selectionMethod === 'median')) { - throw new RangeError(`Unsupported selection method ${options.selectionMethod}`); - } - options.isClassifier = false; +function diana(data, options) { + options = Object.assign({}, defaultOptions, options); - super(options); - this.selectionMethod = options.selectionMethod; + if (typeof options.kind === 'string') { + switch (options.kind) { + case 'single': + options.kind = simpleLink; + break; + + case 'complete': + options.kind = completeLink; + break; + + case 'average': + options.kind = averageLink; + break; + + case 'centroid': + options.kind = centroidLink; + break; + + case 'ward': + options.kind = wardLink; + break; + + default: + throw new RangeError('Unknown kind of similarity'); } + } else if (typeof options.kind !== 'function') { + throw new TypeError('Undefined kind of similarity'); } - /** - * retrieve the prediction given the selection method. - * @param {Array} values - predictions of the estimators. - * @return {number} prediction - */ - selection(values) { - return selectionMethods[this.selectionMethod](values); - } + var tree = new Cluster(); + tree.children = new Array(data.length); + tree.index = new Array(data.length); - /** - * Export the current model to JSON. - * @return {object} - Current model. - */ - toJSON() { - var baseModel = super.toJSON(); - return { - baseModel: baseModel, - selectionMethod: this.selectionMethod, - name: 'RFRegression' - }; + for (var ind = 0; ind < data.length; ind++) { + tree.children[ind] = new ClusterLeaf(ind); + tree.index[ind] = new ClusterLeaf(ind); } - /** - * Load a Decision tree classifier with the given model. - * @param {object} model - * @return {RandomForestRegression} - */ - static load(model) { - if (model.name !== 'RFRegression') { - throw new RangeError(`Invalid model: ${model.name}`); - } + tree.distance = intrDist(tree.index, data, options.dist); + var m, M, clId, dist, rebel; + var list = [tree]; - return new RandomForestRegression(true, model); - } -} -exports.RandomForestRegression = RandomForestRegression; + while (list.length > 0) { + M = 0; + clId = 0; -/***/ }), -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { + for (var i = 0; i < list.length; i++) { + m = 0; + + for (var j = 0; j < list[i].length; j++) { + for (var l = j + 1; l < list[i].length; l++) { + m = Math.max(options.dist(data[list[i].index[j].index], data[list[i].index[l].index]), m); + } + } -"use strict"; -(function(){function d(c){for(var d=0,e=c.length-1,f=void 0,g=void 0,h=void 0,i=b(d,e);;){if(e<=d)return c[i];if(e==d+1)return c[d]>c[e]&&a(c,d,e),c[i];for(f=b(d,e),c[f]>c[e]&&a(c,f,e),c[d]>c[e]&&a(c,d,e),c[f]>c[d]&&a(c,f,d),a(c,f,d+1),g=d+1,h=e;;){do g++;while(c[d]>c[g]);do h--;while(c[h]>c[d]);if(h=i&&(e=h-1)}}var a=function(a,b,c){var d;return d=[a[c],a[b]],a[b]=d[0],a[c]=d[1],d},b=function(a,b){return~~((a+b)/2)};'undefined'!=typeof module&&module.exports?module.exports=d:window.median=d})(); + if (m > M) { + M = m; + clId = i; + } + } -/***/ }), -/* 81 */ -/***/ (function(module, exports, __webpack_require__) { + M = 0; -"use strict"; + if (list[clId].index.length === 2) { + list[clId].children = [list[clId].index[0], list[clId].index[1]]; + list[clId].distance = options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]); + } else if (list[clId].index.length === 3) { + list[clId].children = [list[clId].index[0], list[clId].index[1], list[clId].index[2]]; + var d = [options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]), options.dist(data[list[clId].index[1].index], data[list[clId].index[2].index])]; + list[clId].distance = (d[0] + d[1]) / 2; + } else { + var C = new Cluster(); + var sG = new Cluster(); + var splitting = [new Array(list[clId].index.length), []]; + for (var spl = 0; spl < splitting[0].length; spl++) { + splitting[0][spl] = spl; + } -var matrixLib = __webpack_require__(0); -var Matrix = matrixLib.Matrix; -var EVD = matrixLib.EVD; -var SVD = matrixLib.SVD; -var Stat = __webpack_require__(10); -var mean = Stat.mean; -var stdev = Stat.standardDeviation; + for (var ii = 0; ii < splitting[0].length; ii++) { + dist = 0; -var defaultOptions = { - isCovarianceMatrix: false, - center: true, - scale: false -}; + for (var jj = 0; jj < splitting[0].length; jj++) { + if (ii !== jj) { + dist += options.dist(data[list[clId].index[splitting[0][jj]].index], data[list[clId].index[splitting[0][ii]].index]); + } + } -/** - * Creates new PCA (Principal Component Analysis) from the dataset - * @param {Matrix} dataset - dataset or covariance matrix - * @param {Object} options - * @param {boolean} [options.isCovarianceMatrix=false] - true if the dataset is a covariance matrix - * @param {boolean} [options.center=true] - should the data be centered (subtract the mean) - * @param {boolean} [options.scale=false] - should the data be scaled (divide by the standard deviation) - * */ -class PCA { - constructor(dataset, options) { - if (dataset === true) { - var model = options; - this.center = model.center; - this.scale = model.scale; - this.means = model.means; - this.stdevs = model.stdevs; - this.U = Matrix.checkMatrix(model.U); - this.S = model.S; - return; + dist /= splitting[0].length - 1; + + if (dist > M) { + M = dist; + rebel = ii; } + } - options = Object.assign({}, defaultOptions, options); + splitting[1] = [rebel]; + splitting[0].splice(rebel, 1); + dist = diff(splitting, data, options.dist); - this.center = false; - this.scale = false; - this.means = null; - this.stdevs = null; + while (dist.d > 0) { + splitting[1].push(splitting[0][dist.p]); + splitting[0].splice(dist.p, 1); + dist = diff(splitting, data, options.dist); + } - if (options.isCovarianceMatrix) { - // user provided a covariance matrix instead of dataset - this._computeFromCovarianceMatrix(dataset); - return; - } + var fData = new Array(splitting[0].length); + C.index = new Array(splitting[0].length); - var useCovarianceMatrix; - if (typeof options.useCovarianceMatrix === 'boolean') { - useCovarianceMatrix = options.useCovarianceMatrix; - } else { - useCovarianceMatrix = dataset.length > dataset[0].length; - } + for (var e = 0; e < fData.length; e++) { + fData[e] = data[list[clId].index[splitting[0][e]].index]; + C.index[e] = list[clId].index[splitting[0][e]]; + C.children[e] = list[clId].index[splitting[0][e]]; + } - if (useCovarianceMatrix) { - // user provided a dataset but wants us to compute and use the covariance matrix - dataset = this._adjust(dataset, options); - var covarianceMatrix = dataset.transposeView().mmul(dataset).div(dataset.rows - 1); - this._computeFromCovarianceMatrix(covarianceMatrix); - } else { - dataset = this._adjust(dataset, options); - var svd = new SVD(dataset, { - computeLeftSingularVectors: false, - computeRightSingularVectors: true, - autoTranspose: true - }); + var sData = new Array(splitting[1].length); + sG.index = new Array(splitting[1].length); - this.U = svd.rightSingularVectors; + for (var f = 0; f < sData.length; f++) { + sData[f] = data[list[clId].index[splitting[1][f]].index]; + sG.index[f] = list[clId].index[splitting[1][f]]; + sG.children[f] = list[clId].index[splitting[1][f]]; + } - var singularValues = svd.diagonal; - var eigenvalues = new Array(singularValues.length); - for (var i = 0; i < singularValues.length; i++) { - eigenvalues[i] = singularValues[i] * singularValues[i] / (dataset.length - 1); - } - this.S = eigenvalues; - } + C.distance = intrDist(C.index, data, options.dist); + sG.distance = intrDist(sG.index, data, options.dist); + list.push(C); + list.push(sG); + list[clId].children = [C, sG]; } - /** - * Load a PCA model from JSON - * @param {Object} model - * @return {PCA} - */ - static load(model) { - if (model.name !== 'PCA') throw new RangeError('Invalid model: ' + model.name); - return new PCA(true, model); - } + list.splice(clId, 1); + } - /** - * Project the dataset into the PCA space - * @param {Matrix} dataset - * @param {Object} options - * @return {Matrix} dataset projected in the PCA space - */ - predict(dataset, options = {}) { - var _options$nComponents = options.nComponents, - nComponents = _options$nComponents === undefined ? this.U.columns : _options$nComponents; + return tree; +} +module.exports = diana; - dataset = new Matrix(dataset); - if (this.center) { - dataset.subRowVector(this.means); - if (this.scale) { - dataset.divRowVector(this.stdevs); - } - } +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { - var predictions = dataset.mmul(this.U); - return predictions.subMatrix(0, predictions.rows - 1, 0, nComponents - 1); - } +"use strict"; - /** - * Returns the proportion of variance for each component - * @return {[number]} - */ - getExplainedVariance() { - var sum = 0; - for (var i = 0; i < this.S.length; i++) { - sum += this.S[i]; - } - return this.S.map(value => value / sum); - } - /** - * Returns the cumulative proportion of variance - * @return {[number]} - */ - getCumulativeVariance() { - var explained = this.getExplainedVariance(); - for (var i = 1; i < explained.length; i++) { - explained[i] += explained[i - 1]; - } - return explained; - } +const Kernel = __webpack_require__(10); - /** - * Returns the Eigenvectors of the covariance matrix - * @returns {Matrix} - */ - getEigenvectors() { - return this.U; - } +const stat = __webpack_require__(3).array; - /** - * Returns the Eigenvalues (on the diagonal) - * @returns {[number]} - */ - getEigenvalues() { - return this.S; - } +var defaultOptions = { + C: 1, + tol: 1e-4, + maxPasses: 10, + maxIterations: 10000, + kernel: 'linear', + alphaTol: 1e-6, + random: Math.random, + whitening: true +}; +/** + * Simplified version of the Sequential Minimal Optimization algorithm for training + * support vector machines + * @param {{Object}} options - SVM options + * @param {Number} [options.C=1] - regularization parameter + * @param {Number} [options.tol=1e-4] - numerical tolerance + * @param {Number} [options.alphaTol=1e-6] - alpha tolerance, threshold to decide support vectors + * @param {Number} [options.maxPasses=10] - max number of times to iterate over alphas without changing + * @param {Number} [options.maxIterations=10000] - max number of iterations + * @param {String} [options.kernel=linear] - the kind of kernel. {@link https://github.com/mljs/kernel/tree/1252de5f9012776e6e0eb06c7b434b8631fb21f0 List of kernels} + * @param {Function} [options.random=Math.random] - custom random number generator + * @constructor + */ - /** - * Returns the standard deviations of the principal components - * @returns {[number]} - */ - getStandardDeviations() { - return this.S.map(x => Math.sqrt(x)); - } +function SVM(options) { + this.options = Object.assign({}, defaultOptions, options); + this.kernel = new Kernel(this.options.kernel, this.options.kernelOptions); + this.b = 0; +} +/** + * Train the SVM model + * @param {Array >} features - training data features + * @param {Array } labels - training data labels in the domain {1,-1} + */ - /** - * Returns the loadings matrix - * @return {Matrix} - */ - getLoadings() { - return this.U.transpose(); - } - /** - * Export the current model to a JSON object - * @return {Object} model - */ - toJSON() { - return { - name: 'PCA', - center: this.center, - scale: this.scale, - means: this.means, - stdevs: this.stdevs, - U: this.U, - S: this.S - }; +SVM.prototype.train = function (features, labels) { + if (features.length !== labels.length) { + throw new Error('Features and labels should have the same length'); + } + + if (features.length < 2) { + throw new Error('Cannot train with less than 2 observations'); + } + + this._trained = false; + this._loaded = false; + this.N = labels.length; + this.D = features[0].length; + + if (this.options.whitening) { + this.X = new Array(this.N); + + for (var i = 0; i < this.N; i++) { + this.X[i] = new Array(this.D); } - _adjust(dataset, options) { - this.center = !!options.center; - this.scale = !!options.scale; + this.minMax = new Array(this.D); // Apply normalization and keep normalization parameters - dataset = new Matrix(dataset); + for (var j = 0; j < this.D; j++) { + var d = new Array(this.N); - if (this.center) { - var means = mean(dataset); - var stdevs = this.scale ? stdev(dataset, means, true) : null; - this.means = means; - dataset.subRowVector(means); - if (this.scale) { - for (var i = 0; i < stdevs.length; i++) { - if (stdevs[i] === 0) { - throw new RangeError('Cannot scale the dataset (standard deviation is zero at index ' + i); - } - } - this.stdevs = stdevs; - dataset.divRowVector(stdevs); - } - } + for (i = 0; i < this.N; i++) { + d[i] = features[i][j]; + } + + this.minMax[j] = stat.minMax(d); - return dataset; + for (i = 0; i < this.N; i++) { + this.X[i][j] = (features[i][j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min); + } } + } else { + this.X = features; + } - _computeFromCovarianceMatrix(dataset) { - var evd = new EVD(dataset, { assumeSymmetric: true }); - this.U = evd.eigenvectorMatrix; - for (var i = 0; i < this.U.length; i++) { - this.U[i].reverse(); - } - this.S = evd.realEigenvalues.reverse(); + this.Y = labels; + this.b = 0; + this.W = undefined; + var kernel = this.kernel.compute(this.X); + var m = labels.length; + var alpha = new Array(m).fill(0); + this.alphas = alpha; + + for (var a = 0; a < m; a++) alpha[a] = 0; + + var b1 = 0, + b2 = 0, + iter = 0, + passes = 0, + Ei = 0, + Ej = 0, + ai = 0, + aj = 0, + L = 0, + H = 0, + eta = 0; + + while (passes < this.options.maxPasses && iter < this.options.maxIterations) { + var numChange = 0; + + for (i = 0; i < m; i++) { + Ei = this._marginOnePrecomputed(i, kernel) - labels[i]; + + if (labels[i] * Ei < -this.options.tol && alpha[i] < this.options.C || labels[i] * Ei > this.options.tol && alpha[i] > 0) { + j = i; + + while (j === i) j = Math.floor(this.options.random() * m); + + Ej = this._marginOnePrecomputed(j, kernel) - labels[j]; + ai = alpha[i]; + aj = alpha[j]; + + if (labels[i] === labels[j]) { + L = Math.max(0, ai + aj - this.options.C); + H = Math.min(this.options.C, ai + aj); + } else { + L = Math.max(0, aj - ai); + H = Math.min(this.options.C, this.options.C + aj + ai); + } + + if (Math.abs(L - H) < 1e-4) continue; + eta = 2 * kernel[i][j] - kernel[i][i] - kernel[j][j]; + if (eta >= 0) continue; + var newaj = alpha[j] - labels[j] * (Ei - Ej) / eta; + if (newaj > H) newaj = H;else if (newaj < L) newaj = L; + if (Math.abs(aj - newaj) < 10e-4) continue; + alpha[j] = newaj; + alpha[i] = alpha[i] + labels[i] * labels[j] * (aj - newaj); + b1 = this.b - Ei - labels[i] * (alpha[i] - ai) * kernel[i][i] - labels[j] * (alpha[j] - aj) * kernel[i][j]; + b2 = this.b - Ej - labels[i] * (alpha[i] - ai) * kernel[i][j] - labels[j] * (alpha[j] - aj) * kernel[j][j]; + this.b = (b1 + b2) / 2; + if (alpha[i] < this.options.C && alpha[i] > 0) this.b = b1; + if (alpha[j] < this.options.C && alpha[j] > 0) this.b = b2; + numChange += 1; + } } -} -module.exports = PCA; + iter++; + if (numChange === 0) passes += 1;else passes = 0; + } -/***/ }), -/* 82 */ -/***/ (function(module, exports, __webpack_require__) { + if (iter === this.options.maxIterations) { + throw new Error('max iterations reached'); + } -"use strict"; + this.iterations = iter; // Compute the weights (useful for fast decision on new test instances when linear SVM) + if (this.options.kernel === 'linear') { + this.W = new Array(this.D); -exports.agnes = __webpack_require__(83); -exports.diana = __webpack_require__(91); -//exports.birch = require('./birch'); -//exports.cure = require('./cure'); -//exports.chameleon = require('./chameleon'); + for (var r = 0; r < this.D; r++) { + this.W[r] = 0; -/***/ }), -/* 83 */ -/***/ (function(module, exports, __webpack_require__) { + for (var w = 0; w < m; w++) this.W[r] += labels[w] * alpha[w] * this.X[w][r]; + } + } // Keep only support vectors + // It will compute decision on new test instances faster + // We also keep the index of the support vectors + // in the original data -"use strict"; + var nX = []; + var nY = []; + var nAlphas = []; + this._supportVectorIdx = []; -var euclidean = __webpack_require__(1); -var ClusterLeaf = __webpack_require__(28); -var Cluster = __webpack_require__(14); -var distanceMatrix = __webpack_require__(29); + for (i = 0; i < this.N; i++) { + if (this.alphas[i] > this.options.alphaTol) { + nX.push(this.X[i]); + nY.push(labels[i]); + nAlphas.push(this.alphas[i]); -/** - * @private - * @param cluster1 - * @param cluster2 - * @param disFun - * @returns {number} - */ -function simpleLink(cluster1, cluster2, disFun) { - var m = 10e100; - for (var i = 0; i < cluster1.length; i++) { - for (var j = 0; j < cluster2.length; j++) { - var d = disFun[cluster1[i]][cluster2[j]]; - m = Math.min(d, m); - } + this._supportVectorIdx.push(i); } - return m; -} + } -/** - * @private - * @param cluster1 - * @param cluster2 - * @param disFun - * @returns {number} - */ -function completeLink(cluster1, cluster2, disFun) { - var m = -1; - for (var i = 0; i < cluster1.length; i++) { - for (var j = 0; j < cluster2.length; j++) { - var d = disFun[cluster1[i]][cluster2[j]]; - m = Math.max(d, m); - } - } - return m; -} + this.X = nX; + this.Y = nY; + this.N = nX.length; + this.alphas = nAlphas; // A flag to say this SVM has been trained + this._trained = true; +}; /** + * Get prediction ({-1,1}) given one observation's features. * @private - * @param cluster1 - * @param cluster2 - * @param disFun - * @returns {number} + * @param p The observation's features. + * @returns {number} Classification result ({-1,1}) */ -function averageLink(cluster1, cluster2, disFun) { - var m = 0; - for (var i = 0; i < cluster1.length; i++) { - for (var j = 0; j < cluster2.length; j++) { - m += disFun[cluster1[i]][cluster2[j]]; - } - } - return m / (cluster1.length * cluster2.length); -} + +SVM.prototype.predictOne = function (p) { + var margin = this.marginOne(p); + return margin > 0 ? 1 : -1; +}; /** - * @private - * @param cluster1 - * @param cluster2 - * @param disFun - * @returns {*} + * Predict the classification outcome of a trained svm given one or several observations' features. + * @param {Array} features - The observation(s)' features + * @returns {Array|Number} An array of {-1, 1} if several observations are given or a number if one observation + * is given */ -function centroidLink(cluster1, cluster2, disFun) { - var dist = new Array(cluster1.length * cluster2.length); - for (var i = 0; i < cluster1.length; i++) { - for (var j = 0; j < cluster2.length; j++) { - dist[i * cluster2.length + j] = disFun[cluster1[i]][cluster2[j]]; - } - } - return median(dist); -} + +SVM.prototype.predict = function (features) { + if (!this._trained && !this._loaded) throw new Error('Cannot predict, you need to train the SVM first'); + + if (Array.isArray(features) && Array.isArray(features[0])) { + return features.map(this.predictOne.bind(this)); + } else { + return this.predictOne(features); + } +}; /** + * Get margin given one observation's features * @private - * @param cluster1 - * @param cluster2 - * @param disFun - * @returns {number} + * @param {Array} features - Features + * @returns {Number} - The computed margin */ -function wardLink(cluster1, cluster2, disFun) { - return centroidLink(cluster1, cluster2, disFun) * cluster1.length * cluster2.length / (cluster1.length + cluster2.length); -} - -function compareNumbers(a, b) { - return a - b; -} -function median(values, alreadySorted) { - if (alreadySorted === undefined) alreadySorted = false; - if (!alreadySorted) { - values = [].concat(values).sort(compareNumbers); - } - var l = values.length; - var half = Math.floor(l / 2); - if (l % 2 === 0) { - return (values[half - 1] + values[half]) * 0.5; - } else { - return values[half]; - } -} -var defaultOptions = { - disFunc: euclidean, - kind: 'single', - isDistanceMatrix: false +SVM.prototype.marginOne = function (features, noWhitening) { + // Apply normalization + if (this.options.whitening && !noWhitening) { + features = this._applyWhitening(features); + } -}; + var ans = this.b, + i; -/** - * Continuously merge nodes that have the least dissimilarity - * @param {Array >} distance - Array of points to be clustered - * @param {json} options - * @option isDistanceMatrix: Is the input a distance matrix? - * @constructor - */ -function agnes(data, options) { - options = Object.assign({}, defaultOptions, options); - var len = data.length; - var distance = data; //If source - if (!options.isDistanceMatrix) { - distance = distanceMatrix(data, options.disFunc); + if (this.options.kernel === 'linear' && this.W) { + // Use weights, it's faster + for (i = 0; i < this.W.length; i++) { + ans += this.W[i] * features[i]; } - - // allows to use a string or a given function - if (typeof options.kind === 'string') { - switch (options.kind) { - case 'single': - options.kind = simpleLink; - break; - case 'complete': - options.kind = completeLink; - break; - case 'average': - options.kind = averageLink; - break; - case 'centroid': - options.kind = centroidLink; - break; - case 'ward': - options.kind = wardLink; - break; - default: - throw new RangeError('Unknown kind of similarity'); - } - } else if (typeof options.kind !== 'function') { - throw new TypeError('Undefined kind of similarity'); - } - - var list = new Array(len); - for (var i = 0; i < distance.length; i++) { - list[i] = new ClusterLeaf(i); - } - var min = 10e5, - d = {}, - dis = 0; - - while (list.length > 1) { - // calculates the minimum distance - d = {}; - min = 10e5; - for (var j = 0; j < list.length; j++) { - for (var k = j + 1; k < list.length; k++) { - var fdistance, sdistance; - if (list[j] instanceof ClusterLeaf) { - fdistance = [list[j].index]; - } else { - fdistance = new Array(list[j].index.length); - for (var e = 0; e < fdistance.length; e++) { - fdistance[e] = list[j].index[e].index; - } - } - if (list[k] instanceof ClusterLeaf) { - sdistance = [list[k].index]; - } else { - sdistance = new Array(list[k].index.length); - for (var f = 0; f < sdistance.length; f++) { - sdistance[f] = list[k].index[f].index; - } - } - dis = options.kind(fdistance, sdistance, distance).toFixed(4); - if (dis in d) { - d[dis].push([list[j], list[k]]); - } else { - d[dis] = [[list[j], list[k]]]; - } - min = Math.min(dis, min); - } - } - // cluster dots - var dmin = d[min.toFixed(4)]; - var clustered = new Array(dmin.length); - var aux, - count = 0; - while (dmin.length > 0) { - aux = dmin.shift(); - for (var q = 0; q < dmin.length; q++) { - var int = dmin[q].filter(function (n) { - //noinspection JSReferencingMutableVariableFromClosure - return aux.indexOf(n) !== -1; - }); - if (int.length > 0) { - var diff = dmin[q].filter(function (n) { - //noinspection JSReferencingMutableVariableFromClosure - return aux.indexOf(n) === -1; - }); - aux = aux.concat(diff); - dmin.splice(q--, 1); - } - } - clustered[count++] = aux; - } - clustered.length = count; - - for (var ii = 0; ii < clustered.length; ii++) { - var obj = new Cluster(); - obj.children = clustered[ii].concat(); - obj.distance = min; - obj.index = new Array(len); - var indCount = 0; - for (var jj = 0; jj < clustered[ii].length; jj++) { - if (clustered[ii][jj] instanceof ClusterLeaf) { - obj.index[indCount++] = clustered[ii][jj]; - } else { - indCount += clustered[ii][jj].index.length; - obj.index = clustered[ii][jj].index.concat(obj.index); - } - list.splice(list.indexOf(clustered[ii][jj]), 1); - } - obj.index.length = indCount; - list.push(obj); - } + } else { + for (i = 0; i < this.N; i++) { + ans += this.alphas[i] * this.Y[i] * this.kernel.compute([features], [this.X[i]])[0][0]; } - return list[0]; -} + } -module.exports = agnes; + return ans; +}; +/** + * Get a margin using the precomputed kernel. Much faster than normal margin computation + * @private + * @param {Number} index - Train data index + * @param {Array< Array >} kernel - The precomputed kernel + * @returns {number} Computed margin + * @private + */ -/***/ }), -/* 84 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +SVM.prototype._marginOnePrecomputed = function (index, kernel) { + var ans = this.b, + i; + for (i = 0; i < this.N; i++) { + ans += this.alphas[i] * this.Y[i] * kernel[index][i]; + } -module.exports = __webpack_require__(85); + return ans; +}; +/** + * Returns the margin of one or several observations given its features + * @param {Array >|Array} features - Features from on or several observations. + * @returns {Number|Array} The computed margin. Is an Array if several observations' features given, or a Number if + * only one observation's features given + */ -/***/ }), -/* 85 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__; +SVM.prototype.margin = function (features) { + if (Array.isArray(features)) { + return features.map(this.marginOne.bind(this)); + } else { + return this.marginOne(features); + } +}; +/** + * Get support vectors indexes of the trained classifier. WARINNG: this method does not work for svm instances + * created from {@link #SVM.load load} if linear kernel + * @returns {Array} The indices in the training vector of the support vectors + */ -// Generated by CoffeeScript 1.8.0 -(function () { - var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup; - floor = Math.floor, min = Math.min; +SVM.prototype.supportVectors = function () { + if (!this._trained && !this._loaded) throw new Error('Cannot get support vectors, you need to train the SVM first'); + if (this._loaded && this.options.kernel === 'linear') throw new Error('Cannot get support vectors from saved linear model, you need to train the SVM to have them'); + return this._supportVectorIdx; +}; +/** + * Create a SVM instance from a saved model + * @param {Object} model - Object such as returned by a trained SVM instance with {@link #SVM#toJSON toJSON} + * @returns {SVM} Instance of svm classifier + */ - /* - Default comparison function to be used - */ - defaultCmp = function defaultCmp(x, y) { - if (x < y) { - return -1; - } - if (x > y) { - return 1; - } - return 0; - }; +SVM.load = function (model) { + this._loaded = true; + this._trained = false; + var svm = new SVM(model.options); - /* - Insert item x in list a, and keep it sorted assuming a is sorted. - - If x is already in a, insert it to the right of the rightmost x. - - Optional args lo (default 0) and hi (default a.length) bound the slice - of a to be searched. - */ + if (model.options.kernel === 'linear') { + svm.W = model.W.slice(); + svm.D = svm.W.length; + } else { + svm.X = model.X.slice(); + svm.Y = model.Y.slice(); + svm.alphas = model.alphas.slice(); + svm.N = svm.X.length; + svm.D = svm.X[0].length; + } - insort = function insort(a, x, lo, hi, cmp) { - var mid; - if (lo == null) { - lo = 0; - } - if (cmp == null) { - cmp = defaultCmp; - } - if (lo < 0) { - throw new Error('lo must be non-negative'); - } - if (hi == null) { - hi = a.length; - } - while (lo < hi) { - mid = floor((lo + hi) / 2); - if (cmp(x, a[mid]) < 0) { - hi = mid; - } else { - lo = mid + 1; - } - } - return [].splice.apply(a, [lo, lo - lo].concat(x)), x; - }; + svm.minMax = model.minMax; + svm.b = model.b; + svm._loaded = true; + svm._trained = false; + return svm; +}; +/** + * Export the minimal object that enables to reload the model + * @returns {Object} Model object that can be reused with {@link #SVM.load load} + */ - /* - Push item onto heap, maintaining the heap invariant. - */ - heappush = function heappush(array, item, cmp) { - if (cmp == null) { - cmp = defaultCmp; - } - array.push(item); - return _siftdown(array, 0, array.length - 1, cmp); - }; +SVM.prototype.toJSON = function () { + if (!this._trained && !this._loaded) throw new Error('Cannot export, you need to train the SVM first'); + var model = {}; + model.options = Object.assign({}, this.options); + model.b = this.b; + model.minMax = this.minMax; + + if (model.options.kernel === 'linear') { + model.W = this.W.slice(); + } else { + // Exporting non-linear models is heavier + model.X = this.X.slice(); + model.Y = this.Y.slice(); + model.alphas = this.alphas.slice(); + } - /* - Pop the smallest item off the heap, maintaining the heap invariant. - */ + return model; +}; - heappop = function heappop(array, cmp) { - var lastelt, returnitem; - if (cmp == null) { - cmp = defaultCmp; - } - lastelt = array.pop(); - if (array.length) { - returnitem = array[0]; - array[0] = lastelt; - _siftup(array, 0, cmp); - } else { - returnitem = lastelt; - } - return returnitem; - }; +SVM.prototype._applyWhitening = function (features) { + if (!this.minMax) throw new Error('Could not apply whitening'); + var whitened = new Array(features.length); - /* - Pop and return the current smallest value, and add the new item. - - This is more efficient than heappop() followed by heappush(), and can be - more appropriate when using a fixed size heap. Note that the value - returned may be larger than item! That constrains reasonable use of - this routine unless written as part of a conditional replacement: - if item > array[0] - item = heapreplace(array, item) - */ + for (var j = 0; j < features.length; j++) { + whitened[j] = (features[j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min); + } - heapreplace = function heapreplace(array, item, cmp) { - var returnitem; - if (cmp == null) { - cmp = defaultCmp; - } - returnitem = array[0]; - array[0] = item; - _siftup(array, 0, cmp); - return returnitem; - }; + return whitened; +}; - /* - Fast version of a heappush followed by a heappop. - */ +module.exports = SVM; - heappushpop = function heappushpop(array, item, cmp) { - var _ref; - if (cmp == null) { - cmp = defaultCmp; - } - if (array.length && cmp(array[0], item) < 0) { - _ref = [array[0], item], item = _ref[0], array[0] = _ref[1]; - _siftup(array, 0, cmp); - } - return item; - }; +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { - /* - Transform list into a heap, in-place, in O(array.length) time. - */ +"use strict"; - heapify = function heapify(array, cmp) { - var i, _i, _j, _len, _ref, _ref1, _results, _results1; - if (cmp == null) { - cmp = defaultCmp; - } - _ref1 = function () { - _results1 = []; - for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--) { - _results1.push(_j); - } - return _results1; - }.apply(this).reverse(); - _results = []; - for (_i = 0, _len = _ref1.length; _i < _len; _i++) { - i = _ref1[_i]; - _results.push(_siftup(array, i, cmp)); - } - return _results; - }; - /* - Update the position of the given item in the heap. - This function should be called every time the item is being modified. - */ +const squaredEuclidean = __webpack_require__(2).squared; - updateItem = function updateItem(array, item, cmp) { - var pos; - if (cmp == null) { - cmp = defaultCmp; - } - pos = array.indexOf(item); - if (pos === -1) { - return; - } - _siftdown(array, 0, pos, cmp); - return _siftup(array, pos, cmp); - }; +const defaultOptions = { + sigma: 1 +}; - /* - Find the n largest elements in a dataset. - */ +class GaussianKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; + this.divisor = 2 * options.sigma * options.sigma; + } - nlargest = function nlargest(array, n, cmp) { - var elem, result, _i, _len, _ref; - if (cmp == null) { - cmp = defaultCmp; - } - result = array.slice(0, n); - if (!result.length) { - return result; - } - heapify(result, cmp); - _ref = array.slice(n); - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - elem = _ref[_i]; - heappushpop(result, elem, cmp); - } - return result.sort(cmp).reverse(); - }; + compute(x, y) { + const distance = squaredEuclidean(x, y); + return Math.exp(-distance / this.divisor); + } - /* - Find the n smallest elements in a dataset. - */ +} - nsmallest = function nsmallest(array, n, cmp) { - var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results; - if (cmp == null) { - cmp = defaultCmp; - } - if (n * 10 <= array.length) { - result = array.slice(0, n).sort(cmp); - if (!result.length) { - return result; - } - los = result[result.length - 1]; - _ref = array.slice(n); - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - elem = _ref[_i]; - if (cmp(elem, los) < 0) { - insort(result, elem, 0, null, cmp); - result.pop(); - los = result[result.length - 1]; - } - } - return result; - } - heapify(array, cmp); - _results = []; - for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) { - _results.push(heappop(array, cmp)); - } - return _results; - }; +module.exports = GaussianKernel; - _siftdown = function _siftdown(array, startpos, pos, cmp) { - var newitem, parent, parentpos; - if (cmp == null) { - cmp = defaultCmp; - } - newitem = array[pos]; - while (pos > startpos) { - parentpos = pos - 1 >> 1; - parent = array[parentpos]; - if (cmp(newitem, parent) < 0) { - array[pos] = parent; - pos = parentpos; - continue; - } - break; - } - return array[pos] = newitem; - }; +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { - _siftup = function _siftup(array, pos, cmp) { - var childpos, endpos, newitem, rightpos, startpos; - if (cmp == null) { - cmp = defaultCmp; - } - endpos = array.length; - startpos = pos; - newitem = array[pos]; - childpos = 2 * pos + 1; - while (childpos < endpos) { - rightpos = childpos + 1; - if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) { - childpos = rightpos; - } - array[pos] = array[childpos]; - pos = childpos; - childpos = 2 * pos + 1; +"use strict"; + + +const defaultOptions = { + degree: 1, + constant: 1, + scale: 1 +}; + +class PolynomialKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.degree = options.degree; + this.constant = options.constant; + this.scale = options.scale; + } + + compute(x, y) { + var sum = 0; + + for (var i = 0; i < x.length; i++) { + sum += x[i] * y[i]; } - array[pos] = newitem; - return _siftdown(array, startpos, pos, cmp); - }; - Heap = function () { - Heap.push = heappush; + return Math.pow(this.scale * sum + this.constant, this.degree); + } - Heap.pop = heappop; +} - Heap.replace = heapreplace; +module.exports = PolynomialKernel; - Heap.pushpop = heappushpop; +/***/ }), +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { - Heap.heapify = heapify; +"use strict"; - Heap.updateItem = updateItem; - Heap.nlargest = nlargest; +const defaultOptions = { + sigma: 1, + degree: 1 +}; - Heap.nsmallest = nsmallest; +class ANOVAKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; + this.degree = options.degree; + } - function Heap(cmp) { - this.cmp = cmp != null ? cmp : defaultCmp; - this.nodes = []; + compute(x, y) { + var sum = 0; + var len = Math.min(x.length, y.length); + + for (var i = 1; i <= len; ++i) { + sum += Math.pow(Math.exp(-this.sigma * Math.pow(Math.pow(x[i - 1], i) - Math.pow(y[i - 1], i), 2)), this.degree); } - Heap.prototype.push = function (x) { - return heappush(this.nodes, x, this.cmp); - }; + return sum; + } - Heap.prototype.pop = function () { - return heappop(this.nodes, this.cmp); - }; +} - Heap.prototype.peek = function () { - return this.nodes[0]; - }; +module.exports = ANOVAKernel; - Heap.prototype.contains = function (x) { - return this.nodes.indexOf(x) !== -1; - }; +/***/ }), +/* 58 */ +/***/ (function(module, exports, __webpack_require__) { - Heap.prototype.replace = function (x) { - return heapreplace(this.nodes, x, this.cmp); - }; +"use strict"; - Heap.prototype.pushpop = function (x) { - return heappushpop(this.nodes, x, this.cmp); - }; - Heap.prototype.heapify = function () { - return heapify(this.nodes, this.cmp); - }; +const squaredEuclidean = __webpack_require__(2).squared; - Heap.prototype.updateItem = function (x) { - return updateItem(this.nodes, x, this.cmp); - }; +const defaultOptions = { + sigma: 1 +}; - Heap.prototype.clear = function () { - return this.nodes = []; - }; +class CauchyKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; + } - Heap.prototype.empty = function () { - return this.nodes.length === 0; - }; + compute(x, y) { + return 1 / (1 + squaredEuclidean(x, y) / (this.sigma * this.sigma)); + } - Heap.prototype.size = function () { - return this.nodes.length; - }; +} - Heap.prototype.clone = function () { - var heap; - heap = new Heap(); - heap.nodes = this.nodes.slice(0); - return heap; - }; +module.exports = CauchyKernel; - Heap.prototype.toArray = function () { - return this.nodes.slice(0); - }; +/***/ }), +/* 59 */ +/***/ (function(module, exports, __webpack_require__) { - Heap.prototype.insert = Heap.prototype.push; +"use strict"; - Heap.prototype.top = Heap.prototype.peek; - Heap.prototype.front = Heap.prototype.peek; +const euclidean = __webpack_require__(2); - Heap.prototype.has = Heap.prototype.contains; +const defaultOptions = { + sigma: 1 +}; - Heap.prototype.copy = Heap.prototype.clone; +class ExponentialKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; + this.divisor = 2 * options.sigma * options.sigma; + } - return Heap; - }(); + compute(x, y) { + const distance = euclidean(x, y); + return Math.exp(-distance / this.divisor); + } - (function (root, factory) { - if (true) { - return !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else if (typeof exports === 'object') { - return module.exports = factory(); - } else { - return root.Heap = factory(); - } - })(this, function () { - return Heap; - }); -}).call(undefined); +} + +module.exports = ExponentialKernel; /***/ }), -/* 86 */ +/* 60 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* WEBPACK VAR INJECTION */(function(global, process) { -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -var formatRegExp = /%[sdj%]/g; -exports.format = function (f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); +class HistogramIntersectionKernel { + compute(x, y) { + var min = Math.min(x.length, y.length); + var sum = 0; + + for (var i = 0; i < min; ++i) { + sum += Math.min(x[i], y[i]); } - return objects.join(' '); + + return sum; } - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function (x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': - return String(args[i++]); - case '%d': - return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } +} + +module.exports = HistogramIntersectionKernel; + +/***/ }), +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const euclidean = __webpack_require__(2); + +const defaultOptions = { + sigma: 1 +}; + +class LaplacianKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; } - return str; + + compute(x, y) { + const distance = euclidean(x, y); + return Math.exp(-distance / this.sigma); + } + +} + +module.exports = LaplacianKernel; + +/***/ }), +/* 62 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const squaredEuclidean = __webpack_require__(2).squared; + +const defaultOptions = { + constant: 1 }; -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function (fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function () { - return exports.deprecate(fn, msg).apply(this, arguments); - }; +class MultiquadraticKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.constant = options.constant; } - if (process.noDeprecation === true) { - return fn; + compute(x, y) { + return Math.sqrt(squaredEuclidean(x, y) + this.constant * this.constant); } - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } +} - return deprecated; +module.exports = MultiquadraticKernel; + +/***/ }), +/* 63 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const squaredEuclidean = __webpack_require__(2).squared; + +const defaultOptions = { + constant: 1 }; -var debugs = {}; -var debugEnviron; -exports.debuglog = function (set) { - if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function () { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function () {}; - } +class RationalQuadraticKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.constant = options.constant; } - return debugs[set]; -}; -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); + compute(x, y) { + const distance = squaredEuclidean(x, y); + return 1 - distance / (distance + this.constant); } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); + } -exports.inspect = inspect; -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold': [1, 22], - 'italic': [3, 23], - 'underline': [4, 24], - 'inverse': [7, 27], - 'white': [37, 39], - 'grey': [90, 39], - 'black': [30, 39], - 'blue': [34, 39], - 'cyan': [36, 39], - 'green': [32, 39], - 'magenta': [35, 39], - 'red': [31, 39], - 'yellow': [33, 39] -}; +module.exports = RationalQuadraticKernel; -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' +/***/ }), +/* 64 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const defaultOptions = { + alpha: 0.01, + constant: -Math.E }; -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; +class SigmoidKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.alpha = options.alpha; + this.constant = options.constant; + } - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; + compute(x, y) { + var sum = 0; + + for (var i = 0; i < x.length; i++) { + sum += x[i] * y[i]; + } + + return Math.tanh(this.alpha * sum + this.constant); } -} -function stylizeNoColor(str, styleType) { - return str; } -function arrayToHash(array) { - var hash = {}; +module.exports = SigmoidKernel; - array.forEach(function (val, idx) { - hash[val] = true; - }); +/***/ }), +/* 65 */ +/***/ (function(module, exports, __webpack_require__) { - return hash; -} +"use strict"; -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && value && isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; +const ConfusionMatrix = __webpack_require__(25); + +const CV = {}; + +const combinations = __webpack_require__(66); +/** + * Performs a leave-one-out cross-validation (LOO-CV) of the given samples. In LOO-CV, 1 observation is used as the + * validation set while the rest is used as the training set. This is repeated once for each observation. LOO-CV is a + * special case of LPO-CV. @see leavePout + * @param {function} Classifier - The classifier's constructor to use for the cross validation. Expect ml-classifier + * api. + * @param {Array} features - The features for all samples of the data-set + * @param {Array} labels - The classification class of all samples of the data-set + * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated. + * @return {ConfusionMatrix} - The cross-validation confusion matrix + */ + + +CV.leaveOneOut = function (Classifier, features, labels, classifierOptions) { + if (typeof labels === 'function') { + var callback = labels; + labels = features; + features = Classifier; + return CV.leavePOut(features, labels, 1, callback); } - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); + return CV.leavePOut(Classifier, features, labels, classifierOptions, 1); +}; +/** + * Performs a leave-p-out cross-validation (LPO-CV) of the given samples. In LPO-CV, p observations are used as the + * validation set while the rest is used as the training set. This is repeated as many times as there are possible + * ways to combine p observations from the set (unordered without replacement). Be aware that for relatively small + * data-set size this can require a very large number of training and testing to do! + * @param {function} Classifier - The classifier's constructor to use for the cross validation. Expect ml-classifier + * api. + * @param {Array} features - The features for all samples of the data-set + * @param {Array} labels - The classification class of all samples of the data-set + * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated. + * @param {number} p - The size of the validation sub-samples' set + * @return {ConfusionMatrix} - The cross-validation confusion matrix + */ - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); + +CV.leavePOut = function (Classifier, features, labels, classifierOptions, p) { + if (typeof classifierOptions === 'function') { + var callback = classifierOptions; + p = labels; + labels = features; + features = Classifier; } - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); + check(features, labels); + const distinct = getDistinct(labels); + const confusionMatrix = initMatrix(distinct.length, distinct.length); + var N = features.length; + var gen = combinations(p, N); + var allIdx = new Array(N); + + for (let i = 0; i < N; i++) { + allIdx[i] = i; } - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); + for (const testIdx of gen) { + var trainIdx = allIdx.slice(); + + for (let i = testIdx.length - 1; i >= 0; i--) { + trainIdx.splice(testIdx[i], 1); } - if (isError(value)) { - return formatError(value); + + if (callback) { + validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback); + } else { + validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct); } } - var base = '', - array = false, - braces = ['{', '}']; + return new ConfusionMatrix(confusionMatrix, distinct); +}; +/** + * Performs k-fold cross-validation (KF-CV). KF-CV separates the data-set into k random equally sized partitions, and + * uses each as a validation set, with all other partitions used in the training set. Observations left over from if k + * does not divide the number of observations are left out of the cross-validation process. + * @param {function} Classifier - The classifier's to use for the cross validation. Expect ml-classifier api. + * @param {Array} features - The features for all samples of the data-set + * @param {Array} labels - The classification class of all samples of the data-set + * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated. + * @param {number} k - The number of partitions to create + * @return {ConfusionMatrix} - The cross-validation confusion matrix + */ - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; +CV.kFold = function (Classifier, features, labels, classifierOptions, k) { + if (typeof classifierOptions === 'function') { + var callback = classifierOptions; + k = labels; + labels = features; + features = Classifier; } - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } + check(features, labels); + const distinct = getDistinct(labels); + const confusionMatrix = initMatrix(distinct.length, distinct.length); + var N = features.length; + var allIdx = new Array(N); - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); + for (var i = 0; i < N; i++) { + allIdx[i] = i; } - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } + var l = Math.floor(N / k); // create random k-folds - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; + var current = []; + var folds = []; + + while (allIdx.length) { + var randi = Math.floor(Math.random() * allIdx.length); + current.push(allIdx[randi]); + allIdx.splice(randi, 1); + + if (current.length === l) { + folds.push(current); + current = []; + } } - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + if (current.length) folds.push(current); + folds = folds.slice(0, k); + + for (i = 0; i < folds.length; i++) { + var testIdx = folds[i]; + var trainIdx = []; + + for (var j = 0; j < folds.length; j++) { + if (j !== i) trainIdx = trainIdx.concat(folds[j]); + } + + if (callback) { + validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback); } else { - return ctx.stylize('[Object]', 'special'); + validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct); } } - ctx.seen.push(value); + return new ConfusionMatrix(confusionMatrix, distinct); +}; - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function (key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); +function check(features, labels) { + if (features.length !== labels.length) { + throw new Error('features and labels should have the same length'); } +} - ctx.seen.pop(); +function initMatrix(rows, columns) { + return new Array(rows).fill(0).map(() => new Array(columns).fill(0)); +} - return reduceToSingleString(output, base, braces); +function getDistinct(arr) { + var s = new Set(); + + for (let i = 0; i < arr.length; i++) { + s.add(arr[i]); + } + + return Array.from(s); } -function formatPrimitive(ctx, value) { - if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); +function validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct) { + const { + testFeatures, + trainFeatures, + testLabels, + trainLabels + } = getTrainTest(features, labels, testIdx, trainIdx); + var classifier; + + if (Classifier.prototype.train) { + classifier = new Classifier(classifierOptions); + classifier.train(trainFeatures, trainLabels); + } else { + classifier = new Classifier(trainFeatures, trainLabels, classifierOptions); } - if (isNumber(value)) return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) return ctx.stylize('null', 'null'); + + var predictedLabels = classifier.predict(testFeatures); + updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct); } -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; +function validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback) { + const { + testFeatures, + trainFeatures, + testLabels, + trainLabels + } = getTrainTest(features, labels, testIdx, trainIdx); + const predictedLabels = callback(trainFeatures, trainLabels, testFeatures); + updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct); } -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); - } else { - output.push(''); +function updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct) { + for (var i = 0; i < predictedLabels.length; i++) { + const actualIdx = distinct.indexOf(testLabels[i]); + const predictedIdx = distinct.indexOf(predictedLabels[i]); + + if (actualIdx < 0 || predictedIdx < 0) { + // eslint-disable-next-line no-console + console.warn("ignore unknown predicted label ".concat(predictedLabels[i])); } + + confusionMatrix[actualIdx][predictedIdx]++; } - keys.forEach(function (key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); - } - }); - return output; } -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; +function getTrainTest(features, labels, testIdx, trainIdx) { + return { + testFeatures: testIdx.map(function (index) { + return features[index]; + }), + trainFeatures: trainIdx.map(function (index) { + return features[index]; + }), + testLabels: testIdx.map(function (index) { + return labels[index]; + }), + trainLabels: trainIdx.map(function (index) { + return labels[index]; + }) + }; +} + +module.exports = CV; + +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { + +(function (global, factory) { + true ? factory() : undefined; +})(this, function () { + 'use strict'; + + function createCommonjsModule(fn, module) { + return module = { + exports: {} + }, fn(module, module.exports), module.exports; } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); + + var runtime = createCommonjsModule(function (module) { + /** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + !function (global) { + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined; // More compressible than void 0. + + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + var runtime = global.regeneratorRuntime; + + if (runtime) { + { + // If regeneratorRuntime is defined globally and we're in a module, + // make the exports object identical to regeneratorRuntime. + module.exports = runtime; + } // Don't bother evaluating the rest of this file if the runtime was + // already defined globally. + + return; + } // Define the runtime globally (as expected by generated code) as either + // module.exports (if we're in a module) or a new, empty object. + + + runtime = global.regeneratorRuntime = module.exports; + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + + generator._invoke = makeInvokeMethod(innerFn, self, context); + return generator; } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function (line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function (line) { - return ' ' + line; - }).join('\n'); + + runtime.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + + function tryCatch(fn, obj, arg) { + try { + return { + type: "normal", + arg: fn.call(obj, arg) + }; + } catch (err) { + return { + type: "throw", + arg: err + }; } } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - return name + ': ' + str; -} + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function (prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); + var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. - if (length > 60) { - return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; - } + function Generator() {} - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} + function GeneratorFunction() {} -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; + function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; + var IteratorPrototype = {}; -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; + IteratorPrototype[iteratorSymbol] = function () { + return this; + }; -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; + if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; + var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; + GeneratorFunctionPrototype.constructor = GeneratorFunction; + GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function (method) { + prototype[method] = function (arg) { + return this._invoke(method, arg); + }; + }); + } -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; + runtime.isGeneratorFunction = function (genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" : false; + }; -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; + runtime.mark = function (genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; + if (!(toStringTagSymbol in genFun)) { + genFun[toStringTagSymbol] = "GeneratorFunction"; + } + } -function isError(e) { - return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; + genFun.prototype = Object.create(Gp); + return genFun; + }; // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; -function isPrimitive(arg) { - return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; + runtime.awrap = function (arg) { + return { + __await: arg + }; + }; -exports.isBuffer = __webpack_require__(89); + function AsyncIterator(generator) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); -function objectToString(o) { - return Object.prototype.toString.call(o); -} + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + + if (value && typeof value === "object" && hasOwn.call(value, "__await")) { + return Promise.resolve(value.__await).then(function (value) { + invoke("next", value, resolve, reject); + }, function (err) { + invoke("throw", err, resolve, reject); + }); + } -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} + return Promise.resolve(value).then(function (unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. If the Promise is rejected, however, the + // result for this iteration will be rejected with the same + // reason. Note that rejections of yielded Promises are not + // thrown back into the generator function, as is the case + // when an awaited Promise is rejected. This difference in + // behavior between yield and await is important, because it + // allows the consumer to decide what to do with the yielded + // rejection (swallow it and continue, manually .throw it back + // into the generator, abandon iteration, whatever). With + // await, by contrast, there is no opportunity to examine the + // rejection reason outside the generator function, so the + // only option is to throw it from the await expression, and + // let the generator function handle the exception. + result.value = unwrapped; + resolve(result); + }, reject); + } + } -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + var previousPromise; -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new Promise(function (resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function () { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; + return previousPromise = // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); + } // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + + + this._invoke = enqueue; + } -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = __webpack_require__(90); + defineIteratorMethods(AsyncIterator.prototype); -exports._extend = function (origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; + AsyncIterator.prototype[asyncIteratorSymbol] = function () { + return this; + }; - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; + runtime.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + + runtime.async = function (innerFn, outerFn, self, tryLocsList) { + var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList)); + return runtime.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function (result) { + return result.done ? result.value : iter.next(); + }); + }; -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(87), __webpack_require__(88))) + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } -/***/ }), -/* 87 */ -/***/ (function(module, exports, __webpack_require__) { + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume -"use strict"; + return doneResult(); + } -var g; + context.method = method; + context.arg = arg; -// This works in non-strict mode -g = function () { - return this; -}(); + while (true) { + var delegate = context.delegate; -try { - // This works if eval is allowed (see CSP) - g = g || Function("return this")() || (1, eval)("this"); -} catch (e) { - // This works if the window reference is available - if (typeof window === "object") g = window; -} + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); -// g can still be undefined, but nothing to do about it... -// We return undefined, instead of nothing here, so it's -// easier to handle this case. if(!global) { ...} + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } -module.exports = g; + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } -/***/ }), -/* 88 */ -/***/ (function(module, exports, __webpack_require__) { + context.dispatchException(context.arg); + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } -"use strict"; + state = GenStateExecuting; + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done ? GenStateCompleted : GenStateSuspendedYield; -// shim for using process in browser -var process = module.exports = {}; + if (record.arg === ContinueSentinel) { + continue; + } -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. + return { + value: record.arg, + done: context.done + }; + } else if (record.type === "throw") { + state = GenStateCompleted; // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. -var cachedSetTimeout; -var cachedClearTimeout; + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + + + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + + if (method === undefined) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; + + if (context.method === "throw") { + if (delegate.iterator.return) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout() { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -})(); -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch (e) { - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch (e) { - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e) { - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e) { - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; + context.method = "throw"; + context.arg = new TypeError("The iterator does not provide a 'throw' method"); + } -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} + return ContinueSentinel; + } -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; + var record = tryCatch(method, delegate.iterator, context.arg); - var len = queue.length; - while (len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; + var info = record.arg; + + if (!info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). -function noop() {} + context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined; + } + } else { + // Re-yield the result returned by the delegate method. + return info; + } // The delegate iterator is finished, so forget it and continue with + // the outer generator. -process.listeners = function (name) { - return []; -}; -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; + context.delegate = null; + return ContinueSentinel; + } // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. -process.cwd = function () { - return '/'; -}; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function () { - return 0; -}; -/***/ }), -/* 89 */ -/***/ (function(module, exports, __webpack_require__) { + defineIteratorMethods(Gp); + Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. -"use strict"; + Gp[iteratorSymbol] = function () { + return this; + }; + Gp.toString = function () { + return "[object Generator]"; + }; -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; -}; + function pushTryEntry(locs) { + var entry = { + tryLoc: locs[0] + }; -/***/ }), -/* 90 */ -/***/ (function(module, exports, __webpack_require__) { + if (1 in locs) { + entry.catchLoc = locs[1]; + } -"use strict"; + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + this.tryEntries.push(entry); + } -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function TempCtor() {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; -} -/***/ }), -/* 91 */ -/***/ (function(module, exports, __webpack_require__) { + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ + tryLoc: "root" + }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } -"use strict"; + runtime.keys = function (object) { + var keys = []; + for (var key in object) { + keys.push(key); + } -var euclidean = __webpack_require__(1); -var ClusterLeaf = __webpack_require__(28); -var Cluster = __webpack_require__(14); + keys.reverse(); // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. -/** - * @private - * @param {Array >} cluster1 - * @param {Array >} cluster2 - * @param {function} disFun - * @returns {number} - */ -function simpleLink(cluster1, cluster2, disFun) { - var m = 10e100; - for (var i = 0; i < cluster1.length; i++) { - for (var j = i; j < cluster2.length; j++) { - var d = disFun(cluster1[i], cluster2[j]); - m = Math.min(d, m); - } - } - return m; -} + return function next() { + while (keys.length) { + var key = keys.pop(); -/** - * @private - * @param {Array >} cluster1 - * @param {Array >} cluster2 - * @param {function} disFun - * @returns {number} - */ -function completeLink(cluster1, cluster2, disFun) { - var m = -1; - for (var i = 0; i < cluster1.length; i++) { - for (var j = i; j < cluster2.length; j++) { - var d = disFun(cluster1[i], cluster2[j]); - m = Math.max(d, m); - } - } - return m; -} + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. -/** - * @private - * @param {Array >} cluster1 - * @param {Array >} cluster2 - * @param {function} disFun - * @returns {number} - */ -function averageLink(cluster1, cluster2, disFun) { - var m = 0; - for (var i = 0; i < cluster1.length; i++) { - for (var j = 0; j < cluster2.length; j++) { - m += disFun(cluster1[i], cluster2[j]); - } - } - return m / (cluster1.length * cluster2.length); -} -/** - * @private - * @param {Array >} cluster1 - * @param {Array >} cluster2 - * @param {function} disFun - * @returns {number} - */ -function centroidLink(cluster1, cluster2, disFun) { - var x1 = 0, - y1 = 0, - x2 = 0, - y2 = 0; - for (var i = 0; i < cluster1.length; i++) { - x1 += cluster1[i][0]; - y1 += cluster1[i][1]; - } - for (var j = 0; j < cluster2.length; j++) { - x2 += cluster2[j][0]; - y2 += cluster2[j][1]; - } - x1 /= cluster1.length; - y1 /= cluster1.length; - x2 /= cluster2.length; - y2 /= cluster2.length; - return disFun([x1, y1], [x2, y2]); -} + next.done = true; + return next; + }; + }; -/** - * @private - * @param {Array >} cluster1 - * @param {Array >} cluster2 - * @param {function} disFun - * @returns {number} - */ -function wardLink(cluster1, cluster2, disFun) { - var x1 = 0, - y1 = 0, - x2 = 0, - y2 = 0; - for (var i = 0; i < cluster1.length; i++) { - x1 += cluster1[i][0]; - y1 += cluster1[i][1]; - } - for (var j = 0; j < cluster2.length; j++) { - x2 += cluster2[j][0]; - y2 += cluster2[j][1]; - } - x1 /= cluster1.length; - y1 /= cluster1.length; - x2 /= cluster2.length; - y2 /= cluster2.length; - return disFun([x1, y1], [x2, y2]) * cluster1.length * cluster2.length / (cluster1.length + cluster2.length); -} + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; -/** - * @private - * Returns the most distant point and his distance - * @param {Array >} splitting - Clusters to split - * @param {Array >} data - Original data - * @param {function} disFun - Distance function - * @returns {{d: number, p: number}} - d: maximum difference between points, p: the point more distant - */ -function diff(splitting, data, disFun) { - var ans = { - d: 0, - p: 0 - }; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, + next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined; + next.done = true; + return next; + }; + + return next.next = next; + } + } // Return an iterator with no values. + + + return { + next: doneResult + }; + } - var Ci = new Array(splitting[0].length); - for (var e = 0; e < splitting[0].length; e++) { - Ci[e] = data[splitting[0][e]]; - } - var Cj = new Array(splitting[1].length); - for (var f = 0; f < splitting[1].length; f++) { - Cj[f] = data[splitting[1][f]]; - } + runtime.values = values; - var dist, ndist; - for (var i = 0; i < Ci.length; i++) { - dist = 0; - for (var j = 0; j < Ci.length; j++) { - if (i !== j) { - dist += disFun(Ci[i], Ci[j]); + function doneResult() { + return { + value: undefined, + done: true + }; + } + + Context.prototype = { + constructor: Context, + reset: function reset(skipTempReset) { + this.prev = 0; + this.next = 0; // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; + this.method = "next"; + this.arg = undefined; + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { + this[name] = undefined; + } } - } - dist /= Ci.length - 1; - ndist = 0; - for (var k = 0; k < Cj.length; k++) { - ndist += disFun(Ci[i], Cj[k]); - } - ndist /= Cj.length; - if (dist - ndist > ans.d) { - ans.d = dist - ndist; - ans.p = i; - } - } - return ans; -} + } + }, + stop: function stop() { + this.done = true; + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; -var defaultOptions = { - dist: euclidean, - kind: 'single' -}; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } -/** - * @private - * Intra-cluster distance - * @param {Array} index - * @param {Array} data - * @param {function} disFun - * @returns {number} - */ -function intrDist(index, data, disFun) { - var dist = 0, - count = 0; - for (var i = 0; i < index.length; i++) { - for (var j = i; j < index.length; j++) { - dist += disFun(data[index[i].index], data[index[j].index]); - count++; - } - } - return dist / count; -} + return this.rval; + }, + dispatchException: function dispatchException(exception) { + if (this.done) { + throw exception; + } -/** - * Splits the higher level clusters - * @param {Array >} data - Array of points to be clustered - * @param {json} options - * @constructor - */ -function diana(data, options) { - options = Object.assign({}, defaultOptions, options); - if (typeof options.kind === 'string') { - switch (options.kind) { - case 'single': - options.kind = simpleLink; - break; - case 'complete': - options.kind = completeLink; - break; - case 'average': - options.kind = averageLink; - break; - case 'centroid': - options.kind = centroidLink; - break; - case 'ward': - options.kind = wardLink; - break; - default: - throw new RangeError('Unknown kind of similarity'); - } - } else if (typeof options.kind !== 'function') { - throw new TypeError('Undefined kind of similarity'); - } - var tree = new Cluster(); - tree.children = new Array(data.length); - tree.index = new Array(data.length); - for (var ind = 0; ind < data.length; ind++) { - tree.children[ind] = new ClusterLeaf(ind); - tree.index[ind] = new ClusterLeaf(ind); - } - - tree.distance = intrDist(tree.index, data, options.dist); - var m, M, clId, dist, rebel; - var list = [tree]; - while (list.length > 0) { - M = 0; - clId = 0; - for (var i = 0; i < list.length; i++) { - m = 0; - for (var j = 0; j < list[i].length; j++) { - for (var l = j + 1; l < list[i].length; l++) { - m = Math.max(options.dist(data[list[i].index[j].index], data[list[i].index[l].index]), m); - } - } - if (m > M) { - M = m; - clId = i; + var context = this; + + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined; } - } - M = 0; - if (list[clId].index.length === 2) { - list[clId].children = [list[clId].index[0], list[clId].index[1]]; - list[clId].distance = options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]); - } else if (list[clId].index.length === 3) { - list[clId].children = [list[clId].index[0], list[clId].index[1], list[clId].index[2]]; - var d = [options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]), options.dist(data[list[clId].index[1].index], data[list[clId].index[2].index])]; - list[clId].distance = (d[0] + d[1]) / 2; - } else { - var C = new Cluster(); - var sG = new Cluster(); - var splitting = [new Array(list[clId].index.length), []]; - for (var spl = 0; spl < splitting[0].length; spl++) { - splitting[0][spl] = spl; + + return !!caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); } - for (var ii = 0; ii < splitting[0].length; ii++) { - dist = 0; - for (var jj = 0; jj < splitting[0].length; jj++) { - if (ii !== jj) { - dist += options.dist(data[list[clId].index[splitting[0][jj]].index], data[list[clId].index[splitting[0][ii]].index]); - } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); } - dist /= splitting[0].length - 1; - if (dist > M) { - M = dist; - rebel = ii; + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); } + } else { + throw new Error("try statement without catch or finally"); + } } - splitting[1] = [rebel]; - splitting[0].splice(rebel, 1); - dist = diff(splitting, data, options.dist); - while (dist.d > 0) { - splitting[1].push(splitting[0][dist.p]); - splitting[0].splice(dist.p, 1); - dist = diff(splitting, data, options.dist); + } + }, + abrupt: function abrupt(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + + if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; } - var fData = new Array(splitting[0].length); - C.index = new Array(splitting[0].length); - for (var e = 0; e < fData.length; e++) { - fData[e] = data[list[clId].index[splitting[0][e]].index]; - C.index[e] = list[clId].index[splitting[0][e]]; - C.children[e] = list[clId].index[splitting[0][e]]; + } + + if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + complete: function complete(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + finish: function finish(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; } - var sData = new Array(splitting[1].length); - sG.index = new Array(splitting[1].length); - for (var f = 0; f < sData.length; f++) { - sData[f] = data[list[clId].index[splitting[1][f]].index]; - sG.index[f] = list[clId].index[splitting[1][f]]; - sG.children[f] = list[clId].index[splitting[1][f]]; + } + }, + "catch": function _catch(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + + return thrown; } - C.distance = intrDist(C.index, data, options.dist); - sG.distance = intrDist(sG.index, data, options.dist); - list.push(C); - list.push(sG); - list[clId].children = [C, sG]; + } // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + + + throw new Error("illegal catch attempt"); + }, + delegateYield: function delegateYield(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined; + } + + return ContinueSentinel; } - list.splice(clId, 1); + }; + }( // In sloppy mode, unbound `this` refers to the global object, fallback to + // Function constructor if we're in global strict mode. That is sadly a form + // of indirect eval which violates Content Security Policy. + function () { + return this; + }() || Function("return this")()); + }); + /** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + // This method of obtaining a reference to the global object needs to be + // kept identical to the way it is obtained in runtime.js + + var g = function () { + return this; + }() || Function("return this")(); // Use `getOwnPropertyNames` because not all browsers support calling + // `hasOwnProperty` on the global `self` object in a worker. See #183. + + + var hadRuntime = g.regeneratorRuntime && Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0; // Save the old regeneratorRuntime in case it needs to be restored later. + + var oldRuntime = hadRuntime && g.regeneratorRuntime; // Force reevalutation of runtime.js. + + g.regeneratorRuntime = undefined; + var runtimeModule = runtime; + + if (hadRuntime) { + // Restore the original runtime. + g.regeneratorRuntime = oldRuntime; + } else { + // Remove the global property added by runtime.js. + try { + delete g.regeneratorRuntime; + } catch (e) { + g.regeneratorRuntime = undefined; } - return tree; -} + } -module.exports = diana; + var regenerator = runtimeModule; + var defaultOptions = { + mode: 'index' + }; + module.exports = + /*#__PURE__*/ + regenerator.mark(function _callee(M, N, options) { + var a, c, b, p, x, y, z, i, twiddle; + return regenerator.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + twiddle = function twiddle() { + var i, j, k; + j = 1; + + while (p[j] <= 0) { + j++; + } -/***/ }), -/* 92 */ -/***/ (function(module, exports, __webpack_require__) { + if (p[j - 1] === 0) { + for (i = j - 1; i !== 1; i--) { + p[i] = -1; + } -"use strict"; + p[j] = 0; + x = z = 0; + p[1] = 1; + y = j - 1; + } else { + if (j > 1) { + p[j - 1] = 0; + } + do { + j++; + } while (p[j] > 0); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = kmeans; + k = j - 1; + i = j; + + while (p[i] === 0) { + p[i++] = -1; + } + + if (p[i] === -1) { + p[i] = p[k]; + z = p[k] - 1; + x = i - 1; + y = k - 1; + p[k] = -1; + } else { + if (i === p[0]) { + return 0; + } else { + p[j] = p[i]; + z = p[i] - 1; + p[i] = 0; + x = j - 1; + y = i - 1; + } + } + } -var _mlDistanceEuclidean = __webpack_require__(1); + return 1; + }; -var _mlDistanceEuclidean2 = _interopRequireDefault(_mlDistanceEuclidean); + options = Object.assign({}, defaultOptions, options); + a = new Array(N); + c = new Array(M); + b = new Array(N); + p = new Array(N + 2); // init a and b -var _utils = __webpack_require__(30); + for (i = 0; i < N; i++) { + a[i] = i; + if (i < N - M) b[i] = 0;else b[i] = 1; + } // init c -var _initialization = __webpack_require__(94); -var _KMeansResult = __webpack_require__(96); + for (i = 0; i < M; i++) { + c[i] = N - M + i; + } // init p -var _KMeansResult2 = _interopRequireDefault(_KMeansResult); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (i = 0; i < p.length; i++) { + if (i === 0) p[i] = N + 1;else if (i <= N - M) p[i] = 0;else if (i <= N) p[i] = i - N + M;else p[i] = -2; + } -var defaultOptions = { - maxIterations: 100, - tolerance: 1e-6, - withIterations: false, - initialization: 'kmeans++', - distanceFunction: _mlDistanceEuclidean2.default.squared -}; + if (!(options.mode === 'index')) { + _context.next = 20; + break; + } -/** - * Each step operation for kmeans - * @ignore - * @param {Array>} centers - K centers in format [x,y,z,...] - * @param {Array>} data - Points [x,y,z,...] to cluster - * @param {Array} clusterID - Cluster identifier for each data dot - * @param {number} K - Number of clusters - * @param {object} [options] - Option object - * @param {number} iterations - Current number of iterations - * @return {KMeansResult} - */ -function step(centers, data, clusterID, K, options, iterations) { - clusterID = (0, _utils.updateClusterID)(data, centers, clusterID, options.distanceFunction); - var newCenters = (0, _utils.updateCenters)(centers, data, clusterID, K); - var converged = (0, _utils.hasConverged)(newCenters, centers, options.distanceFunction, options.tolerance); - return new _KMeansResult2.default(clusterID, newCenters, converged, iterations, options.distanceFunction); -} + _context.next = 12; + return c.slice(); -/** - * Generator version for the algorithm - * @ignore - * @param {Array>} centers - K centers in format [x,y,z,...] - * @param {Array>} data - Points [x,y,z,...] to cluster - * @param {Array} clusterID - Cluster identifier for each data dot - * @param {number} K - Number of clusters - * @param {object} [options] - Option object - */ -function* kmeansGenerator(centers, data, clusterID, K, options) { - var converged = false; - var stepNumber = 0; - var stepResult; - while (!converged && stepNumber < options.maxIterations) { - stepResult = step(centers, data, clusterID, K, options, ++stepNumber); - yield stepResult.computeInformation(data); - converged = stepResult.converged; - centers = stepResult.centroids; - } -} + case 12: + if (!twiddle()) { + _context.next = 18; + break; + } -/** - * K-means algorithm - * @param {Array>} data - Points in the format to cluster [x,y,z,...] - * @param {number} K - Number of clusters - * @param {object} [options] - Option object - * @param {number} [options.maxIterations = 100] - Maximum of iterations allowed - * @param {number} [options.tolerance = 1e-6] - Error tolerance - * @param {boolean} [options.withIterations = false] - Store clusters and centroids for each iteration - * @param {function} [options.distanceFunction = squaredDistance] - Distance function to use between the points - * @param {number} [options.seed] - Seed for random initialization. - * @param {string|Array>} [options.initialization = 'kmeans++'] - K centers in format [x,y,z,...] or a method for initialize the data: - * * You can either specify your custom start centroids, or select one of the following initialization method: - * * `'kmeans++'` will use the kmeans++ method as described by http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf - * * `'random'` will choose K random different values. - * * `'mostDistant'` will choose the more distant points to a first random pick - * @return {KMeansResult} - Cluster identifier for each data dot and centroids with the following fields: - * * `'clusters'`: Array of indexes for the clusters. - * * `'centroids'`: Array with the resulting centroids. - * * `'iterations'`: Number of iterations that took to converge - */ -function kmeans(data, K, options) { - options = Object.assign({}, defaultOptions, options); + c[z] = a[x]; + _context.next = 16; + return c.slice(); - if (K <= 0 || K > data.length || !Number.isInteger(K)) { - throw new Error('K should be a positive integer smaller than the number of points'); - } + case 16: + _context.next = 12; + break; - var centers; - if (Array.isArray(options.initialization)) { - if (options.initialization.length !== K) { - throw new Error('The initial centers should have the same length as K'); - } else { - centers = options.initialization; - } - } else { - switch (options.initialization) { - case 'kmeans++': - centers = (0, _initialization.kmeanspp)(data, K, options); - break; - case 'random': - centers = (0, _initialization.random)(data, K, options.seed); - break; - case 'mostDistant': - centers = (0, _initialization.mostDistant)(data, K, (0, _utils.calculateDistanceMatrix)(data, options.distanceFunction), options.seed); - break; - default: - throw new Error(`Unknown initialization method: "${options.initialization}"`); - } - } + case 18: + _context.next = 33; + break; - // infinite loop until convergence - if (options.maxIterations === 0) { - options.maxIterations = Number.MAX_VALUE; - } + case 20: + if (!(options.mode === 'mask')) { + _context.next = 32; + break; + } - var clusterID = new Array(data.length); - if (options.withIterations) { - return kmeansGenerator(centers, data, clusterID, K, options); - } else { - var converged = false; - var stepNumber = 0; - var stepResult; - while (!converged && stepNumber < options.maxIterations) { - stepResult = step(centers, data, clusterID, K, options, ++stepNumber); - converged = stepResult.converged; - centers = stepResult.centroids; - } - return stepResult.computeInformation(data); - } -} + _context.next = 23; + return b.slice(); + + case 23: + if (!twiddle()) { + _context.next = 30; + break; + } + + b[x] = 1; + b[y] = 0; + _context.next = 28; + return b.slice(); + + case 28: + _context.next = 23; + break; + + case 30: + _context.next = 33; + break; + + case 32: + throw new Error('Invalid mode'); + + case 33: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + }); +}); /***/ }), -/* 93 */ +/* 67 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +"use strict"; + + +const Matrix = __webpack_require__(0).Matrix; + +const Layer = __webpack_require__(26); +const OutputLayer = __webpack_require__(68); -var squaredDistance = __webpack_require__(1).squared; +const Utils = __webpack_require__(27); -var defaultOptions = { - distanceFunction: squaredDistance, - similarityFunction: false, - returnVector: false -}; +const ACTIVATION_FUNCTIONS = __webpack_require__(28); -/** - * Find the nearest vector in a list to a sample vector - * @param {Array>} listVectors - List of vectors with same dimensions - * @param {Array} vector - Reference vector to "classify" - * @param {object} [options] - Options object - * @param {function} [options.distanceFunction = squaredDistance] - Function that receives two vectors and return their distance value as number - * @param {function} [options.similarityFunction = undefined] - Function that receives two vectors and return their similarity value as number - * @param {boolean} [options.returnVector = false] - Return the nearest vector instead of its index - * @return {number|Array} - The index or the content of the nearest vector - */ -function nearestVector(listVectors, vector, options) { - options = options || defaultOptions; - var distanceFunction = options.distanceFunction || defaultOptions.distanceFunction; - var similarityFunction = options.similarityFunction || defaultOptions.similarityFunction; - var returnVector = options.returnVector || defaultOptions.returnVector; - - var vectorIndex = -1; - if (typeof similarityFunction === 'function') { - - // maximum similarity - var maxSim = Number.MIN_VALUE; - for (var j = 0; j < listVectors.length; j++) { - var sim = similarityFunction(vector, listVectors[j]); - if (sim > maxSim) { - maxSim = sim; - vectorIndex = j; - } - } - } else if (typeof distanceFunction === 'function') { - - // minimum distance - var minDist = Number.MAX_VALUE; - for (var i = 0; i < listVectors.length; i++) { - var dist = distanceFunction(vector, listVectors[i]); - if (dist < minDist) { - minDist = dist; - vectorIndex = i; - } - } - } else { - throw new Error('A similarity or distance function it\'s required'); - } +class FeedForwardNeuralNetworks { + /** + * Create a new Feedforword neural network model. + * @class FeedForwardNeuralNetworks + * @param {object} [options] + * @param {Array} [options.hiddenLayers=[10]] - Array that contains the sizes of the hidden layers. + * @param {number} [options.iterations=50] - Number of iterations at the training step. + * @param {number} [options.learningRate=0.01] - Learning rate of the neural net (also known as epsilon). + * @param {number} [options.regularization=0.01] - Regularization parameter af the neural net. + * @param {string} [options.activation='tanh'] - activation function to be used. (options: 'tanh'(default), + * 'identity', 'logistic', 'arctan', 'softsign', 'relu', 'softplus', 'bent', 'sinusoid', 'sinc', 'gaussian'). + * (single-parametric options: 'parametric-relu', 'exponential-relu', 'soft-exponential'). + * @param {number} [options.activationParam=1] - if the selected activation function needs a parameter. + */ + constructor(options) { + options = options || {}; + + if (options.model) { + // load network + this.hiddenLayers = options.hiddenLayers; + this.iterations = options.iterations; + this.learningRate = options.learningRate; + this.regularization = options.regularization; + this.dicts = options.dicts; + this.activation = options.activation; + this.activationParam = options.activationParam; + this.model = new Array(options.layers.length); + + for (var i = 0; i < this.model.length - 1; ++i) { + this.model[i] = Layer.load(options.layers[i]); + } - if (returnVector) { - return listVectors[vectorIndex]; + this.model[this.model.length - 1] = OutputLayer.load(options.layers[this.model.length - 1]); } else { - return vectorIndex; + // default constructor + this.hiddenLayers = options.hiddenLayers || [10]; + this.iterations = options.iterations || 50; + this.learningRate = options.learningRate || 0.01; + this.regularization = options.regularization || 0.01; + this.activation = options.activation || 'tanh'; + this.activationParam = options.activationParam || 1; + + if (!(this.activation in Object.keys(ACTIVATION_FUNCTIONS))) { + this.activation = 'tanh'; + } } -} + } + /** + * @private + * Function that build and initialize the neural net. + * @param {number} inputSize - total of features to fit. + * @param {number} outputSize - total of labels of the prediction set. + */ -module.exports = nearestVector; -/***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { + buildNetwork(inputSize, outputSize) { + var size = 2 + (this.hiddenLayers.length - 1); + this.model = new Array(size); // input layer + + this.model[0] = new Layer({ + inputSize: inputSize, + outputSize: this.hiddenLayers[0], + activation: this.activation, + activationParam: this.activationParam, + regularization: this.regularization, + epsilon: this.learningRate + }); // hidden layers + + for (var i = 1; i < this.hiddenLayers.length; ++i) { + this.model[i] = new Layer({ + inputSize: this.hiddenLayers[i - 1], + outputSize: this.hiddenLayers[i], + activation: this.activation, + activationParam: this.activationParam, + regularization: this.regularization, + epsilon: this.learningRate + }); + } // output layer + + + this.model[size - 1] = new OutputLayer({ + inputSize: this.hiddenLayers[this.hiddenLayers.length - 1], + outputSize: outputSize, + activation: this.activation, + activationParam: this.activationParam, + regularization: this.regularization, + epsilon: this.learningRate + }); + } + /** + * Train the neural net with the given features and labels. + * @param {Matrix|Array} features + * @param {Matrix|Array} labels + */ -"use strict"; + train(features, labels) { + features = Matrix.checkMatrix(features); + this.dicts = Utils.dictOutputs(labels); + var inputSize = features.columns; + var outputSize = Object.keys(this.dicts.inputs).length; + this.buildNetwork(inputSize, outputSize); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.random = random; -exports.mostDistant = mostDistant; -exports.kmeanspp = kmeanspp; + for (var i = 0; i < this.iterations; ++i) { + var probabilities = this.propagate(features); + this.backpropagation(features, labels, probabilities); + } + } + /** + * @private + * Propagate the input(training set) and retrives the probabilities of each class. + * @param {Matrix} X + * @return {Matrix} probabilities of each class. + */ -var _mlRandom = __webpack_require__(31); -var _mlRandom2 = _interopRequireDefault(_mlRandom); + propagate(X) { + var input = X; -var _mlDistanceEuclidean = __webpack_require__(1); + for (var i = 0; i < this.model.length; ++i) { + //console.log(i); + input = this.model[i].forward(input); + } // get probabilities -var _mlMatrix = __webpack_require__(0); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return input.divColumnVector(Utils.sumRow(input)); + } + /** + * @private + * Function that applies the backpropagation algorithm on each layer of the network + * in order to fit the features and labels. + * @param {Matrix} features + * @param {Array} labels + * @param {Matrix} probabilities - probabilities of each class of the feature set. + */ -/** - * Choose K different random points from the original data - * @ignore - * @param {Array>} data - Points in the format to cluster [x,y,z,...] - * @param {number} K - number of clusters - * @param {number} seed - seed for random number generation - * @return {Array>} - Initial random points - */ -function random(data, K, seed) { - var random = new _mlRandom2.default(seed); - return random.choice(data, { size: K }); -} -/** - * Chooses the most distant points to a first random pick - * @ignore - * @param {Array>} data - Points in the format to cluster [x,y,z,...] - * @param {number} K - number of clusters - * @param {Array>} distanceMatrix - matrix with the distance values - * @param {number} seed - seed for random number generation - * @return {Array>} - Initial random points - */ -function mostDistant(data, K, distanceMatrix, seed) { - var random = new _mlRandom2.default(seed); - var ans = new Array(K); - // chooses a random point as initial cluster - ans[0] = Math.floor(random.random() * data.length); + backpropagation(features, labels, probabilities) { + for (var i = 0; i < probabilities.length; ++i) { + probabilities[i][this.dicts.inputs[labels[i]]] -= 1; + } // remember, the last delta doesn't matter - if (K > 1) { - // chooses the more distant point - var maxDist = { dist: -1, index: -1 }; - for (var l = 0; l < data.length; ++l) { - if (distanceMatrix[ans[0]][l] > maxDist.dist) { - maxDist.dist = distanceMatrix[ans[0]][l]; - maxDist.index = l; - } - } - ans[1] = maxDist.index; - if (K > 2) { - // chooses the set of points that maximises the min distance - for (var k = 2; k < K; ++k) { - var center = { dist: -1, index: -1 }; - for (var m = 0; m < data.length; ++m) { - // minimum distance to centers - var minDistCent = { dist: Number.MAX_VALUE, index: -1 }; - for (var n = 0; n < k; ++n) { - if (distanceMatrix[n][m] < minDistCent.dist && ans.indexOf(m) === -1) { - minDistCent = { - dist: distanceMatrix[n][m], - index: m - }; - } - } + var delta = probabilities; - if (minDistCent.dist !== Number.MAX_VALUE && minDistCent.dist > center.dist) { - center = Object.assign({}, minDistCent); - } - } + for (i = this.model.length - 1; i >= 0; --i) { + var a = i > 0 ? this.model[i - 1].a : features; + delta = this.model[i].backpropagation(delta, a); + } - ans[k] = center.index; - } + for (i = 0; i < this.model.length; ++i) { + this.model[i].update(); } } + /** + * Predict the output given the feature set. + * @param {Array|Matrix} features + * @return {Array} + */ - return ans.map(index => data[index]); -} -// Implementation inspired from scikit -function kmeanspp(X, K, options = {}) { - X = new _mlMatrix.Matrix(X); - var nSamples = X.length; - var random = new _mlRandom2.default(options.seed); - // Set the number of trials - var centers = []; - var localTrials = options.localTrials || 2 + Math.floor(Math.log(K)); - - // Pick the first center at random from the dataset - var firstCenterIdx = random.randInt(nSamples); - centers.push(X[firstCenterIdx].slice()); - - // Init closest distances - var closestDistSquared = [X.map(x => (0, _mlDistanceEuclidean.squared)(x, centers[0]))]; - var cumSumClosestDistSquared = [cumSum(closestDistSquared[0])]; - var factor = 1 / cumSumClosestDistSquared[0][nSamples - 1]; - var probabilities = _mlMatrix.Matrix.mul(closestDistSquared, factor); - - // Iterate over the remaining centers - for (var i = 1; i < K; i++) { - var candidateIdx = random.choice(nSamples, { - replace: true, - size: localTrials, - probabilities: probabilities[0] - }); + predict(features) { + features = Matrix.checkMatrix(features); + var outputs = new Array(features.rows); + var probabilities = this.propagate(features); - var candidates = X.selection(candidateIdx, range(X[0].length)); - var distanceToCandidates = euclidianDistances(candidates, X); + for (var i = 0; i < features.rows; ++i) { + outputs[i] = this.dicts.outputs[probabilities.maxRowIndex(i)[1]]; + } - var bestCandidate = void 0; - var bestPot = void 0; - var bestDistSquared = void 0; + return outputs; + } + /** + * Export the current model to JSON. + * @return {object} model + */ - for (var j = 0; j < localTrials; j++) { - var newDistSquared = _mlMatrix.Matrix.min(closestDistSquared, [distanceToCandidates[j]]); - var newPot = newDistSquared.sum(); - if (bestCandidate === undefined || newPot < bestPot) { - bestCandidate = candidateIdx[j]; - bestPot = newPot; - bestDistSquared = newDistSquared; - } + + toJSON() { + var model = { + model: 'FNN', + hiddenLayers: this.hiddenLayers, + iterations: this.iterations, + learningRate: this.learningRate, + regularization: this.regularization, + activation: this.activation, + activationParam: this.activationParam, + dicts: this.dicts, + layers: new Array(this.model.length) + }; + + for (var i = 0; i < this.model.length; ++i) { + model.layers[i] = this.model[i].toJSON(); } - centers[i] = X[bestCandidate].slice(); - closestDistSquared = bestDistSquared; - cumSumClosestDistSquared = [cumSum(closestDistSquared[0])]; - probabilities = _mlMatrix.Matrix.mul(closestDistSquared, 1 / cumSumClosestDistSquared[0][nSamples - 1]); + + return model; } - return centers; -} + /** + * Load a Feedforward Neural Network with the current model. + * @param {object} model + * @return {FeedForwardNeuralNetworks} + */ -function euclidianDistances(A, B) { - var result = new _mlMatrix.Matrix(A.length, B.length); - for (var i = 0; i < A.length; i++) { - for (var j = 0; j < B.length; j++) { - result.set(i, j, (0, _mlDistanceEuclidean.squared)(A.getRow(i), B.getRow(j))); + + static load(model) { + if (model.model !== 'FNN') { + throw new RangeError('the current model is not a feed forward network'); } - } - return result; -} -function range(l) { - var r = []; - for (var i = 0; i < l; i++) { - r.push(i); + return new FeedForwardNeuralNetworks(model); } - return r; -} -function cumSum(arr) { - var cumSum = [arr[0]]; - for (var i = 1; i < arr.length; i++) { - cumSum[i] = cumSum[i - 1] + arr[i]; - } - return cumSum; } +module.exports = FeedForwardNeuralNetworks; + /***/ }), -/* 95 */ +/* 68 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -var PROB_TOLERANCE = 0.00000001; -function randomChoice(values, options = {}, random = Math.random) { - var _options$size = options.size, - size = _options$size === undefined ? 1 : _options$size, - _options$replace = options.replace, - replace = _options$replace === undefined ? false : _options$replace, - probabilities = options.probabilities; - - var valuesArr = void 0; - var cumSum = void 0; - if (typeof values === 'number') { - valuesArr = getArray(values); - } else { - valuesArr = values.slice(); - } - if (probabilities) { - if (!replace) { - throw new Error('choice with probabilities and no replacement is not implemented'); - } - // check input is sane - if (probabilities.length !== valuesArr.length) { - throw new Error('the length of probabilities option should be equal to the number of choices'); - } - cumSum = [probabilities[0]]; - for (var i = 1; i < probabilities.length; i++) { - cumSum[i] = cumSum[i - 1] + probabilities[i]; - } - if (Math.abs(1 - cumSum[cumSum.length - 1]) > PROB_TOLERANCE) { - throw new Error(`probabilities should sum to 1, but instead sums to ${cumSum[cumSum.length - 1]}`); - } - } - if (replace === false && size > valuesArr.length) { - throw new Error('size option is too large'); - } - var result = []; - for (var _i = 0; _i < size; _i++) { - var index = randomIndex(valuesArr.length, random, cumSum); - result.push(valuesArr[index]); - if (!replace) { - valuesArr.splice(index, 1); - } - } - return result; -} -function getArray(n) { - var arr = []; - for (var i = 0; i < n; i++) { - arr.push(i); - } - return arr; -} -function randomIndex(n, random, cumSum) { - var rand = random(); - if (!cumSum) { - return Math.floor(rand * n); - } else { - var idx = 0; - while (rand > cumSum[idx]) { - idx++; - } - return idx; +var Layer = __webpack_require__(26); + +class OutputLayer extends Layer { + constructor(options) { + super(options); + + this.activationFunction = function (i, j) { + this[i][j] = Math.exp(this[i][j]); + }; + } + + static load(model) { + if (model.model !== 'Layer') { + throw new RangeError('the current model is not a Layer model'); } + + return new OutputLayer(model); + } + } -exports.default = randomChoice; + +module.exports = OutputLayer; /***/ }), -/* 96 */ +/* 69 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); +var NodeSquare = __webpack_require__(29), + NodeHexagonal = __webpack_require__(70); -var _utils = __webpack_require__(30); +var defaultOptions = { + fields: 3, + randomizer: Math.random, + distance: squareEuclidean, + iterations: 10, + learningRate: 0.1, + gridType: 'rect', + torus: true, + method: 'random' +}; -var distanceSymbol = Symbol('distance'); +function SOM(x, y, options, reload) { + this.x = x; + this.y = y; + options = options || {}; + this.options = {}; + + for (var i in defaultOptions) { + if (options.hasOwnProperty(i)) { + this.options[i] = options[i]; + } else { + this.options[i] = defaultOptions[i]; + } + } -class KMeansResult { - /** - * Result of the kmeans algorithm - * @param {Array} clusters - the cluster identifier for each data dot - * @param {Array>} centroids - the K centers in format [x,y,z,...], the error and size of the cluster - * @param {boolean} converged - Converge criteria satisfied - * @param {number} iterations - Current number of iterations - * @param {function} distance - (*Private*) Distance function to use between the points - * @constructor - */ - constructor(clusters, centroids, converged, iterations, distance) { - this.clusters = clusters; - this.centroids = centroids; - this.converged = converged; - this.iterations = iterations; - this[distanceSymbol] = distance; + if (typeof this.options.fields === 'number') { + this.numWeights = this.options.fields; + } else if (Array.isArray(this.options.fields)) { + this.numWeights = this.options.fields.length; + var converters = getConverters(this.options.fields); + this.extractor = converters.extractor; + this.creator = converters.creator; + } else { + throw new Error('Invalid fields definition'); } - /** - * Allows to compute for a new array of points their cluster id - * @param {Array>} data - the [x,y,z,...] points to cluster - * @return {Array} - cluster id for each point - */ - nearest(data) { - var clusterID = new Array(data.length); - var centroids = this.centroids.map(function (centroid) { - return centroid.centroid; - }); - return (0, _utils.updateClusterID)(data, centroids, clusterID, this[distanceSymbol]); + if (this.options.gridType === 'rect') { + this.nodeType = NodeSquare; + this.gridDim = { + x: x, + y: y + }; + } else { + this.nodeType = NodeHexagonal; + var hx = this.x - Math.floor(this.y / 2); + this.gridDim = { + x: hx, + y: this.y, + z: -(0 - hx - this.y) + }; } - /** - * Returns a KMeansResult with the error and size of the cluster - * @ignore - * @param {Array>} data - the [x,y,z,...] points to cluster - * @return {KMeansResult} - */ - computeInformation(data) { - var enrichedCentroids = this.centroids.map(function (centroid) { - return { - centroid: centroid, - error: 0, - size: 0 - }; - }); + this.torus = this.options.torus; + this.distanceMethod = this.torus ? 'getDistanceTorus' : 'getDistance'; + this.distance = this.options.distance; + this.maxDistance = getMaxDistance(this.distance, this.numWeights); - for (var i = 0; i < data.length; i++) { - enrichedCentroids[this.clusters[i]].error += this[distanceSymbol](data[i], this.centroids[this.clusters[i]]); - enrichedCentroids[this.clusters[i]].size++; + if (reload === true) { + // For model loading + this.done = true; + return; + } + + if (!(x > 0 && y > 0)) { + throw new Error('x and y must be positive'); + } + + this.times = { + findBMU: 0, + adjust: 0 + }; + this.randomizer = this.options.randomizer; + this.iterationCount = 0; + this.iterations = this.options.iterations; + this.startLearningRate = this.learningRate = this.options.learningRate; + this.mapRadius = Math.floor(Math.max(x, y) / 2); + this.algorithmMethod = this.options.method; + + this._initNodes(); + + this.done = false; +} + +SOM.load = function loadModel(model, distance) { + if (model.name === 'SOM') { + var x = model.data.length, + y = model.data[0].length; + + if (distance) { + model.options.distance = distance; + } else if (model.options.distance) { + model.options.distance = eval('(' + model.options.distance + ')'); + } + + var som = new SOM(x, y, model.options, true); + som.nodes = new Array(x); + + for (var i = 0; i < x; i++) { + som.nodes[i] = new Array(y); + + for (var j = 0; j < y; j++) { + som.nodes[i][j] = new som.nodeType(i, j, model.data[i][j], som); + } + } + + return som; + } else { + throw new Error('expecting a SOM model'); + } +}; + +SOM.prototype.export = function exportModel(includeDistance) { + if (!this.done) { + throw new Error('model is not ready yet'); + } + + var model = { + name: 'SOM' + }; + model.options = { + fields: this.options.fields, + gridType: this.options.gridType, + torus: this.options.torus + }; + model.data = new Array(this.x); + + for (var i = 0; i < this.x; i++) { + model.data[i] = new Array(this.y); + + for (var j = 0; j < this.y; j++) { + model.data[i][j] = this.nodes[i][j].weights; } + } - for (var j = 0; j < this.centroids.length; j++) { - if (enrichedCentroids[j].size) { - enrichedCentroids[j].error /= enrichedCentroids[j].size; - } else { - enrichedCentroids[j].error = null; + if (includeDistance) { + model.options.distance = this.distance.toString(); + } + + return model; +}; + +SOM.prototype._initNodes = function initNodes() { + var now = Date.now(), + i, + j, + k; + this.nodes = new Array(this.x); + + for (i = 0; i < this.x; i++) { + this.nodes[i] = new Array(this.y); + + for (j = 0; j < this.y; j++) { + var weights = new Array(this.numWeights); + + for (k = 0; k < this.numWeights; k++) { + weights[k] = this.randomizer(); } + + this.nodes[i][j] = new this.nodeType(i, j, weights, this); } + } + + this.times.initNodes = Date.now() - now; +}; - return new KMeansResult(this.clusters, enrichedCentroids, this.converged, this.iterations, this[distanceSymbol]); +SOM.prototype.setTraining = function setTraining(trainingSet) { + if (this.trainingSet) { + throw new Error('training set has already been set'); } -} -exports.default = KMeansResult; -/***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { + var now = Date.now(); + var convertedSet = trainingSet; + var i, + l = trainingSet.length; -"use strict"; + if (this.extractor) { + convertedSet = new Array(l); + for (i = 0; i < l; i++) { + convertedSet[i] = this.extractor(trainingSet[i]); + } + } -var Kernel = __webpack_require__(15); -var stat = __webpack_require__(4).array; + this.numIterations = this.iterations * l; -var defaultOptions = { - C: 1, - tol: 1e-4, - maxPasses: 10, - maxIterations: 10000, - kernel: 'linear', - alphaTol: 1e-6, - random: Math.random, - whitening: true + if (this.algorithmMethod === 'random') { + this.timeConstant = this.numIterations / Math.log(this.mapRadius); + } else { + this.timeConstant = l / Math.log(this.mapRadius); + } + + this.trainingSet = convertedSet; + this.times.setTraining = Date.now() - now; }; -/** - * Simplified version of the Sequential Minimal Optimization algorithm for training - * support vector machines - * @param {{Object}} options - SVM options - * @param {Number} [options.C=1] - regularization parameter - * @param {Number} [options.tol=1e-4] - numerical tolerance - * @param {Number} [options.alphaTol=1e-6] - alpha tolerance, threshold to decide support vectors - * @param {Number} [options.maxPasses=10] - max number of times to iterate over alphas without changing - * @param {Number} [options.maxIterations=10000] - max number of iterations - * @param {String} [options.kernel=linear] - the kind of kernel. {@link https://github.com/mljs/kernel/tree/1252de5f9012776e6e0eb06c7b434b8631fb21f0 List of kernels} - * @param {Function} [options.random=Math.random] - custom random number generator - * @constructor - */ -function SVM(options) { - this.options = Object.assign({}, defaultOptions, options); +SOM.prototype.trainOne = function trainOne() { + if (this.done) { + return false; + } else if (this.numIterations-- > 0) { + var neighbourhoodRadius, trainingValue, trainingSetFactor; - this.kernel = new Kernel(this.options.kernel, this.options.kernelOptions); - this.b = 0; -} + if (this.algorithmMethod === 'random') { + // Pick a random value of the training set at each step + neighbourhoodRadius = this.mapRadius * Math.exp(-this.iterationCount / this.timeConstant); + trainingValue = getRandomValue(this.trainingSet, this.randomizer); -/** - * Train the SVM model - * @param {Array >} features - training data features - * @param {Array } labels - training data labels in the domain {1,-1} - */ -SVM.prototype.train = function (features, labels) { - if (features.length !== labels.length) { - throw new Error('Features and labels should have the same length'); - } - if (features.length < 2) { - throw new Error('Cannot train with less than 2 observations'); - } - this._trained = false; - this._loaded = false; - this.N = labels.length; - this.D = features[0].length; - if (this.options.whitening) { - this.X = new Array(this.N); - for (var i = 0; i < this.N; i++) { - this.X[i] = new Array(this.D); - } - this.minMax = new Array(this.D); - // Apply normalization and keep normalization parameters - for (var j = 0; j < this.D; j++) { - var d = new Array(this.N); - for (i = 0; i < this.N; i++) { - d[i] = features[i][j]; - } - this.minMax[j] = stat.minMax(d); - for (i = 0; i < this.N; i++) { - this.X[i][j] = (features[i][j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min); - } - } - } else { - this.X = features; - } - this.Y = labels; - this.b = 0; - this.W = undefined; - - var kernel = this.kernel.compute(this.X); - var m = labels.length; - var alpha = new Array(m).fill(0); - this.alphas = alpha; - for (var a = 0; a < m; a++) { - alpha[a] = 0; - }var b1 = 0, - b2 = 0, - iter = 0, - passes = 0, - Ei = 0, - Ej = 0, - ai = 0, - aj = 0, - L = 0, - H = 0, - eta = 0; - - while (passes < this.options.maxPasses && iter < this.options.maxIterations) { - var numChange = 0; - for (i = 0; i < m; i++) { - Ei = this._marginOnePrecomputed(i, kernel) - labels[i]; - if (labels[i] * Ei < -this.options.tol && alpha[i] < this.options.C || labels[i] * Ei > this.options.tol && alpha[i] > 0) { - j = i; - while (j === i) { - j = Math.floor(this.options.random() * m); - }Ej = this._marginOnePrecomputed(j, kernel) - labels[j]; - ai = alpha[i]; - aj = alpha[j]; - if (labels[i] === labels[j]) { - L = Math.max(0, ai + aj - this.options.C); - H = Math.min(this.options.C, ai + aj); - } else { - L = Math.max(0, aj - ai); - H = Math.min(this.options.C, this.options.C + aj + ai); - } - if (Math.abs(L - H) < 1e-4) continue; - - eta = 2 * kernel[i][j] - kernel[i][i] - kernel[j][j]; - if (eta >= 0) continue; - var newaj = alpha[j] - labels[j] * (Ei - Ej) / eta; - if (newaj > H) newaj = H;else if (newaj < L) newaj = L; - if (Math.abs(aj - newaj) < 10e-4) continue; - alpha[j] = newaj; - alpha[i] = alpha[i] + labels[i] * labels[j] * (aj - newaj); - b1 = this.b - Ei - labels[i] * (alpha[i] - ai) * kernel[i][i] - labels[j] * (alpha[j] - aj) * kernel[i][j]; - b2 = this.b - Ej - labels[i] * (alpha[i] - ai) * kernel[i][j] - labels[j] * (alpha[j] - aj) * kernel[j][j]; - this.b = (b1 + b2) / 2; - if (alpha[i] < this.options.C && alpha[i] > 0) this.b = b1; - if (alpha[j] < this.options.C && alpha[j] > 0) this.b = b2; - numChange += 1; - } - } - iter++; - if (numChange === 0) passes += 1;else passes = 0; - } - if (iter === this.options.maxIterations) { - throw new Error('max iterations reached'); - } + this._adjust(trainingValue, neighbourhoodRadius); - this.iterations = iter; + this.learningRate = this.startLearningRate * Math.exp(-this.iterationCount / this.numIterations); + } else { + // Get next input vector + trainingSetFactor = -Math.floor(this.iterationCount / this.trainingSet.length); + neighbourhoodRadius = this.mapRadius * Math.exp(trainingSetFactor / this.timeConstant); + trainingValue = this.trainingSet[this.iterationCount % this.trainingSet.length]; - // Compute the weights (useful for fast decision on new test instances when linear SVM) - if (this.options.kernel === 'linear') { - this.W = new Array(this.D); - for (var r = 0; r < this.D; r++) { - this.W[r] = 0; - for (var w = 0; w < m; w++) { - this.W[r] += labels[w] * alpha[w] * this.X[w][r]; - } - } - } + this._adjust(trainingValue, neighbourhoodRadius); - // Keep only support vectors - // It will compute decision on new test instances faster - // We also keep the index of the support vectors - // in the original data - var nX = []; - var nY = []; - var nAlphas = []; - this._supportVectorIdx = []; - for (i = 0; i < this.N; i++) { - if (this.alphas[i] > this.options.alphaTol) { - nX.push(this.X[i]); - nY.push(labels[i]); - nAlphas.push(this.alphas[i]); - this._supportVectorIdx.push(i); - } + if ((this.iterationCount + 1) % this.trainingSet.length === 0) { + this.learningRate = this.startLearningRate * Math.exp(trainingSetFactor / Math.floor(this.numIterations / this.trainingSet.length)); + } } - this.X = nX; - this.Y = nY; - this.N = nX.length; - this.alphas = nAlphas; - // A flag to say this SVM has been trained - this._trained = true; + this.iterationCount++; + return true; + } else { + this.done = true; + return false; + } }; -/** - * Get prediction ({-1,1}) given one observation's features. - * @private - * @param p The observation's features. - * @returns {number} Classification result ({-1,1}) - */ -SVM.prototype.predictOne = function (p) { - var margin = this.marginOne(p); - return margin > 0 ? 1 : -1; -}; +SOM.prototype._adjust = function adjust(trainingValue, neighbourhoodRadius) { + var now = Date.now(), + x, + y, + dist, + influence; + + var bmu = this._findBestMatchingUnit(trainingValue); + + var now2 = Date.now(); + this.times.findBMU += now2 - now; + var radiusLimit = Math.floor(neighbourhoodRadius); + var xMin = bmu.x - radiusLimit, + xMax = bmu.x + radiusLimit, + yMin = bmu.y - radiusLimit, + yMax = bmu.y + radiusLimit; + + for (x = xMin; x <= xMax; x++) { + var theX = x; + + if (x < 0) { + theX += this.x; + } else if (x >= this.x) { + theX -= this.x; + } + + for (y = yMin; y <= yMax; y++) { + var theY = y; + + if (y < 0) { + theY += this.y; + } else if (y >= this.y) { + theY -= this.y; + } -/** - * Predict the classification outcome of a trained svm given one or several observations' features. - * @param {Array} features - The observation(s)' features - * @returns {Array|Number} An array of {-1, 1} if several observations are given or a number if one observation - * is given - */ -SVM.prototype.predict = function (features) { - if (!this._trained && !this._loaded) throw new Error('Cannot predict, you need to train the SVM first'); - if (Array.isArray(features) && Array.isArray(features[0])) { - return features.map(this.predictOne.bind(this)); - } else { - return this.predictOne(features); + dist = bmu[this.distanceMethod](this.nodes[theX][theY]); + + if (dist < neighbourhoodRadius) { + influence = Math.exp(-dist / (2 * neighbourhoodRadius)); + this.nodes[theX][theY].adjustWeights(trainingValue, this.learningRate, influence); + } } + } + + this.times.adjust += Date.now() - now2; }; -/** - * Get margin given one observation's features - * @private - * @param {Array} features - Features - * @returns {Number} - The computed margin - */ -SVM.prototype.marginOne = function (features, noWhitening) { - // Apply normalization - if (this.options.whitening && !noWhitening) { - features = this._applyWhitening(features); - } - var ans = this.b, - i; - if (this.options.kernel === 'linear' && this.W) { - // Use weights, it's faster - for (i = 0; i < this.W.length; i++) { - ans += this.W[i] * features[i]; - } - } else { - for (i = 0; i < this.N; i++) { - ans += this.alphas[i] * this.Y[i] * this.kernel.compute([features], [this.X[i]])[0][0]; - } - } - return ans; +SOM.prototype.train = function train(trainingSet) { + if (!this.done) { + this.setTraining(trainingSet); + + while (this.trainOne()) {} + } }; -/** - * Get a margin using the precomputed kernel. Much faster than normal margin computation - * @private - * @param {Number} index - Train data index - * @param {Array< Array >} kernel - The precomputed kernel - * @returns {number} Computed margin - * @private - */ -SVM.prototype._marginOnePrecomputed = function (index, kernel) { - var ans = this.b, - i; - for (i = 0; i < this.N; i++) { - ans += this.alphas[i] * this.Y[i] * kernel[index][i]; +SOM.prototype.getConvertedNodes = function getConvertedNodes() { + var result = new Array(this.x); + + for (var i = 0; i < this.x; i++) { + result[i] = new Array(this.y); + + for (var j = 0; j < this.y; j++) { + var node = this.nodes[i][j]; + result[i][j] = this.creator ? this.creator(node.weights) : node.weights; } - return ans; + } + + return result; }; -/** - * Returns the margin of one or several observations given its features - * @param {Array >|Array} features - Features from on or several observations. - * @returns {Number|Array} The computed margin. Is an Array if several observations' features given, or a Number if - * only one observation's features given - */ -SVM.prototype.margin = function (features) { - if (Array.isArray(features)) { - return features.map(this.marginOne.bind(this)); - } else { - return this.marginOne(features); +SOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) { + var bmu, + lowest = Infinity, + dist; + + for (var i = 0; i < this.x; i++) { + for (var j = 0; j < this.y; j++) { + dist = this.distance(this.nodes[i][j].weights, candidate); + + if (dist < lowest) { + lowest = dist; + bmu = this.nodes[i][j]; + } } + } + + return bmu; }; -/** - * Get support vectors indexes of the trained classifier. WARINNG: this method does not work for svm instances - * created from {@link #SVM.load load} if linear kernel - * @returns {Array} The indices in the training vector of the support vectors - */ -SVM.prototype.supportVectors = function () { - if (!this._trained && !this._loaded) throw new Error('Cannot get support vectors, you need to train the SVM first'); - if (this._loaded && this.options.kernel === 'linear') throw new Error('Cannot get support vectors from saved linear model, you need to train the SVM to have them'); - return this._supportVectorIdx; +SOM.prototype.predict = function predict(data, computePosition) { + if (typeof data === 'boolean') { + computePosition = data; + data = null; + } + + if (!data) { + data = this.trainingSet; + } + + if (Array.isArray(data) && (Array.isArray(data[0]) || typeof data[0] === 'object')) { + // predict a dataset + var self = this; + return data.map(function (element) { + return self._predict(element, computePosition); + }); + } else { + // predict a single element + return this._predict(data, computePosition); + } }; -/** - * Create a SVM instance from a saved model - * @param {Object} model - Object such as returned by a trained SVM instance with {@link #SVM#toJSON toJSON} - * @returns {SVM} Instance of svm classifier - */ -SVM.load = function (model) { - this._loaded = true; - this._trained = false; - var svm = new SVM(model.options); - if (model.options.kernel === 'linear') { - svm.W = model.W.slice(); - svm.D = svm.W.length; - } else { - svm.X = model.X.slice(); - svm.Y = model.Y.slice(); - svm.alphas = model.alphas.slice(); - svm.N = svm.X.length; - svm.D = svm.X[0].length; - } - svm.minMax = model.minMax; - svm.b = model.b; - svm._loaded = true; - svm._trained = false; - return svm; +SOM.prototype._predict = function _predict(element, computePosition) { + if (!Array.isArray(element)) { + element = this.extractor(element); + } + + var bmu = this._findBestMatchingUnit(element); + + var result = [bmu.x, bmu.y]; + + if (computePosition) { + result[2] = bmu.getPosition(element); + } + + return result; +}; // As seen in http://www.scholarpedia.org/article/Kohonen_network + + +SOM.prototype.getQuantizationError = function getQuantizationError() { + var fit = this.getFit(), + l = fit.length, + sum = 0; + + for (var i = 0; i < l; i++) { + sum += fit[i]; + } + + return sum / l; }; -/** - * Export the minimal object that enables to reload the model - * @returns {Object} Model object that can be reused with {@link #SVM.load load} - */ -SVM.prototype.toJSON = function () { - if (!this._trained && !this._loaded) throw new Error('Cannot export, you need to train the SVM first'); - var model = {}; - model.options = Object.assign({}, this.options); - model.b = this.b; - model.minMax = this.minMax; - if (model.options.kernel === 'linear') { - model.W = this.W.slice(); - } else { - // Exporting non-linear models is heavier - model.X = this.X.slice(); - model.Y = this.Y.slice(); - model.alphas = this.alphas.slice(); - } - return model; +SOM.prototype.getFit = function getFit(dataset) { + if (!dataset) { + dataset = this.trainingSet; + } + + var l = dataset.length, + bmu, + result = new Array(l); + + for (var i = 0; i < l; i++) { + bmu = this._findBestMatchingUnit(dataset[i]); + result[i] = Math.sqrt(this.distance(dataset[i], bmu.weights)); + } + + return result; }; -SVM.prototype._applyWhitening = function (features) { - if (!this.minMax) throw new Error('Could not apply whitening'); - var whitened = new Array(features.length); - for (var j = 0; j < features.length; j++) { - whitened[j] = (features[j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min); +function getConverters(fields) { + var l = fields.length, + normalizers = new Array(l), + denormalizers = new Array(l); + + for (var i = 0; i < l; i++) { + normalizers[i] = getNormalizer(fields[i].range); + denormalizers[i] = getDenormalizer(fields[i].range); + } + + return { + extractor: function extractor(value) { + var result = new Array(l); + + for (var i = 0; i < l; i++) { + result[i] = normalizers[i](value[fields[i].name]); + } + + return result; + }, + creator: function creator(value) { + var result = {}; + + for (var i = 0; i < l; i++) { + result[fields[i].name] = denormalizers[i](value[i]); + } + + return result; } - return whitened; -}; + }; +} -module.exports = SVM; +function getNormalizer(minMax) { + return function normalizer(value) { + return (value - minMax[0]) / (minMax[1] - minMax[0]); + }; +} + +function getDenormalizer(minMax) { + return function denormalizer(value) { + return minMax[0] + value * (minMax[1] - minMax[0]); + }; +} + +function squareEuclidean(a, b) { + var d = 0; + + for (var i = 0, ii = a.length; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]); + } + + return d; +} + +function getRandomValue(arr, randomizer) { + return arr[Math.floor(randomizer() * arr.length)]; +} + +function getMaxDistance(distance, numWeights) { + var zero = new Array(numWeights), + one = new Array(numWeights); + + for (var i = 0; i < numWeights; i++) { + zero[i] = 0; + one[i] = 1; + } + + return distance(zero, one); +} + +module.exports = SOM; /***/ }), -/* 98 */ +/* 70 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +var NodeSquare = __webpack_require__(29); +function NodeHexagonal(x, y, weights, som) { + NodeSquare.call(this, x, y, weights, som); + this.hX = x - Math.floor(y / 2); + this.z = 0 - this.hX - y; +} -var squaredEuclidean = __webpack_require__(1).squared; +NodeHexagonal.prototype = new NodeSquare(); +NodeHexagonal.prototype.constructor = NodeHexagonal; -var defaultOptions = { - sigma: 1 +NodeHexagonal.prototype.getDistance = function getDistanceHexagonal(otherNode) { + return Math.max(Math.abs(this.hX - otherNode.hX), Math.abs(this.y - otherNode.y), Math.abs(this.z - otherNode.z)); }; -class GaussianKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.sigma = options.sigma; - this.divisor = 2 * options.sigma * options.sigma; - } +NodeHexagonal.prototype.getDistanceTorus = function getDistanceTorus(otherNode) { + var distX = Math.abs(this.hX - otherNode.hX), + distY = Math.abs(this.y - otherNode.y), + distZ = Math.abs(this.z - otherNode.z); + return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY), Math.min(distZ, this.som.gridDim.z - distZ)); +}; - compute(x, y) { - var distance = squaredEuclidean(x, y); - return Math.exp(-distance / this.divisor); - } -} +NodeHexagonal.prototype.getPosition = function getPosition() { + throw new Error('Unimplemented : cannot get position of the points for hexagonal grid'); +}; -module.exports = GaussianKernel; +module.exports = NodeHexagonal; /***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { +/* 71 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SparseMatrix", function() { return SparseMatrix; }); +/* harmony import */ var ml_hash_table__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14); +/* harmony import */ var ml_hash_table__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(ml_hash_table__WEBPACK_IMPORTED_MODULE_0__); +class SparseMatrix { + constructor(rows, columns) { + let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; -var defaultOptions = { - degree: 1, - constant: 1, - scale: 1 -}; + if (rows instanceof SparseMatrix) { + // clone + const other = rows; -class PolynomialKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); + this._init(other.rows, other.columns, other.elements.clone(), other.threshold); - this.degree = options.degree; - this.constant = options.constant; - this.scale = options.scale; + return; } - compute(x, y) { - var sum = 0; - for (var i = 0; i < x.length; i++) { - sum += x[i] * y[i]; + if (Array.isArray(rows)) { + const matrix = rows; + rows = matrix.length; + options = columns || {}; + columns = matrix[0].length; + + this._init(rows, columns, new ml_hash_table__WEBPACK_IMPORTED_MODULE_0___default.a(options), options.threshold); + + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + var value = matrix[i][j]; + if (this.threshold && Math.abs(value) < this.threshold) value = 0; + + if (value !== 0) { + this.elements.set(i * columns + j, matrix[i][j]); + } } - return Math.pow(this.scale * sum + this.constant, this.degree); + } + } else { + this._init(rows, columns, new ml_hash_table__WEBPACK_IMPORTED_MODULE_0___default.a(options), options.threshold); } -} + } -module.exports = PolynomialKernel; + _init(rows, columns, elements, threshold) { + this.rows = rows; + this.columns = columns; + this.elements = elements; + this.threshold = threshold || 0; + } -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { + static eye() { + let rows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + let columns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : rows; + const min = Math.min(rows, columns); + const matrix = new SparseMatrix(rows, columns, { + initialCapacity: min + }); -"use strict"; + for (var i = 0; i < min; i++) { + matrix.set(i, i, 1); + } + return matrix; + } -var defaultOptions = { - sigma: 1, - degree: 1 -}; + clone() { + return new SparseMatrix(this); + } -class ANOVAKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.sigma = options.sigma; - this.degree = options.degree; - } + to2DArray() { + const copy = new Array(this.rows); - compute(x, y) { - var sum = 0; - var len = Math.min(x.length, y.length); - for (var i = 1; i <= len; ++i) { - sum += Math.pow(Math.exp(-this.sigma * Math.pow(Math.pow(x[i - 1], i) - Math.pow(y[i - 1], i), 2)), this.degree); - } - return sum; + for (var i = 0; i < this.rows; i++) { + copy[i] = new Array(this.columns); + + for (var j = 0; j < this.columns; j++) { + copy[i][j] = this.get(i, j); + } } -} -module.exports = ANOVAKernel; + return copy; + } -/***/ }), -/* 101 */ -/***/ (function(module, exports, __webpack_require__) { + isSquare() { + return this.rows === this.columns; + } -"use strict"; + isSymmetric() { + if (!this.isSquare()) return false; + var symmetric = true; + this.forEachNonZero((i, j, v) => { + if (this.get(j, i) !== v) { + symmetric = false; + return false; + } + return v; + }); + return symmetric; + } + /** + * Search for the wither band in the main diagonals + * @return {number} + */ -var squaredEuclidean = __webpack_require__(1).squared; -var defaultOptions = { - sigma: 1 -}; + bandWidth() { + let min = this.columns; + let max = -1; + this.forEachNonZero((i, j, v) => { + let diff = i - j; + min = Math.min(min, diff); + max = Math.max(max, diff); + return v; + }); + return max - min; + } + /** + * Test if a matrix is consider banded using a threshold + * @param {number} width + * @return {boolean} + */ -class CauchyKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.sigma = options.sigma; - } - compute(x, y) { - return 1 / (1 + squaredEuclidean(x, y) / (this.sigma * this.sigma)); - } -} + isBanded(width) { + let bandWidth = this.bandWidth(); + return bandWidth <= width; + } -module.exports = CauchyKernel; + get cardinality() { + return this.elements.size; + } -/***/ }), -/* 102 */ -/***/ (function(module, exports, __webpack_require__) { + get size() { + return this.rows * this.columns; + } -"use strict"; + get(row, column) { + return this.elements.get(row * this.columns + column); + } + set(row, column, value) { + if (this.threshold && Math.abs(value) < this.threshold) value = 0; -var euclidean = __webpack_require__(1); + if (value === 0) { + this.elements.remove(row * this.columns + column); + } else { + this.elements.set(row * this.columns + column, value); + } -var defaultOptions = { - sigma: 1 -}; + return this; + } -class ExponentialKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.sigma = options.sigma; - this.divisor = 2 * options.sigma * options.sigma; + mmul(other) { + if (this.columns !== other.rows) { + // eslint-disable-next-line no-console + console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.'); } - compute(x, y) { - var distance = euclidean(x, y); - return Math.exp(-distance / this.divisor); - } -} + const m = this.rows; + const p = other.columns; + const result = new SparseMatrix(m, p); + this.forEachNonZero((i, j, v1) => { + other.forEachNonZero((k, l, v2) => { + if (j === k) { + result.set(i, l, result.get(i, l) + v1 * v2); + } -module.exports = ExponentialKernel; + return v2; + }); + return v1; + }); + return result; + } -/***/ }), -/* 103 */ -/***/ (function(module, exports, __webpack_require__) { + kroneckerProduct(other) { + const m = this.rows; + const n = this.columns; + const p = other.rows; + const q = other.columns; + const result = new SparseMatrix(m * p, n * q, { + initialCapacity: this.cardinality * other.cardinality + }); + this.forEachNonZero((i, j, v1) => { + other.forEachNonZero((k, l, v2) => { + result.set(p * i + k, q * j + l, v1 * v2); + return v2; + }); + return v1; + }); + return result; + } -"use strict"; + forEachNonZero(callback) { + this.elements.forEachPair((key, value) => { + const i = key / this.columns | 0; + const j = key % this.columns; + let r = callback(i, j, value); + if (r === false) return false; // stop iteration + if (this.threshold && Math.abs(r) < this.threshold) r = 0; -class HistogramIntersectionKernel { - compute(x, y) { - var min = Math.min(x.length, y.length); - var sum = 0; - for (var i = 0; i < min; ++i) { - sum += Math.min(x[i], y[i]); + if (r !== value) { + if (r === 0) { + this.elements.remove(key, true); + } else { + this.elements.set(key, r); } + } - return sum; - } -} + return true; + }); + this.elements.maybeShrinkCapacity(); + return this; + } -module.exports = HistogramIntersectionKernel; + getNonZeros() { + const cardinality = this.cardinality; + const rows = new Array(cardinality); + const columns = new Array(cardinality); + const values = new Array(cardinality); + var idx = 0; + this.forEachNonZero((i, j, value) => { + rows[idx] = i; + columns[idx] = j; + values[idx] = value; + idx++; + return value; + }); + return { + rows, + columns, + values + }; + } -/***/ }), -/* 104 */ -/***/ (function(module, exports, __webpack_require__) { + setThreshold(newThreshold) { + if (newThreshold !== 0 && newThreshold !== this.threshold) { + this.threshold = newThreshold; + this.forEachNonZero((i, j, v) => v); + } -"use strict"; + return this; + } + /** + * @return {SparseMatrix} - New transposed sparse matrix + */ -var euclidean = __webpack_require__(1); + transpose() { + let trans = new SparseMatrix(this.columns, this.rows, { + initialCapacity: this.cardinality + }); + this.forEachNonZero((i, j, value) => { + trans.set(j, i, value); + return value; + }); + return trans; + } -var defaultOptions = { - sigma: 1 -}; +} +SparseMatrix.prototype.klass = 'Matrix'; +SparseMatrix.identity = SparseMatrix.eye; +SparseMatrix.prototype.tensorProduct = SparseMatrix.prototype.kroneckerProduct; +/* + Add dynamically instance and static methods for mathematical operations + */ -class LaplacianKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.sigma = options.sigma; - } +var inplaceOperator = "\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n"; +var inplaceOperatorScalar = "\n(function %name%S(value) {\n this.forEachNonZero((i, j, v) => v %op% value);\n return this;\n})\n"; +var inplaceOperatorMatrix = "\n(function %name%M(matrix) {\n matrix.forEachNonZero((i, j, v) => {\n this.set(i, j, this.get(i, j) %op% v);\n return v;\n });\n return this;\n})\n"; +var staticOperator = "\n(function %name%(matrix, value) {\n var newMatrix = new SparseMatrix(matrix);\n return newMatrix.%name%(value);\n})\n"; +var inplaceMethod = "\n(function %name%() {\n this.forEachNonZero((i, j, v) => %method%(v));\n return this;\n})\n"; +var staticMethod = "\n(function %name%(matrix) {\n var newMatrix = new SparseMatrix(matrix);\n return newMatrix.%name%();\n})\n"; +const operators = [// Arithmetic operators +['+', 'add'], ['-', 'sub', 'subtract'], ['*', 'mul', 'multiply'], ['/', 'div', 'divide'], ['%', 'mod', 'modulus'], // Bitwise operators +['&', 'and'], ['|', 'or'], ['^', 'xor'], ['<<', 'leftShift'], ['>>', 'signPropagatingRightShift'], ['>>>', 'rightShift', 'zeroFillRightShift']]; - compute(x, y) { - var distance = euclidean(x, y); - return Math.exp(-distance / this.sigma); - } +for (const operator of operators) { + for (let i = 1; i < operator.length; i++) { + SparseMatrix.prototype[operator[i]] = eval(fillTemplateFunction(inplaceOperator, { + name: operator[i], + op: operator[0] + })); + SparseMatrix.prototype[operator[i] + 'S'] = eval(fillTemplateFunction(inplaceOperatorScalar, { + name: operator[i] + 'S', + op: operator[0] + })); + SparseMatrix.prototype[operator[i] + 'M'] = eval(fillTemplateFunction(inplaceOperatorMatrix, { + name: operator[i] + 'M', + op: operator[0] + })); + SparseMatrix[operator[i]] = eval(fillTemplateFunction(staticOperator, { + name: operator[i] + })); + } } -module.exports = LaplacianKernel; +var methods = [['~', 'not']]; +['abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil', 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p', 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'].forEach(function (mathMethod) { + methods.push(['Math.' + mathMethod, mathMethod]); +}); -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { +for (const method of methods) { + for (let i = 1; i < method.length; i++) { + SparseMatrix.prototype[method[i]] = eval(fillTemplateFunction(inplaceMethod, { + name: method[i], + method: method[0] + })); + SparseMatrix[method[i]] = eval(fillTemplateFunction(staticMethod, { + name: method[i] + })); + } +} -"use strict"; +function fillTemplateFunction(template, values) { + for (const i in values) { + template = template.replace(new RegExp('%' + i + '%', 'g'), values[i]); + } + return template; +} -var squaredEuclidean = __webpack_require__(1).squared; +/***/ }), +/* 72 */ +/***/ (function(module, exports) { -var defaultOptions = { - constant: 1 -}; +module.exports = newArray; -class MultiquadraticKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.constant = options.constant; - } +function newArray(n, value) { + n = n || 0; + var array = new Array(n); - compute(x, y) { - return Math.sqrt(squaredEuclidean(x, y) + this.constant * this.constant); - } -} + for (var i = 0; i < n; i++) { + array[i] = value; + } -module.exports = MultiquadraticKernel; + return array; +} /***/ }), -/* 106 */ +/* 73 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +const binarySearch = __webpack_require__(6); +const sortAsc = __webpack_require__(7).asc; -var squaredEuclidean = __webpack_require__(1).squared; +const largestPrime = 0x7fffffff; +const primeNumbers = [//chunk #0 +largestPrime, // 2^31-1 +//chunk #1 +5, 11, 23, 47, 97, 197, 397, 797, 1597, 3203, 6421, 12853, 25717, 51437, 102877, 205759, 411527, 823117, 1646237, 3292489, 6584983, 13169977, 26339969, 52679969, 105359939, 210719881, 421439783, 842879579, 1685759167, //chunk #2 +433, 877, 1759, 3527, 7057, 14143, 28289, 56591, 113189, 226379, 452759, 905551, 1811107, 3622219, 7244441, 14488931, 28977863, 57955739, 115911563, 231823147, 463646329, 927292699, 1854585413, //chunk #3 +953, 1907, 3821, 7643, 15287, 30577, 61169, 122347, 244703, 489407, 978821, 1957651, 3915341, 7830701, 15661423, 31322867, 62645741, 125291483, 250582987, 501165979, 1002331963, 2004663929, //chunk #4 +1039, 2081, 4177, 8363, 16729, 33461, 66923, 133853, 267713, 535481, 1070981, 2141977, 4283963, 8567929, 17135863, 34271747, 68543509, 137087021, 274174111, 548348231, 1096696463, //chunk #5 +31, 67, 137, 277, 557, 1117, 2237, 4481, 8963, 17929, 35863, 71741, 143483, 286973, 573953, 1147921, 2295859, 4591721, 9183457, 18366923, 36733847, 73467739, 146935499, 293871013, 587742049, 1175484103, //chunk #6 +599, 1201, 2411, 4831, 9677, 19373, 38747, 77509, 155027, 310081, 620171, 1240361, 2480729, 4961459, 9922933, 19845871, 39691759, 79383533, 158767069, 317534141, 635068283, 1270136683, //chunk #7 +311, 631, 1277, 2557, 5119, 10243, 20507, 41017, 82037, 164089, 328213, 656429, 1312867, 2625761, 5251529, 10503061, 21006137, 42012281, 84024581, 168049163, 336098327, 672196673, 1344393353, //chunk #8 +3, 7, 17, 37, 79, 163, 331, 673, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899, 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557, 359339171, 718678369, 1437356741, //chunk #9 +43, 89, 179, 359, 719, 1439, 2879, 5779, 11579, 23159, 46327, 92657, 185323, 370661, 741337, 1482707, 2965421, 5930887, 11861791, 23723597, 47447201, 94894427, 189788857, 379577741, 759155483, 1518310967, //chunk #10 +379, 761, 1523, 3049, 6101, 12203, 24407, 48817, 97649, 195311, 390647, 781301, 1562611, 3125257, 6250537, 12501169, 25002389, 50004791, 100009607, 200019221, 400038451, 800076929, 1600153859, //chunk #11 +13, 29, 59, 127, 257, 521, 1049, 2099, 4201, 8419, 16843, 33703, 67409, 134837, 269683, 539389, 1078787, 2157587, 4315183, 8630387, 17260781, 34521589, 69043189, 138086407, 276172823, 552345671, 1104691373, //chunk #12 +19, 41, 83, 167, 337, 677, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899, 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557, 359339171, 718678369, 1437356741, //chunk #13 +53, 107, 223, 449, 907, 1823, 3659, 7321, 14653, 29311, 58631, 117269, 234539, 469099, 938207, 1876417, 3752839, 7505681, 15011389, 30022781, 60045577, 120091177, 240182359, 480364727, 960729461, 1921458943]; +primeNumbers.sort(sortAsc); -var defaultOptions = { - constant: 1 -}; +function nextPrime(value) { + let index = binarySearch(primeNumbers, value, sortAsc); -class RationalQuadraticKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.constant = options.constant; - } + if (index < 0) { + index = ~index; + } - compute(x, y) { - var distance = squaredEuclidean(x, y); - return 1 - distance / (distance + this.constant); - } + return primeNumbers[index]; } -module.exports = RationalQuadraticKernel; +exports.nextPrime = nextPrime; +exports.largestPrime = largestPrime; /***/ }), -/* 107 */ +/* 74 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defaultOptions = { - alpha: 0.01, - constant: -Math.E +module.exports = Number.isNaN || function (x) { + return x !== x; }; -class SigmoidKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.alpha = options.alpha; - this.constant = options.constant; - } - - compute(x, y) { - var sum = 0; - for (var i = 0; i < x.length; i++) { - sum += x[i] * y[i]; - } - return Math.tanh(this.alpha * sum + this.constant); - } -} - -module.exports = SigmoidKernel; - /***/ }), -/* 108 */ +/* 75 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); +exports.additiveSymmetric = __webpack_require__(76); +exports.avg = __webpack_require__(77); +exports.bhattacharyya = __webpack_require__(78); +exports.canberra = __webpack_require__(79); +exports.chebyshev = __webpack_require__(80); +exports.clark = __webpack_require__(81); +exports.czekanowski = __webpack_require__(82); +exports.dice = __webpack_require__(32); +exports.divergence = __webpack_require__(83); +exports.euclidean = __webpack_require__(2); +exports.fidelity = __webpack_require__(84); +exports.gower = __webpack_require__(85); +exports.harmonicMean = __webpack_require__(86); +exports.hellinger = __webpack_require__(87); +exports.innerProduct = __webpack_require__(88); +exports.intersection = __webpack_require__(33); +exports.jaccard = __webpack_require__(34); +exports.jeffreys = __webpack_require__(89); +exports.jensenDifference = __webpack_require__(90); +exports.jensenShannon = __webpack_require__(91); +exports.kdivergence = __webpack_require__(92); +exports.kulczynski = __webpack_require__(35); +exports.kullbackLeibler = __webpack_require__(93); +exports.kumarHassebrook = __webpack_require__(94); +exports.kumarJohnson = __webpack_require__(95); +exports.lorentzian = __webpack_require__(96); +exports.manhattan = __webpack_require__(97); +exports.matusita = __webpack_require__(98); +exports.minkowski = __webpack_require__(99); +exports.motyka = __webpack_require__(36); +exports.neyman = __webpack_require__(100); +exports.pearson = __webpack_require__(101); +exports.probabilisticSymmetric = __webpack_require__(102); +exports.ruzicka = __webpack_require__(103); +exports.soergel = __webpack_require__(104); +exports.sorensen = __webpack_require__(105); +exports.squared = __webpack_require__(106); +exports.squaredChord = __webpack_require__(37); +exports.squaredEuclidean = __webpack_require__(2).squared; +exports.taneja = __webpack_require__(107); +exports.tanimoto = __webpack_require__(108); +exports.topsoe = __webpack_require__(109); +exports.tree = __webpack_require__(110); +exports.waveHedges = __webpack_require__(111); + +/***/ }), +/* 76 */ +/***/ (function(module, exports) { -var _GaussianNB = __webpack_require__(109); +module.exports = function additiveSymmetric(a, b) { + var i = 0, + ii = a.length, + d = 0; -Object.defineProperty(exports, 'GaussianNB', { - enumerable: true, - get: function get() { - return _GaussianNB.GaussianNB; + for (; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]) * (a[i] + b[i]) / (a[i] * b[i]); } -}); -var _MultinomialNB = __webpack_require__(110); + return 2 * d; +}; + +/***/ }), +/* 77 */ +/***/ (function(module, exports) { + +module.exports = function avg(a, b) { + var ii = a.length, + max = 0, + ans = 0, + aux = 0; + + for (var i = 0; i < ii; i++) { + aux = Math.abs(a[i] - b[i]); + ans += aux; -Object.defineProperty(exports, 'MultinomialNB', { - enumerable: true, - get: function get() { - return _MultinomialNB.MultinomialNB; + if (max < aux) { + max = aux; + } } -}); + + return (max + ans) / 2; +}; /***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { +/* 78 */ +/***/ (function(module, exports) { -"use strict"; +module.exports = function bhattacharyya(a, b) { + var ii = a.length, + ans = 0; + for (var i = 0; i < ii; i++) { + ans += Math.sqrt(a[i] * b[i]); + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.GaussianNB = undefined; + return -Math.log(ans); +}; -var _mlMatrix = __webpack_require__(0); +/***/ }), +/* 79 */ +/***/ (function(module, exports) { -var _mlMatrix2 = _interopRequireDefault(_mlMatrix); +module.exports = function canberra(a, b) { + var ii = a.length, + ans = 0; -var _mlStat = __webpack_require__(4); + for (var i = 0; i < ii; i++) { + ans += Math.abs(a[i] - b[i]) / (a[i] + b[i]); + } -var _mlStat2 = _interopRequireDefault(_mlStat); + return ans; +}; -var _utils = __webpack_require__(33); +/***/ }), +/* 80 */ +/***/ (function(module, exports) { -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +module.exports = function chebyshev(a, b) { + var ii = a.length, + max = 0, + aux = 0; -/** - * @class GaussianNB - */ -class GaussianNB { + for (var i = 0; i < ii; i++) { + aux = Math.abs(a[i] - b[i]); - /** - * @constructor - * Constructor for the Gaussian Naive Bayes classifier, the parameters here is just for loading purposes. - * - * @param {boolean} reload - * @param {object} model - */ - constructor(reload, model) { - if (reload) { - this.means = model.means; - this.calculateProbabilities = model.calculateProbabilities; - } + if (max < aux) { + max = aux; } + } - /** - * Function that trains the classifier with a matrix that represents the training set and an array that - * represents the label of each row in the training set. the labels must be numbers between 0 to n-1 where - * n represents the number of classes. - * - * WARNING: in the case that one class, all the cases in one or more features have the same value, the - * Naive Bayes classifier will not work well. - * @param {Matrix|Array} trainingSet - * @param {Matrix|Array} trainingLabels - */ - train(trainingSet, trainingLabels) { - var C1 = Math.sqrt(2 * Math.PI); // constant to precalculate the squared root - trainingSet = _mlMatrix2.default.checkMatrix(trainingSet); //if (!Matrix.isMatrix(trainingSet)) trainingSet = new Matrix(trainingSet); - - if (trainingSet.rows !== trainingLabels.length) { - throw new RangeError('the size of the training set and the training labels must be the same.'); - } + return max; +}; - var separatedClasses = (0, _utils.separateClasses)(trainingSet, trainingLabels); - var calculateProbabilities = new Array(separatedClasses.length); - this.means = new Array(separatedClasses.length); - for (var i = 0; i < separatedClasses.length; ++i) { - var means = _mlStat2.default.matrix.mean(separatedClasses[i]); - var std = _mlStat2.default.matrix.standardDeviation(separatedClasses[i], means); +/***/ }), +/* 81 */ +/***/ (function(module, exports) { - var logPriorProbability = Math.log(separatedClasses[i].rows / trainingSet.rows); - calculateProbabilities[i] = new Array(means.length + 1); +module.exports = function clark(a, b) { + var i = 0, + ii = a.length, + d = 0; - calculateProbabilities[i][0] = logPriorProbability; - for (var j = 1; j < means.length + 1; ++j) { - var currentStd = std[j - 1]; - calculateProbabilities[i][j] = [1 / (C1 * currentStd), -2 * currentStd * currentStd]; - } + for (; i < ii; i++) { + d += Math.sqrt((a[i] - b[i]) * (a[i] - b[i]) / ((a[i] + b[i]) * (a[i] + b[i]))); + } - this.means[i] = means; - } + return 2 * d; +}; - this.calculateProbabilities = calculateProbabilities; - } +/***/ }), +/* 82 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * function that predicts each row of the dataset (must be a matrix). - * - * @param {Matrix|Array} dataset - * @return {Array} - */ - predict(dataset) { - if (dataset[0].length === this.calculateProbabilities[0].length) { - throw new RangeError('the dataset must have the same features as the training set'); - } +"use strict"; - var predictions = new Array(dataset.length); - for (var i = 0; i < predictions.length; ++i) { - predictions[i] = getCurrentClass(dataset[i], this.means, this.calculateProbabilities); - } +const czekanowskiSimilarity = __webpack_require__(31); - return predictions; - } +module.exports = function czekanowskiDistance(a, b) { + return 1 - czekanowskiSimilarity(a, b); +}; - /** - * Function that export the NaiveBayes model. - * @return {object} - */ - toJSON() { - return { - modelName: 'NaiveBayes', - means: this.means, - calculateProbabilities: this.calculateProbabilities - }; - } +/***/ }), +/* 83 */ +/***/ (function(module, exports) { - /** - * Function that create a GaussianNB classifier with the given model. - * @param {object} model - * @return {GaussianNB} - */ - static load(model) { - if (model.modelName !== 'NaiveBayes') { - throw new RangeError('The current model is not a Multinomial Naive Bayes, current model:', model.name); - } +module.exports = function divergence(a, b) { + var i = 0, + ii = a.length, + d = 0; - return new GaussianNB(true, model); - } -} + for (; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]) / ((a[i] + b[i]) * (a[i] + b[i])); + } -exports.GaussianNB = GaussianNB; /** - * @private - * Function the retrieves a prediction with one case. - * - * @param {Array} currentCase - * @param {Array} mean - Precalculated means of each class trained - * @param {Array} classes - Precalculated value of each class (Prior probability and probability function of each feature) - * @return {number} - */ + return 2 * d; +}; -function getCurrentClass(currentCase, mean, classes) { - var maxProbability = 0; - var predictedClass = -1; - - // going through all precalculated values for the classes - for (var i = 0; i < classes.length; ++i) { - var currentProbability = classes[i][0]; // initialize with the prior probability - for (var j = 1; j < classes[0][1].length + 1; ++j) { - currentProbability += calculateLogProbability(currentCase[j - 1], mean[i][j - 1], classes[i][j][0], classes[i][j][1]); - } +/***/ }), +/* 84 */ +/***/ (function(module, exports) { - currentProbability = Math.exp(currentProbability); - if (currentProbability > maxProbability) { - maxProbability = currentProbability; - predictedClass = i; - } - } +module.exports = function fidelity(a, b) { + var ii = a.length, + ans = 0; - return predictedClass; -} + for (var i = 0; i < ii; i++) { + ans += Math.sqrt(a[i] * b[i]); + } -/** - * @private - * function that retrieves the probability of the feature given the class. - * @param {number} value - value of the feature. - * @param {number} mean - mean of the feature for the given class. - * @param {number} C1 - precalculated value of (1 / (sqrt(2*pi) * std)). - * @param {number} C2 - precalculated value of (2 * std^2) for the denominator of the exponential. - * @return {number} - */ -function calculateLogProbability(value, mean, C1, C2) { - value = value - mean; - return Math.log(C1 * Math.exp(value * value / C2)); -} + return ans; +}; /***/ }), -/* 110 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +/* 85 */ +/***/ (function(module, exports) { +module.exports = function gower(a, b) { + var ii = a.length, + ans = 0; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.MultinomialNB = undefined; + for (var i = 0; i < ii; i++) { + ans += Math.abs(a[i] - b[i]); + } -var _mlMatrix = __webpack_require__(0); + return ans / ii; +}; -var _mlMatrix2 = _interopRequireDefault(_mlMatrix); +/***/ }), +/* 86 */ +/***/ (function(module, exports) { -var _utils = __webpack_require__(33); +module.exports = function harmonicMean(a, b) { + var ii = a.length, + ans = 0; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (var i = 0; i < ii; i++) { + ans += a[i] * b[i] / (a[i] + b[i]); + } -/** - * @class MultinomialNB - */ -class MultinomialNB { + return 2 * ans; +}; - /** - * @constructor - * Constructor for Multinomial Naive Bayes, the model parameter is for load purposes. - * - * @param {object} model - for load purposes. - */ - constructor(model) { - if (model) { - this.conditionalProbability = _mlMatrix2.default.checkMatrix(model.conditionalProbability); - this.priorProbability = _mlMatrix2.default.checkMatrix(model.priorProbability); - } - } +/***/ }), +/* 87 */ +/***/ (function(module, exports) { - /** - * Train the classifier with the current training set and labels, the labels must be numbers between 0 and n. - * @param {Matrix|Array} trainingSet - * @param {Array} trainingLabels - */ - train(trainingSet, trainingLabels) { - trainingSet = _mlMatrix2.default.checkMatrix(trainingSet); +module.exports = function hellinger(a, b) { + var ii = a.length, + ans = 0; - if (trainingSet.rows !== trainingLabels.length) { - throw new RangeError('the size of the training set and the training labels must be the same.'); - } + for (var i = 0; i < ii; i++) { + ans += Math.sqrt(a[i] * b[i]); + } - var separateClass = (0, _utils.separateClasses)(trainingSet, trainingLabels); - this.priorProbability = new _mlMatrix2.default(separateClass.length, 1); + return 2 * Math.sqrt(1 - ans); +}; - for (var i = 0; i < separateClass.length; ++i) { - this.priorProbability[i][0] = Math.log(separateClass[i].length / trainingSet.rows); - } +/***/ }), +/* 88 */ +/***/ (function(module, exports) { - var features = trainingSet.columns; - this.conditionalProbability = new _mlMatrix2.default(separateClass.length, features); - for (i = 0; i < separateClass.length; ++i) { - var classValues = _mlMatrix2.default.checkMatrix(separateClass[i]); - var total = classValues.sum(); - var divisor = total + features; - this.conditionalProbability.setRow(i, classValues.sum('column').add(1).div(divisor).apply(matrixLog)); - } - } +module.exports = function innerProduct(a, b) { + var ii = a.length, + ans = 0; - /** - * Retrieves the predictions for the dataset with the current model. - * @param {Matrix|Array} dataset - * @return {Array} - predictions from the dataset. - */ - predict(dataset) { - dataset = _mlMatrix2.default.checkMatrix(dataset); - var predictions = new Array(dataset.rows); - for (var i = 0; i < dataset.rows; ++i) { - var currentElement = dataset.getRowVector(i); - predictions[i] = this.conditionalProbability.clone().mulRowVector(currentElement).sum('row').add(this.priorProbability).maxIndex()[0]; - } + for (var i = 0; i < ii; i++) { + ans += a[i] * b[i]; + } - return predictions; - } + return ans; +}; - /** - * Function that saves the current model. - * @return {object} - model in JSON format. - */ - toJSON() { - return { - name: 'MultinomialNB', - priorProbability: this.priorProbability, - conditionalProbability: this.conditionalProbability - }; - } +/***/ }), +/* 89 */ +/***/ (function(module, exports) { - /** - * Creates a new MultinomialNB from the given model - * @param {object} model - * @return {MultinomialNB} - */ - static load(model) { - if (model.name !== 'MultinomialNB') { - throw new RangeError(`${model.name} is not a Multinomial Naive Bayes`); - } +module.exports = function jeffreys(a, b) { + var ii = a.length, + ans = 0; - return new MultinomialNB(model); - } -} + for (var i = 0; i < ii; i++) { + ans += (a[i] - b[i]) * Math.log(a[i] / b[i]); + } -exports.MultinomialNB = MultinomialNB; -function matrixLog(i, j) { - this[i][j] = Math.log(this[i][j]); -} + return ans; +}; /***/ }), -/* 111 */ -/***/ (function(module, exports, __webpack_require__) { +/* 90 */ +/***/ (function(module, exports) { -"use strict"; +module.exports = function jensenDifference(a, b) { + var ii = a.length, + ans = 0; + for (var i = 0; i < ii; i++) { + ans += (a[i] * Math.log(a[i]) + b[i] * Math.log(b[i])) / 2 - (a[i] + b[i]) / 2 * Math.log((a[i] + b[i]) / 2); + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + return ans; +}; + +/***/ }), +/* 91 */ +/***/ (function(module, exports) { -var _KDTree = __webpack_require__(112); +module.exports = function jensenShannon(a, b) { + var ii = a.length, + p = 0, + q = 0; -var _KDTree2 = _interopRequireDefault(_KDTree); + for (var i = 0; i < ii; i++) { + p += a[i] * Math.log(2 * a[i] / (a[i] + b[i])); + q += b[i] * Math.log(2 * b[i] / (a[i] + b[i])); + } -var _mlDistanceEuclidean = __webpack_require__(1); + return (p + q) / 2; +}; -var _mlDistanceEuclidean2 = _interopRequireDefault(_mlDistanceEuclidean); +/***/ }), +/* 92 */ +/***/ (function(module, exports) { -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +module.exports = function kdivergence(a, b) { + var ii = a.length, + ans = 0; -class KNN { + for (var i = 0; i < ii; i++) { + ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])); + } - /** - * @param {Array} dataset - * @param {Array} labels - * @param {object} options - * @param {number} [options.k=numberOfClasses + 1] - Number of neighbors to classify. - * @param {function} [options.distance=euclideanDistance] - Distance function that takes two parameters. - */ - constructor(dataset, labels, options = {}) { - if (dataset === true) { - var model = labels; - this.kdTree = new _KDTree2.default(model.kdTree, options); - this.k = model.k; - this.classes = new Set(model.classes); - this.isEuclidean = model.isEuclidean; - return; - } + return ans; +}; - var classes = new Set(labels); +/***/ }), +/* 93 */ +/***/ (function(module, exports) { - var _options$distance = options.distance, - distance = _options$distance === undefined ? _mlDistanceEuclidean2.default : _options$distance, - _options$k = options.k, - k = _options$k === undefined ? classes.size + 1 : _options$k; +module.exports = function kullbackLeibler(a, b) { + var ii = a.length, + ans = 0; + for (var i = 0; i < ii; i++) { + ans += a[i] * Math.log(a[i] / b[i]); + } - var points = new Array(dataset.length); - for (var i = 0; i < points.length; ++i) { - points[i] = dataset[i].slice(); - } + return ans; +}; - for (i = 0; i < labels.length; ++i) { - points[i].push(labels[i]); - } +/***/ }), +/* 94 */ +/***/ (function(module, exports) { - this.kdTree = new _KDTree2.default(points, distance); - this.k = k; - this.classes = classes; - this.isEuclidean = distance === _mlDistanceEuclidean2.default; - } +module.exports = function kumarHassebrook(a, b) { + var ii = a.length, + p = 0, + p2 = 0, + q2 = 0; + + for (var i = 0; i < ii; i++) { + p += a[i] * b[i]; + p2 += a[i] * a[i]; + q2 += b[i] * b[i]; + } - /** - * Create a new KNN instance with the given model. - * @param {object} model - * @param {function} distance=euclideanDistance - distance function must be provided if the model wasn't trained with euclidean distance. - * @return {KNN} - */ - static load(model, distance = _mlDistanceEuclidean2.default) { - if (model.name !== 'KNN') { - throw new Error('invalid model: ' + model.name); - } - if (!model.isEuclidean && distance === _mlDistanceEuclidean2.default) { - throw new Error('a custom distance function was used to create the model. Please provide it again'); - } - if (model.isEuclidean && distance !== _mlDistanceEuclidean2.default) { - throw new Error('the model was created with the default distance function. Do not load it with another one'); - } - return new KNN(true, model, distance); - } + return p / (p2 + q2 - p); +}; - /** - * Return a JSON containing the kd-tree model. - * @return {object} JSON KNN model. - */ - toJSON() { - return { - name: 'KNN', - kdTree: this.kdTree, - k: this.k, - classes: Array.from(this.classes), - isEuclidean: this.isEuclidean - }; - } +/***/ }), +/* 95 */ +/***/ (function(module, exports) { - /** - * Predicts the output given the matrix to predict. - * @param {Array} dataset - * @return {Array} predictions - */ - predict(dataset) { - if (Array.isArray(dataset)) { - if (typeof dataset[0] === 'number') { - return getSinglePrediction(this, dataset); - } else if (Array.isArray(dataset[0]) && typeof dataset[0][0] === 'number') { - var predictions = new Array(dataset.length); - for (var i = 0; i < dataset.length; i++) { - predictions[i] = getSinglePrediction(this, dataset[i]); - } - return predictions; - } - } - throw new TypeError('dataset to predict must be an array or a matrix'); - } -} +module.exports = function kumarJohnson(a, b) { + var ii = a.length, + ans = 0; -exports.default = KNN; -function getSinglePrediction(knn, currentCase) { - var nearestPoints = knn.kdTree.nearest(currentCase, knn.k); - var pointsPerClass = {}; - var predictedClass = -1; - var maxPoints = -1; - var lastElement = nearestPoints[0][0].length - 1; - - for (var element of knn.classes) { - pointsPerClass[element] = 0; - } - - for (var i = 0; i < nearestPoints.length; ++i) { - var currentClass = nearestPoints[i][0][lastElement]; - var currentPoints = ++pointsPerClass[currentClass]; - if (currentPoints > maxPoints) { - predictedClass = currentClass; - maxPoints = currentPoints; - } - } + for (var i = 0; i < ii; i++) { + ans += Math.pow(a[i] * a[i] - b[i] * b[i], 2) / (2 * Math.pow(a[i] * b[i], 1.5)); + } - return predictedClass; -} + return ans; +}; /***/ }), -/* 112 */ -/***/ (function(module, exports, __webpack_require__) { +/* 96 */ +/***/ (function(module, exports) { -"use strict"; +module.exports = function lorentzian(a, b) { + var ii = a.length, + ans = 0; + for (var i = 0; i < ii; i++) { + ans += Math.log(Math.abs(a[i] - b[i]) + 1); + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -/* - * Original code from: - * - * k-d Tree JavaScript - V 1.01 - * - * https://github.com/ubilabs/kd-tree-javascript - * - * @author Mircea Pricop , 2012 - * @author Martin Kleppe , 2012 - * @author Ubilabs http://ubilabs.net, 2012 - * @license MIT License - */ + return ans; +}; -function Node(obj, dimension, parent) { - this.obj = obj; - this.left = null; - this.right = null; - this.parent = parent; - this.dimension = dimension; -} +/***/ }), +/* 97 */ +/***/ (function(module, exports) { -class KDTree { - constructor(points, metric) { - // If points is not an array, assume we're loading a pre-built tree - if (!Array.isArray(points)) { - this.dimensions = points.dimensions; - this.root = points; - restoreParent(this.root); - } else { - this.dimensions = new Array(points[0].length); - for (var i = 0; i < this.dimensions.length; i++) { - this.dimensions[i] = i; - } - this.root = buildTree(points, 0, null, this.dimensions); - } - this.metric = metric; - } +module.exports = function manhattan(a, b) { + var i = 0, + ii = a.length, + d = 0; - // Convert to a JSON serializable structure; this just requires removing - // the `parent` property - toJSON() { - var result = toJSONImpl(this.root, true); - result.dimensions = this.dimensions; - return result; - } + for (; i < ii; i++) { + d += Math.abs(a[i] - b[i]); + } - nearest(point, maxNodes, maxDistance) { - var metric = this.metric; - var dimensions = this.dimensions; - var i; + return d; +}; - var bestNodes = new BinaryHeap(function (e) { - return -e[1]; - }); +/***/ }), +/* 98 */ +/***/ (function(module, exports) { - function nearestSearch(node) { - var dimension = dimensions[node.dimension]; - var ownDistance = metric(point, node.obj); - var linearPoint = {}; - var bestChild, linearDistance, otherChild, i; +module.exports = function matusita(a, b) { + var ii = a.length, + ans = 0; - function saveNode(node, distance) { - bestNodes.push([node, distance]); - if (bestNodes.size() > maxNodes) { - bestNodes.pop(); - } - } + for (var i = 0; i < ii; i++) { + ans += Math.sqrt(a[i] * b[i]); + } - for (i = 0; i < dimensions.length; i += 1) { - if (i === node.dimension) { - linearPoint[dimensions[i]] = point[dimensions[i]]; - } else { - linearPoint[dimensions[i]] = node.obj[dimensions[i]]; - } - } + return Math.sqrt(2 - 2 * ans); +}; - linearDistance = metric(linearPoint, node.obj); +/***/ }), +/* 99 */ +/***/ (function(module, exports) { - if (node.right === null && node.left === null) { - if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { - saveNode(node, ownDistance); - } - return; - } +module.exports = function minkowski(a, b, p) { + var i = 0, + ii = a.length, + d = 0; - if (node.right === null) { - bestChild = node.left; - } else if (node.left === null) { - bestChild = node.right; - } else { - if (point[dimension] < node.obj[dimension]) { - bestChild = node.left; - } else { - bestChild = node.right; - } - } + for (; i < ii; i++) { + d += Math.pow(Math.abs(a[i] - b[i]), p); + } - nearestSearch(bestChild); + return Math.pow(d, 1 / p); +}; - if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { - saveNode(node, ownDistance); - } +/***/ }), +/* 100 */ +/***/ (function(module, exports) { - if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) { - if (bestChild === node.left) { - otherChild = node.right; - } else { - otherChild = node.left; - } - if (otherChild !== null) { - nearestSearch(otherChild); - } - } - } +module.exports = function neyman(a, b) { + var i = 0, + ii = a.length, + d = 0; - if (maxDistance) { - for (i = 0; i < maxNodes; i += 1) { - bestNodes.push([null, maxDistance]); - } - } + for (; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]) / a[i]; + } - if (this.root) { - nearestSearch(this.root); - } + return d; +}; + +/***/ }), +/* 101 */ +/***/ (function(module, exports) { - var result = []; - for (i = 0; i < Math.min(maxNodes, bestNodes.content.length); i += 1) { - if (bestNodes.content[i][0]) { - result.push([bestNodes.content[i][0].obj, bestNodes.content[i][1]]); - } - } - return result; - } -} +module.exports = function pearson(a, b) { + var i = 0, + ii = a.length, + d = 0; -exports.default = KDTree; -function toJSONImpl(src) { - var dest = new Node(src.obj, src.dimension, null); - if (src.left) dest.left = toJSONImpl(src.left); - if (src.right) dest.right = toJSONImpl(src.right); - return dest; -} + for (; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]) / b[i]; + } -function buildTree(points, depth, parent, dimensions) { - var dim = depth % dimensions.length; + return d; +}; - if (points.length === 0) { - return null; - } - if (points.length === 1) { - return new Node(points[0], dim, parent); - } +/***/ }), +/* 102 */ +/***/ (function(module, exports) { - points.sort((a, b) => a[dimensions[dim]] - b[dimensions[dim]]); +module.exports = function probabilisticSymmetric(a, b) { + var i = 0, + ii = a.length, + d = 0; - var median = Math.floor(points.length / 2); - var node = new Node(points[median], dim, parent); - node.left = buildTree(points.slice(0, median), depth + 1, node, dimensions); - node.right = buildTree(points.slice(median + 1), depth + 1, node, dimensions); + for (; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]) / (a[i] + b[i]); + } - return node; -} + return 2 * d; +}; -function restoreParent(root) { - if (root.left) { - root.left.parent = root; - restoreParent(root.left); - } +/***/ }), +/* 103 */ +/***/ (function(module, exports) { - if (root.right) { - root.right.parent = root; - restoreParent(root.right); - } -} +module.exports = function ruzicka(a, b) { + var ii = a.length, + up = 0, + down = 0; -// Binary heap implementation from: -// http://eloquentjavascript.net/appendix2.html -class BinaryHeap { - constructor(scoreFunction) { - this.content = []; - this.scoreFunction = scoreFunction; - } - - push(element) { - // Add the new element to the end of the array. - this.content.push(element); - // Allow it to bubble up. - this.bubbleUp(this.content.length - 1); - } - - pop() { - // Store the first element so we can return it later. - var result = this.content[0]; - // Get the element at the end of the array. - var end = this.content.pop(); - // If there are any elements left, put the end element at the - // start, and let it sink down. - if (this.content.length > 0) { - this.content[0] = end; - this.sinkDown(0); - } - return result; - } + for (var i = 0; i < ii; i++) { + up += Math.min(a[i], b[i]); + down += Math.max(a[i], b[i]); + } - peek() { - return this.content[0]; - } + return up / down; +}; - size() { - return this.content.length; - } +/***/ }), +/* 104 */ +/***/ (function(module, exports) { - bubbleUp(n) { - // Fetch the element that has to be moved. - var element = this.content[n]; - // When at 0, an element can not go up any further. - while (n > 0) { - // Compute the parent element's index, and fetch it. - var parentN = Math.floor((n + 1) / 2) - 1; - var parent = this.content[parentN]; - // Swap the elements if the parent is greater. - if (this.scoreFunction(element) < this.scoreFunction(parent)) { - this.content[parentN] = element; - this.content[n] = parent; - // Update 'n' to continue at the new position. - n = parentN; - } else { - // Found a parent that is less, no need to move it further. - break; - } - } - } +module.exports = function soergel(a, b) { + var ii = a.length, + up = 0, + down = 0; - sinkDown(n) { - // Look up the target element and its score. - var length = this.content.length; - var element = this.content[n]; - var elemScore = this.scoreFunction(element); - - while (true) { - // Compute the indices of the child elements. - var child2N = (n + 1) * 2; - var child1N = child2N - 1; - // This is used to store the new position of the element, - // if any. - var swap = null; - // If the first child exists (is inside the array)... - if (child1N < length) { - // Look it up and compute its score. - var child1 = this.content[child1N]; - var child1Score = this.scoreFunction(child1); - // If the score is less than our element's, we need to swap. - if (child1Score < elemScore) { - swap = child1N; - } - } - // Do the same checks for the other child. - if (child2N < length) { - var child2 = this.content[child2N]; - var child2Score = this.scoreFunction(child2); - if (child2Score < (swap === null ? elemScore : child1Score)) { - swap = child2N; - } - } + for (var i = 0; i < ii; i++) { + up += Math.abs(a[i] - b[i]); + down += Math.max(a[i], b[i]); + } - // If the element needs to be moved, swap it, and continue. - if (swap !== null) { - this.content[n] = this.content[swap]; - this.content[swap] = element; - n = swap; - } else { - // Otherwise, we are done. - break; - } - } - } -} + return up / down; +}; /***/ }), -/* 113 */ -/***/ (function(module, exports, __webpack_require__) { +/* 105 */ +/***/ (function(module, exports) { -"use strict"; +module.exports = function sorensen(a, b) { + var ii = a.length, + up = 0, + down = 0; + for (var i = 0; i < ii; i++) { + up += Math.abs(a[i] - b[i]); + down += a[i] + b[i]; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + return up / down; +}; + +/***/ }), +/* 106 */ +/***/ (function(module, exports) { -var _pls = __webpack_require__(114); +module.exports = function squared(a, b) { + var i = 0, + ii = a.length, + d = 0; -Object.defineProperty(exports, 'PLS', { - enumerable: true, - get: function get() { - return _pls.PLS; + for (; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]) / (a[i] + b[i]); } -}); -var _kopls = __webpack_require__(115); + return d; +}; + +/***/ }), +/* 107 */ +/***/ (function(module, exports) { + +module.exports = function taneja(a, b) { + var ii = a.length, + ans = 0; -Object.defineProperty(exports, 'KOPLS', { - enumerable: true, - get: function get() { - return _kopls.KOPLS; + for (var i = 0; i < ii; i++) { + ans += (a[i] + b[i]) / 2 * Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i]))); } -}); + + return ans; +}; /***/ }), -/* 114 */ +/* 108 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - +var tanimotoS = __webpack_require__(38); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.PLS = undefined; +module.exports = function tanimoto(a, b, bitvector) { + if (bitvector) return 1 - tanimotoS(a, b, bitvector);else { + var ii = a.length, + p = 0, + q = 0, + m = 0; -var _mlMatrix = __webpack_require__(0); + for (var i = 0; i < ii; i++) { + p += a[i]; + q += b[i]; + m += Math.min(a[i], b[i]); + } -var _mlMatrix2 = _interopRequireDefault(_mlMatrix); + return (p + q - 2 * m) / (p + q - m); + } +}; -var _matrix = __webpack_require__(10); +/***/ }), +/* 109 */ +/***/ (function(module, exports) { -var _matrix2 = _interopRequireDefault(_matrix); +module.exports = function topsoe(a, b) { + var ii = a.length, + ans = 0; -var _utils = __webpack_require__(34); + for (var i = 0; i < ii; i++) { + ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])) + b[i] * Math.log(2 * b[i] / (a[i] + b[i])); + } -var Utils = _interopRequireWildcard(_utils); + return ans; +}; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +/***/ }), +/* 110 */ +/***/ (function(module, exports, __webpack_require__) { -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +"use strict"; /** - * @class PLS + * Function that creates the tree + * @param {Array } X - chemical shifts of the signal + * @param {Array } Y - intensity of the signal + * @param {number} from - the low limit of x + * @param {number} to - the top limit of x + * @param {number} minWindow - smallest range to accept in x + * @param {number} threshold - smallest range to accept in y + * @returns {{sum: number, center: number, left: {json}, right: {json}}} + * left and right have the same structure than the parent, or have a + * undefined value if are leafs */ -class PLS { - /** - * Constructor for Partial Least Squares (PLS) - * @param {object} options - * @param {number} [options.latentVectors] - Number of latent vector to get (if the algorithm doesn't find a good model below the tolerance) - * @param {number} [options.tolerance=1e-5] - * @param {boolean} [options.scale=true] - rescale dataset using mean. - * @param {object} model - for load purposes. - */ - constructor(options, model) { - if (options === true) { - this.meanX = model.meanX; - this.stdDevX = model.stdDevX; - this.meanY = model.meanY; - this.stdDevY = model.stdDevY; - this.PBQ = _mlMatrix2.default.checkMatrix(model.PBQ); - this.R2X = model.R2X; - this.scale = model.scale; - this.scaleMethod = model.scaleMethod; - this.tolerance = model.tolerance; - } else { - var _options$tolerance = options.tolerance, - tolerance = _options$tolerance === undefined ? 1e-5 : _options$tolerance, - _options$scale = options.scale, - scale = _options$scale === undefined ? true : _options$scale; - - this.tolerance = tolerance; - this.scale = scale; - this.latentVectors = options.latentVectors; - } - } +function createTree(X, Y, from, to, minWindow, threshold) { + minWindow = minWindow || 0.16; + threshold = threshold || 0.01; + if (to - from < minWindow) return undefined; + var sum = 0; - /** - * Fits the model with the given data and predictions, in this function is calculated the - * following outputs: - * - * T - Score matrix of X - * P - Loading matrix of X - * U - Score matrix of Y - * Q - Loading matrix of Y - * B - Matrix of regression coefficient - * W - Weight matrix of X - * - * @param {Matrix|Array} trainingSet - * @param {Matrix|Array} trainingValues - */ - train(trainingSet, trainingValues) { - trainingSet = _mlMatrix2.default.checkMatrix(trainingSet); - trainingValues = _mlMatrix2.default.checkMatrix(trainingValues); + for (var i = 0; X[i] < to; i++) { + if (X[i] > from) sum += Y[i]; + } - if (trainingSet.length !== trainingValues.length) { - throw new RangeError('The number of X rows must be equal to the number of Y rows'); - } + if (sum < threshold) { + return undefined; + } - this.meanX = _matrix2.default.mean(trainingSet); - this.stdDevX = _matrix2.default.standardDeviation(trainingSet, this.meanX, true); - this.meanY = _matrix2.default.mean(trainingValues); - this.stdDevY = _matrix2.default.standardDeviation(trainingValues, this.meanY, true); + var center = 0; - if (this.scale) { - // here should be the ml-preprocess project - trainingSet = trainingSet.clone().subRowVector(this.meanX).divRowVector(this.stdDevX); - trainingValues = trainingValues.clone().subRowVector(this.meanY).divRowVector(this.stdDevY); - } + for (var j = 0; X[j] < to; j++) { + if (X[i] > from) center += X[j] * Y[j]; + } - if (this.latentVectors === undefined) { - this.latentVectors = Math.min(trainingSet.length - 1, trainingSet[0].length); - } + center = center / sum; + if (center - from < 10e-6 || to - center < 10e-6) return undefined; - var rx = trainingSet.rows; - var cx = trainingSet.columns; - var ry = trainingValues.rows; - var cy = trainingValues.columns; - - var ssqXcal = trainingSet.clone().mul(trainingSet).sum(); // for the r² - var sumOfSquaresY = trainingValues.clone().mul(trainingValues).sum(); - - var tolerance = this.tolerance; - var n = this.latentVectors; - var T = _mlMatrix2.default.zeros(rx, n); - var P = _mlMatrix2.default.zeros(cx, n); - var U = _mlMatrix2.default.zeros(ry, n); - var Q = _mlMatrix2.default.zeros(cy, n); - var B = _mlMatrix2.default.zeros(n, n); - var W = P.clone(); - var k = 0; + if (center - from < minWindow / 4) { + return createTree(X, Y, center, to, minWindow, threshold); + } else { + if (to - center < minWindow / 4) { + return createTree(X, Y, from, center, minWindow, threshold); + } else { + return { + 'sum': sum, + 'center': center, + 'left': createTree(X, Y, from, center, minWindow, threshold), + 'right': createTree(X, Y, center, to, minWindow, threshold) + }; + } + } +} +/** + * Similarity between two nodes + * @param {{sum: number, center: number, left: {json}, right: {json}}} a - tree A node + * @param {{sum: number, center: number, left: {json}, right: {json}}} b - tree B node + * @param {number} alpha - weights the relative importance of intensity vs. shift match + * @param {number} beta - weights the relative importance of node matching and children matching + * @param {number} gamma - controls the attenuation of the effect of chemical shift differences + * @returns {number} similarity measure between tree nodes + */ - while (Utils.norm(trainingValues) > tolerance && k < n) { - var transposeX = trainingSet.transpose(); - var transposeY = trainingValues.transpose(); - - var tIndex = maxSumColIndex(trainingSet.clone().mulM(trainingSet)); - var uIndex = maxSumColIndex(trainingValues.clone().mulM(trainingValues)); - - var t1 = trainingSet.getColumnVector(tIndex); - var u = trainingValues.getColumnVector(uIndex); - var t = _mlMatrix2.default.zeros(rx, 1); - - while (Utils.norm(t1.clone().sub(t)) > tolerance) { - var w = transposeX.mmul(u); - w.div(Utils.norm(w)); - t = t1; - t1 = trainingSet.mmul(w); - var q = transposeY.mmul(t1); - q.div(Utils.norm(q)); - u = trainingValues.mmul(q); - } - t = t1; - var num = transposeX.mmul(t); - var den = t.transpose().mmul(t)[0][0]; - var p = num.div(den); - var pnorm = Utils.norm(p); - p.div(pnorm); - t.mul(pnorm); - w.mul(pnorm); - - num = u.transpose().mmul(t); - den = t.transpose().mmul(t)[0][0]; - var b = num.div(den)[0][0]; - trainingSet.sub(t.mmul(p.transpose())); - trainingValues.sub(t.clone().mul(b).mmul(q.transpose())); - - T.setColumn(k, t); - P.setColumn(k, p); - U.setColumn(k, u); - Q.setColumn(k, q); - W.setColumn(k, w); - - B[k][k] = b; - k++; - } +function S(a, b, alpha, beta, gamma) { + if (a === undefined || b === undefined) { + return 0; + } else { + var C = alpha * Math.min(a.sum, b.sum) / Math.max(a.sum, b.sum) + (1 - alpha) * Math.exp(-gamma * Math.abs(a.center - b.center)); + } - k--; - T = T.subMatrix(0, T.rows - 1, 0, k); - P = P.subMatrix(0, P.rows - 1, 0, k); - U = U.subMatrix(0, U.rows - 1, 0, k); - Q = Q.subMatrix(0, Q.rows - 1, 0, k); - W = W.subMatrix(0, W.rows - 1, 0, k); - B = B.subMatrix(0, k, 0, k); - - // TODO: review of R2Y - //this.R2Y = t.transpose().mmul(t).mul(q[k][0]*q[k][0]).divS(ssqYcal)[0][0]; - // - this.ssqYcal = sumOfSquaresY; - this.E = trainingSet; - this.F = trainingValues; - this.T = T; - this.P = P; - this.U = U; - this.Q = Q; - this.W = W; - this.B = B; - this.PBQ = P.mmul(B).mmul(Q.transpose()); - this.R2X = t.transpose().mmul(t).mmul(p.transpose().mmul(p)).div(ssqXcal)[0][0]; - } + return beta * C + (1 - beta) * (S(a.left, b.left, alpha, beta, gamma) + S(a.right, b.right, alpha, beta, gamma)); +} +/** + * @type {number} alpha - weights the relative importance of intensity vs. shift match + * @type {number} beta - weights the relative importance of node matching and children matching + * @type {number} gamma - controls the attenuation of the effect of chemical shift differences + * @type {number} minWindow - smallest range to accept in x + * @type {number} threshold - smallest range to accept in y + */ - /** - * Predicts the behavior of the given dataset. - * @param {Matrix|Array} dataset - data to be predicted. - * @return {Matrix} - predictions of each element of the dataset. - */ - predict(dataset) { - var X = _mlMatrix2.default.checkMatrix(dataset); - if (this.scale) { - X = X.subRowVector(this.meanX).divRowVector(this.stdDevX); - } - var Y = X.mmul(this.PBQ); - Y = Y.mulRowVector(this.stdDevY).addRowVector(this.meanY); - return Y; - } - /** - * Returns the explained variance on training of the PLS model - * @return {number} - */ - getExplainedVariance() { - return this.R2X; - } +var defaultOptions = { + minWindow: 0.16, + threshold: 0.01, + alpha: 0.1, + beta: 0.33, + gamma: 0.001 +}; +/** + * Builds a tree based in the spectra and compares this trees + * @param {{x: Array, y: Array}} A - first spectra to be compared + * @param {{x: Array, y: Array}} B - second spectra to be compared + * @param {number} from - the low limit of x + * @param {number} to - the top limit of x + * @param {{minWindow: number, threshold: number, alpha: number, beta: number, gamma: number}} options + * @returns {number} similarity measure between the spectra + */ - /** - * Export the current model to JSON. - * @return {object} - Current model. - */ - toJSON() { - return { - name: 'PLS', - R2X: this.R2X, - meanX: this.meanX, - stdDevX: this.stdDevX, - meanY: this.meanY, - stdDevY: this.stdDevY, - PBQ: this.PBQ, - tolerance: this.tolerance, - scale: this.scale - }; - } +function tree(A, B, from, to, options) { + options = options || {}; - /** - * Load a PLS model from a JSON Object - * @param {object} model - * @return {PLS} - PLS object from the given model - */ - static load(model) { - if (model.name !== 'PLS') { - throw new RangeError('Invalid model: ' + model.name); - } - return new PLS(true, model); - } + for (var o in defaultOptions) if (!options.hasOwnProperty(o)) { + options[o] = defaultOptions[o]; + } + + var Atree, Btree; + if (A.sum) Atree = A;else Atree = createTree(A.x, A.y, from, to, options.minWindow, options.threshold); + if (B.sum) Btree = B;else Btree = createTree(B.x, B.y, from, to, options.minWindow, options.threshold); + return S(Atree, Btree, options.alpha, options.beta, options.gamma); } -exports.PLS = PLS; /** - * @private - * Function that returns the index where the sum of each - * column vector is maximum. - * @param {Matrix} data - * @return {number} index of the maximum - */ +module.exports = { + calc: tree, + createTree: createTree +}; -function maxSumColIndex(data) { - return data.sum('column').maxIndex()[0]; -} +/***/ }), +/* 111 */ +/***/ (function(module, exports) { + +module.exports = function waveHedges(a, b) { + var ii = a.length, + ans = 0; + + for (var i = 0; i < ii; i++) { + ans += 1 - Math.min(a[i], b[i]) / Math.max(a[i], b[i]); + } + + return ans; +}; /***/ }), -/* 115 */ +/* 112 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.KOPLS = undefined; +exports.cosine = __webpack_require__(39); +exports.czekanowski = __webpack_require__(31); +exports.dice = __webpack_require__(113); +exports.intersection = __webpack_require__(114); +exports.jaccard = __webpack_require__(115); +exports.kulczynski = __webpack_require__(116); +exports.motyka = __webpack_require__(117); +exports.pearson = __webpack_require__(118); +exports.squaredChord = __webpack_require__(119); +exports.tanimoto = __webpack_require__(38); -var _mlMatrix = __webpack_require__(0); +/***/ }), +/* 113 */ +/***/ (function(module, exports, __webpack_require__) { -var _utils = __webpack_require__(34); +var diceD = __webpack_require__(32); -/** - * @class KOPLS - */ -class KOPLS { +module.exports = function dice(a, b) { + return 1 - diceD(a, b); +}; - /** - * Constructor for Kernel-based Orthogonal Projections to Latent Structures (K-OPLS) - * @param {object} options - * @param {number} [options.predictiveComponents] - Number of predictive components to use. - * @param {number} [options.orthogonalComponents] - Number of Y-Orthogonal components. - * @param {Kernel} [options.kernel] - Kernel object to apply, see [ml-kernel](https://github.com/mljs/kernel). - * @param {object} model - for load purposes. - */ - constructor(options, model) { - if (options === true) { - this.trainingSet = new _mlMatrix.Matrix(model.trainingSet); - this.YLoadingMat = new _mlMatrix.Matrix(model.YLoadingMat); - this.SigmaPow = new _mlMatrix.Matrix(model.SigmaPow); - this.YScoreMat = new _mlMatrix.Matrix(model.YScoreMat); - this.predScoreMat = (0, _utils.initializeMatrices)(model.predScoreMat, false); - this.YOrthLoadingVec = (0, _utils.initializeMatrices)(model.YOrthLoadingVec, false); - this.YOrthEigen = model.YOrthEigen; - this.YOrthScoreMat = (0, _utils.initializeMatrices)(model.YOrthScoreMat, false); - this.toNorm = (0, _utils.initializeMatrices)(model.toNorm, false); - this.TURegressionCoeff = (0, _utils.initializeMatrices)(model.TURegressionCoeff, false); - this.kernelX = (0, _utils.initializeMatrices)(model.kernelX, true); - this.kernel = model.kernel; - this.orthogonalComp = model.orthogonalComp; - this.predictiveComp = model.predictiveComp; - } else { - if (options.predictiveComponents === undefined) { - throw new RangeError('no predictive components found!'); - } - if (options.orthogonalComponents === undefined) { - throw new RangeError('no orthogonal components found!'); - } - if (options.kernel === undefined) { - throw new RangeError('no kernel found!'); - } +/***/ }), +/* 114 */ +/***/ (function(module, exports, __webpack_require__) { - this.orthogonalComp = options.orthogonalComponents; - this.predictiveComp = options.predictiveComponents; - this.kernel = options.kernel; - } - } +var intersectionD = __webpack_require__(33); - /** - * Train the K-OPLS model with the given training set and labels. - * @param {Matrix|Array} trainingSet - * @param {Matrix|Array} trainingValues - */ - train(trainingSet, trainingValues) { - trainingSet = _mlMatrix.Matrix.checkMatrix(trainingSet); - trainingValues = _mlMatrix.Matrix.checkMatrix(trainingValues); +module.exports = function intersection(a, b) { + return 1 - intersectionD(a, b); +}; - // to save and compute kernel with the prediction dataset. - this.trainingSet = trainingSet.clone(); +/***/ }), +/* 115 */ +/***/ (function(module, exports, __webpack_require__) { - var kernelX = this.kernel.compute(trainingSet); +var jaccardD = __webpack_require__(34); - var Identity = _mlMatrix.Matrix.eye(kernelX.rows, kernelX.rows, 1); - var temp = kernelX; - kernelX = new _mlMatrix.Matrix(this.orthogonalComp + 1, this.orthogonalComp + 1); - kernelX[0][0] = temp; +module.exports = function jaccard(a, b) { + return 1 - jaccardD(a, b); +}; - var result = new _mlMatrix.SingularValueDecomposition(trainingValues.transpose().mmul(kernelX[0][0]).mmul(trainingValues), { - computeLeftSingularVectors: true, - computeRightSingularVectors: false - }); - var YLoadingMat = result.leftSingularVectors; - var Sigma = result.diagonalMatrix; - - YLoadingMat = YLoadingMat.subMatrix(0, YLoadingMat.rows - 1, 0, this.predictiveComp - 1); - Sigma = Sigma.subMatrix(0, this.predictiveComp - 1, 0, this.predictiveComp - 1); - - var YScoreMat = trainingValues.mmul(YLoadingMat); - - var predScoreMat = new Array(this.orthogonalComp + 1); - var TURegressionCoeff = new Array(this.orthogonalComp + 1); - var YOrthScoreMat = new Array(this.orthogonalComp); - var YOrthLoadingVec = new Array(this.orthogonalComp); - var YOrthEigen = new Array(this.orthogonalComp); - var YOrthScoreNorm = new Array(this.orthogonalComp); - - var SigmaPow = _mlMatrix.Matrix.pow(Sigma, -0.5); - // to avoid errors, check infinity - SigmaPow.apply(function (i, j) { - if (this[i][j] === Infinity) { - this[i][j] = 0.0; - } - }); +/***/ }), +/* 116 */ +/***/ (function(module, exports, __webpack_require__) { - for (var i = 0; i < this.orthogonalComp; ++i) { - predScoreMat[i] = kernelX[0][i].transpose().mmul(YScoreMat).mmul(SigmaPow); +var kulczynskiD = __webpack_require__(35); - var TpiPrime = predScoreMat[i].transpose(); - TURegressionCoeff[i] = (0, _mlMatrix.inverse)(TpiPrime.mmul(predScoreMat[i])).mmul(TpiPrime).mmul(YScoreMat); +module.exports = function kulczynski(a, b) { + return 1 / kulczynskiD(a, b); +}; - result = new _mlMatrix.SingularValueDecomposition(TpiPrime.mmul(_mlMatrix.Matrix.sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime))).mmul(predScoreMat[i]), { - computeLeftSingularVectors: true, - computeRightSingularVectors: false - }); - var CoTemp = result.leftSingularVectors; - var SoTemp = result.diagonalMatrix; +/***/ }), +/* 117 */ +/***/ (function(module, exports, __webpack_require__) { + +var motykaD = __webpack_require__(36); - YOrthLoadingVec[i] = CoTemp.subMatrix(0, CoTemp.rows - 1, 0, 0); - YOrthEigen[i] = SoTemp[0][0]; +module.exports = function motyka(a, b) { + return 1 - motykaD(a, b); +}; - YOrthScoreMat[i] = _mlMatrix.Matrix.sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime)).mmul(predScoreMat[i]).mmul(YOrthLoadingVec[i]).mul(Math.pow(YOrthEigen[i], -0.5)); +/***/ }), +/* 118 */ +/***/ (function(module, exports, __webpack_require__) { - var toiPrime = YOrthScoreMat[i].transpose(); - YOrthScoreNorm[i] = _mlMatrix.Matrix.sqrt(toiPrime.mmul(YOrthScoreMat[i])); +"use strict"; - YOrthScoreMat[i] = YOrthScoreMat[i].divRowVector(YOrthScoreNorm[i]); - var ITo = _mlMatrix.Matrix.sub(Identity, YOrthScoreMat[i].mmul(YOrthScoreMat[i].transpose())); +var stat = __webpack_require__(3).array; - kernelX[0][i + 1] = kernelX[0][i].mmul(ITo); - kernelX[i + 1][i + 1] = ITo.mmul(kernelX[i][i]).mmul(ITo); - } +var cosine = __webpack_require__(39); - var lastScoreMat = predScoreMat[this.orthogonalComp] = kernelX[0][this.orthogonalComp].transpose().mmul(YScoreMat).mmul(SigmaPow); +module.exports = function pearson(a, b) { + var avgA = stat.mean(a); + var avgB = stat.mean(b); + var newA = new Array(a.length); + var newB = new Array(b.length); + + for (var i = 0; i < newA.length; i++) { + newA[i] = a[i] - avgA; + newB[i] = b[i] - avgB; + } - var lastTpPrime = lastScoreMat.transpose(); - TURegressionCoeff[this.orthogonalComp] = (0, _mlMatrix.inverse)(lastTpPrime.mmul(lastScoreMat)).mmul(lastTpPrime).mmul(YScoreMat); + return cosine(newA, newB); +}; - this.YLoadingMat = YLoadingMat; - this.SigmaPow = SigmaPow; - this.YScoreMat = YScoreMat; - this.predScoreMat = predScoreMat; - this.YOrthLoadingVec = YOrthLoadingVec; - this.YOrthEigen = YOrthEigen; - this.YOrthScoreMat = YOrthScoreMat; - this.toNorm = YOrthScoreNorm; - this.TURegressionCoeff = TURegressionCoeff; - this.kernelX = kernelX; - } +/***/ }), +/* 119 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Predicts the output given the matrix to predict. - * @param {Matrix|Array} toPredict - * @return {{y: Matrix, predScoreMat: Array, predYOrthVectors: Array}} predictions - */ - predict(toPredict) { +var squaredChordD = __webpack_require__(37); - var KTestTrain = this.kernel.compute(toPredict, this.trainingSet); +module.exports = function squaredChord(a, b) { + return 1 - squaredChordD(a, b); +}; - var temp = KTestTrain; - KTestTrain = new _mlMatrix.Matrix(this.orthogonalComp + 1, this.orthogonalComp + 1); - KTestTrain[0][0] = temp; +/***/ }), +/* 120 */ +/***/ (function(module, exports, __webpack_require__) { - var YOrthScoreVector = new Array(this.orthogonalComp); - var predScoreMat = new Array(this.orthogonalComp); +"use strict"; - var i; - for (i = 0; i < this.orthogonalComp; ++i) { - predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow); - YOrthScoreVector[i] = _mlMatrix.Matrix.sub(KTestTrain[i][i], predScoreMat[i].mmul(this.predScoreMat[i].transpose())).mmul(this.predScoreMat[i]).mmul(this.YOrthLoadingVec[i]).mul(Math.pow(this.YOrthEigen[i], -0.5)); +const measures = __webpack_require__(121); - YOrthScoreVector[i] = YOrthScoreVector[i].divRowVector(this.toNorm[i]); +class Performance { + /** + * + * @param prediction - The prediction matrix + * @param target - The target matrix (values: truthy for same class, falsy for different class) + * @param options + * + * @option all True if the entire matrix must be used. False to ignore the diagonal and lower part (default is false, for similarity/distance matrices) + * @option max True if the max value corresponds to a perfect match (like in similarity matrices), false if it is the min value (default is false, like in distance matrices. All values will be multiplied by -1) + */ + constructor(prediction, target, options) { + options = options || {}; - var scoreMatPrime = this.YOrthScoreMat[i].transpose(); - KTestTrain[i + 1][0] = _mlMatrix.Matrix.sub(KTestTrain[i][0], YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[0][i].transpose())); + if (prediction.length !== target.length || prediction[0].length !== target[0].length) { + throw new Error('dimensions of prediction and target do not match'); + } - var p1 = _mlMatrix.Matrix.sub(KTestTrain[i][0], KTestTrain[i][i].mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime)); - var p2 = YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[i][i]); - var p3 = p2.mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime); + const rows = prediction.length; + const columns = prediction[0].length; + const isDistance = !options.max; + const predP = []; - KTestTrain[i + 1][i + 1] = p1.sub(p2).add(p3); + if (options.all) { + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + predP.push({ + pred: prediction[i][j], + targ: target[i][j] + }); } + } + } else { + if (rows < 3 || rows !== columns) { + throw new Error('When "all" option is false, the prediction matrix must be square and have at least 3 columns'); + } - predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow); - var prediction = predScoreMat[i].mmul(this.TURegressionCoeff[i]).mmul(this.YLoadingMat.transpose()); - - return { - prediction: prediction, - predScoreMat: predScoreMat, - predYOrthVectors: YOrthScoreVector - }; + for (var i = 0; i < rows - 1; i++) { + for (var j = i + 1; j < columns; j++) { + predP.push({ + pred: prediction[i][j], + targ: target[i][j] + }); + } + } } - /** - * Export the current model to JSON. - * @return {object} - Current model. - */ - toJSON() { - return { - name: 'K-OPLS', - YLoadingMat: this.YLoadingMat, - SigmaPow: this.SigmaPow, - YScoreMat: this.YScoreMat, - predScoreMat: this.predScoreMat, - YOrthLoadingVec: this.YOrthLoadingVec, - YOrthEigen: this.YOrthEigen, - YOrthScoreMat: this.YOrthScoreMat, - toNorm: this.toNorm, - TURegressionCoeff: this.TURegressionCoeff, - kernelX: this.kernelX, - trainingSet: this.trainingSet, - orthogonalComp: this.orthogonalComp, - predictiveComp: this.predictiveComp - }; + if (isDistance) { + predP.sort((a, b) => a.pred - b.pred); + } else { + predP.sort((a, b) => b.pred - a.pred); } - /** - * Load a K-OPLS with the given model. - * @param {object} model - * @param {Kernel} kernel - kernel used on the model, see [ml-kernel](https://github.com/mljs/kernel). - * @return {KOPLS} - */ - static load(model, kernel) { - if (model.name !== 'K-OPLS') { - throw new RangeError('Invalid model: ' + model.name); - } + const cutoffs = this.cutoffs = [isDistance ? Number.MIN_VALUE : Number.MAX_VALUE]; + const fp = this.fp = [0]; + const tp = this.tp = [0]; + var nPos = 0; + var nNeg = 0; + var currentPred = predP[0].pred; + var nTp = 0; + var nFp = 0; - if (!kernel) { - throw new RangeError('You must provide a kernel for the model!'); - } + for (var i = 0; i < predP.length; i++) { + if (predP[i].pred !== currentPred) { + cutoffs.push(currentPred); + fp.push(nFp); + tp.push(nTp); + currentPred = predP[i].pred; + } - model.kernel = kernel; - return new KOPLS(true, model); + if (predP[i].targ) { + nPos++; + nTp++; + } else { + nNeg++; + nFp++; + } } -} -exports.KOPLS = KOPLS; - -/***/ }), -/* 116 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + cutoffs.push(currentPred); + fp.push(nFp); + tp.push(nTp); + const l = cutoffs.length; + const fn = this.fn = new Array(l); + const tn = this.tn = new Array(l); + const nPosPred = this.nPosPred = new Array(l); + const nNegPred = this.nNegPred = new Array(l); + for (var i = 0; i < l; i++) { + fn[i] = nPos - tp[i]; + tn[i] = nNeg - fp[i]; + nPosPred[i] = tp[i] + fp[i]; + nNegPred[i] = tn[i] + fn[i]; + } -var ConfusionMatrix = __webpack_require__(35); + this.nPos = nPos; + this.nNeg = nNeg; + this.nSamples = nPos + nNeg; + } + /** + * Computes a measure from the prediction object. + * + * Many measures are available and can be combined : + * To create a ROC curve, you need fpr and tpr + * To create a DET curve, you need fnr and fpr + * To create a Lift chart, you need rpp and lift + * + * Possible measures are : threshold (Threshold), acc (Accuracy), err (Error rate), + * fpr (False positive rate), tpr (True positive rate), fnr (False negative rate), tnr (True negative rate), ppv (Positive predictive value), + * npv (Negative predictive value), pcfall (Prediction-conditioned fallout), pcmiss (Prediction-conditioned miss), lift (Lift value), rpp (Rate of positive predictions), rnp (Rate of negative predictions) + * + * @param measure - The short name of the measure + * + * @return [number] + */ -var CV = {}; -var combinations = __webpack_require__(117); -/** - * Performs a leave-one-out cross-validation (LOO-CV) of the given samples. In LOO-CV, 1 observation is used as the - * validation set while the rest is used as the training set. This is repeated once for each observation. LOO-CV is a - * special case of LPO-CV. @see leavePout - * @param {function} Classifier - The classifier's constructor to use for the cross validation. Expect ml-classifier - * api. - * @param {Array} features - The features for all samples of the data-set - * @param {Array} labels - The classification class of all samples of the data-set - * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated. - * @return {ConfusionMatrix} - The cross-validation confusion matrix - */ -CV.leaveOneOut = function (Classifier, features, labels, classifierOptions) { - if (typeof labels === 'function') { - var callback = labels; - labels = features; - features = Classifier; - return CV.leavePOut(features, labels, 1, callback); + getMeasure(measure) { + if (typeof measure !== 'string') { + throw new Error('No measure specified'); } - return CV.leavePOut(Classifier, features, labels, classifierOptions, 1); -}; - -/** - * Performs a leave-p-out cross-validation (LPO-CV) of the given samples. In LPO-CV, p observations are used as the - * validation set while the rest is used as the training set. This is repeated as many times as there are possible - * ways to combine p observations from the set (unordered without replacement). Be aware that for relatively small - * data-set size this can require a very large number of training and testing to do! - * @param {function} Classifier - The classifier's constructor to use for the cross validation. Expect ml-classifier - * api. - * @param {Array} features - The features for all samples of the data-set - * @param {Array} labels - The classification class of all samples of the data-set - * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated. - * @param {number} p - The size of the validation sub-samples' set - * @return {ConfusionMatrix} - The cross-validation confusion matrix - */ -CV.leavePOut = function (Classifier, features, labels, classifierOptions, p) { - if (typeof classifierOptions === 'function') { - var callback = classifierOptions; - p = labels; - labels = features; - features = Classifier; - } - check(features, labels); - var distinct = getDistinct(labels); - var confusionMatrix = initMatrix(distinct.length, distinct.length); - - var N = features.length; - var gen = combinations(p, N); - var allIdx = new Array(N); - for (var i = 0; i < N; i++) { - allIdx[i] = i; - } - for (var testIdx of gen) { - var trainIdx = allIdx.slice(); - - for (var _i = testIdx.length - 1; _i >= 0; _i--) { - trainIdx.splice(testIdx[_i], 1); - } - if (callback) { - validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback); - } else { - validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct); - } + if (!measures[measure]) { + throw new Error("The specified measure (".concat(measure, ") does not exist")); } - return new ConfusionMatrix(confusionMatrix, distinct); -}; + return measures[measure](this); + } + /** + * Returns the area under the ROC curve + */ -/** - * Performs k-fold cross-validation (KF-CV). KF-CV separates the data-set into k random equally sized partitions, and - * uses each as a validation set, with all other partitions used in the training set. Observations left over from if k - * does not divide the number of observations are left out of the cross-validation process. - * @param {function} Classifier - The classifier's to use for the cross validation. Expect ml-classifier api. - * @param {Array} features - The features for all samples of the data-set - * @param {Array} labels - The classification class of all samples of the data-set - * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated. - * @param {number} k - The number of partitions to create - * @return {ConfusionMatrix} - The cross-validation confusion matrix - */ -CV.kFold = function (Classifier, features, labels, classifierOptions, k) { - if (typeof classifierOptions === 'function') { - var callback = classifierOptions; - k = labels; - labels = features; - features = Classifier; - } - check(features, labels); - var distinct = getDistinct(labels); - var confusionMatrix = initMatrix(distinct.length, distinct.length); - var N = features.length; - var allIdx = new Array(N); - for (var i = 0; i < N; i++) { - allIdx[i] = i; - } - - var l = Math.floor(N / k); - // create random k-folds - var current = []; - var folds = []; - while (allIdx.length) { - var randi = Math.floor(Math.random() * allIdx.length); - current.push(allIdx[randi]); - allIdx.splice(randi, 1); - if (current.length === l) { - folds.push(current); - current = []; - } - } - if (current.length) folds.push(current); - folds = folds.slice(0, k); - for (i = 0; i < folds.length; i++) { - var testIdx = folds[i]; - var trainIdx = []; - for (var j = 0; j < folds.length; j++) { - if (j !== i) trainIdx = trainIdx.concat(folds[j]); - } + getAURC() { + const l = this.cutoffs.length; + const x = new Array(l); + const y = new Array(l); - if (callback) { - validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback); - } else { - validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct); - } + for (var i = 0; i < l; i++) { + x[i] = this.fp[i] / this.nNeg; + y[i] = this.tp[i] / this.nPos; } - return new ConfusionMatrix(confusionMatrix, distinct); -}; + var auc = 0; -function check(features, labels) { - if (features.length !== labels.length) { - throw new Error('features and labels should have the same length'); + for (i = 1; i < l; i++) { + auc += 0.5 * (x[i] - x[i - 1]) * (y[i] + y[i - 1]); } -} -function initMatrix(rows, columns) { - return new Array(rows).fill(0).map(() => new Array(columns).fill(0)); -} + return auc; + } + /** + * Returns the area under the DET curve + */ -function getDistinct(arr) { - var s = new Set(); - for (var i = 0; i < arr.length; i++) { - s.add(arr[i]); - } - return Array.from(s); -} -function validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct) { - var _getTrainTest = getTrainTest(features, labels, testIdx, trainIdx), - testFeatures = _getTrainTest.testFeatures, - trainFeatures = _getTrainTest.trainFeatures, - testLabels = _getTrainTest.testLabels, - trainLabels = _getTrainTest.trainLabels; - - var classifier; - if (Classifier.prototype.train) { - classifier = new Classifier(classifierOptions); - classifier.train(trainFeatures, trainLabels); - } else { - classifier = new Classifier(trainFeatures, trainLabels, classifierOptions); - } + getAUDC() { + const l = this.cutoffs.length; + const x = new Array(l); + const y = new Array(l); - var predictedLabels = classifier.predict(testFeatures); - updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct); -} + for (var i = 0; i < l; i++) { + x[i] = this.fn[i] / this.nPos; + y[i] = this.fp[i] / this.nNeg; + } -function validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback) { - var _getTrainTest2 = getTrainTest(features, labels, testIdx, trainIdx), - testFeatures = _getTrainTest2.testFeatures, - trainFeatures = _getTrainTest2.trainFeatures, - testLabels = _getTrainTest2.testLabels, - trainLabels = _getTrainTest2.trainLabels; + var auc = 0; - var predictedLabels = callback(trainFeatures, trainLabels, testFeatures); - updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct); -} + for (i = 1; i < l; i++) { + auc += 0.5 * (x[i] + x[i - 1]) * (y[i] - y[i - 1]); + } -function updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct) { + return auc; + } - for (var i = 0; i < predictedLabels.length; i++) { - var actualIdx = distinct.indexOf(testLabels[i]); - var predictedIdx = distinct.indexOf(predictedLabels[i]); - if (actualIdx < 0 || predictedIdx < 0) { - // eslint-disable-next-line no-console - console.warn(`ignore unknown predicted label ${predictedLabels[i]}`); - } - confusionMatrix[actualIdx][predictedIdx]++; + getDistribution(options) { + options = options || {}; + var cutLength = this.cutoffs.length; + var cutLow = options.xMin || Math.floor(this.cutoffs[cutLength - 1] * 100) / 100; + var cutHigh = options.xMax || Math.ceil(this.cutoffs[1] * 100) / 100; + var interval = options.interval || Math.floor((cutHigh - cutLow) / 20 * 10000000 - 1) / 10000000; // Trick to avoid the precision problem of float numbers + + var xLabels = []; + var interValues = []; + var intraValues = []; + var interCumPercent = []; + var intraCumPercent = []; + var nTP = this.tp[cutLength - 1], + currentTP = 0; + var nFP = this.fp[cutLength - 1], + currentFP = 0; + + for (var i = cutLow, j = cutLength - 1; i <= cutHigh; i += interval) { + while (this.cutoffs[j] < i) j--; + + xLabels.push(i); + var thisTP = nTP - currentTP - this.tp[j]; + var thisFP = nFP - currentFP - this.fp[j]; + currentTP += thisTP; + currentFP += thisFP; + interValues.push(thisFP); + intraValues.push(thisTP); + interCumPercent.push(100 - (nFP - this.fp[j]) / nFP * 100); + intraCumPercent.push(100 - (nTP - this.tp[j]) / nTP * 100); } -} -function getTrainTest(features, labels, testIdx, trainIdx) { return { - testFeatures: testIdx.map(function (index) { - return features[index]; - }), - trainFeatures: trainIdx.map(function (index) { - return features[index]; - }), - testLabels: testIdx.map(function (index) { - return labels[index]; - }), - trainLabels: trainIdx.map(function (index) { - return labels[index]; - }) + xLabels: xLabels, + interValues: interValues, + intraValues: intraValues, + interCumPercent: interCumPercent, + intraCumPercent: intraCumPercent }; + } + } -module.exports = CV; +Performance.names = { + acc: 'Accuracy', + err: 'Error rate', + fpr: 'False positive rate', + tpr: 'True positive rate', + fnr: 'False negative rate', + tnr: 'True negative rate', + ppv: 'Positive predictive value', + npv: 'Negative predictive value', + pcfall: 'Prediction-conditioned fallout', + pcmiss: 'Prediction-conditioned miss', + lift: 'Lift value', + rpp: 'Rate of positive predictions', + rnp: 'Rate of negative predictions', + threshold: 'Threshold' +}; +module.exports = Performance; /***/ }), -/* 117 */ +/* 121 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; + // Accuracy +exports.acc = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); -(function (global, factory) { - true ? factory() : typeof define === 'function' && define.amd ? define(factory) : factory(); -})(undefined, function () { - 'use strict'; + for (var i = 0; i < l; i++) { + result[i] = (pred.tn[i] + pred.tp[i]) / (l - 1); + } - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } + return result; +}; // Error rate - var runtime = createCommonjsModule(function (module) { - /** - * Copyright (c) 2014-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - !function (global) { - - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - var runtime = global.regeneratorRuntime; - if (runtime) { - { - // If regeneratorRuntime is defined globally and we're in a module, - // make the exports object identical to regeneratorRuntime. - module.exports = runtime; - } - // Don't bother evaluating the rest of this file if the runtime was - // already defined globally. - return; - } - - // Define the runtime globally (as expected by generated code) as either - // module.exports (if we're in a module) or a new, empty object. - runtime = global.regeneratorRuntime = module.exports; - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); - - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); - - return generator; - } - runtime.wrap = wrap; - - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; - - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; - - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - - // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - var IteratorPrototype = {}; - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function (method) { - prototype[method] = function (arg) { - return this._invoke(method, arg); - }; - }); - } - - runtime.isGeneratorFunction = function (genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" : false; - }; - - runtime.mark = function (genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } - } - genFun.prototype = Object.create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - runtime.awrap = function (arg) { - return { __await: arg }; - }; - - function AsyncIterator(generator) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value && typeof value === "object" && hasOwn.call(value, "__await")) { - return Promise.resolve(value.__await).then(function (value) { - invoke("next", value, resolve, reject); - }, function (err) { - invoke("throw", err, resolve, reject); - }); - } - - return Promise.resolve(value).then(function (unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. If the Promise is rejected, however, the - // result for this iteration will be rejected with the same - // reason. Note that rejections of yielded Promises are not - // thrown back into the generator function, as is the case - // when an awaited Promise is rejected. This difference in - // behavior between yield and await is important, because it - // allows the consumer to decide what to do with the yielded - // rejection (swallow it and continue, manually .throw it back - // into the generator, abandon iteration, whatever). With - // await, by contrast, there is no opportunity to examine the - // rejection reason outside the generator function, so the - // only option is to throw it from the await expression, and - // let the generator function handle the exception. - result.value = unwrapped; - resolve(result); - }, reject); - } - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new Promise(function (resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; - runtime.AsyncIterator = AsyncIterator; - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - runtime.async = function (innerFn, outerFn, self, tryLocsList) { - var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList)); - - return runtime.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function (result) { - return result.done ? result.value : iter.next(); - }); - }; - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } - - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done ? GenStateCompleted : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } - - // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - if (method === undefined) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - if (delegate.iterator.return) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError("The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (!info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; - - // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; - - // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined; - } - } else { - // Re-yield the result returned by the delegate method. - return info; - } - - // The delegate iterator is finished, so forget it and continue with - // the outer generator. - context.delegate = null; - return ContinueSentinel; - } - - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); - - Gp[toStringTagSymbol] = "Generator"; - - // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - Gp[iteratorSymbol] = function () { - return this; - }; - - Gp.toString = function () { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - runtime.keys = function (object) { - var keys = []; - for (var key in object) { - keys.push(key); - } - keys.reverse(); - - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } - - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, - next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined; - next.done = true; - - return next; - }; - - return next.next = next; - } - } - - // Return an iterator with no values. - return { next: doneResult }; - } - runtime.values = values; - - function doneResult() { - return { value: undefined, done: true }; - } - - Context.prototype = { - constructor: Context, - - reset: function reset(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined; - this.done = false; - this.delegate = null; - - this.method = "next"; - this.arg = undefined; - - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { - this[name] = undefined; - } - } - } - }, - - stop: function stop() { - this.done = true; - - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - - dispatchException: function dispatchException(exception) { - if (this.done) { - throw exception; - } - - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined; - } - - return !!caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - - abrupt: function abrupt(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - - complete: function complete(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - - finish: function finish(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - - "catch": function _catch(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } - - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, - - delegateYield: function delegateYield(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined; - } - - return ContinueSentinel; - } - }; - }( - // In sloppy mode, unbound `this` refers to the global object, fallback to - // Function constructor if we're in global strict mode. That is sadly a form - // of indirect eval which violates Content Security Policy. - function () { - return this; - }() || Function("return this")()); - }); - - /** - * Copyright (c) 2014-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - // This method of obtaining a reference to the global object needs to be - // kept identical to the way it is obtained in runtime.js - var g = function () { - return this; - }() || Function("return this")(); - - // Use `getOwnPropertyNames` because not all browsers support calling - // `hasOwnProperty` on the global `self` object in a worker. See #183. - var hadRuntime = g.regeneratorRuntime && Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0; - - // Save the old regeneratorRuntime in case it needs to be restored later. - var oldRuntime = hadRuntime && g.regeneratorRuntime; - - // Force reevalutation of runtime.js. - g.regeneratorRuntime = undefined; - - var runtimeModule = runtime; - - if (hadRuntime) { - // Restore the original runtime. - g.regeneratorRuntime = oldRuntime; - } else { - // Remove the global property added by runtime.js. - try { - delete g.regeneratorRuntime; - } catch (e) { - g.regeneratorRuntime = undefined; - } - } - - var regenerator = runtimeModule; - - var defaultOptions = { - mode: 'index' - }; - - module.exports = /*#__PURE__*/regenerator.mark(function _callee(M, N, options) { - var a, c, b, p, x, y, z, i, twiddle; - return regenerator.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - twiddle = function twiddle() { - var i, j, k; - j = 1; - while (p[j] <= 0) { - j++; - } - if (p[j - 1] === 0) { - for (i = j - 1; i !== 1; i--) { - p[i] = -1; - } - p[j] = 0; - x = z = 0; - p[1] = 1; - y = j - 1; - } else { - if (j > 1) { - p[j - 1] = 0; - } - do { - j++; - } while (p[j] > 0); - k = j - 1; - i = j; - while (p[i] === 0) { - p[i++] = -1; - } - if (p[i] === -1) { - p[i] = p[k]; - z = p[k] - 1; - x = i - 1; - y = k - 1; - p[k] = -1; - } else { - if (i === p[0]) { - return 0; - } else { - p[j] = p[i]; - z = p[i] - 1; - p[i] = 0; - x = j - 1; - y = i - 1; - } - } - } - return 1; - }; - - options = Object.assign({}, defaultOptions, options); - a = new Array(N); - c = new Array(M); - b = new Array(N); - p = new Array(N + 2); - - // init a and b - for (i = 0; i < N; i++) { - a[i] = i; - if (i < N - M) b[i] = 0;else b[i] = 1; - } - - // init c - for (i = 0; i < M; i++) { - c[i] = N - M + i; - } - - // init p - for (i = 0; i < p.length; i++) { - if (i === 0) p[i] = N + 1;else if (i <= N - M) p[i] = 0;else if (i <= N) p[i] = i - N + M;else p[i] = -2; - } - - if (!(options.mode === 'index')) { - _context.next = 20; - break; - } - - _context.next = 12; - return c.slice(); - - case 12: - if (!twiddle()) { - _context.next = 18; - break; - } - - c[z] = a[x]; - _context.next = 16; - return c.slice(); - - case 16: - _context.next = 12; - break; - - case 18: - _context.next = 33; - break; - - case 20: - if (!(options.mode === 'mask')) { - _context.next = 32; - break; - } - - _context.next = 23; - return b.slice(); - - case 23: - if (!twiddle()) { - _context.next = 30; - break; - } - - b[x] = 1; - b[y] = 0; - _context.next = 28; - return b.slice(); - - case 28: - _context.next = 23; - break; - - case 30: - _context.next = 33; - break; - - case 32: - throw new Error('Invalid mode'); - - case 33: - case 'end': - return _context.stop(); - } - } - }, _callee, this); - }); -}); +exports.err = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); -/***/ }), -/* 118 */ -/***/ (function(module, exports, __webpack_require__) { + for (var i = 0; i < l; i++) { + result[i] = pred.fn[i] + pred.fp[i] / (l - 1); + } -"use strict"; + return result; +}; // False positive rate -var Matrix = __webpack_require__(0).Matrix; +exports.fpr = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); -var Layer = __webpack_require__(36); -var OutputLayer = __webpack_require__(119); -var Utils = __webpack_require__(37); -var ACTIVATION_FUNCTIONS = __webpack_require__(38); + for (var i = 0; i < l; i++) { + result[i] = pred.fp[i] / pred.nNeg; + } -class FeedForwardNeuralNetworks { + return result; +}; // True positive rate - /** - * Create a new Feedforword neural network model. - * @class FeedForwardNeuralNetworks - * @param {object} [options] - * @param {Array} [options.hiddenLayers=[10]] - Array that contains the sizes of the hidden layers. - * @param {number} [options.iterations=50] - Number of iterations at the training step. - * @param {number} [options.learningRate=0.01] - Learning rate of the neural net (also known as epsilon). - * @param {number} [options.regularization=0.01] - Regularization parameter af the neural net. - * @param {string} [options.activation='tanh'] - activation function to be used. (options: 'tanh'(default), - * 'identity', 'logistic', 'arctan', 'softsign', 'relu', 'softplus', 'bent', 'sinusoid', 'sinc', 'gaussian'). - * (single-parametric options: 'parametric-relu', 'exponential-relu', 'soft-exponential'). - * @param {number} [options.activationParam=1] - if the selected activation function needs a parameter. - */ - constructor(options) { - options = options || {}; - if (options.model) { - // load network - this.hiddenLayers = options.hiddenLayers; - this.iterations = options.iterations; - this.learningRate = options.learningRate; - this.regularization = options.regularization; - this.dicts = options.dicts; - this.activation = options.activation; - this.activationParam = options.activationParam; - this.model = new Array(options.layers.length); - - for (var i = 0; i < this.model.length - 1; ++i) { - this.model[i] = Layer.load(options.layers[i]); - } - this.model[this.model.length - 1] = OutputLayer.load(options.layers[this.model.length - 1]); - } else { - // default constructor - this.hiddenLayers = options.hiddenLayers || [10]; - this.iterations = options.iterations || 50; - this.learningRate = options.learningRate || 0.01; - this.regularization = options.regularization || 0.01; +exports.tpr = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); - this.activation = options.activation || 'tanh'; - this.activationParam = options.activationParam || 1; - if (!(this.activation in Object.keys(ACTIVATION_FUNCTIONS))) { - this.activation = 'tanh'; - } - } - } + for (var i = 0; i < l; i++) { + result[i] = pred.tp[i] / pred.nPos; + } - /** - * @private - * Function that build and initialize the neural net. - * @param {number} inputSize - total of features to fit. - * @param {number} outputSize - total of labels of the prediction set. - */ - buildNetwork(inputSize, outputSize) { - var size = 2 + (this.hiddenLayers.length - 1); - this.model = new Array(size); - - // input layer - this.model[0] = new Layer({ - inputSize: inputSize, - outputSize: this.hiddenLayers[0], - activation: this.activation, - activationParam: this.activationParam, - regularization: this.regularization, - epsilon: this.learningRate - }); + return result; +}; // False negative rate - // hidden layers - for (var i = 1; i < this.hiddenLayers.length; ++i) { - this.model[i] = new Layer({ - inputSize: this.hiddenLayers[i - 1], - outputSize: this.hiddenLayers[i], - activation: this.activation, - activationParam: this.activationParam, - regularization: this.regularization, - epsilon: this.learningRate - }); - } - // output layer - this.model[size - 1] = new OutputLayer({ - inputSize: this.hiddenLayers[this.hiddenLayers.length - 1], - outputSize: outputSize, - activation: this.activation, - activationParam: this.activationParam, - regularization: this.regularization, - epsilon: this.learningRate - }); - } +exports.fnr = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); - /** - * Train the neural net with the given features and labels. - * @param {Matrix|Array} features - * @param {Matrix|Array} labels - */ - train(features, labels) { - features = Matrix.checkMatrix(features); - this.dicts = Utils.dictOutputs(labels); + for (var i = 0; i < l; i++) { + result[i] = pred.fn[i] / pred.nPos; + } - var inputSize = features.columns; - var outputSize = Object.keys(this.dicts.inputs).length; + return result; +}; // True negative rate - this.buildNetwork(inputSize, outputSize); - for (var i = 0; i < this.iterations; ++i) { - var probabilities = this.propagate(features); - this.backpropagation(features, labels, probabilities); - } - } +exports.tnr = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); - /** - * @private - * Propagate the input(training set) and retrives the probabilities of each class. - * @param {Matrix} X - * @return {Matrix} probabilities of each class. - */ - propagate(X) { - var input = X; - for (var i = 0; i < this.model.length; ++i) { - //console.log(i); - input = this.model[i].forward(input); - } + for (var i = 0; i < l; i++) { + result[i] = pred.tn[i] / pred.nNeg; + } - // get probabilities - return input.divColumnVector(Utils.sumRow(input)); - } + return result; +}; // Positive predictive value - /** - * @private - * Function that applies the backpropagation algorithm on each layer of the network - * in order to fit the features and labels. - * @param {Matrix} features - * @param {Array} labels - * @param {Matrix} probabilities - probabilities of each class of the feature set. - */ - backpropagation(features, labels, probabilities) { - for (var i = 0; i < probabilities.length; ++i) { - probabilities[i][this.dicts.inputs[labels[i]]] -= 1; - } - // remember, the last delta doesn't matter - var delta = probabilities; - for (i = this.model.length - 1; i >= 0; --i) { - var a = i > 0 ? this.model[i - 1].a : features; - delta = this.model[i].backpropagation(delta, a); - } +exports.ppv = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); - for (i = 0; i < this.model.length; ++i) { - this.model[i].update(); - } - } + for (var i = 0; i < l; i++) { + result[i] = pred.fp[i] + pred.tp[i] !== 0 ? pred.tp[i] / (pred.fp[i] + pred.tp[i]) : 0; + } - /** - * Predict the output given the feature set. - * @param {Array|Matrix} features - * @return {Array} - */ - predict(features) { - features = Matrix.checkMatrix(features); - var outputs = new Array(features.rows); - var probabilities = this.propagate(features); - for (var i = 0; i < features.rows; ++i) { - outputs[i] = this.dicts.outputs[probabilities.maxRowIndex(i)[1]]; - } + return result; +}; // Negative predictive value - return outputs; - } - /** - * Export the current model to JSON. - * @return {object} model - */ - toJSON() { - var model = { - model: 'FNN', - hiddenLayers: this.hiddenLayers, - iterations: this.iterations, - learningRate: this.learningRate, - regularization: this.regularization, - activation: this.activation, - activationParam: this.activationParam, - dicts: this.dicts, - layers: new Array(this.model.length) - }; +exports.npv = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); - for (var i = 0; i < this.model.length; ++i) { - model.layers[i] = this.model[i].toJSON(); - } + for (var i = 0; i < l; i++) { + result[i] = pred.fn[i] + pred.tn[i] !== 0 ? pred.tn[i] / (pred.fn[i] + pred.tn[i]) : 0; + } + + return result; +}; // Prediction conditioned fallout + + +exports.pcfall = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + + for (var i = 0; i < l; i++) { + result[i] = pred.fp[i] + pred.tp[i] !== 0 ? 1 - pred.tp[i] / (pred.fp[i] + pred.tp[i]) : 1; + } + + return result; +}; // Prediction conditioned miss + + +exports.pcmiss = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + + for (var i = 0; i < l; i++) { + result[i] = pred.fn[i] + pred.tn[i] !== 0 ? 1 - pred.tn[i] / (pred.fn[i] + pred.tn[i]) : 1; + } + + return result; +}; // Lift value + + +exports.lift = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); - return model; - } + for (var i = 0; i < l; i++) { + result[i] = pred.nPosPred[i] !== 0 ? pred.tp[i] / pred.nPos / (pred.nPosPred[i] / pred.nSamples) : 0; + } - /** - * Load a Feedforward Neural Network with the current model. - * @param {object} model - * @return {FeedForwardNeuralNetworks} - */ - static load(model) { - if (model.model !== 'FNN') { - throw new RangeError('the current model is not a feed forward network'); - } + return result; +}; // Rate of positive predictions - return new FeedForwardNeuralNetworks(model); - } -} -module.exports = FeedForwardNeuralNetworks; +exports.rpp = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); -/***/ }), -/* 119 */ -/***/ (function(module, exports, __webpack_require__) { + for (var i = 0; i < l; i++) { + result[i] = pred.nPosPred[i] / pred.nSamples; + } -"use strict"; + return result; +}; // Rate of negative predictions -var Layer = __webpack_require__(36); +exports.rnp = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); -class OutputLayer extends Layer { - constructor(options) { - super(options); + for (var i = 0; i < l; i++) { + result[i] = pred.nNegPred[i] / pred.nSamples; + } - this.activationFunction = function (i, j) { - this[i][j] = Math.exp(this[i][j]); - }; - } + return result; +}; // Threshold - static load(model) { - if (model.model !== 'Layer') { - throw new RangeError('the current model is not a Layer model'); - } - return new OutputLayer(model); - } -} +exports.threshold = pred => { + const clone = pred.cutoffs.slice(); + clone[0] = clone[1]; // Remove the infinite value -module.exports = OutputLayer; + return clone; +}; /***/ }), -/* 120 */ +/* 122 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var NodeSquare = __webpack_require__(39), - NodeHexagonal = __webpack_require__(121); +var matrixLib = __webpack_require__(0); + +var Matrix = matrixLib.Matrix; +var inverse = matrixLib.inverse; + +var padArray = __webpack_require__(40); + +var extend = __webpack_require__(16); var defaultOptions = { - fields: 3, - randomizer: Math.random, - distance: squareEuclidean, - iterations: 10, - learningRate: 0.1, - gridType: 'rect', - torus: true, - method: 'random' + windowSize: 5, + derivative: 1, + polynomial: 2, + pad: 'none', + padValue: 'replicate' }; +/** + * Savitzky-Golay filter + * @param {Array } data + * @param {number} h + * @param {Object} options + * @returns {Array} + */ -function SOM(x, y, options, reload) { - - this.x = x; - this.y = y; +function SavitzkyGolay(data, h, options) { + options = extend({}, defaultOptions, options); + if (options.windowSize % 2 === 0 || options.windowSize < 5 || !Number.isInteger(options.windowSize)) throw new RangeError('Invalid window size (should be odd and at least 5 integer number)'); + if (options.derivative < 0 || !Number.isInteger(options.derivative)) throw new RangeError('Derivative should be a positive integer'); + if (options.polynomial < 1 || !Number.isInteger(options.polynomial)) throw new RangeError('Polynomial should be a positive integer'); + var C, norm; + var step = Math.floor(options.windowSize / 2); + + if (options.pad === 'pre') { + data = padArray(data, { + size: step, + value: options.padValue + }); + } - options = options || {}; - this.options = {}; - for (var i in defaultOptions) { - if (options.hasOwnProperty(i)) { - this.options[i] = options[i]; - } else { - this.options[i] = defaultOptions[i]; - } - } + var ans = new Array(data.length - 2 * step); - if (typeof this.options.fields === 'number') { - this.numWeights = this.options.fields; - } else if (Array.isArray(this.options.fields)) { - this.numWeights = this.options.fields.length; - var converters = getConverters(this.options.fields); - this.extractor = converters.extractor; - this.creator = converters.creator; + if (options.windowSize === 5 && options.polynomial === 2 && (options.derivative === 1 || options.derivative === 2)) { + if (options.derivative === 1) { + C = [-2, -1, 0, 1, 2]; + norm = 10; } else { - throw new Error('Invalid fields definition'); + C = [2, -1, -2, -1, 2]; + norm = 7; } + } else { + var J = Matrix.ones(options.windowSize, options.polynomial + 1); + var inic = -(options.windowSize - 1) / 2; - if (this.options.gridType === 'rect') { - this.nodeType = NodeSquare; - this.gridDim = { - x: x, - y: y - }; - } else { - this.nodeType = NodeHexagonal; - var hx = this.x - Math.floor(this.y / 2); - this.gridDim = { - x: hx, - y: this.y, - z: -(0 - hx - this.y) - }; + for (var i = 0; i < J.length; i++) { + for (var j = 0; j < J[i].length; j++) { + if (inic + 1 !== 0 || j !== 0) J[i][j] = Math.pow(inic + i, j); + } } - this.torus = this.options.torus; - this.distanceMethod = this.torus ? 'getDistanceTorus' : 'getDistance'; - - this.distance = this.options.distance; + var Jtranspose = J.transposeView(); + var Jinv = inverse(Jtranspose.mmul(J)); + C = Jinv.mmul(Jtranspose); + C = C[options.derivative]; + norm = 1; + } - this.maxDistance = getMaxDistance(this.distance, this.numWeights); + var det = norm * Math.pow(h, options.derivative); - if (reload === true) { - // For model loading - this.done = true; - return; - } - if (!(x > 0 && y > 0)) { - throw new Error('x and y must be positive'); - } + for (var k = step; k < data.length - step; k++) { + var d = 0; - this.times = { - findBMU: 0, - adjust: 0 - }; + for (var l = 0; l < C.length; l++) d += C[l] * data[l + k - step] / det; - this.randomizer = this.options.randomizer; + ans[k - step] = d; + } - this.iterationCount = 0; - this.iterations = this.options.iterations; + if (options.pad === 'post') { + ans = padArray(ans, { + size: step, + value: options.padValue + }); + } - this.startLearningRate = this.learningRate = this.options.learningRate; + return ans; +} - this.mapRadius = Math.floor(Math.max(x, y) / 2); +module.exports = SavitzkyGolay; - this.algorithmMethod = this.options.method; +/***/ }), +/* 123 */ +/***/ (function(module, exports, __webpack_require__) { - this._initNodes(); +//Code translate from Pascal source in http://pubs.acs.org/doi/pdf/10.1021/ac00205a007 +var extend = __webpack_require__(16); - this.done = false; -} +var stat = __webpack_require__(3); -SOM.load = function loadModel(model, distance) { - if (model.name === 'SOM') { - var x = model.data.length, - y = model.data[0].length; - if (distance) { - model.options.distance = distance; - } else if (model.options.distance) { - model.options.distance = eval('(' + model.options.distance + ')'); - } - var som = new SOM(x, y, model.options, true); - som.nodes = new Array(x); - for (var i = 0; i < x; i++) { - som.nodes[i] = new Array(y); - for (var j = 0; j < y; j++) { - som.nodes[i][j] = new som.nodeType(i, j, model.data[i][j], som); - } - } - return som; - } else { - throw new Error('expecting a SOM model'); - } +var defaultOptions = { + windowSize: 9, + derivative: 0, + polynomial: 3 }; -SOM.prototype.export = function exportModel(includeDistance) { - if (!this.done) { - throw new Error('model is not ready yet'); - } - var model = { - name: 'SOM' - }; - model.options = { - fields: this.options.fields, - gridType: this.options.gridType, - torus: this.options.torus - }; - model.data = new Array(this.x); - for (var i = 0; i < this.x; i++) { - model.data[i] = new Array(this.y); - for (var j = 0; j < this.y; j++) { - model.data[i][j] = this.nodes[i][j].weights; - } - } - if (includeDistance) { - model.options.distance = this.distance.toString(); - } - return model; -}; +function SavitzkyGolay(data, h, options) { + options = extend({}, defaultOptions, options); + if (options.windowSize % 2 === 0 || options.windowSize < 5 || !Number.isInteger(options.windowSize)) throw new RangeError('Invalid window size (should be odd and at least 5 integer number)'); + if (options.windowSize > data.length) throw new RangeError('Window size is higher than the data length ' + options.windowSize + ">" + data.length); + if (options.derivative < 0 || !Number.isInteger(options.derivative)) throw new RangeError('Derivative should be a positive integer'); + if (options.polynomial < 1 || !Number.isInteger(options.polynomial)) throw new RangeError('Polynomial should be a positive integer'); + if (options.polynomial >= 6) console.warn('You should not use polynomial grade higher than 5 if you are' + ' not sure that your data arises from such a model. Possible polynomial oscillation problems'); + var windowSize = options.windowSize; + var half = Math.floor(windowSize / 2); + var np = data.length; + var ans = new Array(np); + var weights = fullWeights(windowSize, options.polynomial, options.derivative); + var hs = 0; + var constantH = true; + + if (Object.prototype.toString.call(h) === '[object Array]') { + constantH = false; + } else { + hs = Math.pow(h, options.derivative); + } //console.log("Constant h: "+constantH); + //For the borders -SOM.prototype._initNodes = function initNodes() { - var now = Date.now(), - i, - j, - k; - this.nodes = new Array(this.x); - for (i = 0; i < this.x; i++) { - this.nodes[i] = new Array(this.y); - for (j = 0; j < this.y; j++) { - var weights = new Array(this.numWeights); - for (k = 0; k < this.numWeights; k++) { - weights[k] = this.randomizer(); - } - this.nodes[i][j] = new this.nodeType(i, j, weights, this); - } - } - this.times.initNodes = Date.now() - now; -}; -SOM.prototype.setTraining = function setTraining(trainingSet) { - if (this.trainingSet) { - throw new Error('training set has already been set'); - } - var now = Date.now(); - var convertedSet = trainingSet; - var i, - l = trainingSet.length; - if (this.extractor) { - convertedSet = new Array(l); - for (i = 0; i < l; i++) { - convertedSet[i] = this.extractor(trainingSet[i]); - } + for (var i = 0; i < half; i++) { + var wg1 = weights[half - i - 1]; + var wg2 = weights[half + i + 1]; + var d1 = 0, + d2 = 0; + + for (var l = 0; l < windowSize; l++) { + d1 += wg1[l] * data[l]; + d2 += wg2[l] * data[np - windowSize + l - 1]; } - this.numIterations = this.iterations * l; - if (this.algorithmMethod === 'random') { - this.timeConstant = this.numIterations / Math.log(this.mapRadius); + if (constantH) { + ans[half - i - 1] = d1 / hs; + ans[np - half + i] = d2 / hs; } else { - this.timeConstant = l / Math.log(this.mapRadius); + hs = getHs(h, half - i - 1, half, options.derivative); + ans[half - i - 1] = d1 / hs; + hs = getHs(h, np - half + i, half, options.derivative); + ans[np - half + i] = d2 / hs; } - this.trainingSet = convertedSet; - this.times.setTraining = Date.now() - now; -}; + } //For the internal points -SOM.prototype.trainOne = function trainOne() { - if (this.done) { - return false; - } else if (this.numIterations-- > 0) { + var wg = weights[half]; - var neighbourhoodRadius, trainingValue, trainingSetFactor; + for (var i = windowSize; i < np + 1; i++) { + var d = 0; - if (this.algorithmMethod === 'random') { - // Pick a random value of the training set at each step - neighbourhoodRadius = this.mapRadius * Math.exp(-this.iterationCount / this.timeConstant); - trainingValue = getRandomValue(this.trainingSet, this.randomizer); - this._adjust(trainingValue, neighbourhoodRadius); - this.learningRate = this.startLearningRate * Math.exp(-this.iterationCount / this.numIterations); - } else { - // Get next input vector - trainingSetFactor = -Math.floor(this.iterationCount / this.trainingSet.length); - neighbourhoodRadius = this.mapRadius * Math.exp(trainingSetFactor / this.timeConstant); - trainingValue = this.trainingSet[this.iterationCount % this.trainingSet.length]; - this._adjust(trainingValue, neighbourhoodRadius); - if ((this.iterationCount + 1) % this.trainingSet.length === 0) { - this.learningRate = this.startLearningRate * Math.exp(trainingSetFactor / Math.floor(this.numIterations / this.trainingSet.length)); - } - } + for (var l = 0; l < windowSize; l++) d += wg[l] * data[l + i - windowSize]; - this.iterationCount++; + if (!constantH) hs = getHs(h, i - half - 1, half, options.derivative); + ans[i - half - 1] = d / hs; + } - return true; - } else { + return ans; +} - this.done = true; - return false; +function getHs(h, center, half, derivative) { + var hs = 0; + var count = 0; + + for (var i = center - half; i < center + half; i++) { + if (i >= 0 && i < h.length - 1) { + hs += h[i + 1] - h[i]; + count++; } -}; + } -SOM.prototype._adjust = function adjust(trainingValue, neighbourhoodRadius) { - var now = Date.now(), - x, - y, - dist, - influence; - - var bmu = this._findBestMatchingUnit(trainingValue); - - var now2 = Date.now(); - this.times.findBMU += now2 - now; - - var radiusLimit = Math.floor(neighbourhoodRadius); - var xMin = bmu.x - radiusLimit, - xMax = bmu.x + radiusLimit, - yMin = bmu.y - radiusLimit, - yMax = bmu.y + radiusLimit; - - for (x = xMin; x <= xMax; x++) { - var theX = x; - if (x < 0) { - theX += this.x; - } else if (x >= this.x) { - theX -= this.x; - } - for (y = yMin; y <= yMax; y++) { - var theY = y; - if (y < 0) { - theY += this.y; - } else if (y >= this.y) { - theY -= this.y; - } + return Math.pow(hs / count, derivative); +} - dist = bmu[this.distanceMethod](this.nodes[theX][theY]); +function GramPoly(i, m, k, s) { + var Grampoly = 0; - if (dist < neighbourhoodRadius) { - influence = Math.exp(-dist / (2 * neighbourhoodRadius)); - this.nodes[theX][theY].adjustWeights(trainingValue, this.learningRate, influence); - } - } + if (k > 0) { + Grampoly = (4 * k - 2) / (k * (2 * m - k + 1)) * (i * GramPoly(i, m, k - 1, s) + s * GramPoly(i, m, k - 1, s - 1)) - (k - 1) * (2 * m + k) / (k * (2 * m - k + 1)) * GramPoly(i, m, k - 2, s); + } else { + if (k == 0 && s == 0) { + Grampoly = 1; + } else { + Grampoly = 0; } + } //console.log(Grampoly); - this.times.adjust += Date.now() - now2; -}; -SOM.prototype.train = function train(trainingSet) { - if (!this.done) { - this.setTraining(trainingSet); - while (this.trainOne()) {} - } -}; + return Grampoly; +} -SOM.prototype.getConvertedNodes = function getConvertedNodes() { - var result = new Array(this.x); - for (var i = 0; i < this.x; i++) { - result[i] = new Array(this.y); - for (var j = 0; j < this.y; j++) { - var node = this.nodes[i][j]; - result[i][j] = this.creator ? this.creator(node.weights) : node.weights; - } +function GenFact(a, b) { + var gf = 1; + + if (a >= b) { + for (var j = a - b + 1; j <= a; j++) { + gf *= j; } - return result; -}; + } -SOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) { + return gf; +} - var bmu, - lowest = Infinity, - dist; +function Weight(i, t, m, n, s) { + var sum = 0; - for (var i = 0; i < this.x; i++) { - for (var j = 0; j < this.y; j++) { - dist = this.distance(this.nodes[i][j].weights, candidate); - if (dist < lowest) { - lowest = dist; - bmu = this.nodes[i][j]; - } - } - } + for (var k = 0; k <= n; k++) { + //console.log(k); + sum += (2 * k + 1) * (GenFact(2 * m, k) / GenFact(2 * m + k + 1, k + 1)) * GramPoly(i, m, k, 0) * GramPoly(t, m, k, s); + } - return bmu; -}; + return sum; +} +/** + * + * @param m Number of points + * @param n Polynomial grade + * @param s Derivative + */ -SOM.prototype.predict = function predict(data, computePosition) { - if (typeof data === 'boolean') { - computePosition = data; - data = null; - } - if (!data) { - data = this.trainingSet; - } - if (Array.isArray(data) && (Array.isArray(data[0]) || typeof data[0] === 'object')) { - // predict a dataset - var self = this; - return data.map(function (element) { - return self._predict(element, computePosition); - }); - } else { - // predict a single element - return this._predict(data, computePosition); - } -}; -SOM.prototype._predict = function _predict(element, computePosition) { - if (!Array.isArray(element)) { - element = this.extractor(element); - } - var bmu = this._findBestMatchingUnit(element); - var result = [bmu.x, bmu.y]; - if (computePosition) { - result[2] = bmu.getPosition(element); - } - return result; -}; +function fullWeights(m, n, s) { + var weights = new Array(m); + var np = Math.floor(m / 2); -// As seen in http://www.scholarpedia.org/article/Kohonen_network -SOM.prototype.getQuantizationError = function getQuantizationError() { - var fit = this.getFit(), - l = fit.length, - sum = 0; - for (var i = 0; i < l; i++) { - sum += fit[i]; - } - return sum / l; -}; + for (var t = -np; t <= np; t++) { + weights[t + np] = new Array(m); -SOM.prototype.getFit = function getFit(dataset) { - if (!dataset) { - dataset = this.trainingSet; - } - var l = dataset.length, - bmu, - result = new Array(l); - for (var i = 0; i < l; i++) { - bmu = this._findBestMatchingUnit(dataset[i]); - result[i] = Math.sqrt(this.distance(dataset[i], bmu.weights)); + for (var j = -np; j <= np; j++) { + weights[t + np][j + np] = Weight(j, t, np, n, s); } - return result; -}; + } -function getConverters(fields) { - var l = fields.length, - normalizers = new Array(l), - denormalizers = new Array(l); - for (var i = 0; i < l; i++) { - normalizers[i] = getNormalizer(fields[i].range); - denormalizers[i] = getDenormalizer(fields[i].range); - } - return { - extractor: function extractor(value) { - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = normalizers[i](value[fields[i].name]); - } - return result; - }, - creator: function creator(value) { - var result = {}; - for (var i = 0; i < l; i++) { - result[fields[i].name] = denormalizers[i](value[i]); - } - return result; - } - }; + return weights; } +/*function entropy(data,h,options){ + var trend = SavitzkyGolay(data,h,trendOptions); + var copy = new Array(data.length); + var sum = 0; + var max = 0; + for(var i=0;i> 8 & 0xff] + eightBits[arr[i] >> 16 & 0xff] + eightBits[arr[i] >> 24 & 0xff]; + } + + return c; +} +/** + * Logical AND operation + * @param {Array} arr1 + * @param {Array} arr2 + * @return {Array} + */ + + +function and(arr1, arr2) { + var ans = new Array(arr1.length); + + for (var i = 0; i < arr1.length; i++) ans[i] = arr1[i] & arr2[i]; + + return ans; +} +/** + * Logical OR operation + * @param {Array} arr1 + * @param {Array} arr2 + * @return {Array} + */ + -function NodeHexagonal(x, y, weights, som) { +function or(arr1, arr2) { + var ans = new Array(arr1.length); - NodeSquare.call(this, x, y, weights, som); + for (var i = 0; i < arr1.length; i++) ans[i] = arr1[i] | arr2[i]; - this.hX = x - Math.floor(y / 2); - this.z = 0 - this.hX - y; + return ans; } +/** + * Logical XOR operation + * @param {Array} arr1 + * @param {Array} arr2 + * @return {Array} + */ -NodeHexagonal.prototype = new NodeSquare(); -NodeHexagonal.prototype.constructor = NodeHexagonal; - -NodeHexagonal.prototype.getDistance = function getDistanceHexagonal(otherNode) { - return Math.max(Math.abs(this.hX - otherNode.hX), Math.abs(this.y - otherNode.y), Math.abs(this.z - otherNode.z)); -}; -NodeHexagonal.prototype.getDistanceTorus = function getDistanceTorus(otherNode) { - var distX = Math.abs(this.hX - otherNode.hX), - distY = Math.abs(this.y - otherNode.y), - distZ = Math.abs(this.z - otherNode.z); - return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY), Math.min(distZ, this.som.gridDim.z - distZ)); -}; +function xor(arr1, arr2) { + var ans = new Array(arr1.length); -NodeHexagonal.prototype.getPosition = function getPosition() { - throw new Error('Unimplemented : cannot get position of the points for hexagonal grid'); -}; + for (var i = 0; i < arr1.length; i++) ans[i] = arr1[i] ^ arr2[i]; -module.exports = NodeHexagonal; + return ans; +} +/** + * Logical NOT operation + * @param {Array} arr + * @return {Array} + */ -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +function not(arr) { + var ans = new Array(arr.length); + for (var i = 0; i < ans.length; i++) ans[i] = ~arr[i]; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = maybeToPrecision; -function maybeToPrecision(value, digits) { - if (value < 0) { - value = 0 - value; - if (typeof digits === 'number') { - return '- ' + value.toPrecision(digits); - } else { - return '- ' + value.toString(); - } - } else { - if (typeof digits === 'number') { - return value.toPrecision(digits); - } else { - return value.toString(); - } - } + return ans; } +/** + * Gets the n value of array arr + * @param {Array} arr + * @param {number} n + * @return {boolean} + */ -/***/ }), -/* 123 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +function getBit(arr, n) { + var index = n >> 5; // Same as Math.floor(n/32) -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = checkArraySize; -function checkArraySize(x, y) { - if (!Array.isArray(x) || !Array.isArray(y)) { - throw new TypeError('x and y must be arrays'); - } - if (x.length !== y.length) { - throw new RangeError('x and y arrays must have the same length'); - } + var mask = 1 << 31 - n % 32; + return Boolean(arr[index] & mask); } +/** + * Sets the n value of array arr to the value val + * @param {Array} arr + * @param {number} n + * @param {boolean} val + * @return {Array} + */ -/***/ }), -/* 124 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +function setBit(arr, n, val) { + var index = n >> 5; // Same as Math.floor(n/32) + var mask = 1 << 31 - n % 32; + if (val) arr[index] = mask | arr[index];else arr[index] = ~mask & arr[index]; + return arr; +} +/** + * Translates an array of numbers to a string of bits + * @param {Array} arr + * @returns {string} + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -var _mlRegressionBase = __webpack_require__(2); +function toBinaryString(arr) { + var str = ''; -var _mlRegressionBase2 = _interopRequireDefault(_mlRegressionBase); + for (var i = 0; i < arr.length; i++) { + var obj = (arr[i] >>> 0).toString(2); + str += '00000000000000000000000000000000'.substr(obj.length) + obj; + } -var _mlRegressionSimpleLinear = __webpack_require__(16); + return str; +} +/** + * Creates an array of numbers based on a string of bits + * @param {string} str + * @returns {Array} + */ -var _mlRegressionSimpleLinear2 = _interopRequireDefault(_mlRegressionSimpleLinear); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function parseBinaryString(str) { + var len = str.length / 32; + var ans = new Array(len); -class ExponentialRegression extends _mlRegressionBase2.default { - constructor(x, y) { - super(); - if (x === true) { - this.A = y.A; - this.B = y.B; - } else { - (0, _mlRegressionBase.checkArrayLength)(x, y); - regress(this, x, y); - } - } + for (var i = 0; i < len; i++) { + ans[i] = parseInt(str.substr(i * 32, 32), 2) | 0; + } - _predict(input) { - return this.B * Math.exp(input * this.A); - } + return ans; +} +/** + * Translates an array of numbers to a hex string + * @param {Array} arr + * @returns {string} + */ - toJSON() { - return { - name: 'exponentialRegression', - A: this.A, - B: this.B - }; - } - toString(precision) { - return 'f(x) = ' + (0, _mlRegressionBase.maybeToPrecision)(this.B, precision) + ' * e^(' + (0, _mlRegressionBase.maybeToPrecision)(this.A, precision) + ' * x)'; - } +function toHexString(arr) { + var str = ''; - toLaTeX(precision) { - if (this.A >= 0) { - return 'f(x) = ' + (0, _mlRegressionBase.maybeToPrecision)(this.B, precision) + 'e^{' + (0, _mlRegressionBase.maybeToPrecision)(this.A, precision) + 'x}'; - } else { - return 'f(x) = \\frac{' + (0, _mlRegressionBase.maybeToPrecision)(this.B, precision) + '}{e^{' + (0, _mlRegressionBase.maybeToPrecision)(-this.A, precision) + 'x}}'; - } - } + for (var i = 0; i < arr.length; i++) { + var obj = (arr[i] >>> 0).toString(16); + str += '00000000'.substr(obj.length) + obj; + } - static load(json) { - if (json.name !== 'exponentialRegression') { - throw new TypeError('not a exponential regression model'); - } - return new ExponentialRegression(true, json); - } + return str; } +/** + * Creates an array of numbers based on a hex string + * @param {string} str + * @returns {Array} + */ -exports.default = ExponentialRegression; -function regress(er, x, y) { - var n = x.length; - var yl = new Array(n); - for (var i = 0; i < n; i++) { - yl[i] = Math.log(y[i]); - } - - var linear = new _mlRegressionSimpleLinear2.default(x, yl); - er.A = linear.slope; - er.B = Math.exp(linear.intercept); -} -/***/ }), -/* 125 */ -/***/ (function(module, exports, __webpack_require__) { +function parseHexString(str) { + var len = str.length / 8; + var ans = new Array(len); -"use strict"; + for (var i = 0; i < len; i++) { + ans[i] = parseInt(str.substr(i * 8, 8), 16) | 0; + } + return ans; +} +/** + * Creates a human readable string of the array + * @param {Array} arr + * @returns {string} + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -var _mlRegressionBase = __webpack_require__(2); +function toDebug(arr) { + var binary = toBinaryString(arr); + var str = ''; -var _mlRegressionBase2 = _interopRequireDefault(_mlRegressionBase); + for (var i = 0; i < arr.length; i++) { + str += '0000'.substr((i * 32).toString(16).length) + (i * 32).toString(16) + ':'; -var _mlRegressionSimpleLinear = __webpack_require__(16); + for (var j = 0; j < 32; j += 4) { + str += ' ' + binary.substr(i * 32 + j, 4); + } -var _mlRegressionSimpleLinear2 = _interopRequireDefault(_mlRegressionSimpleLinear); + if (i < arr.length - 1) str += '\n'; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return str; +} -class PowerRegression extends _mlRegressionBase2.default { - constructor(x, y) { - super(); - if (x === true) { - // reloading model - this.A = y.A; - this.B = y.B; - } else { - (0, _mlRegressionBase.checkArrayLength)(x, y); - regress(this, x, y); - } - } +module.exports = { + count: count, + and: and, + or: or, + xor: xor, + not: not, + getBit: getBit, + setBit: setBit, + toBinaryString: toBinaryString, + parseBinaryString: parseBinaryString, + toHexString: toHexString, + parseHexString: parseHexString, + toDebug: toDebug +}; - _predict(newInputs) { - return this.A * Math.pow(newInputs, this.B); - } +/***/ }), +/* 125 */ +/***/ (function(module, exports) { - toJSON() { - return { - name: 'powerRegression', - A: this.A, - B: this.B - }; - } +// auxiliary file to create the 256 look at table elements +var ans = new Array(256); - toString(precision) { - return 'f(x) = ' + (0, _mlRegressionBase.maybeToPrecision)(this.A, precision) + ' * x^' + (0, _mlRegressionBase.maybeToPrecision)(this.B, precision); - } +for (var i = 0; i < 256; i++) { + var num = i; + var c = 0; - toLaTeX(precision) { - if (this.B >= 0) { - return 'f(x) = ' + (0, _mlRegressionBase.maybeToPrecision)(this.A, precision) + 'x^{' + (0, _mlRegressionBase.maybeToPrecision)(this.B, precision) + '}'; - } else { - return 'f(x) = \\frac{' + (0, _mlRegressionBase.maybeToPrecision)(this.A, precision) + '}{x^{' + (0, _mlRegressionBase.maybeToPrecision)(-this.B, precision) + '}}'; - } - } + while (num) { + num = num & num - 1; + c++; + } - static load(json) { - if (json.name !== 'powerRegression') { - throw new TypeError('not a power regression model'); - } - return new PowerRegression(true, json); - } + ans[i] = c; } -exports.default = PowerRegression; -function regress(pr, x, y) { - var n = x.length; - var xl = new Array(n); - var yl = new Array(n); - for (var i = 0; i < n; i++) { - xl[i] = Math.log(x[i]); - yl[i] = Math.log(y[i]); - } - - var linear = new _mlRegressionSimpleLinear2.default(xl, yl); - pr.A = Math.exp(linear.intercept); - pr.B = linear.slope; -} +module.exports = ans; /***/ }), /* 126 */ @@ -17703,212 +18699,259 @@ function regress(pr, x, y) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); +module.exports = exports = __webpack_require__(127); +exports.getEquallySpacedData = __webpack_require__(128).getEquallySpacedData; +exports.SNV = __webpack_require__(129).SNV; -var _mlMatrix = __webpack_require__(0); +/***/ }), +/* 127 */ +/***/ (function(module, exports, __webpack_require__) { -var _mlMatrix2 = _interopRequireDefault(_mlMatrix); +"use strict"; -var _mlRegressionBase = __webpack_require__(2); -var _mlRegressionBase2 = _interopRequireDefault(_mlRegressionBase); +const Stat = __webpack_require__(3).array; +/** + * Function that returns an array of points given 1D array as follows: + * + * [x1, y1, .. , x2, y2, ..] + * + * And receive the number of dimensions of each point. + * @param array + * @param dimensions + * @returns {Array} - Array of points. + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -class MultivariateLinearRegression extends _mlRegressionBase2.default { - constructor(x, y, options = {}) { - var _options$intercept = options.intercept, - intercept = _options$intercept === undefined ? true : _options$intercept, - _options$statistics = options.statistics, - statistics = _options$statistics === undefined ? true : _options$statistics; +function coordArrayToPoints(array, dimensions) { + if (array.length % dimensions !== 0) { + throw new RangeError('Dimensions number must be accordance with the size of the array.'); + } - super(); - this.statistics = statistics; - if (x === true) { - this.weights = y.weights; - this.inputs = y.inputs; - this.outputs = y.outputs; - this.intercept = y.intercept; - } else { - x = new _mlMatrix2.default(x); - if (intercept) { - x.addColumn(new Array(x.length).fill(1)); - } - var beta = new _mlMatrix.SVD(x, { autoTranspose: true }).solve(y); - this.weights = beta.to2DArray(); - this.inputs = x[0].length; - this.outputs = y[0].length; - if (intercept) this.inputs--; - this.intercept = intercept; - if (statistics) { - /* - * Let's add some basic statistics about the beta's to be able to interpret them. - * source: http://dept.stat.lsa.umich.edu/~kshedden/Courses/Stat401/Notes/401-multreg.pdf - * validated against Excel Regression AddIn - * test: "datamining statistics test" - */ - var fittedValues = x.mmul(beta); - var residuals = new _mlMatrix2.default(y).addM(fittedValues.neg()); - var variance = residuals.to2DArray().map(ri => Math.pow(ri[0], 2)).reduce((a, b) => a + b) / (y.length - x.columns); - this.stdError = Math.sqrt(variance); - this.stdErrorMatrix = x.transposeView().mmul(x).pseudoInverse().mul(variance); - this.stdErrors = this.stdErrorMatrix.diagonal().map(d => Math.sqrt(d)); - this.tStats = this.weights.map((d, i) => this.stdErrors[i] === 0 ? 0 : d[0] / this.stdErrors[i]); - } + var length = array.length / dimensions; + var pointsArr = new Array(length); + var k = 0; + + for (var i = 0; i < array.length; i += dimensions) { + var point = new Array(dimensions); + + for (var j = 0; j < dimensions; ++j) { + point[j] = array[i + j]; } + + pointsArr[k] = point; + k++; } - predict(x) { - if (Array.isArray(x)) { - if (typeof x[0] === 'number') { - return this._predict(x); - } else if (Array.isArray(x[0])) { - var y = new Array(x.length); - for (var i = 0; i < x.length; i++) { - y[i] = this._predict(x[i]); - } - return y; - } + return pointsArr; +} +/** + * Function that given an array as follows: + * [x1, y1, .. , x2, y2, ..] + * + * Returns an array as follows: + * [[x1, x2, ..], [y1, y2, ..], [ .. ]] + * + * And receives the number of dimensions of each coordinate. + * @param array + * @param dimensions + * @returns {Array} - Matrix of coordinates + */ + + +function coordArrayToCoordMatrix(array, dimensions) { + if (array.length % dimensions !== 0) { + throw new RangeError('Dimensions number must be accordance with the size of the array.'); + } + + var coordinatesArray = new Array(dimensions); + var points = array.length / dimensions; + + for (var i = 0; i < coordinatesArray.length; i++) { + coordinatesArray[i] = new Array(points); + } + + for (i = 0; i < array.length; i += dimensions) { + for (var j = 0; j < dimensions; ++j) { + var currentPoint = Math.floor(i / dimensions); + coordinatesArray[j][currentPoint] = array[i + j]; } - throw new TypeError('x must be a matrix or array of numbers'); } - _predict(x) { - var result = new Array(this.outputs); - if (this.intercept) { - for (var i = 0; i < this.outputs; i++) { - result[i] = this.weights[this.inputs][i]; - } - } else { - result.fill(0); - } - for (var _i = 0; _i < this.inputs; _i++) { - for (var j = 0; j < this.outputs; j++) { - result[j] += this.weights[_i][j] * x[_i]; - } + return coordinatesArray; +} +/** + * Function that receives a coordinate matrix as follows: + * [[x1, x2, ..], [y1, y2, ..], [ .. ]] + * + * Returns an array of coordinates as follows: + * [x1, y1, .. , x2, y2, ..] + * + * @param coordMatrix + * @returns {Array} + */ + + +function coordMatrixToCoordArray(coordMatrix) { + var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length); + var k = 0; + + for (var i = 0; i < coordMatrix[0].length; ++i) { + for (var j = 0; j < coordMatrix.length; ++j) { + coodinatesArray[k] = coordMatrix[j][i]; + ++k; } - return result; } - score() { - throw new Error('score method is not implemented yet'); - } + return coodinatesArray; +} +/** + * Tranpose a matrix, this method is for coordMatrixToPoints and + * pointsToCoordMatrix, that because only transposing the matrix + * you can change your representation. + * + * @param matrix + * @returns {Array} + */ - toJSON() { - return { - name: 'multivariateLinearRegression', - weights: this.weights, - inputs: this.inputs, - outputs: this.outputs, - intercept: this.intercept, - summary: this.statistics ? { - regressionStatistics: { - standardError: this.stdError, - observations: this.outputs - }, - variables: this.weights.map((d, i) => { - return { - label: i === this.weights.length - 1 ? 'Intercept' : `X Variable ${i + 1}`, - coefficients: d, - standardError: this.stdErrors[i], - tStat: this.tStats[i] - }; - }) - } : undefined - }; + +function transpose(matrix) { + var resultMatrix = new Array(matrix[0].length); + + for (var i = 0; i < resultMatrix.length; ++i) { + resultMatrix[i] = new Array(matrix.length); } - static load(model) { - if (model.name !== 'multivariateLinearRegression') { - throw new Error('not a MLR model'); + for (i = 0; i < matrix.length; ++i) { + for (var j = 0; j < matrix[0].length; ++j) { + resultMatrix[j][i] = matrix[i][j]; } - return new MultivariateLinearRegression(true, model); } + + return resultMatrix; } -exports.default = MultivariateLinearRegression; +/** + * Function that transform an array of points into a coordinates array + * as follows: + * [x1, y1, .. , x2, y2, ..] + * + * @param points + * @returns {Array} + */ -/***/ }), -/* 127 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +function pointsToCoordArray(points) { + var coodinatesArray = new Array(points.length * points[0].length); + var k = 0; + for (var i = 0; i < points.length; ++i) { + for (var j = 0; j < points[0].length; ++j) { + coodinatesArray[k] = points[i][j]; + ++k; + } + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + return coodinatesArray; +} +/** + * Apply the dot product between the smaller vector and a subsets of the + * largest one. + * + * @param firstVector + * @param secondVector + * @returns {Array} each dot product of size of the difference between the + * larger and the smallest one. + */ -var _mlMatrix = __webpack_require__(0); -var _mlKernel = __webpack_require__(15); +function applyDotProduct(firstVector, secondVector) { + var largestVector, smallestVector; -var _mlKernel2 = _interopRequireDefault(_mlKernel); + if (firstVector.length <= secondVector.length) { + smallestVector = firstVector; + largestVector = secondVector; + } else { + smallestVector = secondVector; + largestVector = firstVector; + } -var _mlRegressionBase = __webpack_require__(2); + var difference = largestVector.length - smallestVector.length + 1; + var dotProductApplied = new Array(difference); -var _mlRegressionBase2 = _interopRequireDefault(_mlRegressionBase); + for (var i = 0; i < difference; ++i) { + var sum = 0; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (var j = 0; j < smallestVector.length; ++j) { + sum += smallestVector[j] * largestVector[i + j]; + } -var defaultOptions = { - lambda: 0.1, - kernelType: 'gaussian', - kernelOptions: {}, - computeCoefficient: false -}; + dotProductApplied[i] = sum; + } -// Implements the Kernel ridge regression algorithm. -// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf -class KernelRidgeRegression extends _mlRegressionBase2.default { - constructor(inputs, outputs, options) { - super(); - if (inputs === true) { - // reloading model - this.alpha = outputs.alpha; - this.inputs = outputs.inputs; - this.kernelType = outputs.kernelType; - this.kernelOptions = outputs.kernelOptions; - this.kernel = new _mlKernel2.default(outputs.kernelType, outputs.kernelOptions); - } else { - options = Object.assign({}, defaultOptions, options); + return dotProductApplied; +} +/** + * To scale the input array between the specified min and max values. The operation is performed inplace + * if the options.inplace is specified. If only one of the min or max parameters is specified, then the scaling + * will multiply the input array by min/min(input) or max/max(input) + * @param input + * @param options + * @returns {*} + */ - var kernelFunction = new _mlKernel2.default(options.kernelType, options.kernelOptions); - var K = kernelFunction.compute(inputs); - var n = inputs.length; - K.add(_mlMatrix.Matrix.eye(n, n).mul(options.lambda)); - this.alpha = (0, _mlMatrix.solve)(K, outputs); - this.inputs = inputs; - this.kernelType = options.kernelType; - this.kernelOptions = options.kernelOptions; - this.kernel = kernelFunction; - } - } +function scale(input) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const { + min, + max + } = options; + var y = options.inPlace ? input : new Array(input.length); + var minMax = Stat.minMax(input); - _predict(newInputs) { - return this.kernel.compute([newInputs], this.inputs).mmul(this.alpha)[0]; - } + if (typeof max === 'number') { + if (typeof min === 'number') { + let factor = (max - min) / (minMax.max - minMax.min); - toJSON() { - return { - name: 'kernelRidgeRegression', - alpha: this.alpha, - inputs: this.inputs, - kernelType: this.kernelType, - kernelOptions: this.kernelOptions - }; + for (let i = 0; i < y.length; i++) { + y[i] = (input[i] - minMax.min) * factor + min; + } + } else if (minMax.max !== 0) { + let factor = max / minMax.max; + + for (let i = 0; i < y.length; i++) { + y[i] = input[i] * factor; + } + } else { + options.min = minMax.min; + y = scale(input, options); } + } else if (typeof min === 'number') { + if (minMax.min !== 0) { + let factor = min / minMax.min; - static load(json) { - if (json.name !== 'kernelRidgeRegression') { - throw new TypeError('not a KRR model'); - } - return new KernelRidgeRegression(true, json); + for (let i = 0; i < y.length; i++) { + y[i] = input[i] * factor; + } + } else { + options.max = minMax.max; + y = scale(input, options); } + } + + return y; } -exports.default = KernelRidgeRegression; + +module.exports = { + coordArrayToPoints: coordArrayToPoints, + coordArrayToCoordMatrix: coordArrayToCoordMatrix, + coordMatrixToCoordArray: coordMatrixToCoordArray, + coordMatrixToPoints: transpose, + pointsToCoordArray: pointsToCoordArray, + pointsToCoordMatrix: transpose, + applyDotProduct: applyDotProduct, + scale: scale +}; /***/ }), /* 128 */ @@ -17916,3538 +18959,3805 @@ exports.default = KernelRidgeRegression; "use strict"; +/** + * + * Function that returns a Number array of equally spaced numberOfPoints + * containing a representation of intensities of the spectra arguments x + * and y. + * + * The options parameter contains an object in the following form: + * from: starting point + * to: last point + * numberOfPoints: number of points between from and to + * variant: "slot" or "smooth" - smooth is the default option + * + * The slot variant consist that each point in the new array is calculated + * averaging the existing points between the slot that belongs to the current + * value. The smooth variant is the same but takes the integral of the range + * of the slot and divide by the step size between two points in the new array. + * + * @param x - sorted increasing x values + * @param y + * @param options + * @returns {Array} new array with the equally spaced data. + * + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _mlMatrix = __webpack_require__(0); - -var _mlRegressionBase = __webpack_require__(2); +function getEquallySpacedData(x, y) { + let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var xLength = x.length; -var _mlRegressionBase2 = _interopRequireDefault(_mlRegressionBase); + if (x.length > 1 && x[0] > x[1]) { + x = x.slice().reverse(); + y = y.slice().reverse(); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var { + from = x[0], + to = x[xLength - 1], + variant = 'smooth', + numberOfPoints = 100 + } = options; -var defaultOptions = { - order: 2 -}; -// Implements the Kernel ridge regression algorithm. -// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf -class PolynomialFitRegression2D extends _mlRegressionBase2.default { - /** - * Constructor for the 2D polynomial fitting - * - * @param inputs - * @param outputs - * @param options - * @constructor - */ - constructor(inputs, outputs, options) { - super(); - if (inputs === true) { - // reloading model - this.coefficients = _mlMatrix.Matrix.columnVector(outputs.coefficients); - this.order = outputs.order; - if (outputs.r) { - this.r = outputs.r; - this.r2 = outputs.r2; - } - if (outputs.chi2) { - this.chi2 = outputs.chi2; - } - } else { - options = Object.assign({}, defaultOptions, options); - this.order = options.order; - this.coefficients = []; - this.X = inputs; - this.y = outputs; + if (xLength !== y.length) { + throw new RangeError("the x and y vector doesn't have the same size."); + } - this.train(this.X, this.y, options); - } - } + if (typeof from !== 'number' || isNaN(from)) { + throw new RangeError("'from' option must be a number"); + } - /** - * Function that fits the model given the data(X) and predictions(y). - * The third argument is an object with the following options: - * * order: order of the polynomial to fit. - * - * @param {Matrix} X - A matrix with n rows and 2 columns. - * @param {Matrix} y - A vector of the prediction values. - */ - train(X, y) { - if (!_mlMatrix.Matrix.isMatrix(X)) X = new _mlMatrix.Matrix(X); - if (!_mlMatrix.Matrix.isMatrix(y)) y = _mlMatrix.Matrix.columnVector(y); + if (typeof to !== 'number' || isNaN(to)) { + throw new RangeError("'to' option must be a number"); + } - if (y.rows !== X.rows) { - y = y.transpose(); - } + var reverse = from > to; - if (X.columns !== 2) { - throw new RangeError('You give X with ' + X.columns + ' columns and it must be 2'); - } - if (X.rows !== y.rows) { - throw new RangeError('X and y must have the same rows'); - } + if (reverse) { + [from, to] = [to, from]; + } - var examples = X.rows; - var coefficients = (this.order + 2) * (this.order + 1) / 2; - this.coefficients = new Array(coefficients); + if (typeof numberOfPoints !== 'number' || isNaN(numberOfPoints)) { + throw new RangeError("'numberOfPoints' option must be a number"); + } - var x1 = X.getColumnVector(0); - var x2 = X.getColumnVector(1); + if (numberOfPoints < 1) { + throw new RangeError('the number of points must be at least 1'); + } - var scaleX1 = 1.0 / x1.clone().apply(abs).max(); - var scaleX2 = 1.0 / x2.clone().apply(abs).max(); - var scaleY = 1.0 / y.clone().apply(abs).max(); + var output = variant === 'slot' ? getEquallySpacedSlot(x, y, from, to, numberOfPoints) : getEquallySpacedSmooth(x, y, from, to, numberOfPoints); + return reverse ? output.reverse() : output; +} +/** + * function that retrieves the getEquallySpacedData with the variant "smooth" + * + * @param x + * @param y + * @param from - Initial point + * @param to - Final point + * @param numberOfPoints + * @returns {Array} - Array of y's equally spaced with the variant "smooth" + */ - x1.mulColumn(0, scaleX1); - x2.mulColumn(0, scaleX2); - y.mulColumn(0, scaleY); - var A = new _mlMatrix.Matrix(examples, coefficients); - var col = 0; +function getEquallySpacedSmooth(x, y, from, to, numberOfPoints) { + var xLength = x.length; + var step = (to - from) / (numberOfPoints - 1); + var halfStep = step / 2; + var output = new Array(numberOfPoints); + var initialOriginalStep = x[1] - x[0]; + var lastOriginalStep = x[xLength - 1] - x[xLength - 2]; // Init main variables + + var min = from - halfStep; + var max = from + halfStep; + var previousX = Number.MIN_VALUE; + var previousY = 0; + var nextX = x[0] - initialOriginalStep; + var nextY = 0; + var currentValue = 0; + var slope = 0; + var intercept = 0; + var sumAtMin = 0; + var sumAtMax = 0; + var i = 0; // index of input + + var j = 0; // index of output + + function getSlope(x0, y0, x1, y1) { + return (y1 - y0) / (x1 - x0); + } - for (var i = 0; i <= this.order; ++i) { - var limit = this.order - i; - for (var j = 0; j <= limit; ++j) { - var result = powColVector(x1, i).mulColumnVector(powColVector(x2, j)); - A.setColumn(col, result); - col++; - } - } + main: while (true) { + if (previousX <= min && min <= nextX) { + add = integral(0, min - previousX, slope, previousY); + sumAtMin = currentValue + add; + } - var svd = new _mlMatrix.SVD(A.transpose(), { - computeLeftSingularVectors: true, - computeRightSingularVectors: true, - autoTranspose: false - }); + while (nextX - max >= 0) { + // no overlap with original point, just consume current value + var add = integral(0, max - previousX, slope, previousY); + sumAtMax = currentValue + add; + output[j++] = (sumAtMax - sumAtMin) / step; - var qqs = _mlMatrix.Matrix.rowVector(svd.diagonal); - qqs = qqs.apply(function (i, j) { - if (this[i][j] >= 1e-15) this[i][j] = 1 / this[i][j];else this[i][j] = 0; - }); + if (j === numberOfPoints) { + break main; + } - var qqs1 = _mlMatrix.Matrix.zeros(examples, coefficients); - for (i = 0; i < coefficients; ++i) { - qqs1[i][i] = qqs[0][i]; - } + min = max; + max += step; + sumAtMin = sumAtMax; + } - qqs = qqs1; + currentValue += integral(previousX, nextX, slope, intercept); + previousX = nextX; + previousY = nextY; - var U = svd.rightSingularVectors; - var V = svd.leftSingularVectors; + if (i < xLength) { + nextX = x[i]; + nextY = y[i]; + i++; + } else if (i === xLength) { + nextX += lastOriginalStep; + nextY = 0; + } - this.coefficients = V.mmul(qqs.transpose()).mmul(U.transpose()).mmul(y); + slope = getSlope(previousX, previousY, nextX, nextY); + intercept = -slope * previousX + previousY; + } - col = 0; + return output; +} +/** + * function that retrieves the getEquallySpacedData with the variant "slot" + * + * @param x + * @param y + * @param from - Initial point + * @param to - Final point + * @param numberOfPoints + * @returns {Array} - Array of y's equally spaced with the variant "slot" + */ - for (i = 0; i <= coefficients; ++i) { - limit = this.order - i; - for (j = 0; j <= limit; ++j) { - this.coefficients[col][0] = this.coefficients[col][0] * Math.pow(scaleX1, i) * Math.pow(scaleX2, j) / scaleY; - col++; - } - } - } - _predict(newInputs) { - var x1 = newInputs[0]; - var x2 = newInputs[1]; +function getEquallySpacedSlot(x, y, from, to, numberOfPoints) { + var xLength = x.length; + var step = (to - from) / (numberOfPoints - 1); + var halfStep = step / 2; + var lastStep = x[x.length - 1] - x[x.length - 2]; + var start = from - halfStep; + var output = new Array(numberOfPoints); // Init main variables + + var min = start; + var max = start + step; + var previousX = -Number.MAX_VALUE; + var previousY = 0; + var nextX = x[0]; + var nextY = y[0]; + var frontOutsideSpectra = 0; + var backOutsideSpectra = true; + var currentValue = 0; // for slot algorithm + + var currentPoints = 0; + var i = 1; // index of input + + var j = 0; // index of output + + main: while (true) { + if (previousX >= nextX) throw new Error('x must be an increasing serie'); + + while (previousX - max > 0) { + // no overlap with original point, just consume current value + if (backOutsideSpectra) { + currentPoints++; + backOutsideSpectra = false; + } - var y = 0; - var column = 0; + output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints; + j++; - for (var i = 0; i <= this.order; i++) { - for (var j = 0; j <= this.order - i; j++) { - y += Math.pow(x1, i) * Math.pow(x2, j) * this.coefficients[column][0]; - column++; - } - } + if (j === numberOfPoints) { + break main; + } - return y; + min = max; + max += step; + currentValue = 0; + currentPoints = 0; } - toJSON() { - return { - name: 'polyfit2D', - order: this.order, - coefficients: this.coefficients - }; + if (previousX > min) { + currentValue += previousY; + currentPoints++; } - static load(json) { - if (json.name !== 'polyfit2D') { - throw new TypeError('not a polyfit2D model'); - } - return new PolynomialFitRegression2D(true, json); + if (previousX === -Number.MAX_VALUE || frontOutsideSpectra > 1) { + currentPoints--; } -} -exports.default = PolynomialFitRegression2D; /** - * Function that given a column vector return this: vector^power - * - * @param x - Column vector. - * @param power - Pow number. - * @return {Suite|Matrix} - */ + previousX = nextX; + previousY = nextY; -function powColVector(x, power) { - var result = x.clone(); - for (var i = 0; i < x.rows; ++i) { - result[i][0] = Math.pow(result[i][0], power); + if (i < xLength) { + nextX = x[i]; + nextY = y[i]; + i++; + } else { + nextX += lastStep; + nextY = 0; + frontOutsideSpectra++; } - return result; -} + } + return output; +} /** - * Function to use in the apply method to get the absolute value - * of each element of the matrix - * - * @param i - current row. - * @param j - current column. + * Function that calculates the integral of the line between two + * x-coordinates, given the slope and intercept of the line. + * @param x0 + * @param x1 + * @param slope + * @param intercept + * @returns {number} integral value. */ -function abs(i, j) { - this[i][j] = Math.abs(this[i][j]); -} - -/***/ }), -/* 129 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _mlRegressionBase = __webpack_require__(2); - -var _mlRegressionBase2 = _interopRequireDefault(_mlRegressionBase); - -var _mlStat = __webpack_require__(4); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var median = _mlStat.array.median; -class TheilSenRegression extends _mlRegressionBase2.default { +function integral(x0, x1, slope, intercept) { + return 0.5 * slope * x1 * x1 + intercept * x1 - (0.5 * slope * x0 * x0 + intercept * x0); +} - /** - * Theil–Sen estimator - * https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator - * @param {Array|boolean} x - * @param {Array|object} y - * @constructor - */ - constructor(x, y) { - super(); - if (x === true) { - // loads the model - this.slope = y.slope; - this.intercept = y.intercept; - this.coefficients = y.coefficients; - } else { - // creates the model - (0, _mlRegressionBase.checkArrayLength)(x, y); - theilSen(this, x, y); - } - } +exports.getEquallySpacedData = getEquallySpacedData; +exports.integral = integral; - toJSON() { - return { - name: 'TheilSenRegression', - slope: this.slope, - intercept: this.intercept - }; - } +/***/ }), +/* 129 */ +/***/ (function(module, exports, __webpack_require__) { - _predict(input) { - return this.slope * input + this.intercept; - } +"use strict"; - computeX(input) { - return (input - this.intercept) / this.slope; - } - toString(precision) { - var result = 'f(x) = '; - if (this.slope) { - var xFactor = (0, _mlRegressionBase.maybeToPrecision)(this.slope, precision); - result += (Math.abs(xFactor - 1) < 1e-5 ? '' : xFactor + ' * ') + 'x'; - if (this.intercept) { - var absIntercept = Math.abs(this.intercept); - var operator = absIntercept === this.intercept ? '+' : '-'; - result += ' ' + operator + ' ' + (0, _mlRegressionBase.maybeToPrecision)(absIntercept, precision); - } - } else { - result += (0, _mlRegressionBase.maybeToPrecision)(this.intercept, precision); - } - return result; - } +exports.SNV = SNV; - toLaTeX(precision) { - return this.toString(precision); - } +var Stat = __webpack_require__(3).array; +/** + * Function that applies the standard normal variate (SNV) to an array of values. + * + * @param data - Array of values. + * @returns {Array} - applied the SNV. + */ - static load(json) { - if (json.name !== 'TheilSenRegression') { - throw new TypeError('not a Theil-Sen model'); - } - return new TheilSenRegression(true, json); - } -} -exports.default = TheilSenRegression; -function theilSen(regression, x, y) { - var len = x.length; - var slopes = new Array(len * len); - var count = 0; - for (var i = 0; i < len; ++i) { - for (var j = i + 1; j < len; ++j) { - if (x[i] !== x[j]) { - slopes[count++] = (y[j] - y[i]) / (x[j] - x[i]); - } - } - } - slopes.length = count; - var medianSlope = median(slopes); +function SNV(data) { + var mean = Stat.mean(data); + var std = Stat.standardDeviation(data); + var result = data.slice(); - var cuts = new Array(len); - for (var _i = 0; _i < len; ++_i) { - cuts[_i] = y[_i] - medianSlope * x[_i]; - } + for (var i = 0; i < data.length; i++) { + result[i] = (result[i] - mean) / std; + } - regression.slope = medianSlope; - regression.intercept = median(cuts); - regression.coefficients = [regression.intercept, regression.slope]; + return result; } /***/ }), /* 130 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); +/* harmony import */ var is_any_array__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(is_any_array__WEBPACK_IMPORTED_MODULE_0__); +/** + * Computes the mode of the given values + * @param {Array} input + * @return {number} + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _mlRegressionBase = __webpack_require__(2); +function mode(input) { + if (!is_any_array__WEBPACK_IMPORTED_MODULE_0___default()(input)) { + throw new TypeError('input must be an array'); + } -var _mlRegressionBase2 = _interopRequireDefault(_mlRegressionBase); + if (input.length === 0) { + throw new TypeError('input must not be empty'); + } -var _mlMatrix = __webpack_require__(0); + var maxValue = 0; + var maxCount = 0; + var count = 0; + var counts = {}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (var i = 0; i < input.length; ++i) { + var element = input[i]; + count = counts[element]; -class RobustPolynomialRegression extends _mlRegressionBase2.default { - constructor(x, y, degree) { - super(); - if (x === true) { - this.degree = y.degree; - this.powers = y.powers; - this.coefficients = y.coefficients; - } else { - (0, _mlRegressionBase.checkArrayLength)(x, y); - robustPolynomial(this, x, y, degree); - } + if (count) { + counts[element]++; + count++; + } else { + counts[element] = count = 1; } - toJSON() { - return { - name: 'robustPolynomialRegression', - degree: this.degree, - powers: this.powers, - coefficients: this.coefficients - }; + if (count > maxCount) { + maxCount = count; + maxValue = input[i]; } + } - _predict(x) { - return predict(x, this.powers, this.coefficients); - } + return maxValue; +} - toString(precision) { - return this._toFormula(precision, false); - } +/* harmony default export */ __webpack_exports__["default"] = (mode); - toLaTeX(precision) { - return this._toFormula(precision, true); - } +/***/ }), +/* 131 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - _toFormula(precision, isLaTeX) { - var sup = '^'; - var closeSup = ''; - var times = ' * '; - if (isLaTeX) { - sup = '^{'; - closeSup = '}'; - times = ''; - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/** + * Computes the norm of the given values + * @param {Array} input + * @param {object} [options={}] + * @param {string} [algorithm='absolute'] + * @return {number} + */ +function norm(input) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var _options$algorithm = options.algorithm, + algorithm = _options$algorithm === void 0 ? 'absolute' : _options$algorithm; - var fn = ''; - var str = ''; - for (var k = 0; k < this.coefficients.length; k++) { - str = ''; - if (this.coefficients[k] !== 0) { - if (this.powers[k] === 0) { - str = (0, _mlRegressionBase.maybeToPrecision)(this.coefficients[k], precision); - } else { - if (this.powers[k] === 1) { - str = (0, _mlRegressionBase.maybeToPrecision)(this.coefficients[k], precision) + times + 'x'; - } else { - str = (0, _mlRegressionBase.maybeToPrecision)(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup; - } - } + if (!Array.isArray(input)) { + throw new Error('input must be an array'); + } - if (this.coefficients[k] > 0 && k !== this.coefficients.length - 1) { - str = ' + ' + str; - } else if (k !== this.coefficients.length - 1) { - str = ' ' + str; - } - } - fn = str + fn; - } - if (fn.charAt(0) === '+') { - fn = fn.slice(1); - } + if (input.length === 0) { + throw new Error('input must not be empty'); + } - return 'f(x) = ' + fn; - } + switch (algorithm.toLowerCase()) { + case 'absolute': + var sum = absoluteSum(input); + if (sum === 0) return input.slice(0); + return input.map(function (element) { + return element / sum; + }); - static load(json) { - if (json.name !== 'robustPolynomialRegression') { - throw new TypeError('not a RobustPolynomialRegression model'); - } - return new RobustPolynomialRegression(true, json); - } + default: + throw new Error("norm: unknown algorithm: ".concat(algorithm)); + } } -exports.default = RobustPolynomialRegression; -function robustPolynomial(regression, x, y, degree) { - var powers = new Array(degree); - for (var k = 0; k < degree; k++) { - powers[k] = k; - } +function absoluteSum(input) { + var sum = 0; - var tuples = getRandomTuples(x, y, degree); - var min; + for (var i = 0; i < input.length; i++) { + sum += Math.abs(input[i]); + } - for (var i = 0; i < tuples.length; i++) { - var tuple = tuples[i]; - var coefficients = calcCoefficients(tuple, powers); + return sum; +} - var residuals = x.slice(); - for (var j = 0; j < x.length; j++) { - residuals[j] = y[j] - predict(x[j], powers, coefficients); - residuals[j] = { - residual: residuals[j] * residuals[j], - coefficients - }; - } +/* harmony default export */ __webpack_exports__["default"] = (norm); - var median = residualsMedian(residuals); - if (!min || median.residual < min.residual) { - min = median; - } - } +/***/ }), +/* 132 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - regression.degree = degree; - regression.powers = powers; - regression.coefficients = min.coefficients; -} +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var ml_array_variance__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21); /** - * @ignore - * @param {Array} x - * @param {Array} y - * @param {number} degree - * @return {Array<{x:number,y:number}>} + * Computes the standard deviation of the given values + * @param {Array} values + * @param {object} [options] + * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n. + * @param {number} [options.mean = arrayMean] - precalculated mean, if any. + * @return {number} */ -function getRandomTuples(x, y, degree) { - var len = Math.floor(x.length / degree); - var tuples = new Array(len); - - for (var i = 0; i < x.length; i++) { - var pos = Math.floor(Math.random() * len); - - var counter = 0; - while (counter < x.length) { - if (!tuples[pos]) { - tuples[pos] = [{ - x: x[i], - y: y[i] - }]; - break; - } else if (tuples[pos].length < degree) { - tuples[pos].push({ - x: x[i], - y: y[i] - }); - break; - } else { - counter++; - pos = (pos + 1) % len; - } - } - if (counter === x.length) { - return tuples; - } - } - return tuples; +function standardDeviation(values) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + return Math.sqrt(Object(ml_array_variance__WEBPACK_IMPORTED_MODULE_0__["default"])(values, options)); } -/** - * @ignore - * @param {{x:number,y:number}} tuple - * @param {Array} powers - * @return {Array} - */ -function calcCoefficients(tuple, powers) { - var X = tuple.slice(); - var Y = tuple.slice(); - for (var i = 0; i < X.length; i++) { - Y[i] = [tuple[i].y]; - X[i] = new Array(powers.length); - for (var j = 0; j < powers.length; j++) { - X[i][j] = Math.pow(tuple[i].x, powers[j]); - } - } +/* harmony default export */ __webpack_exports__["default"] = (standardDeviation); - return (0, _mlMatrix.solve)(X, Y).to1DArray(); -} +/***/ }), +/* 133 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -function predict(x, powers, coefficients) { - var y = 0; - for (var k = 0; k < powers.length; k++) { - y += coefficients[k] * Math.pow(x, powers[k]); - } - return y; -} +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return mergeByCentroids; }); +/** + * Merge abscissa values if the ordinate value is in a list of centroids + * @param {object} originalPoints + * @param {Array} originalPoints.x + * @param {Array} originalPoints.y + * @param {Array} centroids + * @param {object} [options] + * @param {number} [options.window = 0.01] - has to be a positive number + * @return {{x: Array, y: Array}} + */ +function mergeByCentroids(originalPoints, centroids) { + let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + const { + window = 0.01 + } = options; + var mergedPoints = { + x: centroids.slice(), + y: new Array(centroids.length).fill(0) + }; + var originalIndex = 0; + var mergedIndex = 0; -function residualsMedian(residuals) { - residuals.sort((a, b) => a.residual - b.residual); + while (originalIndex < originalPoints.x.length && mergedIndex < centroids.length) { + var diff = originalPoints.x[originalIndex] - centroids[mergedIndex]; - var l = residuals.length; - var half = Math.floor(l / 2); - if (l % 2 === 0) { - return residuals[half - 1]; + if (Math.abs(diff) < window) { + mergedPoints.y[mergedIndex] += originalPoints.y[originalIndex++]; + } else if (diff < 0) { + originalIndex++; } else { - return residuals[half]; + mergedIndex++; } + } + + return mergedPoints; } /***/ }), -/* 131 */ -/***/ (function(module, exports, __webpack_require__) { +/* 134 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return closestX; }); +/* harmony import */ var binary_search__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var binary_search__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(binary_search__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var num_sort__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7); +/* harmony import */ var num_sort__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(num_sort__WEBPACK_IMPORTED_MODULE_1__); -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _mlRegressionBase = __webpack_require__(2); - -var _mlRegressionBase2 = _interopRequireDefault(_mlRegressionBase); - -var _mlRegressionPolynomial = __webpack_require__(41); - -var _mlRegressionPolynomial2 = _interopRequireDefault(_mlRegressionPolynomial); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/* - * Function that calculate the potential fit in the form f(x) = A*x^M - * with a given M and return de A coefficient. +/** * - * @param {Vector} X - Vector of the x positions of the points. - * @param {Vector} Y - Vector of the x positions of the points. - * @param {Number} M - The exponent of the potential fit. - * @return {Number} A - The A coefficient of the potential fit. + * @param {object} points + * @param {Array} originalPoints.x + * @param {Array} originalPoints.y + * @param {*} options + * @return {{x: Array, y: Array}} */ -class PotentialRegression extends _mlRegressionBase2.default { - /** - * @constructor - * @param x: Independent variable - * @param y: Dependent variable - * @param M - */ - constructor(x, y, M) { - super(); - if (x === true) { - // reloading model - this.A = y.A; - this.M = y.M; - } else { - var n = x.length; - if (n !== y.length) { - throw new RangeError('input and output array have a different length'); - } - var linear = new _mlRegressionPolynomial2.default(x, y, [M]); - this.A = linear.coefficients[0]; - this.M = M; - } - } +function closestX(points, options) { + const { + x, + y + } = points; + const { + target = x[0], + reverse = false + } = options; + let index; + + if (reverse) { + index = binary_search__WEBPACK_IMPORTED_MODULE_0___default()(x, target, num_sort__WEBPACK_IMPORTED_MODULE_1__["desc"]); + } else { + index = binary_search__WEBPACK_IMPORTED_MODULE_0___default()(x, target, num_sort__WEBPACK_IMPORTED_MODULE_1__["asc"]); + } - _predict(x) { - return this.A * Math.pow(x, this.M); - } + if (index >= 0) { + return { + x: x[index], + y: y[index] + }; + } else { + index = ~index; - toJSON() { - return { - name: 'potentialRegression', - A: this.A, - M: this.M - }; + if (index !== 0 && Math.abs(x[index] - target) > 0.5 || index === x.length) { + return { + x: x[index - 1], + y: y[index - 1] + }; + } else { + return { + x: x[index], + y: y[index] + }; } + } +} - toString(precision) { - return 'f(x) = ' + (0, _mlRegressionBase.maybeToPrecision)(this.A, precision) + ' * x^' + this.M; - } +/***/ }), +/* 135 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - toLaTeX(precision) { - if (this.M >= 0) { - return 'f(x) = ' + (0, _mlRegressionBase.maybeToPrecision)(this.A, precision) + 'x^{' + this.M + '}'; - } else { - return 'f(x) = \\frac{' + (0, _mlRegressionBase.maybeToPrecision)(this.A, precision) + '}{x^{' + -this.M + '}}'; - } - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return maxMerge; }); +/** + * Merge abscissas values on similar ordinates and weight the group of abscissas + * @param {object} points + * @param {Array} points.x - sorted abscissas values + * @param {Array} points.y - ordinates values + * @param {object} [options] + * @param {number} [options.groupWidth = 0.001] - window for abscissas to merge + * @return {{x: Array, y: Array}} + */ +function maxMerge(points) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const { + x, + y + } = points; + const { + groupWidth = 0.001 + } = options; + var merged = { + x: [], + y: [] + }; + var maxAbscissa = { + x: [], + y: [] + }; + var size = 0; + var index = 0; + + while (index < x.length) { + if (size === 0 || x[index] - merged.x[size - 1] > groupWidth) { + maxAbscissa.x.push(x[index]); + maxAbscissa.y.push(y[index]); + merged.x.push(x[index]); + merged.y.push(y[index]); + index++; + size++; + } else { + if (y[index] > maxAbscissa.y[size - 1]) { + maxAbscissa.x[size - 1] = x[index]; + maxAbscissa.y[size - 1] = y[index]; + } - static load(json) { - if (json.name !== 'potentialRegression') { - throw new TypeError('not a potential regression model'); - } - return new PotentialRegression(true, json); + merged.x[size - 1] = x[index]; + merged.y[size - 1] += y[index]; + index++; } + } + + merged.x = maxAbscissa.x.slice(); + return merged; } -exports.default = PotentialRegression; /***/ }), -/* 132 */ -/***/ (function(module, exports, __webpack_require__) { +/* 136 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return maxY; }); +/* harmony import */ var binary_search__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var binary_search__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(binary_search__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var num_sort__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7); +/* harmony import */ var num_sort__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(num_sort__WEBPACK_IMPORTED_MODULE_1__); -var mlMatrix = __webpack_require__(0); - /** - * Calculate current error - * @ignore - * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ] - * @param {Array} parameters - Array of current parameter values - * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter - * @return {number} + * @param {object} points + * @param {Array} points.x - sorted abscissas values + * @param {Array} points.y - ordinates values + * @param {object} [options] + * @param {object} [options.from = {index: 0}] + * @param {object} [options.to = {index: x.length-1}] + * @param {boolean} [options.reverse = false] + * @return {{index: number, value: number}} */ -function errorCalculation(data, parameters, parameterizedFunction) { - var error = 0; - var func = parameterizedFunction(parameters); - for (var i = 0; i < data.x.length; i++) { - error += Math.abs(data.y[i] - func(data.x[i])); +function maxY(points) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const { + x, + y + } = points; + let { + from = { + index: 0 + }, + to = { + index: x.length + }, + reverse = false + } = options; + + if (from.value !== undefined && from.index === undefined) { + from.index = calculateIndex(from.value, x, reverse); } - return error; -} + if (to.value !== undefined && to.index === undefined) { + to.index = calculateIndex(to.value, x, reverse); + } + + var currentMax = Number.MIN_VALUE; + var currentIndex; + for (var i = from.index; i < to.index; i++) { + if (currentMax < y[i]) { + currentMax = y[i]; + currentIndex = i; + } + } + + return { + index: currentIndex, + value: currentMax + }; +} /** - * Difference of the matrix function over the parameters - * @ignore - * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ] - * @param {Array} evaluatedData - Array of previous evaluated function values - * @param {Array} params - Array of previous parameter values - * @param {number} gradientDifference - Adjustment for decrease the damping parameter - * @param {function} paramFunction - The parameters and returns a function with the independent variable as a parameter - * @return {Matrix} + * @param {number} value + * @param {Array} x + * @param {boolean} reverse + * @return {number} index of the value in the array */ -function gradientFunction(data, evaluatedData, params, gradientDifference, paramFunction) { - var n = params.length; - var m = data.x.length; - var ans = new Array(n); +function calculateIndex(value, x, reverse) { + let index; - for (var param = 0; param < n; param++) { - ans[param] = new Array(m); - var auxParams = params.concat(); - auxParams[param] += gradientDifference; - var funcParam = paramFunction(auxParams); + if (reverse) { + index = binary_search__WEBPACK_IMPORTED_MODULE_0___default()(x, value, num_sort__WEBPACK_IMPORTED_MODULE_1__["desc"]); + } else { + index = binary_search__WEBPACK_IMPORTED_MODULE_0___default()(x, value, num_sort__WEBPACK_IMPORTED_MODULE_1__["asc"]); + } - for (var point = 0; point < m; point++) { - ans[param][point] = evaluatedData[point] - funcParam(data.x[point]); - } + if (index < 0) { + throw new Error("the value ".concat(value, " doesn't belongs to the abscissa value")); } - return new mlMatrix.Matrix(ans); + + return index; } -/** - * Matrix function over the samples - * @ignore - * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ] - * @param {Array} evaluatedData - Array of previous evaluated function values - * @return {Matrix} - */ -function matrixFunction(data, evaluatedData) { - var m = data.x.length; +/***/ }), +/* 137 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return sortX; }); +function sortX(points) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const { + x, + y + } = points; + const { + reverse = false + } = options; + var sortFunc; + + if (!reverse) { + sortFunc = (a, b) => a.x - b.x; + } else { + sortFunc = (a, b) => b.x - a.x; + } - var ans = new Array(m); + var grouped = x.map((val, index) => ({ + x: val, + y: y[index] + })).sort(sortFunc); + var response = { + x: x.slice(), + y: y.slice() + }; - for (var point = 0; point < m; point++) { - ans[point] = data.y[point] - evaluatedData[point]; + for (var i = 0; i < x.length; i++) { + response.x[i] = grouped[i].x; + response.y[i] = grouped[i].y; } - return new mlMatrix.Matrix([ans]); + return response; } +/***/ }), +/* 138 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return uniqueX; }); /** - * Iteration for Levenberg-Marquardt - * @ignore - * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ] - * @param {Array} params - Array of previous parameter values - * @param {number} damping - Levenberg-Marquardt parameter - * @param {number} gradientDifference - Adjustment for decrease the damping parameter - * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter - * @return {Array} + * In place modification of the 2 arrays to make X unique and sum the Y if X has the same value + * @param {object} [points={}] : Object of points contains property x (an array) and y (an array) + * @return points */ -function step(data, params, damping, gradientDifference, parameterizedFunction) { - var identity = mlMatrix.Matrix.eye(params.length).mul(damping * gradientDifference * gradientDifference); - - var l = data.x.length; - var evaluatedData = new Array(l); - var func = parameterizedFunction(params); - for (var i = 0; i < l; i++) { - evaluatedData[i] = func(data.x[i]); +function uniqueX() { + let points = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + const { + x, + y + } = points; + if (x.length < 2) return; + + if (x.length !== y.length) { + throw new Error('The X and Y arrays mush have the same length'); } - var gradientFunc = gradientFunction(data, evaluatedData, params, gradientDifference, parameterizedFunction); - var matrixFunc = matrixFunction(data, evaluatedData).transposeView(); - var inverseMatrix = mlMatrix.inverse(identity.add(gradientFunc.mmul(gradientFunc.transposeView()))); - params = new mlMatrix.Matrix([params]); - params = params.sub(inverseMatrix.mmul(gradientFunc).mmul(matrixFunc).mul(gradientDifference).transposeView()); - return params.to1DArray(); -} + let current = x[0]; + let counter = 0; -/** - * Curve fitting algorithm - * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ] - * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter - * @param {object} [options] - Options object - * @param {number} [options.damping] - Levenberg-Marquardt parameter - * @param {number} [options.gradientDifference = 10e-2] - Adjustment for decrease the damping parameter - * @param {Array} [options.initialValues] - Array of initial parameter values - * @param {number} [options.maxIterations = 100] - Maximum of allowed iterations - * @param {number} [options.errorTolerance = 10e-3] - Minimum uncertainty allowed for each point - * @return {{parameterValues: Array, parameterError: number, iterations: number}} - */ -function levenbergMarquardt(data, parameterizedFunction, options = {}) { - var _options$maxIteration = options.maxIterations, - maxIterations = _options$maxIteration === undefined ? 100 : _options$maxIteration, - _options$gradientDiff = options.gradientDifference, - gradientDifference = _options$gradientDiff === undefined ? 10e-2 : _options$gradientDiff, - _options$damping = options.damping, - damping = _options$damping === undefined ? 0 : _options$damping, - _options$errorToleran = options.errorTolerance, - errorTolerance = _options$errorToleran === undefined ? 10e-3 : _options$errorToleran, - initialValues = options.initialValues; + for (let i = 1; i < x.length; i++) { + if (current !== x[i]) { + counter++; + current = x[i]; + x[counter] = x[i]; + if (i !== counter) { + y[counter] = 0; + } + } - if (damping <= 0) { - throw new Error('The damping option must be a positive number'); - } else if (!data.x || !data.y) { - throw new Error('The data parameter must have x and y elements'); - } else if (!Array.isArray(data.x) || data.x.length < 2 || !Array.isArray(data.y) || data.y.length < 2) { - throw new Error('The data parameter elements must be an array with more than 2 points'); - } else { - var dataLen = data.x.length; - if (dataLen !== data.y.length) { - throw new Error('The data parameter elements must have the same size'); + if (i !== counter) { + y[counter] += y[i]; } } - var parameters = initialValues || new Array(parameterizedFunction.length).fill(1); - - if (!Array.isArray(parameters)) { - throw new Error('initialValues must be an array'); - } + x.length = counter + 1; + y.length = counter + 1; +} - var error = errorCalculation(data, parameters, parameterizedFunction); +/***/ }), +/* 139 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - var converged = error <= errorTolerance; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return weightedMerge; }); +/** + * Merge abscissas values on similar ordinates and weight the group of abscissas + * @param {object} points + * @param {Array} points.x - sorted abscissas values + * @param {Array} points.y - ordinates values + * @param {object} [options] + * @param {number} [options.groupWidth = 0.001] - window for abscissas to merge + * @return {{x: Array, y: Array}} + */ +function weightedMerge(points) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const { + x, + y + } = points; + const { + groupWidth = 0.001 + } = options; + var merged = { + x: [], + y: [] + }; + var weightedAbscissa = { + x: [], + y: [] + }; + var size = 0; + var index = 0; + + while (index < x.length) { + if (size === 0 || x[index] - merged.x[size - 1] > groupWidth) { + weightedAbscissa.x.push(x[index] * y[index]); + weightedAbscissa.y.push(y[index]); + merged.x.push(x[index]); + merged.y.push(y[index]); + index++; + size++; + } else { + weightedAbscissa.x[size - 1] += x[index] * y[index]; + weightedAbscissa.y[size - 1] += y[index]; + merged.x[size - 1] = x[index]; + merged.y[size - 1] += y[index]; + index++; + } + } - for (var iteration = 0; iteration < maxIterations && !converged; iteration++) { - parameters = step(data, parameters, damping, gradientDifference, parameterizedFunction); - error = errorCalculation(data, parameters, parameterizedFunction); - converged = error <= errorTolerance; + for (var i = 0; i < merged.x.length; i++) { + merged.x[i] = weightedAbscissa.x[i] / weightedAbscissa.y[i]; } - return { - parameterValues: parameters, - parameterError: error, - iterations: iteration - }; + return merged; } -module.exports = levenbergMarquardt; - /***/ }), -/* 133 */ -/***/ (function(module, exports, __webpack_require__) { +/* 140 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +__webpack_require__.r(__webpack_exports__); +// CONCATENATED MODULE: ./node_modules/ml-kmeans/node_modules/ml-distance-euclidean/lib-es6/euclidean.js +function squaredEuclidean(p, q) { + let d = 0; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.SparseMatrix = undefined; + for (let i = 0; i < p.length; i++) { + d += (p[i] - q[i]) * (p[i] - q[i]); + } -var _mlHashTable = __webpack_require__(42); + return d; +} +function euclidean(p, q) { + return Math.sqrt(squaredEuclidean(p, q)); +} +// CONCATENATED MODULE: ./node_modules/ml-nearest-vector/node_modules/ml-distance-euclidean/lib-es6/euclidean.js +function euclidean_squaredEuclidean(p, q) { + let d = 0; -var _mlHashTable2 = _interopRequireDefault(_mlHashTable); + for (let i = 0; i < p.length; i++) { + d += (p[i] - q[i]) * (p[i] - q[i]); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return d; +} +function euclidean_euclidean(p, q) { + return Math.sqrt(euclidean_squaredEuclidean(p, q)); +} +// CONCATENATED MODULE: ./node_modules/ml-nearest-vector/lib-es6/index.js -class SparseMatrix { - constructor(rows, columns, options = {}) { - if (rows instanceof SparseMatrix) { - // clone - var other = rows; - this._init(other.rows, other.columns, other.elements.clone(), other.threshold); - return; - } - if (Array.isArray(rows)) { - var matrix = rows; - rows = matrix.length; - options = columns || {}; - columns = matrix[0].length; - this._init(rows, columns, new _mlHashTable2.default(options), options.threshold); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - var value = matrix[i][j]; - if (this.threshold && Math.abs(value) < this.threshold) value = 0; - if (value !== 0) { - this.elements.set(i * columns + j, matrix[i][j]); - } - } - } - } else { - this._init(rows, columns, new _mlHashTable2.default(options), options.threshold); - } - } - _init(rows, columns, elements, threshold) { - this.rows = rows; - this.columns = columns; - this.elements = elements; - this.threshold = threshold || 0; +const defaultOptions = { + distanceFunction: euclidean_squaredEuclidean +}; +function nearestVector(listVectors, vector) { + let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultOptions; + const distanceFunction = options.distanceFunction || defaultOptions.distanceFunction; + const similarityFunction = options.similarityFunction || defaultOptions.similarityFunction; + let vectorIndex = -1; + + if (typeof similarityFunction === 'function') { + // maximum similarity + let maxSim = Number.MIN_VALUE; + + for (let j = 0; j < listVectors.length; j++) { + const sim = similarityFunction(vector, listVectors[j]); + + if (sim > maxSim) { + maxSim = sim; + vectorIndex = j; + } } + } else if (typeof distanceFunction === 'function') { + // minimum distance + let minDist = Number.MAX_VALUE; - static eye(rows = 1, columns = rows) { - var min = Math.min(rows, columns); - var matrix = new SparseMatrix(rows, columns, { initialCapacity: min }); - for (var i = 0; i < min; i++) { - matrix.set(i, i, 1); - } - return matrix; - } + for (let i = 0; i < listVectors.length; i++) { + const dist = distanceFunction(vector, listVectors[i]); - clone() { - return new SparseMatrix(this); + if (dist < minDist) { + minDist = dist; + vectorIndex = i; + } } + } else { + throw new Error("A similarity or distance function it's required"); + } - to2DArray() { - var copy = new Array(this.rows); - for (var i = 0; i < this.rows; i++) { - copy[i] = new Array(this.columns); - for (var j = 0; j < this.columns; j++) { - copy[i][j] = this.get(i, j); - } - } - return copy; - } + return vectorIndex; +} +function findNearestVector(vectorList, vector) { + let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultOptions; + const index = nearestVector(vectorList, vector, options); + return vectorList[index]; +} +// CONCATENATED MODULE: ./node_modules/ml-kmeans/src/utils.js - isSquare() { - return this.rows === this.columns; - } +/** + * Calculates the distance matrix for a given array of points + * @ignore + * @param {Array>} data - the [x,y,z,...] points to cluster + * @param {function} distance - Distance function to use between the points + * @return {Array>} - matrix with the distance values + */ - isSymmetric() { - if (!this.isSquare()) return false; +function calculateDistanceMatrix(data, distance) { + var distanceMatrix = new Array(data.length); - var symmetric = true; - this.forEachNonZero((i, j, v) => { - if (this.get(j, i) !== v) { - symmetric = false; - return false; - } - return v; - }); - return symmetric; - } + for (var i = 0; i < data.length; ++i) { + for (var j = i; j < data.length; ++j) { + if (!distanceMatrix[i]) { + distanceMatrix[i] = new Array(data.length); + } - /** - * Search for the wither band in the main diagonals - * @return {number} - */ - bandWidth() { - var min = this.columns; - var max = -1; - this.forEachNonZero((i, j, v) => { - var diff = i - j; - min = Math.min(min, diff); - max = Math.max(max, diff); - return v; - }); - return max - min; - } + if (!distanceMatrix[j]) { + distanceMatrix[j] = new Array(data.length); + } - /** - * Test if a matrix is consider banded using a threshold - * @param {number} width - * @return {boolean} - */ - isBanded(width) { - var bandWidth = this.bandWidth(); - return bandWidth <= width; + const dist = distance(data[i], data[j]); + distanceMatrix[i][j] = dist; + distanceMatrix[j][i] = dist; } + } - get cardinality() { - return this.elements.size; - } + return distanceMatrix; +} +/** + * Updates the cluster identifier based in the new data + * @ignore + * @param {Array>} data - the [x,y,z,...] points to cluster + * @param {Array>} centers - the K centers in format [x,y,z,...] + * @param {Array } clusterID - the cluster identifier for each data dot + * @param {function} distance - Distance function to use between the points + * @return {Array} the cluster identifier for each data dot + */ - get size() { - return this.rows * this.columns; - } +function updateClusterID(data, centers, clusterID, distance) { + for (var i = 0; i < data.length; i++) { + clusterID[i] = nearestVector(centers, data[i], { + distanceFunction: distance + }); + } - get(row, column) { - return this.elements.get(row * this.columns + column); - } + return clusterID; +} +/** + * Update the center values based in the new configurations of the clusters + * @ignore + * @param {Array>} prevCenters - Centroids from the previous iteration + * @param {Array >} data - the [x,y,z,...] points to cluster + * @param {Array } clusterID - the cluster identifier for each data dot + * @param {number} K - Number of clusters + * @return {Array} he K centers in format [x,y,z,...] + */ - set(row, column, value) { - if (this.threshold && Math.abs(value) < this.threshold) value = 0; - if (value === 0) { - this.elements.remove(row * this.columns + column); - } else { - this.elements.set(row * this.columns + column, value); - } - return this; - } +function updateCenters(prevCenters, data, clusterID, K) { + const nDim = data[0].length; // copy previous centers - mmul(other) { - if (this.columns !== other.rows) { - // eslint-disable-next-line no-console - console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.'); - } + var centers = new Array(K); + var centersLen = new Array(K); - var m = this.rows; - var p = other.columns; + for (var i = 0; i < K; i++) { + centers[i] = new Array(nDim); + centersLen[i] = 0; - var result = new SparseMatrix(m, p); - this.forEachNonZero((i, j, v1) => { - other.forEachNonZero((k, l, v2) => { - if (j === k) { - result.set(i, l, result.get(i, l) + v1 * v2); - } - return v2; - }); - return v1; - }); - return result; + for (var j = 0; j < nDim; j++) { + centers[i][j] = 0; } + } // add the value for all dimensions of the point - kroneckerProduct(other) { - var m = this.rows; - var n = this.columns; - var p = other.rows; - var q = other.columns; - var result = new SparseMatrix(m * p, n * q, { - initialCapacity: this.cardinality * other.cardinality - }); - this.forEachNonZero((i, j, v1) => { - other.forEachNonZero((k, l, v2) => { - result.set(p * i + k, q * j + l, v1 * v2); - return v2; - }); - return v1; - }); - return result; - } + for (var l = 0; l < data.length; l++) { + centersLen[clusterID[l]]++; - forEachNonZero(callback) { - this.elements.forEachPair((key, value) => { - var i = key / this.columns | 0; - var j = key % this.columns; - var r = callback(i, j, value); - if (r === false) return false; // stop iteration - if (this.threshold && Math.abs(r) < this.threshold) r = 0; - if (r !== value) { - if (r === 0) { - this.elements.remove(key, true); - } else { - this.elements.set(key, r); - } - } - return true; - }); - this.elements.maybeShrinkCapacity(); - return this; + for (var dim = 0; dim < nDim; dim++) { + centers[clusterID[l]][dim] += data[l][dim]; } + } // divides by length - getNonZeros() { - var cardinality = this.cardinality; - var rows = new Array(cardinality); - var columns = new Array(cardinality); - var values = new Array(cardinality); - var idx = 0; - this.forEachNonZero((i, j, value) => { - rows[idx] = i; - columns[idx] = j; - values[idx] = value; - idx++; - return value; - }); - return { rows, columns, values }; - } - setThreshold(newThreshold) { - if (newThreshold !== 0 && newThreshold !== this.threshold) { - this.threshold = newThreshold; - this.forEachNonZero((i, j, v) => v); - } - return this; + for (var id = 0; id < K; id++) { + for (var d = 0; d < nDim; d++) { + if (centersLen[id]) { + centers[id][d] /= centersLen[id]; + } else { + centers[id][d] = prevCenters[id][d]; + } } + } - /** - * @return {SparseMatrix} - New transposed sparse matrix - */ - transpose() { - var trans = new SparseMatrix(this.columns, this.rows, { initialCapacity: this.cardinality }); - this.forEachNonZero((i, j, value) => { - trans.set(j, i, value); - return value; - }); - return trans; - } + return centers; } +/** + * The centers have moved more than the tolerance value? + * @ignore + * @param {Array>} centers - the K centers in format [x,y,z,...] + * @param {Array>} oldCenters - the K old centers in format [x,y,z,...] + * @param {function} distanceFunction - Distance function to use between the points + * @param {number} tolerance - Allowed distance for the centroids to move + * @return {boolean} + */ -exports.SparseMatrix = SparseMatrix; -SparseMatrix.prototype.klass = 'Matrix'; +function hasConverged(centers, oldCenters, distanceFunction, tolerance) { + for (var i = 0; i < centers.length; i++) { + if (distanceFunction(centers[i], oldCenters[i]) > tolerance) { + return false; + } + } -SparseMatrix.identity = SparseMatrix.eye; -SparseMatrix.prototype.tensorProduct = SparseMatrix.prototype.kroneckerProduct; + return true; +} +// EXTERNAL MODULE: ./node_modules/ml-random/lib-es6/index.js + 1 modules +var lib_es6 = __webpack_require__(11); -/* - Add dynamically instance and static methods for mathematical operations - */ +// EXTERNAL MODULE: ./node_modules/ml-matrix/src/index.js + 24 modules +var src = __webpack_require__(0); + +// CONCATENATED MODULE: ./node_modules/ml-kmeans/src/initialization.js -var inplaceOperator = ` -(function %name%(value) { - if (typeof value === 'number') return this.%name%S(value); - return this.%name%M(value); -}) -`; -var inplaceOperatorScalar = ` -(function %name%S(value) { - this.forEachNonZero((i, j, v) => v %op% value); - return this; -}) -`; - -var inplaceOperatorMatrix = ` -(function %name%M(matrix) { - matrix.forEachNonZero((i, j, v) => { - this.set(i, j, this.get(i, j) %op% v); - return v; - }); - return this; -}) -`; - -var staticOperator = ` -(function %name%(matrix, value) { - var newMatrix = new SparseMatrix(matrix); - return newMatrix.%name%(value); -}) -`; - -var inplaceMethod = ` -(function %name%() { - this.forEachNonZero((i, j, v) => %method%(v)); - return this; -}) -`; - -var staticMethod = ` -(function %name%(matrix) { - var newMatrix = new SparseMatrix(matrix); - return newMatrix.%name%(); -}) -`; - -var operators = [ -// Arithmetic operators -['+', 'add'], ['-', 'sub', 'subtract'], ['*', 'mul', 'multiply'], ['/', 'div', 'divide'], ['%', 'mod', 'modulus'], -// Bitwise operators -['&', 'and'], ['|', 'or'], ['^', 'xor'], ['<<', 'leftShift'], ['>>', 'signPropagatingRightShift'], ['>>>', 'rightShift', 'zeroFillRightShift']]; -for (var operator of operators) { - for (var i = 1; i < operator.length; i++) { - SparseMatrix.prototype[operator[i]] = eval(fillTemplateFunction(inplaceOperator, { name: operator[i], op: operator[0] })); - SparseMatrix.prototype[operator[i] + 'S'] = eval(fillTemplateFunction(inplaceOperatorScalar, { name: operator[i] + 'S', op: operator[0] })); - SparseMatrix.prototype[operator[i] + 'M'] = eval(fillTemplateFunction(inplaceOperatorMatrix, { name: operator[i] + 'M', op: operator[0] })); +/** + * Choose K different random points from the original data + * @ignore + * @param {Array>} data - Points in the format to cluster [x,y,z,...] + * @param {number} K - number of clusters + * @param {number} seed - seed for random number generation + * @return {Array>} - Initial random points + */ - SparseMatrix[operator[i]] = eval(fillTemplateFunction(staticOperator, { name: operator[i] })); - } +function initialization_random(data, K, seed) { + const random = new lib_es6["default"](seed); + return random.choice(data, { + size: K + }); } +/** + * Chooses the most distant points to a first random pick + * @ignore + * @param {Array>} data - Points in the format to cluster [x,y,z,...] + * @param {number} K - number of clusters + * @param {Array>} distanceMatrix - matrix with the distance values + * @param {number} seed - seed for random number generation + * @return {Array>} - Initial random points + */ -var methods = [['~', 'not']]; +function mostDistant(data, K, distanceMatrix, seed) { + const random = new lib_es6["default"](seed); + var ans = new Array(K); // chooses a random point as initial cluster -['abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil', 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p', 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'].forEach(function (mathMethod) { - methods.push(['Math.' + mathMethod, mathMethod]); -}); + ans[0] = Math.floor(random.random() * data.length); -for (var method of methods) { - for (var _i = 1; _i < method.length; _i++) { - SparseMatrix.prototype[method[_i]] = eval(fillTemplateFunction(inplaceMethod, { name: method[_i], method: method[0] })); - SparseMatrix[method[_i]] = eval(fillTemplateFunction(staticMethod, { name: method[_i] })); - } -} + if (K > 1) { + // chooses the more distant point + var maxDist = { + dist: -1, + index: -1 + }; -function fillTemplateFunction(template, values) { - for (var _i2 in values) { - template = template.replace(new RegExp('%' + _i2 + '%', 'g'), values[_i2]); + for (var l = 0; l < data.length; ++l) { + if (distanceMatrix[ans[0]][l] > maxDist.dist) { + maxDist.dist = distanceMatrix[ans[0]][l]; + maxDist.index = l; + } } - return template; -} - -/***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + ans[1] = maxDist.index; + if (K > 2) { + // chooses the set of points that maximises the min distance + for (var k = 2; k < K; ++k) { + var center = { + dist: -1, + index: -1 + }; -module.exports = newArray; + for (var m = 0; m < data.length; ++m) { + // minimum distance to centers + var minDistCent = { + dist: Number.MAX_VALUE, + index: -1 + }; -function newArray(n, value) { - n = n || 0; - var array = new Array(n); - for (var i = 0; i < n; i++) { - array[i] = value; - } - return array; -} + for (var n = 0; n < k; ++n) { + if (distanceMatrix[n][m] < minDistCent.dist && ans.indexOf(m) === -1) { + minDistCent = { + dist: distanceMatrix[n][m], + index: m + }; + } + } -/***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { + if (minDistCent.dist !== Number.MAX_VALUE && minDistCent.dist > center.dist) { + center = Object.assign({}, minDistCent); + } + } -"use strict"; + ans[k] = center.index; + } + } + } + return ans.map(index => data[index]); +} // Implementation inspired from scikit -var binarySearch = __webpack_require__(43); -var sortAsc = __webpack_require__(44).asc; +function kmeanspp(X, K) { + let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + X = new src["Matrix"](X); + const nSamples = X.length; + const random = new lib_es6["default"](options.seed); // Set the number of trials -var largestPrime = 0x7fffffff; + const centers = []; + const localTrials = options.localTrials || 2 + Math.floor(Math.log(K)); // Pick the first center at random from the dataset -var primeNumbers = [ -//chunk #0 -largestPrime, // 2^31-1 + const firstCenterIdx = random.randInt(nSamples); + centers.push(X[firstCenterIdx].slice()); // Init closest distances -//chunk #1 -5, 11, 23, 47, 97, 197, 397, 797, 1597, 3203, 6421, 12853, 25717, 51437, 102877, 205759, 411527, 823117, 1646237, 3292489, 6584983, 13169977, 26339969, 52679969, 105359939, 210719881, 421439783, 842879579, 1685759167, + let closestDistSquared = [X.map(x => squaredEuclidean(x, centers[0]))]; + let cumSumClosestDistSquared = [cumSum(closestDistSquared[0])]; + const factor = 1 / cumSumClosestDistSquared[0][nSamples - 1]; + let probabilities = src["Matrix"].mul(closestDistSquared, factor); // Iterate over the remaining centers -//chunk #2 -433, 877, 1759, 3527, 7057, 14143, 28289, 56591, 113189, 226379, 452759, 905551, 1811107, 3622219, 7244441, 14488931, 28977863, 57955739, 115911563, 231823147, 463646329, 927292699, 1854585413, + for (let i = 1; i < K; i++) { + const candidateIdx = random.choice(nSamples, { + replace: true, + size: localTrials, + probabilities: probabilities[0] + }); + const candidates = X.selection(candidateIdx, range(X[0].length)); + const distanceToCandidates = euclidianDistances(candidates, X); + let bestCandidate; + let bestPot; + let bestDistSquared; -//chunk #3 -953, 1907, 3821, 7643, 15287, 30577, 61169, 122347, 244703, 489407, 978821, 1957651, 3915341, 7830701, 15661423, 31322867, 62645741, 125291483, 250582987, 501165979, 1002331963, 2004663929, + for (let j = 0; j < localTrials; j++) { + const newDistSquared = src["Matrix"].min(closestDistSquared, [distanceToCandidates[j]]); + const newPot = newDistSquared.sum(); -//chunk #4 -1039, 2081, 4177, 8363, 16729, 33461, 66923, 133853, 267713, 535481, 1070981, 2141977, 4283963, 8567929, 17135863, 34271747, 68543509, 137087021, 274174111, 548348231, 1096696463, + if (bestCandidate === undefined || newPot < bestPot) { + bestCandidate = candidateIdx[j]; + bestPot = newPot; + bestDistSquared = newDistSquared; + } + } -//chunk #5 -31, 67, 137, 277, 557, 1117, 2237, 4481, 8963, 17929, 35863, 71741, 143483, 286973, 573953, 1147921, 2295859, 4591721, 9183457, 18366923, 36733847, 73467739, 146935499, 293871013, 587742049, 1175484103, + centers[i] = X[bestCandidate].slice(); + closestDistSquared = bestDistSquared; + cumSumClosestDistSquared = [cumSum(closestDistSquared[0])]; + probabilities = src["Matrix"].mul(closestDistSquared, 1 / cumSumClosestDistSquared[0][nSamples - 1]); + } -//chunk #6 -599, 1201, 2411, 4831, 9677, 19373, 38747, 77509, 155027, 310081, 620171, 1240361, 2480729, 4961459, 9922933, 19845871, 39691759, 79383533, 158767069, 317534141, 635068283, 1270136683, + return centers; +} -//chunk #7 -311, 631, 1277, 2557, 5119, 10243, 20507, 41017, 82037, 164089, 328213, 656429, 1312867, 2625761, 5251529, 10503061, 21006137, 42012281, 84024581, 168049163, 336098327, 672196673, 1344393353, +function euclidianDistances(A, B) { + const result = new src["Matrix"](A.length, B.length); -//chunk #8 -3, 7, 17, 37, 79, 163, 331, 673, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899, 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557, 359339171, 718678369, 1437356741, + for (let i = 0; i < A.length; i++) { + for (let j = 0; j < B.length; j++) { + result.set(i, j, squaredEuclidean(A.getRow(i), B.getRow(j))); + } + } -//chunk #9 -43, 89, 179, 359, 719, 1439, 2879, 5779, 11579, 23159, 46327, 92657, 185323, 370661, 741337, 1482707, 2965421, 5930887, 11861791, 23723597, 47447201, 94894427, 189788857, 379577741, 759155483, 1518310967, + return result; +} -//chunk #10 -379, 761, 1523, 3049, 6101, 12203, 24407, 48817, 97649, 195311, 390647, 781301, 1562611, 3125257, 6250537, 12501169, 25002389, 50004791, 100009607, 200019221, 400038451, 800076929, 1600153859, +function range(l) { + let r = []; -//chunk #11 -13, 29, 59, 127, 257, 521, 1049, 2099, 4201, 8419, 16843, 33703, 67409, 134837, 269683, 539389, 1078787, 2157587, 4315183, 8630387, 17260781, 34521589, 69043189, 138086407, 276172823, 552345671, 1104691373, + for (let i = 0; i < l; i++) { + r.push(i); + } -//chunk #12 -19, 41, 83, 167, 337, 677, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899, 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557, 359339171, 718678369, 1437356741, + return r; +} -//chunk #13 -53, 107, 223, 449, 907, 1823, 3659, 7321, 14653, 29311, 58631, 117269, 234539, 469099, 938207, 1876417, 3752839, 7505681, 15011389, 30022781, 60045577, 120091177, 240182359, 480364727, 960729461, 1921458943]; +function cumSum(arr) { + let cumSum = [arr[0]]; -primeNumbers.sort(sortAsc); + for (let i = 1; i < arr.length; i++) { + cumSum[i] = cumSum[i - 1] + arr[i]; + } -function nextPrime(value) { - var index = binarySearch(primeNumbers, value, sortAsc); - if (index < 0) { - index = ~index; - } - return primeNumbers[index]; + return cumSum; } +// CONCATENATED MODULE: ./node_modules/ml-kmeans/src/KMeansResult.js -exports.nextPrime = nextPrime; -exports.largestPrime = largestPrime; +const distanceSymbol = Symbol('distance'); +class KMeansResult_KMeansResult { + /** + * Result of the kmeans algorithm + * @param {Array} clusters - the cluster identifier for each data dot + * @param {Array>} centroids - the K centers in format [x,y,z,...], the error and size of the cluster + * @param {boolean} converged - Converge criteria satisfied + * @param {number} iterations - Current number of iterations + * @param {function} distance - (*Private*) Distance function to use between the points + * @constructor + */ + constructor(clusters, centroids, converged, iterations, distance) { + this.clusters = clusters; + this.centroids = centroids; + this.converged = converged; + this.iterations = iterations; + this[distanceSymbol] = distance; + } + /** + * Allows to compute for a new array of points their cluster id + * @param {Array>} data - the [x,y,z,...] points to cluster + * @return {Array} - cluster id for each point + */ -/***/ }), -/* 136 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + nearest(data) { + const clusterID = new Array(data.length); + const centroids = this.centroids.map(function (centroid) { + return centroid.centroid; + }); + return updateClusterID(data, centroids, clusterID, this[distanceSymbol]); + } + /** + * Returns a KMeansResult with the error and size of the cluster + * @ignore + * @param {Array>} data - the [x,y,z,...] points to cluster + * @return {KMeansResult} + */ -module.exports = Number.isNaN || function (x) { - return x !== x; -}; + computeInformation(data) { + var enrichedCentroids = this.centroids.map(function (centroid) { + return { + centroid: centroid, + error: 0, + size: 0 + }; + }); -/***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { + for (var i = 0; i < data.length; i++) { + enrichedCentroids[this.clusters[i]].error += this[distanceSymbol](data[i], this.centroids[this.clusters[i]]); + enrichedCentroids[this.clusters[i]].size++; + } -"use strict"; + for (var j = 0; j < this.centroids.length; j++) { + if (enrichedCentroids[j].size) { + enrichedCentroids[j].error /= enrichedCentroids[j].size; + } else { + enrichedCentroids[j].error = null; + } + } + return new KMeansResult_KMeansResult(this.clusters, enrichedCentroids, this.converged, this.iterations, this[distanceSymbol]); + } -exports.additiveSymmetric = __webpack_require__(138); -exports.avg = __webpack_require__(139); -exports.bhattacharyya = __webpack_require__(140); -exports.canberra = __webpack_require__(141); -exports.chebyshev = __webpack_require__(142); -exports.clark = __webpack_require__(143); -exports.czekanowski = __webpack_require__(144); -exports.dice = __webpack_require__(47); -exports.divergence = __webpack_require__(145); -exports.euclidean = __webpack_require__(1); -exports.fidelity = __webpack_require__(146); -exports.gower = __webpack_require__(147); -exports.harmonicMean = __webpack_require__(148); -exports.hellinger = __webpack_require__(149); -exports.innerProduct = __webpack_require__(150); -exports.intersection = __webpack_require__(48); -exports.jaccard = __webpack_require__(49); -exports.jeffreys = __webpack_require__(151); -exports.jensenDifference = __webpack_require__(152); -exports.jensenShannon = __webpack_require__(153); -exports.kdivergence = __webpack_require__(154); -exports.kulczynski = __webpack_require__(50); -exports.kullbackLeibler = __webpack_require__(155); -exports.kumarHassebrook = __webpack_require__(156); -exports.kumarJohnson = __webpack_require__(157); -exports.lorentzian = __webpack_require__(158); -exports.manhattan = __webpack_require__(159); -exports.matusita = __webpack_require__(160); -exports.minkowski = __webpack_require__(161); -exports.motyka = __webpack_require__(51); -exports.neyman = __webpack_require__(162); -exports.pearson = __webpack_require__(163); -exports.probabilisticSymmetric = __webpack_require__(164); -exports.ruzicka = __webpack_require__(165); -exports.soergel = __webpack_require__(166); -exports.sorensen = __webpack_require__(167); -exports.squared = __webpack_require__(168); -exports.squaredChord = __webpack_require__(52); -exports.squaredEuclidean = __webpack_require__(1).squared; -exports.taneja = __webpack_require__(169); -exports.tanimoto = __webpack_require__(170); -exports.topsoe = __webpack_require__(171); -exports.tree = __webpack_require__(172); -exports.waveHedges = __webpack_require__(173); +} +// CONCATENATED MODULE: ./node_modules/ml-kmeans/src/kmeans.js +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return kmeans; }); -/***/ }), -/* 138 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; -module.exports = function additiveSymmetric(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += (a[i] - b[i]) * (a[i] - b[i]) * (a[i] + b[i]) / (a[i] * b[i]); - } - return 2 * d; +const kmeans_defaultOptions = { + maxIterations: 100, + tolerance: 1e-6, + withIterations: false, + initialization: 'kmeans++', + distanceFunction: squaredEuclidean }; +/** + * Each step operation for kmeans + * @ignore + * @param {Array>} centers - K centers in format [x,y,z,...] + * @param {Array>} data - Points [x,y,z,...] to cluster + * @param {Array} clusterID - Cluster identifier for each data dot + * @param {number} K - Number of clusters + * @param {object} [options] - Option object + * @param {number} iterations - Current number of iterations + * @return {KMeansResult} + */ -/***/ }), -/* 139 */ -/***/ (function(module, exports, __webpack_require__) { +function step(centers, data, clusterID, K, options, iterations) { + clusterID = updateClusterID(data, centers, clusterID, options.distanceFunction); + var newCenters = updateCenters(centers, data, clusterID, K); + var converged = hasConverged(newCenters, centers, options.distanceFunction, options.tolerance); + return new KMeansResult_KMeansResult(clusterID, newCenters, converged, iterations, options.distanceFunction); +} +/** + * Generator version for the algorithm + * @ignore + * @param {Array>} centers - K centers in format [x,y,z,...] + * @param {Array>} data - Points [x,y,z,...] to cluster + * @param {Array} clusterID - Cluster identifier for each data dot + * @param {number} K - Number of clusters + * @param {object} [options] - Option object + */ -"use strict"; +function* kmeansGenerator(centers, data, clusterID, K, options) { + var converged = false; + var stepNumber = 0; + var stepResult; -module.exports = function avg(a, b) { - var ii = a.length, - max = 0, - ans = 0, - aux = 0; - for (var i = 0; i < ii; i++) { - aux = Math.abs(a[i] - b[i]); - ans += aux; - if (max < aux) { - max = aux; - } - } - return (max + ans) / 2; -}; + while (!converged && stepNumber < options.maxIterations) { + stepResult = step(centers, data, clusterID, K, options, ++stepNumber); + yield stepResult.computeInformation(data); + converged = stepResult.converged; + centers = stepResult.centroids; + } +} +/** + * K-means algorithm + * @param {Array>} data - Points in the format to cluster [x,y,z,...] + * @param {number} K - Number of clusters + * @param {object} [options] - Option object + * @param {number} [options.maxIterations = 100] - Maximum of iterations allowed + * @param {number} [options.tolerance = 1e-6] - Error tolerance + * @param {boolean} [options.withIterations = false] - Store clusters and centroids for each iteration + * @param {function} [options.distanceFunction = squaredDistance] - Distance function to use between the points + * @param {number} [options.seed] - Seed for random initialization. + * @param {string|Array>} [options.initialization = 'kmeans++'] - K centers in format [x,y,z,...] or a method for initialize the data: + * * You can either specify your custom start centroids, or select one of the following initialization method: + * * `'kmeans++'` will use the kmeans++ method as described by http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf + * * `'random'` will choose K random different values. + * * `'mostDistant'` will choose the more distant points to a first random pick + * @return {KMeansResult} - Cluster identifier for each data dot and centroids with the following fields: + * * `'clusters'`: Array of indexes for the clusters. + * * `'centroids'`: Array with the resulting centroids. + * * `'iterations'`: Number of iterations that took to converge + */ -/***/ }), -/* 140 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +function kmeans(data, K, options) { + options = Object.assign({}, kmeans_defaultOptions, options); + + if (K <= 0 || K > data.length || !Number.isInteger(K)) { + throw new Error('K should be a positive integer smaller than the number of points'); + } + var centers; -module.exports = function bhattacharyya(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += Math.sqrt(a[i] * b[i]); + if (Array.isArray(options.initialization)) { + if (options.initialization.length !== K) { + throw new Error('The initial centers should have the same length as K'); + } else { + centers = options.initialization; } - return -Math.log(ans); -}; - -/***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { + } else { + switch (options.initialization) { + case 'kmeans++': + centers = kmeanspp(data, K, options); + break; -"use strict"; + case 'random': + centers = initialization_random(data, K, options.seed); + break; + case 'mostDistant': + centers = mostDistant(data, K, calculateDistanceMatrix(data, options.distanceFunction), options.seed); + break; -module.exports = function canberra(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += Math.abs(a[i] - b[i]) / (a[i] + b[i]); + default: + throw new Error("Unknown initialization method: \"".concat(options.initialization, "\"")); } - return ans; -}; + } // infinite loop until convergence -/***/ }), -/* 142 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + if (options.maxIterations === 0) { + options.maxIterations = Number.MAX_VALUE; + } + var clusterID = new Array(data.length); -module.exports = function chebyshev(a, b) { - var ii = a.length, - max = 0, - aux = 0; - for (var i = 0; i < ii; i++) { - aux = Math.abs(a[i] - b[i]); - if (max < aux) { - max = aux; - } + if (options.withIterations) { + return kmeansGenerator(centers, data, clusterID, K, options); + } else { + var converged = false; + var stepNumber = 0; + var stepResult; + + while (!converged && stepNumber < options.maxIterations) { + stepResult = step(centers, data, clusterID, K, options, ++stepNumber); + converged = stepResult.converged; + centers = stepResult.centroids; } - return max; -}; + + return stepResult.computeInformation(data); + } +} /***/ }), -/* 143 */ -/***/ (function(module, exports, __webpack_require__) { +/* 141 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +__webpack_require__.r(__webpack_exports__); +// EXTERNAL MODULE: ./node_modules/ml-cart/src/index.js + 4 modules +var src = __webpack_require__(8); -module.exports = function clark(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += Math.sqrt((a[i] - b[i]) * (a[i] - b[i]) / ((a[i] + b[i]) * (a[i] + b[i]))); - } - return 2 * d; -}; +// EXTERNAL MODULE: ./node_modules/ml-matrix/src/index.js + 24 modules +var ml_matrix_src = __webpack_require__(0); -/***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { +// EXTERNAL MODULE: ./node_modules/random-js/lib/random.js +var random = __webpack_require__(12); +var random_default = /*#__PURE__*/__webpack_require__.n(random); -"use strict"; +// CONCATENATED MODULE: ./node_modules/ml-random-forest/src/utils.js -var czekanowskiSimilarity = __webpack_require__(46); +function checkFloat(n) { + return n > 0.0 && n <= 1.0; +} +/** + * Select n with replacement elements on the training set and values, where n is the size of the training set. + * @ignore + * @param {Matrix} trainingSet + * @param {Array} trainingValue + * @param {number} seed - seed for the random selection, must be a 32-bit integer. + * @return {object} with new X and y. + */ -module.exports = function czekanowskiDistance(a, b) { - return 1 - czekanowskiSimilarity(a, b); -}; +function examplesBaggingWithReplacement(trainingSet, trainingValue, seed) { + var engine = random_default.a.engines.mt19937(); + var distribution = random_default.a.integer(0, trainingSet.rows - 1); -/***/ }), -/* 145 */ -/***/ (function(module, exports, __webpack_require__) { + if (seed === undefined) { + engine = engine.autoSeed(); + } else if (Number.isInteger(seed)) { + engine = engine.seed(seed); + } else { + throw new RangeError("Expected seed must be undefined or integer not ".concat(seed)); + } -"use strict"; + var Xr = new Array(trainingSet.rows); + var yr = new Array(trainingSet.rows); + for (var i = 0; i < trainingSet.rows; ++i) { + var index = distribution(engine); + Xr[i] = trainingSet[index]; + yr[i] = trainingValue[index]; + } -module.exports = function divergence(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += (a[i] - b[i]) * (a[i] - b[i]) / ((a[i] + b[i]) * (a[i] + b[i])); - } - return 2 * d; -}; + return { + X: new ml_matrix_src["default"](Xr), + y: yr + }; +} +/** + * selects n features from the training set with or without replacement, returns the new training set and the indexes used. + * @ignore + * @param {Matrix} trainingSet + * @param {number} n - features. + * @param {boolean} replacement + * @param {number} seed - seed for the random selection, must be a 32-bit integer. + * @return {object} + */ -/***/ }), -/* 146 */ -/***/ (function(module, exports, __webpack_require__) { +function featureBagging(trainingSet, n, replacement, seed) { + if (trainingSet.columns < n) { + throw new RangeError('N should be less or equal to the number of columns of X'); + } -"use strict"; + var distribution = random_default.a.integer(0, trainingSet.columns - 1); + var engine = random_default.a.engines.mt19937(); + if (seed === undefined) { + engine = engine.autoSeed(); + } else if (Number.isInteger(seed)) { + engine = engine.seed(seed); + } else { + throw new RangeError("Expected seed must be undefined or integer not ".concat(seed)); + } -module.exports = function fidelity(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += Math.sqrt(a[i] * b[i]); - } - return ans; -}; + var toRet = new ml_matrix_src["default"](trainingSet.rows, n); -/***/ }), -/* 147 */ -/***/ (function(module, exports, __webpack_require__) { + if (replacement) { + var usedIndex = new Array(n); -"use strict"; + for (var i = 0; i < n; ++i) { + var index = distribution(engine); + usedIndex[i] = index; + toRet.setColumn(i, trainingSet.getColumn(index)); + } + } else { + usedIndex = new Set(); + index = distribution(engine); + for (i = 0; i < n; ++i) { + while (usedIndex.has(index)) { + index = distribution(engine); + } -module.exports = function gower(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += Math.abs(a[i] - b[i]); + toRet.setColumn(i, trainingSet.getColumn(index)); + usedIndex.add(index); } - return ans / ii; -}; -/***/ }), -/* 148 */ -/***/ (function(module, exports, __webpack_require__) { + usedIndex = Array.from(usedIndex); + } -"use strict"; + return { + X: toRet, + usedIndex: usedIndex + }; +} +// CONCATENATED MODULE: ./node_modules/ml-random-forest/src/RandomForestBase.js -module.exports = function harmonicMean(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += a[i] * b[i] / (a[i] + b[i]); + +/** + * @class RandomForestBase + */ + +class RandomForestBase_RandomForestBase { + /** + * Create a new base random forest for a classifier or regression model. + * @constructor + * @param {object} options + * @param {number|String} [options.maxFeatures] - the number of features used on each estimator. + * * if is an integer it selects maxFeatures elements over the sample features. + * * if is a float between (0, 1), it takes the percentage of features. + * @param {boolean} [options.replacement] - use replacement over the sample features. + * @param {number} [options.seed] - seed for feature and samples selection, must be a 32-bit integer. + * @param {number} [options.nEstimators] - number of estimator to use. + * @param {object} [options.treeOptions] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/} + * @param {boolean} [options.isClassifier] - boolean to check if is a classifier or regression model (used by subclasses). + * @param {boolean} [options.useSampleBagging] - use bagging over training samples. + * @param {object} model - for load purposes. + */ + constructor(options, model) { + if (options === true) { + this.replacement = model.replacement; + this.maxFeatures = model.maxFeatures; + this.nEstimators = model.nEstimators; + this.treeOptions = model.treeOptions; + this.isClassifier = model.isClassifier; + this.seed = model.seed; + this.n = model.n; + this.indexes = model.indexes; + this.useSampleBagging = model.useSampleBagging; + var Estimator = this.isClassifier ? src["DecisionTreeClassifier"] : src["DecisionTreeRegression"]; + this.estimators = model.estimators.map(est => Estimator.load(est)); + } else { + this.replacement = options.replacement; + this.maxFeatures = options.maxFeatures; + this.nEstimators = options.nEstimators; + this.treeOptions = options.treeOptions; + this.isClassifier = options.isClassifier; + this.seed = options.seed; + this.useSampleBagging = options.useSampleBagging; } - return 2 * ans; -}; + } + /** + * Train the decision tree with the given training set and labels. + * @param {Matrix|Array} trainingSet + * @param {Array} trainingValues + */ -/***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + train(trainingSet, trainingValues) { + trainingSet = ml_matrix_src["Matrix"].checkMatrix(trainingSet); + this.maxFeatures = this.maxFeatures || trainingSet.columns; + if (checkFloat(this.maxFeatures)) { + this.n = Math.floor(trainingSet.columns * this.maxFeatures); + } else if (Number.isInteger(this.maxFeatures)) { + if (this.maxFeatures > trainingSet.columns) { + throw new RangeError("The maxFeatures parameter should be less than ".concat(trainingSet.columns)); + } else { + this.n = this.maxFeatures; + } + } else { + throw new RangeError("Cannot process the maxFeatures parameter ".concat(this.maxFeatures)); + } -module.exports = function hellinger(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += Math.sqrt(a[i] * b[i]); + if (this.isClassifier) { + var Estimator = src["DecisionTreeClassifier"]; + } else { + Estimator = src["DecisionTreeRegression"]; } - return 2 * Math.sqrt(1 - ans); -}; -/***/ }), -/* 150 */ -/***/ (function(module, exports, __webpack_require__) { + this.estimators = new Array(this.nEstimators); + this.indexes = new Array(this.nEstimators); -"use strict"; + for (var i = 0; i < this.nEstimators; ++i) { + var res = this.useSampleBagging ? examplesBaggingWithReplacement(trainingSet, trainingValues, this.seed) : { + X: trainingSet, + y: trainingValues + }; + var X = res.X; + var y = res.y; + res = featureBagging(X, this.n, this.replacement, this.seed); + X = res.X; + this.indexes[i] = res.usedIndex; + this.estimators[i] = new Estimator(this.treeOptions); + this.estimators[i].train(X, y); + } + } + /** + * Method that returns the way the algorithm generates the predictions, for example, in classification + * you can return the mode of all predictions retrieved by the trees, or in case of regression you can + * use the mean or the median. + * @abstract + * @param {Array} values - predictions of the estimators. + * @return {number} prediction. + */ + // eslint-disable-next-line no-unused-vars -module.exports = function innerProduct(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += a[i] * b[i]; - } - return ans; -}; + selection(values) { + throw new Error('Abstract method \'selection\' not implemented!'); + } + /** + * Predicts the output given the matrix to predict. + * @param {Matrix|Array} toPredict + * @return {Array} predictions + */ -/***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + predict(toPredict) { + var predictionValues = new Array(this.nEstimators); + toPredict = ml_matrix_src["Matrix"].checkMatrix(toPredict); + for (var i = 0; i < this.nEstimators; ++i) { + var X = toPredict.columnSelectionView(this.indexes[i]); // get features for estimator -module.exports = function jeffreys(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += (a[i] - b[i]) * Math.log(a[i] / b[i]); + predictionValues[i] = this.estimators[i].predict(X); } - return ans; -}; - -/***/ }), -/* 152 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + predictionValues = new ml_matrix_src["WrapperMatrix2D"](predictionValues).transposeView(); + var predictions = new Array(predictionValues.rows); -module.exports = function jensenDifference(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += (a[i] * Math.log(a[i]) + b[i] * Math.log(b[i])) / 2 - (a[i] + b[i]) / 2 * Math.log((a[i] + b[i]) / 2); + for (i = 0; i < predictionValues.rows; ++i) { + predictions[i] = this.selection(predictionValues.getRow(i)); } - return ans; -}; -/***/ }), -/* 153 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -module.exports = function jensenShannon(a, b) { - var ii = a.length, - p = 0, - q = 0; - for (var i = 0; i < ii; i++) { - p += a[i] * Math.log(2 * a[i] / (a[i] + b[i])); - q += b[i] * Math.log(2 * b[i] / (a[i] + b[i])); - } - return (p + q) / 2; -}; + return predictions; + } + /** + * Export the current model to JSON. + * @return {object} - Current model. + */ -/***/ }), -/* 154 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + toJSON() { + return { + indexes: this.indexes, + n: this.n, + replacement: this.replacement, + maxFeatures: this.maxFeatures, + nEstimators: this.nEstimators, + treeOptions: this.treeOptions, + isClassifier: this.isClassifier, + seed: this.seed, + estimators: this.estimators.map(est => est.toJSON()), + useSampleBagging: this.useSampleBagging + }; + } +} +// CONCATENATED MODULE: ./node_modules/ml-random-forest/src/RandomForestClassifier.js -module.exports = function kdivergence(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])); - } - return ans; +const defaultOptions = { + maxFeatures: 1.0, + replacement: true, + nEstimators: 10, + seed: 42, + useSampleBagging: false }; +/** + * @class RandomForestClassifier + * @augments RandomForestBase + */ -/***/ }), -/* 155 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +class RandomForestClassifier_RandomForestClassifier extends RandomForestBase_RandomForestBase { + /** + * Create a new base random forest for a classifier or regression model. + * @constructor + * @param {object} options + * @param {number} [options.maxFeatures=1.0] - the number of features used on each estimator. + * * if is an integer it selects maxFeatures elements over the sample features. + * * if is a float between (0, 1), it takes the percentage of features. + * @param {boolean} [options.replacement=true] - use replacement over the sample features. + * @param {number} [options.seed=42] - seed for feature and samples selection, must be a 32-bit integer. + * @param {number} [options.nEstimators=10] - number of estimator to use. + * @param {object} [options.treeOptions={}] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/} + * @param {boolean} [options.useSampleBagging=false] - use bagging over training samples. + * @param {object} model - for load purposes. + */ + constructor(options, model) { + if (options === true) { + super(true, model.baseModel); + } else { + options = Object.assign({}, defaultOptions, options); + options.isClassifier = true; + super(options); + } + } + /** + * retrieve the prediction given the selection method. + * @param {Array} values - predictions of the estimators. + * @return {number} prediction + */ -module.exports = function kullbackLeibler(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += a[i] * Math.log(a[i] / b[i]); - } - return ans; -}; + selection(values) { + return mode(values); + } + /** + * Export the current model to JSON. + * @return {object} - Current model. + */ -/***/ }), -/* 156 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + toJSON() { + var baseModel = super.toJSON(); + return { + baseModel: baseModel, + name: 'RFClassifier' + }; + } + /** + * Load a Decision tree classifier with the given model. + * @param {object} model + * @return {RandomForestClassifier} + */ -module.exports = function kumarHassebrook(a, b) { - var ii = a.length, - p = 0, - p2 = 0, - q2 = 0; - for (var i = 0; i < ii; i++) { - p += a[i] * b[i]; - p2 += a[i] * a[i]; - q2 += b[i] * b[i]; + static load(model) { + if (model.name !== 'RFClassifier') { + throw new RangeError("Invalid model: ".concat(model.name)); } - return p / (p2 + q2 - p); -}; -/***/ }), -/* 157 */ -/***/ (function(module, exports, __webpack_require__) { + return new RandomForestClassifier_RandomForestClassifier(true, model); + } -"use strict"; +} +/** + * Return the most repeated element on the array. + * @param {Array} arr + * @return {number} mode + */ +function mode(arr) { + return arr.sort((a, b) => arr.filter(v => v === a).length - arr.filter(v => v === b).length).pop(); +} +// EXTERNAL MODULE: ./node_modules/ml-array-mean/lib-es6/index.js +var lib_es6 = __webpack_require__(5); -module.exports = function kumarJohnson(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += Math.pow(a[i] * a[i] - b[i] * b[i], 2) / (2 * Math.pow(a[i] * b[i], 1.5)); - } - return ans; -}; +// EXTERNAL MODULE: ./node_modules/ml-array-median/lib-es6/index.js +var ml_array_median_lib_es6 = __webpack_require__(18); -/***/ }), -/* 158 */ -/***/ (function(module, exports, __webpack_require__) { +// CONCATENATED MODULE: ./node_modules/ml-random-forest/src/RandomForestRegression.js -"use strict"; -module.exports = function lorentzian(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += Math.log(Math.abs(a[i] - b[i]) + 1); - } - return ans; +const selectionMethods = { + mean: lib_es6["default"], + median: ml_array_median_lib_es6["default"] }; +const RandomForestRegression_defaultOptions = { + maxFeatures: 1.0, + replacement: false, + nEstimators: 10, + treeOptions: {}, + selectionMethod: 'mean', + seed: 42, + useSampleBagging: false +}; +/** + * @class RandomForestRegression + * @augments RandomForestBase + */ -/***/ }), -/* 159 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +class RandomForestRegression_RandomForestRegression extends RandomForestBase_RandomForestBase { + /** + * Create a new base random forest for a classifier or regression model. + * @constructor + * @param {object} options + * @param {number} [options.maxFeatures=1.0] - the number of features used on each estimator. + * * if is an integer it selects maxFeatures elements over the sample features. + * * if is a float between (0, 1), it takes the percentage of features. + * @param {boolean} [options.replacement=true] - use replacement over the sample features. + * @param {number} [options.seed=42] - seed for feature and samples selection, must be a 32-bit integer. + * @param {number} [options.nEstimators=10] - number of estimator to use. + * @param {object} [options.treeOptions={}] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/} + * @param {string} [options.selectionMethod="mean"] - the way to calculate the prediction from estimators, "mean" and "median" are supported. + * @param {boolean} [options.useSampleBagging=false] - use bagging over training samples. + * @param {object} model - for load purposes. + */ + constructor(options, model) { + if (options === true) { + super(true, model.baseModel); + this.selectionMethod = model.selectionMethod; + } else { + options = Object.assign({}, RandomForestRegression_defaultOptions, options); + if (!(options.selectionMethod === 'mean' || options.selectionMethod === 'median')) { + throw new RangeError("Unsupported selection method ".concat(options.selectionMethod)); + } -module.exports = function manhattan(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += Math.abs(a[i] - b[i]); + options.isClassifier = false; + super(options); + this.selectionMethod = options.selectionMethod; } - return d; -}; - -/***/ }), -/* 160 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + } + /** + * retrieve the prediction given the selection method. + * @param {Array} values - predictions of the estimators. + * @return {number} prediction + */ -module.exports = function matusita(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += Math.sqrt(a[i] * b[i]); - } - return Math.sqrt(2 - 2 * ans); -}; + selection(values) { + return selectionMethods[this.selectionMethod](values); + } + /** + * Export the current model to JSON. + * @return {object} - Current model. + */ -/***/ }), -/* 161 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + toJSON() { + var baseModel = super.toJSON(); + return { + baseModel: baseModel, + selectionMethod: this.selectionMethod, + name: 'RFRegression' + }; + } + /** + * Load a Decision tree classifier with the given model. + * @param {object} model + * @return {RandomForestRegression} + */ -module.exports = function minkowski(a, b, p) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += Math.pow(Math.abs(a[i] - b[i]), p); + static load(model) { + if (model.name !== 'RFRegression') { + throw new RangeError("Invalid model: ".concat(model.name)); } - return Math.pow(d, 1 / p); -}; -/***/ }), -/* 162 */ -/***/ (function(module, exports, __webpack_require__) { + return new RandomForestRegression_RandomForestRegression(true, model); + } -"use strict"; +} +// CONCATENATED MODULE: ./node_modules/ml-random-forest/src/index.js +/* concated harmony reexport RandomForestClassifier */__webpack_require__.d(__webpack_exports__, "RandomForestClassifier", function() { return RandomForestClassifier_RandomForestClassifier; }); +/* concated harmony reexport RandomForestRegression */__webpack_require__.d(__webpack_exports__, "RandomForestRegression", function() { return RandomForestRegression_RandomForestRegression; }); -module.exports = function neyman(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += (a[i] - b[i]) * (a[i] - b[i]) / a[i]; - } - return d; -}; /***/ }), -/* 163 */ -/***/ (function(module, exports, __webpack_require__) { +/* 142 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +__webpack_require__.r(__webpack_exports__); +// EXTERNAL MODULE: ./node_modules/ml-array-sequential-fill/lib-es6/index.js +var lib_es6 = __webpack_require__(20); -module.exports = function pearson(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += (a[i] - b[i]) * (a[i] - b[i]) / b[i]; - } - return d; -}; - -/***/ }), -/* 164 */ -/***/ (function(module, exports, __webpack_require__) { +// CONCATENATED MODULE: ./node_modules/ml-array-xy-equally-spaced/src/integral.js +/** + * Function that calculates the integral of the line between two + * x-coordinates, given the slope and intercept of the line. + * @param {number} x0 + * @param {number} x1 + * @param {number} slope + * @param {number} intercept + * @return {number} integral value. + */ +function integral(x0, x1, slope, intercept) { + return 0.5 * slope * x1 * x1 + intercept * x1 - (0.5 * slope * x0 * x0 + intercept * x0); +} +// CONCATENATED MODULE: ./node_modules/ml-array-xy-equally-spaced/src/equallySpacedSmooth.js -"use strict"; +/** + * function that retrieves the getEquallySpacedData with the variant "smooth" + * + * @param {Array} x + * @param {Array} y + * @param {number} from - Initial point + * @param {number} to - Final point + * @param {number} numberOfPoints + * @return {Array} - Array of y's equally spaced with the variant "smooth" + */ +function equallySpacedSmooth(x, y, from, to, numberOfPoints) { + var xLength = x.length; + var step = (to - from) / (numberOfPoints - 1); + var halfStep = step / 2; + var output = new Array(numberOfPoints); + var initialOriginalStep = x[1] - x[0]; + var lastOriginalStep = x[xLength - 1] - x[xLength - 2]; // Init main variables + + var min = from - halfStep; + var max = from + halfStep; + var previousX = Number.MIN_VALUE; + var previousY = 0; + var nextX = x[0] - initialOriginalStep; + var nextY = 0; + var currentValue = 0; + var slope = 0; + var intercept = 0; + var sumAtMin = 0; + var sumAtMax = 0; + var i = 0; // index of input + + var j = 0; // index of output + + function getSlope(x0, y0, x1, y1) { + return (y1 - y0) / (x1 - x0); + } -module.exports = function probabilisticSymmetric(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += (a[i] - b[i]) * (a[i] - b[i]) / (a[i] + b[i]); + main: while (true) { + if (previousX <= min && min <= nextX) { + add = integral(0, min - previousX, slope, previousY); + sumAtMin = currentValue + add; } - return 2 * d; -}; -/***/ }), -/* 165 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + while (nextX - max >= 0) { + // no overlap with original point, just consume current value + var add = integral(0, max - previousX, slope, previousY); + sumAtMax = currentValue + add; + output[j++] = (sumAtMax - sumAtMin) / step; + if (j === numberOfPoints) { + break main; + } -module.exports = function ruzicka(a, b) { - var ii = a.length, - up = 0, - down = 0; - for (var i = 0; i < ii; i++) { - up += Math.min(a[i], b[i]); - down += Math.max(a[i], b[i]); + min = max; + max += step; + sumAtMin = sumAtMax; } - return up / down; -}; - -/***/ }), -/* 166 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + currentValue += integral(previousX, nextX, slope, intercept); + previousX = nextX; + previousY = nextY; -module.exports = function soergel(a, b) { - var ii = a.length, - up = 0, - down = 0; - for (var i = 0; i < ii; i++) { - up += Math.abs(a[i] - b[i]); - down += Math.max(a[i], b[i]); + if (i < xLength) { + nextX = x[i]; + nextY = y[i]; + i++; + } else if (i === xLength) { + nextX += lastOriginalStep; + nextY = 0; } - return up / down; -}; -/***/ }), -/* 167 */ -/***/ (function(module, exports, __webpack_require__) { + slope = getSlope(previousX, previousY, nextX, nextY); + intercept = -slope * previousX + previousY; + } -"use strict"; + return output; +} +// CONCATENATED MODULE: ./node_modules/ml-array-xy-equally-spaced/src/equallySpacedSlot.js +/** + * function that retrieves the getEquallySpacedData with the variant "slot" + * + * @param {Array} x + * @param {Array} y + * @param {number} from - Initial point + * @param {number} to - Final point + * @param {number} numberOfPoints + * @return {Array} - Array of y's equally spaced with the variant "slot" + */ +function equallySpacedSlot(x, y, from, to, numberOfPoints) { + var xLength = x.length; + var step = (to - from) / (numberOfPoints - 1); + var halfStep = step / 2; + var lastStep = x[x.length - 1] - x[x.length - 2]; + var start = from - halfStep; + var output = new Array(numberOfPoints); // Init main variables + + var min = start; + var max = start + step; + var previousX = -Number.MAX_VALUE; + var previousY = 0; + var nextX = x[0]; + var nextY = y[0]; + var frontOutsideSpectra = 0; + var backOutsideSpectra = true; + var currentValue = 0; // for slot algorithm + + var currentPoints = 0; + var i = 1; // index of input + + var j = 0; // index of output + + main: while (true) { + if (previousX >= nextX) throw new Error('x must be an increasing serie'); + + while (previousX - max > 0) { + // no overlap with original point, just consume current value + if (backOutsideSpectra) { + currentPoints++; + backOutsideSpectra = false; + } + output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints; + j++; -module.exports = function sorensen(a, b) { - var ii = a.length, - up = 0, - down = 0; - for (var i = 0; i < ii; i++) { - up += Math.abs(a[i] - b[i]); - down += a[i] + b[i]; + if (j === numberOfPoints) { + break main; + } + + min = max; + max += step; + currentValue = 0; + currentPoints = 0; } - return up / down; -}; -/***/ }), -/* 168 */ -/***/ (function(module, exports, __webpack_require__) { + if (previousX > min) { + currentValue += previousY; + currentPoints++; + } -"use strict"; + if (previousX === -Number.MAX_VALUE || frontOutsideSpectra > 1) { + currentPoints--; + } + previousX = nextX; + previousY = nextY; -module.exports = function squared(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += (a[i] - b[i]) * (a[i] - b[i]) / (a[i] + b[i]); + if (i < xLength) { + nextX = x[i]; + nextY = y[i]; + i++; + } else { + nextX += lastStep; + nextY = 0; + frontOutsideSpectra++; } - return d; -}; + } -/***/ }), -/* 169 */ -/***/ (function(module, exports, __webpack_require__) { + return output; +} +// CONCATENATED MODULE: ./node_modules/ml-array-xy-equally-spaced/src/getZones.js +function getZones(from, to, numberOfPoints) { + let exclusions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; -"use strict"; + if (from > to) { + [from, to] = [to, from]; + } // in exclusions from and to have to be defined -module.exports = function taneja(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += (a[i] + b[i]) / 2 * Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i]))); - } - return ans; -}; + exclusions = exclusions.filter(exclusion => exclusion.from !== undefined && exclusion.to !== undefined); + exclusions = JSON.parse(JSON.stringify(exclusions)); // we ensure that from before to -/***/ }), -/* 170 */ -/***/ (function(module, exports, __webpack_require__) { + exclusions.forEach(exclusion => { + if (exclusion.from > exclusion.to) { + [exclusion.to, exclusion.from] = [exclusion.from, exclusion.to]; + } + }); + exclusions.sort((a, b) => a.from - b.from); // we will rework the exclusions in order to remove overlap and outside range (from / to) -"use strict"; + exclusions.forEach(exclusion => { + if (exclusion.from < from) exclusion.from = from; + if (exclusion.to > to) exclusion.to = to; + }); + for (let i = 0; i < exclusions.length - 1; i++) { + if (exclusions[i].to > exclusions[i + 1].from) { + exclusions[i].to = exclusions[i + 1].from; + } + } -var tanimotoS = __webpack_require__(53); + exclusions = exclusions.filter(exclusion => exclusion.from < exclusion.to); -module.exports = function tanimoto(a, b, bitvector) { - if (bitvector) return 1 - tanimotoS(a, b, bitvector);else { - var ii = a.length, - p = 0, - q = 0, - m = 0; - for (var i = 0; i < ii; i++) { - p += a[i]; - q += b[i]; - m += Math.min(a[i], b[i]); - } - return (p + q - 2 * m) / (p + q - m); - } -}; + if (!exclusions || exclusions.length === 0) { + return [{ + from, + to, + numberOfPoints + }]; + } // need to deal with overlapping exclusions and out of bound exclusions -/***/ }), -/* 171 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + let toRemove = exclusions.reduce((previous, exclusion) => previous += exclusion.to - exclusion.from, 0); + let total = to - from; + let unitsPerPoint = (total - toRemove) / numberOfPoints; + let zones = []; + let currentFrom = from; + let totalPoints = 0; + for (let exclusion of exclusions) { + let currentNbPoints = Math.round((exclusion.from - currentFrom) / unitsPerPoint); + totalPoints += currentNbPoints; -module.exports = function topsoe(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])) + b[i] * Math.log(2 * b[i] / (a[i] + b[i])); + if (currentNbPoints > 0) { + zones.push({ + from: currentFrom, + to: exclusion.from, + numberOfPoints: currentNbPoints + }); } - return ans; -}; -/***/ }), -/* 172 */ -/***/ (function(module, exports, __webpack_require__) { + currentFrom = exclusion.to; + } -"use strict"; + if (numberOfPoints - totalPoints > 0) { + zones.push({ + from: currentFrom, + to: to, + numberOfPoints: numberOfPoints - totalPoints + }); + } + return zones; +} +// CONCATENATED MODULE: ./node_modules/ml-array-xy-equally-spaced/src/index.js +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return equallySpaced; }); -/** - * Function that creates the tree - * @param {Array } X - chemical shifts of the signal - * @param {Array } Y - intensity of the signal - * @param {number} from - the low limit of x - * @param {number} to - the top limit of x - * @param {number} minWindow - smallest range to accept in x - * @param {number} threshold - smallest range to accept in y - * @returns {{sum: number, center: number, left: {json}, right: {json}}} - * left and right have the same structure than the parent, or have a - * undefined value if are leafs - */ -function createTree(X, Y, from, to, minWindow, threshold) { - minWindow = minWindow || 0.16; - threshold = threshold || 0.01; - if (to - from < minWindow) return undefined; - var sum = 0; - for (var i = 0; X[i] < to; i++) { - if (X[i] > from) sum += Y[i]; - } - if (sum < threshold) { - return undefined; - } - var center = 0; - for (var j = 0; X[j] < to; j++) { - if (X[i] > from) center += X[j] * Y[j]; - } - center = center / sum; - if (center - from < 10e-6 || to - center < 10e-6) return undefined; - if (center - from < minWindow / 4) { - return createTree(X, Y, center, to, minWindow, threshold); - } else { - if (to - center < minWindow / 4) { - return createTree(X, Y, from, center, minWindow, threshold); - } else { - return { - 'sum': sum, - 'center': center, - 'left': createTree(X, Y, from, center, minWindow, threshold), - 'right': createTree(X, Y, center, to, minWindow, threshold) - }; - } - } -} -/** - * Similarity between two nodes - * @param {{sum: number, center: number, left: {json}, right: {json}}} a - tree A node - * @param {{sum: number, center: number, left: {json}, right: {json}}} b - tree B node - * @param {number} alpha - weights the relative importance of intensity vs. shift match - * @param {number} beta - weights the relative importance of node matching and children matching - * @param {number} gamma - controls the attenuation of the effect of chemical shift differences - * @returns {number} similarity measure between tree nodes - */ -function S(a, b, alpha, beta, gamma) { - if (a === undefined || b === undefined) { - return 0; - } else { - var C = alpha * Math.min(a.sum, b.sum) / Math.max(a.sum, b.sum) + (1 - alpha) * Math.exp(-gamma * Math.abs(a.center - b.center)); - } - return beta * C + (1 - beta) * (S(a.left, b.left, alpha, beta, gamma) + S(a.right, b.right, alpha, beta, gamma)); -} /** - * @type {number} alpha - weights the relative importance of intensity vs. shift match - * @type {number} beta - weights the relative importance of node matching and children matching - * @type {number} gamma - controls the attenuation of the effect of chemical shift differences - * @type {number} minWindow - smallest range to accept in x - * @type {number} threshold - smallest range to accept in y + * Function that returns a Number array of equally spaced numberOfPoints + * containing a representation of intensities of the spectra arguments x + * and y. + * + * The options parameter contains an object in the following form: + * from: starting point + * to: last point + * numberOfPoints: number of points between from and to + * variant: "slot" or "smooth" - smooth is the default option + * + * The slot variant consist that each point in the new array is calculated + * averaging the existing points between the slot that belongs to the current + * value. The smooth variant is the same but takes the integral of the range + * of the slot and divide by the step size between two points in the new array. + * + * @param {object} [arrayXY={}] - object containing 2 properties x and y (both an array) + * @param {object} [options={}] + * @param {number} [options.from=x[0]] + * @param {number} [options.to=x[x.length-1]] + * @param {string} [options.variant='smooth'] + * @param {number} [options.numberOfPoints=100] + * @param {Array} [options.exclusions=[]] array of from / to that should be skipped for the generation of the points + * @return {object} new object with x / y array with the equally spaced data. */ -var defaultOptions = { - minWindow: 0.16, - threshold: 0.01, - alpha: 0.1, - beta: 0.33, - gamma: 0.001 -}; -/** - * Builds a tree based in the spectra and compares this trees - * @param {{x: Array, y: Array}} A - first spectra to be compared - * @param {{x: Array, y: Array}} B - second spectra to be compared - * @param {number} from - the low limit of x - * @param {number} to - the top limit of x - * @param {{minWindow: number, threshold: number, alpha: number, beta: number, gamma: number}} options - * @returns {number} similarity measure between the spectra - */ -function tree(A, B, from, to, options) { - options = options || {}; - for (var o in defaultOptions) { - if (!options.hasOwnProperty(o)) { - options[o] = defaultOptions[o]; - } - }var Atree, Btree; - if (A.sum) Atree = A;else Atree = createTree(A.x, A.y, from, to, options.minWindow, options.threshold); - if (B.sum) Btree = B;else Btree = createTree(B.x, B.y, from, to, options.minWindow, options.threshold); - return S(Atree, Btree, options.alpha, options.beta, options.gamma); -} +function equallySpaced() { + let arrayXY = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + let { + x, + y + } = arrayXY; + let xLength = x.length; + let reverse = false; + + if (x.length > 1 && x[0] > x[1]) { + x = x.slice().reverse(); + y = y.slice().reverse(); + reverse = true; + } -module.exports = { - calc: tree, - createTree: createTree -}; + let { + from = x[0], + to = x[xLength - 1], + variant = 'smooth', + numberOfPoints = 100, + exclusions = [] + } = options; -/***/ }), -/* 173 */ -/***/ (function(module, exports, __webpack_require__) { + if (xLength !== y.length) { + throw new RangeError("the x and y vector doesn't have the same size."); + } -"use strict"; + if (typeof from !== 'number' || isNaN(from)) { + throw new RangeError("'from' option must be a number"); + } + if (typeof to !== 'number' || isNaN(to)) { + throw new RangeError("'to' option must be a number"); + } -module.exports = function waveHedges(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii; i++) { - ans += 1 - Math.min(a[i], b[i]) / Math.max(a[i], b[i]); - } - return ans; -}; + if (typeof numberOfPoints !== 'number' || isNaN(numberOfPoints)) { + throw new RangeError("'numberOfPoints' option must be a number"); + } -/***/ }), -/* 174 */ -/***/ (function(module, exports, __webpack_require__) { + let zones = getZones(from, to, numberOfPoints, exclusions); + let xResult = []; + let yResult = []; -"use strict"; + for (let zone of zones) { + let zoneResult = processZone(x, y, zone.from, zone.to, zone.numberOfPoints, variant, reverse); + xResult.push(...zoneResult.x); + yResult.push(...zoneResult.y); + } + + if (reverse) { + if (from < to) { + return { + x: xResult.reverse(), + y: yResult.reverse() + }; + } else { + return { + x: xResult, + y: yResult + }; + } + } else { + if (from < to) { + return { + x: xResult, + y: yResult + }; + } else { + return { + x: xResult.reverse(), + y: yResult.reverse() + }; + } + } +} +function processZone(x, y, from, to, numberOfPoints, variant) { + if (numberOfPoints < 1) { + throw new RangeError('the number of points must be at least 1'); + } -exports.cosine = __webpack_require__(54); -exports.czekanowski = __webpack_require__(46); -exports.dice = __webpack_require__(175); -exports.intersection = __webpack_require__(176); -exports.jaccard = __webpack_require__(177); -exports.kulczynski = __webpack_require__(178); -exports.motyka = __webpack_require__(179); -exports.pearson = __webpack_require__(180); -exports.squaredChord = __webpack_require__(181); -exports.tanimoto = __webpack_require__(53); + var output = variant === 'slot' ? equallySpacedSlot(x, y, from, to, numberOfPoints) : equallySpacedSmooth(x, y, from, to, numberOfPoints); + return { + x: Object(lib_es6["default"])({ + from, + to, + size: numberOfPoints + }), + y: output + }; +} /***/ }), -/* 175 */ -/***/ (function(module, exports, __webpack_require__) { +/* 143 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +__webpack_require__.r(__webpack_exports__); +// EXTERNAL MODULE: ./node_modules/ml-matrix/src/index.js + 24 modules +var src = __webpack_require__(0); -var diceD = __webpack_require__(47); - -module.exports = function dice(a, b) { - return 1 - diceD(a, b); -}; +// EXTERNAL MODULE: ./node_modules/ml-stat/index.js +var ml_stat = __webpack_require__(3); +var ml_stat_default = /*#__PURE__*/__webpack_require__.n(ml_stat); -/***/ }), -/* 176 */ -/***/ (function(module, exports, __webpack_require__) { +// CONCATENATED MODULE: ./node_modules/ml-naivebayes/src/utils.js -"use strict"; +/** + * @private + * Function that retuns an array of matrices of the cases that belong to each class. + * @param {Matrix} X - dataset + * @param {Array} y - predictions + * @return {Array} + */ +function separateClasses(X, y) { + var features = X.columns; + var classes = 0; + var totalPerClasses = new Array(10000); // max upperbound of classes -var intersectionD = __webpack_require__(48); + for (var i = 0; i < y.length; i++) { + if (totalPerClasses[y[i]] === undefined) { + totalPerClasses[y[i]] = 0; + classes++; + } -module.exports = function intersection(a, b) { - return 1 - intersectionD(a, b); -}; + totalPerClasses[y[i]]++; + } -/***/ }), -/* 177 */ -/***/ (function(module, exports, __webpack_require__) { + var separatedClasses = new Array(classes); + var currentIndex = new Array(classes); -"use strict"; + for (i = 0; i < classes; ++i) { + separatedClasses[i] = new src["default"](totalPerClasses[i], features); + currentIndex[i] = 0; + } + for (i = 0; i < X.rows; ++i) { + separatedClasses[y[i]].setRow(currentIndex[y[i]], X.getRow(i)); + currentIndex[y[i]]++; + } -var jaccardD = __webpack_require__(49); + return separatedClasses; +} +// CONCATENATED MODULE: ./node_modules/ml-naivebayes/src/GaussianNB.js -module.exports = function jaccard(a, b) { - return 1 - jaccardD(a, b); -}; -/***/ }), -/* 178 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +/** + * @class GaussianNB + */ +class GaussianNB_GaussianNB { + /** + * @constructor + * Constructor for the Gaussian Naive Bayes classifier, the parameters here is just for loading purposes. + * + * @param {boolean} reload + * @param {object} model + */ + constructor(reload, model) { + if (reload) { + this.means = model.means; + this.calculateProbabilities = model.calculateProbabilities; + } + } + /** + * Function that trains the classifier with a matrix that represents the training set and an array that + * represents the label of each row in the training set. the labels must be numbers between 0 to n-1 where + * n represents the number of classes. + * + * WARNING: in the case that one class, all the cases in one or more features have the same value, the + * Naive Bayes classifier will not work well. + * @param {Matrix|Array} trainingSet + * @param {Matrix|Array} trainingLabels + */ -var kulczynskiD = __webpack_require__(50); -module.exports = function kulczynski(a, b) { - return 1 / kulczynskiD(a, b); -}; + train(trainingSet, trainingLabels) { + var C1 = Math.sqrt(2 * Math.PI); // constant to precalculate the squared root -/***/ }), -/* 179 */ -/***/ (function(module, exports, __webpack_require__) { + trainingSet = src["default"].checkMatrix(trainingSet); //if (!Matrix.isMatrix(trainingSet)) trainingSet = new Matrix(trainingSet); -"use strict"; + if (trainingSet.rows !== trainingLabels.length) { + throw new RangeError('the size of the training set and the training labels must be the same.'); + } + var separatedClasses = separateClasses(trainingSet, trainingLabels); + var calculateProbabilities = new Array(separatedClasses.length); + this.means = new Array(separatedClasses.length); -var motykaD = __webpack_require__(51); + for (var i = 0; i < separatedClasses.length; ++i) { + var means = ml_stat_default.a.matrix.mean(separatedClasses[i]); + var std = ml_stat_default.a.matrix.standardDeviation(separatedClasses[i], means); + var logPriorProbability = Math.log(separatedClasses[i].rows / trainingSet.rows); + calculateProbabilities[i] = new Array(means.length + 1); + calculateProbabilities[i][0] = logPriorProbability; -module.exports = function motyka(a, b) { - return 1 - motykaD(a, b); -}; + for (var j = 1; j < means.length + 1; ++j) { + var currentStd = std[j - 1]; + calculateProbabilities[i][j] = [1 / (C1 * currentStd), -2 * currentStd * currentStd]; + } -/***/ }), -/* 180 */ -/***/ (function(module, exports, __webpack_require__) { + this.means[i] = means; + } -"use strict"; + this.calculateProbabilities = calculateProbabilities; + } + /** + * function that predicts each row of the dataset (must be a matrix). + * + * @param {Matrix|Array} dataset + * @return {Array} + */ -var stat = __webpack_require__(4).array; -var cosine = __webpack_require__(54); + predict(dataset) { + if (dataset[0].length === this.calculateProbabilities[0].length) { + throw new RangeError('the dataset must have the same features as the training set'); + } -module.exports = function pearson(a, b) { - var avgA = stat.mean(a); - var avgB = stat.mean(b); + var predictions = new Array(dataset.length); - var newA = new Array(a.length); - var newB = new Array(b.length); - for (var i = 0; i < newA.length; i++) { - newA[i] = a[i] - avgA; - newB[i] = b[i] - avgB; + for (var i = 0; i < predictions.length; ++i) { + predictions[i] = getCurrentClass(dataset[i], this.means, this.calculateProbabilities); } - return cosine(newA, newB); -}; + return predictions; + } + /** + * Function that export the NaiveBayes model. + * @return {object} + */ -/***/ }), -/* 181 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + toJSON() { + return { + modelName: 'NaiveBayes', + means: this.means, + calculateProbabilities: this.calculateProbabilities + }; + } + /** + * Function that create a GaussianNB classifier with the given model. + * @param {object} model + * @return {GaussianNB} + */ -var squaredChordD = __webpack_require__(52); + static load(model) { + if (model.modelName !== 'NaiveBayes') { + throw new RangeError('The current model is not a Multinomial Naive Bayes, current model:', model.name); + } -module.exports = function squaredChord(a, b) { - return 1 - squaredChordD(a, b); -}; + return new GaussianNB_GaussianNB(true, model); + } -/***/ }), -/* 182 */ -/***/ (function(module, exports, __webpack_require__) { +} +/** + * @private + * Function the retrieves a prediction with one case. + * + * @param {Array} currentCase + * @param {Array} mean - Precalculated means of each class trained + * @param {Array} classes - Precalculated value of each class (Prior probability and probability function of each feature) + * @return {number} + */ -"use strict"; +function getCurrentClass(currentCase, mean, classes) { + var maxProbability = 0; + var predictedClass = -1; // going through all precalculated values for the classes + for (var i = 0; i < classes.length; ++i) { + var currentProbability = classes[i][0]; // initialize with the prior probability -var measures = __webpack_require__(183); + for (var j = 1; j < classes[0][1].length + 1; ++j) { + currentProbability += calculateLogProbability(currentCase[j - 1], mean[i][j - 1], classes[i][j][0], classes[i][j][1]); + } -class Performance { - /** - * - * @param prediction - The prediction matrix - * @param target - The target matrix (values: truthy for same class, falsy for different class) - * @param options - * - * @option all True if the entire matrix must be used. False to ignore the diagonal and lower part (default is false, for similarity/distance matrices) - * @option max True if the max value corresponds to a perfect match (like in similarity matrices), false if it is the min value (default is false, like in distance matrices. All values will be multiplied by -1) - */ - constructor(prediction, target, options) { - options = options || {}; - if (prediction.length !== target.length || prediction[0].length !== target[0].length) { - throw new Error('dimensions of prediction and target do not match'); - } - var rows = prediction.length; - var columns = prediction[0].length; - var isDistance = !options.max; - - var predP = []; - - if (options.all) { - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - predP.push({ - pred: prediction[i][j], - targ: target[i][j] - }); - } - } - } else { - if (rows < 3 || rows !== columns) { - throw new Error('When "all" option is false, the prediction matrix must be square and have at least 3 columns'); - } - for (var i = 0; i < rows - 1; i++) { - for (var j = i + 1; j < columns; j++) { - predP.push({ - pred: prediction[i][j], - targ: target[i][j] - }); - } - } - } + currentProbability = Math.exp(currentProbability); - if (isDistance) { - predP.sort((a, b) => a.pred - b.pred); - } else { - predP.sort((a, b) => b.pred - a.pred); - } + if (currentProbability > maxProbability) { + maxProbability = currentProbability; + predictedClass = i; + } + } - var cutoffs = this.cutoffs = [isDistance ? Number.MIN_VALUE : Number.MAX_VALUE]; - var fp = this.fp = [0]; - var tp = this.tp = [0]; - - var nPos = 0; - var nNeg = 0; - - var currentPred = predP[0].pred; - var nTp = 0; - var nFp = 0; - for (var i = 0; i < predP.length; i++) { - if (predP[i].pred !== currentPred) { - cutoffs.push(currentPred); - fp.push(nFp); - tp.push(nTp); - currentPred = predP[i].pred; - } - if (predP[i].targ) { - nPos++; - nTp++; - } else { - nNeg++; - nFp++; - } - } - cutoffs.push(currentPred); - fp.push(nFp); - tp.push(nTp); + return predictedClass; +} +/** + * @private + * function that retrieves the probability of the feature given the class. + * @param {number} value - value of the feature. + * @param {number} mean - mean of the feature for the given class. + * @param {number} C1 - precalculated value of (1 / (sqrt(2*pi) * std)). + * @param {number} C2 - precalculated value of (2 * std^2) for the denominator of the exponential. + * @return {number} + */ - var l = cutoffs.length; - var fn = this.fn = new Array(l); - var tn = this.tn = new Array(l); - var nPosPred = this.nPosPred = new Array(l); - var nNegPred = this.nNegPred = new Array(l); - for (var i = 0; i < l; i++) { - fn[i] = nPos - tp[i]; - tn[i] = nNeg - fp[i]; +function calculateLogProbability(value, mean, C1, C2) { + value = value - mean; + return Math.log(C1 * Math.exp(value * value / C2)); +} +// CONCATENATED MODULE: ./node_modules/ml-naivebayes/src/MultinomialNB.js - nPosPred[i] = tp[i] + fp[i]; - nNegPred[i] = tn[i] + fn[i]; - } - this.nPos = nPos; - this.nNeg = nNeg; - this.nSamples = nPos + nNeg; - } +/** + * @class MultinomialNB + */ - /** - * Computes a measure from the prediction object. - * - * Many measures are available and can be combined : - * To create a ROC curve, you need fpr and tpr - * To create a DET curve, you need fnr and fpr - * To create a Lift chart, you need rpp and lift - * - * Possible measures are : threshold (Threshold), acc (Accuracy), err (Error rate), - * fpr (False positive rate), tpr (True positive rate), fnr (False negative rate), tnr (True negative rate), ppv (Positive predictive value), - * npv (Negative predictive value), pcfall (Prediction-conditioned fallout), pcmiss (Prediction-conditioned miss), lift (Lift value), rpp (Rate of positive predictions), rnp (Rate of negative predictions) - * - * @param measure - The short name of the measure - * - * @return [number] - */ - getMeasure(measure) { - if (typeof measure !== 'string') { - throw new Error('No measure specified'); - } - if (!measures[measure]) { - throw new Error(`The specified measure (${measure}) does not exist`); - } - return measures[measure](this); +class MultinomialNB_MultinomialNB { + /** + * @constructor + * Constructor for Multinomial Naive Bayes, the model parameter is for load purposes. + * + * @param {object} model - for load purposes. + */ + constructor(model) { + if (model) { + this.conditionalProbability = src["default"].checkMatrix(model.conditionalProbability); + this.priorProbability = src["default"].checkMatrix(model.priorProbability); } + } + /** + * Train the classifier with the current training set and labels, the labels must be numbers between 0 and n. + * @param {Matrix|Array} trainingSet + * @param {Array} trainingLabels + */ - /** - * Returns the area under the ROC curve - */ - getAURC() { - var l = this.cutoffs.length; - var x = new Array(l); - var y = new Array(l); - for (var i = 0; i < l; i++) { - x[i] = this.fp[i] / this.nNeg; - y[i] = this.tp[i] / this.nPos; - } - var auc = 0; - for (i = 1; i < l; i++) { - auc += 0.5 * (x[i] - x[i - 1]) * (y[i] + y[i - 1]); - } - return auc; - } - /** - * Returns the area under the DET curve - */ - getAUDC() { - var l = this.cutoffs.length; - var x = new Array(l); - var y = new Array(l); - for (var i = 0; i < l; i++) { - x[i] = this.fn[i] / this.nPos; - y[i] = this.fp[i] / this.nNeg; - } - var auc = 0; - for (i = 1; i < l; i++) { - auc += 0.5 * (x[i] + x[i - 1]) * (y[i] - y[i - 1]); - } - return auc; + train(trainingSet, trainingLabels) { + trainingSet = src["default"].checkMatrix(trainingSet); + + if (trainingSet.rows !== trainingLabels.length) { + throw new RangeError('the size of the training set and the training labels must be the same.'); } - getDistribution(options) { - options = options || {}; - var cutLength = this.cutoffs.length; - var cutLow = options.xMin || Math.floor(this.cutoffs[cutLength - 1] * 100) / 100; - var cutHigh = options.xMax || Math.ceil(this.cutoffs[1] * 100) / 100; - var interval = options.interval || Math.floor((cutHigh - cutLow) / 20 * 10000000 - 1) / 10000000; // Trick to avoid the precision problem of float numbers + var separateClass = separateClasses(trainingSet, trainingLabels); + this.priorProbability = new src["default"](separateClass.length, 1); - var xLabels = []; - var interValues = []; - var intraValues = []; - var interCumPercent = []; - var intraCumPercent = []; + for (var i = 0; i < separateClass.length; ++i) { + this.priorProbability[i][0] = Math.log(separateClass[i].length / trainingSet.rows); + } - var nTP = this.tp[cutLength - 1], - currentTP = 0; - var nFP = this.fp[cutLength - 1], - currentFP = 0; + var features = trainingSet.columns; + this.conditionalProbability = new src["default"](separateClass.length, features); - for (var i = cutLow, j = cutLength - 1; i <= cutHigh; i += interval) { - while (this.cutoffs[j] < i) { - j--; - }xLabels.push(i); + for (i = 0; i < separateClass.length; ++i) { + var classValues = src["default"].checkMatrix(separateClass[i]); + var total = classValues.sum(); + var divisor = total + features; + this.conditionalProbability.setRow(i, classValues.sum('column').add(1).div(divisor).apply(matrixLog)); + } + } + /** + * Retrieves the predictions for the dataset with the current model. + * @param {Matrix|Array} dataset + * @return {Array} - predictions from the dataset. + */ - var thisTP = nTP - currentTP - this.tp[j]; - var thisFP = nFP - currentFP - this.fp[j]; - currentTP += thisTP; - currentFP += thisFP; + predict(dataset) { + dataset = src["default"].checkMatrix(dataset); + var predictions = new Array(dataset.rows); - interValues.push(thisFP); - intraValues.push(thisTP); + for (var i = 0; i < dataset.rows; ++i) { + var currentElement = dataset.getRowVector(i); + predictions[i] = this.conditionalProbability.clone().mulRowVector(currentElement).sum('row').add(this.priorProbability).maxIndex()[0]; + } - interCumPercent.push(100 - (nFP - this.fp[j]) / nFP * 100); - intraCumPercent.push(100 - (nTP - this.tp[j]) / nTP * 100); - } + return predictions; + } + /** + * Function that saves the current model. + * @return {object} - model in JSON format. + */ - return { - xLabels: xLabels, - interValues: interValues, - intraValues: intraValues, - interCumPercent: interCumPercent, - intraCumPercent: intraCumPercent - }; - } -} -Performance.names = { - acc: 'Accuracy', - err: 'Error rate', - fpr: 'False positive rate', - tpr: 'True positive rate', - fnr: 'False negative rate', - tnr: 'True negative rate', - ppv: 'Positive predictive value', - npv: 'Negative predictive value', - pcfall: 'Prediction-conditioned fallout', - pcmiss: 'Prediction-conditioned miss', - lift: 'Lift value', - rpp: 'Rate of positive predictions', - rnp: 'Rate of negative predictions', - threshold: 'Threshold' -}; + toJSON() { + return { + name: 'MultinomialNB', + priorProbability: this.priorProbability, + conditionalProbability: this.conditionalProbability + }; + } + /** + * Creates a new MultinomialNB from the given model + * @param {object} model + * @return {MultinomialNB} + */ -module.exports = Performance; -/***/ }), -/* 183 */ -/***/ (function(module, exports, __webpack_require__) { + static load(model) { + if (model.name !== 'MultinomialNB') { + throw new RangeError("".concat(model.name, " is not a Multinomial Naive Bayes")); + } -"use strict"; + return new MultinomialNB_MultinomialNB(model); + } +} -// Accuracy +function matrixLog(i, j) { + this[i][j] = Math.log(this[i][j]); +} +// CONCATENATED MODULE: ./node_modules/ml-naivebayes/src/index.js +/* concated harmony reexport GaussianNB */__webpack_require__.d(__webpack_exports__, "GaussianNB", function() { return GaussianNB_GaussianNB; }); +/* concated harmony reexport MultinomialNB */__webpack_require__.d(__webpack_exports__, "MultinomialNB", function() { return MultinomialNB_MultinomialNB; }); -exports.acc = pred => { - var l = pred.cutoffs.length; - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = (pred.tn[i] + pred.tp[i]) / (l - 1); - } - return result; -}; -// Error rate -exports.err = pred => { - var l = pred.cutoffs.length; - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = pred.fn[i] + pred.fp[i] / (l - 1); - } - return result; -}; -// False positive rate -exports.fpr = pred => { - var l = pred.cutoffs.length; - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = pred.fp[i] / pred.nNeg; - } - return result; -}; +/***/ }), +/* 144 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -// True positive rate -exports.tpr = pred => { - var l = pred.cutoffs.length; - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = pred.tp[i] / pred.nPos; - } - return result; -}; +"use strict"; +__webpack_require__.r(__webpack_exports__); -// False negative rate -exports.fnr = pred => { - var l = pred.cutoffs.length; - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = pred.fn[i] / pred.nPos; - } - return result; -}; +// EXTERNAL MODULE: ./node_modules/ml-matrix/src/index.js + 24 modules +var src = __webpack_require__(0); -// True negative rate -exports.tnr = pred => { - var l = pred.cutoffs.length; - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = pred.tn[i] / pred.nNeg; - } - return result; -}; +// EXTERNAL MODULE: ./node_modules/ml-stat/matrix.js +var matrix = __webpack_require__(4); +var matrix_default = /*#__PURE__*/__webpack_require__.n(matrix); -// Positive predictive value -exports.ppv = pred => { - var l = pred.cutoffs.length; - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = pred.fp[i] + pred.tp[i] !== 0 ? pred.tp[i] / (pred.fp[i] + pred.tp[i]) : 0; - } - return result; -}; +// CONCATENATED MODULE: ./node_modules/ml-pls/src/utils.js -// Negative predictive value -exports.npv = pred => { - var l = pred.cutoffs.length; - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = pred.fn[i] + pred.tn[i] !== 0 ? pred.tn[i] / (pred.fn[i] + pred.tn[i]) : 0; - } - return result; -}; -// Prediction conditioned fallout -exports.pcfall = pred => { - var l = pred.cutoffs.length; - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = pred.fp[i] + pred.tp[i] !== 0 ? 1 - pred.tp[i] / (pred.fp[i] + pred.tp[i]) : 1; - } - return result; -}; +/** + * @private + * Function that given vector, returns his norm + * @param {Vector} X + * @return {number} Norm of the vector + */ -// Prediction conditioned miss -exports.pcmiss = pred => { - var l = pred.cutoffs.length; - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = pred.fn[i] + pred.tn[i] !== 0 ? 1 - pred.tn[i] / (pred.fn[i] + pred.tn[i]) : 1; - } - return result; -}; +function norm(X) { + return Math.sqrt(X.clone().apply(pow2array).sum()); +} +/** + * @private + * Function that pow 2 each element of a Matrix or a Vector, + * used in the apply method of the Matrix object + * @param {number} i - index i. + * @param {number} j - index j. + * @return {Matrix} The Matrix object modified at the index i, j. + * */ -// Lift value -exports.lift = pred => { - var l = pred.cutoffs.length; - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = pred.nPosPred[i] !== 0 ? pred.tp[i] / pred.nPos / (pred.nPosPred[i] / pred.nSamples) : 0; - } - return result; -}; +function pow2array(i, j) { + this[i][j] = this[i][j] * this[i][j]; + return this; +} +/** + * @private + * Function that normalize the dataset and return the means and + * standard deviation of each feature. + * @param {Matrix} dataset + * @return {object} dataset normalized, means and standard deviations + */ + +function featureNormalize(dataset) { + var means = matrix_default.a.mean(dataset); + var std = matrix_default.a.standardDeviation(dataset, means, true); + var result = src["default"].checkMatrix(dataset).subRowVector(means); + return { + result: result.divRowVector(std), + means: means, + std: std + }; +} +/** + * @private + * Function that initialize an array of matrices. + * @param {Array} array + * @param {boolean} isMatrix + * @return {Array} array with the matrices initialized. + */ -// Rate of positive predictions -exports.rpp = pred => { - var l = pred.cutoffs.length; - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = pred.nPosPred[i] / pred.nSamples; +function initializeMatrices(array, isMatrix) { + if (isMatrix) { + for (var i = 0; i < array.length; ++i) { + for (var j = 0; j < array[i].length; ++j) { + var elem = array[i][j]; + array[i][j] = elem !== null ? new src["default"](array[i][j]) : undefined; + } } - return result; -}; - -// Rate of negative predictions -exports.rnp = pred => { - var l = pred.cutoffs.length; - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = pred.nNegPred[i] / pred.nSamples; + } else { + for (i = 0; i < array.length; ++i) { + array[i] = new src["default"](array[i]); } - return result; -}; - -// Threshold -exports.threshold = pred => { - var clone = pred.cutoffs.slice(); - clone[0] = clone[1]; // Remove the infinite value - return clone; -}; - -/***/ }), -/* 184 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + } + return array; +} +// CONCATENATED MODULE: ./node_modules/ml-pls/src/pls.js -var matrixLib = __webpack_require__(0); -var Matrix = matrixLib.Matrix; -var inverse = matrixLib.inverse; -var padArray = __webpack_require__(55); -var extend = __webpack_require__(17); -var defaultOptions = { - windowSize: 5, - derivative: 1, - polynomial: 2, - pad: 'none', - padValue: 'replicate' -}; /** - * Savitzky-Golay filter - * @param {Array } data - * @param {number} h - * @param {Object} options - * @returns {Array} + * @class PLS */ -function SavitzkyGolay(data, h, options) { - options = extend({}, defaultOptions, options); - if (options.windowSize % 2 === 0 || options.windowSize < 5 || !Number.isInteger(options.windowSize)) throw new RangeError('Invalid window size (should be odd and at least 5 integer number)'); - if (options.derivative < 0 || !Number.isInteger(options.derivative)) throw new RangeError('Derivative should be a positive integer'); - if (options.polynomial < 1 || !Number.isInteger(options.polynomial)) throw new RangeError('Polynomial should be a positive integer'); - - var C, norm; - var step = Math.floor(options.windowSize / 2); - if (options.pad === 'pre') { - data = padArray(data, { size: step, value: options.padValue }); +class pls_PLS { + /** + * Constructor for Partial Least Squares (PLS) + * @param {object} options + * @param {number} [options.latentVectors] - Number of latent vector to get (if the algorithm doesn't find a good model below the tolerance) + * @param {number} [options.tolerance=1e-5] + * @param {boolean} [options.scale=true] - rescale dataset using mean. + * @param {object} model - for load purposes. + */ + constructor(options, model) { + if (options === true) { + this.meanX = model.meanX; + this.stdDevX = model.stdDevX; + this.meanY = model.meanY; + this.stdDevY = model.stdDevY; + this.PBQ = src["default"].checkMatrix(model.PBQ); + this.R2X = model.R2X; + this.scale = model.scale; + this.scaleMethod = model.scaleMethod; + this.tolerance = model.tolerance; + } else { + var { + tolerance = 1e-5, + scale = true + } = options; + this.tolerance = tolerance; + this.scale = scale; + this.latentVectors = options.latentVectors; } + } + /** + * Fits the model with the given data and predictions, in this function is calculated the + * following outputs: + * + * T - Score matrix of X + * P - Loading matrix of X + * U - Score matrix of Y + * Q - Loading matrix of Y + * B - Matrix of regression coefficient + * W - Weight matrix of X + * + * @param {Matrix|Array} trainingSet + * @param {Matrix|Array} trainingValues + */ - var ans = new Array(data.length - 2 * step); - if (options.windowSize === 5 && options.polynomial === 2 && (options.derivative === 1 || options.derivative === 2)) { - if (options.derivative === 1) { - C = [-2, -1, 0, 1, 2]; - norm = 10; - } else { - C = [2, -1, -2, -1, 2]; - norm = 7; - } - } else { - var J = Matrix.ones(options.windowSize, options.polynomial + 1); - var inic = -(options.windowSize - 1) / 2; - for (var i = 0; i < J.length; i++) { - for (var j = 0; j < J[i].length; j++) { - if (inic + 1 !== 0 || j !== 0) J[i][j] = Math.pow(inic + i, j); - } - } - var Jtranspose = J.transposeView(); - var Jinv = inverse(Jtranspose.mmul(J)); - C = Jinv.mmul(Jtranspose); - C = C[options.derivative]; - norm = 1; + train(trainingSet, trainingValues) { + trainingSet = src["default"].checkMatrix(trainingSet); + trainingValues = src["default"].checkMatrix(trainingValues); + + if (trainingSet.length !== trainingValues.length) { + throw new RangeError('The number of X rows must be equal to the number of Y rows'); } - var det = norm * Math.pow(h, options.derivative); - for (var k = step; k < data.length - step; k++) { - var d = 0; - for (var l = 0; l < C.length; l++) { - d += C[l] * data[l + k - step] / det; - }ans[k - step] = d; + + this.meanX = matrix_default.a.mean(trainingSet); + this.stdDevX = matrix_default.a.standardDeviation(trainingSet, this.meanX, true); + this.meanY = matrix_default.a.mean(trainingValues); + this.stdDevY = matrix_default.a.standardDeviation(trainingValues, this.meanY, true); + + if (this.scale) { + // here should be the ml-preprocess project + trainingSet = trainingSet.clone().subRowVector(this.meanX).divRowVector(this.stdDevX); + trainingValues = trainingValues.clone().subRowVector(this.meanY).divRowVector(this.stdDevY); } - if (options.pad === 'post') { - ans = padArray(ans, { size: step, value: options.padValue }); + if (this.latentVectors === undefined) { + this.latentVectors = Math.min(trainingSet.length - 1, trainingSet[0].length); } - return ans; -} + var rx = trainingSet.rows; + var cx = trainingSet.columns; + var ry = trainingValues.rows; + var cy = trainingValues.columns; + var ssqXcal = trainingSet.clone().mul(trainingSet).sum(); // for the r² -module.exports = SavitzkyGolay; + var sumOfSquaresY = trainingValues.clone().mul(trainingValues).sum(); + var tolerance = this.tolerance; + var n = this.latentVectors; + var T = src["default"].zeros(rx, n); + var P = src["default"].zeros(cx, n); + var U = src["default"].zeros(ry, n); + var Q = src["default"].zeros(cy, n); + var B = src["default"].zeros(n, n); + var W = P.clone(); + var k = 0; -/***/ }), -/* 185 */ -/***/ (function(module, exports, __webpack_require__) { + while (norm(trainingValues) > tolerance && k < n) { + var transposeX = trainingSet.transpose(); + var transposeY = trainingValues.transpose(); + var tIndex = maxSumColIndex(trainingSet.clone().mulM(trainingSet)); + var uIndex = maxSumColIndex(trainingValues.clone().mulM(trainingValues)); + var t1 = trainingSet.getColumnVector(tIndex); + var u = trainingValues.getColumnVector(uIndex); + var t = src["default"].zeros(rx, 1); + + while (norm(t1.clone().sub(t)) > tolerance) { + var w = transposeX.mmul(u); + w.div(norm(w)); + t = t1; + t1 = trainingSet.mmul(w); + var q = transposeY.mmul(t1); + q.div(norm(q)); + u = trainingValues.mmul(q); + } -"use strict"; + t = t1; + var num = transposeX.mmul(t); + var den = t.transpose().mmul(t)[0][0]; + var p = num.div(den); + var pnorm = norm(p); + p.div(pnorm); + t.mul(pnorm); + w.mul(pnorm); + num = u.transpose().mmul(t); + den = t.transpose().mmul(t)[0][0]; + var b = num.div(den)[0][0]; + trainingSet.sub(t.mmul(p.transpose())); + trainingValues.sub(t.clone().mul(b).mmul(q.transpose())); + T.setColumn(k, t); + P.setColumn(k, p); + U.setColumn(k, u); + Q.setColumn(k, q); + W.setColumn(k, w); + B[k][k] = b; + k++; + } + + k--; + T = T.subMatrix(0, T.rows - 1, 0, k); + P = P.subMatrix(0, P.rows - 1, 0, k); + U = U.subMatrix(0, U.rows - 1, 0, k); + Q = Q.subMatrix(0, Q.rows - 1, 0, k); + W = W.subMatrix(0, W.rows - 1, 0, k); + B = B.subMatrix(0, k, 0, k); // TODO: review of R2Y + //this.R2Y = t.transpose().mmul(t).mul(q[k][0]*q[k][0]).divS(ssqYcal)[0][0]; + // + + this.ssqYcal = sumOfSquaresY; + this.E = trainingSet; + this.F = trainingValues; + this.T = T; + this.P = P; + this.U = U; + this.Q = Q; + this.W = W; + this.B = B; + this.PBQ = P.mmul(B).mmul(Q.transpose()); + this.R2X = t.transpose().mmul(t).mmul(p.transpose().mmul(p)).div(ssqXcal)[0][0]; + } + /** + * Predicts the behavior of the given dataset. + * @param {Matrix|Array} dataset - data to be predicted. + * @return {Matrix} - predictions of each element of the dataset. + */ -//Code translate from Pascal source in http://pubs.acs.org/doi/pdf/10.1021/ac00205a007 -var extend = __webpack_require__(17); -var stat = __webpack_require__(4); + predict(dataset) { + var X = src["default"].checkMatrix(dataset); -var defaultOptions = { - windowSize: 9, - derivative: 0, - polynomial: 3 -}; + if (this.scale) { + X = X.subRowVector(this.meanX).divRowVector(this.stdDevX); + } -function SavitzkyGolay(data, h, options) { - options = extend({}, defaultOptions, options); + var Y = X.mmul(this.PBQ); + Y = Y.mulRowVector(this.stdDevY).addRowVector(this.meanY); + return Y; + } + /** + * Returns the explained variance on training of the PLS model + * @return {number} + */ - if (options.windowSize % 2 === 0 || options.windowSize < 5 || !Number.isInteger(options.windowSize)) throw new RangeError('Invalid window size (should be odd and at least 5 integer number)'); - if (options.windowSize > data.length) throw new RangeError('Window size is higher than the data length ' + options.windowSize + ">" + data.length); - if (options.derivative < 0 || !Number.isInteger(options.derivative)) throw new RangeError('Derivative should be a positive integer'); - if (options.polynomial < 1 || !Number.isInteger(options.polynomial)) throw new RangeError('Polynomial should be a positive integer'); - if (options.polynomial >= 6) console.warn('You should not use polynomial grade higher than 5 if you are' + ' not sure that your data arises from such a model. Possible polynomial oscillation problems'); + getExplainedVariance() { + return this.R2X; + } + /** + * Export the current model to JSON. + * @return {object} - Current model. + */ - var windowSize = options.windowSize; - var half = Math.floor(windowSize / 2); - var np = data.length; - var ans = new Array(np); - var weights = fullWeights(windowSize, options.polynomial, options.derivative); - var hs = 0; - var constantH = true; - if (Object.prototype.toString.call(h) === '[object Array]') { - constantH = false; - } else { - hs = Math.pow(h, options.derivative); - } - //console.log("Constant h: "+constantH); - //For the borders - for (var i = 0; i < half; i++) { - var wg1 = weights[half - i - 1]; - var wg2 = weights[half + i + 1]; - var d1 = 0, - d2 = 0; - for (var l = 0; l < windowSize; l++) { - d1 += wg1[l] * data[l]; - d2 += wg2[l] * data[np - windowSize + l - 1]; - } - if (constantH) { - ans[half - i - 1] = d1 / hs; - ans[np - half + i] = d2 / hs; - } else { - hs = getHs(h, half - i - 1, half, options.derivative); - ans[half - i - 1] = d1 / hs; - hs = getHs(h, np - half + i, half, options.derivative); - ans[np - half + i] = d2 / hs; - } - } - //For the internal points - var wg = weights[half]; - for (var i = windowSize; i < np + 1; i++) { - var d = 0; - for (var l = 0; l < windowSize; l++) { - d += wg[l] * data[l + i - windowSize]; - }if (!constantH) hs = getHs(h, i - half - 1, half, options.derivative); - ans[i - half - 1] = d / hs; - } - return ans; -} + toJSON() { + return { + name: 'PLS', + R2X: this.R2X, + meanX: this.meanX, + stdDevX: this.stdDevX, + meanY: this.meanY, + stdDevY: this.stdDevY, + PBQ: this.PBQ, + tolerance: this.tolerance, + scale: this.scale + }; + } + /** + * Load a PLS model from a JSON Object + * @param {object} model + * @return {PLS} - PLS object from the given model + */ -function getHs(h, center, half, derivative) { - var hs = 0; - var count = 0; - for (var i = center - half; i < center + half; i++) { - if (i >= 0 && i < h.length - 1) { - hs += h[i + 1] - h[i]; - count++; - } - } - return Math.pow(hs / count, derivative); -} -function GramPoly(i, m, k, s) { - var Grampoly = 0; - if (k > 0) { - Grampoly = (4 * k - 2) / (k * (2 * m - k + 1)) * (i * GramPoly(i, m, k - 1, s) + s * GramPoly(i, m, k - 1, s - 1)) - (k - 1) * (2 * m + k) / (k * (2 * m - k + 1)) * GramPoly(i, m, k - 2, s); - } else { - if (k == 0 && s == 0) { - Grampoly = 1; - } else { - Grampoly = 0; - } + static load(model) { + if (model.name !== 'PLS') { + throw new RangeError('Invalid model: ' + model.name); } - //console.log(Grampoly); - return Grampoly; -} -function GenFact(a, b) { - var gf = 1; - if (a >= b) { - for (var j = a - b + 1; j <= a; j++) { - gf *= j; - } - } - return gf; -} + return new pls_PLS(true, model); + } -function Weight(i, t, m, n, s) { - var sum = 0; - for (var k = 0; k <= n; k++) { - //console.log(k); - sum += (2 * k + 1) * (GenFact(2 * m, k) / GenFact(2 * m + k + 1, k + 1)) * GramPoly(i, m, k, 0) * GramPoly(t, m, k, s); - } - return sum; } - /** - * - * @param m Number of points - * @param n Polynomial grade - * @param s Derivative + * @private + * Function that returns the index where the sum of each + * column vector is maximum. + * @param {Matrix} data + * @return {number} index of the maximum */ -function fullWeights(m, n, s) { - var weights = new Array(m); - var np = Math.floor(m / 2); - for (var t = -np; t <= np; t++) { - weights[t + np] = new Array(m); - for (var j = -np; j <= np; j++) { - weights[t + np][j + np] = Weight(j, t, np, n, s); - } - } - return weights; -} - -/*function entropy(data,h,options){ - var trend = SavitzkyGolay(data,h,trendOptions); - var copy = new Array(data.length); - var sum = 0; - var max = 0; - for(var i=0;i> 8 & 0xff] + eightBits[arr[i] >> 16 & 0xff] + eightBits[arr[i] >> 24 & 0xff]; - } - return c; -} + train(trainingSet, trainingValues) { + trainingSet = src["Matrix"].checkMatrix(trainingSet); + trainingValues = src["Matrix"].checkMatrix(trainingValues); // to save and compute kernel with the prediction dataset. + + this.trainingSet = trainingSet.clone(); + var kernelX = this.kernel.compute(trainingSet); + var Identity = src["Matrix"].eye(kernelX.rows, kernelX.rows, 1); + var temp = kernelX; + kernelX = new src["Matrix"](this.orthogonalComp + 1, this.orthogonalComp + 1); + kernelX[0][0] = temp; + var result = new src["SingularValueDecomposition"](trainingValues.transpose().mmul(kernelX[0][0]).mmul(trainingValues), { + computeLeftSingularVectors: true, + computeRightSingularVectors: false + }); + var YLoadingMat = result.leftSingularVectors; + var Sigma = result.diagonalMatrix; + YLoadingMat = YLoadingMat.subMatrix(0, YLoadingMat.rows - 1, 0, this.predictiveComp - 1); + Sigma = Sigma.subMatrix(0, this.predictiveComp - 1, 0, this.predictiveComp - 1); + var YScoreMat = trainingValues.mmul(YLoadingMat); + var predScoreMat = new Array(this.orthogonalComp + 1); + var TURegressionCoeff = new Array(this.orthogonalComp + 1); + var YOrthScoreMat = new Array(this.orthogonalComp); + var YOrthLoadingVec = new Array(this.orthogonalComp); + var YOrthEigen = new Array(this.orthogonalComp); + var YOrthScoreNorm = new Array(this.orthogonalComp); + var SigmaPow = src["Matrix"].pow(Sigma, -0.5); // to avoid errors, check infinity + + SigmaPow.apply(function (i, j) { + if (this[i][j] === Infinity) { + this[i][j] = 0.0; + } + }); -/** - * Logical AND operation - * @param {Array} arr1 - * @param {Array} arr2 - * @return {Array} - */ -function and(arr1, arr2) { - var ans = new Array(arr1.length); - for (var i = 0; i < arr1.length; i++) { - ans[i] = arr1[i] & arr2[i]; - }return ans; -} + for (var i = 0; i < this.orthogonalComp; ++i) { + predScoreMat[i] = kernelX[0][i].transpose().mmul(YScoreMat).mmul(SigmaPow); + var TpiPrime = predScoreMat[i].transpose(); + TURegressionCoeff[i] = Object(src["inverse"])(TpiPrime.mmul(predScoreMat[i])).mmul(TpiPrime).mmul(YScoreMat); + result = new src["SingularValueDecomposition"](TpiPrime.mmul(src["Matrix"].sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime))).mmul(predScoreMat[i]), { + computeLeftSingularVectors: true, + computeRightSingularVectors: false + }); + var CoTemp = result.leftSingularVectors; + var SoTemp = result.diagonalMatrix; + YOrthLoadingVec[i] = CoTemp.subMatrix(0, CoTemp.rows - 1, 0, 0); + YOrthEigen[i] = SoTemp[0][0]; + YOrthScoreMat[i] = src["Matrix"].sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime)).mmul(predScoreMat[i]).mmul(YOrthLoadingVec[i]).mul(Math.pow(YOrthEigen[i], -0.5)); + var toiPrime = YOrthScoreMat[i].transpose(); + YOrthScoreNorm[i] = src["Matrix"].sqrt(toiPrime.mmul(YOrthScoreMat[i])); + YOrthScoreMat[i] = YOrthScoreMat[i].divRowVector(YOrthScoreNorm[i]); + var ITo = src["Matrix"].sub(Identity, YOrthScoreMat[i].mmul(YOrthScoreMat[i].transpose())); + kernelX[0][i + 1] = kernelX[0][i].mmul(ITo); + kernelX[i + 1][i + 1] = ITo.mmul(kernelX[i][i]).mmul(ITo); + } + + var lastScoreMat = predScoreMat[this.orthogonalComp] = kernelX[0][this.orthogonalComp].transpose().mmul(YScoreMat).mmul(SigmaPow); + var lastTpPrime = lastScoreMat.transpose(); + TURegressionCoeff[this.orthogonalComp] = Object(src["inverse"])(lastTpPrime.mmul(lastScoreMat)).mmul(lastTpPrime).mmul(YScoreMat); + this.YLoadingMat = YLoadingMat; + this.SigmaPow = SigmaPow; + this.YScoreMat = YScoreMat; + this.predScoreMat = predScoreMat; + this.YOrthLoadingVec = YOrthLoadingVec; + this.YOrthEigen = YOrthEigen; + this.YOrthScoreMat = YOrthScoreMat; + this.toNorm = YOrthScoreNorm; + this.TURegressionCoeff = TURegressionCoeff; + this.kernelX = kernelX; + } + /** + * Predicts the output given the matrix to predict. + * @param {Matrix|Array} toPredict + * @return {{y: Matrix, predScoreMat: Array, predYOrthVectors: Array}} predictions + */ -/** - * Logical OR operation - * @param {Array} arr1 - * @param {Array} arr2 - * @return {Array} - */ -function or(arr1, arr2) { - var ans = new Array(arr1.length); - for (var i = 0; i < arr1.length; i++) { - ans[i] = arr1[i] | arr2[i]; - }return ans; -} -/** - * Logical XOR operation - * @param {Array} arr1 - * @param {Array} arr2 - * @return {Array} - */ -function xor(arr1, arr2) { - var ans = new Array(arr1.length); - for (var i = 0; i < arr1.length; i++) { - ans[i] = arr1[i] ^ arr2[i]; - }return ans; -} + predict(toPredict) { + var KTestTrain = this.kernel.compute(toPredict, this.trainingSet); + var temp = KTestTrain; + KTestTrain = new src["Matrix"](this.orthogonalComp + 1, this.orthogonalComp + 1); + KTestTrain[0][0] = temp; + var YOrthScoreVector = new Array(this.orthogonalComp); + var predScoreMat = new Array(this.orthogonalComp); + var i; -/** - * Logical NOT operation - * @param {Array} arr - * @return {Array} - */ -function not(arr) { - var ans = new Array(arr.length); - for (var i = 0; i < ans.length; i++) { - ans[i] = ~arr[i]; - }return ans; -} + for (i = 0; i < this.orthogonalComp; ++i) { + predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow); + YOrthScoreVector[i] = src["Matrix"].sub(KTestTrain[i][i], predScoreMat[i].mmul(this.predScoreMat[i].transpose())).mmul(this.predScoreMat[i]).mmul(this.YOrthLoadingVec[i]).mul(Math.pow(this.YOrthEigen[i], -0.5)); + YOrthScoreVector[i] = YOrthScoreVector[i].divRowVector(this.toNorm[i]); + var scoreMatPrime = this.YOrthScoreMat[i].transpose(); + KTestTrain[i + 1][0] = src["Matrix"].sub(KTestTrain[i][0], YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[0][i].transpose())); + var p1 = src["Matrix"].sub(KTestTrain[i][0], KTestTrain[i][i].mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime)); + var p2 = YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[i][i]); + var p3 = p2.mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime); + KTestTrain[i + 1][i + 1] = p1.sub(p2).add(p3); + } -/** - * Gets the n value of array arr - * @param {Array} arr - * @param {number} n - * @return {boolean} - */ -function getBit(arr, n) { - var index = n >> 5; // Same as Math.floor(n/32) - var mask = 1 << 31 - n % 32; - return Boolean(arr[index] & mask); -} + predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow); + var prediction = predScoreMat[i].mmul(this.TURegressionCoeff[i]).mmul(this.YLoadingMat.transpose()); + return { + prediction: prediction, + predScoreMat: predScoreMat, + predYOrthVectors: YOrthScoreVector + }; + } + /** + * Export the current model to JSON. + * @return {object} - Current model. + */ -/** - * Sets the n value of array arr to the value val - * @param {Array} arr - * @param {number} n - * @param {boolean} val - * @return {Array} - */ -function setBit(arr, n, val) { - var index = n >> 5; // Same as Math.floor(n/32) - var mask = 1 << 31 - n % 32; - if (val) arr[index] = mask | arr[index];else arr[index] = ~mask & arr[index]; - return arr; -} -/** - * Translates an array of numbers to a string of bits - * @param {Array} arr - * @returns {string} - */ -function toBinaryString(arr) { - var str = ''; - for (var i = 0; i < arr.length; i++) { - var obj = (arr[i] >>> 0).toString(2); - str += '00000000000000000000000000000000'.substr(obj.length) + obj; + toJSON() { + return { + name: 'K-OPLS', + YLoadingMat: this.YLoadingMat, + SigmaPow: this.SigmaPow, + YScoreMat: this.YScoreMat, + predScoreMat: this.predScoreMat, + YOrthLoadingVec: this.YOrthLoadingVec, + YOrthEigen: this.YOrthEigen, + YOrthScoreMat: this.YOrthScoreMat, + toNorm: this.toNorm, + TURegressionCoeff: this.TURegressionCoeff, + kernelX: this.kernelX, + trainingSet: this.trainingSet, + orthogonalComp: this.orthogonalComp, + predictiveComp: this.predictiveComp + }; + } + /** + * Load a K-OPLS with the given model. + * @param {object} model + * @param {Kernel} kernel - kernel used on the model, see [ml-kernel](https://github.com/mljs/kernel). + * @return {KOPLS} + */ + + + static load(model, kernel) { + if (model.name !== 'K-OPLS') { + throw new RangeError('Invalid model: ' + model.name); } - return str; -} -/** - * Creates an array of numbers based on a string of bits - * @param {string} str - * @returns {Array} - */ -function parseBinaryString(str) { - var len = str.length / 32; - var ans = new Array(len); - for (var i = 0; i < len; i++) { - ans[i] = parseInt(str.substr(i * 32, 32), 2) | 0; + if (!kernel) { + throw new RangeError('You must provide a kernel for the model!'); } - return ans; + + model.kernel = kernel; + return new kopls_KOPLS(true, model); + } + } +// CONCATENATED MODULE: ./node_modules/ml-pls/src/index.js +/* concated harmony reexport PLS */__webpack_require__.d(__webpack_exports__, "PLS", function() { return pls_PLS; }); +/* concated harmony reexport KOPLS */__webpack_require__.d(__webpack_exports__, "KOPLS", function() { return kopls_KOPLS; }); + + +/***/ }), +/* 145 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + +// CONCATENATED MODULE: ./node_modules/ml-levenberg-marquardt/src/errorCalculation.js /** - * Translates an array of numbers to a hex string - * @param {Array} arr - * @returns {string} + * Calculate current error + * @ignore + * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ] + * @param {Array} parameters - Array of current parameter values + * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter + * @return {number} */ -function toHexString(arr) { - var str = ''; - for (var i = 0; i < arr.length; i++) { - var obj = (arr[i] >>> 0).toString(16); - str += '00000000'.substr(obj.length) + obj; - } - return str; +function errorCalculation(data, parameters, parameterizedFunction) { + var error = 0; + const func = parameterizedFunction(parameters); + + for (var i = 0; i < data.x.length; i++) { + error += Math.abs(data.y[i] - func(data.x[i])); + } + + return error; } +// EXTERNAL MODULE: ./node_modules/ml-matrix/src/index.js + 24 modules +var src = __webpack_require__(0); + +// CONCATENATED MODULE: ./node_modules/ml-levenberg-marquardt/src/step.js /** - * Creates an array of numbers based on a hex string - * @param {string} str - * @returns {Array} + * Difference of the matrix function over the parameters + * @ignore + * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ] + * @param {Array} evaluatedData - Array of previous evaluated function values + * @param {Array} params - Array of previous parameter values + * @param {number} gradientDifference - Adjustment for decrease the damping parameter + * @param {function} paramFunction - The parameters and returns a function with the independent variable as a parameter + * @return {Matrix} */ -function parseHexString(str) { - var len = str.length / 8; - var ans = new Array(len); - for (var i = 0; i < len; i++) { - ans[i] = parseInt(str.substr(i * 8, 8), 16) | 0; + +function gradientFunction(data, evaluatedData, params, gradientDifference, paramFunction) { + const n = params.length; + const m = data.x.length; + var ans = new Array(n); + + for (var param = 0; param < n; param++) { + ans[param] = new Array(m); + var auxParams = params.concat(); + auxParams[param] += gradientDifference; + var funcParam = paramFunction(auxParams); + + for (var point = 0; point < m; point++) { + ans[param][point] = evaluatedData[point] - funcParam(data.x[point]); } - return ans; + } + + return new src["Matrix"](ans); } +/** + * Matrix function over the samples + * @ignore + * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ] + * @param {Array} evaluatedData - Array of previous evaluated function values + * @return {Matrix} + */ + + +function matrixFunction(data, evaluatedData) { + const m = data.x.length; + var ans = new Array(m); + + for (var point = 0; point < m; point++) { + ans[point] = [data.y[point] - evaluatedData[point]]; + } + return new src["Matrix"](ans); +} /** - * Creates a human readable string of the array - * @param {Array} arr - * @returns {string} + * Iteration for Levenberg-Marquardt + * @ignore + * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ] + * @param {Array} params - Array of previous parameter values + * @param {number} damping - Levenberg-Marquardt parameter + * @param {number} gradientDifference - Adjustment for decrease the damping parameter + * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter + * @return {Array} */ -function toDebug(arr) { - var binary = toBinaryString(arr); - var str = ''; - for (var i = 0; i < arr.length; i++) { - str += '0000'.substr((i * 32).toString(16).length) + (i * 32).toString(16) + ':'; - for (var j = 0; j < 32; j += 4) { - str += ' ' + binary.substr(i * 32 + j, 4); - } - if (i < arr.length - 1) str += '\n'; - } - return str; + + +function step(data, params, damping, gradientDifference, parameterizedFunction) { + var value = damping * gradientDifference * gradientDifference; + var identity = src["Matrix"].eye(params.length, params.length, value); + const func = parameterizedFunction(params); + var evaluatedData = data.x.map(e => func(e)); + var gradientFunc = gradientFunction(data, evaluatedData, params, gradientDifference, parameterizedFunction); + var matrixFunc = matrixFunction(data, evaluatedData); + var inverseMatrix = Object(src["inverse"])(identity.add(gradientFunc.mmul(gradientFunc.transpose()))); + params = new src["Matrix"]([params]); + params = params.sub(inverseMatrix.mmul(gradientFunc).mmul(matrixFunc).mul(gradientDifference).transpose()); + return params.to1DArray(); } +// CONCATENATED MODULE: ./node_modules/ml-levenberg-marquardt/src/index.js +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return levenbergMarquardt; }); -module.exports = { - count: count, - and: and, - or: or, - xor: xor, - not: not, - getBit: getBit, - setBit: setBit, - toBinaryString: toBinaryString, - parseBinaryString: parseBinaryString, - toHexString: toHexString, - parseHexString: parseHexString, - toDebug: toDebug -}; -/***/ }), -/* 187 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Curve fitting algorithm + * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ] + * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter + * @param {object} [options] - Options object + * @param {number} [options.damping] - Levenberg-Marquardt parameter + * @param {number} [options.gradientDifference = 10e-2] - Adjustment for decrease the damping parameter + * @param {Array} [options.minValues] - Minimum allowed values for parameters + * @param {Array} [options.maxValues] - Maximum allowed values for parameters + * @param {Array} [options.initialValues] - Array of initial parameter values + * @param {number} [options.maxIterations = 100] - Maximum of allowed iterations + * @param {number} [options.errorTolerance = 10e-3] - Minimum uncertainty allowed for each point + * @return {{parameterValues: Array, parameterError: number, iterations: number}} + */ -"use strict"; +function levenbergMarquardt(data, parameterizedFunction) { + let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + let { + maxIterations = 100, + gradientDifference = 10e-2, + damping = 0, + errorTolerance = 10e-3, + minValues, + maxValues, + initialValues + } = options; + if (damping <= 0) { + throw new Error('The damping option must be a positive number'); + } else if (!data.x || !data.y) { + throw new Error('The data parameter must have x and y elements'); + } else if (!Array.isArray(data.x) || data.x.length < 2 || !Array.isArray(data.y) || data.y.length < 2) { + throw new Error('The data parameter elements must be an array with more than 2 points'); + } else if (data.x.length !== data.y.length) { + throw new Error('The data parameter elements must have the same size'); + } -// auxiliary file to create the 256 look at table elements + var parameters = initialValues || new Array(parameterizedFunction.length).fill(1); + let parLen = parameters.length; + maxValues = maxValues || new Array(parLen).fill(Number.MAX_SAFE_INTEGER); + minValues = minValues || new Array(parLen).fill(Number.MIN_SAFE_INTEGER); -var ans = new Array(256); -for (var i = 0; i < 256; i++) { - var num = i; - var c = 0; - while (num) { - num = num & num - 1; - c++; - } - ans[i] = c; -} + if (maxValues.length !== minValues.length) { + throw new Error('minValues and maxValues must be the same size'); + } -module.exports = ans; + if (!Array.isArray(parameters)) { + throw new Error('initialValues must be an array'); + } -/***/ }), -/* 188 */ -/***/ (function(module, exports, __webpack_require__) { + var error = errorCalculation(data, parameters, parameterizedFunction); + var converged = error <= errorTolerance; -"use strict"; + for (var iteration = 0; iteration < maxIterations && !converged; iteration++) { + parameters = step(data, parameters, damping, gradientDifference, parameterizedFunction); + for (let k = 0; k < parLen; k++) { + parameters[k] = Math.min(Math.max(minValues[k], parameters[k]), maxValues[k]); + } -module.exports = exports = __webpack_require__(189); + error = errorCalculation(data, parameters, parameterizedFunction); + if (isNaN(error)) break; + converged = error <= errorTolerance; + } -exports.getEquallySpacedData = __webpack_require__(190).getEquallySpacedData; -exports.SNV = __webpack_require__(191).SNV; + return { + parameterValues: parameters, + parameterError: error, + iterations: iteration + }; +} /***/ }), -/* 189 */ -/***/ (function(module, exports, __webpack_require__) { +/* 146 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +__webpack_require__.r(__webpack_exports__); +// CONCATENATED MODULE: ./node_modules/ml-array-xy-filter-x/src/getZones.js +function getZones(from, to) { + let exclusions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; -var Stat = __webpack_require__(4).array; -/** - * Function that returns an array of points given 1D array as follows: - * - * [x1, y1, .. , x2, y2, ..] - * - * And receive the number of dimensions of each point. - * @param array - * @param dimensions - * @returns {Array} - Array of points. - */ -function coordArrayToPoints(array, dimensions) { - if (array.length % dimensions !== 0) { - throw new RangeError('Dimensions number must be accordance with the size of the array.'); - } + if (from > to) { + [from, to] = [to, from]; + } // in exclusions from and to have to be defined - var length = array.length / dimensions; - var pointsArr = new Array(length); - var k = 0; - for (var i = 0; i < array.length; i += dimensions) { - var point = new Array(dimensions); - for (var j = 0; j < dimensions; ++j) { - point[j] = array[i + j]; - } + exclusions = exclusions.filter(exclusion => exclusion.from !== undefined && exclusion.to !== undefined); + exclusions = JSON.parse(JSON.stringify(exclusions)); // we ensure that from before to - pointsArr[k] = point; - k++; + exclusions.forEach(exclusion => { + if (exclusion.from > exclusion.to) { + [exclusion.to, exclusion.from] = [exclusion.from, exclusion.to]; } + }); + exclusions.sort((a, b) => a.from - b.from); // we will rework the exclusions in order to remove overlap and outside range (from / to) - return pointsArr; -} + exclusions.forEach(exclusion => { + if (exclusion.from < from) exclusion.from = from; + if (exclusion.to > to) exclusion.to = to; + }); -/** - * Function that given an array as follows: - * [x1, y1, .. , x2, y2, ..] - * - * Returns an array as follows: - * [[x1, x2, ..], [y1, y2, ..], [ .. ]] - * - * And receives the number of dimensions of each coordinate. - * @param array - * @param dimensions - * @returns {Array} - Matrix of coordinates - */ -function coordArrayToCoordMatrix(array, dimensions) { - if (array.length % dimensions !== 0) { - throw new RangeError('Dimensions number must be accordance with the size of the array.'); + for (let i = 0; i < exclusions.length - 1; i++) { + if (exclusions[i].to > exclusions[i + 1].from) { + exclusions[i].to = exclusions[i + 1].from; } + } - var coordinatesArray = new Array(dimensions); - var points = array.length / dimensions; - for (var i = 0; i < coordinatesArray.length; i++) { - coordinatesArray[i] = new Array(points); - } + exclusions = exclusions.filter(exclusion => exclusion.from < exclusion.to); - for (i = 0; i < array.length; i += dimensions) { - for (var j = 0; j < dimensions; ++j) { - var currentPoint = Math.floor(i / dimensions); - coordinatesArray[j][currentPoint] = array[i + j]; - } - } + if (!exclusions || exclusions.length === 0) { + return [{ + from, + to + }]; + } - return coordinatesArray; -} + let zones = []; + let currentFrom = from; -/** - * Function that receives a coordinate matrix as follows: - * [[x1, x2, ..], [y1, y2, ..], [ .. ]] - * - * Returns an array of coordinates as follows: - * [x1, y1, .. , x2, y2, ..] - * - * @param coordMatrix - * @returns {Array} - */ -function coordMatrixToCoordArray(coordMatrix) { - var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length); - var k = 0; - for (var i = 0; i < coordMatrix[0].length; ++i) { - for (var j = 0; j < coordMatrix.length; ++j) { - coodinatesArray[k] = coordMatrix[j][i]; - ++k; - } + for (let exclusion of exclusions) { + if (currentFrom < exclusion.from) { + zones.push({ + from: currentFrom, + to: exclusion.from + }); } - return coodinatesArray; + currentFrom = exclusion.to; + } + + if (currentFrom < to) { + zones.push({ + from: currentFrom, + to: to + }); + } + + return zones; } +// CONCATENATED MODULE: ./node_modules/ml-array-xy-filter-x/src/index.js +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return filterX; }); /** - * Tranpose a matrix, this method is for coordMatrixToPoints and - * pointsToCoordMatrix, that because only transposing the matrix - * you can change your representation. + * Filter an array x/y based on various criteria + * x points are expected to be sorted * - * @param matrix - * @returns {Array} + * @param {object} points + * @param {object} [options={}] + * @param {array} [options.from] + * @param {array} [options.to] + * @param {array} [options.exclusions=[]] + * @return {{x: Array, y: Array}} */ -function transpose(matrix) { - var resultMatrix = new Array(matrix[0].length); - for (var i = 0; i < resultMatrix.length; ++i) { - resultMatrix[i] = new Array(matrix.length); - } - for (i = 0; i < matrix.length; ++i) { - for (var j = 0; j < matrix[0].length; ++j) { - resultMatrix[j][i] = matrix[i][j]; - } +function filterX(points) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const { + x, + y + } = points; + const { + from = x[0], + to = x[x.length - 1], + exclusions = [] + } = options; + let zones = getZones(from, to, exclusions); + let currentZoneIndex = 0; + let newX = []; + let newY = []; + let position = 0; + + while (position < x.length) { + if (x[position] <= zones[currentZoneIndex].to && x[position] >= zones[currentZoneIndex].from) { + newX.push(x[position]); + newY.push(y[position]); + } else { + if (x[position] > zones[currentZoneIndex].to) { + currentZoneIndex++; + if (!zones[currentZoneIndex]) break; + } } - return resultMatrix; + position++; + } + + return { + x: newX, + y: newY + }; } -/** - * Function that transform an array of points into a coordinates array - * as follows: - * [x1, y1, .. , x2, y2, ..] +/***/ }), +/* 147 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + +// CONCATENATED MODULE: ./node_modules/ml-knn/src/KDTree.js +/* + * Original code from: * - * @param points - * @returns {Array} + * k-d Tree JavaScript - V 1.01 + * + * https://github.com/ubilabs/kd-tree-javascript + * + * @author Mircea Pricop , 2012 + * @author Martin Kleppe , 2012 + * @author Ubilabs http://ubilabs.net, 2012 + * @license MIT License */ -function pointsToCoordArray(points) { - var coodinatesArray = new Array(points.length * points[0].length); - var k = 0; - for (var i = 0; i < points.length; ++i) { - for (var j = 0; j < points[0].length; ++j) { - coodinatesArray[k] = points[i][j]; - ++k; - } - } - - return coodinatesArray; +function Node(obj, dimension, parent) { + this.obj = obj; + this.left = null; + this.right = null; + this.parent = parent; + this.dimension = dimension; } -/** - * Apply the dot product between the smaller vector and a subsets of the - * largest one. - * - * @param firstVector - * @param secondVector - * @returns {Array} each dot product of size of the difference between the - * larger and the smallest one. - */ -function applyDotProduct(firstVector, secondVector) { - var largestVector, smallestVector; - if (firstVector.length <= secondVector.length) { - smallestVector = firstVector; - largestVector = secondVector; +class KDTree { + constructor(points, metric) { + // If points is not an array, assume we're loading a pre-built tree + if (!Array.isArray(points)) { + this.dimensions = points.dimensions; + this.root = points; + restoreParent(this.root); } else { - smallestVector = secondVector; - largestVector = firstVector; - } + this.dimensions = new Array(points[0].length); - var difference = largestVector.length - smallestVector.length + 1; - var dotProductApplied = new Array(difference); + for (var i = 0; i < this.dimensions.length; i++) { + this.dimensions[i] = i; + } - for (var i = 0; i < difference; ++i) { - var sum = 0; - for (var j = 0; j < smallestVector.length; ++j) { - sum += smallestVector[j] * largestVector[i + j]; - } - dotProductApplied[i] = sum; + this.root = buildTree(points, 0, null, this.dimensions); } - return dotProductApplied; -} -/** - * To scale the input array between the specified min and max values. The operation is performed inplace - * if the options.inplace is specified. If only one of the min or max parameters is specified, then the scaling - * will multiply the input array by min/min(input) or max/max(input) - * @param input - * @param options - * @returns {*} - */ -function scale(input, options = {}) { - var min = options.min, - max = options.max; + this.metric = metric; + } // Convert to a JSON serializable structure; this just requires removing + // the `parent` property + + + toJSON() { + const result = toJSONImpl(this.root, true); + result.dimensions = this.dimensions; + return result; + } + nearest(point, maxNodes, maxDistance) { + const metric = this.metric; + const dimensions = this.dimensions; + var i; + const bestNodes = new BinaryHeap(function (e) { + return -e[1]; + }); - var y = options.inPlace ? input : new Array(input.length); - var minMax = Stat.minMax(input); + function nearestSearch(node) { + const dimension = dimensions[node.dimension]; + const ownDistance = metric(point, node.obj); + const linearPoint = {}; + var bestChild, linearDistance, otherChild, i; - if (typeof max === 'number') { - if (typeof min === 'number') { - var factor = (max - min) / (minMax.max - minMax.min); - for (var i = 0; i < y.length; i++) { - y[i] = (input[i] - minMax.min) * factor + min; - } - } else if (minMax.max !== 0) { - var _factor = max / minMax.max; - for (var _i = 0; _i < y.length; _i++) { - y[_i] = input[_i] * _factor; - } - } else { - options.min = minMax.min; - y = scale(input, options); + function saveNode(node, distance) { + bestNodes.push([node, distance]); + + if (bestNodes.size() > maxNodes) { + bestNodes.pop(); } - } else if (typeof min === 'number') { - if (minMax.min !== 0) { - var _factor2 = min / minMax.min; - for (var _i2 = 0; _i2 < y.length; _i2++) { - y[_i2] = input[_i2] * _factor2; - } + } + + for (i = 0; i < dimensions.length; i += 1) { + if (i === node.dimension) { + linearPoint[dimensions[i]] = point[dimensions[i]]; } else { - options.max = minMax.max; - y = scale(input, options); + linearPoint[dimensions[i]] = node.obj[dimensions[i]]; } - } - return y; -} - -module.exports = { - coordArrayToPoints: coordArrayToPoints, - coordArrayToCoordMatrix: coordArrayToCoordMatrix, - coordMatrixToCoordArray: coordMatrixToCoordArray, - coordMatrixToPoints: transpose, - pointsToCoordArray: pointsToCoordArray, - pointsToCoordMatrix: transpose, - applyDotProduct: applyDotProduct, - scale: scale -}; + } -/***/ }), -/* 190 */ -/***/ (function(module, exports, __webpack_require__) { + linearDistance = metric(linearPoint, node.obj); -"use strict"; + if (node.right === null && node.left === null) { + if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { + saveNode(node, ownDistance); + } + return; + } -/** - * - * Function that returns a Number array of equally spaced numberOfPoints - * containing a representation of intensities of the spectra arguments x - * and y. - * - * The options parameter contains an object in the following form: - * from: starting point - * to: last point - * numberOfPoints: number of points between from and to - * variant: "slot" or "smooth" - smooth is the default option - * - * The slot variant consist that each point in the new array is calculated - * averaging the existing points between the slot that belongs to the current - * value. The smooth variant is the same but takes the integral of the range - * of the slot and divide by the step size between two points in the new array. - * - * @param x - sorted increasing x values - * @param y - * @param options - * @returns {Array} new array with the equally spaced data. - * - */ + if (node.right === null) { + bestChild = node.left; + } else if (node.left === null) { + bestChild = node.right; + } else { + if (point[dimension] < node.obj[dimension]) { + bestChild = node.left; + } else { + bestChild = node.right; + } + } -function getEquallySpacedData(x, y, options = {}) { - var xLength = x.length; - if (x.length > 1 && x[0] > x[1]) { - x = x.slice().reverse(); - y = y.slice().reverse(); - } + nearestSearch(bestChild); - var _options$from = options.from, - from = _options$from === undefined ? x[0] : _options$from, - _options$to = options.to, - to = _options$to === undefined ? x[xLength - 1] : _options$to, - _options$variant = options.variant, - variant = _options$variant === undefined ? 'smooth' : _options$variant, - _options$numberOfPoin = options.numberOfPoints, - numberOfPoints = _options$numberOfPoin === undefined ? 100 : _options$numberOfPoin; + if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { + saveNode(node, ownDistance); + } + if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) { + if (bestChild === node.left) { + otherChild = node.right; + } else { + otherChild = node.left; + } - if (xLength !== y.length) { - throw new RangeError("the x and y vector doesn't have the same size."); + if (otherChild !== null) { + nearestSearch(otherChild); + } + } } - if (typeof from !== 'number' || isNaN(from)) { - throw new RangeError("'from' option must be a number"); + if (maxDistance) { + for (i = 0; i < maxNodes; i += 1) { + bestNodes.push([null, maxDistance]); + } } - if (typeof to !== 'number' || isNaN(to)) { - throw new RangeError("'to' option must be a number"); + if (this.root) { + nearestSearch(this.root); } - var reverse = from > to; - if (reverse) { - var _ref = [to, from]; - from = _ref[0]; - to = _ref[1]; - } + const result = []; - if (typeof numberOfPoints !== 'number' || isNaN(numberOfPoints)) { - throw new RangeError("'numberOfPoints' option must be a number"); - } - if (numberOfPoints < 1) { - throw new RangeError('the number of points must be at least 1'); + for (i = 0; i < Math.min(maxNodes, bestNodes.content.length); i += 1) { + if (bestNodes.content[i][0]) { + result.push([bestNodes.content[i][0].obj, bestNodes.content[i][1]]); + } } - var output = variant === 'slot' ? getEquallySpacedSlot(x, y, from, to, numberOfPoints) : getEquallySpacedSmooth(x, y, from, to, numberOfPoints); + return result; + } - return reverse ? output.reverse() : output; } -/** - * function that retrieves the getEquallySpacedData with the variant "smooth" - * - * @param x - * @param y - * @param from - Initial point - * @param to - Final point - * @param numberOfPoints - * @returns {Array} - Array of y's equally spaced with the variant "smooth" - */ -function getEquallySpacedSmooth(x, y, from, to, numberOfPoints) { - var xLength = x.length; - - var step = (to - from) / (numberOfPoints - 1); - var halfStep = step / 2; - - var output = new Array(numberOfPoints); - - var initialOriginalStep = x[1] - x[0]; - var lastOriginalStep = x[xLength - 1] - x[xLength - 2]; - - // Init main variables - var min = from - halfStep; - var max = from + halfStep; - - var previousX = Number.MIN_VALUE; - var previousY = 0; - var nextX = x[0] - initialOriginalStep; - var nextY = 0; +function toJSONImpl(src) { + const dest = new Node(src.obj, src.dimension, null); + if (src.left) dest.left = toJSONImpl(src.left); + if (src.right) dest.right = toJSONImpl(src.right); + return dest; +} - var currentValue = 0; - var slope = 0; - var intercept = 0; - var sumAtMin = 0; - var sumAtMax = 0; +function buildTree(points, depth, parent, dimensions) { + const dim = depth % dimensions.length; - var i = 0; // index of input - var j = 0; // index of output + if (points.length === 0) { + return null; + } - function getSlope(x0, y0, x1, y1) { - return (y1 - y0) / (x1 - x0); - } + if (points.length === 1) { + return new Node(points[0], dim, parent); + } - main: while (true) { + points.sort((a, b) => a[dimensions[dim]] - b[dimensions[dim]]); + const median = Math.floor(points.length / 2); + const node = new Node(points[median], dim, parent); + node.left = buildTree(points.slice(0, median), depth + 1, node, dimensions); + node.right = buildTree(points.slice(median + 1), depth + 1, node, dimensions); + return node; +} - if (previousX <= min && min <= nextX) { - add = integral(0, min - previousX, slope, previousY); - sumAtMin = currentValue + add; - } +function restoreParent(root) { + if (root.left) { + root.left.parent = root; + restoreParent(root.left); + } - while (nextX - max >= 0) { - // no overlap with original point, just consume current value - var add = integral(0, max - previousX, slope, previousY); - sumAtMax = currentValue + add; + if (root.right) { + root.right.parent = root; + restoreParent(root.right); + } +} // Binary heap implementation from: +// http://eloquentjavascript.net/appendix2.html - output[j++] = (sumAtMax - sumAtMin) / step; - if (j === numberOfPoints) { - break main; - } +class BinaryHeap { + constructor(scoreFunction) { + this.content = []; + this.scoreFunction = scoreFunction; + } - min = max; - max += step; - sumAtMin = sumAtMax; - } + push(element) { + // Add the new element to the end of the array. + this.content.push(element); // Allow it to bubble up. - currentValue += integral(previousX, nextX, slope, intercept); + this.bubbleUp(this.content.length - 1); + } - previousX = nextX; - previousY = nextY; + pop() { + // Store the first element so we can return it later. + var result = this.content[0]; // Get the element at the end of the array. - if (i < xLength) { - nextX = x[i]; - nextY = y[i]; - i++; - } else if (i === xLength) { - nextX += lastOriginalStep; - nextY = 0; - } + var end = this.content.pop(); // If there are any elements left, put the end element at the + // start, and let it sink down. - slope = getSlope(previousX, previousY, nextX, nextY); - intercept = -slope * previousX + previousY; + if (this.content.length > 0) { + this.content[0] = end; + this.sinkDown(0); } - return output; -} - -/** - * function that retrieves the getEquallySpacedData with the variant "slot" - * - * @param x - * @param y - * @param from - Initial point - * @param to - Final point - * @param numberOfPoints - * @returns {Array} - Array of y's equally spaced with the variant "slot" - */ -function getEquallySpacedSlot(x, y, from, to, numberOfPoints) { - var xLength = x.length; + return result; + } - var step = (to - from) / (numberOfPoints - 1); - var halfStep = step / 2; - var lastStep = x[x.length - 1] - x[x.length - 2]; + peek() { + return this.content[0]; + } - var start = from - halfStep; - var output = new Array(numberOfPoints); + size() { + return this.content.length; + } - // Init main variables - var min = start; - var max = start + step; + bubbleUp(n) { + // Fetch the element that has to be moved. + var element = this.content[n]; // When at 0, an element can not go up any further. - var previousX = -Number.MAX_VALUE; - var previousY = 0; - var nextX = x[0]; - var nextY = y[0]; - var frontOutsideSpectra = 0; - var backOutsideSpectra = true; + while (n > 0) { + // Compute the parent element's index, and fetch it. + const parentN = Math.floor((n + 1) / 2) - 1; + const parent = this.content[parentN]; // Swap the elements if the parent is greater. - var currentValue = 0; + if (this.scoreFunction(element) < this.scoreFunction(parent)) { + this.content[parentN] = element; + this.content[n] = parent; // Update 'n' to continue at the new position. - // for slot algorithm - var currentPoints = 0; + n = parentN; + } else { + // Found a parent that is less, no need to move it further. + break; + } + } + } - var i = 1; // index of input - var j = 0; // index of output + sinkDown(n) { + // Look up the target element and its score. + var length = this.content.length; + var element = this.content[n]; + var elemScore = this.scoreFunction(element); - main: while (true) { - if (previousX >= nextX) throw new Error('x must be an increasing serie'); - while (previousX - max > 0) { - // no overlap with original point, just consume current value - if (backOutsideSpectra) { - currentPoints++; - backOutsideSpectra = false; - } + while (true) { + // Compute the indices of the child elements. + var child2N = (n + 1) * 2; + var child1N = child2N - 1; // This is used to store the new position of the element, + // if any. - output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints; - j++; + var swap = null; // If the first child exists (is inside the array)... - if (j === numberOfPoints) { - break main; - } + if (child1N < length) { + // Look it up and compute its score. + var child1 = this.content[child1N]; + var child1Score = this.scoreFunction(child1); // If the score is less than our element's, we need to swap. - min = max; - max += step; - currentValue = 0; - currentPoints = 0; + if (child1Score < elemScore) { + swap = child1N; } + } // Do the same checks for the other child. - if (previousX > min) { - currentValue += previousY; - currentPoints++; - } - if (previousX === -Number.MAX_VALUE || frontOutsideSpectra > 1) { - currentPoints--; + if (child2N < length) { + var child2 = this.content[child2N]; + var child2Score = this.scoreFunction(child2); + + if (child2Score < (swap === null ? elemScore : child1Score)) { + swap = child2N; } + } // If the element needs to be moved, swap it, and continue. - previousX = nextX; - previousY = nextY; - if (i < xLength) { - nextX = x[i]; - nextY = y[i]; - i++; - } else { - nextX += lastStep; - nextY = 0; - frontOutsideSpectra++; - } + if (swap !== null) { + this.content[n] = this.content[swap]; + this.content[swap] = element; + n = swap; + } else { + // Otherwise, we are done. + break; + } } + } - return output; -} -/** - * Function that calculates the integral of the line between two - * x-coordinates, given the slope and intercept of the line. - * @param x0 - * @param x1 - * @param slope - * @param intercept - * @returns {number} integral value. - */ -function integral(x0, x1, slope, intercept) { - return 0.5 * slope * x1 * x1 + intercept * x1 - (0.5 * slope * x0 * x0 + intercept * x0); } +// EXTERNAL MODULE: ./node_modules/ml-distance-euclidean/euclidean.js +var euclidean = __webpack_require__(2); +var euclidean_default = /*#__PURE__*/__webpack_require__.n(euclidean); -exports.getEquallySpacedData = getEquallySpacedData; -exports.integral = integral; +// CONCATENATED MODULE: ./node_modules/ml-knn/src/index.js +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return src_KNN; }); -/***/ }), -/* 191 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +class src_KNN { + /** + * @param {Array} dataset + * @param {Array} labels + * @param {object} options + * @param {number} [options.k=numberOfClasses + 1] - Number of neighbors to classify. + * @param {function} [options.distance=euclideanDistance] - Distance function that takes two parameters. + */ + constructor(dataset, labels) { + let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (dataset === true) { + const model = labels; + this.kdTree = new KDTree(model.kdTree, options); + this.k = model.k; + this.classes = new Set(model.classes); + this.isEuclidean = model.isEuclidean; + return; + } + const classes = new Set(labels); + const { + distance = euclidean_default.a, + k = classes.size + 1 + } = options; + const points = new Array(dataset.length); -exports.SNV = SNV; -var Stat = __webpack_require__(4).array; + for (var i = 0; i < points.length; ++i) { + points[i] = dataset[i].slice(); + } -/** - * Function that applies the standard normal variate (SNV) to an array of values. - * - * @param data - Array of values. - * @returns {Array} - applied the SNV. - */ -function SNV(data) { - var mean = Stat.mean(data); - var std = Stat.standardDeviation(data); - var result = data.slice(); - for (var i = 0; i < data.length; i++) { - result[i] = (result[i] - mean) / std; + for (i = 0; i < labels.length; ++i) { + points[i].push(labels[i]); } - return result; -} -/***/ }), -/* 192 */ -/***/ (function(module, exports, __webpack_require__) { + this.kdTree = new KDTree(points, distance); + this.k = k; + this.classes = classes; + this.isEuclidean = distance === euclidean_default.a; + } + /** + * Create a new KNN instance with the given model. + * @param {object} model + * @param {function} distance=euclideanDistance - distance function must be provided if the model wasn't trained with euclidean distance. + * @return {KNN} + */ -"use strict"; + static load(model) { + let distance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : euclidean_default.a; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = mode; -/** - * Computes the mode of the given values - * @param {Array} input - * @return {number} - */ -function mode(input) { - if (!Array.isArray(input)) { - throw new Error('input must be an array'); - } - if (input.length === 0) { - throw new Error('input must not be empty'); + if (model.name !== 'KNN') { + throw new Error('invalid model: ' + model.name); } - var maxValue = 0; - var maxCount = 0; - var count = 0; - var counts = {}; - - for (var i = 0; i < input.length; ++i) { - var element = input[i]; - count = counts[element]; - if (count) { - counts[element]++; - count++; - } else { - counts[element] = count = 1; - } + if (!model.isEuclidean && distance === euclidean_default.a) { + throw new Error('a custom distance function was used to create the model. Please provide it again'); + } - if (count > maxCount) { - maxCount = count; - maxValue = input[i]; - } + if (model.isEuclidean && distance !== euclidean_default.a) { + throw new Error('the model was created with the default distance function. Do not load it with another one'); } - return maxValue; -} + return new src_KNN(true, model, distance); + } + /** + * Return a JSON containing the kd-tree model. + * @return {object} JSON KNN model. + */ -/***/ }), -/* 193 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + toJSON() { + return { + name: 'KNN', + kdTree: this.kdTree, + k: this.k, + classes: Array.from(this.classes), + isEuclidean: this.isEuclidean + }; + } + /** + * Predicts the output given the matrix to predict. + * @param {Array} dataset + * @return {Array} predictions + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = standardDeviation; + predict(dataset) { + if (Array.isArray(dataset)) { + if (typeof dataset[0] === 'number') { + return getSinglePrediction(this, dataset); + } else if (Array.isArray(dataset[0]) && typeof dataset[0][0] === 'number') { + const predictions = new Array(dataset.length); -var _mlArrayVariance = __webpack_require__(56); + for (var i = 0; i < dataset.length; i++) { + predictions[i] = getSinglePrediction(this, dataset[i]); + } -var _mlArrayVariance2 = _interopRequireDefault(_mlArrayVariance); + return predictions; + } + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + throw new TypeError('dataset to predict must be an array or a matrix'); + } -/** - * Computes the standard deviation of the given values - * @param {Array} values - * @param {object} [options] - * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n. - * @param {number} [options.mean = arrayMean] - precalculated mean, if any. - * @return {number} - */ -function standardDeviation(values, options = {}) { - return Math.sqrt((0, _mlArrayVariance2.default)(values, options)); +} + +function getSinglePrediction(knn, currentCase) { + var nearestPoints = knn.kdTree.nearest(currentCase, knn.k); + var pointsPerClass = {}; + var predictedClass = -1; + var maxPoints = -1; + var lastElement = nearestPoints[0][0].length - 1; + + for (var element of knn.classes) { + pointsPerClass[element] = 0; + } + + for (var i = 0; i < nearestPoints.length; ++i) { + var currentClass = nearestPoints[i][0][lastElement]; + var currentPoints = ++pointsPerClass[currentClass]; + + if (currentPoints > maxPoints) { + predictedClass = currentClass; + maxPoints = currentPoints; + } + } + + return predictedClass; } /***/ }) diff --git a/dist/ml.js.map b/dist/ml.js.map index d03b289..cb6b486 100644 --- a/dist/ml.js.map +++ b/dist/ml.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap 3ceba11ba2297c055a6e","webpack:///./node_modules/ml-matrix/src/index.js","webpack:///./node_modules/ml-distance-euclidean/euclidean.js","webpack:///./node_modules/ml-regression-base/src/index.js","webpack:///./node_modules/ml-matrix/src/views/base.js","webpack:///./node_modules/ml-stat/index.js","webpack:///./node_modules/ml-matrix/src/matrix.js","webpack:///./node_modules/ml-matrix/src/util.js","webpack:///./node_modules/ml-matrix/src/abstractMatrix.js","webpack:///./node_modules/ml-array-mean/src/index.js","webpack:///./node_modules/ml-matrix/src/dc/svd.js","webpack:///./node_modules/ml-stat/matrix.js","webpack:///./node_modules/ml-array-max/src/index.js","webpack:///./node_modules/ml-matrix/src/dc/lu.js","webpack:///./node_modules/ml-matrix/src/dc/util.js","webpack:///./node_modules/ml-hclust/src/Cluster.js","webpack:///./node_modules/ml-kernel/src/kernel.js","webpack:///./node_modules/ml-regression-simple-linear/src/index.js","webpack:///./node_modules/extend/index.js","webpack:///./node_modules/ml-cart/src/index.js","webpack:///./node_modules/ml-array-rescale/src/index.js","webpack:///./node_modules/ml-array-min/src/index.js","webpack:///./node_modules/ml-matrix/src/wrap/WrapperMatrix1D.js","webpack:///./node_modules/ml-matrix/src/wrap/WrapperMatrix2D.js","webpack:///./node_modules/ml-matrix/src/dc/qr.js","webpack:///./node_modules/ml-cart/src/TreeNode.js","webpack:///./node_modules/ml-random-forest/src/RandomForestBase.js","webpack:///./node_modules/ml-array-median/src/index.js","webpack:///./node_modules/ml-stat/array.js","webpack:///./node_modules/ml-hclust/src/ClusterLeaf.js","webpack:///./node_modules/ml-distance-matrix/src/index.js","webpack:///./node_modules/ml-kmeans/src/utils.js","webpack:///./node_modules/ml-random/lib-es6/index.js","webpack:///./node_modules/ml-xsadd/xsadd-es5.js","webpack:///./node_modules/ml-naivebayes/src/utils.js","webpack:///./node_modules/ml-pls/src/utils.js","webpack:///./node_modules/ml-confusion-matrix/src/index.js","webpack:///./node_modules/ml-fnn/src/Layer.js","webpack:///./node_modules/ml-fnn/src/utils.js","webpack:///./node_modules/ml-fnn/src/activationFunctions.js","webpack:///./node_modules/ml-som/src/node-square.js","webpack:///./node_modules/ml-regression/src/index.js","webpack:///./node_modules/ml-regression-polynomial/src/index.js","webpack:///./node_modules/ml-hash-table/src/HashTable.js","webpack:///./node_modules/binary-search/index.js","webpack:///./node_modules/num-sort/index.js","webpack:///./node_modules/ml-distance/src/index.js","webpack:///./node_modules/ml-distance/src/similarities/czekanowski.js","webpack:///./node_modules/ml-distance/src/distances/dice.js","webpack:///./node_modules/ml-distance/src/distances/intersection.js","webpack:///./node_modules/ml-distance/src/distances/jaccard.js","webpack:///./node_modules/ml-distance/src/distances/kulczynski.js","webpack:///./node_modules/ml-distance/src/distances/motyka.js","webpack:///./node_modules/ml-distance/src/distances/squaredChord.js","webpack:///./node_modules/ml-distance/src/similarities/tanimoto.js","webpack:///./node_modules/ml-distance/src/similarities/cosine.js","webpack:///./node_modules/ml-pad-array/src/index.js","webpack:///./node_modules/ml-array-variance/src/index.js","webpack:///./src/index.js","webpack:///./node_modules/ml-cart/src/DecisionTreeClassifier.js","webpack:///./node_modules/ml-matrix/src/views/transpose.js","webpack:///./node_modules/ml-matrix/src/views/row.js","webpack:///./node_modules/ml-matrix/src/views/sub.js","webpack:///./node_modules/ml-matrix/src/views/selection.js","webpack:///./node_modules/ml-matrix/src/views/rowSelection.js","webpack:///./node_modules/ml-matrix/src/views/columnSelection.js","webpack:///./node_modules/ml-matrix/src/views/column.js","webpack:///./node_modules/ml-matrix/src/views/flipRow.js","webpack:///./node_modules/ml-matrix/src/views/flipColumn.js","webpack:///./node_modules/ml-matrix/src/wrap/wrap.js","webpack:///./node_modules/ml-matrix/src/decompositions.js","webpack:///./node_modules/ml-matrix/src/linearDependencies.js","webpack:///./node_modules/ml-matrix/src/dc/evd.js","webpack:///./node_modules/ml-matrix/src/dc/cholesky.js","webpack:///./node_modules/ml-cart/src/utils.js","webpack:///./node_modules/ml-cart/src/DecisionTreeRegression.js","webpack:///./node_modules/ml-random-forest/src/index.js","webpack:///./node_modules/ml-random-forest/src/RandomForestClassifier.js","webpack:///./node_modules/ml-random-forest/src/utils.js","webpack:///./node_modules/random-js/lib/random.js","webpack:///./node_modules/ml-random-forest/src/RandomForestRegression.js","webpack:///./node_modules/median-quickselect/lib/median-quickselect.min.js","webpack:///./node_modules/ml-pca/src/pca.js","webpack:///./node_modules/ml-hclust/src/index.js","webpack:///./node_modules/ml-hclust/src/agnes.js","webpack:///./node_modules/heap/index.js","webpack:///./node_modules/heap/lib/heap.js","webpack:///./node_modules/util/util.js","webpack:///(webpack)/buildin/global.js","webpack:///./node_modules/process/browser.js","webpack:///./node_modules/util/support/isBufferBrowser.js","webpack:///./node_modules/inherits/inherits_browser.js","webpack:///./node_modules/ml-hclust/src/diana.js","webpack:///./node_modules/ml-kmeans/src/kmeans.js","webpack:///./node_modules/ml-nearest-vector/src/index.js","webpack:///./node_modules/ml-kmeans/src/initialization.js","webpack:///./node_modules/ml-random/lib-es6/choice.js","webpack:///./node_modules/ml-kmeans/src/KMeansResult.js","webpack:///./node_modules/ml-svm/src/svm.js","webpack:///./node_modules/ml-kernel-gaussian/gaussian-kernel.js","webpack:///./node_modules/ml-kernel-polynomial/polynomial-kernel.js","webpack:///./node_modules/ml-kernel/src/kernels/anova-kernel.js","webpack:///./node_modules/ml-kernel/src/kernels/cauchy-kernel.js","webpack:///./node_modules/ml-kernel/src/kernels/exponential-kernel.js","webpack:///./node_modules/ml-kernel/src/kernels/histogram-intersection-kernel.js","webpack:///./node_modules/ml-kernel/src/kernels/laplacian-kernel.js","webpack:///./node_modules/ml-kernel/src/kernels/multiquadratic-kernel.js","webpack:///./node_modules/ml-kernel/src/kernels/rational-quadratic-kernel.js","webpack:///./node_modules/ml-kernel-sigmoid/sigmoid-kernel.js","webpack:///./node_modules/ml-naivebayes/src/index.js","webpack:///./node_modules/ml-naivebayes/src/GaussianNB.js","webpack:///./node_modules/ml-naivebayes/src/MultinomialNB.js","webpack:///./node_modules/ml-knn/src/index.js","webpack:///./node_modules/ml-knn/src/KDTree.js","webpack:///./node_modules/ml-pls/src/index.js","webpack:///./node_modules/ml-pls/src/pls.js","webpack:///./node_modules/ml-pls/src/kopls.js","webpack:///./node_modules/ml-cross-validation/src/index.js","webpack:///./node_modules/ml-combinations/lib/index.js","webpack:///./node_modules/ml-fnn/src/FeedForwardNeuralNetwork.js","webpack:///./node_modules/ml-fnn/src/OutputLayer.js","webpack:///./node_modules/ml-som/src/index.js","webpack:///./node_modules/ml-som/src/node-hexagonal.js","webpack:///./node_modules/ml-regression-base/src/maybeToPrecision.js","webpack:///./node_modules/ml-regression-base/src/checkArrayLength.js","webpack:///./node_modules/ml-regression-exponential/src/index.js","webpack:///./node_modules/ml-regression-power/src/index.js","webpack:///./node_modules/ml-regression-multivariate-linear/src/index.js","webpack:///./node_modules/ml-regression/src/regression/kernel-ridge-regression.js","webpack:///./node_modules/ml-regression/src/regression/poly-fit-regression2d.js","webpack:///./node_modules/ml-regression-theil-sen/src/index.js","webpack:///./node_modules/ml-regression-robust-polynomial/src/index.js","webpack:///./node_modules/ml-regression/src/regression/potential-regression.js","webpack:///./node_modules/ml-levenberg-marquardt/lib/index.js","webpack:///./node_modules/ml-sparse-matrix/src/index.js","webpack:///./node_modules/new-array/index.js","webpack:///./node_modules/ml-hash-table/src/primeFinder.js","webpack:///./node_modules/number-is-nan/index.js","webpack:///./node_modules/ml-distance/src/distances.js","webpack:///./node_modules/ml-distance/src/distances/additiveSymmetric.js","webpack:///./node_modules/ml-distance/src/distances/avg.js","webpack:///./node_modules/ml-distance/src/distances/bhattacharyya.js","webpack:///./node_modules/ml-distance/src/distances/canberra.js","webpack:///./node_modules/ml-distance/src/distances/chebyshev.js","webpack:///./node_modules/ml-distance/src/distances/clark.js","webpack:///./node_modules/ml-distance/src/distances/czekanowski.js","webpack:///./node_modules/ml-distance/src/distances/divergence.js","webpack:///./node_modules/ml-distance/src/distances/fidelity.js","webpack:///./node_modules/ml-distance/src/distances/gower.js","webpack:///./node_modules/ml-distance/src/distances/harmonicMean.js","webpack:///./node_modules/ml-distance/src/distances/hellinger.js","webpack:///./node_modules/ml-distance/src/distances/innerProduct.js","webpack:///./node_modules/ml-distance/src/distances/jeffreys.js","webpack:///./node_modules/ml-distance/src/distances/jensenDifference.js","webpack:///./node_modules/ml-distance/src/distances/jensenShannon.js","webpack:///./node_modules/ml-distance/src/distances/kdivergence.js","webpack:///./node_modules/ml-distance/src/distances/kullbackLeibler.js","webpack:///./node_modules/ml-distance/src/distances/kumarHassebrook.js","webpack:///./node_modules/ml-distance/src/distances/kumarJohnson.js","webpack:///./node_modules/ml-distance/src/distances/lorentzian.js","webpack:///./node_modules/ml-distance/src/distances/manhattan.js","webpack:///./node_modules/ml-distance/src/distances/matusita.js","webpack:///./node_modules/ml-distance/src/distances/minkowski.js","webpack:///./node_modules/ml-distance/src/distances/neyman.js","webpack:///./node_modules/ml-distance/src/distances/pearson.js","webpack:///./node_modules/ml-distance/src/distances/probabilisticSymmetric.js","webpack:///./node_modules/ml-distance/src/distances/ruzicka.js","webpack:///./node_modules/ml-distance/src/distances/soergel.js","webpack:///./node_modules/ml-distance/src/distances/sorensen.js","webpack:///./node_modules/ml-distance/src/distances/squared.js","webpack:///./node_modules/ml-distance/src/distances/taneja.js","webpack:///./node_modules/ml-distance/src/distances/tanimoto.js","webpack:///./node_modules/ml-distance/src/distances/topsoe.js","webpack:///./node_modules/ml-tree-similarity/src/index.js","webpack:///./node_modules/ml-distance/src/distances/waveHedges.js","webpack:///./node_modules/ml-distance/src/similarities.js","webpack:///./node_modules/ml-distance/src/similarities/dice.js","webpack:///./node_modules/ml-distance/src/similarities/intersection.js","webpack:///./node_modules/ml-distance/src/similarities/jaccard.js","webpack:///./node_modules/ml-distance/src/similarities/kulczynski.js","webpack:///./node_modules/ml-distance/src/similarities/motyka.js","webpack:///./node_modules/ml-distance/src/similarities/pearson.js","webpack:///./node_modules/ml-distance/src/similarities/squaredChord.js","webpack:///./node_modules/ml-performance/src/index.js","webpack:///./node_modules/ml-performance/src/measures.js","webpack:///./node_modules/ml-savitzky-golay/src/index.js","webpack:///./node_modules/ml-savitzky-golay-generalized/src/index.js","webpack:///./node_modules/ml-bit-array/src/index.js","webpack:///./node_modules/ml-bit-array/src/creator.js","webpack:///./node_modules/ml-array-utils/src/index.js","webpack:///./node_modules/ml-array-utils/src/ArrayUtils.js","webpack:///./node_modules/ml-array-utils/src/getEquallySpaced.js","webpack:///./node_modules/ml-array-utils/src/snv.js","webpack:///./node_modules/ml-array-mode/src/index.js","webpack:///./node_modules/ml-array-standard-deviation/src/index.js"],"names":["default","wrap","solve","inverse","linearDependencies","squaredEuclidean","p","q","d","i","length","euclidean","Math","sqrt","module","exports","squared","BaseRegression","constructor","new","target","Error","predict","x","_predict","Array","isArray","y","TypeError","train","toString","toLaTeX","score","n","y2","xSum","ySum","chi2","rmsd","xSquared","ySquared","xY","r","r2","BaseView","matrix","rows","columns","Symbol","species","Matrix","array","require","nRows","nColumns","arguments","isMatrix","clone","Number","isInteger","RangeError","concat","set","rowIndex","columnIndex","value","get","removeRow","index","splice","addRow","undefined","removeColumn","addColumn","checkRowIndex","checkColumnIndex","checkRowVector","checkColumnVector","checkIndices","checkRowIndices","checkColumnIndices","checkRange","getRange","sumByRow","sumByColumn","sumAll","outer","max","vector","to1DArray","rowIndices","columnIndices","row","column","rowOut","some","from","columnOut","c","startRow","endRow","startColumn","endColumn","checkNumber","to","arr","sum","zeros","j","v","name","AbstractMatrix","superCtor","Object","from1DArray","newRows","newColumns","newData","newMatrix","rowVector","columnVector","empty","fill","ones","rand","rng","random","randInt","maxValue","floor","eye","min","diag","data","l","matrix1","matrix2","checkMatrix","result","klass","size","apply","callback","ii","jj","call","to2DArray","copy","isRowVector","isColumnVector","isVector","isSquare","isSymmetric","repeat","rowRep","colRep","setSubMatrix","neg","mulS","getRow","getRowVector","setRow","swapRows","row1","row2","temp","getColumn","getColumnVector","setColumn","swapColumns","column1","column2","addRowVector","subRowVector","mulRowVector","divRowVector","addColumnVector","subColumnVector","mulColumnVector","divColumnVector","mulRow","mulColumn","maxIndex","idx","minIndex","maxRow","maxRowIndex","minRow","minRowIndex","maxColumn","maxColumnIndex","minColumn","minColumnIndex","by","mean","prod","norm","type","cumulativeSum","dot","vector2","vector1","mmul","other","console","warn","m","Bcolj","k","s","strassen2x2","a11","b11","a12","b12","a21","b21","a22","b22","m1","m2","m3","m4","m5","m6","m7","c00","c01","c10","c11","strassen3x3","a00","a01","a02","a10","a20","b00","b01","b02","b10","b20","m8","m9","m10","m11","m12","m13","m14","m15","m16","m17","m18","m19","m20","m21","m22","m23","c02","c12","c20","c21","c22","mmulStrassen","r1","c1","c2","embed","mat","cols","resultat","blockMult","a","b","halfRows","parseInt","halfCols","subMatrix","add","sub","scaleRows","scaled","scaleColumns","kroneckerProduct","transpose","sortRows","compareFunction","compareNumbers","sort","sortColumns","subMatrixRow","indices","subMatrixColumn","selection","trace","transposeView","MatrixTransposeView","rowView","MatrixRowView","columnView","MatrixColumnView","flipRowView","MatrixFlipRowView","flipColumnView","MatrixFlipColumnView","subMatrixView","MatrixSubView","selectionView","MatrixSelectionView","rowSelectionView","MatrixRowSelectionView","columnSelectionView","MatrixColumnSelectionView","det","subMatrix0","subMatrix1","subMatrix2","LuDecomposition","determinant","pseudoInverse","threshold","EPSILON","svdSolution","SvDecomposition","autoTranspose","U","leftSingularVectors","V","rightSingularVectors","diagonal","abs","prototype","identity","negate","tensorProduct","inplaceOperator","inplaceOperatorScalar","inplaceOperatorMatrix","staticOperator","inplaceMethod","staticMethod","inplaceMethodWithArgs","staticMethodWithArgs","inplaceMethodWithOneArgScalar","inplaceMethodWithOneArgMatrix","inplaceMethodWithOneArg","staticMethodWithOneArg","operators","eval2","eval","operator","inplaceOp","fillTemplateFunction","op","inplaceOpS","inplaceOpM","staticOp","methods","forEach","mathMethod","push","method","inplaceMeth","staticMeth","methodsWithArgs","methodWithArg","args","inplaceMethWithArgs","staticMethWithArgs","tmplVar","inplaceMethod2","inplaceMethodS","inplaceMethodM","staticMethod2","template","values","replace","RegExp","input","SingularValueDecomposition","options","WrapperMatrix2D","computeLeftSingularVectors","computeRightSingularVectors","wantu","Boolean","wantv","swapped","aux","nu","ni","e","work","si","nct","nrt","mrc","t","pp","iter","eps","kase","alpha","MIN_VALUE","isNaN","ks","f","cs","sn","scale","sp","spm1","epm1","sk","ek","shift","g","tmp","Y","scols","Ls","VL","vrows","urows","VLU","solveForDiagonal","vcols","X","ucols","condition","norm2","rank","tol","diagonalMatrix","arrayStat","Infinity","minMax","entropy","l1","l2","log","dimension","theMean","N","theSum","product","theProduct","standardDeviation","means","unbiased","vari","variance","sum1","sum2","median","medians","mode","modes","itemCount","itemArray","count","indexOf","skewness","skew","s2","s3","dev","pow","kurtosis","kurt","s4","standardError","samples","standardDeviations","standardErrors","sqrtN","covariance","scatter","divisor","cov","correlation","scores","zScores","cor","standardize","center","inPlace","resultRow","sourceRow","weightedVariance","weights","z","w","weightedMean","weightSum","weightedCovariance","s1","factor","weightedScatter","lu","pivotVector","pivotSign","LUcolj","kmax","LU","isSingular","col","lowerTriangularMatrix","upperTriangularMatrix","pivotPermutationVector","slice","hypotenuse","getFilled2DArray","Heap","Cluster","children","distance","cut","root","list","ans","group","minGroups","heap","first","pop","child","toArray","traverse","cb","visit","GaussianKernel","PolynomialKernel","ANOVAKernel","CauchyKernel","ExponentialKernel","HistogramKernel","LaplacianKernel","MultiquadraticKernel","RationalKernel","SigmoidKernel","kernelType","gaussian","rbf","polynomial","poly","anova","cauchy","exponential","histogram","laplacian","multiquadratic","rational","sigmoid","mlp","Kernel","toLowerCase","KernelConstructor","kernelFunction","compute","inputs","landmarks","kernelMatrix","SimpleLinearRegression","slope","intercept","coefficients","regress","toJSON","computeX","precision","xFactor","absIntercept","load","json","slr","numerator","hasOwn","hasOwnProperty","toStr","defineProperty","gOPD","getOwnPropertyDescriptor","isPlainObject","obj","hasOwnConstructor","hasIsPrototypeOf","key","setProperty","enumerable","configurable","newValue","writable","getProperty","extend","src","copyIsArray","deep","DecisionTreeClassifier","DecisionTreeRegression","rescale","output","currentMin","currentMax","minValue","autoMinMax","WrapperMatrix1D","_calculateIndex","QrDecomposition","qr","rdiag","nrm","QR","Rdiag","isFullRank","orthogonalMatrix","Utils","gainFunctions","gini","giniGain","regression","regressionError","splitFunctions","TreeNode","kind","gainFunction","splitFunction","minNumSamples","maxDepth","bestSplit","XTranspose","bestGain","check","currentFeature","splitValues","featureSplit","currentSplitVal","splitted","split","gain","maxGain","splitValue","lesser","greater","zip","calculatePrediction","distribution","toDiscreteDistribution","getNumberOfClasses","currentDepth","parentGain","splitColumn","splittedMatrix","matrixSplitter","lesserX","greaterX","left","right","lesserY","greaterY","classify","setNodeParameters","node","RandomForestBase","model","replacement","maxFeatures","nEstimators","treeOptions","isClassifier","seed","indexes","useSampleBagging","Estimator","DTClassifier","DTRegression","estimators","map","est","trainingSet","trainingValues","checkFloat","res","examplesBaggingWithReplacement","featureBagging","usedIndex","toPredict","predictionValues","predictions","arithmeticMean","geometricMean","mul","logMean","lnsum","grandMean","truncatedMean","percent","alreadySorted","harmonicMean","contraHarmonicMean","half","theVariance","robustMeanAndStdev","stdev","averageDeviations","quartiles","quart","q1","ceil","q2","q3","pooledStandardDeviation","pooledVariance","mean1","mean2","weightedStandardDeviation","standardDev","util","ClusterLeaf","inherits","distanceMatrix","distanceFn","calculateDistanceMatrix","updateClusterID","updateCenters","hasConverged","dist","centers","clusterID","distanceFunction","prevCenters","K","nDim","centersLen","dim","id","oldCenters","tolerance","XSAdd","Random","seedOrRandom","xsadd","randomGenerator","choice","low","high","randomSample","_createClass","defineProperties","props","descriptor","Constructor","protoProps","staticProps","_classCallCheck","instance","LOOP","FLOAT_MUL","multiply_uint32","nlo","nhi","XSadd","Date","now","state","Uint32Array","init","period_certification","next_state","getUint32","getFloat","_random","bind","sh1","sh2","sh3","separateClasses","features","classes","totalPerClasses","separatedClasses","currentIndex","pow2array","featureNormalize","initializeMatrices","dataset","Stat","std","elem","ConfusionMatrix","labels","fromLabels","actual","predicted","distinctLabels","Set","actualIdx","predictedIdx","getMatrix","getLabels","getTotalCount","getTrueCount","getFalseCount","getTruePositiveCount","label","getIndex","getTrueNegativeCount","getFalsePositiveCount","getFalseNegativeCount","getPositiveCount","getNegativeCount","getTruePositiveRate","getTrueNegativeRate","getPositivePredictiveValue","TP","getNegativePredictiveValue","TN","getFalseNegativeRate","getFalsePositiveRate","getFalseDiscoveryRate","FP","getFalseOmissionRate","FN","getF1Score","getMatthewsCorrelationCoefficient","getInformedness","getMarkedness","getConfusionTable","getAccuracy","correct","incorrect","getCount","actualIndex","predictedIndex","accuracy","total","ACTIVATION_FUNCTIONS","Layer","inputSize","outputSize","regularization","epsilon","activation","activationParam","selectedFunction","params","actFunction","val","derFunction","derivate","activationFunction","W","forward","backpropagation","delta","dW","db","sumCol","aCopy","update","sumRow","dictOutputs","outputs","logistic","exp","expELU","param","softExponential","softExponentialPrime","tanh","arctan","atan","softsign","relu","softplus","bent","sinusoid","sin","cos","sinc","NodeSquare","som","neighbors","adjustWeights","learningRate","influence","getDistance","otherNode","getDistanceTorus","distX","distY","gridDim","getNeighbors","xy","torus","nodes","getPos","element","bestNeighbor","direction","dist1","dist2","simA","simB","getPosition","NLR","PotentialRegression","NonLinearRegression","PolynomialRegression","degree","powers","_toFormula","isLaTeX","sup","closeSup","times","fn","str","charAt","pr","F","FT","A","B","newArray","primeFinder","nextPrime","largestPrime","FREE","FULL","REMOVED","defaultInitialCapacity","defaultMinLoadFactor","defaultMaxLoadFactor","HashTable","table","minLoadFactor","maxLoadFactor","distinct","freeEntries","lowWaterMark","highWaterMark","initialCapacity","capacity","chooseHighWaterMark","indexOfKey","indexOfInsertion","newCapacity","chooseGrowCapacity","rehash","remove","noRehash","maybeShrinkCapacity","delete","chooseShrinkCapacity","containsKey","hash","decrement","containsValue","indexOfValue","ensureCapacity","minCapacity","oldCapacity","oldTable","oldValues","oldState","newTable","newValues","newState","chooseLowWaterMark","forEachKey","forEachValue","forEachPair","minLoad","maxLoad","haystack","needle","comparator","mid","cmp","numberIsNan","assertNum","asc","desc","similarity","czekanowskiSimilarity","up","down","dice","intersection","jaccard","p1","p2","kulczynski","motyka","squaredChord","tanimoto","bitvector","inter","union","cosine","defaultOptions","arrayCase","len","cond","matrixCase","padArray","sqrError","mlCart","mlRandomForest","ML","PCA","HClust","KMeans","SVM","NaiveBayes","KNN","PLS","CrossValidation","RandomForestClassifier","FNN","SOM","Regression","MultivariateLinearRegression","PowerRegression","ExponentialRegression","TheilSenRegression","RobustPolynomialRegression","RandomForestRegression","levenbergMarquardt","SVD","EVD","CholeskyDecomposition","SparseMatrix","Distance","Similarity","Performance","savitzkyGolay","savitzkyGolayGeneralized","BitArray","binarySearch","numSort","ArrayUtils","MatrixUtil","ArrayStat","MatrixStat","Tree","assign","trainingLabels","useSVD","leftHandSide","rightHandSide","xrange","exception","range","dependenciesOneRow","error","thresholdValue","thresholdError","returnArray","results","Abis","svd","EigenvalueDecomposition","assumeSymmetric","tred2","tql2","H","ort","orthes","hqr2","realEigenvalues","imaginaryEigenvalues","eigenvectorMatrix","h","hh","dl1","c3","el1","tst1","nn","exshift","ra","sa","vr","vi","notlast","cdivres","cdiv","xr","xi","yr","yi","positiveDefinite","Lrowj","Lrowk","L","giniImpurity","squaredError","numberOfClasses","counts","probabilities","filter","splitsImpurity","splits","currentSplit","currentElement","ret","baseModel","trainingValue","engine","engines","mt19937","integer","autoSeed","Xr","toRet","has","GLOBAL_KEY","imul","ah","al","bh","bl","stringRepeat","String","pattern","nativeMath","proto","Int32Array","refreshData","temper","seedWithArray","source","sourceLength","previous","uses","next","getUseCount","discard","initial","generateEntropyArray","browserCrypto","crypto","getRandomValues","getTime","returnValue","int32","uint32","uint53","uint53Full","int53","int53Full","generate","addend","isPowerOfTwoMinusOne","bitmask","masking","downscaleToLoopCheckedRange","extendedRange","maximum","downscaleToRange","isEvenlyDivisibleByMaxInt32","upscaleWithHighMasking","upscaleToLoopCheckedRange","upscaleWithinU53","highRange","upscaleWithinI53AndLoopCheck","isFinite","realZeroToOneInclusive","realZeroToOneExclusive","real","multiply","multiplier","inclusive","bool","isLeastBitTrue","lessThan","probability","percentage","round","denominator","toInteger","number","convertSliceArgument","pick","begin","end","start","finish","returnUndefined","picker","shuffle","downTo","sample","population","sampleSize","tailLength","die","sideCount","dieCount","uuid4","zeroPad","string","zeroCount","DEFAULT_STRING_POOL","pool","hex","LOWER_HEX_POOL","lowerHex","upperHex","toUpperCase","upper","date","define","oldGlobal","noConflict","selectionMethods","arrayMean","arrayMedian","selectionMethod","window","matrixLib","isCovarianceMatrix","stdevs","S","_computeFromCovarianceMatrix","useCovarianceMatrix","_adjust","covarianceMatrix","div","singularValues","eigenvalues","nComponents","getExplainedVariance","getCumulativeVariance","explained","getEigenvectors","getEigenvalues","getStandardDeviations","getLoadings","evd","reverse","agnes","diana","simpleLink","cluster1","cluster2","disFun","completeLink","averageLink","centroidLink","wardLink","disFunc","isDistanceMatrix","dis","fdistance","sdistance","toFixed","dmin","clustered","int","diff","indCount","defaultCmp","heapify","heappop","heappush","heappushpop","heapreplace","insort","nlargest","nsmallest","updateItem","_siftdown","_siftup","lo","hi","item","lastelt","returnitem","_ref","_i","_j","_len","_ref1","_results","_results1","pos","los","startpos","newitem","parent","parentpos","childpos","endpos","rightpos","pushpop","peek","contains","clear","insert","top","front","factory","formatRegExp","format","isString","objects","inspect","join","JSON","stringify","_","isNull","isObject","deprecate","msg","isUndefined","global","process","noDeprecation","warned","deprecated","throwDeprecation","traceDeprecation","debugs","debugEnviron","debuglog","env","NODE_DEBUG","test","pid","opts","ctx","seen","stylize","stylizeNoColor","depth","colors","isBoolean","showHidden","_extend","customInspect","stylizeWithColor","formatValue","styles","styleType","style","arrayToHash","recurseTimes","isFunction","primitive","formatPrimitive","keys","visibleKeys","getOwnPropertyNames","isError","formatError","isRegExp","isDate","base","braces","toUTCString","formatArray","formatProperty","reduceToSingleString","simple","isNumber","match","line","substr","numLinesEst","reduce","prev","cur","ar","arg","isNullOrUndefined","isSymbol","re","objectToString","isPrimitive","isBuffer","o","pad","months","timestamp","time","getHours","getMinutes","getSeconds","getDate","getMonth","origin","prop","Function","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","setTimeout","clearTimeout","runTimeout","fun","runClearTimeout","marker","queue","draining","currentQueue","queueIndex","cleanUpNextTick","drainQueue","timeout","run","nextTick","Item","title","browser","argv","version","versions","noop","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","readUInt8","create","ctor","super_","TempCtor","x1","y1","x2","splitting","Ci","Cj","ndist","intrDist","tree","ind","M","clId","rebel","C","sG","spl","fData","sData","kmeans","maxIterations","withIterations","initialization","step","iterations","newCenters","converged","KMeansResult","kmeansGenerator","stepNumber","stepResult","computeInformation","centroids","MAX_VALUE","squaredDistance","similarityFunction","returnVector","nearestVector","listVectors","vectorIndex","maxSim","sim","minDist","mostDistant","kmeanspp","maxDist","minDistCent","nSamples","localTrials","firstCenterIdx","closestDistSquared","cumSumClosestDistSquared","cumSum","candidateIdx","candidates","distanceToCandidates","euclidianDistances","bestCandidate","bestPot","bestDistSquared","newDistSquared","newPot","PROB_TOLERANCE","randomChoice","valuesArr","getArray","randomIndex","distanceSymbol","clusters","nearest","centroid","enrichedCentroids","stat","maxPasses","kernel","alphaTol","whitening","kernelOptions","_trained","_loaded","D","alphas","b1","b2","passes","Ei","Ej","ai","aj","eta","numChange","_marginOnePrecomputed","newaj","nX","nY","nAlphas","_supportVectorIdx","predictOne","margin","marginOne","noWhitening","_applyWhitening","supportVectors","svm","whitened","sigma","constant","HistogramIntersectionKernel","RationalQuadraticKernel","E","GaussianNB","MultinomialNB","reload","calculateProbabilities","C1","PI","logPriorProbability","currentStd","getCurrentClass","modelName","currentCase","maxProbability","predictedClass","currentProbability","calculateLogProbability","C2","conditionalProbability","priorProbability","separateClass","classValues","matrixLog","kdTree","KDTree","isEuclidean","euclideanDistance","points","getSinglePrediction","knn","nearestPoints","pointsPerClass","maxPoints","lastElement","currentClass","currentPoints","Node","metric","dimensions","restoreParent","buildTree","toJSONImpl","point","maxNodes","maxDistance","bestNodes","BinaryHeap","nearestSearch","ownDistance","linearPoint","bestChild","linearDistance","otherChild","saveNode","content","dest","scoreFunction","bubbleUp","sinkDown","parentN","elemScore","child2N","child1N","swap","child1","child1Score","child2","child2Score","KOPLS","meanX","stdDevX","meanY","stdDevY","PBQ","R2X","scaleMethod","latentVectors","rx","cx","ry","cy","ssqXcal","sumOfSquaresY","T","P","Q","transposeX","transposeY","tIndex","maxSumColIndex","mulM","uIndex","t1","u","num","den","pnorm","ssqYcal","YLoadingMat","SigmaPow","YScoreMat","predScoreMat","YOrthLoadingVec","YOrthEigen","YOrthScoreMat","toNorm","TURegressionCoeff","kernelX","orthogonalComp","predictiveComp","predictiveComponents","orthogonalComponents","Identity","Sigma","YOrthScoreNorm","TpiPrime","CoTemp","SoTemp","toiPrime","ITo","lastScoreMat","lastTpPrime","KTestTrain","YOrthScoreVector","scoreMatPrime","p3","prediction","predYOrthVectors","CV","combinations","leaveOneOut","Classifier","classifierOptions","leavePOut","getDistinct","confusionMatrix","initMatrix","gen","allIdx","testIdx","trainIdx","validateWithCallback","validate","kFold","current","folds","randi","getTrainTest","testFeatures","trainFeatures","testLabels","trainLabels","classifier","predictedLabels","updateConfusionMatrix","amd","createCommonjsModule","runtime","Op","$Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","regeneratorRuntime","innerFn","outerFn","self","tryLocsList","protoGenerator","Generator","generator","context","Context","_invoke","makeInvokeMethod","tryCatch","err","GenStateSuspendedStart","GenStateSuspendedYield","GenStateExecuting","GenStateCompleted","ContinueSentinel","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","getProto","getPrototypeOf","NativeIteratorPrototype","Gp","displayName","defineIteratorMethods","isGeneratorFunction","genFun","mark","setPrototypeOf","__proto__","awrap","__await","AsyncIterator","invoke","resolve","reject","record","Promise","then","unwrapped","previousPromise","enqueue","callInvokeWithMethodAndArg","async","done","doneResult","delegate","delegateResult","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","return","info","resultName","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","resetTryEntry","completion","reset","object","iterable","iteratorMethod","skipTempReset","stop","rootEntry","rootRecord","rval","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","thrown","delegateYield","hadRuntime","oldRuntime","runtimeModule","regenerator","_callee","twiddle","_callee$","_context","OutputLayer","FeedForwardNeuralNetworks","hiddenLayers","dicts","layers","buildNetwork","propagate","NodeHexagonal","fields","randomizer","squareEuclidean","gridType","numWeights","converters","getConverters","extractor","creator","nodeType","hx","distanceMethod","getMaxDistance","findBMU","adjust","iterationCount","startLearningRate","mapRadius","algorithmMethod","_initNodes","loadModel","export","exportModel","includeDistance","initNodes","setTraining","convertedSet","numIterations","timeConstant","trainOne","neighbourhoodRadius","trainingSetFactor","getRandomValue","bmu","_findBestMatchingUnit","now2","radiusLimit","xMin","xMax","yMin","yMax","theX","theY","getConvertedNodes","findBestMatchingUnit","candidate","lowest","computePosition","getQuantizationError","fit","getFit","normalizers","denormalizers","getNormalizer","getDenormalizer","normalizer","denormalizer","zero","one","hX","getDistanceHexagonal","distZ","maybeToPrecision","digits","toPrecision","checkArraySize","er","yl","linear","newInputs","xl","statistics","beta","fittedValues","residuals","addM","ri","stdError","stdErrorMatrix","stdErrors","tStats","summary","regressionStatistics","observations","variables","tStat","lambda","computeCoefficient","KernelRidgeRegression","order","PolynomialFitRegression2D","examples","scaleX1","scaleX2","scaleY","limit","powColVector","qqs","qqs1","power","theilSen","slopes","medianSlope","cuts","robustPolynomial","tuples","getRandomTuples","tuple","calcCoefficients","residual","residualsMedian","counter","mlMatrix","errorCalculation","parameters","parameterizedFunction","func","gradientFunction","evaluatedData","gradientDifference","paramFunction","auxParams","funcParam","matrixFunction","damping","gradientFunc","matrixFunc","inverseMatrix","errorTolerance","initialValues","dataLen","iteration","parameterValues","parameterError","_init","elements","symmetric","forEachNonZero","bandWidth","isBanded","width","cardinality","v1","v2","getNonZeros","setThreshold","newThreshold","trans","sortAsc","primeNumbers","additiveSymmetric","avg","bhattacharyya","canberra","chebyshev","clark","czekanowski","divergence","fidelity","gower","hellinger","innerProduct","jeffreys","jensenDifference","jensenShannon","kdivergence","kullbackLeibler","kumarHassebrook","kumarJohnson","lorentzian","manhattan","matusita","minkowski","neyman","pearson","probabilisticSymmetric","ruzicka","soergel","sorensen","taneja","topsoe","waveHedges","czekanowskiDistance","tanimotoS","createTree","minWindow","gamma","Atree","Btree","calc","diceD","intersectionD","jaccardD","kulczynskiD","motykaD","avgA","avgB","newA","newB","squaredChordD","measures","isDistance","predP","all","pred","targ","cutoffs","fp","tp","nPos","nNeg","currentPred","nTp","nFp","tn","nPosPred","nNegPred","getMeasure","measure","getAURC","auc","getAUDC","getDistribution","cutLength","cutLow","cutHigh","interval","xLabels","interValues","intraValues","interCumPercent","intraCumPercent","nTP","currentTP","nFP","currentFP","thisTP","thisFP","names","acc","fpr","tpr","fnr","tnr","ppv","npv","pcfall","pcmiss","lift","rpp","rnp","windowSize","derivative","padValue","SavitzkyGolay","J","inic","Jtranspose","Jinv","np","fullWeights","hs","constantH","wg1","wg2","d1","d2","getHs","wg","GramPoly","Grampoly","GenFact","gf","Weight","eightBits","and","arr1","arr2","or","xor","not","getBit","mask","setBit","toBinaryString","parseBinaryString","toHexString","parseHexString","toDebug","binary","getEquallySpacedData","SNV","coordArrayToPoints","pointsArr","coordArrayToCoordMatrix","coordinatesArray","currentPoint","coordMatrixToCoordArray","coordMatrix","coodinatesArray","resultMatrix","pointsToCoordArray","applyDotProduct","firstVector","secondVector","largestVector","smallestVector","difference","dotProductApplied","coordMatrixToPoints","pointsToCoordMatrix","xLength","variant","numberOfPoints","getEquallySpacedSlot","getEquallySpacedSmooth","halfStep","initialOriginalStep","lastOriginalStep","previousX","previousY","nextX","nextY","currentValue","sumAtMin","sumAtMax","getSlope","x0","y0","main","integral","lastStep","frontOutsideSpectra","backOutsideSpectra","maxCount"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,mCAA2B,0BAA0B,EAAE;AACvD,yCAAiC,eAAe;AAChD;AAC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MAAMhX,CAAN,CAAX;AACH;AACJ;;AAED,WAAOuH,QAAP;AACH,C;;;;;;;;;;;;kBCzBuB8T,iB;;AAVxB;;;;;;AAEA;;;;;;;;AAQe,SAASA,iBAAT,CAA2BxE,MAA3B,EAAmCK,UAAU,EAA7C,EAAiD;AAC5D,SAAO/W,KAAKC,IAAL,CAAU,+BAASyW,MAAT,EAAiBK,OAAjB,CAAV,CAAP;AACH,C","file":"ml.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"ML\"] = factory();\n\telse\n\t\troot[\"ML\"] = factory();\n})(typeof self !== 'undefined' ? self : this, function() {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 57);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 3ceba11ba2297c055a6e","export { default, default as Matrix } from './matrix';\nexport { default as abstractMatrix } from './abstractMatrix';\n\nexport { wrap } from './wrap/wrap';\nexport { default as WrapperMatrix2D } from './wrap/WrapperMatrix2D';\nexport { default as WrapperMatrix1D } from './wrap/WrapperMatrix1D';\n\nexport { solve, inverse } from './decompositions';\nexport { linearDependencies } from './linearDependencies';\nexport {\n default as SingularValueDecomposition,\n default as SVD\n} from './dc/svd.js';\nexport {\n default as EigenvalueDecomposition,\n default as EVD\n} from './dc/evd.js';\nexport {\n default as CholeskyDecomposition,\n default as CHO\n} from './dc/cholesky.js';\nexport { default as LuDecomposition, default as LU } from './dc/lu.js';\nexport { default as QrDecomposition, default as QR } from './dc/qr.js';\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/index.js","'use strict';\n\nfunction squaredEuclidean(p, q) {\n var d = 0;\n for (var i = 0; i < p.length; i++) {\n d += (p[i] - q[i]) * (p[i] - q[i]);\n }\n return d;\n}\n\nfunction euclidean(p, q) {\n return Math.sqrt(squaredEuclidean(p, q));\n}\n\nmodule.exports = euclidean;\neuclidean.squared = squaredEuclidean;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance-euclidean/euclidean.js","export {default as maybeToPrecision} from './maybeToPrecision';\nexport {default as checkArrayLength} from './checkArrayLength';\n\nexport default class BaseRegression {\n constructor() {\n if (new.target === BaseRegression) {\n throw new Error('BaseRegression must be subclassed');\n }\n }\n\n predict(x) {\n if (typeof x === 'number') {\n return this._predict(x);\n } else if (Array.isArray(x)) {\n const y = new Array(x.length);\n for (let i = 0; i < x.length; i++) {\n y[i] = this._predict(x[i]);\n }\n return y;\n } else {\n throw new TypeError('x must be a number or array');\n }\n }\n\n _predict() {\n throw new Error('_predict must be implemented');\n }\n\n train() {\n //Do nothing for this package\n }\n\n toString() {\n return '';\n }\n\n toLaTeX() {\n return '';\n }\n\n /**\n * Return the correlation coefficient of determination (r) and chi-square.\n * @param {Array} x\n * @param {Array} y\n * @return {object}\n */\n score(x, y) {\n if (!Array.isArray(x) || !Array.isArray(y) || x.length !== y.length) {\n throw new Error('x and y must be arrays of the same length');\n }\n\n const n = x.length;\n const y2 = new Array(n);\n for (let i = 0; i < n; i++) {\n y2[i] = this._predict(x[i]);\n }\n\n let xSum = 0;\n let ySum = 0;\n let chi2 = 0;\n let rmsd = 0;\n let xSquared = 0;\n let ySquared = 0;\n let xY = 0;\n for (let i = 0; i < n; i++) {\n xSum += y2[i];\n ySum += y[i];\n xSquared += y2[i] * y2[i];\n ySquared += y[i] * y[i];\n xY += y2[i] * y[i];\n if (y[i] !== 0) {\n chi2 += (y[i] - y2[i]) * (y[i] - y2[i]) / y[i];\n }\n rmsd = (y[i] - y2[i]) * (y[i] - y2[i]);\n }\n\n const r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum));\n\n return {\n r: r,\n r2: r * r,\n chi2: chi2,\n rmsd: rmsd * rmsd / n\n };\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-regression-base/src/index.js","import AbstractMatrix from '../abstractMatrix';\nimport Matrix from '../matrix';\n\nexport default class BaseView extends AbstractMatrix() {\n constructor(matrix, rows, columns) {\n super();\n this.matrix = matrix;\n this.rows = rows;\n this.columns = columns;\n }\n\n static get [Symbol.species]() {\n return Matrix;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/views/base.js","'use strict';\n\nexports.array = require('./array');\nexports.matrix = require('./matrix');\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-stat/index.js","import AbstractMatrix from './abstractMatrix';\nimport {\n checkColumnIndex,\n checkColumnVector,\n checkRowIndex,\n checkRowVector\n} from './util';\n\nexport default class Matrix extends AbstractMatrix(Array) {\n constructor(nRows, nColumns) {\n var i;\n if (arguments.length === 1 && typeof nRows === 'number') {\n return new Array(nRows);\n }\n if (Matrix.isMatrix(nRows)) {\n return nRows.clone();\n } else if (Number.isInteger(nRows) && nRows > 0) {\n // Create an empty matrix\n super(nRows);\n if (Number.isInteger(nColumns) && nColumns > 0) {\n for (i = 0; i < nRows; i++) {\n this[i] = new Array(nColumns);\n }\n } else {\n throw new TypeError('nColumns must be a positive integer');\n }\n } else if (Array.isArray(nRows)) {\n // Copy the values from the 2D array\n const matrix = nRows;\n nRows = matrix.length;\n nColumns = matrix[0].length;\n if (typeof nColumns !== 'number' || nColumns === 0) {\n throw new TypeError(\n 'Data must be a 2D array with at least one element'\n );\n }\n super(nRows);\n for (i = 0; i < nRows; i++) {\n if (matrix[i].length !== nColumns) {\n throw new RangeError('Inconsistent array dimensions');\n }\n this[i] = [].concat(matrix[i]);\n }\n } else {\n throw new TypeError(\n 'First argument must be a positive number or an array'\n );\n }\n this.rows = nRows;\n this.columns = nColumns;\n return this;\n }\n\n set(rowIndex, columnIndex, value) {\n this[rowIndex][columnIndex] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this[rowIndex][columnIndex];\n }\n\n /**\n * Removes a row from the given index\n * @param {number} index - Row index\n * @return {Matrix} this\n */\n removeRow(index) {\n checkRowIndex(this, index);\n if (this.rows === 1) {\n throw new RangeError('A matrix cannot have less than one row');\n }\n this.splice(index, 1);\n this.rows -= 1;\n return this;\n }\n\n /**\n * Adds a row at the given index\n * @param {number} [index = this.rows] - Row index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n addRow(index, array) {\n if (array === undefined) {\n array = index;\n index = this.rows;\n }\n checkRowIndex(this, index, true);\n array = checkRowVector(this, array, true);\n this.splice(index, 0, array);\n this.rows += 1;\n return this;\n }\n\n /**\n * Removes a column from the given index\n * @param {number} index - Column index\n * @return {Matrix} this\n */\n removeColumn(index) {\n checkColumnIndex(this, index);\n if (this.columns === 1) {\n throw new RangeError('A matrix cannot have less than one column');\n }\n for (var i = 0; i < this.rows; i++) {\n this[i].splice(index, 1);\n }\n this.columns -= 1;\n return this;\n }\n\n /**\n * Adds a column at the given index\n * @param {number} [index = this.columns] - Column index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n addColumn(index, array) {\n if (typeof array === 'undefined') {\n array = index;\n index = this.columns;\n }\n checkColumnIndex(this, index, true);\n array = checkColumnVector(this, array);\n for (var i = 0; i < this.rows; i++) {\n this[i].splice(index, 0, array[i]);\n }\n this.columns += 1;\n return this;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/matrix.js","import Matrix from './matrix';\n\n/**\n * @private\n * Check that a row index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexport function checkRowIndex(matrix, index, outer) {\n var max = outer ? matrix.rows : matrix.rows - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Row index out of range');\n }\n}\n\n/**\n * @private\n * Check that a column index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexport function checkColumnIndex(matrix, index, outer) {\n var max = outer ? matrix.columns : matrix.columns - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Column index out of range');\n }\n}\n\n/**\n * @private\n * Check that the provided vector is an array with the right length\n * @param {Matrix} matrix\n * @param {Array|Matrix} vector\n * @return {Array}\n * @throws {RangeError}\n */\nexport function checkRowVector(matrix, vector) {\n if (vector.to1DArray) {\n vector = vector.to1DArray();\n }\n if (vector.length !== matrix.columns) {\n throw new RangeError(\n 'vector size must be the same as the number of columns'\n );\n }\n return vector;\n}\n\n/**\n * @private\n * Check that the provided vector is an array with the right length\n * @param {Matrix} matrix\n * @param {Array|Matrix} vector\n * @return {Array}\n * @throws {RangeError}\n */\nexport function checkColumnVector(matrix, vector) {\n if (vector.to1DArray) {\n vector = vector.to1DArray();\n }\n if (vector.length !== matrix.rows) {\n throw new RangeError('vector size must be the same as the number of rows');\n }\n return vector;\n}\n\nexport function checkIndices(matrix, rowIndices, columnIndices) {\n return {\n row: checkRowIndices(matrix, rowIndices),\n column: checkColumnIndices(matrix, columnIndices)\n };\n}\n\nexport function checkRowIndices(matrix, rowIndices) {\n if (typeof rowIndices !== 'object') {\n throw new TypeError('unexpected type for row indices');\n }\n\n var rowOut = rowIndices.some((r) => {\n return r < 0 || r >= matrix.rows;\n });\n\n if (rowOut) {\n throw new RangeError('row indices are out of range');\n }\n\n if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices);\n\n return rowIndices;\n}\n\nexport function checkColumnIndices(matrix, columnIndices) {\n if (typeof columnIndices !== 'object') {\n throw new TypeError('unexpected type for column indices');\n }\n\n var columnOut = columnIndices.some((c) => {\n return c < 0 || c >= matrix.columns;\n });\n\n if (columnOut) {\n throw new RangeError('column indices are out of range');\n }\n if (!Array.isArray(columnIndices)) columnIndices = Array.from(columnIndices);\n\n return columnIndices;\n}\n\nexport function checkRange(matrix, startRow, endRow, startColumn, endColumn) {\n if (arguments.length !== 5) {\n throw new RangeError('expected 4 arguments');\n }\n checkNumber('startRow', startRow);\n checkNumber('endRow', endRow);\n checkNumber('startColumn', startColumn);\n checkNumber('endColumn', endColumn);\n if (\n startRow > endRow ||\n startColumn > endColumn ||\n startRow < 0 ||\n startRow >= matrix.rows ||\n endRow < 0 ||\n endRow >= matrix.rows ||\n startColumn < 0 ||\n startColumn >= matrix.columns ||\n endColumn < 0 ||\n endColumn >= matrix.columns\n ) {\n throw new RangeError('Submatrix indices are out of range');\n }\n}\n\nexport function getRange(from, to) {\n var arr = new Array(to - from + 1);\n for (var i = 0; i < arr.length; i++) {\n arr[i] = from + i;\n }\n return arr;\n}\n\nexport function sumByRow(matrix) {\n var sum = Matrix.zeros(matrix.rows, 1);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j));\n }\n }\n return sum;\n}\n\nexport function sumByColumn(matrix) {\n var sum = Matrix.zeros(1, matrix.columns);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum.set(0, j, sum.get(0, j) + matrix.get(i, j));\n }\n }\n return sum;\n}\n\nexport function sumAll(matrix) {\n var v = 0;\n for (var i = 0; i < matrix.rows; i++) {\n for (var j = 0; j < matrix.columns; j++) {\n v += matrix.get(i, j);\n }\n }\n return v;\n}\n\nfunction checkNumber(name, value) {\n if (typeof value !== 'number') {\n throw new TypeError(`${name} must be a number`);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/util.js","import rescale from 'ml-array-rescale';\n\nimport LuDecomposition from './dc/lu';\nimport SvDecomposition from './dc/svd';\nimport {\n checkRowVector, checkRowIndex, checkColumnIndex, checkColumnVector,\n checkRange, checkIndices,\n sumByRow, sumByColumn, sumAll\n} from './util';\nimport MatrixTransposeView from './views/transpose';\nimport MatrixRowView from './views/row';\nimport MatrixSubView from './views/sub';\nimport MatrixSelectionView from './views/selection';\nimport MatrixRowSelectionView from './views/rowSelection';\nimport MatrixColumnSelectionView from './views/columnSelection';\nimport MatrixColumnView from './views/column';\nimport MatrixFlipRowView from './views/flipRow';\nimport MatrixFlipColumnView from './views/flipColumn';\n\nexport default function AbstractMatrix(superCtor) {\n if (superCtor === undefined) superCtor = Object;\n\n /**\n * Real matrix\n * @class Matrix\n * @param {number|Array|Matrix} nRows - Number of rows of the new matrix,\n * 2D array containing the data or Matrix instance to clone\n * @param {number} [nColumns] - Number of columns of the new matrix\n */\n class Matrix extends superCtor {\n static get [Symbol.species]() {\n return this;\n }\n\n /**\n * Constructs a Matrix with the chosen dimensions from a 1D array\n * @param {number} newRows - Number of rows\n * @param {number} newColumns - Number of columns\n * @param {Array} newData - A 1D array containing data for the matrix\n * @return {Matrix} - The new matrix\n */\n static from1DArray(newRows, newColumns, newData) {\n var length = newRows * newColumns;\n if (length !== newData.length) {\n throw new RangeError('Data length does not match given dimensions');\n }\n var newMatrix = new this(newRows, newColumns);\n for (var row = 0; row < newRows; row++) {\n for (var column = 0; column < newColumns; column++) {\n newMatrix.set(row, column, newData[row * newColumns + column]);\n }\n }\n return newMatrix;\n }\n\n /**\n * Creates a row vector, a matrix with only one row.\n * @param {Array} newData - A 1D array containing data for the vector\n * @return {Matrix} - The new matrix\n */\n static rowVector(newData) {\n var vector = new this(1, newData.length);\n for (var i = 0; i < newData.length; i++) {\n vector.set(0, i, newData[i]);\n }\n return vector;\n }\n\n /**\n * Creates a column vector, a matrix with only one column.\n * @param {Array} newData - A 1D array containing data for the vector\n * @return {Matrix} - The new matrix\n */\n static columnVector(newData) {\n var vector = new this(newData.length, 1);\n for (var i = 0; i < newData.length; i++) {\n vector.set(i, 0, newData[i]);\n }\n return vector;\n }\n\n /**\n * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns).\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static empty(rows, columns) {\n return new this(rows, columns);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be set to zero.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static zeros(rows, columns) {\n return this.empty(rows, columns).fill(0);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be set to one.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static ones(rows, columns) {\n return this.empty(rows, columns).fill(1);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be randomly set.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @param {function} [rng=Math.random] - Random number generator\n * @return {Matrix} The new matrix\n */\n static rand(rows, columns, rng) {\n if (rng === undefined) rng = Math.random;\n var matrix = this.empty(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n matrix.set(i, j, rng());\n }\n }\n return matrix;\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be random integers.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @param {number} [maxValue=1000] - Maximum value\n * @param {function} [rng=Math.random] - Random number generator\n * @return {Matrix} The new matrix\n */\n static randInt(rows, columns, maxValue, rng) {\n if (maxValue === undefined) maxValue = 1000;\n if (rng === undefined) rng = Math.random;\n var matrix = this.empty(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n var value = Math.floor(rng() * maxValue);\n matrix.set(i, j, value);\n }\n }\n return matrix;\n }\n\n /**\n * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0.\n * @param {number} rows - Number of rows\n * @param {number} [columns=rows] - Number of columns\n * @param {number} [value=1] - Value to fill the diagonal with\n * @return {Matrix} - The new identity matrix\n */\n static eye(rows, columns, value) {\n if (columns === undefined) columns = rows;\n if (value === undefined) value = 1;\n var min = Math.min(rows, columns);\n var matrix = this.zeros(rows, columns);\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, value);\n }\n return matrix;\n }\n\n /**\n * Creates a diagonal matrix based on the given array.\n * @param {Array} data - Array containing the data for the diagonal\n * @param {number} [rows] - Number of rows (Default: data.length)\n * @param {number} [columns] - Number of columns (Default: rows)\n * @return {Matrix} - The new diagonal matrix\n */\n static diag(data, rows, columns) {\n var l = data.length;\n if (rows === undefined) rows = l;\n if (columns === undefined) columns = rows;\n var min = Math.min(l, rows, columns);\n var matrix = this.zeros(rows, columns);\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, data[i]);\n }\n return matrix;\n }\n\n /**\n * Returns a matrix whose elements are the minimum between matrix1 and matrix2\n * @param {Matrix} matrix1\n * @param {Matrix} matrix2\n * @return {Matrix}\n */\n static min(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n var rows = matrix1.rows;\n var columns = matrix1.columns;\n var result = new this(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n /**\n * Returns a matrix whose elements are the maximum between matrix1 and matrix2\n * @param {Matrix} matrix1\n * @param {Matrix} matrix2\n * @return {Matrix}\n */\n static max(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n var rows = matrix1.rows;\n var columns = matrix1.columns;\n var result = new this(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n /**\n * Check that the provided value is a Matrix and tries to instantiate one if not\n * @param {*} value - The value to check\n * @return {Matrix}\n */\n static checkMatrix(value) {\n return Matrix.isMatrix(value) ? value : new this(value);\n }\n\n /**\n * Returns true if the argument is a Matrix, false otherwise\n * @param {*} value - The value to check\n * @return {boolean}\n */\n static isMatrix(value) {\n return (value != null) && (value.klass === 'Matrix');\n }\n\n /**\n * @prop {number} size - The number of elements in the matrix.\n */\n get size() {\n return this.rows * this.columns;\n }\n\n /**\n * Applies a callback for each element of the matrix. The function is called in the matrix (this) context.\n * @param {function} callback - Function that will be called with two parameters : i (row) and j (column)\n * @return {Matrix} this\n */\n apply(callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('callback must be a function');\n }\n var ii = this.rows;\n var jj = this.columns;\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n callback.call(this, i, j);\n }\n }\n return this;\n }\n\n /**\n * Returns a new 1D array filled row by row with the matrix values\n * @return {Array}\n */\n to1DArray() {\n var array = new Array(this.size);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n array[i * this.columns + j] = this.get(i, j);\n }\n }\n return array;\n }\n\n /**\n * Returns a 2D array containing a copy of the data\n * @return {Array}\n */\n to2DArray() {\n var copy = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n copy[i] = new Array(this.columns);\n for (var j = 0; j < this.columns; j++) {\n copy[i][j] = this.get(i, j);\n }\n }\n return copy;\n }\n\n /**\n * @return {boolean} true if the matrix has one row\n */\n isRowVector() {\n return this.rows === 1;\n }\n\n /**\n * @return {boolean} true if the matrix has one column\n */\n isColumnVector() {\n return this.columns === 1;\n }\n\n /**\n * @return {boolean} true if the matrix has one row or one column\n */\n isVector() {\n return (this.rows === 1) || (this.columns === 1);\n }\n\n /**\n * @return {boolean} true if the matrix has the same number of rows and columns\n */\n isSquare() {\n return this.rows === this.columns;\n }\n\n /**\n * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal\n */\n isSymmetric() {\n if (this.isSquare()) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j <= i; j++) {\n if (this.get(i, j) !== this.get(j, i)) {\n return false;\n }\n }\n }\n return true;\n }\n return false;\n }\n\n /**\n * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1\n * @abstract\n * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @param {number} value - The new value for the element\n * @return {Matrix} this\n */\n set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars\n throw new Error('set method is unimplemented');\n }\n\n /**\n * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4]\n * @abstract\n * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @return {number}\n */\n get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars\n throw new Error('get method is unimplemented');\n }\n\n /**\n * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of\n * rows of the matrix, and colRep times the number of columns of the matrix\n * @param {number} rowRep - Number of times the rows should be repeated\n * @param {number} colRep - Number of times the columns should be re\n * @return {Matrix}\n * @example\n * var matrix = new Matrix([[1,2]]);\n * matrix.repeat(2); // [[1,2],[1,2]]\n */\n repeat(rowRep, colRep) {\n rowRep = rowRep || 1;\n colRep = colRep || 1;\n var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep);\n for (var i = 0; i < rowRep; i++) {\n for (var j = 0; j < colRep; j++) {\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\n }\n }\n return matrix;\n }\n\n /**\n * Fills the matrix with a given value. All elements will be set to this value.\n * @param {number} value - New value\n * @return {Matrix} this\n */\n fill(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, value);\n }\n }\n return this;\n }\n\n /**\n * Negates the matrix. All elements will be multiplied by (-1)\n * @return {Matrix} this\n */\n neg() {\n return this.mulS(-1);\n }\n\n /**\n * Returns a new array from the given row index\n * @param {number} index - Row index\n * @return {Array}\n */\n getRow(index) {\n checkRowIndex(this, index);\n var row = new Array(this.columns);\n for (var i = 0; i < this.columns; i++) {\n row[i] = this.get(index, i);\n }\n return row;\n }\n\n /**\n * Returns a new row vector from the given row index\n * @param {number} index - Row index\n * @return {Matrix}\n */\n getRowVector(index) {\n return this.constructor.rowVector(this.getRow(index));\n }\n\n /**\n * Sets a row at the given index\n * @param {number} index - Row index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n setRow(index, array) {\n checkRowIndex(this, index);\n array = checkRowVector(this, array);\n for (var i = 0; i < this.columns; i++) {\n this.set(index, i, array[i]);\n }\n return this;\n }\n\n /**\n * Swaps two rows\n * @param {number} row1 - First row index\n * @param {number} row2 - Second row index\n * @return {Matrix} this\n */\n swapRows(row1, row2) {\n checkRowIndex(this, row1);\n checkRowIndex(this, row2);\n for (var i = 0; i < this.columns; i++) {\n var temp = this.get(row1, i);\n this.set(row1, i, this.get(row2, i));\n this.set(row2, i, temp);\n }\n return this;\n }\n\n /**\n * Returns a new array from the given column index\n * @param {number} index - Column index\n * @return {Array}\n */\n getColumn(index) {\n checkColumnIndex(this, index);\n var column = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n column[i] = this.get(i, index);\n }\n return column;\n }\n\n /**\n * Returns a new column vector from the given column index\n * @param {number} index - Column index\n * @return {Matrix}\n */\n getColumnVector(index) {\n return this.constructor.columnVector(this.getColumn(index));\n }\n\n /**\n * Sets a column at the given index\n * @param {number} index - Column index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n setColumn(index, array) {\n checkColumnIndex(this, index);\n array = checkColumnVector(this, array);\n for (var i = 0; i < this.rows; i++) {\n this.set(i, index, array[i]);\n }\n return this;\n }\n\n /**\n * Swaps two columns\n * @param {number} column1 - First column index\n * @param {number} column2 - Second column index\n * @return {Matrix} this\n */\n swapColumns(column1, column2) {\n checkColumnIndex(this, column1);\n checkColumnIndex(this, column2);\n for (var i = 0; i < this.rows; i++) {\n var temp = this.get(i, column1);\n this.set(i, column1, this.get(i, column2));\n this.set(i, column2, temp);\n }\n return this;\n }\n\n /**\n * Adds the values of a vector to each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n addRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Subtracts the values of a vector from each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n subRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a vector with each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n mulRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Divides the values of each row by those of a vector\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n divRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Adds the values of a vector to each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n addColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Subtracts the values of a vector from each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n subColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a vector with each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n mulColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Divides the values of each column by those of a vector\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n divColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a row with a scalar\n * @param {number} index - Row index\n * @param {number} value\n * @return {Matrix} this\n */\n mulRow(index, value) {\n checkRowIndex(this, index);\n for (var i = 0; i < this.columns; i++) {\n this.set(index, i, this.get(index, i) * value);\n }\n return this;\n }\n\n /**\n * Multiplies the values of a column with a scalar\n * @param {number} index - Column index\n * @param {number} value\n * @return {Matrix} this\n */\n mulColumn(index, value) {\n checkColumnIndex(this, index);\n for (var i = 0; i < this.rows; i++) {\n this.set(i, index, this.get(i, index) * value);\n }\n return this;\n }\n\n /**\n * Returns the maximum value of the matrix\n * @return {number}\n */\n max() {\n var v = this.get(0, 0);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value\n * @return {Array}\n */\n maxIndex() {\n var v = this.get(0, 0);\n var idx = [0, 0];\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of the matrix\n * @return {number}\n */\n min() {\n var v = this.get(0, 0);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the minimum value\n * @return {Array}\n */\n minIndex() {\n var v = this.get(0, 0);\n var idx = [0, 0];\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n /**\n * Returns the maximum value of one row\n * @param {number} row - Row index\n * @return {number}\n */\n maxRow(row) {\n checkRowIndex(this, row);\n var v = this.get(row, 0);\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one row\n * @param {number} row - Row index\n * @return {Array}\n */\n maxRowIndex(row) {\n checkRowIndex(this, row);\n var v = this.get(row, 0);\n var idx = [row, 0];\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of one row\n * @param {number} row - Row index\n * @return {number}\n */\n minRow(row) {\n checkRowIndex(this, row);\n var v = this.get(row, 0);\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one row\n * @param {number} row - Row index\n * @return {Array}\n */\n minRowIndex(row) {\n checkRowIndex(this, row);\n var v = this.get(row, 0);\n var idx = [row, 0];\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the maximum value of one column\n * @param {number} column - Column index\n * @return {number}\n */\n maxColumn(column) {\n checkColumnIndex(this, column);\n var v = this.get(0, column);\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one column\n * @param {number} column - Column index\n * @return {Array}\n */\n maxColumnIndex(column) {\n checkColumnIndex(this, column);\n var v = this.get(0, column);\n var idx = [0, column];\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of one column\n * @param {number} column - Column index\n * @return {number}\n */\n minColumn(column) {\n checkColumnIndex(this, column);\n var v = this.get(0, column);\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the minimum value of one column\n * @param {number} column - Column index\n * @return {Array}\n */\n minColumnIndex(column) {\n checkColumnIndex(this, column);\n var v = this.get(0, column);\n var idx = [0, column];\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns an array containing the diagonal values of the matrix\n * @return {Array}\n */\n diag() {\n var min = Math.min(this.rows, this.columns);\n var diag = new Array(min);\n for (var i = 0; i < min; i++) {\n diag[i] = this.get(i, i);\n }\n return diag;\n }\n\n /**\n * Returns the sum by the argument given, if no argument given,\n * it returns the sum of all elements of the matrix.\n * @param {string} by - sum by 'row' or 'column'.\n * @return {Matrix|number}\n */\n sum(by) {\n switch (by) {\n case 'row':\n return sumByRow(this);\n case 'column':\n return sumByColumn(this);\n default:\n return sumAll(this);\n }\n }\n\n /**\n * Returns the mean of all elements of the matrix\n * @return {number}\n */\n mean() {\n return this.sum() / this.size;\n }\n\n /**\n * Returns the product of all elements of the matrix\n * @return {number}\n */\n prod() {\n var prod = 1;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n prod *= this.get(i, j);\n }\n }\n return prod;\n }\n\n /**\n * Returns the norm of a matrix.\n * @param {string} type - \"frobenius\" (default) or \"max\" return resp. the Frobenius norm and the max norm.\n * @return {number}\n */\n norm(type = 'frobenius') {\n var result = 0;\n if (type === 'max') {\n return this.max();\n } else if (type === 'frobenius') {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n result = result + this.get(i, j) * this.get(i, j);\n }\n }\n return Math.sqrt(result);\n } else {\n throw new RangeError(`unknown norm type: ${type}`);\n }\n }\n\n /**\n * Computes the cumulative sum of the matrix elements (in place, row by row)\n * @return {Matrix} this\n */\n cumulativeSum() {\n var sum = 0;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n sum += this.get(i, j);\n this.set(i, j, sum);\n }\n }\n return this;\n }\n\n /**\n * Computes the dot (scalar) product between the matrix and another\n * @param {Matrix} vector2 vector\n * @return {number}\n */\n dot(vector2) {\n if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\n var vector1 = this.to1DArray();\n if (vector1.length !== vector2.length) {\n throw new RangeError('vectors do not have the same size');\n }\n var dot = 0;\n for (var i = 0; i < vector1.length; i++) {\n dot += vector1[i] * vector2[i];\n }\n return dot;\n }\n\n /**\n * Returns the matrix product between this and other\n * @param {Matrix} other\n * @return {Matrix}\n */\n mmul(other) {\n other = this.constructor.checkMatrix(other);\n if (this.columns !== other.rows) {\n // eslint-disable-next-line no-console\n console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\n }\n\n var m = this.rows;\n var n = this.columns;\n var p = other.columns;\n\n var result = new this.constructor[Symbol.species](m, p);\n\n var Bcolj = new Array(n);\n for (var j = 0; j < p; j++) {\n for (var k = 0; k < n; k++) {\n Bcolj[k] = other.get(k, j);\n }\n\n for (var i = 0; i < m; i++) {\n var s = 0;\n for (k = 0; k < n; k++) {\n s += this.get(i, k) * Bcolj[k];\n }\n\n result.set(i, j, s);\n }\n }\n return result;\n }\n\n strassen2x2(other) {\n var result = new this.constructor[Symbol.species](2, 2);\n const a11 = this.get(0, 0);\n const b11 = other.get(0, 0);\n const a12 = this.get(0, 1);\n const b12 = other.get(0, 1);\n const a21 = this.get(1, 0);\n const b21 = other.get(1, 0);\n const a22 = this.get(1, 1);\n const b22 = other.get(1, 1);\n\n // Compute intermediate values.\n const m1 = (a11 + a22) * (b11 + b22);\n const m2 = (a21 + a22) * b11;\n const m3 = a11 * (b12 - b22);\n const m4 = a22 * (b21 - b11);\n const m5 = (a11 + a12) * b22;\n const m6 = (a21 - a11) * (b11 + b12);\n const m7 = (a12 - a22) * (b21 + b22);\n\n // Combine intermediate values into the output.\n const c00 = m1 + m4 - m5 + m7;\n const c01 = m3 + m5;\n const c10 = m2 + m4;\n const c11 = m1 - m2 + m3 + m6;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n return result;\n }\n\n strassen3x3(other) {\n var result = new this.constructor[Symbol.species](3, 3);\n\n const a00 = this.get(0, 0);\n const a01 = this.get(0, 1);\n const a02 = this.get(0, 2);\n const a10 = this.get(1, 0);\n const a11 = this.get(1, 1);\n const a12 = this.get(1, 2);\n const a20 = this.get(2, 0);\n const a21 = this.get(2, 1);\n const a22 = this.get(2, 2);\n\n const b00 = other.get(0, 0);\n const b01 = other.get(0, 1);\n const b02 = other.get(0, 2);\n const b10 = other.get(1, 0);\n const b11 = other.get(1, 1);\n const b12 = other.get(1, 2);\n const b20 = other.get(2, 0);\n const b21 = other.get(2, 1);\n const b22 = other.get(2, 2);\n\n const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;\n const m2 = (a00 - a10) * (-b01 + b11);\n const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);\n const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);\n const m5 = (a10 + a11) * (-b00 + b01);\n const m6 = a00 * b00;\n const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);\n const m8 = (-a00 + a20) * (b02 - b12);\n const m9 = (a20 + a21) * (-b00 + b02);\n const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;\n const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);\n const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);\n const m13 = (a02 - a22) * (b11 - b21);\n const m14 = a02 * b20;\n const m15 = (a21 + a22) * (-b20 + b21);\n const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);\n const m17 = (a02 - a12) * (b12 - b22);\n const m18 = (a11 + a12) * (-b20 + b22);\n const m19 = a01 * b10;\n const m20 = a12 * b21;\n const m21 = a10 * b02;\n const m22 = a20 * b01;\n const m23 = a22 * b22;\n\n const c00 = m6 + m14 + m19;\n const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;\n const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;\n const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;\n const c11 = m2 + m4 + m5 + m6 + m20;\n const c12 = m14 + m16 + m17 + m18 + m21;\n const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;\n const c21 = m12 + m13 + m14 + m15 + m22;\n const c22 = m6 + m7 + m8 + m9 + m23;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(0, 2, c02);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n result.set(1, 2, c12);\n result.set(2, 0, c20);\n result.set(2, 1, c21);\n result.set(2, 2, c22);\n return result;\n }\n\n /**\n * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000.\n * @param {Matrix} y\n * @return {Matrix}\n */\n mmulStrassen(y) {\n var x = this.clone();\n var r1 = x.rows;\n var c1 = x.columns;\n var r2 = y.rows;\n var c2 = y.columns;\n if (c1 !== r2) {\n // eslint-disable-next-line no-console\n console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`);\n }\n\n // Put a matrix into the top left of a matrix of zeros.\n // `rows` and `cols` are the dimensions of the output matrix.\n function embed(mat, rows, cols) {\n var r = mat.rows;\n var c = mat.columns;\n if ((r === rows) && (c === cols)) {\n return mat;\n } else {\n var resultat = Matrix.zeros(rows, cols);\n resultat = resultat.setSubMatrix(mat, 0, 0);\n return resultat;\n }\n }\n\n\n // Make sure both matrices are the same size.\n // This is exclusively for simplicity:\n // this algorithm can be implemented with matrices of different sizes.\n\n var r = Math.max(r1, r2);\n var c = Math.max(c1, c2);\n x = embed(x, r, c);\n y = embed(y, r, c);\n\n // Our recursive multiplication function.\n function blockMult(a, b, rows, cols) {\n // For small matrices, resort to naive multiplication.\n if (rows <= 512 || cols <= 512) {\n return a.mmul(b); // a is equivalent to this\n }\n\n // Apply dynamic padding.\n if ((rows % 2 === 1) && (cols % 2 === 1)) {\n a = embed(a, rows + 1, cols + 1);\n b = embed(b, rows + 1, cols + 1);\n } else if (rows % 2 === 1) {\n a = embed(a, rows + 1, cols);\n b = embed(b, rows + 1, cols);\n } else if (cols % 2 === 1) {\n a = embed(a, rows, cols + 1);\n b = embed(b, rows, cols + 1);\n }\n\n var halfRows = parseInt(a.rows / 2, 10);\n var halfCols = parseInt(a.columns / 2, 10);\n // Subdivide input matrices.\n var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n\n var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\n var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\n\n var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\n var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\n\n var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\n var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\n\n // Compute intermediate values.\n var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols);\n var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols);\n var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols);\n var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols);\n var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols);\n var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols);\n var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols);\n\n // Combine intermediate values into the output.\n var c11 = Matrix.add(m1, m4);\n c11.sub(m5);\n c11.add(m7);\n var c12 = Matrix.add(m3, m5);\n var c21 = Matrix.add(m2, m4);\n var c22 = Matrix.sub(m1, m2);\n c22.add(m3);\n c22.add(m6);\n\n // Crop output to the desired size (undo dynamic padding).\n var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns);\n resultat = resultat.setSubMatrix(c11, 0, 0);\n resultat = resultat.setSubMatrix(c12, c11.rows, 0);\n resultat = resultat.setSubMatrix(c21, 0, c11.columns);\n resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns);\n return resultat.subMatrix(0, rows - 1, 0, cols - 1);\n }\n return blockMult(x, y, r, c);\n }\n\n /**\n * Returns a row-by-row scaled matrix\n * @param {number} [min=0] - Minimum scaled value\n * @param {number} [max=1] - Maximum scaled value\n * @return {Matrix} - The scaled matrix\n */\n scaleRows(min, max) {\n min = min === undefined ? 0 : min;\n max = max === undefined ? 1 : max;\n if (min >= max) {\n throw new RangeError('min should be strictly smaller than max');\n }\n var newMatrix = this.constructor.empty(this.rows, this.columns);\n for (var i = 0; i < this.rows; i++) {\n var scaled = rescale(this.getRow(i), { min, max });\n newMatrix.setRow(i, scaled);\n }\n return newMatrix;\n }\n\n /**\n * Returns a new column-by-column scaled matrix\n * @param {number} [min=0] - Minimum scaled value\n * @param {number} [max=1] - Maximum scaled value\n * @return {Matrix} - The new scaled matrix\n * @example\n * var matrix = new Matrix([[1,2],[-1,0]]);\n * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]]\n */\n scaleColumns(min, max) {\n min = min === undefined ? 0 : min;\n max = max === undefined ? 1 : max;\n if (min >= max) {\n throw new RangeError('min should be strictly smaller than max');\n }\n var newMatrix = this.constructor.empty(this.rows, this.columns);\n for (var i = 0; i < this.columns; i++) {\n var scaled = rescale(this.getColumn(i), {\n min: min,\n max: max\n });\n newMatrix.setColumn(i, scaled);\n }\n return newMatrix;\n }\n\n\n /**\n * Returns the Kronecker product (also known as tensor product) between this and other\n * See https://en.wikipedia.org/wiki/Kronecker_product\n * @param {Matrix} other\n * @return {Matrix}\n */\n kroneckerProduct(other) {\n other = this.constructor.checkMatrix(other);\n\n var m = this.rows;\n var n = this.columns;\n var p = other.rows;\n var q = other.columns;\n\n var result = new this.constructor[Symbol.species](m * p, n * q);\n for (var i = 0; i < m; i++) {\n for (var j = 0; j < n; j++) {\n for (var k = 0; k < p; k++) {\n for (var l = 0; l < q; l++) {\n result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l);\n }\n }\n }\n }\n return result;\n }\n\n /**\n * Transposes the matrix and returns a new one containing the result\n * @return {Matrix}\n */\n transpose() {\n var result = new this.constructor[Symbol.species](this.columns, this.rows);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n result.set(j, i, this.get(i, j));\n }\n }\n return result;\n }\n\n /**\n * Sorts the rows (in place)\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\n * @return {Matrix} this\n */\n sortRows(compareFunction) {\n if (compareFunction === undefined) compareFunction = compareNumbers;\n for (var i = 0; i < this.rows; i++) {\n this.setRow(i, this.getRow(i).sort(compareFunction));\n }\n return this;\n }\n\n /**\n * Sorts the columns (in place)\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\n * @return {Matrix} this\n */\n sortColumns(compareFunction) {\n if (compareFunction === undefined) compareFunction = compareNumbers;\n for (var i = 0; i < this.columns; i++) {\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\n }\n return this;\n }\n\n /**\n * Returns a subset of the matrix\n * @param {number} startRow - First row index\n * @param {number} endRow - Last row index\n * @param {number} startColumn - First column index\n * @param {number} endColumn - Last column index\n * @return {Matrix}\n */\n subMatrix(startRow, endRow, startColumn, endColumn) {\n checkRange(this, startRow, endRow, startColumn, endColumn);\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1);\n for (var i = startRow; i <= endRow; i++) {\n for (var j = startColumn; j <= endColumn; j++) {\n newMatrix[i - startRow][j - startColumn] = this.get(i, j);\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns a subset of the matrix based on an array of row indices\n * @param {Array} indices - Array containing the row indices\n * @param {number} [startColumn = 0] - First column index\n * @param {number} [endColumn = this.columns-1] - Last column index\n * @return {Matrix}\n */\n subMatrixRow(indices, startColumn, endColumn) {\n if (startColumn === undefined) startColumn = 0;\n if (endColumn === undefined) endColumn = this.columns - 1;\n if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) {\n throw new RangeError('Argument out of range');\n }\n\n var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1);\n for (var i = 0; i < indices.length; i++) {\n for (var j = startColumn; j <= endColumn; j++) {\n if (indices[i] < 0 || indices[i] >= this.rows) {\n throw new RangeError(`Row index out of range: ${indices[i]}`);\n }\n newMatrix.set(i, j - startColumn, this.get(indices[i], j));\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns a subset of the matrix based on an array of column indices\n * @param {Array} indices - Array containing the column indices\n * @param {number} [startRow = 0] - First row index\n * @param {number} [endRow = this.rows-1] - Last row index\n * @return {Matrix}\n */\n subMatrixColumn(indices, startRow, endRow) {\n if (startRow === undefined) startRow = 0;\n if (endRow === undefined) endRow = this.rows - 1;\n if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) {\n throw new RangeError('Argument out of range');\n }\n\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length);\n for (var i = 0; i < indices.length; i++) {\n for (var j = startRow; j <= endRow; j++) {\n if (indices[i] < 0 || indices[i] >= this.columns) {\n throw new RangeError(`Column index out of range: ${indices[i]}`);\n }\n newMatrix.set(j - startRow, i, this.get(j, indices[i]));\n }\n }\n return newMatrix;\n }\n\n /**\n * Set a part of the matrix to the given sub-matrix\n * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values.\n * @param {number} startRow - The index of the first row to set\n * @param {number} startColumn - The index of the first column to set\n * @return {Matrix}\n */\n setSubMatrix(matrix, startRow, startColumn) {\n matrix = this.constructor.checkMatrix(matrix);\n var endRow = startRow + matrix.rows - 1;\n var endColumn = startColumn + matrix.columns - 1;\n checkRange(this, startRow, endRow, startColumn, endColumn);\n for (var i = 0; i < matrix.rows; i++) {\n for (var j = 0; j < matrix.columns; j++) {\n this[startRow + i][startColumn + j] = matrix.get(i, j);\n }\n }\n return this;\n }\n\n /**\n * Return a new matrix based on a selection of rows and columns\n * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once.\n * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once.\n * @return {Matrix} The new matrix\n */\n selection(rowIndices, columnIndices) {\n var indices = checkIndices(this, rowIndices, columnIndices);\n var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length);\n for (var i = 0; i < indices.row.length; i++) {\n var rowIndex = indices.row[i];\n for (var j = 0; j < indices.column.length; j++) {\n var columnIndex = indices.column[j];\n newMatrix[i][j] = this.get(rowIndex, columnIndex);\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns the trace of the matrix (sum of the diagonal elements)\n * @return {number}\n */\n trace() {\n var min = Math.min(this.rows, this.columns);\n var trace = 0;\n for (var i = 0; i < min; i++) {\n trace += this.get(i, i);\n }\n return trace;\n }\n\n /*\n Matrix views\n */\n\n /**\n * Returns a view of the transposition of the matrix\n * @return {MatrixTransposeView}\n */\n transposeView() {\n return new MatrixTransposeView(this);\n }\n\n /**\n * Returns a view of the row vector with the given index\n * @param {number} row - row index of the vector\n * @return {MatrixRowView}\n */\n rowView(row) {\n checkRowIndex(this, row);\n return new MatrixRowView(this, row);\n }\n\n /**\n * Returns a view of the column vector with the given index\n * @param {number} column - column index of the vector\n * @return {MatrixColumnView}\n */\n columnView(column) {\n checkColumnIndex(this, column);\n return new MatrixColumnView(this, column);\n }\n\n /**\n * Returns a view of the matrix flipped in the row axis\n * @return {MatrixFlipRowView}\n */\n flipRowView() {\n return new MatrixFlipRowView(this);\n }\n\n /**\n * Returns a view of the matrix flipped in the column axis\n * @return {MatrixFlipColumnView}\n */\n flipColumnView() {\n return new MatrixFlipColumnView(this);\n }\n\n /**\n * Returns a view of a submatrix giving the index boundaries\n * @param {number} startRow - first row index of the submatrix\n * @param {number} endRow - last row index of the submatrix\n * @param {number} startColumn - first column index of the submatrix\n * @param {number} endColumn - last column index of the submatrix\n * @return {MatrixSubView}\n */\n subMatrixView(startRow, endRow, startColumn, endColumn) {\n return new MatrixSubView(this, startRow, endRow, startColumn, endColumn);\n }\n\n /**\n * Returns a view of the cross of the row indices and the column indices\n * @example\n * // resulting vector is [[2], [2]]\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1])\n * @param {Array} rowIndices\n * @param {Array} columnIndices\n * @return {MatrixSelectionView}\n */\n selectionView(rowIndices, columnIndices) {\n return new MatrixSelectionView(this, rowIndices, columnIndices);\n }\n\n /**\n * Returns a view of the row indices\n * @example\n * // resulting vector is [[1,2,3], [1,2,3]]\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).rowSelectionView([0, 0])\n * @param {Array} rowIndices\n * @return {MatrixRowSelectionView}\n */\n rowSelectionView(rowIndices) {\n return new MatrixRowSelectionView(this, rowIndices);\n }\n\n /**\n * Returns a view of the column indices\n * @example\n * // resulting vector is [[2, 2], [5, 5]]\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).columnSelectionView([1, 1])\n * @param {Array} columnIndices\n * @return {MatrixColumnSelectionView}\n */\n columnSelectionView(columnIndices) {\n return new MatrixColumnSelectionView(this, columnIndices);\n }\n\n\n /**\n * Calculates and returns the determinant of a matrix as a Number\n * @example\n * new Matrix([[1,2,3], [4,5,6]]).det()\n * @return {number}\n */\n det() {\n if (this.isSquare()) {\n var a, b, c, d;\n if (this.columns === 2) {\n // 2 x 2 matrix\n a = this.get(0, 0);\n b = this.get(0, 1);\n c = this.get(1, 0);\n d = this.get(1, 1);\n\n return a * d - (b * c);\n } else if (this.columns === 3) {\n // 3 x 3 matrix\n var subMatrix0, subMatrix1, subMatrix2;\n subMatrix0 = this.selectionView([1, 2], [1, 2]);\n subMatrix1 = this.selectionView([1, 2], [0, 2]);\n subMatrix2 = this.selectionView([1, 2], [0, 1]);\n a = this.get(0, 0);\n b = this.get(0, 1);\n c = this.get(0, 2);\n\n return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det();\n } else {\n // general purpose determinant using the LU decomposition\n return new LuDecomposition(this).determinant;\n }\n } else {\n throw Error('Determinant can only be calculated for a square matrix.');\n }\n }\n\n /**\n * Returns inverse of a matrix if it exists or the pseudoinverse\n * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15)\n * @return {Matrix} the (pseudo)inverted matrix.\n */\n pseudoInverse(threshold) {\n if (threshold === undefined) threshold = Number.EPSILON;\n var svdSolution = new SvDecomposition(this, { autoTranspose: true });\n\n var U = svdSolution.leftSingularVectors;\n var V = svdSolution.rightSingularVectors;\n var s = svdSolution.diagonal;\n\n for (var i = 0; i < s.length; i++) {\n if (Math.abs(s[i]) > threshold) {\n s[i] = 1.0 / s[i];\n } else {\n s[i] = 0.0;\n }\n }\n\n // convert list to diagonal\n s = this.constructor[Symbol.species].diag(s);\n return V.mmul(s.mmul(U.transposeView()));\n }\n\n /**\n * Creates an exact and independent copy of the matrix\n * @return {Matrix}\n */\n clone() {\n var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns);\n for (var row = 0; row < this.rows; row++) {\n for (var column = 0; column < this.columns; column++) {\n newMatrix.set(row, column, this.get(row, column));\n }\n }\n return newMatrix;\n }\n }\n\n Matrix.prototype.klass = 'Matrix';\n\n function compareNumbers(a, b) {\n return a - b;\n }\n\n /*\n Synonyms\n */\n\n Matrix.random = Matrix.rand;\n Matrix.diagonal = Matrix.diag;\n Matrix.prototype.diagonal = Matrix.prototype.diag;\n Matrix.identity = Matrix.eye;\n Matrix.prototype.negate = Matrix.prototype.neg;\n Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct;\n Matrix.prototype.determinant = Matrix.prototype.det;\n\n /*\n Add dynamically instance and static methods for mathematical operations\n */\n\n var inplaceOperator = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\n var inplaceOperatorScalar = `\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% value);\n }\n }\n return this;\n})\n`;\n\n var inplaceOperatorMatrix = `\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% matrix.get(i, j));\n }\n }\n return this;\n})\n`;\n\n var staticOperator = `\n(function %name%(matrix, value) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(value);\n})\n`;\n\n var inplaceMethod = `\n(function %name%() {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j)));\n }\n }\n return this;\n})\n`;\n\n var staticMethod = `\n(function %name%(matrix) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%();\n})\n`;\n\n var inplaceMethodWithArgs = `\n(function %name%(%args%) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), %args%));\n }\n }\n return this;\n})\n`;\n\n var staticMethodWithArgs = `\n(function %name%(matrix, %args%) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(%args%);\n})\n`;\n\n\n var inplaceMethodWithOneArgScalar = `\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), value));\n }\n }\n return this;\n})\n`;\n var inplaceMethodWithOneArgMatrix = `\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), matrix.get(i, j)));\n }\n }\n return this;\n})\n`;\n\n var inplaceMethodWithOneArg = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\n var staticMethodWithOneArg = staticMethodWithArgs;\n\n var operators = [\n // Arithmetic operators\n ['+', 'add'],\n ['-', 'sub', 'subtract'],\n ['*', 'mul', 'multiply'],\n ['/', 'div', 'divide'],\n ['%', 'mod', 'modulus'],\n // Bitwise operators\n ['&', 'and'],\n ['|', 'or'],\n ['^', 'xor'],\n ['<<', 'leftShift'],\n ['>>', 'signPropagatingRightShift'],\n ['>>>', 'rightShift', 'zeroFillRightShift']\n ];\n\n var i;\n var eval2 = eval; // eslint-disable-line no-eval\n for (var operator of operators) {\n var inplaceOp = eval2(fillTemplateFunction(inplaceOperator, { name: operator[1], op: operator[0] }));\n var inplaceOpS = eval2(fillTemplateFunction(inplaceOperatorScalar, { name: `${operator[1]}S`, op: operator[0] }));\n var inplaceOpM = eval2(fillTemplateFunction(inplaceOperatorMatrix, { name: `${operator[1]}M`, op: operator[0] }));\n var staticOp = eval2(fillTemplateFunction(staticOperator, { name: operator[1] }));\n for (i = 1; i < operator.length; i++) {\n Matrix.prototype[operator[i]] = inplaceOp;\n Matrix.prototype[`${operator[i]}S`] = inplaceOpS;\n Matrix.prototype[`${operator[i]}M`] = inplaceOpM;\n Matrix[operator[i]] = staticOp;\n }\n }\n\n var methods = [['~', 'not']];\n\n [\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\n ].forEach(function (mathMethod) {\n methods.push([`Math.${mathMethod}`, mathMethod]);\n });\n\n for (var method of methods) {\n var inplaceMeth = eval2(fillTemplateFunction(inplaceMethod, { name: method[1], method: method[0] }));\n var staticMeth = eval2(fillTemplateFunction(staticMethod, { name: method[1] }));\n for (i = 1; i < method.length; i++) {\n Matrix.prototype[method[i]] = inplaceMeth;\n Matrix[method[i]] = staticMeth;\n }\n }\n\n var methodsWithArgs = [['Math.pow', 1, 'pow']];\n\n for (var methodWithArg of methodsWithArgs) {\n var args = 'arg0';\n for (i = 1; i < methodWithArg[1]; i++) {\n args += `, arg${i}`;\n }\n if (methodWithArg[1] !== 1) {\n var inplaceMethWithArgs = eval2(fillTemplateFunction(inplaceMethodWithArgs, {\n name: methodWithArg[2],\n method: methodWithArg[0],\n args: args\n }));\n var staticMethWithArgs = eval2(fillTemplateFunction(staticMethodWithArgs, { name: methodWithArg[2], args: args }));\n for (i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs;\n Matrix[methodWithArg[i]] = staticMethWithArgs;\n }\n } else {\n var tmplVar = {\n name: methodWithArg[2],\n args: args,\n method: methodWithArg[0]\n };\n var inplaceMethod2 = eval2(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar));\n var inplaceMethodS = eval2(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar));\n var inplaceMethodM = eval2(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar));\n var staticMethod2 = eval2(fillTemplateFunction(staticMethodWithOneArg, tmplVar));\n for (i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethod2;\n Matrix.prototype[`${methodWithArg[i]}M`] = inplaceMethodM;\n Matrix.prototype[`${methodWithArg[i]}S`] = inplaceMethodS;\n Matrix[methodWithArg[i]] = staticMethod2;\n }\n }\n }\n\n function fillTemplateFunction(template, values) {\n for (var value in values) {\n template = template.replace(new RegExp(`%${value}%`, 'g'), values[value]);\n }\n return template;\n }\n\n return Matrix;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/abstractMatrix.js","/**\n * Computes the mean of the given values\n * @param {Array} input\n * @return {number}\n */\nexport default function mean(input) {\n if (!Array.isArray(input)) {\n throw new Error('input must be an array');\n }\n\n if (input.length === 0) {\n throw new Error('input must not be empty');\n }\n\n var sum = 0;\n for (var i = 0; i < input.length; i++) {\n sum += input[i];\n }\n return sum / input.length;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-array-mean/src/index.js","import { Matrix, WrapperMatrix2D } from '../index';\n\nimport { hypotenuse, getFilled2DArray } from './util';\n\n/**\n * @class SingularValueDecomposition\n * @see https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs\n * @param {Matrix} value\n * @param {object} [options]\n * @param {boolean} [options.computeLeftSingularVectors=true]\n * @param {boolean} [options.computeRightSingularVectors=true]\n * @param {boolean} [options.autoTranspose=false]\n */\nexport default class SingularValueDecomposition {\n constructor(value, options = {}) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n var m = value.rows;\n var n = value.columns;\n\n const {\n computeLeftSingularVectors = true,\n computeRightSingularVectors = true,\n autoTranspose = false\n } = options;\n\n var wantu = Boolean(computeLeftSingularVectors);\n var wantv = Boolean(computeRightSingularVectors);\n\n var swapped = false;\n var a;\n if (m < n) {\n if (!autoTranspose) {\n a = value.clone();\n // eslint-disable-next-line no-console\n console.warn(\n 'Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose'\n );\n } else {\n a = value.transpose();\n m = a.rows;\n n = a.columns;\n swapped = true;\n var aux = wantu;\n wantu = wantv;\n wantv = aux;\n }\n } else {\n a = value.clone();\n }\n\n var nu = Math.min(m, n);\n var ni = Math.min(m + 1, n);\n var s = new Array(ni);\n var U = getFilled2DArray(m, nu, 0);\n var V = getFilled2DArray(n, n, 0);\n\n var e = new Array(n);\n var work = new Array(m);\n\n var si = new Array(ni);\n for (let i = 0; i < ni; i++) si[i] = i;\n\n var nct = Math.min(m - 1, n);\n var nrt = Math.max(0, Math.min(n - 2, m));\n var mrc = Math.max(nct, nrt);\n\n for (let k = 0; k < mrc; k++) {\n if (k < nct) {\n s[k] = 0;\n for (let i = k; i < m; i++) {\n s[k] = hypotenuse(s[k], a[i][k]);\n }\n if (s[k] !== 0) {\n if (a[k][k] < 0) {\n s[k] = -s[k];\n }\n for (let i = k; i < m; i++) {\n a[i][k] /= s[k];\n }\n a[k][k] += 1;\n }\n s[k] = -s[k];\n }\n\n for (let j = k + 1; j < n; j++) {\n if (k < nct && s[k] !== 0) {\n let t = 0;\n for (let i = k; i < m; i++) {\n t += a[i][k] * a[i][j];\n }\n t = -t / a[k][k];\n for (let i = k; i < m; i++) {\n a[i][j] += t * a[i][k];\n }\n }\n e[j] = a[k][j];\n }\n\n if (wantu && k < nct) {\n for (let i = k; i < m; i++) {\n U[i][k] = a[i][k];\n }\n }\n\n if (k < nrt) {\n e[k] = 0;\n for (let i = k + 1; i < n; i++) {\n e[k] = hypotenuse(e[k], e[i]);\n }\n if (e[k] !== 0) {\n if (e[k + 1] < 0) {\n e[k] = 0 - e[k];\n }\n for (let i = k + 1; i < n; i++) {\n e[i] /= e[k];\n }\n e[k + 1] += 1;\n }\n e[k] = -e[k];\n if (k + 1 < m && e[k] !== 0) {\n for (let i = k + 1; i < m; i++) {\n work[i] = 0;\n }\n for (let i = k + 1; i < m; i++) {\n for (let j = k + 1; j < n; j++) {\n work[i] += e[j] * a[i][j];\n }\n }\n for (let j = k + 1; j < n; j++) {\n let t = -e[j] / e[k + 1];\n for (let i = k + 1; i < m; i++) {\n a[i][j] += t * work[i];\n }\n }\n }\n if (wantv) {\n for (let i = k + 1; i < n; i++) {\n V[i][k] = e[i];\n }\n }\n }\n }\n\n let p = Math.min(n, m + 1);\n if (nct < n) {\n s[nct] = a[nct][nct];\n }\n if (m < p) {\n s[p - 1] = 0;\n }\n if (nrt + 1 < p) {\n e[nrt] = a[nrt][p - 1];\n }\n e[p - 1] = 0;\n\n if (wantu) {\n for (let j = nct; j < nu; j++) {\n for (let i = 0; i < m; i++) {\n U[i][j] = 0;\n }\n U[j][j] = 1;\n }\n for (let k = nct - 1; k >= 0; k--) {\n if (s[k] !== 0) {\n for (let j = k + 1; j < nu; j++) {\n let t = 0;\n for (let i = k; i < m; i++) {\n t += U[i][k] * U[i][j];\n }\n t = -t / U[k][k];\n for (let i = k; i < m; i++) {\n U[i][j] += t * U[i][k];\n }\n }\n for (let i = k; i < m; i++) {\n U[i][k] = -U[i][k];\n }\n U[k][k] = 1 + U[k][k];\n for (let i = 0; i < k - 1; i++) {\n U[i][k] = 0;\n }\n } else {\n for (let i = 0; i < m; i++) {\n U[i][k] = 0;\n }\n U[k][k] = 1;\n }\n }\n }\n\n if (wantv) {\n for (let k = n - 1; k >= 0; k--) {\n if (k < nrt && e[k] !== 0) {\n for (let j = k + 1; j < n; j++) {\n let t = 0;\n for (let i = k + 1; i < n; i++) {\n t += V[i][k] * V[i][j];\n }\n t = -t / V[k + 1][k];\n for (let i = k + 1; i < n; i++) {\n V[i][j] += t * V[i][k];\n }\n }\n }\n for (let i = 0; i < n; i++) {\n V[i][k] = 0;\n }\n V[k][k] = 1;\n }\n }\n\n var pp = p - 1;\n var iter = 0;\n var eps = Number.EPSILON;\n while (p > 0) {\n let k, kase;\n for (k = p - 2; k >= -1; k--) {\n if (k === -1) {\n break;\n }\n const alpha =\n Number.MIN_VALUE + eps * Math.abs(s[k] + Math.abs(s[k + 1]));\n if (Math.abs(e[k]) <= alpha || Number.isNaN(e[k])) {\n e[k] = 0;\n break;\n }\n }\n if (k === p - 2) {\n kase = 4;\n } else {\n let ks;\n for (ks = p - 1; ks >= k; ks--) {\n if (ks === k) {\n break;\n }\n let t =\n (ks !== p ? Math.abs(e[ks]) : 0) +\n (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0);\n if (Math.abs(s[ks]) <= eps * t) {\n s[ks] = 0;\n break;\n }\n }\n if (ks === k) {\n kase = 3;\n } else if (ks === p - 1) {\n kase = 1;\n } else {\n kase = 2;\n k = ks;\n }\n }\n\n k++;\n\n switch (kase) {\n case 1: {\n let f = e[p - 2];\n e[p - 2] = 0;\n for (let j = p - 2; j >= k; j--) {\n let t = hypotenuse(s[j], f);\n let cs = s[j] / t;\n let sn = f / t;\n s[j] = t;\n if (j !== k) {\n f = -sn * e[j - 1];\n e[j - 1] = cs * e[j - 1];\n }\n if (wantv) {\n for (let i = 0; i < n; i++) {\n t = cs * V[i][j] + sn * V[i][p - 1];\n V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1];\n V[i][j] = t;\n }\n }\n }\n break;\n }\n case 2: {\n let f = e[k - 1];\n e[k - 1] = 0;\n for (let j = k; j < p; j++) {\n let t = hypotenuse(s[j], f);\n let cs = s[j] / t;\n let sn = f / t;\n s[j] = t;\n f = -sn * e[j];\n e[j] = cs * e[j];\n if (wantu) {\n for (let i = 0; i < m; i++) {\n t = cs * U[i][j] + sn * U[i][k - 1];\n U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1];\n U[i][j] = t;\n }\n }\n }\n break;\n }\n case 3: {\n const scale = Math.max(\n Math.abs(s[p - 1]),\n Math.abs(s[p - 2]),\n Math.abs(e[p - 2]),\n Math.abs(s[k]),\n Math.abs(e[k])\n );\n const sp = s[p - 1] / scale;\n const spm1 = s[p - 2] / scale;\n const epm1 = e[p - 2] / scale;\n const sk = s[k] / scale;\n const ek = e[k] / scale;\n const b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;\n const c = sp * epm1 * (sp * epm1);\n let shift = 0;\n if (b !== 0 || c !== 0) {\n if (b < 0) {\n shift = 0 - Math.sqrt(b * b + c);\n } else {\n shift = Math.sqrt(b * b + c);\n }\n shift = c / (b + shift);\n }\n let f = (sk + sp) * (sk - sp) + shift;\n let g = sk * ek;\n for (let j = k; j < p - 1; j++) {\n let t = hypotenuse(f, g);\n if (t === 0) t = Number.MIN_VALUE;\n let cs = f / t;\n let sn = g / t;\n if (j !== k) {\n e[j - 1] = t;\n }\n f = cs * s[j] + sn * e[j];\n e[j] = cs * e[j] - sn * s[j];\n g = sn * s[j + 1];\n s[j + 1] = cs * s[j + 1];\n if (wantv) {\n for (let i = 0; i < n; i++) {\n t = cs * V[i][j] + sn * V[i][j + 1];\n V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1];\n V[i][j] = t;\n }\n }\n t = hypotenuse(f, g);\n if (t === 0) t = Number.MIN_VALUE;\n cs = f / t;\n sn = g / t;\n s[j] = t;\n f = cs * e[j] + sn * s[j + 1];\n s[j + 1] = -sn * e[j] + cs * s[j + 1];\n g = sn * e[j + 1];\n e[j + 1] = cs * e[j + 1];\n if (wantu && j < m - 1) {\n for (let i = 0; i < m; i++) {\n t = cs * U[i][j] + sn * U[i][j + 1];\n U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1];\n U[i][j] = t;\n }\n }\n }\n e[p - 2] = f;\n iter = iter + 1;\n break;\n }\n case 4: {\n if (s[k] <= 0) {\n s[k] = s[k] < 0 ? -s[k] : 0;\n if (wantv) {\n for (let i = 0; i <= pp; i++) {\n V[i][k] = -V[i][k];\n }\n }\n }\n while (k < pp) {\n if (s[k] >= s[k + 1]) {\n break;\n }\n let t = s[k];\n s[k] = s[k + 1];\n s[k + 1] = t;\n if (wantv && k < n - 1) {\n for (let i = 0; i < n; i++) {\n t = V[i][k + 1];\n V[i][k + 1] = V[i][k];\n V[i][k] = t;\n }\n }\n if (wantu && k < m - 1) {\n for (let i = 0; i < m; i++) {\n t = U[i][k + 1];\n U[i][k + 1] = U[i][k];\n U[i][k] = t;\n }\n }\n k++;\n }\n iter = 0;\n p--;\n break;\n }\n // no default\n }\n }\n\n if (swapped) {\n var tmp = V;\n V = U;\n U = tmp;\n }\n\n this.m = m;\n this.n = n;\n this.s = s;\n this.U = U;\n this.V = V;\n }\n\n /**\n * Solve a problem of least square (Ax=b) by using the SVD. Useful when A is singular. When A is not singular, it would be better to use qr.solve(value).\n * Example : We search to approximate x, with A matrix shape m*n, x vector size n, b vector size m (m > n). We will use :\n * var svd = SingularValueDecomposition(A);\n * var x = svd.solve(b);\n * @param {Matrix} value - Matrix 1D which is the vector b (in the equation Ax = b)\n * @return {Matrix} - The vector x\n */\n solve(value) {\n var Y = value;\n var e = this.threshold;\n var scols = this.s.length;\n var Ls = Matrix.zeros(scols, scols);\n\n for (let i = 0; i < scols; i++) {\n if (Math.abs(this.s[i]) <= e) {\n Ls[i][i] = 0;\n } else {\n Ls[i][i] = 1 / this.s[i];\n }\n }\n\n var U = this.U;\n var V = this.rightSingularVectors;\n\n var VL = V.mmul(Ls);\n var vrows = V.rows;\n var urows = U.length;\n var VLU = Matrix.zeros(vrows, urows);\n\n for (let i = 0; i < vrows; i++) {\n for (let j = 0; j < urows; j++) {\n let sum = 0;\n for (let k = 0; k < scols; k++) {\n sum += VL[i][k] * U[j][k];\n }\n VLU[i][j] = sum;\n }\n }\n\n return VLU.mmul(Y);\n }\n\n /**\n *\n * @param {Array} value\n * @return {Matrix}\n */\n solveForDiagonal(value) {\n return this.solve(Matrix.diag(value));\n }\n\n /**\n * Get the inverse of the matrix. We compute the inverse of a matrix using SVD when this matrix is singular or ill-conditioned. Example :\n * var svd = SingularValueDecomposition(A);\n * var inverseA = svd.inverse();\n * @return {Matrix} - The approximation of the inverse of the matrix\n */\n inverse() {\n var V = this.V;\n var e = this.threshold;\n var vrows = V.length;\n var vcols = V[0].length;\n var X = new Matrix(vrows, this.s.length);\n\n for (let i = 0; i < vrows; i++) {\n for (let j = 0; j < vcols; j++) {\n if (Math.abs(this.s[j]) > e) {\n X[i][j] = V[i][j] / this.s[j];\n } else {\n X[i][j] = 0;\n }\n }\n }\n\n var U = this.U;\n\n var urows = U.length;\n var ucols = U[0].length;\n var Y = new Matrix(vrows, urows);\n\n for (let i = 0; i < vrows; i++) {\n for (let j = 0; j < urows; j++) {\n let sum = 0;\n for (let k = 0; k < ucols; k++) {\n sum += X[i][k] * U[j][k];\n }\n Y[i][j] = sum;\n }\n }\n\n return Y;\n }\n\n /**\n *\n * @return {number}\n */\n get condition() {\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\n }\n\n /**\n *\n * @return {number}\n */\n get norm2() {\n return this.s[0];\n }\n\n /**\n *\n * @return {number}\n */\n get rank() {\n var tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON;\n var r = 0;\n var s = this.s;\n for (var i = 0, ii = s.length; i < ii; i++) {\n if (s[i] > tol) {\n r++;\n }\n }\n return r;\n }\n\n /**\n *\n * @return {Array}\n */\n get diagonal() {\n return this.s;\n }\n\n /**\n *\n * @return {number}\n */\n get threshold() {\n return Number.EPSILON / 2 * Math.max(this.m, this.n) * this.s[0];\n }\n\n /**\n *\n * @return {Matrix}\n */\n get leftSingularVectors() {\n if (!Matrix.isMatrix(this.U)) {\n this.U = new Matrix(this.U);\n }\n return this.U;\n }\n\n /**\n *\n * @return {Matrix}\n */\n get rightSingularVectors() {\n if (!Matrix.isMatrix(this.V)) {\n this.V = new Matrix(this.V);\n }\n return this.V;\n }\n\n /**\n *\n * @return {Matrix}\n */\n get diagonalMatrix() {\n return Matrix.diag(this.s);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/dc/svd.js","'use strict';\n\nvar arrayStat = require('./array');\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nexports.max = function max(matrix) {\n var max = -Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] > max) max = matrix[i][j];\n }\n }\n return max;\n};\n\nexports.min = function min(matrix) {\n var min = Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] < min) min = matrix[i][j];\n }\n }\n return min;\n};\n\nexports.minMax = function minMax(matrix) {\n var min = Infinity;\n var max = -Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] < min) min = matrix[i][j];\n if (matrix[i][j] > max) max = matrix[i][j];\n }\n }\n return {\n min:min,\n max:max\n };\n};\n\nexports.entropy = function entropy(matrix, eps) {\n if (typeof (eps) === 'undefined') {\n eps = 0;\n }\n var sum = 0,\n l1 = matrix.length,\n l2 = matrix[0].length;\n for (var i = 0; i < l1; i++) {\n for (var j = 0; j < l2; j++) {\n sum += matrix[i][j] * Math.log(matrix[i][j] + eps);\n }\n }\n return -sum;\n};\n\nexports.mean = function mean(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theMean, N, i, j;\n\n if (dimension === -1) {\n theMean = [0];\n N = rows * cols;\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theMean[0] += matrix[i][j];\n }\n }\n theMean[0] /= N;\n } else if (dimension === 0) {\n theMean = new Array(cols);\n N = rows;\n for (j = 0; j < cols; j++) {\n theMean[j] = 0;\n for (i = 0; i < rows; i++) {\n theMean[j] += matrix[i][j];\n }\n theMean[j] /= N;\n }\n } else if (dimension === 1) {\n theMean = new Array(rows);\n N = cols;\n for (j = 0; j < rows; j++) {\n theMean[j] = 0;\n for (i = 0; i < cols; i++) {\n theMean[j] += matrix[j][i];\n }\n theMean[j] /= N;\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theMean;\n};\n\nexports.sum = function sum(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theSum, i, j;\n\n if (dimension === -1) {\n theSum = [0];\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theSum[0] += matrix[i][j];\n }\n }\n } else if (dimension === 0) {\n theSum = new Array(cols);\n for (j = 0; j < cols; j++) {\n theSum[j] = 0;\n for (i = 0; i < rows; i++) {\n theSum[j] += matrix[i][j];\n }\n }\n } else if (dimension === 1) {\n theSum = new Array(rows);\n for (j = 0; j < rows; j++) {\n theSum[j] = 0;\n for (i = 0; i < cols; i++) {\n theSum[j] += matrix[j][i];\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theSum;\n};\n\nexports.product = function product(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theProduct, i, j;\n\n if (dimension === -1) {\n theProduct = [1];\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theProduct[0] *= matrix[i][j];\n }\n }\n } else if (dimension === 0) {\n theProduct = new Array(cols);\n for (j = 0; j < cols; j++) {\n theProduct[j] = 1;\n for (i = 0; i < rows; i++) {\n theProduct[j] *= matrix[i][j];\n }\n }\n } else if (dimension === 1) {\n theProduct = new Array(rows);\n for (j = 0; j < rows; j++) {\n theProduct[j] = 1;\n for (i = 0; i < cols; i++) {\n theProduct[j] *= matrix[j][i];\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theProduct;\n};\n\nexports.standardDeviation = function standardDeviation(matrix, means, unbiased) {\n var vari = exports.variance(matrix, means, unbiased), l = vari.length;\n for (var i = 0; i < l; i++) {\n vari[i] = Math.sqrt(vari[i]);\n }\n return vari;\n};\n\nexports.variance = function variance(matrix, means, unbiased) {\n if (typeof (unbiased) === 'undefined') {\n unbiased = true;\n }\n means = means || exports.mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum1 = 0, sum2 = 0, x = 0;\n for (var i = 0; i < rows; i++) {\n x = matrix[i][j] - means[j];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / (rows - 1);\n } else {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / rows;\n }\n }\n return vari;\n};\n\nexports.median = function median(matrix) {\n var rows = matrix.length, cols = matrix[0].length;\n var medians = new Array(cols);\n\n for (var i = 0; i < cols; i++) {\n var data = new Array(rows);\n for (var j = 0; j < rows; j++) {\n data[j] = matrix[j][i];\n }\n data.sort(compareNumbers);\n var N = data.length;\n if (N % 2 === 0) {\n medians[i] = (data[N / 2] + data[(N / 2) - 1]) * 0.5;\n } else {\n medians[i] = data[Math.floor(N / 2)];\n }\n }\n return medians;\n};\n\nexports.mode = function mode(matrix) {\n var rows = matrix.length,\n cols = matrix[0].length,\n modes = new Array(cols),\n i, j;\n for (i = 0; i < cols; i++) {\n var itemCount = new Array(rows);\n for (var k = 0; k < rows; k++) {\n itemCount[k] = 0;\n }\n var itemArray = new Array(rows);\n var count = 0;\n\n for (j = 0; j < rows; j++) {\n var index = itemArray.indexOf(matrix[j][i]);\n if (index >= 0) {\n itemCount[index]++;\n } else {\n itemArray[count] = matrix[j][i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (j = 0; j < count; j++) {\n if (itemCount[j] > maxValue) {\n maxValue = itemCount[j];\n maxIndex = j;\n }\n }\n\n modes[i] = itemArray[maxIndex];\n }\n return modes;\n};\n\nexports.skewness = function skewness(matrix, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var means = exports.mean(matrix);\n var n = matrix.length, l = means.length;\n var skew = new Array(l);\n\n for (var j = 0; j < l; j++) {\n var s2 = 0, s3 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n\n var m2 = s2 / n;\n var m3 = s3 / n;\n var g = m3 / Math.pow(m2, 3 / 2);\n\n if (unbiased) {\n var a = Math.sqrt(n * (n - 1));\n var b = n - 2;\n skew[j] = (a / b) * g;\n } else {\n skew[j] = g;\n }\n }\n return skew;\n};\n\nexports.kurtosis = function kurtosis(matrix, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var means = exports.mean(matrix);\n var n = matrix.length, m = matrix[0].length;\n var kurt = new Array(m);\n\n for (var j = 0; j < m; j++) {\n var s2 = 0, s4 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n kurt[j] = a * b - 3 * c;\n } else {\n kurt[j] = m4 / (m2 * m2) - 3;\n }\n }\n return kurt;\n};\n\nexports.standardError = function standardError(matrix) {\n var samples = matrix.length;\n var standardDeviations = exports.standardDeviation(matrix);\n var l = standardDeviations.length;\n var standardErrors = new Array(l);\n var sqrtN = Math.sqrt(samples);\n\n for (var i = 0; i < l; i++) {\n standardErrors[i] = standardDeviations[i] / sqrtN;\n }\n return standardErrors;\n};\n\nexports.covariance = function covariance(matrix, dimension) {\n return exports.scatter(matrix, undefined, dimension);\n};\n\nexports.scatter = function scatter(matrix, divisor, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n if (typeof (divisor) === 'undefined') {\n if (dimension === 0) {\n divisor = matrix.length - 1;\n } else if (dimension === 1) {\n divisor = matrix[0].length - 1;\n }\n }\n var means = exports.mean(matrix, dimension);\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, s, k;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n};\n\nexports.correlation = function correlation(matrix) {\n var means = exports.mean(matrix),\n standardDeviations = exports.standardDeviation(matrix, true, means),\n scores = exports.zScores(matrix, means, standardDeviations),\n rows = matrix.length,\n cols = matrix[0].length,\n i, j;\n\n var cor = new Array(cols);\n for (i = 0; i < cols; i++) {\n cor[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n var c = 0;\n for (var k = 0, l = scores.length; k < l; k++) {\n c += scores[k][j] * scores[k][i];\n }\n c /= rows - 1;\n cor[i][j] = c;\n cor[j][i] = c;\n }\n }\n return cor;\n};\n\nexports.zScores = function zScores(matrix, means, standardDeviations) {\n means = means || exports.mean(matrix);\n if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix, true, means);\n return exports.standardize(exports.center(matrix, means, false), standardDeviations, true);\n};\n\nexports.center = function center(matrix, means, inPlace) {\n means = means || exports.mean(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var row = result[i];\n for (j = 0, jj = row.length; j < jj; j++) {\n row[j] = matrix[i][j] - means[j];\n }\n }\n return result;\n};\n\nexports.standardize = function standardize(matrix, standardDeviations, inPlace) {\n if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var resultRow = result[i];\n var sourceRow = matrix[i];\n for (j = 0, jj = resultRow.length; j < jj; j++) {\n if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) {\n resultRow[j] = sourceRow[j] / standardDeviations[j];\n }\n }\n }\n return result;\n};\n\nexports.weightedVariance = function weightedVariance(matrix, weights) {\n var means = exports.mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum = 0;\n var a = 0, b = 0;\n\n for (var i = 0; i < rows; i++) {\n var z = matrix[i][j] - means[j];\n var w = weights[i];\n\n sum += w * (z * z);\n b += w;\n a += w * w;\n }\n\n vari[j] = sum * (b / (b * b - a));\n }\n\n return vari;\n};\n\nexports.weightedMean = function weightedMean(matrix, weights, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length,\n means, i, ii, j, w, row;\n\n if (dimension === 0) {\n means = new Array(cols);\n for (i = 0; i < cols; i++) {\n means[i] = 0;\n }\n for (i = 0; i < rows; i++) {\n row = matrix[i];\n w = weights[i];\n for (j = 0; j < cols; j++) {\n means[j] += row[j] * w;\n }\n }\n } else if (dimension === 1) {\n means = new Array(rows);\n for (i = 0; i < rows; i++) {\n means[i] = 0;\n }\n for (j = 0; j < rows; j++) {\n row = matrix[j];\n w = weights[j];\n for (i = 0; i < cols; i++) {\n means[j] += row[i] * w;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n var weightSum = arrayStat.sum(weights);\n if (weightSum !== 0) {\n for (i = 0, ii = means.length; i < ii; i++) {\n means[i] /= weightSum;\n }\n }\n return means;\n};\n\nexports.weightedCovariance = function weightedCovariance(matrix, weights, means, dimension) {\n dimension = dimension || 0;\n means = means || exports.weightedMean(matrix, weights, dimension);\n var s1 = 0, s2 = 0;\n for (var i = 0, ii = weights.length; i < ii; i++) {\n s1 += weights[i];\n s2 += weights[i] * weights[i];\n }\n var factor = s1 / (s1 * s1 - s2);\n return exports.weightedScatter(matrix, weights, means, factor, dimension);\n};\n\nexports.weightedScatter = function weightedScatter(matrix, weights, means, factor, dimension) {\n dimension = dimension || 0;\n means = means || exports.weightedMean(matrix, weights, dimension);\n if (typeof (factor) === 'undefined') {\n factor = 1;\n }\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, k, s;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-stat/matrix.js","/**\n * Computes the maximum of the given values\n * @param {Array} input\n * @return {number}\n */\nexport default function max(input) {\n if (!Array.isArray(input)) {\n throw new Error('input must be an array');\n }\n\n if (input.length === 0) {\n throw new Error('input must not be empty');\n }\n\n var max = input[0];\n for (var i = 1; i < input.length; i++) {\n if (input[i] > max) max = input[i];\n }\n return max;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-array-max/src/index.js","import { Matrix, WrapperMatrix2D } from '../index';\n\n/**\n * @class LuDecomposition\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs\n * @param {Matrix} matrix\n */\nexport default class LuDecomposition {\n constructor(matrix) {\n matrix = WrapperMatrix2D.checkMatrix(matrix);\n\n var lu = matrix.clone();\n var rows = lu.rows;\n var columns = lu.columns;\n var pivotVector = new Array(rows);\n var pivotSign = 1;\n var i, j, k, p, s, t, v;\n var LUcolj, kmax;\n\n for (i = 0; i < rows; i++) {\n pivotVector[i] = i;\n }\n\n LUcolj = new Array(rows);\n\n for (j = 0; j < columns; j++) {\n for (i = 0; i < rows; i++) {\n LUcolj[i] = lu.get(i, j);\n }\n\n for (i = 0; i < rows; i++) {\n kmax = Math.min(i, j);\n s = 0;\n for (k = 0; k < kmax; k++) {\n s += lu.get(i, k) * LUcolj[k];\n }\n LUcolj[i] -= s;\n lu.set(i, j, LUcolj[i]);\n }\n\n p = j;\n for (i = j + 1; i < rows; i++) {\n if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) {\n p = i;\n }\n }\n\n if (p !== j) {\n for (k = 0; k < columns; k++) {\n t = lu.get(p, k);\n lu.set(p, k, lu.get(j, k));\n lu.set(j, k, t);\n }\n\n v = pivotVector[p];\n pivotVector[p] = pivotVector[j];\n pivotVector[j] = v;\n\n pivotSign = -pivotSign;\n }\n\n if (j < rows && lu.get(j, j) !== 0) {\n for (i = j + 1; i < rows; i++) {\n lu.set(i, j, lu.get(i, j) / lu.get(j, j));\n }\n }\n }\n\n this.LU = lu;\n this.pivotVector = pivotVector;\n this.pivotSign = pivotSign;\n }\n\n /**\n *\n * @return {boolean}\n */\n isSingular() {\n var data = this.LU;\n var col = data.columns;\n for (var j = 0; j < col; j++) {\n if (data[j][j] === 0) {\n return true;\n }\n }\n return false;\n }\n\n /**\n *\n * @param {Matrix} value\n * @return {Matrix}\n */\n solve(value) {\n value = Matrix.checkMatrix(value);\n\n var lu = this.LU;\n var rows = lu.rows;\n\n if (rows !== value.rows) {\n throw new Error('Invalid matrix dimensions');\n }\n if (this.isSingular()) {\n throw new Error('LU matrix is singular');\n }\n\n var count = value.columns;\n var X = value.subMatrixRow(this.pivotVector, 0, count - 1);\n var columns = lu.columns;\n var i, j, k;\n\n for (k = 0; k < columns; k++) {\n for (i = k + 1; i < columns; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * lu[i][k];\n }\n }\n }\n for (k = columns - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X[k][j] /= lu[k][k];\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * lu[i][k];\n }\n }\n }\n return X;\n }\n\n /**\n *\n * @return {number}\n */\n get determinant() {\n var data = this.LU;\n if (!data.isSquare()) {\n throw new Error('Matrix must be square');\n }\n var determinant = this.pivotSign;\n var col = data.columns;\n for (var j = 0; j < col; j++) {\n determinant *= data[j][j];\n }\n return determinant;\n }\n\n /**\n *\n * @return {Matrix}\n */\n get lowerTriangularMatrix() {\n var data = this.LU;\n var rows = data.rows;\n var columns = data.columns;\n var X = new Matrix(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n if (i > j) {\n X[i][j] = data[i][j];\n } else if (i === j) {\n X[i][j] = 1;\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n }\n\n /**\n *\n * @return {Matrix}\n */\n get upperTriangularMatrix() {\n var data = this.LU;\n var rows = data.rows;\n var columns = data.columns;\n var X = new Matrix(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n if (i <= j) {\n X[i][j] = data[i][j];\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n }\n\n /**\n *\n * @return {Array}\n */\n get pivotPermutationVector() {\n return this.pivotVector.slice();\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/dc/lu.js","export function hypotenuse(a, b) {\n var r = 0;\n if (Math.abs(a) > Math.abs(b)) {\n r = b / a;\n return Math.abs(a) * Math.sqrt(1 + r * r);\n }\n if (b !== 0) {\n r = a / b;\n return Math.abs(b) * Math.sqrt(1 + r * r);\n }\n return 0;\n}\n\nexport function getFilled2DArray(rows, columns, value) {\n var array = new Array(rows);\n for (var i = 0; i < rows; i++) {\n array[i] = new Array(columns);\n for (var j = 0; j < columns; j++) {\n array[i][j] = value;\n }\n }\n return array;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/dc/util.js","'use strict';\n\nconst Heap = require('heap');\n\nfunction Cluster() {\n this.children = [];\n this.distance = -1;\n this.index = [];\n}\n\n/**\n * Creates an array of values where maximum distance smaller than the threshold\n * @param {number} threshold\n * @return {Array }\n */\nCluster.prototype.cut = function (threshold) {\n if (threshold < 0) throw new RangeError('Threshold too small');\n var root = new Cluster();\n root.children = this.children;\n root.distance = this.distance;\n root.index = this.index;\n var list = [root];\n var ans = [];\n while (list.length > 0) {\n var aux = list.shift();\n if (threshold >= aux.distance) {\n ans.push(aux);\n } else {\n list = list.concat(aux.children);\n }\n }\n return ans;\n};\n\n/**\n * Merge the leaves in the minimum way to have 'minGroups' number of clusters\n * @param {number} minGroups - Them minimum number of children the first level of the tree should have\n * @return {Cluster}\n */\nCluster.prototype.group = function (minGroups) {\n if (!Number.isInteger(minGroups) || minGroups < 1) throw new RangeError('Number of groups must be a positive integer');\n\n const heap = new Heap(function (a, b) {\n return b.distance - a.distance;\n });\n\n heap.push(this);\n\n while (heap.size() < minGroups) {\n var first = heap.pop();\n if (first.children.length === 0) {\n break;\n }\n first.children.forEach(child => heap.push(child));\n }\n\n var root = new Cluster();\n root.children = heap.toArray();\n root.distance = this.distance;\n\n return root;\n};\n\n/**\n * Traverses the tree depth-first and provide callback to be called on each individual node\n * @param {function} cb - The callback to be called on each node encounter\n * @type {Cluster}\n */\nCluster.prototype.traverse = function (cb) {\n function visit(root, callback) {\n callback(root);\n if (root.children) {\n for (var i = root.children.length - 1; i >= 0; i--) {\n visit(root.children[i], callback);\n }\n }\n }\n visit(this, cb);\n};\n\nmodule.exports = Cluster;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-hclust/src/Cluster.js","'use strict';\n\nconst Matrix = require('ml-matrix').Matrix;\n\nconst GaussianKernel = require('ml-kernel-gaussian');\nconst PolynomialKernel = require('ml-kernel-polynomial');\nconst ANOVAKernel = require('./kernels/anova-kernel');\nconst CauchyKernel = require('./kernels/cauchy-kernel');\nconst ExponentialKernel = require('./kernels/exponential-kernel');\nconst HistogramKernel = require('./kernels/histogram-intersection-kernel');\nconst LaplacianKernel = require('./kernels/laplacian-kernel');\nconst MultiquadraticKernel = require('./kernels/multiquadratic-kernel');\nconst RationalKernel = require('./kernels/rational-quadratic-kernel');\nconst SigmoidKernel = require('ml-kernel-sigmoid');\n\nconst kernelType = {\n gaussian: GaussianKernel,\n rbf: GaussianKernel,\n polynomial: PolynomialKernel,\n poly: PolynomialKernel,\n anova: ANOVAKernel,\n cauchy: CauchyKernel,\n exponential: ExponentialKernel,\n histogram: HistogramKernel,\n min: HistogramKernel,\n laplacian: LaplacianKernel,\n multiquadratic: MultiquadraticKernel,\n rational: RationalKernel,\n sigmoid: SigmoidKernel,\n mlp: SigmoidKernel\n};\n\nclass Kernel {\n constructor(type, options) {\n this.kernelType = type;\n if (type === 'linear') return;\n\n if (typeof type === 'string') {\n type = type.toLowerCase();\n\n var KernelConstructor = kernelType[type];\n if (KernelConstructor) {\n this.kernelFunction = new KernelConstructor(options);\n } else {\n throw new Error('unsupported kernel type: ' + type);\n }\n } else if (typeof type === 'object' && typeof type.compute === 'function') {\n this.kernelFunction = type;\n } else {\n throw new TypeError('first argument must be a valid kernel type or instance');\n }\n }\n\n compute(inputs, landmarks) {\n if (landmarks === undefined) {\n landmarks = inputs;\n }\n\n if (this.kernelType === 'linear') {\n var matrix = new Matrix(inputs);\n return matrix.mmul(new Matrix(landmarks).transposeView());\n }\n\n const kernelMatrix = new Matrix(inputs.length, landmarks.length);\n var i, j;\n if (inputs === landmarks) { // fast path, matrix is symmetric\n for (i = 0; i < inputs.length; i++) {\n for (j = i; j < inputs.length; j++) {\n kernelMatrix[i][j] = kernelMatrix[j][i] = this.kernelFunction.compute(inputs[i], inputs[j]);\n }\n }\n } else {\n for (i = 0; i < inputs.length; i++) {\n for (j = 0; j < landmarks.length; j++) {\n kernelMatrix[i][j] = this.kernelFunction.compute(inputs[i], landmarks[j]);\n }\n }\n }\n return kernelMatrix;\n }\n}\n\nmodule.exports = Kernel;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kernel/src/kernel.js","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\n\nexport default class SimpleLinearRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) {\n this.slope = y.slope;\n this.intercept = y.intercept;\n this.coefficients = [y.intercept, y.slope];\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n toJSON() {\n return {\n name: 'simpleLinearRegression',\n slope: this.slope,\n intercept: this.intercept\n };\n }\n\n _predict(x) {\n return this.slope * x + this.intercept;\n }\n\n computeX(y) {\n return (y - this.intercept) / this.slope;\n }\n\n toString(precision) {\n let result = 'f(x) = ';\n if (this.slope !== 0) {\n const xFactor = maybeToPrecision(this.slope, precision);\n result += (xFactor === '1' ? '' : xFactor + ' * ') + 'x';\n if (this.intercept) {\n const absIntercept = Math.abs(this.intercept);\n const operator = absIntercept === this.intercept ? '+' : '-';\n result += ` ${operator} ${maybeToPrecision(absIntercept, precision)}`;\n }\n } else {\n result += maybeToPrecision(this.intercept, precision);\n }\n return result;\n }\n\n toLaTeX(precision) {\n return this.toString(precision);\n }\n\n static load(json) {\n if (json.name !== 'simpleLinearRegression') {\n throw new TypeError('not a SLR model');\n }\n return new SimpleLinearRegression(true, json);\n }\n}\n\nfunction regress(slr, x, y) {\n const n = x.length;\n let xSum = 0;\n let ySum = 0;\n\n let xSquared = 0;\n let xY = 0;\n\n for (let i = 0; i < n; i++) {\n xSum += x[i];\n ySum += y[i];\n xSquared += x[i] * x[i];\n xY += x[i] * y[i];\n }\n\n const numerator = (n * xY - xSum * ySum);\n slr.slope = numerator / (n * xSquared - xSum * xSum);\n slr.intercept = (1 / n) * ySum - slr.slope * (1 / n) * xSum;\n slr.coefficients = [slr.intercept, slr.slope];\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-regression-simple-linear/src/index.js","'use strict';\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toStr = Object.prototype.toString;\nvar defineProperty = Object.defineProperty;\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nvar isArray = function isArray(arr) {\n\tif (typeof Array.isArray === 'function') {\n\t\treturn Array.isArray(arr);\n\t}\n\n\treturn toStr.call(arr) === '[object Array]';\n};\n\nvar isPlainObject = function isPlainObject(obj) {\n\tif (!obj || toStr.call(obj) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tvar hasOwnConstructor = hasOwn.call(obj, 'constructor');\n\tvar hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n\t\treturn false;\n\t}\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor (key in obj) { /**/ }\n\n\treturn typeof key === 'undefined' || hasOwn.call(obj, key);\n};\n\n// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target\nvar setProperty = function setProperty(target, options) {\n\tif (defineProperty && options.name === '__proto__') {\n\t\tdefineProperty(target, options.name, {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\tvalue: options.newValue,\n\t\t\twritable: true\n\t\t});\n\t} else {\n\t\ttarget[options.name] = options.newValue;\n\t}\n};\n\n// Return undefined instead of __proto__ if '__proto__' is not an own property\nvar getProperty = function getProperty(obj, name) {\n\tif (name === '__proto__') {\n\t\tif (!hasOwn.call(obj, name)) {\n\t\t\treturn void 0;\n\t\t} else if (gOPD) {\n\t\t\t// In early versions of node, obj['__proto__'] is buggy when obj has\n\t\t\t// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.\n\t\t\treturn gOPD(obj, name).value;\n\t\t}\n\t}\n\n\treturn obj[name];\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone;\n\tvar target = arguments[0];\n\tvar i = 1;\n\tvar length = arguments.length;\n\tvar deep = false;\n\n\t// Handle a deep copy situation\n\tif (typeof target === 'boolean') {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t}\n\tif (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n\t\ttarget = {};\n\t}\n\n\tfor (; i < length; ++i) {\n\t\toptions = arguments[i];\n\t\t// Only deal with non-null/undefined values\n\t\tif (options != null) {\n\t\t\t// Extend the base object\n\t\t\tfor (name in options) {\n\t\t\t\tsrc = getProperty(target, name);\n\t\t\t\tcopy = getProperty(options, name);\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif (target !== copy) {\n\t\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\t\tif (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {\n\t\t\t\t\t\tif (copyIsArray) {\n\t\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\t\tclone = src && isArray(src) ? src : [];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: extend(deep, clone, copy) });\n\n\t\t\t\t\t// Don't bring in undefined values\n\t\t\t\t\t} else if (typeof copy !== 'undefined') {\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: copy });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/extend/index.js","export {DecisionTreeClassifier} from './DecisionTreeClassifier';\nexport {DecisionTreeRegression} from './DecisionTreeRegression';\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-cart/src/index.js","import max from 'ml-array-max';\nimport min from 'ml-array-min';\n\nexport default function rescale(input, options = {}) {\n if (!Array.isArray(input)) {\n throw new TypeError('input must be an array');\n } else if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n let output;\n if (options.output !== undefined) {\n if (!Array.isArray(options.output)) {\n throw new TypeError('output option must be an array if specified');\n }\n output = options.output;\n } else {\n output = new Array(input.length);\n }\n\n const currentMin = min(input);\n const currentMax = max(input);\n\n if (currentMin === currentMax) {\n throw new RangeError('minimum and maximum input values are equal. Cannot rescale a constant array');\n }\n\n const {\n min: minValue = options.autoMinMax ? currentMin : 0,\n max: maxValue = options.autoMinMax ? currentMax : 1\n } = options;\n\n if (minValue >= maxValue) {\n throw new RangeError('min option must be smaller than max option');\n }\n\n const factor = (maxValue - minValue) / (currentMax - currentMin);\n for (var i = 0; i < input.length; i++) {\n output[i] = (input[i] - currentMin) * factor + minValue;\n }\n\n return output;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-array-rescale/src/index.js","/**\n * Computes the minimum of the given values\n * @param {Array} input\n * @return {number}\n */\nexport default function min(input) {\n if (!Array.isArray(input)) {\n throw new Error('input must be an array');\n }\n\n if (input.length === 0) {\n throw new Error('input must not be empty');\n }\n\n var min = input[0];\n for (var i = 1; i < input.length; i++) {\n if (input[i] < min) min = input[i];\n }\n return min;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-array-min/src/index.js","import AbstractMatrix from '../abstractMatrix';\nimport Matrix from '../matrix';\n\nexport default class WrapperMatrix1D extends AbstractMatrix() {\n /**\n * @class WrapperMatrix1D\n * @param {Array} data\n * @param {object} [options]\n * @param {object} [options.rows = 1]\n */\n constructor(data, options = {}) {\n const { rows = 1 } = options;\n\n if (data.length % rows !== 0) {\n throw new Error('the data length is not divisible by the number of rows');\n }\n super();\n this.rows = rows;\n this.columns = data.length / rows;\n this.data = data;\n }\n\n set(rowIndex, columnIndex, value) {\n var index = this._calculateIndex(rowIndex, columnIndex);\n this.data[index] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n var index = this._calculateIndex(rowIndex, columnIndex);\n return this.data[index];\n }\n\n _calculateIndex(row, column) {\n return row * this.columns + column;\n }\n\n static get [Symbol.species]() {\n return Matrix;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/wrap/WrapperMatrix1D.js","import AbstractMatrix from '../abstractMatrix';\nimport Matrix from '../matrix';\n\nexport default class WrapperMatrix2D extends AbstractMatrix() {\n /**\n * @class WrapperMatrix2D\n * @param {Array>} data\n */\n constructor(data) {\n super();\n this.data = data;\n this.rows = data.length;\n this.columns = data[0].length;\n }\n\n set(rowIndex, columnIndex, value) {\n this.data[rowIndex][columnIndex] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.data[rowIndex][columnIndex];\n }\n\n static get [Symbol.species]() {\n return Matrix;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/wrap/WrapperMatrix2D.js","import { Matrix, WrapperMatrix2D } from '../index';\n\nimport { hypotenuse } from './util';\n\n/**\n * @class QrDecomposition\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs\n * @param {Matrix} value\n */\nexport default class QrDecomposition {\n constructor(value) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n var qr = value.clone();\n var m = value.rows;\n var n = value.columns;\n var rdiag = new Array(n);\n var i, j, k, s;\n\n for (k = 0; k < n; k++) {\n var nrm = 0;\n for (i = k; i < m; i++) {\n nrm = hypotenuse(nrm, qr.get(i, k));\n }\n if (nrm !== 0) {\n if (qr.get(k, k) < 0) {\n nrm = -nrm;\n }\n for (i = k; i < m; i++) {\n qr.set(i, k, qr.get(i, k) / nrm);\n }\n qr.set(k, k, qr.get(k, k) + 1);\n for (j = k + 1; j < n; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr.get(i, k) * qr.get(i, j);\n }\n s = -s / qr.get(k, k);\n for (i = k; i < m; i++) {\n qr.set(i, j, qr.get(i, j) + s * qr.get(i, k));\n }\n }\n }\n rdiag[k] = -nrm;\n }\n\n this.QR = qr;\n this.Rdiag = rdiag;\n }\n\n /**\n * Solve a problem of least square (Ax=b) by using the QR decomposition. Useful when A is rectangular, but not working when A is singular.\n * Example : We search to approximate x, with A matrix shape m*n, x vector size n, b vector size m (m > n). We will use :\n * var qr = QrDecomposition(A);\n * var x = qr.solve(b);\n * @param {Matrix} value - Matrix 1D which is the vector b (in the equation Ax = b)\n * @return {Matrix} - The vector x\n */\n solve(value) {\n value = Matrix.checkMatrix(value);\n\n var qr = this.QR;\n var m = qr.rows;\n\n if (value.rows !== m) {\n throw new Error('Matrix row dimensions must agree');\n }\n if (!this.isFullRank()) {\n throw new Error('Matrix is rank deficient');\n }\n\n var count = value.columns;\n var X = value.clone();\n var n = qr.columns;\n var i, j, k, s;\n\n for (k = 0; k < n; k++) {\n for (j = 0; j < count; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr[i][k] * X[i][j];\n }\n s = -s / qr[k][k];\n for (i = k; i < m; i++) {\n X[i][j] += s * qr[i][k];\n }\n }\n }\n for (k = n - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X[k][j] /= this.Rdiag[k];\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * qr[i][k];\n }\n }\n }\n\n return X.subMatrix(0, n - 1, 0, count - 1);\n }\n\n /**\n *\n * @return {boolean}\n */\n isFullRank() {\n var columns = this.QR.columns;\n for (var i = 0; i < columns; i++) {\n if (this.Rdiag[i] === 0) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *\n * @return {Matrix}\n */\n get upperTriangularMatrix() {\n var qr = this.QR;\n var n = qr.columns;\n var X = new Matrix(n, n);\n var i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n if (i < j) {\n X[i][j] = qr[i][j];\n } else if (i === j) {\n X[i][j] = this.Rdiag[i];\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n }\n\n /**\n *\n * @return {Matrix}\n */\n get orthogonalMatrix() {\n var qr = this.QR;\n var rows = qr.rows;\n var columns = qr.columns;\n var X = new Matrix(rows, columns);\n var i, j, k, s;\n\n for (k = columns - 1; k >= 0; k--) {\n for (i = 0; i < rows; i++) {\n X[i][k] = 0;\n }\n X[k][k] = 1;\n for (j = k; j < columns; j++) {\n if (qr[k][k] !== 0) {\n s = 0;\n for (i = k; i < rows; i++) {\n s += qr[i][k] * X[i][j];\n }\n\n s = -s / qr[k][k];\n\n for (i = k; i < rows; i++) {\n X[i][j] += s * qr[i][k];\n }\n }\n }\n }\n return X;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/dc/qr.js","import Matrix from 'ml-matrix';\nimport * as Utils from './utils';\nimport mean from 'ml-array-mean';\n\nconst gainFunctions = {\n gini: Utils.giniGain,\n regression: Utils.regressionError\n};\n\nconst splitFunctions = {\n mean: Utils.mean\n};\n\nexport default class TreeNode {\n\n /**\n * @private\n * Constructor for a tree node given the options received on the main classes (DecisionTreeClassifier, DecisionTreeRegression)\n * @param {object|TreeNode} options for loading\n * @constructor\n */\n constructor(options) {\n // options parameters\n this.kind = options.kind;\n this.gainFunction = options.gainFunction;\n this.splitFunction = options.splitFunction;\n this.minNumSamples = options.minNumSamples;\n this.maxDepth = options.maxDepth;\n }\n\n /**\n * @private\n * Function that retrieve the best feature to make the split.\n * @param {Matrix} XTranspose - Training set transposed\n * @param {Array} y - labels or values (depending of the decision tree)\n * @return {object} - return tree values, the best gain, column and the split value.\n */\n bestSplit(XTranspose, y) {\n\n // Depending in the node tree class, we set the variables to check information gain (to classify)\n // or error (for regression)\n\n var bestGain = this.kind === 'classifier' ? -Infinity : Infinity;\n var check = this.kind === 'classifier' ? (a, b) => a > b : (a, b) => a < b;\n\n\n var maxColumn;\n var maxValue;\n\n for (var i = 0; i < XTranspose.rows; ++i) {\n var currentFeature = XTranspose[i];\n var splitValues = this.featureSplit(currentFeature, y);\n for (var j = 0; j < splitValues.length; ++j) {\n var currentSplitVal = splitValues[j];\n var splitted = this.split(currentFeature, y, currentSplitVal);\n\n var gain = gainFunctions[this.gainFunction](y, splitted);\n if (check(gain, bestGain)) {\n maxColumn = i;\n maxValue = currentSplitVal;\n bestGain = gain;\n }\n }\n }\n\n return {\n maxGain: bestGain,\n maxColumn: maxColumn,\n maxValue: maxValue\n };\n }\n\n /**\n * @private\n * Makes the split of the training labels or values from the training set feature given a split value.\n * @param {Array} x - Training set feature\n * @param {Array} y - Training set value or label\n * @param {number} splitValue\n * @return {object}\n */\n\n split(x, y, splitValue) {\n var lesser = [];\n var greater = [];\n\n for (var i = 0; i < x.length; ++i) {\n if (x[i] < splitValue) {\n lesser.push(y[i]);\n } else {\n greater.push(y[i]);\n }\n }\n\n return {\n greater: greater,\n lesser: lesser\n };\n }\n\n /**\n * @private\n * Calculates the possible points to split over the tree given a training set feature and corresponding labels or values.\n * @param {Array} x - Training set feature\n * @param {Array} y - Training set value or label\n * @return {Array} possible split values.\n */\n featureSplit(x, y) {\n var splitValues = [];\n var arr = Utils.zip(x, y);\n arr.sort(function (a, b) {\n return a[0] - b[0];\n });\n\n for (var i = 1; i < arr.length; ++i) {\n if (arr[i - 1][1] !== arr[i][1]) {\n splitValues.push(splitFunctions[this.splitFunction](arr[i - 1][0], arr[i][0]));\n }\n }\n\n return splitValues;\n }\n\n /**\n * @private\n * Calculate the predictions of a leaf tree node given the training labels or values\n * @param {Array} y\n */\n calculatePrediction(y) {\n if (this.kind === 'classifier') {\n this.distribution = Utils.toDiscreteDistribution(y, Utils.getNumberOfClasses(y));\n if (this.distribution.columns === 0) {\n throw new TypeError('Error on calculate the prediction');\n }\n } else {\n this.distribution = mean(y);\n }\n }\n\n /**\n * @private\n * Train a node given the training set and labels, because it trains recursively, it also receive\n * the current depth of the node, parent gain to avoid infinite recursion and boolean value to check if\n * the training set is transposed.\n * @param {Matrix} X - Training set (could be transposed or not given transposed).\n * @param {Array} y - Training labels or values.\n * @param {number} currentDepth - Current depth of the node.\n * @param {number} parentGain - parent node gain or error.\n */\n train(X, y, currentDepth, parentGain) {\n if (X.rows <= this.minNumSamples) {\n this.calculatePrediction(y);\n return;\n }\n if (parentGain === undefined) parentGain = 0.0;\n\n var XTranspose = X.transpose();\n var split = this.bestSplit(XTranspose, y);\n\n this.splitValue = split.maxValue;\n this.splitColumn = split.maxColumn;\n this.gain = split.maxGain;\n\n var splittedMatrix = Utils.matrixSplitter(X, y, this.splitColumn, this.splitValue);\n\n if (currentDepth < this.maxDepth &&\n (this.gain > 0.01 && this.gain !== parentGain) &&\n (splittedMatrix.lesserX.length > 0 && splittedMatrix.greaterX.length > 0)) {\n this.left = new TreeNode(this);\n this.right = new TreeNode(this);\n\n var lesserX = new Matrix(splittedMatrix.lesserX);\n var greaterX = new Matrix(splittedMatrix.greaterX);\n\n this.left.train(lesserX, splittedMatrix.lesserY, currentDepth + 1, this.gain);\n this.right.train(greaterX, splittedMatrix.greaterY, currentDepth + 1, this.gain);\n } else {\n this.calculatePrediction(y);\n }\n }\n\n /**\n * @private\n * Calculates the prediction of a given element.\n * @param {Array} row\n * @return {number|Array} prediction\n * * if a node is a classifier returns an array of probabilities of each class.\n * * if a node is for regression returns a number with the prediction.\n */\n classify(row) {\n if (this.right && this.left) {\n if (row[this.splitColumn] < this.splitValue) {\n return this.left.classify(row);\n } else {\n return this.right.classify(row);\n }\n }\n\n return this.distribution;\n }\n\n /**\n * @private\n * Set the parameter of the current node and their children.\n * @param {object} node - parameters of the current node and the children.\n */\n setNodeParameters(node) {\n if (node.distribution !== undefined) {\n this.distribution = node.distribution.constructor === Array ? new Matrix(node.distribution) :\n node.distribution;\n } else {\n this.distribution = undefined;\n this.splitValue = node.splitValue;\n this.splitColumn = node.splitColumn;\n this.gain = node.gain;\n\n this.left = new TreeNode(this);\n this.right = new TreeNode(this);\n\n if (node.left !== {}) {\n this.left.setNodeParameters(node.left);\n }\n if (node.right !== {}) {\n this.right.setNodeParameters(node.right);\n }\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-cart/src/TreeNode.js","import {\n DecisionTreeClassifier as DTClassifier,\n DecisionTreeRegression as DTRegression\n} from 'ml-cart';\nimport { Matrix, WrapperMatrix2D } from 'ml-matrix';\n\nimport * as Utils from './utils';\n\n/**\n * @class RandomForestBase\n */\nexport class RandomForestBase {\n /**\n * Create a new base random forest for a classifier or regression model.\n * @constructor\n * @param {object} options\n * @param {number|String} [options.maxFeatures] - the number of features used on each estimator.\n * * if is an integer it selects maxFeatures elements over the sample features.\n * * if is a float between (0, 1), it takes the percentage of features.\n * @param {boolean} [options.replacement] - use replacement over the sample features.\n * @param {number} [options.seed] - seed for feature and samples selection, must be a 32-bit integer.\n * @param {number} [options.nEstimators] - number of estimator to use.\n * @param {object} [options.treeOptions] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/}\n * @param {boolean} [options.isClassifier] - boolean to check if is a classifier or regression model (used by subclasses).\n * @param {boolean} [options.useSampleBagging] - use bagging over training samples.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.replacement = model.replacement;\n this.maxFeatures = model.maxFeatures;\n this.nEstimators = model.nEstimators;\n this.treeOptions = model.treeOptions;\n this.isClassifier = model.isClassifier;\n this.seed = model.seed;\n this.n = model.n;\n this.indexes = model.indexes;\n this.useSampleBagging = model.useSampleBagging;\n\n var Estimator = this.isClassifier ? DTClassifier : DTRegression;\n this.estimators = model.estimators.map((est) => Estimator.load(est));\n } else {\n this.replacement = options.replacement;\n this.maxFeatures = options.maxFeatures;\n this.nEstimators = options.nEstimators;\n this.treeOptions = options.treeOptions;\n this.isClassifier = options.isClassifier;\n this.seed = options.seed;\n this.useSampleBagging = options.useSampleBagging;\n }\n }\n\n /**\n * Train the decision tree with the given training set and labels.\n * @param {Matrix|Array} trainingSet\n * @param {Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n\n this.maxFeatures = this.maxFeatures || trainingSet.columns;\n\n if (Utils.checkFloat(this.maxFeatures)) {\n this.n = Math.floor(trainingSet.columns * this.maxFeatures);\n } else if (Number.isInteger(this.maxFeatures)) {\n if (this.maxFeatures > trainingSet.columns) {\n throw new RangeError(`The maxFeatures parameter should be less than ${trainingSet.columns}`);\n } else {\n this.n = this.maxFeatures;\n }\n } else {\n throw new RangeError(`Cannot process the maxFeatures parameter ${this.maxFeatures}`);\n }\n\n\n if (this.isClassifier) {\n var Estimator = DTClassifier;\n } else {\n Estimator = DTRegression;\n }\n\n this.estimators = new Array(this.nEstimators);\n this.indexes = new Array(this.nEstimators);\n\n for (var i = 0; i < this.nEstimators; ++i) {\n var res = this.useSampleBagging ? Utils.examplesBaggingWithReplacement(trainingSet, trainingValues, this.seed) : { X: trainingSet, y: trainingValues };\n var X = res.X;\n var y = res.y;\n\n res = Utils.featureBagging(X, this.n, this.replacement, this.seed);\n X = res.X;\n\n this.indexes[i] = res.usedIndex;\n this.estimators[i] = new Estimator(this.treeOptions);\n this.estimators[i].train(X, y);\n }\n }\n\n /**\n * Method that returns the way the algorithm generates the predictions, for example, in classification\n * you can return the mode of all predictions retrieved by the trees, or in case of regression you can\n * use the mean or the median.\n * @abstract\n * @param {Array} values - predictions of the estimators.\n * @return {number} prediction.\n */\n // eslint-disable-next-line no-unused-vars\n selection(values) {\n throw new Error('Abstract method \\'selection\\' not implemented!');\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Matrix|Array} toPredict\n * @return {Array} predictions\n */\n predict(toPredict) {\n var predictionValues = new Array(this.nEstimators);\n toPredict = Matrix.checkMatrix(toPredict);\n for (var i = 0; i < this.nEstimators; ++i) {\n var X = toPredict.columnSelectionView(this.indexes[i]); // get features for estimator\n predictionValues[i] = this.estimators[i].predict(X);\n }\n\n predictionValues = new WrapperMatrix2D(predictionValues).transposeView();\n var predictions = new Array(predictionValues.rows);\n for (i = 0; i < predictionValues.rows; ++i) {\n predictions[i] = this.selection(predictionValues.getRow(i));\n }\n\n return predictions;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n indexes: this.indexes,\n n: this.n,\n replacement: this.replacement,\n maxFeatures: this.maxFeatures,\n nEstimators: this.nEstimators,\n treeOptions: this.treeOptions,\n isClassifier: this.isClassifier,\n seed: this.seed,\n estimators: this.estimators.map((est) => est.toJSON()),\n useSampleBagging: this.useSampleBagging\n };\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-random-forest/src/RandomForestBase.js","import quickSelectMedian from 'median-quickselect';\n\n/**\n * Computes the median of the given values\n * @param {Array} input\n * @return {number}\n */\nexport default function median(input) {\n if (!Array.isArray(input)) {\n throw new Error('input must be an array');\n }\n\n if (input.length === 0) {\n throw new Error('input must not be empty');\n }\n\n return quickSelectMedian(input.slice());\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-array-median/src/index.js","'use strict';\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\n/**\n * Computes the sum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.sum = function sum(values) {\n var sum = 0;\n for (var i = 0; i < values.length; i++) {\n sum += values[i];\n }\n return sum;\n};\n\n/**\n * Computes the maximum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.max = function max(values) {\n var max = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] > max) max = values[i];\n }\n return max;\n};\n\n/**\n * Computes the minimum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.min = function min(values) {\n var min = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] < min) min = values[i];\n }\n return min;\n};\n\n/**\n * Computes the min and max of the given values\n * @param {Array} values\n * @returns {{min: number, max: number}}\n */\nexports.minMax = function minMax(values) {\n var min = values[0];\n var max = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] < min) min = values[i];\n if (values[i] > max) max = values[i];\n }\n return {\n min: min,\n max: max\n };\n};\n\n/**\n * Computes the arithmetic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.arithmeticMean = function arithmeticMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n sum += values[i];\n }\n return sum / l;\n};\n\n/**\n * {@link arithmeticMean}\n */\nexports.mean = exports.arithmeticMean;\n\n/**\n * Computes the geometric mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.geometricMean = function geometricMean(values) {\n var mul = 1;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n mul *= values[i];\n }\n return Math.pow(mul, 1 / l);\n};\n\n/**\n * Computes the mean of the log of the given values\n * If the return value is exponentiated, it gives the same result as the\n * geometric mean.\n * @param {Array} values\n * @returns {number}\n */\nexports.logMean = function logMean(values) {\n var lnsum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n lnsum += Math.log(values[i]);\n }\n return lnsum / l;\n};\n\n/**\n * Computes the weighted grand mean for a list of means and sample sizes\n * @param {Array} means - Mean values for each set of samples\n * @param {Array} samples - Number of original values for each set of samples\n * @returns {number}\n */\nexports.grandMean = function grandMean(means, samples) {\n var sum = 0;\n var n = 0;\n var l = means.length;\n for (var i = 0; i < l; i++) {\n sum += samples[i] * means[i];\n n += samples[i];\n }\n return sum / n;\n};\n\n/**\n * Computes the truncated mean of the given values using a given percentage\n * @param {Array} values\n * @param {number} percent - The percentage of values to keep (range: [0,1])\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.truncatedMean = function truncatedMean(values, percent, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var k = Math.floor(l * percent);\n var sum = 0;\n for (var i = k; i < (l - k); i++) {\n sum += values[i];\n }\n return sum / (l - 2 * k);\n};\n\n/**\n * Computes the harmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.harmonicMean = function harmonicMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (values[i] === 0) {\n throw new RangeError('value at index ' + i + 'is zero');\n }\n sum += 1 / values[i];\n }\n return l / sum;\n};\n\n/**\n * Computes the contraharmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.contraHarmonicMean = function contraHarmonicMean(values) {\n var r1 = 0;\n var r2 = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n r1 += values[i] * values[i];\n r2 += values[i];\n }\n if (r2 < 0) {\n throw new RangeError('sum of values is negative');\n }\n return r1 / r2;\n};\n\n/**\n * Computes the median of the given values\n * @param {Array} values\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.median = function median(values, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return (values[half - 1] + values[half]) * 0.5;\n } else {\n return values[half];\n }\n};\n\n/**\n * Computes the variance of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.variance = function variance(values, unbiased) {\n if (unbiased === undefined) unbiased = true;\n var theMean = exports.mean(values);\n var theVariance = 0;\n var l = values.length;\n\n for (var i = 0; i < l; i++) {\n var x = values[i] - theMean;\n theVariance += x * x;\n }\n\n if (unbiased) {\n return theVariance / (l - 1);\n } else {\n return theVariance / l;\n }\n};\n\n/**\n * Computes the standard deviation of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.standardDeviation = function standardDeviation(values, unbiased) {\n return Math.sqrt(exports.variance(values, unbiased));\n};\n\nexports.standardError = function standardError(values) {\n return exports.standardDeviation(values) / Math.sqrt(values.length);\n};\n\n/**\n * IEEE Transactions on biomedical engineering, vol. 52, no. 1, january 2005, p. 76-\n * Calculate the standard deviation via the Median of the absolute deviation\n * The formula for the standard deviation only holds for Gaussian random variables.\n * @returns {{mean: number, stdev: number}}\n */\nexports.robustMeanAndStdev = function robustMeanAndStdev(y) {\n var mean = 0, stdev = 0;\n var length = y.length, i = 0;\n for (i = 0; i < length; i++) {\n mean += y[i];\n }\n mean /= length;\n var averageDeviations = new Array(length);\n for (i = 0; i < length; i++)\n averageDeviations[i] = Math.abs(y[i] - mean);\n averageDeviations.sort(compareNumbers);\n if (length % 2 === 1) {\n stdev = averageDeviations[(length - 1) / 2] / 0.6745;\n } else {\n stdev = 0.5 * (averageDeviations[length / 2] + averageDeviations[length / 2 - 1]) / 0.6745;\n }\n\n return {\n mean: mean,\n stdev: stdev\n };\n};\n\nexports.quartiles = function quartiles(values, alreadySorted) {\n if (typeof (alreadySorted) === 'undefined') alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n\n var quart = values.length / 4;\n var q1 = values[Math.ceil(quart) - 1];\n var q2 = exports.median(values, true);\n var q3 = values[Math.ceil(quart * 3) - 1];\n\n return {q1: q1, q2: q2, q3: q3};\n};\n\nexports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) {\n return Math.sqrt(exports.pooledVariance(samples, unbiased));\n};\n\nexports.pooledVariance = function pooledVariance(samples, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var sum = 0;\n var length = 0, l = samples.length;\n for (var i = 0; i < l; i++) {\n var values = samples[i];\n var vari = exports.variance(values);\n\n sum += (values.length - 1) * vari;\n\n if (unbiased)\n length += values.length - 1;\n else\n length += values.length;\n }\n return sum / length;\n};\n\nexports.mode = function mode(values) {\n var l = values.length,\n itemCount = new Array(l),\n i;\n for (i = 0; i < l; i++) {\n itemCount[i] = 0;\n }\n var itemArray = new Array(l);\n var count = 0;\n\n for (i = 0; i < l; i++) {\n var index = itemArray.indexOf(values[i]);\n if (index >= 0)\n itemCount[index]++;\n else {\n itemArray[count] = values[i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (i = 0; i < count; i++) {\n if (itemCount[i] > maxValue) {\n maxValue = itemCount[i];\n maxIndex = i;\n }\n }\n\n return itemArray[maxIndex];\n};\n\nexports.covariance = function covariance(vector1, vector2, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var mean1 = exports.mean(vector1);\n var mean2 = exports.mean(vector2);\n\n if (vector1.length !== vector2.length)\n throw 'Vectors do not have the same dimensions';\n\n var cov = 0, l = vector1.length;\n for (var i = 0; i < l; i++) {\n var x = vector1[i] - mean1;\n var y = vector2[i] - mean2;\n cov += x * y;\n }\n\n if (unbiased)\n return cov / (l - 1);\n else\n return cov / l;\n};\n\nexports.skewness = function skewness(values, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n\n var s2 = 0, s3 = 0, l = values.length;\n for (var i = 0; i < l; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n var m2 = s2 / l;\n var m3 = s3 / l;\n\n var g = m3 / (Math.pow(m2, 3 / 2.0));\n if (unbiased) {\n var a = Math.sqrt(l * (l - 1));\n var b = l - 2;\n return (a / b) * g;\n } else {\n return g;\n }\n};\n\nexports.kurtosis = function kurtosis(values, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n var n = values.length, s2 = 0, s4 = 0;\n\n for (var i = 0; i < n; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n\n return a * b - 3 * c;\n } else {\n return m4 / (m2 * m2) - 3;\n }\n};\n\nexports.entropy = function entropy(values, eps) {\n if (typeof (eps) === 'undefined') eps = 0;\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * Math.log(values[i] + eps);\n return -sum;\n};\n\nexports.weightedMean = function weightedMean(values, weights) {\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * weights[i];\n return sum;\n};\n\nexports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) {\n return Math.sqrt(exports.weightedVariance(values, weights));\n};\n\nexports.weightedVariance = function weightedVariance(values, weights) {\n var theMean = exports.weightedMean(values, weights);\n var vari = 0, l = values.length;\n var a = 0, b = 0;\n\n for (var i = 0; i < l; i++) {\n var z = values[i] - theMean;\n var w = weights[i];\n\n vari += w * (z * z);\n b += w;\n a += w * w;\n }\n\n return vari * (b / (b * b - a));\n};\n\nexports.center = function center(values, inPlace) {\n if (typeof (inPlace) === 'undefined') inPlace = false;\n\n var result = values;\n if (!inPlace)\n result = [].concat(values);\n\n var theMean = exports.mean(result), l = result.length;\n for (var i = 0; i < l; i++)\n result[i] -= theMean;\n};\n\nexports.standardize = function standardize(values, standardDev, inPlace) {\n if (typeof (standardDev) === 'undefined') standardDev = exports.standardDeviation(values);\n if (typeof (inPlace) === 'undefined') inPlace = false;\n var l = values.length;\n var result = inPlace ? values : new Array(l);\n for (var i = 0; i < l; i++)\n result[i] = values[i] / standardDev;\n return result;\n};\n\nexports.cumulativeSum = function cumulativeSum(array) {\n var l = array.length;\n var result = new Array(l);\n result[0] = array[0];\n for (var i = 1; i < l; i++)\n result[i] = result[i - 1] + array[i];\n return result;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-stat/array.js","'use strict';\n\nconst Cluster = require('./Cluster');\nconst util = require('util');\n\nfunction ClusterLeaf(index) {\n Cluster.call(this);\n this.index = index;\n this.distance = 0;\n this.children = [];\n}\n\nutil.inherits(ClusterLeaf, Cluster);\n\nmodule.exports = ClusterLeaf;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-hclust/src/ClusterLeaf.js","'use strict';\n\n\n/**\n * Computes a distance/similarity matrix given an array of data and a distance/similarity function.\n * @param {Array} data An array of data\n * @param {function} distanceFn A function that accepts two arguments and computes a distance/similarity between them\n * @return {Array} The similarity matrix. The similarity matrix is square and has a size equal to the length of\n * the data array\n */\nfunction distanceMatrix(data, distanceFn) {\n const length = data.length;\n let result = Array.from({length}).map(() => Array.from({length}));\n\n // Compute upper distance matrix\n for (let i = 0; i < length; i++) {\n for (let j = 0; j <= i; j++) {\n result[i][j] = distanceFn(data[i], data[j]);\n }\n }\n\n // Copy to lower distance matrix\n for (let i = 0; i < length; i++) {\n for (let j = i + 1; j < length; j++) {\n result[i][j] = result[j][i];\n }\n }\n\n return result;\n}\n\nmodule.exports = distanceMatrix;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance-matrix/src/index.js","import nearestVector from 'ml-nearest-vector';\n\n/**\n * Calculates the distance matrix for a given array of points\n * @ignore\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @param {function} distance - Distance function to use between the points\n * @return {Array>} - matrix with the distance values\n */\nexport function calculateDistanceMatrix(data, distance) {\n var distanceMatrix = new Array(data.length);\n for (var i = 0; i < data.length; ++i) {\n for (var j = i; j < data.length; ++j) {\n if (!distanceMatrix[i]) {\n distanceMatrix[i] = new Array(data.length);\n }\n if (!distanceMatrix[j]) {\n distanceMatrix[j] = new Array(data.length);\n }\n const dist = distance(data[i], data[j]);\n distanceMatrix[i][j] = dist;\n distanceMatrix[j][i] = dist;\n }\n }\n return distanceMatrix;\n}\n\n/**\n * Updates the cluster identifier based in the new data\n * @ignore\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @param {Array>} centers - the K centers in format [x,y,z,...]\n * @param {Array } clusterID - the cluster identifier for each data dot\n * @param {function} distance - Distance function to use between the points\n * @return {Array} the cluster identifier for each data dot\n */\nexport function updateClusterID(data, centers, clusterID, distance) {\n for (var i = 0; i < data.length; i++) {\n clusterID[i] = nearestVector(centers, data[i], {\n distanceFunction: distance\n });\n }\n return clusterID;\n}\n\n/**\n * Update the center values based in the new configurations of the clusters\n * @ignore\n * @param {Array>} prevCenters - Centroids from the previous iteration\n * @param {Array >} data - the [x,y,z,...] points to cluster\n * @param {Array } clusterID - the cluster identifier for each data dot\n * @param {number} K - Number of clusters\n * @return {Array} he K centers in format [x,y,z,...]\n */\nexport function updateCenters(prevCenters, data, clusterID, K) {\n const nDim = data[0].length;\n\n // copy previous centers\n var centers = new Array(K);\n var centersLen = new Array(K);\n for (var i = 0; i < K; i++) {\n centers[i] = new Array(nDim);\n centersLen[i] = 0;\n for (var j = 0; j < nDim; j++) {\n centers[i][j] = 0;\n }\n }\n\n // add the value for all dimensions of the point\n for (var l = 0; l < data.length; l++) {\n centersLen[clusterID[l]]++;\n for (var dim = 0; dim < nDim; dim++) {\n centers[clusterID[l]][dim] += data[l][dim];\n }\n }\n\n // divides by length\n for (var id = 0; id < K; id++) {\n for (var d = 0; d < nDim; d++) {\n if (centersLen[id]) {\n centers[id][d] /= centersLen[id];\n } else {\n centers[id][d] = prevCenters[id][d];\n }\n }\n }\n return centers;\n}\n\n/**\n * The centers have moved more than the tolerance value?\n * @ignore\n * @param {Array>} centers - the K centers in format [x,y,z,...]\n * @param {Array>} oldCenters - the K old centers in format [x,y,z,...]\n * @param {function} distanceFunction - Distance function to use between the points\n * @param {number} tolerance - Allowed distance for the centroids to move\n * @return {boolean}\n */\nexport function hasConverged(centers, oldCenters, distanceFunction, tolerance) {\n for (var i = 0; i < centers.length; i++) {\n if (distanceFunction(centers[i], oldCenters[i]) > tolerance) {\n return false;\n }\n }\n return true;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kmeans/src/utils.js","// tslint:disable-next-line\nconst XSAdd = require('ml-xsadd');\nimport choice from './choice';\n/**\n * @classdesc Random class\n */\nexport default class Random {\n /**\n * @param [seedOrRandom=Math.random] - Control the random number generator used by the Random class instance. Pass a random number generator function with a uniform distribution over the half-open interval [0, 1[. If seed will pass it to ml-xsadd to create a seeded random number generator. If undefined will use Math.random.\n */\n constructor(seedOrRandom = Math.random) {\n if (typeof seedOrRandom === 'number') {\n const xsadd = new XSAdd(seedOrRandom);\n this.randomGenerator = xsadd.random;\n }\n else {\n this.randomGenerator = seedOrRandom;\n }\n }\n choice(values, options) {\n if (typeof values === 'number') {\n return choice(values, options, this.randomGenerator);\n }\n return choice(values, options, this.randomGenerator);\n }\n /**\n * Draw a random number from a uniform distribution on [0,1)\n * @return The random number\n */\n random() {\n return this.randomGenerator();\n }\n /**\n * Draw a random integer from a uniform distribution on [low, high). If only low is specified, the number is drawn on [0, low)\n * @param low - The lower bound of the uniform distribution interval.\n * @param high - The higher bound of the uniform distribution interval.\n */\n randInt(low, high) {\n if (high === undefined) {\n high = low;\n low = 0;\n }\n return low + Math.floor(this.randomGenerator() * (high - low));\n }\n /**\n * Draw several random number from a uniform distribution on [0, 1)\n * @param size - The number of number to draw\n * @return - The list of drawn numbers.\n */\n randomSample(size) {\n const result = [];\n for (let i = 0; i < size; i++) {\n result.push(this.random());\n }\n return result;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-random/lib-es6/index.js","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _createClass = (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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar LOOP = 8;\nvar FLOAT_MUL = 1 / 16777216;\n\nfunction multiply_uint32(n, m) {\n n >>>= 0;\n m >>>= 0;\n var nlo = n & 0xffff;\n var nhi = n - nlo;\n return (nhi * m >>> 0) + nlo * m >>> 0;\n}\n\nvar XSadd = (function () {\n function XSadd() {\n var seed = arguments.length <= 0 || arguments[0] === undefined ? Date.now() : arguments[0];\n\n _classCallCheck(this, XSadd);\n\n this.state = new Uint32Array(4);\n this.init(seed);\n }\n\n _createClass(XSadd, [{\n key: \"init\",\n value: function init(seed) {\n this.state[0] = seed;\n this.state[1] = 0;\n this.state[2] = 0;\n this.state[3] = 0;\n for (var i = 1; i < LOOP; i++) {\n this.state[i & 3] ^= i + multiply_uint32(1812433253, this.state[i - 1 & 3] ^ this.state[i - 1 & 3] >>> 30 >>> 0) >>> 0;\n }\n period_certification(this);\n for (var i = 0; i < LOOP; i++) {\n next_state(this);\n }\n }\n\n /**\n * Returns a 32-bit integer r (0 <= r < 2^32)\n */\n }, {\n key: \"getUint32\",\n value: function getUint32() {\n next_state(this);\n return this.state[3] + this.state[2] >>> 0;\n }\n\n /**\n * Returns a floating point number r (0.0 <= r < 1.0)\n */\n }, {\n key: \"getFloat\",\n value: function getFloat() {\n return (this.getUint32() >>> 8) * FLOAT_MUL;\n }\n }, {\n key: \"random\",\n get: function get() {\n if (!this._random) {\n this._random = this.getFloat.bind(this);\n }\n return this._random;\n }\n }]);\n\n return XSadd;\n})();\n\nexports[\"default\"] = XSadd;\n\nfunction period_certification(xsadd) {\n if (xsadd.state[0] === 0 && xsadd.state[1] === 0 && xsadd.state[2] === 0 && xsadd.state[3] === 0) {\n xsadd.state[0] = 88; // X\n xsadd.state[1] = 83; // S\n xsadd.state[2] = 65; // A\n xsadd.state[3] = 68; // D\n }\n}\n\nvar sh1 = 15;\nvar sh2 = 18;\nvar sh3 = 11;\nfunction next_state(xsadd) {\n var t = xsadd.state[0];\n t ^= t << sh1;\n t ^= t >>> sh2;\n t ^= xsadd.state[3] << sh3;\n xsadd.state[0] = xsadd.state[1];\n xsadd.state[1] = xsadd.state[2];\n xsadd.state[2] = xsadd.state[3];\n xsadd.state[3] = t;\n}\nmodule.exports = exports[\"default\"];\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-xsadd/xsadd-es5.js","import Matrix from 'ml-matrix';\n\n/**\n * @private\n * Function that retuns an array of matrices of the cases that belong to each class.\n * @param {Matrix} X - dataset\n * @param {Array} y - predictions\n * @return {Array}\n */\nexport function separateClasses(X, y) {\n var features = X.columns;\n\n var classes = 0;\n var totalPerClasses = new Array(10000); // max upperbound of classes\n for (var i = 0; i < y.length; i++) {\n if (totalPerClasses[y[i]] === undefined) {\n totalPerClasses[y[i]] = 0;\n classes++;\n }\n totalPerClasses[y[i]]++;\n }\n var separatedClasses = new Array(classes);\n var currentIndex = new Array(classes);\n for (i = 0; i < classes; ++i) {\n separatedClasses[i] = new Matrix(totalPerClasses[i], features);\n currentIndex[i] = 0;\n }\n for (i = 0; i < X.rows; ++i) {\n separatedClasses[y[i]].setRow(currentIndex[y[i]], X.getRow(i));\n currentIndex[y[i]]++;\n }\n return separatedClasses;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-naivebayes/src/utils.js","import Matrix from 'ml-matrix';\nimport Stat from 'ml-stat/matrix';\n\n/**\n * @private\n * Function that given vector, returns his norm\n * @param {Vector} X\n * @return {number} Norm of the vector\n */\nexport function norm(X) {\n return Math.sqrt(X.clone().apply(pow2array).sum());\n}\n\n/**\n * @private\n * Function that pow 2 each element of a Matrix or a Vector,\n * used in the apply method of the Matrix object\n * @param {number} i - index i.\n * @param {number} j - index j.\n * @return {Matrix} The Matrix object modified at the index i, j.\n * */\nexport function pow2array(i, j) {\n this[i][j] = this[i][j] * this[i][j];\n return this;\n}\n\n/**\n * @private\n * Function that normalize the dataset and return the means and\n * standard deviation of each feature.\n * @param {Matrix} dataset\n * @return {object} dataset normalized, means and standard deviations\n */\nexport function featureNormalize(dataset) {\n var means = Stat.mean(dataset);\n var std = Stat.standardDeviation(dataset, means, true);\n var result = Matrix.checkMatrix(dataset).subRowVector(means);\n return {result: result.divRowVector(std), means: means, std: std};\n}\n\n/**\n * @private\n * Function that initialize an array of matrices.\n * @param {Array} array\n * @param {boolean} isMatrix\n * @return {Array} array with the matrices initialized.\n */\nexport function initializeMatrices(array, isMatrix) {\n if (isMatrix) {\n for (var i = 0; i < array.length; ++i) {\n for (var j = 0; j < array[i].length; ++j) {\n var elem = array[i][j];\n array[i][j] = elem !== null ? new Matrix(array[i][j]) : undefined;\n }\n }\n } else {\n for (i = 0; i < array.length; ++i) {\n array[i] = new Matrix(array[i]);\n }\n }\n\n return array;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-pls/src/utils.js","/**\n * Constructs a confusion matrix\n * @class ConfusionMatrix\n * @example\n * const CM = new ConfusionMatrix([[13, 2], [10, 5]], ['cat', 'dog'])\n * @param {Array>} matrix - The confusion matrix, a 2D Array. Rows represent the actual label and columns\n * the predicted label.\n * @param {Array} labels - Labels of the confusion matrix, a 1D Array\n */\nclass ConfusionMatrix {\n constructor(matrix, labels) {\n if (matrix.length !== matrix[0].length) {\n throw new Error('Confusion matrix must be square');\n }\n if (labels.length !== matrix.length) {\n throw new Error('Confusion matrix and labels should have the same length');\n }\n this.labels = labels;\n this.matrix = matrix;\n }\n\n\n /**\n * Construct confusion matrix from the predicted and actual labels (classes). Be sure to provide the arguments in\n * the correct order!\n * @param {Array} actual - The predicted labels of the classification\n * @param {Array} predicted - The actual labels of the classification. Has to be of same length as\n * predicted.\n * @param {object} [options] - Additional options\n * @param {Array} [options.labels] - The list of labels that should be used. If not provided the distinct set\n * of labels present in predicted and actual is used. Labels are compared using the strict equality operator\n * '==='\n * @return {ConfusionMatrix} - Confusion matrix\n */\n static fromLabels(actual, predicted, options = {}) {\n if (predicted.length !== actual.length) {\n throw new Error('predicted and actual must have the same length');\n }\n let distinctLabels;\n if (options.labels) {\n distinctLabels = new Set(options.labels);\n } else {\n distinctLabels = new Set([...actual, ...predicted]);\n }\n distinctLabels = Array.from(distinctLabels);\n if (options.sort) {\n distinctLabels.sort(options.sort);\n }\n\n // Create confusion matrix and fill with 0's\n const matrix = Array.from({length: distinctLabels.length});\n for (let i = 0; i < matrix.length; i++) {\n matrix[i] = new Array(matrix.length);\n matrix[i].fill(0);\n }\n\n for (let i = 0; i < predicted.length; i++) {\n const actualIdx = distinctLabels.indexOf(actual[i]);\n const predictedIdx = distinctLabels.indexOf(predicted[i]);\n if (actualIdx >= 0 && predictedIdx >= 0) {\n matrix[actualIdx][predictedIdx]++;\n }\n }\n\n return new ConfusionMatrix(matrix, distinctLabels);\n }\n\n /**\n * Get the confusion matrix\n * @return {Array >}\n */\n getMatrix() {\n return this.matrix;\n }\n\n getLabels() {\n return this.labels;\n }\n\n /**\n * Get the total number of samples\n * @return {number}\n */\n getTotalCount() {\n let predicted = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n for (var j = 0; j < this.matrix.length; j++) {\n predicted += this.matrix[i][j];\n }\n }\n return predicted;\n }\n\n /**\n * Get the total number of true predictions\n * @return {number}\n */\n getTrueCount() {\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n count += this.matrix[i][i];\n }\n return count;\n }\n\n /**\n * Get the total number of false predictions.\n * @return {number}\n */\n getFalseCount() {\n return this.getTotalCount() - this.getTrueCount();\n }\n\n /**\n * Get the number of true positive predictions.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getTruePositiveCount(label) {\n const index = this.getIndex(label);\n return this.matrix[index][index];\n }\n\n /**\n * Get the number of true negative predictions\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getTrueNegativeCount(label) {\n const index = this.getIndex(label);\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n for (var j = 0; j < this.matrix.length; j++) {\n if (i !== index && j !== index) {\n count += this.matrix[i][j];\n }\n }\n }\n return count;\n }\n\n /**\n * Get the number of false positive predictions.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalsePositiveCount(label) {\n const index = this.getIndex(label);\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n if (i !== index) {\n count += this.matrix[i][index];\n }\n }\n return count;\n }\n\n /**\n * Get the number of false negative predictions.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseNegativeCount(label) {\n const index = this.getIndex(label);\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n if (i !== index) {\n count += this.matrix[index][i];\n }\n }\n return count;\n }\n\n /**\n * Get the number of real positive samples.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getPositiveCount(label) {\n return this.getTruePositiveCount(label) + this.getFalseNegativeCount(label);\n }\n\n /**\n * Get the number of real negative samples.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getNegativeCount(label) {\n return this.getTrueNegativeCount(label) + this.getFalsePositiveCount(label);\n }\n\n /**\n * Get the index in the confusion matrix that corresponds to the given label\n * @param {any} label - The label to search for\n * @throws if the label is not found\n * @return {number}\n */\n getIndex(label) {\n const index = this.labels.indexOf(label);\n if (index === -1) throw new Error('The label does not exist');\n return index;\n }\n\n /**\n * Get the true positive rate a.k.a. sensitivity. Computes the ratio between the number of true positive predictions and the total number of positive samples.\n * {@link https://en.wikipedia.org/wiki/Sensitivity_and_specificity}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number} - The true positive rate [0-1]\n */\n getTruePositiveRate(label) {\n return this.getTruePositiveCount(label) / this.getPositiveCount(label);\n }\n\n /**\n * Get the true negative rate a.k.a. specificity. Computes the ration between the number of true negative predictions and the total number of negative samples.\n * {@link https://en.wikipedia.org/wiki/Sensitivity_and_specificity}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getTrueNegativeRate(label) {\n return this.getTrueNegativeCount(label) / this.getNegativeCount(label);\n }\n\n /**\n * Get the positive predictive value a.k.a. precision. Computes TP / (TP + FP)\n * {@link https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getPositivePredictiveValue(label) {\n const TP = this.getTruePositiveCount(label);\n return TP / (TP + this.getFalsePositiveCount(label));\n }\n\n /**\n * Negative predictive value\n * {@link https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getNegativePredictiveValue(label) {\n const TN = this.getTrueNegativeCount(label);\n return TN / (TN + this.getFalseNegativeCount(label));\n }\n\n /**\n * False negative rate a.k.a. miss rate.\n * {@link https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#False_positive_and_false_negative_rates}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseNegativeRate(label) {\n return 1 - this.getTruePositiveRate(label);\n }\n\n /**\n * False positive rate a.k.a. fall-out rate.\n * {@link https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#False_positive_and_false_negative_rates}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalsePositiveRate(label) {\n return 1 - this.getTrueNegativeRate(label);\n }\n\n /**\n * False discovery rate (FDR)\n * {@link https://en.wikipedia.org/wiki/False_discovery_rate}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseDiscoveryRate(label) {\n const FP = this.getFalsePositiveCount(label);\n return FP / (FP + this.getTruePositiveCount(label));\n }\n\n /**\n * False omission rate (FOR)\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseOmissionRate(label) {\n const FN = this.getFalseNegativeCount(label);\n return FN / (FN + this.getTruePositiveCount(label));\n }\n\n /**\n * F1 score\n * {@link https://en.wikipedia.org/wiki/F1_score}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getF1Score(label) {\n const TP = this.getTruePositiveCount(label);\n return 2 * TP / (2 * TP + this.getFalsePositiveCount(label) + this.getFalseNegativeCount(label));\n }\n\n /**\n * Matthews correlation coefficient (MCC)\n * {@link https://en.wikipedia.org/wiki/Matthews_correlation_coefficient}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getMatthewsCorrelationCoefficient(label) {\n const TP = this.getTruePositiveCount(label);\n const TN = this.getTrueNegativeCount(label);\n const FP = this.getFalsePositiveCount(label);\n const FN = this.getFalseNegativeCount(label);\n return (TP * TN - FP * FN) / Math.sqrt((TP + FP) * (TP + FN) * (TN + FP) * (TN + FN));\n }\n\n /**\n * Informedness\n * {@link https://en.wikipedia.org/wiki/Youden%27s_J_statistic}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getInformedness(label) {\n return this.getTruePositiveRate(label) + this.getTrueNegativeRate(label) - 1;\n }\n\n /**\n * Markedness\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getMarkedness(label) {\n return this.getPositivePredictiveValue(label) + this.getNegativePredictiveValue(label) - 1;\n }\n\n /**\n * Get the confusion table.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {Array >} - The 2x2 confusion table. [[TP, FN], [FP, TN]]\n */\n getConfusionTable(label) {\n return [\n [\n this.getTruePositiveCount(label),\n this.getFalseNegativeCount(label)\n ],\n [\n this.getFalsePositiveCount(label),\n this.getTrueNegativeCount(label)\n ]\n ];\n }\n\n /**\n * Get total accuracy.\n * @return {number} - The ratio between the number of true predictions and total number of classifications ([0-1])\n */\n getAccuracy() {\n let correct = 0;\n let incorrect = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n for (var j = 0; j < this.matrix.length; j++) {\n if (i === j) correct += this.matrix[i][j];\n else incorrect += this.matrix[i][j];\n }\n }\n return correct / (correct + incorrect);\n }\n\n\n /**\n * Returns the element in the confusion matrix that corresponds to the given actual and predicted labels.\n * @param {any} actual - The true label\n * @param {any} predicted - The predicted label\n * @return {number} - The element in the confusion matrix\n */\n getCount(actual, predicted) {\n const actualIndex = this.getIndex(actual);\n const predictedIndex = this.getIndex(predicted);\n return this.matrix[actualIndex][predictedIndex];\n }\n\n /**\n * Compute the general prediction accuracy\n * @deprecated Use getAccuracy\n * @return {number} - The prediction accuracy ([0-1]\n */\n get accuracy() {\n return this.getAccuracy();\n }\n\n /**\n * Compute the number of predicted observations\n * @deprecated Use getTotalCount\n * @return {number}\n */\n get total() {\n return this.getTotalCount();\n }\n}\n\nmodule.exports = ConfusionMatrix;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-confusion-matrix/src/index.js","'use strict';\n\nvar Matrix = require('ml-matrix').Matrix;\n\nvar Utils = require('./utils');\nconst ACTIVATION_FUNCTIONS = require('./activationFunctions');\n\nclass Layer {\n /**\n * @private\n * Create a new layer with the given options\n * @param {object} options\n * @param {number} [options.inputSize] - Number of conections that enter the neurons.\n * @param {number} [options.outputSize] - Number of conections that leave the neurons.\n * @param {number} [options.regularization] - Regularization parameter.\n * @param {number} [options.epsilon] - Learning rate parameter.\n * @param {string} [options.activation] - Activation function parameter from the FeedForwardNeuralNetwork class.\n * @param {number} [options.activationParam] - Activation parameter if needed.\n */\n constructor(options) {\n this.inputSize = options.inputSize;\n this.outputSize = options.outputSize;\n this.regularization = options.regularization;\n this.epsilon = options.epsilon;\n this.activation = options.activation;\n this.activationParam = options.activationParam;\n\n var selectedFunction = ACTIVATION_FUNCTIONS[options.activation];\n var params = selectedFunction.activation.length;\n\n var actFunction = params > 1 ? val => selectedFunction.activation(val, options.activationParam) : selectedFunction.activation;\n var derFunction = params > 1 ? val => selectedFunction.derivate(val, options.activationParam) : selectedFunction.derivate;\n\n this.activationFunction = function (i, j) {\n this[i][j] = actFunction(this[i][j]);\n };\n this.derivate = function (i, j) {\n this[i][j] = derFunction(this[i][j]);\n };\n\n if (options.model) {\n // load model\n this.W = Matrix.checkMatrix(options.W);\n this.b = Matrix.checkMatrix(options.b);\n\n } else {\n // default constructor\n\n this.W = Matrix.rand(this.inputSize, this.outputSize);\n this.b = Matrix.zeros(1, this.outputSize);\n\n this.W.apply(function (i, j) {\n this[i][j] /= Math.sqrt(options.inputSize);\n });\n }\n }\n\n /**\n * @private\n * propagate the given input through the current layer.\n * @param {Matrix} X - input.\n * @return {Matrix} output at the current layer.\n */\n forward(X) {\n var z = X.mmul(this.W).addRowVector(this.b);\n z.apply(this.activationFunction);\n this.a = z.clone();\n return z;\n }\n\n /**\n * @private\n * apply backpropagation algorithm at the current layer\n * @param {Matrix} delta - delta values estimated at the following layer.\n * @param {Matrix} a - 'a' values from the following layer.\n * @return {Matrix} the new delta values for the next layer.\n */\n backpropagation(delta, a) {\n this.dW = a.transposeView().mmul(delta);\n this.db = Utils.sumCol(delta);\n\n var aCopy = a.clone();\n return delta.mmul(this.W.transposeView()).mul(aCopy.apply(this.derivate));\n }\n\n /**\n * @private\n * Function that updates the weights at the current layer with the derivatives.\n */\n update() {\n this.dW.add(this.W.clone().mul(this.regularization));\n this.W.add(this.dW.mul(-this.epsilon));\n this.b.add(this.db.mul(-this.epsilon));\n }\n\n /**\n * @private\n * Export the current layer to JSON.\n * @return {object} model\n */\n toJSON() {\n return {\n model: 'Layer',\n inputSize: this.inputSize,\n outputSize: this.outputSize,\n regularization: this.regularization,\n epsilon: this.epsilon,\n activation: this.activation,\n W: this.W,\n b: this.b\n };\n }\n\n /**\n * @private\n * Creates a new Layer with the given model.\n * @param {object} model\n * @return {Layer}\n */\n static load(model) {\n if (model.model !== 'Layer') {\n throw new RangeError('the current model is not a Layer model');\n }\n return new Layer(model);\n }\n\n}\n\nmodule.exports = Layer;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-fnn/src/Layer.js","'use strict';\n\nvar Matrix = require('ml-matrix').Matrix;\n\n/**\n * @private\n * Retrieves the sum at each row of the given matrix.\n * @param {Matrix} matrix\n * @return {Matrix}\n */\nfunction sumRow(matrix) {\n var sum = Matrix.zeros(matrix.rows, 1);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum[i][0] += matrix[i][j];\n }\n }\n return sum;\n}\n\n/**\n * @private\n * Retrieves the sum at each column of the given matrix.\n * @param {Matrix} matrix\n * @return {Matrix}\n */\nfunction sumCol(matrix) {\n var sum = Matrix.zeros(1, matrix.columns);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum[0][j] += matrix[i][j];\n }\n }\n return sum;\n}\n\n/**\n * @private\n * Method that given an array of labels(predictions), returns two dictionaries, one to transform from labels to\n * numbers and other in the reverse way\n * @param {Array} array\n * @return {object}\n */\nfunction dictOutputs(array) {\n var inputs = {};\n var outputs = {};\n var index = 0;\n for (var i = 0; i < array.length; i += 1) {\n if (inputs[array[i]] === undefined) {\n inputs[array[i]] = index;\n outputs[index] = array[i];\n index++;\n }\n }\n\n return {\n inputs: inputs,\n outputs: outputs\n };\n}\n\nmodule.exports = {\n dictOutputs: dictOutputs,\n sumCol: sumCol,\n sumRow: sumRow\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-fnn/src/utils.js","'use strict';\n\nfunction logistic(val) {\n return 1 / (1 + Math.exp(-val));\n}\n\nfunction expELU(val, param) {\n return val < 0 ? param * (Math.exp(val) - 1) : val;\n}\n\nfunction softExponential(val, param) {\n if (param < 0) {\n return -Math.log(1 - param * (val + param)) / param;\n }\n if (param > 0) {\n return ((Math.exp(param * val) - 1) / param) + param;\n }\n return val;\n}\n\nfunction softExponentialPrime(val, param) {\n if (param < 0) {\n return 1 / (1 - param * (param + val));\n } else {\n return Math.exp(param * val);\n }\n}\n\nconst ACTIVATION_FUNCTIONS = {\n tanh: {\n activation: Math.tanh,\n derivate: val => 1 - (val * val)\n },\n identity: {\n activation: val => val,\n derivate: () => 1\n },\n logistic: {\n activation: logistic,\n derivate: val => logistic(val) * (1 - logistic(val))\n },\n arctan: {\n activation: Math.atan,\n derivate: val => 1 / (val * val + 1)\n },\n softsign: {\n activation: val => val / (1 + Math.abs(val)),\n derivate: val => 1 / ((1 + Math.abs(val)) * (1 + Math.abs(val)))\n },\n relu: {\n activation: val => val < 0 ? 0 : val,\n derivate: val => val < 0 ? 0 : 1\n },\n softplus: {\n activation: val => Math.log(1 + Math.exp(val)),\n derivate: val => 1 / (1 + Math.exp(-val))\n },\n bent: {\n activation: val => ((Math.sqrt(val * val + 1) - 1) / 2) + val,\n derivate: val => (val / (2 * Math.sqrt(val * val + 1))) + 1\n },\n sinusoid: {\n activation: Math.sin,\n derivate: Math.cos\n },\n sinc: {\n activation: val => val === 0 ? 1 : Math.sin(val) / val,\n derivate: val => val === 0 ? 0 : (Math.cos(val) / val) - (Math.sin(val) / (val * val))\n },\n gaussian: {\n activation: val => Math.exp(-(val * val)),\n derivate: val => -2 * val * Math.exp(-(val * val))\n },\n 'parametric-relu': {\n activation: (val, param) => val < 0 ? param * val : val,\n derivate: (val, param) => val < 0 ? param : 1\n },\n 'exponential-elu': {\n activation: expELU,\n derivate: (val, param) => val < 0 ? expELU(val, param) + param : 1\n },\n 'soft-exponential': {\n activation: softExponential,\n derivate: softExponentialPrime\n }\n};\n\nmodule.exports = ACTIVATION_FUNCTIONS;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-fnn/src/activationFunctions.js","function NodeSquare(x, y, weights, som) {\n this.x = x;\n this.y = y;\n this.weights = weights;\n this.som = som;\n this.neighbors = {};\n}\n\nNodeSquare.prototype.adjustWeights = function adjustWeights(target, learningRate, influence) {\n for (var i = 0, ii = this.weights.length; i < ii; i++) {\n this.weights[i] += learningRate * influence * (target[i] - this.weights[i]);\n }\n};\n\nNodeSquare.prototype.getDistance = function getDistance(otherNode) {\n return Math.max(Math.abs(this.x - otherNode.x), Math.abs(this.y - otherNode.y));\n};\n\nNodeSquare.prototype.getDistanceTorus = function getDistanceTorus(otherNode) {\n var distX = Math.abs(this.x - otherNode.x),\n distY = Math.abs(this.y - otherNode.y);\n return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY));\n};\n\nNodeSquare.prototype.getNeighbors = function getNeighbors(xy) {\n if (!this.neighbors[xy]) {\n this.neighbors[xy] = new Array(2);\n\n // left or bottom neighbor\n var v;\n if (this[xy] > 0) {\n v = this[xy] - 1;\n } else if (this.som.torus) {\n v = this.som.gridDim[xy] - 1\n }\n if (typeof v !== 'undefined') {\n var x, y;\n if (xy === 'x') {\n x = v;\n y = this.y;\n } else {\n x = this.x;\n y = v;\n }\n this.neighbors[xy][0] = this.som.nodes[x][y];\n }\n\n // top or right neighbor\n var w;\n if (this[xy] < (this.som.gridDim[xy] - 1)) {\n w = this[xy] + 1;\n } else if (this.som.torus) {\n w = 0;\n }\n if (typeof w !== 'undefined') {\n if (xy === 'x') {\n x = w;\n y = this.y;\n } else {\n x = this.x;\n y = w;\n }\n this.neighbors[xy][1] = this.som.nodes[x][y];\n }\n }\n return this.neighbors[xy];\n};\n\nNodeSquare.prototype.getPos = function getPos(xy, element) {\n var neighbors = this.getNeighbors(xy),\n distance = this.som.distance,\n bestNeighbor,\n direction;\n if(neighbors[0]) {\n if (neighbors[1]) {\n var dist1 = distance(element, neighbors[0].weights),\n dist2 = distance(element, neighbors[1].weights);\n if(dist1 < dist2) {\n bestNeighbor = neighbors[0];\n direction = -1;\n } else {\n bestNeighbor = neighbors[1];\n direction = 1;\n }\n } else {\n bestNeighbor = neighbors[0];\n direction = -1;\n }\n } else {\n bestNeighbor = neighbors[1];\n direction = 1;\n }\n var simA = 1 - distance(element, this.weights),\n simB = 1 - distance(element, bestNeighbor.weights);\n var factor = ((simA - simB) / (2 - simA - simB));\n return 0.5 + 0.5 * factor * direction;\n};\n\nNodeSquare.prototype.getPosition = function getPosition(element) {\n return [\n this.getPos('x', element),\n this.getPos('y', element)\n ];\n};\n\nmodule.exports = NodeSquare;\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-som/src/node-square.js","export {default as SimpleLinearRegression, default as SLR} from 'ml-regression-simple-linear';\nexport {default as PolynomialRegression} from 'ml-regression-polynomial';\nexport {default as ExponentialRegression} from 'ml-regression-exponential';\nexport {default as PowerRegression} from 'ml-regression-power';\nexport {default as MultivariateLinearRegression} from 'ml-regression-multivariate-linear';\n\nimport PotentialRegression from './regression/potential-regression';\nconst NLR = {\n PotentialRegression\n};\nexport {NLR, NLR as NonLinearRegression};\n\nexport {default as KernelRidgeRegression, default as KRR} from './regression/kernel-ridge-regression';\nexport {default as PolinomialFitting2D} from './regression/poly-fit-regression2d';\n\n// robust regressions\nexport {default as TheilSenRegression} from 'ml-regression-theil-sen';\nexport {default as RobustPolynomialRegression} from 'ml-regression-robust-polynomial';\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-regression/src/index.js","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport Matrix, {solve} from 'ml-matrix';\n\nexport default class PolynomialRegression extends BaseRegression {\n constructor(x, y, degree) {\n super();\n if (x === true) {\n this.degree = y.degree;\n this.powers = y.powers;\n this.coefficients = y.coefficients;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y, degree);\n }\n }\n\n _predict(x) {\n let y = 0;\n for (let k = 0; k < this.powers.length; k++) {\n y += this.coefficients[k] * Math.pow(x, this.powers[k]);\n }\n return y;\n }\n\n toJSON() {\n return {\n name: 'polynomialRegression',\n degree: this.degree,\n powers: this.powers,\n coefficients: this.coefficients\n };\n }\n\n toString(precision) {\n return this._toFormula(precision, false);\n }\n\n toLaTeX(precision) {\n return this._toFormula(precision, true);\n }\n\n _toFormula(precision, isLaTeX) {\n let sup = '^';\n let closeSup = '';\n let times = ' * ';\n if (isLaTeX) {\n sup = '^{';\n closeSup = '}';\n times = '';\n }\n\n let fn = '';\n let str = '';\n for (let k = 0; k < this.coefficients.length; k++) {\n str = '';\n if (this.coefficients[k] !== 0) {\n if (this.powers[k] === 0) {\n str = maybeToPrecision(this.coefficients[k], precision);\n } else {\n if (this.powers[k] === 1) {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x';\n } else {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup;\n }\n }\n\n if (this.coefficients[k] > 0 && k !== (this.coefficients.length - 1)) {\n str = ' + ' + str;\n } else if (k !== (this.coefficients.length - 1)) {\n str = ' ' + str;\n }\n }\n fn = str + fn;\n }\n if (fn.charAt(0) === '+') {\n fn = fn.slice(1);\n }\n\n return 'f(x) = ' + fn;\n }\n\n static load(json) {\n if (json.name !== 'polynomialRegression') {\n throw new TypeError('not a polynomial regression model');\n }\n return new PolynomialRegression(true, json);\n }\n}\n\nfunction regress(pr, x, y, degree) {\n const n = x.length;\n let powers;\n if (Array.isArray(degree)) {\n powers = degree;\n degree = powers.length;\n } else {\n degree++;\n powers = new Array(degree);\n for (let k = 0; k < degree; k++) {\n powers[k] = k;\n }\n }\n const F = new Matrix(n, degree);\n const Y = new Matrix([y]);\n for (let k = 0; k < degree; k++) {\n for (let i = 0; i < n; i++) {\n if (powers[k] === 0) {\n F[i][k] = 1;\n } else {\n F[i][k] = Math.pow(x[i], powers[k]);\n }\n }\n }\n\n const FT = F.transposeView();\n const A = FT.mmul(F);\n const B = FT.mmul(Y.transposeView());\n\n pr.degree = degree - 1;\n pr.powers = powers;\n pr.coefficients = solve(A, B).to1DArray();\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-regression-polynomial/src/index.js","'use strict';\n\nconst newArray = require('new-array');\n\nconst primeFinder = require('./primeFinder');\nconst nextPrime = primeFinder.nextPrime;\nconst largestPrime = primeFinder.largestPrime;\n\nconst FREE = 0;\nconst FULL = 1;\nconst REMOVED = 2;\n\nconst defaultInitialCapacity = 150;\nconst defaultMinLoadFactor = 1 / 6;\nconst defaultMaxLoadFactor = 2 / 3;\n\nclass HashTable {\n constructor(options = {}) {\n if (options instanceof HashTable) {\n this.table = options.table.slice();\n this.values = options.values.slice();\n this.state = options.state.slice();\n this.minLoadFactor = options.minLoadFactor;\n this.maxLoadFactor = options.maxLoadFactor;\n this.distinct = options.distinct;\n this.freeEntries = options.freeEntries;\n this.lowWaterMark = options.lowWaterMark;\n this.highWaterMark = options.maxLoadFactor;\n return;\n }\n\n const initialCapacity = options.initialCapacity === undefined ? defaultInitialCapacity : options.initialCapacity;\n if (initialCapacity < 0) {\n throw new RangeError(`initial capacity must not be less than zero: ${initialCapacity}`);\n }\n\n const minLoadFactor = options.minLoadFactor === undefined ? defaultMinLoadFactor : options.minLoadFactor;\n const maxLoadFactor = options.maxLoadFactor === undefined ? defaultMaxLoadFactor : options.maxLoadFactor;\n if (minLoadFactor < 0 || minLoadFactor >= 1) {\n throw new RangeError(`invalid minLoadFactor: ${minLoadFactor}`);\n }\n if (maxLoadFactor <= 0 || maxLoadFactor >= 1) {\n throw new RangeError(`invalid maxLoadFactor: ${maxLoadFactor}`);\n }\n if (minLoadFactor >= maxLoadFactor) {\n throw new RangeError(`minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`);\n }\n\n let capacity = initialCapacity;\n // User wants to put at least capacity elements. We need to choose the size based on the maxLoadFactor to\n // avoid the need to rehash before this capacity is reached.\n // actualCapacity * maxLoadFactor >= capacity\n capacity = (capacity / maxLoadFactor) | 0;\n capacity = nextPrime(capacity);\n if (capacity === 0) capacity = 1;\n\n this.table = newArray(capacity, 0);\n this.values = newArray(capacity, 0);\n this.state = newArray(capacity, 0);\n\n this.minLoadFactor = minLoadFactor;\n if (capacity === largestPrime) {\n this.maxLoadFactor = 1;\n } else {\n this.maxLoadFactor = maxLoadFactor;\n }\n\n this.distinct = 0;\n this.freeEntries = capacity;\n\n this.lowWaterMark = 0;\n this.highWaterMark = chooseHighWaterMark(capacity, this.maxLoadFactor);\n }\n\n clone() {\n return new HashTable(this);\n }\n\n get size() {\n return this.distinct;\n }\n\n get(key) {\n const i = this.indexOfKey(key);\n if (i < 0) return 0;\n return this.values[i];\n }\n\n set(key, value) {\n let i = this.indexOfInsertion(key);\n if (i < 0) {\n i = -i - 1;\n this.values[i] = value;\n return false;\n }\n\n if (this.distinct > this.highWaterMark) {\n const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n return this.set(key, value);\n }\n\n this.table[i] = key;\n this.values[i] = value;\n if (this.state[i] === FREE) this.freeEntries--;\n this.state[i] = FULL;\n this.distinct++;\n\n if (this.freeEntries < 1) {\n const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n }\n\n return true;\n }\n \n remove(key, noRehash) {\n const i = this.indexOfKey(key);\n if (i < 0) return false;\n\n this.state[i] = REMOVED;\n this.distinct--;\n\n if (!noRehash) this.maybeShrinkCapacity();\n\n return true;\n }\n\n delete(key, noRehash) {\n const i = this.indexOfKey(key);\n if (i < 0) return false;\n\n this.state[i] = FREE;\n this.distinct--;\n\n if (!noRehash) this.maybeShrinkCapacity();\n\n return true;\n }\n\n maybeShrinkCapacity() {\n if (this.distinct < this.lowWaterMark) {\n const newCapacity = chooseShrinkCapacity(this.distinct, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n }\n }\n\n containsKey(key) {\n return this.indexOfKey(key) >= 0;\n }\n\n indexOfKey(key) {\n const table = this.table;\n const state = this.state;\n const length = this.table.length;\n\n const hash = key & 0x7fffffff;\n let i = hash % length;\n let decrement = hash % (length - 2);\n if (decrement === 0) decrement = 1;\n\n while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) {\n i -= decrement;\n if (i < 0) i += length;\n }\n\n if (state[i] === FREE) return -1;\n return i;\n }\n\n containsValue(value) {\n return this.indexOfValue(value) >= 0;\n }\n\n indexOfValue(value) {\n const values = this.values;\n const state = this.state;\n\n for (var i = 0; i < state.length; i++) {\n if (state[i] === FULL && values[i] === value) {\n return i;\n }\n }\n\n return -1;\n }\n\n indexOfInsertion(key) {\n const table = this.table;\n const state = this.state;\n const length = table.length;\n\n\n const hash = key & 0x7fffffff;\n let i = hash % length;\n let decrement = hash % (length - 2);\n if (decrement === 0) decrement = 1;\n\n while (state[i] === FULL && table[i] !== key) {\n i -= decrement;\n if (i < 0) i += length;\n }\n\n if (state[i] === REMOVED) {\n const j = i;\n while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) {\n i -= decrement;\n if (i < 0) i += length;\n }\n if (state[i] === FREE) i = j;\n }\n\n if (state[i] === FULL) {\n return -i - 1;\n }\n\n return i;\n }\n\n ensureCapacity(minCapacity) {\n if (this.table.length < minCapacity) {\n const newCapacity = nextPrime(minCapacity);\n this.rehash(newCapacity);\n }\n }\n\n rehash(newCapacity) {\n const oldCapacity = this.table.length;\n\n if (newCapacity <= this.distinct) throw new Error('Unexpected');\n\n const oldTable = this.table;\n const oldValues = this.values;\n const oldState = this.state;\n\n const newTable = newArray(newCapacity, 0);\n const newValues = newArray(newCapacity, 0);\n const newState = newArray(newCapacity, 0);\n\n this.lowWaterMark = chooseLowWaterMark(newCapacity, this.minLoadFactor);\n this.highWaterMark = chooseHighWaterMark(newCapacity, this.maxLoadFactor);\n\n this.table = newTable;\n this.values = newValues;\n this.state = newState;\n this.freeEntries = newCapacity - this.distinct;\n\n for (var i = 0; i < oldCapacity; i++) {\n if (oldState[i] === FULL) {\n var element = oldTable[i];\n var index = this.indexOfInsertion(element);\n newTable[index] = element;\n newValues[index] = oldValues[i];\n newState[index] = FULL;\n }\n }\n }\n\n forEachKey(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.table[i])) return false;\n }\n }\n return true;\n }\n\n forEachValue(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.values[i])) return false;\n }\n }\n return true;\n }\n\n forEachPair(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.table[i], this.values[i])) return false;\n }\n }\n return true;\n }\n}\n\nmodule.exports = HashTable;\n\nfunction chooseLowWaterMark(capacity, minLoad) {\n return (capacity * minLoad) | 0;\n}\n\nfunction chooseHighWaterMark(capacity, maxLoad) {\n return Math.min(capacity - 2, (capacity * maxLoad) | 0);\n}\n\nfunction chooseGrowCapacity(size, minLoad, maxLoad) {\n return nextPrime(Math.max(size + 1, (4 * size / (3 * minLoad + maxLoad)) | 0));\n}\n\nfunction chooseShrinkCapacity(size, minLoad, maxLoad) {\n return nextPrime(Math.max(size + 1, (4 * size / (minLoad + 3 * maxLoad)) | 0));\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-hash-table/src/HashTable.js","module.exports = function(haystack, needle, comparator, low, high) {\n var mid, cmp;\n\n if(low === undefined)\n low = 0;\n\n else {\n low = low|0;\n if(low < 0 || low >= haystack.length)\n throw new RangeError(\"invalid lower bound\");\n }\n\n if(high === undefined)\n high = haystack.length - 1;\n\n else {\n high = high|0;\n if(high < low || high >= haystack.length)\n throw new RangeError(\"invalid upper bound\");\n }\n\n while(low <= high) {\n /* Note that \"(low + high) >>> 1\" may overflow, and results in a typecast\n * to double (which gives the wrong results). */\n mid = low + (high - low >> 1);\n cmp = +comparator(haystack[mid], needle, mid, haystack);\n\n /* Too low. */\n if(cmp < 0.0)\n low = mid + 1;\n\n /* Too high. */\n else if(cmp > 0.0)\n high = mid - 1;\n\n /* Key found. */\n else\n return mid;\n }\n\n /* Key not found. */\n return ~low;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/binary-search/index.js","'use strict';\nvar numberIsNan = require('number-is-nan');\n\nfunction assertNum(x) {\n\tif (typeof x !== 'number' || numberIsNan(x)) {\n\t\tthrow new TypeError('Expected a number');\n\t}\n}\n\nexports.asc = function (a, b) {\n\tassertNum(a);\n\tassertNum(b);\n\treturn a - b;\n};\n\nexports.desc = function (a, b) {\n\tassertNum(a);\n\tassertNum(b);\n\treturn b - a;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/num-sort/index.js","'use strict';\n\nexports.distance = require('./distances');\nexports.similarity = require('./similarities');\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/index.js","'use strict';\n\nmodule.exports = function czekanowskiSimilarity(a, b) {\n var up = 0;\n var down = 0;\n for (var i = 0; i < a.length; i++) {\n up += Math.min(a[i], b[i]);\n down += a[i] + b[i];\n }\n return 2 * up / down;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/similarities/czekanowski.js","module.exports = function dice(a, b) {\n var ii = a.length,\n p = 0,\n q1 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * a[i];\n q1 += b[i] * b[i];\n q2 += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return q2 / (p + q1);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/dice.js","module.exports = function intersection(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.min(a[i], b[i]);\n }\n return 1 - ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/intersection.js","module.exports = function jaccard(a, b) {\n var ii = a.length,\n p1 = 0,\n p2 = 0,\n q1 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p1 += a[i] * b[i];\n p2 += a[i] * a[i];\n q1 += b[i] * b[i];\n q2 += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return q2 / (p2 + q1 - p1);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/jaccard.js","module.exports = function kulczynski(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += Math.min(a[i],b[i]);\n }\n return up / down;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/kulczynski.js","module.exports = function motyka(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.min(a[i], b[i]);\n down += a[i] + b[i];\n }\n return 1 - (up / down);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/motyka.js","module.exports = function squaredChord(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i]));\n }\n return ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/squaredChord.js","module.exports = function tanimoto(a, b, bitvector) {\n if (bitvector) {\n var inter = 0,\n union = 0;\n for (var j = 0; j < a.length; j++) {\n inter += a[j] && b[j];\n union += a[j] || b[j];\n }\n if (union === 0)\n return 1;\n return inter / union;\n }\n else {\n var ii = a.length,\n p = 0,\n q = 0,\n m = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i];\n q += b[i];\n m += Math.min(a[i],b[i]);\n }\n return 1 - (p + q - 2 * m) / (p + q - m);\n }\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/similarities/tanimoto.js","module.exports = function cosine(a, b) {\n var ii = a.length,\n p = 0,\n p2 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * b[i];\n p2 += a[i] * a[i];\n q2 += b[i] * b[i];\n }\n return p / (Math.sqrt(p2) * Math.sqrt(q2));\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/similarities/cosine.js","'use strict';\n\nvar extend = require('extend');\n\nvar defaultOptions = {\n size: 1,\n value: 0\n};\n\n/**\n * Case when the entry is an array\n * @param data\n * @param options\n * @returns {Array}\n */\nfunction arrayCase(data, options) {\n var len = data.length;\n if (typeof options.size === 'number')\n options.size = [options.size, options.size];\n\n var cond = len + options.size[0] + options.size[1];\n\n var output;\n if (options.output) {\n if (options.output.length !== cond)\n throw new RangeError('Wrong output size');\n output = options.output;\n }\n else\n output = new Array(cond);\n\n var i;\n\n // circular option\n if (options.value === 'circular') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[((len - (options.size[0] % len)) + i) % len];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[(i - options.size[0]) % len];\n }\n }\n\n // replicate option\n else if (options.value === 'replicate') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[0];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[len - 1];\n }\n }\n\n // symmetric option\n else if (options.value === 'symmetric') {\n if ((options.size[0] > len) || (options.size[1] > len))\n throw new RangeError('expanded value should not be bigger than the data length');\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[options.size[0] - 1 - i];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[2*len + options.size[0] - i - 1];\n }\n }\n\n // default option\n else {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = options.value;\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = options.value;\n }\n }\n\n return output;\n}\n\n/**\n * Case when the entry is a matrix\n * @param data\n * @param options\n * @returns {Array}\n */\nfunction matrixCase(data, options) {\n var row = data.length;\n var col = data[0].length;\n if (options.size[0] === undefined)\n options.size = [options.size, options.size, options.size, options.size];\n throw new Error('matrix not supported yet, sorry');\n}\n\n/**\n * Pads and array\n * @param {Array } data\n * @param {object} options\n */\nfunction padArray (data, options) {\n options = extend({}, defaultOptions, options);\n\n if (Array.isArray(data)) {\n if (Array.isArray(data[0]))\n return matrixCase(data, options);\n else\n return arrayCase(data, options);\n }\n else\n throw new TypeError('data should be an array');\n}\n\nmodule.exports = padArray;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-pad-array/src/index.js","import arrayMean from 'ml-array-mean';\n\n/**\n * Computes the variance of the given values\n * @param {Array} values\n * @param {object} [options]\n * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n.\n * @param {number} [options.mean = arrayMean] - precalculated mean, if any.\n * @return {number}\n */\nexport default function (values, options = {}) {\n const {\n unbiased = true,\n mean = arrayMean(values)\n } = options;\n var sqrError = 0;\n\n for (var i = 0; i < values.length; i++) {\n var x = values[i] - mean;\n sqrError += x * x;\n }\n\n if (unbiased) {\n return sqrError / (values.length - 1);\n } else {\n return sqrError / values.length;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-array-variance/src/index.js","'use strict';\n\nconst mlCart = require('ml-cart');\nconst mlRandomForest = require('ml-random-forest');\n\nconst ML = exports;\n\n// Try to keep this list in the same structure as the README.\n\n// Unsupervised learning\nML.PCA = require('ml-pca');\nML.HClust = require('ml-hclust');\nML.KMeans = require('ml-kmeans');\n\n// Supervised learning\nML.SVM = require('ml-svm');\nML.NaiveBayes = require('ml-naivebayes');\nML.KNN = require('ml-knn');\nML.PLS = require('ml-pls');\nML.CrossValidation = require('ml-cross-validation');\nML.ConfusionMatrix = require('ml-confusion-matrix');\nML.DecisionTreeClassifier = mlCart.DecisionTreeClassifier;\nML.RandomForestClassifier = mlRandomForest.RandomForestClassifier;\n\n// Artificial neural networks\nML.FNN = require('ml-fnn');\nML.SOM = require('ml-som');\n\n// Regression\nconst Regression = require('ml-regression');\nML.SimpleLinearRegression = Regression.SimpleLinearRegression;\nML.PolynomialRegression = Regression.PolynomialRegression;\nML.MultivariateLinearRegression = Regression.MultivariateLinearRegression;\nML.PowerRegression = Regression.PowerRegression;\nML.ExponentialRegression = Regression.ExponentialRegression;\nML.TheilSenRegression = Regression.TheilSenRegression;\nML.RobustPolynomialRegression = Regression.RobustPolynomialRegression;\nML.DecisionTreeRegression = mlCart.DecisionTreeRegression;\nML.RandomForestRegression = mlRandomForest.RandomForestRegression;\n\n// Optimization\nML.levenbergMarquardt = require('ml-levenberg-marquardt');\n\n// Math\nconst Matrix = require('ml-matrix');\nML.Matrix = Matrix.Matrix;\nML.SVD = Matrix.SVD;\nML.EVD = Matrix.EVD;\nML.CholeskyDecomposition = Matrix.CholeskyDecomposition;\nML.LuDecomposition = Matrix.LuDecomposition;\nML.QrDecomposition = Matrix.QrDecomposition;\n\nML.SparseMatrix = require('ml-sparse-matrix');\nML.Kernel = require('ml-kernel');\nML.Distance = require('ml-distance').distance;\nML.Similarity = require('ml-distance').similarity;\nML.distanceMatrix = require('ml-distance-matrix');\nML.XSadd = require('ml-xsadd');\n\n// Statistics\nML.Performance = require('ml-performance');\n\n// Data preprocessing\nML.savitzkyGolay = require('ml-savitzky-golay');\nML.savitzkyGolayGeneralized = require('ml-savitzky-golay-generalized');\n\n// Utility\nML.BitArray = require('ml-bit-array');\nML.HashTable = require('ml-hash-table');\nML.padArray = require('ml-pad-array');\nML.binarySearch = require('binary-search');\nML.numSort = require('num-sort');\nML.Random = require('ml-random');\n\n// Undocumented/deprecated packages\nML.ArrayUtils = require('ml-array-utils');\nML.Regression = require('ml-regression');\nML.MatrixUtil = require('ml-matrix');\nML.ArrayStat = require('ml-stat').array;\nML.MatrixStat = require('ml-stat').matrix;\n\nML.Array = {\n min: require('ml-array-min').default,\n max: require('ml-array-max').default,\n median: require('ml-array-median').default,\n mean: require('ml-array-mean').default,\n mode: require('ml-array-mode').default,\n rescale: require('ml-array-rescale').default,\n standardDeviation: require('ml-array-standard-deviation').default,\n variance: require('ml-array-variance').default,\n}\n\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","import Matrix from 'ml-matrix';\nimport Tree from './TreeNode';\n\nconst defaultOptions = {\n gainFunction: 'gini',\n splitFunction: 'mean',\n minNumSamples: 3,\n maxDepth: Infinity\n};\n\nexport class DecisionTreeClassifier {\n\n /**\n * Create new Decision Tree Classifier with CART implementation with the given options\n * @param {object} options\n * @param {string} [options.gainFunction=\"gini\"] - gain function to get the best split, \"gini\" the only one supported.\n * @param {string} [options.splitFunction=\"mean\"] - given two integers from a split feature, get the value to split, \"mean\" the only one supported.\n * @param {number} [options.minNumSamples=3] - minimum number of samples to create a leaf node to decide a class.\n * @param {number} [options.maxDepth=Infinity] - Max depth of the tree.\n * @param {object} model - for load purposes.\n * @constructor\n */\n constructor(options, model) {\n if (options === true) {\n this.options = model.options;\n this.root = new Tree(model.options);\n this.root.setNodeParameters(model.root);\n } else {\n this.options = Object.assign({}, defaultOptions, options);\n this.options.kind = 'classifier';\n }\n }\n\n /**\n * Train the decision tree with the given training set and labels.\n * @param {Matrix|MatrixTransposeView|Array} trainingSet\n * @param {Array} trainingLabels\n */\n train(trainingSet, trainingLabels) {\n this.root = new Tree(this.options);\n trainingSet = Matrix.checkMatrix(trainingSet);\n this.root.train(trainingSet, trainingLabels, 0, null);\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Matrix|MatrixTransposeView|Array} toPredict\n * @return {Array} predictions\n */\n predict(toPredict) {\n toPredict = Matrix.checkMatrix(toPredict);\n var predictions = new Array(toPredict.rows);\n\n for (var i = 0; i < toPredict.rows; ++i) {\n predictions[i] = this.root.classify(toPredict.getRow(i)).maxRowIndex(0)[1];\n }\n\n return predictions;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n options: this.options,\n root: this.root,\n name: 'DTClassifier'\n };\n }\n\n /**\n * Load a Decision tree classifier with the given model.\n * @param {object} model\n * @return {DecisionTreeClassifier}\n */\n static load(model) {\n if (model.name !== 'DTClassifier') {\n throw new RangeError('Invalid model: ' + model.name);\n }\n\n return new DecisionTreeClassifier(true, model);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-cart/src/DecisionTreeClassifier.js","import BaseView from './base';\n\nexport default class MatrixTransposeView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.columns, matrix.rows);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(columnIndex, rowIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(columnIndex, rowIndex);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/views/transpose.js","import BaseView from './base';\n\nexport default class MatrixRowView extends BaseView {\n constructor(matrix, row) {\n super(matrix, 1, matrix.columns);\n this.row = row;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.row, columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.row, columnIndex);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/views/row.js","import { checkRange } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixSubView extends BaseView {\n constructor(matrix, startRow, endRow, startColumn, endColumn) {\n checkRange(matrix, startRow, endRow, startColumn, endColumn);\n super(matrix, endRow - startRow + 1, endColumn - startColumn + 1);\n this.startRow = startRow;\n this.startColumn = startColumn;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(\n this.startRow + rowIndex,\n this.startColumn + columnIndex,\n value\n );\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(\n this.startRow + rowIndex,\n this.startColumn + columnIndex\n );\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/views/sub.js","import { checkIndices } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixSelectionView extends BaseView {\n constructor(matrix, rowIndices, columnIndices) {\n var indices = checkIndices(matrix, rowIndices, columnIndices);\n super(matrix, indices.row.length, indices.column.length);\n this.rowIndices = indices.row;\n this.columnIndices = indices.column;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(\n this.rowIndices[rowIndex],\n this.columnIndices[columnIndex],\n value\n );\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(\n this.rowIndices[rowIndex],\n this.columnIndices[columnIndex]\n );\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/views/selection.js","import { checkRowIndices } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixRowSelectionView extends BaseView {\n constructor(matrix, rowIndices) {\n rowIndices = checkRowIndices(matrix, rowIndices);\n super(matrix, rowIndices.length, matrix.columns);\n this.rowIndices = rowIndices;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.rowIndices[rowIndex], columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.rowIndices[rowIndex], columnIndex);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/views/rowSelection.js","import { checkColumnIndices } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixColumnSelectionView extends BaseView {\n constructor(matrix, columnIndices) {\n columnIndices = checkColumnIndices(matrix, columnIndices);\n super(matrix, matrix.rows, columnIndices.length);\n this.columnIndices = columnIndices;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.columnIndices[columnIndex], value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(rowIndex, this.columnIndices[columnIndex]);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/views/columnSelection.js","import BaseView from './base';\n\nexport default class MatrixColumnView extends BaseView {\n constructor(matrix, column) {\n super(matrix, matrix.rows, 1);\n this.column = column;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.column, value);\n return this;\n }\n\n get(rowIndex) {\n return this.matrix.get(rowIndex, this.column);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/views/column.js","import BaseView from './base';\n\nexport default class MatrixFlipRowView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.rows, matrix.columns);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.rows - rowIndex - 1, columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.rows - rowIndex - 1, columnIndex);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/views/flipRow.js","import BaseView from './base';\n\nexport default class MatrixFlipColumnView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.rows, matrix.columns);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.columns - columnIndex - 1, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(rowIndex, this.columns - columnIndex - 1);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/views/flipColumn.js","import WrapperMatrix1D from './WrapperMatrix1D';\nimport WrapperMatrix2D from './WrapperMatrix2D';\n\n/**\n * @param {Array>|Array} array\n * @param {object} [options]\n * @param {object} [options.rows = 1]\n * @return {WrapperMatrix1D|WrapperMatrix2D}\n */\nexport function wrap(array, options) {\n if (Array.isArray(array)) {\n if (array[0] && Array.isArray(array[0])) {\n return new WrapperMatrix2D(array);\n } else {\n return new WrapperMatrix1D(array, options);\n }\n } else {\n throw new Error('the argument is not an array');\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/wrap/wrap.js","import LuDecomposition from './dc/lu';\nimport QrDecomposition from './dc/qr';\nimport SingularValueDecomposition from './dc/svd';\n\nimport { Matrix, WrapperMatrix2D } from './index';\n\n/**\n * Computes the inverse of a Matrix\n * @param {Matrix} matrix\n * @param {boolean} [useSVD=false]\n * @return {Matrix}\n */\nexport function inverse(matrix, useSVD = false) {\n matrix = WrapperMatrix2D.checkMatrix(matrix);\n if (useSVD) {\n return new SingularValueDecomposition(matrix).inverse();\n } else {\n return solve(matrix, Matrix.eye(matrix.rows));\n }\n}\n\n/**\n *\n * @param {Matrix} leftHandSide\n * @param {Matrix} rightHandSide\n * @param {boolean} [useSVD = false]\n * @return {Matrix}\n */\nexport function solve(leftHandSide, rightHandSide, useSVD = false) {\n leftHandSide = WrapperMatrix2D.checkMatrix(leftHandSide);\n rightHandSide = WrapperMatrix2D.checkMatrix(rightHandSide);\n if (useSVD) {\n return new SingularValueDecomposition(leftHandSide).solve(rightHandSide);\n } else {\n return leftHandSide.isSquare()\n ? new LuDecomposition(leftHandSide).solve(rightHandSide)\n : new QrDecomposition(leftHandSide).solve(rightHandSide);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/decompositions.js","import max from 'ml-array-max';\n\nimport Matrix from './matrix';\nimport SingularValueDecomposition from './dc/svd';\n\n// function used by rowsDependencies\nfunction xrange(n, exception) {\n var range = [];\n for (var i = 0; i < n; i++) {\n if (i !== exception) {\n range.push(i);\n }\n }\n return range;\n}\n\n// function used by rowsDependencies\nfunction dependenciesOneRow(\n error,\n matrix,\n index,\n thresholdValue = 10e-10,\n thresholdError = 10e-10\n) {\n if (error > thresholdError) {\n return new Array(matrix.rows + 1).fill(0);\n } else {\n var returnArray = matrix.addRow(index, [0]);\n for (var i = 0; i < returnArray.rows; i++) {\n if (Math.abs(returnArray.get(i, 0)) < thresholdValue) {\n returnArray.set(i, 0, 0);\n }\n }\n return returnArray.to1DArray();\n }\n}\n\n/**\n * Creates a matrix which represents the dependencies between rows.\n * If a row is a linear combination of others rows, the result will be a row with the coefficients of this combination.\n * For example : for A = [[2, 0, 0, 1], [0, 1, 6, 0], [0, 3, 0, 1], [0, 0, 1, 0], [0, 1, 2, 0]], the result will be [[0, 0, 0, 0, 0], [0, 0, 0, 4, 1], [0, 0, 0, 0, 0], [0, 0.25, 0, 0, -0.25], [0, 1, 0, -4, 0]]\n * @param {Matrix} matrix\n * @param {Object} [options] includes thresholdValue and thresholdError.\n * @param {number} [options.thresholdValue = 10e-10] If an absolute value is inferior to this threshold, it will equals zero.\n * @param {number} [options.thresholdError = 10e-10] If the error is inferior to that threshold, the linear combination found is accepted and the row is dependent from other rows.\n * @return {Matrix} the matrix which represents the dependencies between rows.\n */\n\nexport function linearDependencies(matrix, options = {}) {\n const { thresholdValue = 10e-10, thresholdError = 10e-10 } = options;\n\n var n = matrix.rows;\n var results = new Matrix(n, n);\n\n for (var i = 0; i < n; i++) {\n var b = Matrix.columnVector(matrix.getRow(i));\n var Abis = matrix.subMatrixRow(xrange(n, i)).transposeView();\n var svd = new SingularValueDecomposition(Abis);\n var x = svd.solve(b);\n var error = max(\n Matrix.sub(b, Abis.mmul(x))\n .abs()\n .to1DArray()\n );\n results.setRow(\n i,\n dependenciesOneRow(error, x, i, thresholdValue, thresholdError)\n );\n }\n return results;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/linearDependencies.js","import { Matrix, WrapperMatrix2D } from '../index';\n\nimport { hypotenuse, getFilled2DArray } from './util';\n\n/**\n * @class EigenvalueDecomposition\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs\n * @param {Matrix} matrix\n * @param {object} [options]\n * @param {boolean} [options.assumeSymmetric=false]\n */\nexport default class EigenvalueDecomposition {\n constructor(matrix, options = {}) {\n const { assumeSymmetric = false } = options;\n\n matrix = WrapperMatrix2D.checkMatrix(matrix);\n if (!matrix.isSquare()) {\n throw new Error('Matrix is not a square matrix');\n }\n\n var n = matrix.columns;\n var V = getFilled2DArray(n, n, 0);\n var d = new Array(n);\n var e = new Array(n);\n var value = matrix;\n var i, j;\n\n var isSymmetric = false;\n if (assumeSymmetric) {\n isSymmetric = true;\n } else {\n isSymmetric = matrix.isSymmetric();\n }\n\n if (isSymmetric) {\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V[i][j] = value.get(i, j);\n }\n }\n tred2(n, e, d, V);\n tql2(n, e, d, V);\n } else {\n var H = getFilled2DArray(n, n, 0);\n var ort = new Array(n);\n for (j = 0; j < n; j++) {\n for (i = 0; i < n; i++) {\n H[i][j] = value.get(i, j);\n }\n }\n orthes(n, H, ort, V);\n hqr2(n, e, d, V, H);\n }\n\n this.n = n;\n this.e = e;\n this.d = d;\n this.V = V;\n }\n\n /**\n *\n * @return {Array}\n */\n get realEigenvalues() {\n return this.d;\n }\n\n /**\n *\n * @return {Array}\n */\n get imaginaryEigenvalues() {\n return this.e;\n }\n\n /**\n *\n * @return {Matrix}\n */\n get eigenvectorMatrix() {\n if (!Matrix.isMatrix(this.V)) {\n this.V = new Matrix(this.V);\n }\n return this.V;\n }\n\n /**\n *\n * @return {Matrix}\n */\n get diagonalMatrix() {\n var n = this.n;\n var e = this.e;\n var d = this.d;\n var X = new Matrix(n, n);\n var i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n X[i][j] = 0;\n }\n X[i][i] = d[i];\n if (e[i] > 0) {\n X[i][i + 1] = e[i];\n } else if (e[i] < 0) {\n X[i][i - 1] = e[i];\n }\n }\n return X;\n }\n}\n\nfunction tred2(n, e, d, V) {\n var f, g, h, i, j, k, hh, scale;\n\n for (j = 0; j < n; j++) {\n d[j] = V[n - 1][j];\n }\n\n for (i = n - 1; i > 0; i--) {\n scale = 0;\n h = 0;\n for (k = 0; k < i; k++) {\n scale = scale + Math.abs(d[k]);\n }\n\n if (scale === 0) {\n e[i] = d[i - 1];\n for (j = 0; j < i; j++) {\n d[j] = V[i - 1][j];\n V[i][j] = 0;\n V[j][i] = 0;\n }\n } else {\n for (k = 0; k < i; k++) {\n d[k] /= scale;\n h += d[k] * d[k];\n }\n\n f = d[i - 1];\n g = Math.sqrt(h);\n if (f > 0) {\n g = -g;\n }\n\n e[i] = scale * g;\n h = h - f * g;\n d[i - 1] = f - g;\n for (j = 0; j < i; j++) {\n e[j] = 0;\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n V[j][i] = f;\n g = e[j] + V[j][j] * f;\n for (k = j + 1; k <= i - 1; k++) {\n g += V[k][j] * d[k];\n e[k] += V[k][j] * f;\n }\n e[j] = g;\n }\n\n f = 0;\n for (j = 0; j < i; j++) {\n e[j] /= h;\n f += e[j] * d[j];\n }\n\n hh = f / (h + h);\n for (j = 0; j < i; j++) {\n e[j] -= hh * d[j];\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n g = e[j];\n for (k = j; k <= i - 1; k++) {\n V[k][j] -= f * e[k] + g * d[k];\n }\n d[j] = V[i - 1][j];\n V[i][j] = 0;\n }\n }\n d[i] = h;\n }\n\n for (i = 0; i < n - 1; i++) {\n V[n - 1][i] = V[i][i];\n V[i][i] = 1;\n h = d[i + 1];\n if (h !== 0) {\n for (k = 0; k <= i; k++) {\n d[k] = V[k][i + 1] / h;\n }\n\n for (j = 0; j <= i; j++) {\n g = 0;\n for (k = 0; k <= i; k++) {\n g += V[k][i + 1] * V[k][j];\n }\n for (k = 0; k <= i; k++) {\n V[k][j] -= g * d[k];\n }\n }\n }\n\n for (k = 0; k <= i; k++) {\n V[k][i + 1] = 0;\n }\n }\n\n for (j = 0; j < n; j++) {\n d[j] = V[n - 1][j];\n V[n - 1][j] = 0;\n }\n\n V[n - 1][n - 1] = 1;\n e[0] = 0;\n}\n\nfunction tql2(n, e, d, V) {\n var g, h, i, j, k, l, m, p, r, dl1, c, c2, c3, el1, s, s2, iter;\n\n for (i = 1; i < n; i++) {\n e[i - 1] = e[i];\n }\n\n e[n - 1] = 0;\n\n var f = 0;\n var tst1 = 0;\n var eps = Number.EPSILON;\n\n for (l = 0; l < n; l++) {\n tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));\n m = l;\n while (m < n) {\n if (Math.abs(e[m]) <= eps * tst1) {\n break;\n }\n m++;\n }\n\n if (m > l) {\n iter = 0;\n do {\n iter = iter + 1;\n\n g = d[l];\n p = (d[l + 1] - g) / (2 * e[l]);\n r = hypotenuse(p, 1);\n if (p < 0) {\n r = -r;\n }\n\n d[l] = e[l] / (p + r);\n d[l + 1] = e[l] * (p + r);\n dl1 = d[l + 1];\n h = g - d[l];\n for (i = l + 2; i < n; i++) {\n d[i] -= h;\n }\n\n f = f + h;\n\n p = d[m];\n c = 1;\n c2 = c;\n c3 = c;\n el1 = e[l + 1];\n s = 0;\n s2 = 0;\n for (i = m - 1; i >= l; i--) {\n c3 = c2;\n c2 = c;\n s2 = s;\n g = c * e[i];\n h = c * p;\n r = hypotenuse(p, e[i]);\n e[i + 1] = s * r;\n s = e[i] / r;\n c = p / r;\n p = c * d[i] - s * g;\n d[i + 1] = h + s * (c * g + s * d[i]);\n\n for (k = 0; k < n; k++) {\n h = V[k][i + 1];\n V[k][i + 1] = s * V[k][i] + c * h;\n V[k][i] = c * V[k][i] - s * h;\n }\n }\n\n p = -s * s2 * c3 * el1 * e[l] / dl1;\n e[l] = s * p;\n d[l] = c * p;\n } while (Math.abs(e[l]) > eps * tst1);\n }\n d[l] = d[l] + f;\n e[l] = 0;\n }\n\n for (i = 0; i < n - 1; i++) {\n k = i;\n p = d[i];\n for (j = i + 1; j < n; j++) {\n if (d[j] < p) {\n k = j;\n p = d[j];\n }\n }\n\n if (k !== i) {\n d[k] = d[i];\n d[i] = p;\n for (j = 0; j < n; j++) {\n p = V[j][i];\n V[j][i] = V[j][k];\n V[j][k] = p;\n }\n }\n }\n}\n\nfunction orthes(n, H, ort, V) {\n var low = 0;\n var high = n - 1;\n var f, g, h, i, j, m;\n var scale;\n\n for (m = low + 1; m <= high - 1; m++) {\n scale = 0;\n for (i = m; i <= high; i++) {\n scale = scale + Math.abs(H[i][m - 1]);\n }\n\n if (scale !== 0) {\n h = 0;\n for (i = high; i >= m; i--) {\n ort[i] = H[i][m - 1] / scale;\n h += ort[i] * ort[i];\n }\n\n g = Math.sqrt(h);\n if (ort[m] > 0) {\n g = -g;\n }\n\n h = h - ort[m] * g;\n ort[m] = ort[m] - g;\n\n for (j = m; j < n; j++) {\n f = 0;\n for (i = high; i >= m; i--) {\n f += ort[i] * H[i][j];\n }\n\n f = f / h;\n for (i = m; i <= high; i++) {\n H[i][j] -= f * ort[i];\n }\n }\n\n for (i = 0; i <= high; i++) {\n f = 0;\n for (j = high; j >= m; j--) {\n f += ort[j] * H[i][j];\n }\n\n f = f / h;\n for (j = m; j <= high; j++) {\n H[i][j] -= f * ort[j];\n }\n }\n\n ort[m] = scale * ort[m];\n H[m][m - 1] = scale * g;\n }\n }\n\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V[i][j] = i === j ? 1 : 0;\n }\n }\n\n for (m = high - 1; m >= low + 1; m--) {\n if (H[m][m - 1] !== 0) {\n for (i = m + 1; i <= high; i++) {\n ort[i] = H[i][m - 1];\n }\n\n for (j = m; j <= high; j++) {\n g = 0;\n for (i = m; i <= high; i++) {\n g += ort[i] * V[i][j];\n }\n\n g = g / ort[m] / H[m][m - 1];\n for (i = m; i <= high; i++) {\n V[i][j] += g * ort[i];\n }\n }\n }\n }\n}\n\nfunction hqr2(nn, e, d, V, H) {\n var n = nn - 1;\n var low = 0;\n var high = nn - 1;\n var eps = Number.EPSILON;\n var exshift = 0;\n var norm = 0;\n var p = 0;\n var q = 0;\n var r = 0;\n var s = 0;\n var z = 0;\n var iter = 0;\n var i, j, k, l, m, t, w, x, y;\n var ra, sa, vr, vi;\n var notlast, cdivres;\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n d[i] = H[i][i];\n e[i] = 0;\n }\n\n for (j = Math.max(i - 1, 0); j < nn; j++) {\n norm = norm + Math.abs(H[i][j]);\n }\n }\n\n while (n >= low) {\n l = n;\n while (l > low) {\n s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]);\n if (s === 0) {\n s = norm;\n }\n if (Math.abs(H[l][l - 1]) < eps * s) {\n break;\n }\n l--;\n }\n\n if (l === n) {\n H[n][n] = H[n][n] + exshift;\n d[n] = H[n][n];\n e[n] = 0;\n n--;\n iter = 0;\n } else if (l === n - 1) {\n w = H[n][n - 1] * H[n - 1][n];\n p = (H[n - 1][n - 1] - H[n][n]) / 2;\n q = p * p + w;\n z = Math.sqrt(Math.abs(q));\n H[n][n] = H[n][n] + exshift;\n H[n - 1][n - 1] = H[n - 1][n - 1] + exshift;\n x = H[n][n];\n\n if (q >= 0) {\n z = p >= 0 ? p + z : p - z;\n d[n - 1] = x + z;\n d[n] = d[n - 1];\n if (z !== 0) {\n d[n] = x - w / z;\n }\n e[n - 1] = 0;\n e[n] = 0;\n x = H[n][n - 1];\n s = Math.abs(x) + Math.abs(z);\n p = x / s;\n q = z / s;\n r = Math.sqrt(p * p + q * q);\n p = p / r;\n q = q / r;\n\n for (j = n - 1; j < nn; j++) {\n z = H[n - 1][j];\n H[n - 1][j] = q * z + p * H[n][j];\n H[n][j] = q * H[n][j] - p * z;\n }\n\n for (i = 0; i <= n; i++) {\n z = H[i][n - 1];\n H[i][n - 1] = q * z + p * H[i][n];\n H[i][n] = q * H[i][n] - p * z;\n }\n\n for (i = low; i <= high; i++) {\n z = V[i][n - 1];\n V[i][n - 1] = q * z + p * V[i][n];\n V[i][n] = q * V[i][n] - p * z;\n }\n } else {\n d[n - 1] = x + p;\n d[n] = x + p;\n e[n - 1] = z;\n e[n] = -z;\n }\n\n n = n - 2;\n iter = 0;\n } else {\n x = H[n][n];\n y = 0;\n w = 0;\n if (l < n) {\n y = H[n - 1][n - 1];\n w = H[n][n - 1] * H[n - 1][n];\n }\n\n if (iter === 10) {\n exshift += x;\n for (i = low; i <= n; i++) {\n H[i][i] -= x;\n }\n s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]);\n x = y = 0.75 * s;\n w = -0.4375 * s * s;\n }\n\n if (iter === 30) {\n s = (y - x) / 2;\n s = s * s + w;\n if (s > 0) {\n s = Math.sqrt(s);\n if (y < x) {\n s = -s;\n }\n s = x - w / ((y - x) / 2 + s);\n for (i = low; i <= n; i++) {\n H[i][i] -= s;\n }\n exshift += s;\n x = y = w = 0.964;\n }\n }\n\n iter = iter + 1;\n\n m = n - 2;\n while (m >= l) {\n z = H[m][m];\n r = x - z;\n s = y - z;\n p = (r * s - w) / H[m + 1][m] + H[m][m + 1];\n q = H[m + 1][m + 1] - z - r - s;\n r = H[m + 2][m + 1];\n s = Math.abs(p) + Math.abs(q) + Math.abs(r);\n p = p / s;\n q = q / s;\n r = r / s;\n if (m === l) {\n break;\n }\n if (\n Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) <\n eps *\n (Math.abs(p) *\n (Math.abs(H[m - 1][m - 1]) +\n Math.abs(z) +\n Math.abs(H[m + 1][m + 1])))\n ) {\n break;\n }\n m--;\n }\n\n for (i = m + 2; i <= n; i++) {\n H[i][i - 2] = 0;\n if (i > m + 2) {\n H[i][i - 3] = 0;\n }\n }\n\n for (k = m; k <= n - 1; k++) {\n notlast = k !== n - 1;\n if (k !== m) {\n p = H[k][k - 1];\n q = H[k + 1][k - 1];\n r = notlast ? H[k + 2][k - 1] : 0;\n x = Math.abs(p) + Math.abs(q) + Math.abs(r);\n if (x !== 0) {\n p = p / x;\n q = q / x;\n r = r / x;\n }\n }\n\n if (x === 0) {\n break;\n }\n\n s = Math.sqrt(p * p + q * q + r * r);\n if (p < 0) {\n s = -s;\n }\n\n if (s !== 0) {\n if (k !== m) {\n H[k][k - 1] = -s * x;\n } else if (l !== m) {\n H[k][k - 1] = -H[k][k - 1];\n }\n\n p = p + s;\n x = p / s;\n y = q / s;\n z = r / s;\n q = q / p;\n r = r / p;\n\n for (j = k; j < nn; j++) {\n p = H[k][j] + q * H[k + 1][j];\n if (notlast) {\n p = p + r * H[k + 2][j];\n H[k + 2][j] = H[k + 2][j] - p * z;\n }\n\n H[k][j] = H[k][j] - p * x;\n H[k + 1][j] = H[k + 1][j] - p * y;\n }\n\n for (i = 0; i <= Math.min(n, k + 3); i++) {\n p = x * H[i][k] + y * H[i][k + 1];\n if (notlast) {\n p = p + z * H[i][k + 2];\n H[i][k + 2] = H[i][k + 2] - p * r;\n }\n\n H[i][k] = H[i][k] - p;\n H[i][k + 1] = H[i][k + 1] - p * q;\n }\n\n for (i = low; i <= high; i++) {\n p = x * V[i][k] + y * V[i][k + 1];\n if (notlast) {\n p = p + z * V[i][k + 2];\n V[i][k + 2] = V[i][k + 2] - p * r;\n }\n\n V[i][k] = V[i][k] - p;\n V[i][k + 1] = V[i][k + 1] - p * q;\n }\n }\n }\n }\n }\n\n if (norm === 0) {\n return;\n }\n\n for (n = nn - 1; n >= 0; n--) {\n p = d[n];\n q = e[n];\n\n if (q === 0) {\n l = n;\n H[n][n] = 1;\n for (i = n - 1; i >= 0; i--) {\n w = H[i][i] - p;\n r = 0;\n for (j = l; j <= n; j++) {\n r = r + H[i][j] * H[j][n];\n }\n\n if (e[i] < 0) {\n z = w;\n s = r;\n } else {\n l = i;\n if (e[i] === 0) {\n H[i][n] = w !== 0 ? -r / w : -r / (eps * norm);\n } else {\n x = H[i][i + 1];\n y = H[i + 1][i];\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\n t = (x * s - z * r) / q;\n H[i][n] = t;\n H[i + 1][n] =\n Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z;\n }\n\n t = Math.abs(H[i][n]);\n if (eps * t * t > 1) {\n for (j = i; j <= n; j++) {\n H[j][n] = H[j][n] / t;\n }\n }\n }\n }\n } else if (q < 0) {\n l = n - 1;\n\n if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) {\n H[n - 1][n - 1] = q / H[n][n - 1];\n H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1];\n } else {\n cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q);\n H[n - 1][n - 1] = cdivres[0];\n H[n - 1][n] = cdivres[1];\n }\n\n H[n][n - 1] = 0;\n H[n][n] = 1;\n for (i = n - 2; i >= 0; i--) {\n ra = 0;\n sa = 0;\n for (j = l; j <= n; j++) {\n ra = ra + H[i][j] * H[j][n - 1];\n sa = sa + H[i][j] * H[j][n];\n }\n\n w = H[i][i] - p;\n\n if (e[i] < 0) {\n z = w;\n r = ra;\n s = sa;\n } else {\n l = i;\n if (e[i] === 0) {\n cdivres = cdiv(-ra, -sa, w, q);\n H[i][n - 1] = cdivres[0];\n H[i][n] = cdivres[1];\n } else {\n x = H[i][i + 1];\n y = H[i + 1][i];\n vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;\n vi = (d[i] - p) * 2 * q;\n if (vr === 0 && vi === 0) {\n vr =\n eps *\n norm *\n (Math.abs(w) +\n Math.abs(q) +\n Math.abs(x) +\n Math.abs(y) +\n Math.abs(z));\n }\n cdivres = cdiv(\n x * r - z * ra + q * sa,\n x * s - z * sa - q * ra,\n vr,\n vi\n );\n H[i][n - 1] = cdivres[0];\n H[i][n] = cdivres[1];\n if (Math.abs(x) > Math.abs(z) + Math.abs(q)) {\n H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x;\n H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x;\n } else {\n cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q);\n H[i + 1][n - 1] = cdivres[0];\n H[i + 1][n] = cdivres[1];\n }\n }\n\n t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n]));\n if (eps * t * t > 1) {\n for (j = i; j <= n; j++) {\n H[j][n - 1] = H[j][n - 1] / t;\n H[j][n] = H[j][n] / t;\n }\n }\n }\n }\n }\n }\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n for (j = i; j < nn; j++) {\n V[i][j] = H[i][j];\n }\n }\n }\n\n for (j = nn - 1; j >= low; j--) {\n for (i = low; i <= high; i++) {\n z = 0;\n for (k = low; k <= Math.min(j, high); k++) {\n z = z + V[i][k] * H[k][j];\n }\n V[i][j] = z;\n }\n }\n}\n\nfunction cdiv(xr, xi, yr, yi) {\n var r, d;\n if (Math.abs(yr) > Math.abs(yi)) {\n r = yi / yr;\n d = yr + r * yi;\n return [(xr + r * xi) / d, (xi - r * xr) / d];\n } else {\n r = yr / yi;\n d = yi + r * yr;\n return [(r * xr + xi) / d, (r * xi - xr) / d];\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/dc/evd.js","import { Matrix, WrapperMatrix2D } from '../index';\n\n/**\n * @class CholeskyDecomposition\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs\n * @param {Matrix} value\n */\nexport default class CholeskyDecomposition {\n constructor(value) {\n value = WrapperMatrix2D.checkMatrix(value);\n if (!value.isSymmetric()) {\n throw new Error('Matrix is not symmetric');\n }\n\n var a = value;\n var dimension = a.rows;\n var l = new Matrix(dimension, dimension);\n var positiveDefinite = true;\n var i, j, k;\n\n for (j = 0; j < dimension; j++) {\n var Lrowj = l[j];\n var d = 0;\n for (k = 0; k < j; k++) {\n var Lrowk = l[k];\n var s = 0;\n for (i = 0; i < k; i++) {\n s += Lrowk[i] * Lrowj[i];\n }\n Lrowj[k] = s = (a.get(j, k) - s) / l[k][k];\n d = d + s * s;\n }\n\n d = a.get(j, j) - d;\n\n positiveDefinite &= d > 0;\n l[j][j] = Math.sqrt(Math.max(d, 0));\n for (k = j + 1; k < dimension; k++) {\n l[j][k] = 0;\n }\n }\n\n if (!positiveDefinite) {\n throw new Error('Matrix is not positive definite');\n }\n\n this.L = l;\n }\n\n /**\n *\n * @param {Matrix} value\n * @return {Matrix}\n */\n solve(value) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n var l = this.L;\n var dimension = l.rows;\n\n if (value.rows !== dimension) {\n throw new Error('Matrix dimensions do not match');\n }\n\n var count = value.columns;\n var B = value.clone();\n var i, j, k;\n\n for (k = 0; k < dimension; k++) {\n for (j = 0; j < count; j++) {\n for (i = 0; i < k; i++) {\n B[k][j] -= B[i][j] * l[k][i];\n }\n B[k][j] /= l[k][k];\n }\n }\n\n for (k = dimension - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n for (i = k + 1; i < dimension; i++) {\n B[k][j] -= B[i][j] * l[i][k];\n }\n B[k][j] /= l[k][k];\n }\n }\n\n return B;\n }\n\n /**\n *\n * @return {Matrix}\n */\n get lowerTriangularMatrix() {\n return this.L;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-matrix/src/dc/cholesky.js","import Matrix from 'ml-matrix';\nimport meanArray from 'ml-array-mean';\n\n/**\n * @private\n * return an array of probabilities of each class\n * @param {Array} array - contains the classes\n * @param {number} numberOfClasses\n * @return {Matrix} - rowVector of probabilities.\n */\nexport function toDiscreteDistribution(array, numberOfClasses) {\n var counts = new Array(numberOfClasses).fill(0);\n for (var i = 0; i < array.length; ++i) {\n counts[array[i]] += 1 / array.length;\n }\n\n return Matrix.rowVector(counts);\n}\n\n/**\n * @private\n * Retrieves the impurity of array of predictions\n * @param {Array} array - predictions.\n * @return {number} Gini impurity\n */\nexport function giniImpurity(array) {\n if (array.length === 0) {\n return 0;\n }\n\n var probabilities = toDiscreteDistribution(array, getNumberOfClasses(array))[0];\n\n var sum = 0.0;\n for (var i = 0; i < probabilities.length; ++i) {\n sum += probabilities[i] * probabilities[i];\n }\n\n return 1 - sum;\n}\n\n/**\n * @private\n * Return the number of classes given the array of predictions.\n * @param {Array} array - predictions.\n * @return {number} Number of classes.\n */\nexport function getNumberOfClasses(array) {\n return array.filter(function (val, i, arr) {\n return arr.indexOf(val) === i;\n }).length;\n}\n\n/**\n * @private\n * Calculates the Gini Gain of an array of predictions and those predictions splitted by a feature.\n * @para {Array} array - Predictions\n * @param {object} splitted - Object with elements \"greater\" and \"lesser\" that contains an array of predictions splitted.\n * @return {number} - Gini Gain.\n */\n\nexport function giniGain(array, splitted) {\n var splitsImpurity = 0.0;\n var splits = ['greater', 'lesser'];\n\n for (var i = 0; i < splits.length; ++i) {\n var currentSplit = splitted[splits[i]];\n splitsImpurity += giniImpurity(currentSplit) * currentSplit.length / array.length;\n }\n\n return giniImpurity(array) - splitsImpurity;\n}\n\n/**\n * @private\n * Calculates the squared error of a predictions values.\n * @param {Array} array - predictions values\n * @return {number} squared error.\n */\nexport function squaredError(array) {\n var l = array.length;\n\n var m = meanArray(array);\n var squaredError = 0.0;\n\n for (var i = 0; i < l; ++i) {\n var currentElement = array[i];\n squaredError += (currentElement - m) * (currentElement - m);\n }\n\n return squaredError;\n}\n\n/**\n * @private\n * Calculates the sum of squared error of the two arrays that contains the splitted values.\n * @param {Array} array - this argument is no necessary but is used to fit with the main interface.\n * @param {object} splitted - Object with elements \"greater\" and \"lesser\" that contains an array of predictions splitted.\n * @return {number} - sum of squared errors.\n */\nexport function regressionError(array, splitted) {\n var error = 0.0;\n var splits = ['greater', 'lesser'];\n\n for (var i = 0; i < splits.length; ++i) {\n var currentSplit = splitted[splits[i]];\n error += squaredError(currentSplit);\n }\n return error;\n}\n\n/**\n * @private\n * Split the training set and values from a given column of the training set if is less than a value\n * @param {Matrix} X - Training set.\n * @param {Array} y - Training values.\n * @param {number} column - Column to split.\n * @param {number} value - value to split the Training set and values.\n * @return {object} - Object that contains the splitted values.\n */\nexport function matrixSplitter(X, y, column, value) {\n var lesserX = [];\n var greaterX = [];\n var lesserY = [];\n var greaterY = [];\n\n for (var i = 0; i < X.rows; ++i) {\n if (X[i][column] < value) {\n lesserX.push(X[i]);\n lesserY.push(y[i]);\n } else {\n greaterX.push(X[i]);\n greaterY.push(y[i]);\n }\n }\n\n return {\n greaterX: greaterX,\n greaterY: greaterY,\n lesserX: lesserX,\n lesserY: lesserY\n };\n}\n\n/**\n * @private\n * Calculates the mean between two values\n * @param {number} a\n * @param {number} b\n * @return {number}\n */\nexport function mean(a, b) {\n return (a + b) / 2;\n}\n\n/**\n * @private\n * Returns a list of tuples that contains the i-th element of each array.\n * @param {Array} a\n * @param {Array} b\n * @return {Array} list of tuples.\n */\nexport function zip(a, b) {\n if (a.length !== b.length) {\n throw new TypeError('Error on zip: the size of a: ' + a.length + ' is different from b: ' + b.length);\n }\n\n var ret = new Array(a.length);\n for (var i = 0; i < a.length; ++i) {\n ret[i] = [a[i], b[i]];\n }\n\n return ret;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-cart/src/utils.js","import Matrix from 'ml-matrix';\nimport Tree from './TreeNode';\n\nconst defaultOptions = {\n gainFunction: 'regression',\n splitFunction: 'mean',\n minNumSamples: 3,\n maxDepth: Infinity\n};\n\nexport class DecisionTreeRegression {\n\n /**\n * Create new Decision Tree Regression with CART implementation with the given options.\n * @param {object} options\n * @param {string} [options.gainFunction=\"regression\"] - gain function to get the best split, \"regression\" the only one supported.\n * @param {string} [options.splitFunction=\"mean\"] - given two integers from a split feature, get the value to split, \"mean\" the only one supported.\n * @param {number} [options.minNumSamples=3] - minimum number of samples to create a leaf node to decide a class.\n * @param {number} [options.maxDepth=Infinity] - Max depth of the tree.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.options = model.options;\n this.root = new Tree(model.options);\n this.root.setNodeParameters(model.root);\n } else {\n this.options = Object.assign({}, defaultOptions, options);\n this.options.kind = 'regression';\n }\n }\n\n /**\n * Train the decision tree with the given training set and values.\n * @param {Matrix|MatrixTransposeView|Array} trainingSet\n * @param {Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n this.root = new Tree(this.options);\n\n if (trainingSet[0].length === undefined) trainingSet = Matrix.columnVector(trainingSet);\n trainingSet = Matrix.checkMatrix(trainingSet);\n this.root.train(trainingSet, trainingValues, 0);\n }\n\n /**\n * Predicts the values given the matrix to predict.\n * @param {Matrix|MatrixTransposeView|Array} toPredict\n * @return {Array} predictions\n */\n predict(toPredict) {\n if (toPredict[0] !== undefined && toPredict[0].length === undefined) toPredict = Matrix.columnVector(toPredict);\n toPredict = Matrix.checkMatrix(toPredict);\n\n var predictions = new Array(toPredict.rows);\n for (var i = 0; i < toPredict.rows; ++i) {\n predictions[i] = this.root.classify(toPredict.getRow(i));\n }\n\n return predictions;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n options: this.options,\n root: this.root,\n name: 'DTRegression'\n };\n }\n\n /**\n * Load a Decision tree regression with the given model.\n * @param {object} model\n * @return {DecisionTreeRegression}\n */\n static load(model) {\n if (model.name !== 'DTRegression') {\n throw new RangeError('Invalid model:' + model.name);\n }\n\n return new DecisionTreeRegression(true, model);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-cart/src/DecisionTreeRegression.js","export { RandomForestClassifier } from './RandomForestClassifier';\nexport { RandomForestRegression } from './RandomForestRegression';\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-random-forest/src/index.js","import { RandomForestBase } from './RandomForestBase';\n\nconst defaultOptions = {\n maxFeatures: 1.0,\n replacement: true,\n nEstimators: 10,\n seed: 42,\n useSampleBagging: false\n};\n\n/**\n * @class RandomForestClassifier\n * @augments RandomForestBase\n */\nexport class RandomForestClassifier extends RandomForestBase {\n /**\n * Create a new base random forest for a classifier or regression model.\n * @constructor\n * @param {object} options\n * @param {number} [options.maxFeatures=1.0] - the number of features used on each estimator.\n * * if is an integer it selects maxFeatures elements over the sample features.\n * * if is a float between (0, 1), it takes the percentage of features.\n * @param {boolean} [options.replacement=true] - use replacement over the sample features.\n * @param {number} [options.seed=42] - seed for feature and samples selection, must be a 32-bit integer.\n * @param {number} [options.nEstimators=10] - number of estimator to use.\n * @param {object} [options.treeOptions={}] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/}\n * @param {boolean} [options.useSampleBagging=false] - use bagging over training samples.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n super(true, model.baseModel);\n } else {\n options = Object.assign({}, defaultOptions, options);\n options.isClassifier = true;\n super(options);\n }\n }\n\n /**\n * retrieve the prediction given the selection method.\n * @param {Array} values - predictions of the estimators.\n * @return {number} prediction\n */\n selection(values) {\n return mode(values);\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n var baseModel = super.toJSON();\n return {\n baseModel: baseModel,\n name: 'RFClassifier'\n };\n }\n\n /**\n * Load a Decision tree classifier with the given model.\n * @param {object} model\n * @return {RandomForestClassifier}\n */\n static load(model) {\n if (model.name !== 'RFClassifier') {\n throw new RangeError(`Invalid model: ${model.name}`);\n }\n\n return new RandomForestClassifier(true, model);\n }\n}\n\n/**\n * Return the most repeated element on the array.\n * @param {Array} arr\n * @return {number} mode\n */\nfunction mode(arr) {\n return arr.sort((a, b) =>\n arr.filter((v) => v === a).length\n - arr.filter((v) => v === b).length\n ).pop();\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-random-forest/src/RandomForestClassifier.js","import Random from 'random-js';\nimport Matrix from 'ml-matrix';\n\nexport function checkFloat(n) {\n return n > 0.0 && n <= 1.0;\n}\n\n/**\n * Select n with replacement elements on the training set and values, where n is the size of the training set.\n * @ignore\n * @param {Matrix} trainingSet\n * @param {Array} trainingValue\n * @param {number} seed - seed for the random selection, must be a 32-bit integer.\n * @return {object} with new X and y.\n */\nexport function examplesBaggingWithReplacement(trainingSet, trainingValue, seed) {\n var engine = Random.engines.mt19937();\n var distribution = Random.integer(0, trainingSet.rows - 1);\n if (seed === undefined) {\n engine = engine.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = engine.seed(seed);\n } else {\n throw new RangeError(`Expected seed must be undefined or integer not ${seed}`);\n }\n\n var Xr = new Array(trainingSet.rows);\n var yr = new Array(trainingSet.rows);\n\n for (var i = 0; i < trainingSet.rows; ++i) {\n var index = distribution(engine);\n Xr[i] = trainingSet[index];\n yr[i] = trainingValue[index];\n }\n\n return {\n X: new Matrix(Xr),\n y: yr\n };\n}\n\n/**\n * selects n features from the training set with or without replacement, returns the new training set and the indexes used.\n * @ignore\n * @param {Matrix} trainingSet\n * @param {number} n - features.\n * @param {boolean} replacement\n * @param {number} seed - seed for the random selection, must be a 32-bit integer.\n * @return {object}\n */\nexport function featureBagging(trainingSet, n, replacement, seed) {\n if (trainingSet.columns < n) {\n throw new RangeError('N should be less or equal to the number of columns of X');\n }\n\n var distribution = Random.integer(0, trainingSet.columns - 1);\n var engine = Random.engines.mt19937();\n if (seed === undefined) {\n engine = engine.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = engine.seed(seed);\n } else {\n throw new RangeError(`Expected seed must be undefined or integer not ${seed}`);\n }\n\n var toRet = new Matrix(trainingSet.rows, n);\n\n if (replacement) {\n var usedIndex = new Array(n);\n for (var i = 0; i < n; ++i) {\n var index = distribution(engine);\n usedIndex[i] = index;\n toRet.setColumn(i, trainingSet.getColumn(index));\n }\n } else {\n usedIndex = new Set();\n index = distribution(engine);\n for (i = 0; i < n; ++i) {\n while (usedIndex.has(index)) {\n index = distribution(engine);\n }\n toRet.setColumn(i, trainingSet.getColumn(index));\n usedIndex.add(index);\n }\n usedIndex = Array.from(usedIndex);\n }\n\n return {\n X: toRet,\n usedIndex: usedIndex\n };\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-random-forest/src/utils.js","/*jshint eqnull:true*/\n(function (root) {\n \"use strict\";\n\n var GLOBAL_KEY = \"Random\";\n\n var imul = (typeof Math.imul !== \"function\" || Math.imul(0xffffffff, 5) !== -5 ?\n function (a, b) {\n var ah = (a >>> 16) & 0xffff;\n var al = a & 0xffff;\n var bh = (b >>> 16) & 0xffff;\n var bl = b & 0xffff;\n // the shift by 0 fixes the sign on the high part\n // the final |0 converts the unsigned value into a signed value\n return (al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0;\n } :\n Math.imul);\n\n var stringRepeat = (typeof String.prototype.repeat === \"function\" && \"x\".repeat(3) === \"xxx\" ?\n function (x, y) {\n return x.repeat(y);\n } : function (pattern, count) {\n var result = \"\";\n while (count > 0) {\n if (count & 1) {\n result += pattern;\n }\n count >>= 1;\n pattern += pattern;\n }\n return result;\n });\n\n function Random(engine) {\n if (!(this instanceof Random)) {\n return new Random(engine);\n }\n\n if (engine == null) {\n engine = Random.engines.nativeMath;\n } else if (typeof engine !== \"function\") {\n throw new TypeError(\"Expected engine to be a function, got \" + typeof engine);\n }\n this.engine = engine;\n }\n var proto = Random.prototype;\n\n Random.engines = {\n nativeMath: function () {\n return (Math.random() * 0x100000000) | 0;\n },\n mt19937: (function (Int32Array) {\n // http://en.wikipedia.org/wiki/Mersenne_twister\n function refreshData(data) {\n var k = 0;\n var tmp = 0;\n for (;\n (k | 0) < 227; k = (k + 1) | 0) {\n tmp = (data[k] & 0x80000000) | (data[(k + 1) | 0] & 0x7fffffff);\n data[k] = data[(k + 397) | 0] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);\n }\n\n for (;\n (k | 0) < 623; k = (k + 1) | 0) {\n tmp = (data[k] & 0x80000000) | (data[(k + 1) | 0] & 0x7fffffff);\n data[k] = data[(k - 227) | 0] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);\n }\n\n tmp = (data[623] & 0x80000000) | (data[0] & 0x7fffffff);\n data[623] = data[396] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);\n }\n\n function temper(value) {\n value ^= value >>> 11;\n value ^= (value << 7) & 0x9d2c5680;\n value ^= (value << 15) & 0xefc60000;\n return value ^ (value >>> 18);\n }\n\n function seedWithArray(data, source) {\n var i = 1;\n var j = 0;\n var sourceLength = source.length;\n var k = Math.max(sourceLength, 624) | 0;\n var previous = data[0] | 0;\n for (;\n (k | 0) > 0; --k) {\n data[i] = previous = ((data[i] ^ imul((previous ^ (previous >>> 30)), 0x0019660d)) + (source[j] | 0) + (j | 0)) | 0;\n i = (i + 1) | 0;\n ++j;\n if ((i | 0) > 623) {\n data[0] = data[623];\n i = 1;\n }\n if (j >= sourceLength) {\n j = 0;\n }\n }\n for (k = 623;\n (k | 0) > 0; --k) {\n data[i] = previous = ((data[i] ^ imul((previous ^ (previous >>> 30)), 0x5d588b65)) - i) | 0;\n i = (i + 1) | 0;\n if ((i | 0) > 623) {\n data[0] = data[623];\n i = 1;\n }\n }\n data[0] = 0x80000000;\n }\n\n function mt19937() {\n var data = new Int32Array(624);\n var index = 0;\n var uses = 0;\n\n function next() {\n if ((index | 0) >= 624) {\n refreshData(data);\n index = 0;\n }\n\n var value = data[index];\n index = (index + 1) | 0;\n uses += 1;\n return temper(value) | 0;\n }\n next.getUseCount = function() {\n return uses;\n };\n next.discard = function (count) {\n uses += count;\n if ((index | 0) >= 624) {\n refreshData(data);\n index = 0;\n }\n while ((count - index) > 624) {\n count -= 624 - index;\n refreshData(data);\n index = 0;\n }\n index = (index + count) | 0;\n return next;\n };\n next.seed = function (initial) {\n var previous = 0;\n data[0] = previous = initial | 0;\n\n for (var i = 1; i < 624; i = (i + 1) | 0) {\n data[i] = previous = (imul((previous ^ (previous >>> 30)), 0x6c078965) + i) | 0;\n }\n index = 624;\n uses = 0;\n return next;\n };\n next.seedWithArray = function (source) {\n next.seed(0x012bd6aa);\n seedWithArray(data, source);\n return next;\n };\n next.autoSeed = function () {\n return next.seedWithArray(Random.generateEntropyArray());\n };\n return next;\n }\n\n return mt19937;\n }(typeof Int32Array === \"function\" ? Int32Array : Array)),\n browserCrypto: (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\" && typeof Int32Array === \"function\") ? (function () {\n var data = null;\n var index = 128;\n\n return function () {\n if (index >= 128) {\n if (data === null) {\n data = new Int32Array(128);\n }\n crypto.getRandomValues(data);\n index = 0;\n }\n\n return data[index++] | 0;\n };\n }()) : null\n };\n\n Random.generateEntropyArray = function () {\n var array = [];\n var engine = Random.engines.nativeMath;\n for (var i = 0; i < 16; ++i) {\n array[i] = engine() | 0;\n }\n array.push(new Date().getTime() | 0);\n return array;\n };\n\n function returnValue(value) {\n return function () {\n return value;\n };\n }\n\n // [-0x80000000, 0x7fffffff]\n Random.int32 = function (engine) {\n return engine() | 0;\n };\n proto.int32 = function () {\n return Random.int32(this.engine);\n };\n\n // [0, 0xffffffff]\n Random.uint32 = function (engine) {\n return engine() >>> 0;\n };\n proto.uint32 = function () {\n return Random.uint32(this.engine);\n };\n\n // [0, 0x1fffffffffffff]\n Random.uint53 = function (engine) {\n var high = engine() & 0x1fffff;\n var low = engine() >>> 0;\n return (high * 0x100000000) + low;\n };\n proto.uint53 = function () {\n return Random.uint53(this.engine);\n };\n\n // [0, 0x20000000000000]\n Random.uint53Full = function (engine) {\n while (true) {\n var high = engine() | 0;\n if (high & 0x200000) {\n if ((high & 0x3fffff) === 0x200000 && (engine() | 0) === 0) {\n return 0x20000000000000;\n }\n } else {\n var low = engine() >>> 0;\n return ((high & 0x1fffff) * 0x100000000) + low;\n }\n }\n };\n proto.uint53Full = function () {\n return Random.uint53Full(this.engine);\n };\n\n // [-0x20000000000000, 0x1fffffffffffff]\n Random.int53 = function (engine) {\n var high = engine() | 0;\n var low = engine() >>> 0;\n return ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);\n };\n proto.int53 = function () {\n return Random.int53(this.engine);\n };\n\n // [-0x20000000000000, 0x20000000000000]\n Random.int53Full = function (engine) {\n while (true) {\n var high = engine() | 0;\n if (high & 0x400000) {\n if ((high & 0x7fffff) === 0x400000 && (engine() | 0) === 0) {\n return 0x20000000000000;\n }\n } else {\n var low = engine() >>> 0;\n return ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);\n }\n }\n };\n proto.int53Full = function () {\n return Random.int53Full(this.engine);\n };\n\n function add(generate, addend) {\n if (addend === 0) {\n return generate;\n } else {\n return function (engine) {\n return generate(engine) + addend;\n };\n }\n }\n\n Random.integer = (function () {\n function isPowerOfTwoMinusOne(value) {\n return ((value + 1) & value) === 0;\n }\n\n function bitmask(masking) {\n return function (engine) {\n return engine() & masking;\n };\n }\n\n function downscaleToLoopCheckedRange(range) {\n var extendedRange = range + 1;\n var maximum = extendedRange * Math.floor(0x100000000 / extendedRange);\n return function (engine) {\n var value = 0;\n do {\n value = engine() >>> 0;\n } while (value >= maximum);\n return value % extendedRange;\n };\n }\n\n function downscaleToRange(range) {\n if (isPowerOfTwoMinusOne(range)) {\n return bitmask(range);\n } else {\n return downscaleToLoopCheckedRange(range);\n }\n }\n\n function isEvenlyDivisibleByMaxInt32(value) {\n return (value | 0) === 0;\n }\n\n function upscaleWithHighMasking(masking) {\n return function (engine) {\n var high = engine() & masking;\n var low = engine() >>> 0;\n return (high * 0x100000000) + low;\n };\n }\n\n function upscaleToLoopCheckedRange(extendedRange) {\n var maximum = extendedRange * Math.floor(0x20000000000000 / extendedRange);\n return function (engine) {\n var ret = 0;\n do {\n var high = engine() & 0x1fffff;\n var low = engine() >>> 0;\n ret = (high * 0x100000000) + low;\n } while (ret >= maximum);\n return ret % extendedRange;\n };\n }\n\n function upscaleWithinU53(range) {\n var extendedRange = range + 1;\n if (isEvenlyDivisibleByMaxInt32(extendedRange)) {\n var highRange = ((extendedRange / 0x100000000) | 0) - 1;\n if (isPowerOfTwoMinusOne(highRange)) {\n return upscaleWithHighMasking(highRange);\n }\n }\n return upscaleToLoopCheckedRange(extendedRange);\n }\n\n function upscaleWithinI53AndLoopCheck(min, max) {\n return function (engine) {\n var ret = 0;\n do {\n var high = engine() | 0;\n var low = engine() >>> 0;\n ret = ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);\n } while (ret < min || ret > max);\n return ret;\n };\n }\n\n return function (min, max) {\n min = Math.floor(min);\n max = Math.floor(max);\n if (min < -0x20000000000000 || !isFinite(min)) {\n throw new RangeError(\"Expected min to be at least \" + (-0x20000000000000));\n } else if (max > 0x20000000000000 || !isFinite(max)) {\n throw new RangeError(\"Expected max to be at most \" + 0x20000000000000);\n }\n\n var range = max - min;\n if (range <= 0 || !isFinite(range)) {\n return returnValue(min);\n } else if (range === 0xffffffff) {\n if (min === 0) {\n return Random.uint32;\n } else {\n return add(Random.int32, min + 0x80000000);\n }\n } else if (range < 0xffffffff) {\n return add(downscaleToRange(range), min);\n } else if (range === 0x1fffffffffffff) {\n return add(Random.uint53, min);\n } else if (range < 0x1fffffffffffff) {\n return add(upscaleWithinU53(range), min);\n } else if (max - 1 - min === 0x1fffffffffffff) {\n return add(Random.uint53Full, min);\n } else if (min === -0x20000000000000 && max === 0x20000000000000) {\n return Random.int53Full;\n } else if (min === -0x20000000000000 && max === 0x1fffffffffffff) {\n return Random.int53;\n } else if (min === -0x1fffffffffffff && max === 0x20000000000000) {\n return add(Random.int53, 1);\n } else if (max === 0x20000000000000) {\n return add(upscaleWithinI53AndLoopCheck(min - 1, max - 1), 1);\n } else {\n return upscaleWithinI53AndLoopCheck(min, max);\n }\n };\n }());\n proto.integer = function (min, max) {\n return Random.integer(min, max)(this.engine);\n };\n\n // [0, 1] (floating point)\n Random.realZeroToOneInclusive = function (engine) {\n return Random.uint53Full(engine) / 0x20000000000000;\n };\n proto.realZeroToOneInclusive = function () {\n return Random.realZeroToOneInclusive(this.engine);\n };\n\n // [0, 1) (floating point)\n Random.realZeroToOneExclusive = function (engine) {\n return Random.uint53(engine) / 0x20000000000000;\n };\n proto.realZeroToOneExclusive = function () {\n return Random.realZeroToOneExclusive(this.engine);\n };\n\n Random.real = (function () {\n function multiply(generate, multiplier) {\n if (multiplier === 1) {\n return generate;\n } else if (multiplier === 0) {\n return function () {\n return 0;\n };\n } else {\n return function (engine) {\n return generate(engine) * multiplier;\n };\n }\n }\n\n return function (left, right, inclusive) {\n if (!isFinite(left)) {\n throw new RangeError(\"Expected left to be a finite number\");\n } else if (!isFinite(right)) {\n throw new RangeError(\"Expected right to be a finite number\");\n }\n return add(\n multiply(\n inclusive ? Random.realZeroToOneInclusive : Random.realZeroToOneExclusive,\n right - left),\n left);\n };\n }());\n proto.real = function (min, max, inclusive) {\n return Random.real(min, max, inclusive)(this.engine);\n };\n\n Random.bool = (function () {\n function isLeastBitTrue(engine) {\n return (engine() & 1) === 1;\n }\n\n function lessThan(generate, value) {\n return function (engine) {\n return generate(engine) < value;\n };\n }\n\n function probability(percentage) {\n if (percentage <= 0) {\n return returnValue(false);\n } else if (percentage >= 1) {\n return returnValue(true);\n } else {\n var scaled = percentage * 0x100000000;\n if (scaled % 1 === 0) {\n return lessThan(Random.int32, (scaled - 0x80000000) | 0);\n } else {\n return lessThan(Random.uint53, Math.round(percentage * 0x20000000000000));\n }\n }\n }\n\n return function (numerator, denominator) {\n if (denominator == null) {\n if (numerator == null) {\n return isLeastBitTrue;\n }\n return probability(numerator);\n } else {\n if (numerator <= 0) {\n return returnValue(false);\n } else if (numerator >= denominator) {\n return returnValue(true);\n }\n return lessThan(Random.integer(0, denominator - 1), numerator);\n }\n };\n }());\n proto.bool = function (numerator, denominator) {\n return Random.bool(numerator, denominator)(this.engine);\n };\n\n function toInteger(value) {\n var number = +value;\n if (number < 0) {\n return Math.ceil(number);\n } else {\n return Math.floor(number);\n }\n }\n\n function convertSliceArgument(value, length) {\n if (value < 0) {\n return Math.max(value + length, 0);\n } else {\n return Math.min(value, length);\n }\n }\n Random.pick = function (engine, array, begin, end) {\n var length = array.length;\n var start = begin == null ? 0 : convertSliceArgument(toInteger(begin), length);\n var finish = end === void 0 ? length : convertSliceArgument(toInteger(end), length);\n if (start >= finish) {\n return void 0;\n }\n var distribution = Random.integer(start, finish - 1);\n return array[distribution(engine)];\n };\n proto.pick = function (array, begin, end) {\n return Random.pick(this.engine, array, begin, end);\n };\n\n function returnUndefined() {\n return void 0;\n }\n var slice = Array.prototype.slice;\n Random.picker = function (array, begin, end) {\n var clone = slice.call(array, begin, end);\n if (!clone.length) {\n return returnUndefined;\n }\n var distribution = Random.integer(0, clone.length - 1);\n return function (engine) {\n return clone[distribution(engine)];\n };\n };\n\n Random.shuffle = function (engine, array, downTo) {\n var length = array.length;\n if (length) {\n if (downTo == null) {\n downTo = 0;\n }\n for (var i = (length - 1) >>> 0; i > downTo; --i) {\n var distribution = Random.integer(0, i);\n var j = distribution(engine);\n if (i !== j) {\n var tmp = array[i];\n array[i] = array[j];\n array[j] = tmp;\n }\n }\n }\n return array;\n };\n proto.shuffle = function (array) {\n return Random.shuffle(this.engine, array);\n };\n\n Random.sample = function (engine, population, sampleSize) {\n if (sampleSize < 0 || sampleSize > population.length || !isFinite(sampleSize)) {\n throw new RangeError(\"Expected sampleSize to be within 0 and the length of the population\");\n }\n\n if (sampleSize === 0) {\n return [];\n }\n\n var clone = slice.call(population);\n var length = clone.length;\n if (length === sampleSize) {\n return Random.shuffle(engine, clone, 0);\n }\n var tailLength = length - sampleSize;\n return Random.shuffle(engine, clone, tailLength - 1).slice(tailLength);\n };\n proto.sample = function (population, sampleSize) {\n return Random.sample(this.engine, population, sampleSize);\n };\n\n Random.die = function (sideCount) {\n return Random.integer(1, sideCount);\n };\n proto.die = function (sideCount) {\n return Random.die(sideCount)(this.engine);\n };\n\n Random.dice = function (sideCount, dieCount) {\n var distribution = Random.die(sideCount);\n return function (engine) {\n var result = [];\n result.length = dieCount;\n for (var i = 0; i < dieCount; ++i) {\n result[i] = distribution(engine);\n }\n return result;\n };\n };\n proto.dice = function (sideCount, dieCount) {\n return Random.dice(sideCount, dieCount)(this.engine);\n };\n\n // http://en.wikipedia.org/wiki/Universally_unique_identifier\n Random.uuid4 = (function () {\n function zeroPad(string, zeroCount) {\n return stringRepeat(\"0\", zeroCount - string.length) + string;\n }\n\n return function (engine) {\n var a = engine() >>> 0;\n var b = engine() | 0;\n var c = engine() | 0;\n var d = engine() >>> 0;\n\n return (\n zeroPad(a.toString(16), 8) +\n \"-\" +\n zeroPad((b & 0xffff).toString(16), 4) +\n \"-\" +\n zeroPad((((b >> 4) & 0x0fff) | 0x4000).toString(16), 4) +\n \"-\" +\n zeroPad(((c & 0x3fff) | 0x8000).toString(16), 4) +\n \"-\" +\n zeroPad(((c >> 4) & 0xffff).toString(16), 4) +\n zeroPad(d.toString(16), 8));\n };\n }());\n proto.uuid4 = function () {\n return Random.uuid4(this.engine);\n };\n\n Random.string = (function () {\n // has 2**x chars, for faster uniform distribution\n var DEFAULT_STRING_POOL = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-\";\n\n return function (pool) {\n if (pool == null) {\n pool = DEFAULT_STRING_POOL;\n }\n\n var length = pool.length;\n if (!length) {\n throw new Error(\"Expected pool not to be an empty string\");\n }\n\n var distribution = Random.integer(0, length - 1);\n return function (engine, length) {\n var result = \"\";\n for (var i = 0; i < length; ++i) {\n var j = distribution(engine);\n result += pool.charAt(j);\n }\n return result;\n };\n };\n }());\n proto.string = function (length, pool) {\n return Random.string(pool)(this.engine, length);\n };\n\n Random.hex = (function () {\n var LOWER_HEX_POOL = \"0123456789abcdef\";\n var lowerHex = Random.string(LOWER_HEX_POOL);\n var upperHex = Random.string(LOWER_HEX_POOL.toUpperCase());\n\n return function (upper) {\n if (upper) {\n return upperHex;\n } else {\n return lowerHex;\n }\n };\n }());\n proto.hex = function (length, upper) {\n return Random.hex(upper)(this.engine, length);\n };\n\n Random.date = function (start, end) {\n if (!(start instanceof Date)) {\n throw new TypeError(\"Expected start to be a Date, got \" + typeof start);\n } else if (!(end instanceof Date)) {\n throw new TypeError(\"Expected end to be a Date, got \" + typeof end);\n }\n var distribution = Random.integer(start.getTime(), end.getTime());\n return function (engine) {\n return new Date(distribution(engine));\n };\n };\n proto.date = function (start, end) {\n return Random.date(start, end)(this.engine);\n };\n\n if (typeof define === \"function\" && define.amd) {\n define(function () {\n return Random;\n });\n } else if (typeof module !== \"undefined\" && typeof require === \"function\") {\n module.exports = Random;\n } else {\n (function () {\n var oldGlobal = root[GLOBAL_KEY];\n Random.noConflict = function () {\n root[GLOBAL_KEY] = oldGlobal;\n return this;\n };\n }());\n root[GLOBAL_KEY] = Random;\n }\n}(this));\n\n\n// WEBPACK FOOTER //\n// ./node_modules/random-js/lib/random.js","import arrayMean from 'ml-array-mean';\nimport arrayMedian from 'ml-array-median';\n\nimport { RandomForestBase } from './RandomForestBase';\n\nconst selectionMethods = {\n mean: arrayMean,\n median: arrayMedian\n};\n\nconst defaultOptions = {\n maxFeatures: 1.0,\n replacement: false,\n nEstimators: 10,\n treeOptions: {},\n selectionMethod: 'mean',\n seed: 42,\n useSampleBagging: false\n};\n\n/**\n * @class RandomForestRegression\n * @augments RandomForestBase\n */\nexport class RandomForestRegression extends RandomForestBase {\n /**\n * Create a new base random forest for a classifier or regression model.\n * @constructor\n * @param {object} options\n * @param {number} [options.maxFeatures=1.0] - the number of features used on each estimator.\n * * if is an integer it selects maxFeatures elements over the sample features.\n * * if is a float between (0, 1), it takes the percentage of features.\n * @param {boolean} [options.replacement=true] - use replacement over the sample features.\n * @param {number} [options.seed=42] - seed for feature and samples selection, must be a 32-bit integer.\n * @param {number} [options.nEstimators=10] - number of estimator to use.\n * @param {object} [options.treeOptions={}] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/}\n * @param {string} [options.selectionMethod=\"mean\"] - the way to calculate the prediction from estimators, \"mean\" and \"median\" are supported.\n * @param {boolean} [options.useSampleBagging=false] - use bagging over training samples.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n super(true, model.baseModel);\n this.selectionMethod = model.selectionMethod;\n } else {\n options = Object.assign({}, defaultOptions, options);\n\n if (!(options.selectionMethod === 'mean' || options.selectionMethod === 'median')) {\n throw new RangeError(`Unsupported selection method ${options.selectionMethod}`);\n }\n\n options.isClassifier = false;\n\n super(options);\n this.selectionMethod = options.selectionMethod;\n }\n }\n\n /**\n * retrieve the prediction given the selection method.\n * @param {Array} values - predictions of the estimators.\n * @return {number} prediction\n */\n selection(values) {\n return selectionMethods[this.selectionMethod](values);\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n var baseModel = super.toJSON();\n return {\n baseModel: baseModel,\n selectionMethod: this.selectionMethod,\n name: 'RFRegression'\n };\n }\n\n /**\n * Load a Decision tree classifier with the given model.\n * @param {object} model\n * @return {RandomForestRegression}\n */\n static load(model) {\n if (model.name !== 'RFRegression') {\n throw new RangeError(`Invalid model: ${model.name}`);\n }\n\n return new RandomForestRegression(true, model);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-random-forest/src/RandomForestRegression.js","(function(){function a(d){for(var e=0,f=d.length-1,g=void 0,h=void 0,i=void 0,j=c(e,f);!0;){if(f<=e)return d[j];if(f==e+1)return d[e]>d[f]&&b(d,e,f),d[j];for(g=c(e,f),d[g]>d[f]&&b(d,g,f),d[e]>d[f]&&b(d,e,f),d[g]>d[e]&&b(d,g,e),b(d,g,e+1),h=e+1,i=f;!0;){do h++;while(d[e]>d[h]);do i--;while(d[i]>d[e]);if(i=j&&(f=i-1)}}var b=function b(d,e,f){var _ref;return _ref=[d[f],d[e]],d[e]=_ref[0],d[f]=_ref[1],_ref},c=function c(d,e){return~~((d+e)/2)};'undefined'!=typeof module&&module.exports?module.exports=a:window.median=a})();\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/median-quickselect/lib/median-quickselect.min.js","'use strict';\n\nconst matrixLib = require('ml-matrix');\nconst Matrix = matrixLib.Matrix;\nconst EVD = matrixLib.EVD;\nconst SVD = matrixLib.SVD;\nconst Stat = require('ml-stat/matrix');\nconst mean = Stat.mean;\nconst stdev = Stat.standardDeviation;\n\nconst defaultOptions = {\n isCovarianceMatrix: false,\n center: true,\n scale: false\n};\n\n/**\n * Creates new PCA (Principal Component Analysis) from the dataset\n * @param {Matrix} dataset - dataset or covariance matrix\n * @param {Object} options\n * @param {boolean} [options.isCovarianceMatrix=false] - true if the dataset is a covariance matrix\n * @param {boolean} [options.center=true] - should the data be centered (subtract the mean)\n * @param {boolean} [options.scale=false] - should the data be scaled (divide by the standard deviation)\n * */\nclass PCA {\n constructor(dataset, options) {\n if (dataset === true) {\n const model = options;\n this.center = model.center;\n this.scale = model.scale;\n this.means = model.means;\n this.stdevs = model.stdevs;\n this.U = Matrix.checkMatrix(model.U);\n this.S = model.S;\n return;\n }\n\n options = Object.assign({}, defaultOptions, options);\n\n this.center = false;\n this.scale = false;\n this.means = null;\n this.stdevs = null;\n\n if (options.isCovarianceMatrix) { // user provided a covariance matrix instead of dataset\n this._computeFromCovarianceMatrix(dataset);\n return;\n }\n\n var useCovarianceMatrix;\n if (typeof options.useCovarianceMatrix === 'boolean') {\n useCovarianceMatrix = options.useCovarianceMatrix;\n } else {\n useCovarianceMatrix = dataset.length > dataset[0].length;\n }\n\n if (useCovarianceMatrix) { // user provided a dataset but wants us to compute and use the covariance matrix\n dataset = this._adjust(dataset, options);\n const covarianceMatrix = dataset.transposeView().mmul(dataset).div(dataset.rows - 1);\n this._computeFromCovarianceMatrix(covarianceMatrix);\n } else {\n dataset = this._adjust(dataset, options);\n var svd = new SVD(dataset, {\n computeLeftSingularVectors: false,\n computeRightSingularVectors: true,\n autoTranspose: true\n });\n\n this.U = svd.rightSingularVectors;\n\n const singularValues = svd.diagonal;\n const eigenvalues = new Array(singularValues.length);\n for (var i = 0; i < singularValues.length; i++) {\n eigenvalues[i] = singularValues[i] * singularValues[i] / (dataset.length - 1);\n }\n this.S = eigenvalues;\n }\n }\n\n /**\n * Load a PCA model from JSON\n * @param {Object} model\n * @return {PCA}\n */\n static load(model) {\n if (model.name !== 'PCA')\n throw new RangeError('Invalid model: ' + model.name);\n return new PCA(true, model);\n }\n\n\n /**\n * Project the dataset into the PCA space\n * @param {Matrix} dataset\n * @param {Object} options\n * @return {Matrix} dataset projected in the PCA space\n */\n predict(dataset, options = {}) {\n const {\n nComponents = this.U.columns\n } = options;\n\n dataset = new Matrix(dataset);\n if (this.center) {\n dataset.subRowVector(this.means);\n if (this.scale) {\n dataset.divRowVector(this.stdevs);\n }\n }\n\n var predictions = dataset.mmul(this.U);\n return predictions.subMatrix(0, predictions.rows - 1, 0, nComponents - 1);\n }\n\n /**\n * Returns the proportion of variance for each component\n * @return {[number]}\n */\n getExplainedVariance() {\n var sum = 0;\n for (var i = 0; i < this.S.length; i++) {\n sum += this.S[i];\n }\n return this.S.map(value => value / sum);\n }\n\n /**\n * Returns the cumulative proportion of variance\n * @return {[number]}\n */\n getCumulativeVariance() {\n var explained = this.getExplainedVariance();\n for (var i = 1; i < explained.length; i++) {\n explained[i] += explained[i - 1];\n }\n return explained;\n }\n\n /**\n * Returns the Eigenvectors of the covariance matrix\n * @returns {Matrix}\n */\n getEigenvectors() {\n return this.U;\n }\n\n /**\n * Returns the Eigenvalues (on the diagonal)\n * @returns {[number]}\n */\n getEigenvalues() {\n return this.S;\n }\n\n /**\n * Returns the standard deviations of the principal components\n * @returns {[number]}\n */\n getStandardDeviations() {\n return this.S.map(x => Math.sqrt(x));\n }\n\n /**\n * Returns the loadings matrix\n * @return {Matrix}\n */\n getLoadings() {\n return this.U.transpose();\n }\n\n /**\n * Export the current model to a JSON object\n * @return {Object} model\n */\n toJSON() {\n return {\n name: 'PCA',\n center: this.center,\n scale: this.scale,\n means: this.means,\n stdevs: this.stdevs,\n U: this.U,\n S: this.S,\n };\n }\n\n _adjust(dataset, options) {\n this.center = !!options.center;\n this.scale = !!options.scale;\n\n dataset = new Matrix(dataset);\n\n if (this.center) {\n const means = mean(dataset);\n const stdevs = this.scale ? stdev(dataset, means, true) : null;\n this.means = means;\n dataset.subRowVector(means);\n if (this.scale) {\n for (var i = 0; i < stdevs.length; i++) {\n if (stdevs[i] === 0) {\n throw new RangeError('Cannot scale the dataset (standard deviation is zero at index ' + i);\n }\n }\n this.stdevs = stdevs;\n dataset.divRowVector(stdevs);\n }\n }\n\n return dataset;\n }\n\n _computeFromCovarianceMatrix(dataset) {\n const evd = new EVD(dataset, {assumeSymmetric: true});\n this.U = evd.eigenvectorMatrix;\n for (var i = 0; i < this.U.length; i++) {\n this.U[i].reverse();\n }\n this.S = evd.realEigenvalues.reverse();\n }\n}\n\nmodule.exports = PCA;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-pca/src/pca.js","'use strict';\n\nexports.agnes = require('./agnes');\nexports.diana = require('./diana');\n//exports.birch = require('./birch');\n//exports.cure = require('./cure');\n//exports.chameleon = require('./chameleon');\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-hclust/src/index.js","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\nconst ClusterLeaf = require('./ClusterLeaf');\nconst Cluster = require('./Cluster');\nconst distanceMatrix = require('ml-distance-matrix');\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction simpleLink(cluster1, cluster2, disFun) {\n var m = 10e100;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n var d = disFun[cluster1[i]][ cluster2[j]];\n m = Math.min(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction completeLink(cluster1, cluster2, disFun) {\n var m = -1;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n var d = disFun[cluster1[i]][ cluster2[j]];\n m = Math.max(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction averageLink(cluster1, cluster2, disFun) {\n var m = 0;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n m += disFun[cluster1[i]][ cluster2[j]];\n }\n }\n return m / (cluster1.length * cluster2.length);\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {*}\n */\nfunction centroidLink(cluster1, cluster2, disFun) {\n var dist = new Array(cluster1.length * cluster2.length);\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n dist[i * cluster2.length + j] = (disFun[cluster1[i]][ cluster2[j]]);\n }\n }\n return median(dist);\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction wardLink(cluster1, cluster2, disFun) {\n return centroidLink(cluster1, cluster2, disFun)\n * cluster1.length * cluster2.length / (cluster1.length + cluster2.length);\n}\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nfunction median(values, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return (values[half - 1] + values[half]) * 0.5;\n } else {\n return values[half];\n }\n}\n\nvar defaultOptions = {\n disFunc: euclidean,\n kind: 'single',\n isDistanceMatrix: false\n\n};\n\n/**\n * Continuously merge nodes that have the least dissimilarity\n * @param {Array >} distance - Array of points to be clustered\n * @param {json} options\n * @option isDistanceMatrix: Is the input a distance matrix?\n * @constructor\n */\nfunction agnes(data, options) {\n options = Object.assign({}, defaultOptions, options);\n var len = data.length;\n var distance = data;//If source\n if (!options.isDistanceMatrix) {\n distance = distanceMatrix(data, options.disFunc);\n }\n\n\n // allows to use a string or a given function\n if (typeof options.kind === 'string') {\n switch (options.kind) {\n case 'single':\n options.kind = simpleLink;\n break;\n case 'complete':\n options.kind = completeLink;\n break;\n case 'average':\n options.kind = averageLink;\n break;\n case 'centroid':\n options.kind = centroidLink;\n break;\n case 'ward':\n options.kind = wardLink;\n break;\n default:\n throw new RangeError('Unknown kind of similarity');\n }\n } else if (typeof options.kind !== 'function') {\n throw new TypeError('Undefined kind of similarity');\n }\n\n var list = new Array(len);\n for (var i = 0; i < distance.length; i++) {\n list[i] = new ClusterLeaf(i);\n }\n var min = 10e5,\n d = {},\n dis = 0;\n\n while (list.length > 1) {\n // calculates the minimum distance\n d = {};\n min = 10e5;\n for (var j = 0; j < list.length; j++) {\n for (var k = j + 1; k < list.length; k++) {\n var fdistance, sdistance;\n if (list[j] instanceof ClusterLeaf) {\n fdistance = [list[j].index];\n } else {\n fdistance = new Array(list[j].index.length);\n for (var e = 0; e < fdistance.length; e++) {\n fdistance[e] = list[j].index[e].index;\n }\n }\n if (list[k] instanceof ClusterLeaf) {\n sdistance = [list[k].index];\n } else {\n sdistance = new Array(list[k].index.length);\n for (var f = 0; f < sdistance.length; f++) {\n sdistance[f] = list[k].index[f].index;\n }\n }\n dis = options.kind(fdistance, sdistance, distance).toFixed(4);\n if (dis in d) {\n d[dis].push([list[j], list[k]]);\n } else {\n d[dis] = [[list[j], list[k]]];\n }\n min = Math.min(dis, min);\n }\n }\n // cluster dots\n var dmin = d[min.toFixed(4)];\n var clustered = new Array(dmin.length);\n var aux,\n count = 0;\n while (dmin.length > 0) {\n aux = dmin.shift();\n for (var q = 0; q < dmin.length; q++) {\n var int = dmin[q].filter(function (n) {\n //noinspection JSReferencingMutableVariableFromClosure\n return aux.indexOf(n) !== -1;\n });\n if (int.length > 0) {\n var diff = dmin[q].filter(function (n) {\n //noinspection JSReferencingMutableVariableFromClosure\n return aux.indexOf(n) === -1;\n });\n aux = aux.concat(diff);\n dmin.splice(q--, 1);\n }\n }\n clustered[count++] = aux;\n }\n clustered.length = count;\n\n for (var ii = 0; ii < clustered.length; ii++) {\n var obj = new Cluster();\n obj.children = clustered[ii].concat();\n obj.distance = min;\n obj.index = new Array(len);\n var indCount = 0;\n for (var jj = 0; jj < clustered[ii].length; jj++) {\n if (clustered[ii][jj] instanceof ClusterLeaf) {\n obj.index[indCount++] = clustered[ii][jj];\n } else {\n indCount += clustered[ii][jj].index.length;\n obj.index = clustered[ii][jj].index.concat(obj.index);\n }\n list.splice((list.indexOf(clustered[ii][jj])), 1);\n }\n obj.index.length = indCount;\n list.push(obj);\n }\n }\n return list[0];\n}\n\nmodule.exports = agnes;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-hclust/src/agnes.js","module.exports = require('./lib/heap');\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/heap/index.js","// Generated by CoffeeScript 1.8.0\n(function() {\n var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;\n\n floor = Math.floor, min = Math.min;\n\n\n /*\n Default comparison function to be used\n */\n\n defaultCmp = function(x, y) {\n if (x < y) {\n return -1;\n }\n if (x > y) {\n return 1;\n }\n return 0;\n };\n\n\n /*\n Insert item x in list a, and keep it sorted assuming a is sorted.\n \n If x is already in a, insert it to the right of the rightmost x.\n \n Optional args lo (default 0) and hi (default a.length) bound the slice\n of a to be searched.\n */\n\n insort = function(a, x, lo, hi, cmp) {\n var mid;\n if (lo == null) {\n lo = 0;\n }\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (lo < 0) {\n throw new Error('lo must be non-negative');\n }\n if (hi == null) {\n hi = a.length;\n }\n while (lo < hi) {\n mid = floor((lo + hi) / 2);\n if (cmp(x, a[mid]) < 0) {\n hi = mid;\n } else {\n lo = mid + 1;\n }\n }\n return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);\n };\n\n\n /*\n Push item onto heap, maintaining the heap invariant.\n */\n\n heappush = function(array, item, cmp) {\n if (cmp == null) {\n cmp = defaultCmp;\n }\n array.push(item);\n return _siftdown(array, 0, array.length - 1, cmp);\n };\n\n\n /*\n Pop the smallest item off the heap, maintaining the heap invariant.\n */\n\n heappop = function(array, cmp) {\n var lastelt, returnitem;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n lastelt = array.pop();\n if (array.length) {\n returnitem = array[0];\n array[0] = lastelt;\n _siftup(array, 0, cmp);\n } else {\n returnitem = lastelt;\n }\n return returnitem;\n };\n\n\n /*\n Pop and return the current smallest value, and add the new item.\n \n This is more efficient than heappop() followed by heappush(), and can be\n more appropriate when using a fixed size heap. Note that the value\n returned may be larger than item! That constrains reasonable use of\n this routine unless written as part of a conditional replacement:\n if item > array[0]\n item = heapreplace(array, item)\n */\n\n heapreplace = function(array, item, cmp) {\n var returnitem;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n returnitem = array[0];\n array[0] = item;\n _siftup(array, 0, cmp);\n return returnitem;\n };\n\n\n /*\n Fast version of a heappush followed by a heappop.\n */\n\n heappushpop = function(array, item, cmp) {\n var _ref;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (array.length && cmp(array[0], item) < 0) {\n _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];\n _siftup(array, 0, cmp);\n }\n return item;\n };\n\n\n /*\n Transform list into a heap, in-place, in O(array.length) time.\n */\n\n heapify = function(array, cmp) {\n var i, _i, _j, _len, _ref, _ref1, _results, _results1;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n _ref1 = (function() {\n _results1 = [];\n for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }\n return _results1;\n }).apply(this).reverse();\n _results = [];\n for (_i = 0, _len = _ref1.length; _i < _len; _i++) {\n i = _ref1[_i];\n _results.push(_siftup(array, i, cmp));\n }\n return _results;\n };\n\n\n /*\n Update the position of the given item in the heap.\n This function should be called every time the item is being modified.\n */\n\n updateItem = function(array, item, cmp) {\n var pos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n pos = array.indexOf(item);\n if (pos === -1) {\n return;\n }\n _siftdown(array, 0, pos, cmp);\n return _siftup(array, pos, cmp);\n };\n\n\n /*\n Find the n largest elements in a dataset.\n */\n\n nlargest = function(array, n, cmp) {\n var elem, result, _i, _len, _ref;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n result = array.slice(0, n);\n if (!result.length) {\n return result;\n }\n heapify(result, cmp);\n _ref = array.slice(n);\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n heappushpop(result, elem, cmp);\n }\n return result.sort(cmp).reverse();\n };\n\n\n /*\n Find the n smallest elements in a dataset.\n */\n\n nsmallest = function(array, n, cmp) {\n var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (n * 10 <= array.length) {\n result = array.slice(0, n).sort(cmp);\n if (!result.length) {\n return result;\n }\n los = result[result.length - 1];\n _ref = array.slice(n);\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n if (cmp(elem, los) < 0) {\n insort(result, elem, 0, null, cmp);\n result.pop();\n los = result[result.length - 1];\n }\n }\n return result;\n }\n heapify(array, cmp);\n _results = [];\n for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) {\n _results.push(heappop(array, cmp));\n }\n return _results;\n };\n\n _siftdown = function(array, startpos, pos, cmp) {\n var newitem, parent, parentpos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n newitem = array[pos];\n while (pos > startpos) {\n parentpos = (pos - 1) >> 1;\n parent = array[parentpos];\n if (cmp(newitem, parent) < 0) {\n array[pos] = parent;\n pos = parentpos;\n continue;\n }\n break;\n }\n return array[pos] = newitem;\n };\n\n _siftup = function(array, pos, cmp) {\n var childpos, endpos, newitem, rightpos, startpos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n endpos = array.length;\n startpos = pos;\n newitem = array[pos];\n childpos = 2 * pos + 1;\n while (childpos < endpos) {\n rightpos = childpos + 1;\n if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {\n childpos = rightpos;\n }\n array[pos] = array[childpos];\n pos = childpos;\n childpos = 2 * pos + 1;\n }\n array[pos] = newitem;\n return _siftdown(array, startpos, pos, cmp);\n };\n\n Heap = (function() {\n Heap.push = heappush;\n\n Heap.pop = heappop;\n\n Heap.replace = heapreplace;\n\n Heap.pushpop = heappushpop;\n\n Heap.heapify = heapify;\n\n Heap.updateItem = updateItem;\n\n Heap.nlargest = nlargest;\n\n Heap.nsmallest = nsmallest;\n\n function Heap(cmp) {\n this.cmp = cmp != null ? cmp : defaultCmp;\n this.nodes = [];\n }\n\n Heap.prototype.push = function(x) {\n return heappush(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.pop = function() {\n return heappop(this.nodes, this.cmp);\n };\n\n Heap.prototype.peek = function() {\n return this.nodes[0];\n };\n\n Heap.prototype.contains = function(x) {\n return this.nodes.indexOf(x) !== -1;\n };\n\n Heap.prototype.replace = function(x) {\n return heapreplace(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.pushpop = function(x) {\n return heappushpop(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.heapify = function() {\n return heapify(this.nodes, this.cmp);\n };\n\n Heap.prototype.updateItem = function(x) {\n return updateItem(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.clear = function() {\n return this.nodes = [];\n };\n\n Heap.prototype.empty = function() {\n return this.nodes.length === 0;\n };\n\n Heap.prototype.size = function() {\n return this.nodes.length;\n };\n\n Heap.prototype.clone = function() {\n var heap;\n heap = new Heap();\n heap.nodes = this.nodes.slice(0);\n return heap;\n };\n\n Heap.prototype.toArray = function() {\n return this.nodes.slice(0);\n };\n\n Heap.prototype.insert = Heap.prototype.push;\n\n Heap.prototype.top = Heap.prototype.peek;\n\n Heap.prototype.front = Heap.prototype.peek;\n\n Heap.prototype.has = Heap.prototype.contains;\n\n Heap.prototype.copy = Heap.prototype.clone;\n\n return Heap;\n\n })();\n\n (function(root, factory) {\n if (typeof define === 'function' && define.amd) {\n return define([], factory);\n } else if (typeof exports === 'object') {\n return module.exports = factory();\n } else {\n return root.Heap = factory();\n }\n })(this, function() {\n return Heap;\n });\n\n}).call(this);\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/heap/lib/heap.js","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n if (!isString(f)) {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j':\n try {\n return JSON.stringify(args[i++]);\n } catch (_) {\n return '[Circular]';\n }\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (isNull(x) || !isObject(x)) {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexports.deprecate = function(fn, msg) {\n // Allow for deprecating things in the process of starting up.\n if (isUndefined(global.process)) {\n return function() {\n return exports.deprecate(fn, msg).apply(this, arguments);\n };\n }\n\n if (process.noDeprecation === true) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnviron;\nexports.debuglog = function(set) {\n if (isUndefined(debugEnviron))\n debugEnviron = process.env.NODE_DEBUG || '';\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (new RegExp('\\\\b' + set + '\\\\b', 'i').test(debugEnviron)) {\n var pid = process.pid;\n debugs[set] = function() {\n var msg = exports.format.apply(exports, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nfunction inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (isBoolean(opts)) {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n exports._extend(ctx, opts);\n }\n // set default options\n if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n if (isUndefined(ctx.depth)) ctx.depth = 2;\n if (isUndefined(ctx.colors)) ctx.colors = false;\n if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\nexports.inspect = inspect;\n\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect &&\n value &&\n isFunction(value.inspect) &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== exports.inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n var ret = value.inspect(recurseTimes, ctx);\n if (!isString(ret)) {\n ret = formatValue(ctx, ret, recurseTimes);\n }\n return ret;\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // IE doesn't make error fields non-enumerable\n // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n if (isError(value)\n && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n return formatError(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (isFunction(value)) {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (isFunction(value)) {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n if (isUndefined(value))\n return ctx.stylize('undefined', 'undefined');\n if (isString(value)) {\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n }\n if (isNumber(value))\n return ctx.stylize('' + value, 'number');\n if (isBoolean(value))\n return ctx.stylize('' + value, 'boolean');\n // For some reason typeof null is \"object\", so special case here.\n if (isNull(value))\n return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (isNull(recurseTimes)) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (isUndefined(name)) {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nfunction isArray(ar) {\n return Array.isArray(ar);\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return isObject(re) && objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return isObject(d) && objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return isObject(e) &&\n (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('./support/isBuffer');\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexports.log = function() {\n console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexports.inherits = require('inherits');\n\nexports._extend = function(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || !isObject(add)) return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/util/util.js","var g;\r\n\r\n// This works in non-strict mode\r\ng = (function() {\r\n\treturn this;\r\n})();\r\n\r\ntry {\r\n\t// This works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\r\n} catch(e) {\r\n\t// This works if the window reference is available\r\n\tif(typeof window === \"object\")\r\n\t\tg = window;\r\n}\r\n\r\n// g can still be undefined, but nothing to do about it...\r\n// We return undefined, instead of nothing here, so it's\r\n// easier to handle this case. if(!global) { ...}\r\n\r\nmodule.exports = g;\r\n\n\n\n// WEBPACK FOOTER //\n// (webpack)/buildin/global.js","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/process/browser.js","module.exports = function isBuffer(arg) {\n return arg && typeof arg === 'object'\n && typeof arg.copy === 'function'\n && typeof arg.fill === 'function'\n && typeof arg.readUInt8 === 'function';\n}\n\n\n// WEBPACK FOOTER //\n// ./node_modules/util/support/isBufferBrowser.js","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/inherits/inherits_browser.js","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\nconst ClusterLeaf = require('./ClusterLeaf');\nconst Cluster = require('./Cluster');\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction simpleLink(cluster1, cluster2, disFun) {\n var m = 10e100;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = i; j < cluster2.length; j++) {\n var d = disFun(cluster1[i], cluster2[j]);\n m = Math.min(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction completeLink(cluster1, cluster2, disFun) {\n var m = -1;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = i; j < cluster2.length; j++) {\n var d = disFun(cluster1[i], cluster2[j]);\n m = Math.max(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction averageLink(cluster1, cluster2, disFun) {\n var m = 0;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n m += disFun(cluster1[i], cluster2[j]);\n }\n }\n return m / (cluster1.length * cluster2.length);\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction centroidLink(cluster1, cluster2, disFun) {\n var x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0;\n for (var i = 0; i < cluster1.length; i++) {\n x1 += cluster1[i][0];\n y1 += cluster1[i][1];\n }\n for (var j = 0; j < cluster2.length; j++) {\n x2 += cluster2[j][0];\n y2 += cluster2[j][1];\n }\n x1 /= cluster1.length;\n y1 /= cluster1.length;\n x2 /= cluster2.length;\n y2 /= cluster2.length;\n return disFun([x1, y1], [x2, y2]);\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction wardLink(cluster1, cluster2, disFun) {\n var x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0;\n for (var i = 0; i < cluster1.length; i++) {\n x1 += cluster1[i][0];\n y1 += cluster1[i][1];\n }\n for (var j = 0; j < cluster2.length; j++) {\n x2 += cluster2[j][0];\n y2 += cluster2[j][1];\n }\n x1 /= cluster1.length;\n y1 /= cluster1.length;\n x2 /= cluster2.length;\n y2 /= cluster2.length;\n return disFun([x1, y1], [x2, y2]) * cluster1.length * cluster2.length / (cluster1.length + cluster2.length);\n}\n\n/**\n * @private\n * Returns the most distant point and his distance\n * @param {Array >} splitting - Clusters to split\n * @param {Array >} data - Original data\n * @param {function} disFun - Distance function\n * @returns {{d: number, p: number}} - d: maximum difference between points, p: the point more distant\n */\nfunction diff(splitting, data, disFun) {\n var ans = {\n d: 0,\n p: 0\n };\n\n var Ci = new Array(splitting[0].length);\n for (var e = 0; e < splitting[0].length; e++) {\n Ci[e] = data[splitting[0][e]];\n }\n var Cj = new Array(splitting[1].length);\n for (var f = 0; f < splitting[1].length; f++) {\n Cj[f] = data[splitting[1][f]];\n }\n\n var dist, ndist;\n for (var i = 0; i < Ci.length; i++) {\n dist = 0;\n for (var j = 0; j < Ci.length; j++) {\n if (i !== j) {\n dist += disFun(Ci[i], Ci[j]);\n }\n }\n dist /= (Ci.length - 1);\n ndist = 0;\n for (var k = 0; k < Cj.length; k++) {\n ndist += disFun(Ci[i], Cj[k]);\n }\n ndist /= Cj.length;\n if ((dist - ndist) > ans.d) {\n ans.d = (dist - ndist);\n ans.p = i;\n }\n }\n return ans;\n}\n\nvar defaultOptions = {\n dist: euclidean,\n kind: 'single'\n};\n\n/**\n * @private\n * Intra-cluster distance\n * @param {Array} index\n * @param {Array} data\n * @param {function} disFun\n * @returns {number}\n */\nfunction intrDist(index, data, disFun) {\n var dist = 0,\n count = 0;\n for (var i = 0; i < index.length; i++) {\n for (var j = i; j < index.length; j++) {\n dist += disFun(data[index[i].index], data[index[j].index]);\n count++;\n }\n }\n return dist / count;\n}\n\n/**\n * Splits the higher level clusters\n * @param {Array >} data - Array of points to be clustered\n * @param {json} options\n * @constructor\n */\nfunction diana(data, options) {\n options = Object.assign({}, defaultOptions, options);\n if (typeof options.kind === 'string') {\n switch (options.kind) {\n case 'single':\n options.kind = simpleLink;\n break;\n case 'complete':\n options.kind = completeLink;\n break;\n case 'average':\n options.kind = averageLink;\n break;\n case 'centroid':\n options.kind = centroidLink;\n break;\n case 'ward':\n options.kind = wardLink;\n break;\n default:\n throw new RangeError('Unknown kind of similarity');\n }\n } else if (typeof options.kind !== 'function') {\n throw new TypeError('Undefined kind of similarity');\n }\n var tree = new Cluster();\n tree.children = new Array(data.length);\n tree.index = new Array(data.length);\n for (var ind = 0; ind < data.length; ind++) {\n tree.children[ind] = new ClusterLeaf(ind);\n tree.index[ind] = new ClusterLeaf(ind);\n }\n\n tree.distance = intrDist(tree.index, data, options.dist);\n var m, M, clId,\n dist, rebel;\n var list = [tree];\n while (list.length > 0) {\n M = 0;\n clId = 0;\n for (var i = 0; i < list.length; i++) {\n m = 0;\n for (var j = 0; j < list[i].length; j++) {\n for (var l = (j + 1); l < list[i].length; l++) {\n m = Math.max(options.dist(data[list[i].index[j].index], data[list[i].index[l].index]), m);\n }\n }\n if (m > M) {\n M = m;\n clId = i;\n }\n }\n M = 0;\n if (list[clId].index.length === 2) {\n list[clId].children = [list[clId].index[0], list[clId].index[1]];\n list[clId].distance = options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]);\n } else if (list[clId].index.length === 3) {\n list[clId].children = [list[clId].index[0], list[clId].index[1], list[clId].index[2]];\n var d = [\n options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]),\n options.dist(data[list[clId].index[1].index], data[list[clId].index[2].index])\n ];\n list[clId].distance = (d[0] + d[1]) / 2;\n } else {\n var C = new Cluster();\n var sG = new Cluster();\n var splitting = [new Array(list[clId].index.length), []];\n for (var spl = 0; spl < splitting[0].length; spl++) {\n splitting[0][spl] = spl;\n }\n for (var ii = 0; ii < splitting[0].length; ii++) {\n dist = 0;\n for (var jj = 0; jj < splitting[0].length; jj++) {\n if (ii !== jj) {\n dist += options.dist(data[list[clId].index[splitting[0][jj]].index], data[list[clId].index[splitting[0][ii]].index]);\n }\n }\n dist /= (splitting[0].length - 1);\n if (dist > M) {\n M = dist;\n rebel = ii;\n }\n }\n splitting[1] = [rebel];\n splitting[0].splice(rebel, 1);\n dist = diff(splitting, data, options.dist);\n while (dist.d > 0) {\n splitting[1].push(splitting[0][dist.p]);\n splitting[0].splice(dist.p, 1);\n dist = diff(splitting, data, options.dist);\n }\n var fData = new Array(splitting[0].length);\n C.index = new Array(splitting[0].length);\n for (var e = 0; e < fData.length; e++) {\n fData[e] = data[list[clId].index[splitting[0][e]].index];\n C.index[e] = list[clId].index[splitting[0][e]];\n C.children[e] = list[clId].index[splitting[0][e]];\n }\n var sData = new Array(splitting[1].length);\n sG.index = new Array(splitting[1].length);\n for (var f = 0; f < sData.length; f++) {\n sData[f] = data[list[clId].index[splitting[1][f]].index];\n sG.index[f] = list[clId].index[splitting[1][f]];\n sG.children[f] = list[clId].index[splitting[1][f]];\n }\n C.distance = intrDist(C.index, data, options.dist);\n sG.distance = intrDist(sG.index, data, options.dist);\n list.push(C);\n list.push(sG);\n list[clId].children = [C, sG];\n }\n list.splice(clId, 1);\n }\n return tree;\n}\n\nmodule.exports = diana;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-hclust/src/diana.js","import euclidean from 'ml-distance-euclidean';\n\nimport {\n updateClusterID,\n updateCenters,\n hasConverged,\n calculateDistanceMatrix\n} from './utils';\nimport { mostDistant, random, kmeanspp } from './initialization';\nimport KMeansResult from './KMeansResult';\n\nconst defaultOptions = {\n maxIterations: 100,\n tolerance: 1e-6,\n withIterations: false,\n initialization: 'kmeans++',\n distanceFunction: euclidean.squared\n};\n\n/**\n * Each step operation for kmeans\n * @ignore\n * @param {Array>} centers - K centers in format [x,y,z,...]\n * @param {Array>} data - Points [x,y,z,...] to cluster\n * @param {Array} clusterID - Cluster identifier for each data dot\n * @param {number} K - Number of clusters\n * @param {object} [options] - Option object\n * @param {number} iterations - Current number of iterations\n * @return {KMeansResult}\n */\nfunction step(centers, data, clusterID, K, options, iterations) {\n clusterID = updateClusterID(\n data,\n centers,\n clusterID,\n options.distanceFunction\n );\n var newCenters = updateCenters(centers, data, clusterID, K);\n var converged = hasConverged(\n newCenters,\n centers,\n options.distanceFunction,\n options.tolerance\n );\n return new KMeansResult(\n clusterID,\n newCenters,\n converged,\n iterations,\n options.distanceFunction\n );\n}\n\n/**\n * Generator version for the algorithm\n * @ignore\n * @param {Array>} centers - K centers in format [x,y,z,...]\n * @param {Array>} data - Points [x,y,z,...] to cluster\n * @param {Array} clusterID - Cluster identifier for each data dot\n * @param {number} K - Number of clusters\n * @param {object} [options] - Option object\n */\nfunction* kmeansGenerator(centers, data, clusterID, K, options) {\n var converged = false;\n var stepNumber = 0;\n var stepResult;\n while (!converged && stepNumber < options.maxIterations) {\n stepResult = step(centers, data, clusterID, K, options, ++stepNumber);\n yield stepResult.computeInformation(data);\n converged = stepResult.converged;\n centers = stepResult.centroids;\n }\n}\n\n/**\n * K-means algorithm\n * @param {Array>} data - Points in the format to cluster [x,y,z,...]\n * @param {number} K - Number of clusters\n * @param {object} [options] - Option object\n * @param {number} [options.maxIterations = 100] - Maximum of iterations allowed\n * @param {number} [options.tolerance = 1e-6] - Error tolerance\n * @param {boolean} [options.withIterations = false] - Store clusters and centroids for each iteration\n * @param {function} [options.distanceFunction = squaredDistance] - Distance function to use between the points\n * @param {number} [options.seed] - Seed for random initialization.\n * @param {string|Array>} [options.initialization = 'kmeans++'] - K centers in format [x,y,z,...] or a method for initialize the data:\n * * You can either specify your custom start centroids, or select one of the following initialization method:\n * * `'kmeans++'` will use the kmeans++ method as described by http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf\n * * `'random'` will choose K random different values.\n * * `'mostDistant'` will choose the more distant points to a first random pick\n * @return {KMeansResult} - Cluster identifier for each data dot and centroids with the following fields:\n * * `'clusters'`: Array of indexes for the clusters.\n * * `'centroids'`: Array with the resulting centroids.\n * * `'iterations'`: Number of iterations that took to converge\n */\nexport default function kmeans(data, K, options) {\n options = Object.assign({}, defaultOptions, options);\n\n if (K <= 0 || K > data.length || !Number.isInteger(K)) {\n throw new Error(\n 'K should be a positive integer smaller than the number of points'\n );\n }\n\n var centers;\n if (Array.isArray(options.initialization)) {\n if (options.initialization.length !== K) {\n throw new Error('The initial centers should have the same length as K');\n } else {\n centers = options.initialization;\n }\n } else {\n switch (options.initialization) {\n case 'kmeans++':\n centers = kmeanspp(data, K, options);\n break;\n case 'random':\n centers = random(data, K, options.seed);\n break;\n case 'mostDistant':\n centers = mostDistant(\n data,\n K,\n calculateDistanceMatrix(data, options.distanceFunction),\n options.seed\n );\n break;\n default:\n throw new Error(\n `Unknown initialization method: \"${options.initialization}\"`\n );\n }\n }\n\n // infinite loop until convergence\n if (options.maxIterations === 0) {\n options.maxIterations = Number.MAX_VALUE;\n }\n\n var clusterID = new Array(data.length);\n if (options.withIterations) {\n return kmeansGenerator(centers, data, clusterID, K, options);\n } else {\n var converged = false;\n var stepNumber = 0;\n var stepResult;\n while (!converged && stepNumber < options.maxIterations) {\n stepResult = step(centers, data, clusterID, K, options, ++stepNumber);\n converged = stepResult.converged;\n centers = stepResult.centroids;\n }\n return stepResult.computeInformation(data);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kmeans/src/kmeans.js","'use strict';\n\nconst squaredDistance = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n distanceFunction: squaredDistance,\n similarityFunction: false,\n returnVector: false\n};\n\n/**\n * Find the nearest vector in a list to a sample vector\n * @param {Array>} listVectors - List of vectors with same dimensions\n * @param {Array} vector - Reference vector to \"classify\"\n * @param {object} [options] - Options object\n * @param {function} [options.distanceFunction = squaredDistance] - Function that receives two vectors and return their distance value as number\n * @param {function} [options.similarityFunction = undefined] - Function that receives two vectors and return their similarity value as number\n * @param {boolean} [options.returnVector = false] - Return the nearest vector instead of its index\n * @return {number|Array} - The index or the content of the nearest vector\n */\nfunction nearestVector(listVectors, vector, options) {\n options = options || defaultOptions;\n const distanceFunction = options.distanceFunction || defaultOptions.distanceFunction;\n const similarityFunction = options.similarityFunction || defaultOptions.similarityFunction;\n const returnVector = options.returnVector || defaultOptions.returnVector;\n\n var vectorIndex = -1;\n if (typeof similarityFunction === 'function') {\n\n // maximum similarity\n var maxSim = Number.MIN_VALUE;\n for (var j = 0; j < listVectors.length; j++) {\n var sim = similarityFunction(vector, listVectors[j]);\n if (sim > maxSim) {\n maxSim = sim;\n vectorIndex = j;\n }\n }\n } else if (typeof distanceFunction === 'function') {\n\n // minimum distance\n var minDist = Number.MAX_VALUE;\n for (var i = 0; i < listVectors.length; i++) {\n var dist = distanceFunction(vector, listVectors[i]);\n if (dist < minDist) {\n minDist = dist;\n vectorIndex = i;\n }\n }\n } else {\n throw new Error('A similarity or distance function it\\'s required');\n }\n\n if (returnVector) {\n return listVectors[vectorIndex];\n } else {\n return vectorIndex;\n }\n}\n\nmodule.exports = nearestVector;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-nearest-vector/src/index.js","import Random from 'ml-random';\nimport { squared as squaredEuclidean } from 'ml-distance-euclidean';\nimport { Matrix } from 'ml-matrix';\n\n/**\n * Choose K different random points from the original data\n * @ignore\n * @param {Array>} data - Points in the format to cluster [x,y,z,...]\n * @param {number} K - number of clusters\n * @param {number} seed - seed for random number generation\n * @return {Array>} - Initial random points\n */\nexport function random(data, K, seed) {\n const random = new Random(seed);\n return random.choice(data, { size: K });\n}\n\n/**\n * Chooses the most distant points to a first random pick\n * @ignore\n * @param {Array>} data - Points in the format to cluster [x,y,z,...]\n * @param {number} K - number of clusters\n * @param {Array>} distanceMatrix - matrix with the distance values\n * @param {number} seed - seed for random number generation\n * @return {Array>} - Initial random points\n */\nexport function mostDistant(data, K, distanceMatrix, seed) {\n const random = new Random(seed);\n var ans = new Array(K);\n // chooses a random point as initial cluster\n ans[0] = Math.floor(random.random() * data.length);\n\n if (K > 1) {\n // chooses the more distant point\n var maxDist = { dist: -1, index: -1 };\n for (var l = 0; l < data.length; ++l) {\n if (distanceMatrix[ans[0]][l] > maxDist.dist) {\n maxDist.dist = distanceMatrix[ans[0]][l];\n maxDist.index = l;\n }\n }\n ans[1] = maxDist.index;\n\n if (K > 2) {\n // chooses the set of points that maximises the min distance\n for (var k = 2; k < K; ++k) {\n var center = { dist: -1, index: -1 };\n for (var m = 0; m < data.length; ++m) {\n // minimum distance to centers\n var minDistCent = { dist: Number.MAX_VALUE, index: -1 };\n for (var n = 0; n < k; ++n) {\n if (\n distanceMatrix[n][m] < minDistCent.dist &&\n ans.indexOf(m) === -1\n ) {\n minDistCent = {\n dist: distanceMatrix[n][m],\n index: m\n };\n }\n }\n\n if (\n minDistCent.dist !== Number.MAX_VALUE &&\n minDistCent.dist > center.dist\n ) {\n center = Object.assign({}, minDistCent);\n }\n }\n\n ans[k] = center.index;\n }\n }\n }\n\n return ans.map((index) => data[index]);\n}\n\n// Implementation inspired from scikit\nexport function kmeanspp(X, K, options = {}) {\n X = new Matrix(X);\n const nSamples = X.length;\n const random = new Random(options.seed);\n // Set the number of trials\n const centers = [];\n const localTrials = options.localTrials || 2 + Math.floor(Math.log(K));\n\n // Pick the first center at random from the dataset\n const firstCenterIdx = random.randInt(nSamples);\n centers.push(X[firstCenterIdx].slice());\n\n // Init closest distances\n let closestDistSquared = [X.map((x) => squaredEuclidean(x, centers[0]))];\n let cumSumClosestDistSquared = [cumSum(closestDistSquared[0])];\n const factor = 1 / cumSumClosestDistSquared[0][nSamples - 1];\n let probabilities = Matrix.mul(closestDistSquared, factor);\n\n // Iterate over the remaining centers\n for (let i = 1; i < K; i++) {\n const candidateIdx = random.choice(nSamples, {\n replace: true,\n size: localTrials,\n probabilities: probabilities[0]\n });\n\n const candidates = X.selection(candidateIdx, range(X[0].length));\n const distanceToCandidates = euclidianDistances(candidates, X);\n\n let bestCandidate;\n let bestPot;\n let bestDistSquared;\n\n for (let j = 0; j < localTrials; j++) {\n const newDistSquared = Matrix.min(closestDistSquared, [distanceToCandidates[j]]);\n const newPot = newDistSquared.sum();\n if (bestCandidate === undefined || newPot < bestPot) {\n bestCandidate = candidateIdx[j];\n bestPot = newPot;\n bestDistSquared = newDistSquared;\n }\n }\n centers[i] = X[bestCandidate].slice();\n closestDistSquared = bestDistSquared;\n cumSumClosestDistSquared = [cumSum(closestDistSquared[0])];\n probabilities = Matrix.mul(\n closestDistSquared,\n 1 / cumSumClosestDistSquared[0][nSamples - 1]\n );\n }\n return centers;\n}\n\nfunction euclidianDistances(A, B) {\n const result = new Matrix(A.length, B.length);\n for (let i = 0; i < A.length; i++) {\n for (let j = 0; j < B.length; j++) {\n result.set(i, j, squaredEuclidean(A.getRow(i), B.getRow(j)));\n }\n }\n return result;\n}\n\nfunction range(l) {\n let r = [];\n for (let i = 0; i < l; i++) {\n r.push(i);\n }\n return r;\n}\n\nfunction cumSum(arr) {\n let cumSum = [arr[0]];\n for (let i = 1; i < arr.length; i++) {\n cumSum[i] = cumSum[i - 1] + arr[i];\n }\n return cumSum;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kmeans/src/initialization.js","const PROB_TOLERANCE = 0.00000001;\nfunction randomChoice(values, options = {}, random = Math.random) {\n const { size = 1, replace = false, probabilities } = options;\n let valuesArr;\n let cumSum;\n if (typeof values === 'number') {\n valuesArr = getArray(values);\n }\n else {\n valuesArr = values.slice();\n }\n if (probabilities) {\n if (!replace) {\n throw new Error('choice with probabilities and no replacement is not implemented');\n }\n // check input is sane\n if (probabilities.length !== valuesArr.length) {\n throw new Error('the length of probabilities option should be equal to the number of choices');\n }\n cumSum = [probabilities[0]];\n for (let i = 1; i < probabilities.length; i++) {\n cumSum[i] = cumSum[i - 1] + probabilities[i];\n }\n if (Math.abs(1 - cumSum[cumSum.length - 1]) > PROB_TOLERANCE) {\n throw new Error(`probabilities should sum to 1, but instead sums to ${cumSum[cumSum.length - 1]}`);\n }\n }\n if (replace === false && size > valuesArr.length) {\n throw new Error('size option is too large');\n }\n const result = [];\n for (let i = 0; i < size; i++) {\n const index = randomIndex(valuesArr.length, random, cumSum);\n result.push(valuesArr[index]);\n if (!replace) {\n valuesArr.splice(index, 1);\n }\n }\n return result;\n}\nfunction getArray(n) {\n const arr = [];\n for (let i = 0; i < n; i++) {\n arr.push(i);\n }\n return arr;\n}\nfunction randomIndex(n, random, cumSum) {\n const rand = random();\n if (!cumSum) {\n return Math.floor(rand * n);\n }\n else {\n let idx = 0;\n while (rand > cumSum[idx]) {\n idx++;\n }\n return idx;\n }\n}\nexport default randomChoice;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-random/lib-es6/choice.js","import { updateClusterID } from './utils';\n\nconst distanceSymbol = Symbol('distance');\n\nexport default class KMeansResult {\n /**\n * Result of the kmeans algorithm\n * @param {Array} clusters - the cluster identifier for each data dot\n * @param {Array>} centroids - the K centers in format [x,y,z,...], the error and size of the cluster\n * @param {boolean} converged - Converge criteria satisfied\n * @param {number} iterations - Current number of iterations\n * @param {function} distance - (*Private*) Distance function to use between the points\n * @constructor\n */\n constructor(clusters, centroids, converged, iterations, distance) {\n this.clusters = clusters;\n this.centroids = centroids;\n this.converged = converged;\n this.iterations = iterations;\n this[distanceSymbol] = distance;\n }\n\n /**\n * Allows to compute for a new array of points their cluster id\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @return {Array} - cluster id for each point\n */\n nearest(data) {\n const clusterID = new Array(data.length);\n const centroids = this.centroids.map(function (centroid) {\n return centroid.centroid;\n });\n return updateClusterID(data, centroids, clusterID, this[distanceSymbol]);\n }\n\n /**\n * Returns a KMeansResult with the error and size of the cluster\n * @ignore\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @return {KMeansResult}\n */\n computeInformation(data) {\n var enrichedCentroids = this.centroids.map(function (centroid) {\n return {\n centroid: centroid,\n error: 0,\n size: 0\n };\n });\n\n for (var i = 0; i < data.length; i++) {\n enrichedCentroids[this.clusters[i]].error += this[distanceSymbol](\n data[i],\n this.centroids[this.clusters[i]]\n );\n enrichedCentroids[this.clusters[i]].size++;\n }\n\n for (var j = 0; j < this.centroids.length; j++) {\n if (enrichedCentroids[j].size) {\n enrichedCentroids[j].error /= enrichedCentroids[j].size;\n } else {\n enrichedCentroids[j].error = null;\n }\n }\n\n return new KMeansResult(\n this.clusters,\n enrichedCentroids,\n this.converged,\n this.iterations,\n this[distanceSymbol]\n );\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kmeans/src/KMeansResult.js","'use strict';\nconst Kernel = require('ml-kernel');\nconst stat = require('ml-stat').array;\n\nvar defaultOptions = {\n C: 1,\n tol: 1e-4,\n maxPasses: 10,\n maxIterations: 10000,\n kernel: 'linear',\n alphaTol: 1e-6,\n random: Math.random,\n whitening: true\n};\n\n/**\n * Simplified version of the Sequential Minimal Optimization algorithm for training\n * support vector machines\n * @param {{Object}} options - SVM options\n * @param {Number} [options.C=1] - regularization parameter\n * @param {Number} [options.tol=1e-4] - numerical tolerance\n * @param {Number} [options.alphaTol=1e-6] - alpha tolerance, threshold to decide support vectors\n * @param {Number} [options.maxPasses=10] - max number of times to iterate over alphas without changing\n * @param {Number} [options.maxIterations=10000] - max number of iterations\n * @param {String} [options.kernel=linear] - the kind of kernel. {@link https://github.com/mljs/kernel/tree/1252de5f9012776e6e0eb06c7b434b8631fb21f0 List of kernels}\n * @param {Function} [options.random=Math.random] - custom random number generator\n * @constructor\n */\nfunction SVM(options) {\n this.options = Object.assign({}, defaultOptions, options);\n\n this.kernel = new Kernel(this.options.kernel, this.options.kernelOptions);\n this.b = 0;\n}\n\n/**\n * Train the SVM model\n * @param {Array >} features - training data features\n * @param {Array } labels - training data labels in the domain {1,-1}\n */\nSVM.prototype.train = function (features, labels) {\n if (features.length !== labels.length) {\n throw new Error('Features and labels should have the same length');\n }\n if (features.length < 2) {\n throw new Error('Cannot train with less than 2 observations');\n }\n this._trained = false;\n this._loaded = false;\n this.N = labels.length;\n this.D = features[0].length;\n if (this.options.whitening) {\n this.X = new Array(this.N);\n for (var i = 0; i < this.N; i++) {\n this.X[i] = new Array(this.D);\n }\n this.minMax = new Array(this.D);\n // Apply normalization and keep normalization parameters\n for (var j = 0; j < this.D; j++) {\n var d = new Array(this.N);\n for (i = 0; i < this.N; i++) {\n d[i] = features[i][j];\n }\n this.minMax[j] = stat.minMax(d);\n for (i = 0; i < this.N; i++) {\n this.X[i][j] = (features[i][j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min);\n }\n }\n } else {\n this.X = features;\n }\n this.Y = labels;\n this.b = 0;\n this.W = undefined;\n\n var kernel = this.kernel.compute(this.X);\n var m = labels.length;\n var alpha = new Array(m).fill(0);\n this.alphas = alpha;\n for (var a = 0; a < m; a++)\n alpha[a] = 0;\n\n var b1 = 0,\n b2 = 0,\n iter = 0,\n passes = 0,\n Ei = 0,\n Ej = 0,\n ai = 0,\n aj = 0,\n L = 0,\n H = 0,\n eta = 0;\n\n while (passes < this.options.maxPasses && iter < this.options.maxIterations) {\n var numChange = 0;\n for (i = 0; i < m; i++) {\n Ei = this._marginOnePrecomputed(i, kernel) - labels[i];\n if (labels[i] * Ei < -this.options.tol && alpha[i] < this.options.C || labels[i] * Ei > this.options.tol && alpha[i] > 0) {\n j = i;\n while (j === i) j = Math.floor(this.options.random() * m);\n Ej = this._marginOnePrecomputed(j, kernel) - labels[j];\n ai = alpha[i];\n aj = alpha[j];\n if (labels[i] === labels[j]) {\n L = Math.max(0, ai + aj - this.options.C);\n H = Math.min(this.options.C, ai + aj);\n } else {\n L = Math.max(0, aj - ai);\n H = Math.min(this.options.C, this.options.C + aj + ai);\n }\n if (Math.abs(L - H) < 1e-4) continue;\n\n eta = 2 * kernel[i][j] - kernel[i][i] - kernel[j][j];\n if (eta >= 0) continue;\n var newaj = alpha[j] - labels[j] * (Ei - Ej) / eta;\n if (newaj > H)\n newaj = H;\n else if (newaj < L)\n newaj = L;\n if (Math.abs(aj - newaj) < 10e-4) continue;\n alpha[j] = newaj;\n alpha[i] = alpha[i] + labels[i] * labels[j] * (aj - newaj);\n b1 = this.b - Ei - labels[i] * (alpha[i] - ai) * kernel[i][i] - labels[j] * (alpha[j] - aj) * kernel[i][j];\n b2 = this.b - Ej - labels[i] * (alpha[i] - ai) * kernel[i][j] - labels[j] * (alpha[j] - aj) * kernel[j][j];\n this.b = (b1 + b2) / 2;\n if (alpha[i] < this.options.C && alpha[i] > 0) this.b = b1;\n if (alpha[j] < this.options.C && alpha[j] > 0) this.b = b2;\n numChange += 1;\n }\n }\n iter++;\n if (numChange === 0)\n passes += 1;\n else\n passes = 0;\n }\n if (iter === this.options.maxIterations) {\n throw new Error('max iterations reached');\n }\n\n this.iterations = iter;\n\n // Compute the weights (useful for fast decision on new test instances when linear SVM)\n if (this.options.kernel === 'linear') {\n this.W = new Array(this.D);\n for (var r = 0; r < this.D; r++) {\n this.W[r] = 0;\n for (var w = 0; w < m; w++)\n this.W[r] += labels[w] * alpha[w] * this.X[w][r];\n }\n }\n\n // Keep only support vectors\n // It will compute decision on new test instances faster\n // We also keep the index of the support vectors\n // in the original data\n var nX = [];\n var nY = [];\n var nAlphas = [];\n this._supportVectorIdx = [];\n for (i = 0; i < this.N; i++) {\n if (this.alphas[i] > this.options.alphaTol) {\n nX.push(this.X[i]);\n nY.push(labels[i]);\n nAlphas.push(this.alphas[i]);\n this._supportVectorIdx.push(i);\n\n }\n }\n this.X = nX;\n this.Y = nY;\n this.N = nX.length;\n this.alphas = nAlphas;\n\n\n // A flag to say this SVM has been trained\n this._trained = true;\n};\n\n/**\n * Get prediction ({-1,1}) given one observation's features.\n * @private\n * @param p The observation's features.\n * @returns {number} Classification result ({-1,1})\n */\nSVM.prototype.predictOne = function (p) {\n var margin = this.marginOne(p);\n return margin > 0 ? 1 : -1;\n};\n\n/**\n * Predict the classification outcome of a trained svm given one or several observations' features.\n * @param {Array} features - The observation(s)' features\n * @returns {Array|Number} An array of {-1, 1} if several observations are given or a number if one observation\n * is given\n */\nSVM.prototype.predict = function (features) {\n if (!this._trained && !this._loaded) throw new Error('Cannot predict, you need to train the SVM first');\n if (Array.isArray(features) && Array.isArray(features[0])) {\n return features.map(this.predictOne.bind(this));\n } else {\n return this.predictOne(features);\n }\n};\n\n/**\n * Get margin given one observation's features\n * @private\n * @param {Array} features - Features\n * @returns {Number} - The computed margin\n */\nSVM.prototype.marginOne = function (features, noWhitening) {\n // Apply normalization\n if (this.options.whitening && !noWhitening) {\n features = this._applyWhitening(features);\n }\n var ans = this.b, i;\n if (this.options.kernel === 'linear' && this.W) {\n // Use weights, it's faster\n for (i = 0; i < this.W.length; i++) {\n ans += this.W[i] * features[i];\n }\n } else {\n for (i = 0; i < this.N; i++) {\n ans += this.alphas[i] * this.Y[i] * this.kernel.compute([features], [this.X[i]])[0][0];\n }\n }\n return ans;\n};\n\n\n/**\n * Get a margin using the precomputed kernel. Much faster than normal margin computation\n * @private\n * @param {Number} index - Train data index\n * @param {Array< Array >} kernel - The precomputed kernel\n * @returns {number} Computed margin\n * @private\n */\nSVM.prototype._marginOnePrecomputed = function (index, kernel) {\n var ans = this.b, i;\n for (i = 0; i < this.N; i++) {\n ans += this.alphas[i] * this.Y[i] * kernel[index][i];\n }\n return ans;\n};\n\n\n/**\n * Returns the margin of one or several observations given its features\n * @param {Array >|Array} features - Features from on or several observations.\n * @returns {Number|Array} The computed margin. Is an Array if several observations' features given, or a Number if\n * only one observation's features given\n */\nSVM.prototype.margin = function (features) {\n if (Array.isArray(features)) {\n return features.map(this.marginOne.bind(this));\n } else {\n return this.marginOne(features);\n }\n};\n\n/**\n * Get support vectors indexes of the trained classifier. WARINNG: this method does not work for svm instances\n * created from {@link #SVM.load load} if linear kernel\n * @returns {Array} The indices in the training vector of the support vectors\n */\nSVM.prototype.supportVectors = function () {\n if (!this._trained && !this._loaded) throw new Error('Cannot get support vectors, you need to train the SVM first');\n if (this._loaded && this.options.kernel === 'linear') throw new Error('Cannot get support vectors from saved linear model, you need to train the SVM to have them');\n return this._supportVectorIdx;\n};\n\n/**\n * Create a SVM instance from a saved model\n * @param {Object} model - Object such as returned by a trained SVM instance with {@link #SVM#toJSON toJSON}\n * @returns {SVM} Instance of svm classifier\n */\nSVM.load = function (model) {\n this._loaded = true;\n this._trained = false;\n var svm = new SVM(model.options);\n if (model.options.kernel === 'linear') {\n svm.W = model.W.slice();\n svm.D = svm.W.length;\n } else {\n svm.X = model.X.slice();\n svm.Y = model.Y.slice();\n svm.alphas = model.alphas.slice();\n svm.N = svm.X.length;\n svm.D = svm.X[0].length;\n }\n svm.minMax = model.minMax;\n svm.b = model.b;\n svm._loaded = true;\n svm._trained = false;\n return svm;\n};\n\n/**\n * Export the minimal object that enables to reload the model\n * @returns {Object} Model object that can be reused with {@link #SVM.load load}\n */\nSVM.prototype.toJSON = function () {\n if (!this._trained && !this._loaded) throw new Error('Cannot export, you need to train the SVM first');\n var model = {};\n model.options = Object.assign({}, this.options);\n model.b = this.b;\n model.minMax = this.minMax;\n if (model.options.kernel === 'linear') {\n model.W = this.W.slice();\n } else {\n // Exporting non-linear models is heavier\n model.X = this.X.slice();\n model.Y = this.Y.slice();\n model.alphas = this.alphas.slice();\n }\n return model;\n};\n\nSVM.prototype._applyWhitening = function (features) {\n if (!this.minMax) throw new Error('Could not apply whitening');\n var whitened = new Array(features.length);\n for (var j = 0; j < features.length; j++) {\n whitened[j] = (features[j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min);\n }\n return whitened;\n};\n\nmodule.exports = SVM;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-svm/src/svm.js","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass GaussianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = GaussianKernel;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kernel-gaussian/gaussian-kernel.js","'use strict';\n\nconst defaultOptions = {\n degree: 1,\n constant: 1,\n scale: 1\n};\n\nclass PolynomialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n\n this.degree = options.degree;\n this.constant = options.constant;\n this.scale = options.scale;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.pow(this.scale * sum + this.constant, this.degree);\n }\n}\n\nmodule.exports = PolynomialKernel;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kernel-polynomial/polynomial-kernel.js","'use strict';\n\nconst defaultOptions = {\n sigma: 1,\n degree: 1\n};\n\nclass ANOVAKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.degree = options.degree;\n }\n\n compute(x, y) {\n var sum = 0;\n var len = Math.min(x.length, y.length);\n for (var i = 1; i <= len; ++i) {\n sum += Math.pow(Math.exp(-this.sigma * Math.pow(Math.pow(x[i - 1], i) -\n Math.pow(y[i - 1], i), 2)), this.degree);\n }\n return sum;\n }\n}\n\nmodule.exports = ANOVAKernel;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kernel/src/kernels/anova-kernel.js","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass CauchyKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n return 1 / (1 + squaredEuclidean(x, y) / (this.sigma * this.sigma));\n }\n}\n\nmodule.exports = CauchyKernel;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kernel/src/kernels/cauchy-kernel.js","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass ExponentialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = ExponentialKernel;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kernel/src/kernels/exponential-kernel.js","'use strict';\n\nclass HistogramIntersectionKernel {\n compute(x, y) {\n var min = Math.min(x.length, y.length);\n var sum = 0;\n for (var i = 0; i < min; ++i) {\n sum += Math.min(x[i], y[i]);\n }\n\n return sum;\n }\n}\n\nmodule.exports = HistogramIntersectionKernel;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kernel/src/kernels/histogram-intersection-kernel.js","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass LaplacianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.sigma);\n }\n}\n\nmodule.exports = LaplacianKernel;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kernel/src/kernels/laplacian-kernel.js","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass MultiquadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n return Math.sqrt(squaredEuclidean(x, y) + this.constant * this.constant);\n }\n}\n\nmodule.exports = MultiquadraticKernel;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kernel/src/kernels/multiquadratic-kernel.js","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass RationalQuadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return 1 - (distance / (distance + this.constant));\n }\n}\n\nmodule.exports = RationalQuadraticKernel;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kernel/src/kernels/rational-quadratic-kernel.js","'use strict';\n\nconst defaultOptions = {\n alpha: 0.01,\n constant: -Math.E\n};\n\nclass SigmoidKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.alpha = options.alpha;\n this.constant = options.constant;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.tanh(this.alpha * sum + this.constant);\n }\n}\n\nmodule.exports = SigmoidKernel;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-kernel-sigmoid/sigmoid-kernel.js","export {GaussianNB} from './GaussianNB';\nexport {MultinomialNB} from './MultinomialNB';\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-naivebayes/src/index.js","import Matrix from 'ml-matrix';\nimport Stat from 'ml-stat';\nimport {separateClasses} from './utils';\n\n/**\n * @class GaussianNB\n */\nexport class GaussianNB {\n\n /**\n * @constructor\n * Constructor for the Gaussian Naive Bayes classifier, the parameters here is just for loading purposes.\n *\n * @param {boolean} reload\n * @param {object} model\n */\n constructor(reload, model) {\n if (reload) {\n this.means = model.means;\n this.calculateProbabilities = model.calculateProbabilities;\n }\n }\n\n /**\n * Function that trains the classifier with a matrix that represents the training set and an array that\n * represents the label of each row in the training set. the labels must be numbers between 0 to n-1 where\n * n represents the number of classes.\n *\n * WARNING: in the case that one class, all the cases in one or more features have the same value, the\n * Naive Bayes classifier will not work well.\n * @param {Matrix|Array} trainingSet\n * @param {Matrix|Array} trainingLabels\n */\n train(trainingSet, trainingLabels) {\n var C1 = Math.sqrt(2 * Math.PI); // constant to precalculate the squared root\n trainingSet = Matrix.checkMatrix(trainingSet);//if (!Matrix.isMatrix(trainingSet)) trainingSet = new Matrix(trainingSet);\n\n if (trainingSet.rows !== trainingLabels.length) {\n throw new RangeError('the size of the training set and the training labels must be the same.');\n }\n\n var separatedClasses = separateClasses(trainingSet, trainingLabels);\n var calculateProbabilities = new Array(separatedClasses.length);\n this.means = new Array(separatedClasses.length);\n for (var i = 0; i < separatedClasses.length; ++i) {\n var means = Stat.matrix.mean(separatedClasses[i]);\n var std = Stat.matrix.standardDeviation(separatedClasses[i], means);\n\n var logPriorProbability = Math.log(separatedClasses[i].rows / trainingSet.rows);\n calculateProbabilities[i] = new Array(means.length + 1);\n\n calculateProbabilities[i][0] = logPriorProbability;\n for (var j = 1; j < means.length + 1; ++j) {\n var currentStd = std[j - 1];\n calculateProbabilities[i][j] = [(1 / (C1 * currentStd)), -2 * currentStd * currentStd];\n }\n\n this.means[i] = means;\n }\n\n this.calculateProbabilities = calculateProbabilities;\n }\n\n /**\n * function that predicts each row of the dataset (must be a matrix).\n *\n * @param {Matrix|Array} dataset\n * @return {Array}\n */\n predict(dataset) {\n if (dataset[0].length === this.calculateProbabilities[0].length) {\n throw new RangeError('the dataset must have the same features as the training set');\n }\n\n var predictions = new Array(dataset.length);\n\n for (var i = 0; i < predictions.length; ++i) {\n predictions[i] = getCurrentClass(dataset[i], this.means, this.calculateProbabilities);\n }\n\n return predictions;\n }\n\n /**\n * Function that export the NaiveBayes model.\n * @return {object}\n */\n toJSON() {\n return {\n modelName: 'NaiveBayes',\n means: this.means,\n calculateProbabilities: this.calculateProbabilities\n };\n }\n\n /**\n * Function that create a GaussianNB classifier with the given model.\n * @param {object} model\n * @return {GaussianNB}\n */\n static load(model) {\n if (model.modelName !== 'NaiveBayes') {\n throw new RangeError('The current model is not a Multinomial Naive Bayes, current model:', model.name);\n }\n\n return new GaussianNB(true, model);\n }\n}\n\n/**\n * @private\n * Function the retrieves a prediction with one case.\n *\n * @param {Array} currentCase\n * @param {Array} mean - Precalculated means of each class trained\n * @param {Array} classes - Precalculated value of each class (Prior probability and probability function of each feature)\n * @return {number}\n */\nfunction getCurrentClass(currentCase, mean, classes) {\n var maxProbability = 0;\n var predictedClass = -1;\n\n // going through all precalculated values for the classes\n for (var i = 0; i < classes.length; ++i) {\n var currentProbability = classes[i][0]; // initialize with the prior probability\n for (var j = 1; j < classes[0][1].length + 1; ++j) {\n currentProbability += calculateLogProbability(currentCase[j - 1], mean[i][j - 1], classes[i][j][0], classes[i][j][1]);\n }\n\n currentProbability = Math.exp(currentProbability);\n if (currentProbability > maxProbability) {\n maxProbability = currentProbability;\n predictedClass = i;\n }\n }\n\n return predictedClass;\n}\n\n/**\n * @private\n * function that retrieves the probability of the feature given the class.\n * @param {number} value - value of the feature.\n * @param {number} mean - mean of the feature for the given class.\n * @param {number} C1 - precalculated value of (1 / (sqrt(2*pi) * std)).\n * @param {number} C2 - precalculated value of (2 * std^2) for the denominator of the exponential.\n * @return {number}\n */\nfunction calculateLogProbability(value, mean, C1, C2) {\n value = value - mean;\n return Math.log(C1 * Math.exp((value * value) / C2));\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-naivebayes/src/GaussianNB.js","import Matrix from 'ml-matrix';\nimport {separateClasses} from './utils';\n\n/**\n * @class MultinomialNB\n */\nexport class MultinomialNB {\n\n /**\n * @constructor\n * Constructor for Multinomial Naive Bayes, the model parameter is for load purposes.\n *\n * @param {object} model - for load purposes.\n */\n constructor(model) {\n if (model) {\n this.conditionalProbability = Matrix.checkMatrix(model.conditionalProbability);\n this.priorProbability = Matrix.checkMatrix(model.priorProbability);\n }\n }\n\n /**\n * Train the classifier with the current training set and labels, the labels must be numbers between 0 and n.\n * @param {Matrix|Array} trainingSet\n * @param {Array} trainingLabels\n */\n train(trainingSet, trainingLabels) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n\n if (trainingSet.rows !== trainingLabels.length) {\n throw new RangeError('the size of the training set and the training labels must be the same.');\n }\n\n var separateClass = separateClasses(trainingSet, trainingLabels);\n this.priorProbability = new Matrix(separateClass.length, 1);\n\n for (var i = 0; i < separateClass.length; ++i) {\n this.priorProbability[i][0] = Math.log(separateClass[i].length / trainingSet.rows);\n }\n\n var features = trainingSet.columns;\n this.conditionalProbability = new Matrix(separateClass.length, features);\n for (i = 0; i < separateClass.length; ++i) {\n var classValues = Matrix.checkMatrix(separateClass[i]);\n var total = classValues.sum();\n var divisor = total + features;\n this.conditionalProbability.setRow(i, classValues.sum('column').add(1).div(divisor).apply(matrixLog));\n }\n }\n\n /**\n * Retrieves the predictions for the dataset with the current model.\n * @param {Matrix|Array} dataset\n * @return {Array} - predictions from the dataset.\n */\n predict(dataset) {\n dataset = Matrix.checkMatrix(dataset);\n var predictions = new Array(dataset.rows);\n for (var i = 0; i < dataset.rows; ++i) {\n var currentElement = dataset.getRowVector(i);\n predictions[i] = this.conditionalProbability.clone().mulRowVector(currentElement).sum('row')\n .add(this.priorProbability).maxIndex()[0];\n }\n\n return predictions;\n }\n\n /**\n * Function that saves the current model.\n * @return {object} - model in JSON format.\n */\n toJSON() {\n return {\n name: 'MultinomialNB',\n priorProbability: this.priorProbability,\n conditionalProbability: this.conditionalProbability\n };\n }\n\n /**\n * Creates a new MultinomialNB from the given model\n * @param {object} model\n * @return {MultinomialNB}\n */\n static load(model) {\n if (model.name !== 'MultinomialNB') {\n throw new RangeError(`${model.name} is not a Multinomial Naive Bayes`);\n }\n\n return new MultinomialNB(model);\n }\n}\n\nfunction matrixLog(i, j) {\n this[i][j] = Math.log(this[i][j]);\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-naivebayes/src/MultinomialNB.js","import KDTree from './KDTree';\nimport euclideanDistance from 'ml-distance-euclidean';\n\nexport default class KNN {\n\n /**\n * @param {Array} dataset\n * @param {Array} labels\n * @param {object} options\n * @param {number} [options.k=numberOfClasses + 1] - Number of neighbors to classify.\n * @param {function} [options.distance=euclideanDistance] - Distance function that takes two parameters.\n */\n constructor(dataset, labels, options = {}) {\n if (dataset === true) {\n const model = labels;\n this.kdTree = new KDTree(model.kdTree, options);\n this.k = model.k;\n this.classes = new Set(model.classes);\n this.isEuclidean = model.isEuclidean;\n return;\n }\n\n const classes = new Set(labels);\n\n const {\n distance = euclideanDistance,\n k = classes.size + 1\n } = options;\n\n const points = new Array(dataset.length);\n for (var i = 0; i < points.length; ++i) {\n points[i] = dataset[i].slice();\n }\n\n for (i = 0; i < labels.length; ++i) {\n points[i].push(labels[i]);\n }\n\n this.kdTree = new KDTree(points, distance);\n this.k = k;\n this.classes = classes;\n this.isEuclidean = distance === euclideanDistance;\n }\n\n /**\n * Create a new KNN instance with the given model.\n * @param {object} model\n * @param {function} distance=euclideanDistance - distance function must be provided if the model wasn't trained with euclidean distance.\n * @return {KNN}\n */\n static load(model, distance = euclideanDistance) {\n if (model.name !== 'KNN') {\n throw new Error('invalid model: ' + model.name);\n }\n if (!model.isEuclidean && distance === euclideanDistance) {\n throw new Error('a custom distance function was used to create the model. Please provide it again');\n }\n if (model.isEuclidean && distance !== euclideanDistance) {\n throw new Error('the model was created with the default distance function. Do not load it with another one');\n }\n return new KNN(true, model, distance);\n }\n\n /**\n * Return a JSON containing the kd-tree model.\n * @return {object} JSON KNN model.\n */\n toJSON() {\n return {\n name: 'KNN',\n kdTree: this.kdTree,\n k: this.k,\n classes: Array.from(this.classes),\n isEuclidean: this.isEuclidean\n };\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Array} dataset\n * @return {Array} predictions\n */\n predict(dataset) {\n if (Array.isArray(dataset)) {\n if (typeof dataset[0] === 'number') {\n return getSinglePrediction(this, dataset);\n } else if (Array.isArray(dataset[0]) && typeof dataset[0][0] === 'number') {\n const predictions = new Array(dataset.length);\n for (var i = 0; i < dataset.length; i++) {\n predictions[i] = getSinglePrediction(this, dataset[i]);\n }\n return predictions;\n }\n }\n throw new TypeError('dataset to predict must be an array or a matrix');\n }\n}\n\nfunction getSinglePrediction(knn, currentCase) {\n var nearestPoints = knn.kdTree.nearest(currentCase, knn.k);\n var pointsPerClass = {};\n var predictedClass = -1;\n var maxPoints = -1;\n var lastElement = nearestPoints[0][0].length - 1;\n\n for (var element of knn.classes) {\n pointsPerClass[element] = 0;\n }\n\n for (var i = 0; i < nearestPoints.length; ++i) {\n var currentClass = nearestPoints[i][0][lastElement];\n var currentPoints = ++pointsPerClass[currentClass];\n if (currentPoints > maxPoints) {\n predictedClass = currentClass;\n maxPoints = currentPoints;\n }\n }\n\n return predictedClass;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-knn/src/index.js","/*\n * Original code from:\n *\n * k-d Tree JavaScript - V 1.01\n *\n * https://github.com/ubilabs/kd-tree-javascript\n *\n * @author Mircea Pricop , 2012\n * @author Martin Kleppe , 2012\n * @author Ubilabs http://ubilabs.net, 2012\n * @license MIT License \n */\n\nfunction Node(obj, dimension, parent) {\n this.obj = obj;\n this.left = null;\n this.right = null;\n this.parent = parent;\n this.dimension = dimension;\n}\n\nexport default class KDTree {\n constructor(points, metric) {\n // If points is not an array, assume we're loading a pre-built tree\n if (!Array.isArray(points)) {\n this.dimensions = points.dimensions;\n this.root = points;\n restoreParent(this.root);\n } else {\n this.dimensions = new Array(points[0].length);\n for (var i = 0; i < this.dimensions.length; i++) {\n this.dimensions[i] = i;\n }\n this.root = buildTree(points, 0, null, this.dimensions);\n }\n this.metric = metric;\n }\n\n // Convert to a JSON serializable structure; this just requires removing\n // the `parent` property\n toJSON() {\n const result = toJSONImpl(this.root, true);\n result.dimensions = this.dimensions;\n return result;\n }\n\n nearest(point, maxNodes, maxDistance) {\n const metric = this.metric;\n const dimensions = this.dimensions;\n var i;\n\n const bestNodes = new BinaryHeap(\n function (e) {\n return -e[1];\n }\n );\n\n function nearestSearch(node) {\n const dimension = dimensions[node.dimension];\n const ownDistance = metric(point, node.obj);\n const linearPoint = {};\n var bestChild,\n linearDistance,\n otherChild,\n i;\n\n function saveNode(node, distance) {\n bestNodes.push([node, distance]);\n if (bestNodes.size() > maxNodes) {\n bestNodes.pop();\n }\n }\n\n for (i = 0; i < dimensions.length; i += 1) {\n if (i === node.dimension) {\n linearPoint[dimensions[i]] = point[dimensions[i]];\n } else {\n linearPoint[dimensions[i]] = node.obj[dimensions[i]];\n }\n }\n\n linearDistance = metric(linearPoint, node.obj);\n\n if (node.right === null && node.left === null) {\n if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {\n saveNode(node, ownDistance);\n }\n return;\n }\n\n if (node.right === null) {\n bestChild = node.left;\n } else if (node.left === null) {\n bestChild = node.right;\n } else {\n if (point[dimension] < node.obj[dimension]) {\n bestChild = node.left;\n } else {\n bestChild = node.right;\n }\n }\n\n nearestSearch(bestChild);\n\n if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {\n saveNode(node, ownDistance);\n }\n\n if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) {\n if (bestChild === node.left) {\n otherChild = node.right;\n } else {\n otherChild = node.left;\n }\n if (otherChild !== null) {\n nearestSearch(otherChild);\n }\n }\n }\n\n if (maxDistance) {\n for (i = 0; i < maxNodes; i += 1) {\n bestNodes.push([null, maxDistance]);\n }\n }\n\n if (this.root) {\n nearestSearch(this.root);\n }\n\n const result = [];\n for (i = 0; i < Math.min(maxNodes, bestNodes.content.length); i += 1) {\n if (bestNodes.content[i][0]) {\n result.push([bestNodes.content[i][0].obj, bestNodes.content[i][1]]);\n }\n }\n return result;\n }\n}\n\nfunction toJSONImpl(src) {\n const dest = new Node(src.obj, src.dimension, null);\n if (src.left) dest.left = toJSONImpl(src.left);\n if (src.right) dest.right = toJSONImpl(src.right);\n return dest;\n}\n\nfunction buildTree(points, depth, parent, dimensions) {\n const dim = depth % dimensions.length;\n\n if (points.length === 0) {\n return null;\n }\n if (points.length === 1) {\n return new Node(points[0], dim, parent);\n }\n\n points.sort((a, b) => a[dimensions[dim]] - b[dimensions[dim]]);\n\n const median = Math.floor(points.length / 2);\n const node = new Node(points[median], dim, parent);\n node.left = buildTree(points.slice(0, median), depth + 1, node, dimensions);\n node.right = buildTree(points.slice(median + 1), depth + 1, node, dimensions);\n\n return node;\n}\n\nfunction restoreParent(root) {\n if (root.left) {\n root.left.parent = root;\n restoreParent(root.left);\n }\n\n if (root.right) {\n root.right.parent = root;\n restoreParent(root.right);\n }\n}\n\n// Binary heap implementation from:\n// http://eloquentjavascript.net/appendix2.html\nclass BinaryHeap {\n constructor(scoreFunction) {\n this.content = [];\n this.scoreFunction = scoreFunction;\n }\n\n push(element) {\n // Add the new element to the end of the array.\n this.content.push(element);\n // Allow it to bubble up.\n this.bubbleUp(this.content.length - 1);\n }\n\n pop() {\n // Store the first element so we can return it later.\n var result = this.content[0];\n // Get the element at the end of the array.\n var end = this.content.pop();\n // If there are any elements left, put the end element at the\n // start, and let it sink down.\n if (this.content.length > 0) {\n this.content[0] = end;\n this.sinkDown(0);\n }\n return result;\n }\n\n peek() {\n return this.content[0];\n }\n\n size() {\n return this.content.length;\n }\n\n bubbleUp(n) {\n // Fetch the element that has to be moved.\n var element = this.content[n];\n // When at 0, an element can not go up any further.\n while (n > 0) {\n // Compute the parent element's index, and fetch it.\n const parentN = Math.floor((n + 1) / 2) - 1;\n const parent = this.content[parentN];\n // Swap the elements if the parent is greater.\n if (this.scoreFunction(element) < this.scoreFunction(parent)) {\n this.content[parentN] = element;\n this.content[n] = parent;\n // Update 'n' to continue at the new position.\n n = parentN;\n } else { // Found a parent that is less, no need to move it further.\n break;\n }\n }\n }\n\n sinkDown(n) {\n // Look up the target element and its score.\n var length = this.content.length;\n var element = this.content[n];\n var elemScore = this.scoreFunction(element);\n\n while (true) {\n // Compute the indices of the child elements.\n var child2N = (n + 1) * 2;\n var child1N = child2N - 1;\n // This is used to store the new position of the element,\n // if any.\n var swap = null;\n // If the first child exists (is inside the array)...\n if (child1N < length) {\n // Look it up and compute its score.\n var child1 = this.content[child1N];\n var child1Score = this.scoreFunction(child1);\n // If the score is less than our element's, we need to swap.\n if (child1Score < elemScore) {\n swap = child1N;\n }\n }\n // Do the same checks for the other child.\n if (child2N < length) {\n var child2 = this.content[child2N];\n var child2Score = this.scoreFunction(child2);\n if (child2Score < (swap === null ? elemScore : child1Score)) {\n swap = child2N;\n }\n }\n\n // If the element needs to be moved, swap it, and continue.\n if (swap !== null) {\n this.content[n] = this.content[swap];\n this.content[swap] = element;\n n = swap;\n } else {\n // Otherwise, we are done.\n break;\n }\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-knn/src/KDTree.js","export {PLS} from './pls';\nexport {KOPLS} from './kopls';\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-pls/src/index.js","import Matrix from 'ml-matrix';\nimport Stat from 'ml-stat/matrix';\nimport * as Utils from './utils';\n\n/**\n * @class PLS\n */\nexport class PLS {\n\n /**\n * Constructor for Partial Least Squares (PLS)\n * @param {object} options\n * @param {number} [options.latentVectors] - Number of latent vector to get (if the algorithm doesn't find a good model below the tolerance)\n * @param {number} [options.tolerance=1e-5]\n * @param {boolean} [options.scale=true] - rescale dataset using mean.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.meanX = model.meanX;\n this.stdDevX = model.stdDevX;\n this.meanY = model.meanY;\n this.stdDevY = model.stdDevY;\n this.PBQ = Matrix.checkMatrix(model.PBQ);\n this.R2X = model.R2X;\n this.scale = model.scale;\n this.scaleMethod = model.scaleMethod;\n this.tolerance = model.tolerance;\n } else {\n var {\n tolerance = 1e-5,\n scale = true,\n } = options;\n this.tolerance = tolerance;\n this.scale = scale;\n this.latentVectors = options.latentVectors;\n }\n }\n\n /**\n * Fits the model with the given data and predictions, in this function is calculated the\n * following outputs:\n *\n * T - Score matrix of X\n * P - Loading matrix of X\n * U - Score matrix of Y\n * Q - Loading matrix of Y\n * B - Matrix of regression coefficient\n * W - Weight matrix of X\n *\n * @param {Matrix|Array} trainingSet\n * @param {Matrix|Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n trainingValues = Matrix.checkMatrix(trainingValues);\n\n if (trainingSet.length !== trainingValues.length) {\n throw new RangeError('The number of X rows must be equal to the number of Y rows');\n }\n\n this.meanX = Stat.mean(trainingSet);\n this.stdDevX = Stat.standardDeviation(trainingSet, this.meanX, true);\n this.meanY = Stat.mean(trainingValues);\n this.stdDevY = Stat.standardDeviation(trainingValues, this.meanY, true);\n\n if (this.scale) { // here should be the ml-preprocess project\n trainingSet = trainingSet.clone().subRowVector(this.meanX).divRowVector(this.stdDevX);\n trainingValues = trainingValues.clone().subRowVector(this.meanY).divRowVector(this.stdDevY);\n }\n\n if (this.latentVectors === undefined) {\n this.latentVectors = Math.min(trainingSet.length - 1, trainingSet[0].length);\n }\n\n var rx = trainingSet.rows;\n var cx = trainingSet.columns;\n var ry = trainingValues.rows;\n var cy = trainingValues.columns;\n\n var ssqXcal = trainingSet.clone().mul(trainingSet).sum(); // for the r²\n var sumOfSquaresY = trainingValues.clone().mul(trainingValues).sum();\n\n var tolerance = this.tolerance;\n var n = this.latentVectors;\n var T = Matrix.zeros(rx, n);\n var P = Matrix.zeros(cx, n);\n var U = Matrix.zeros(ry, n);\n var Q = Matrix.zeros(cy, n);\n var B = Matrix.zeros(n, n);\n var W = P.clone();\n var k = 0;\n\n while (Utils.norm(trainingValues) > tolerance && k < n) {\n var transposeX = trainingSet.transpose();\n var transposeY = trainingValues.transpose();\n\n var tIndex = maxSumColIndex(trainingSet.clone().mulM(trainingSet));\n var uIndex = maxSumColIndex(trainingValues.clone().mulM(trainingValues));\n\n var t1 = trainingSet.getColumnVector(tIndex);\n var u = trainingValues.getColumnVector(uIndex);\n var t = Matrix.zeros(rx, 1);\n\n while (Utils.norm(t1.clone().sub(t)) > tolerance) {\n var w = transposeX.mmul(u);\n w.div(Utils.norm(w));\n t = t1;\n t1 = trainingSet.mmul(w);\n var q = transposeY.mmul(t1);\n q.div(Utils.norm(q));\n u = trainingValues.mmul(q);\n }\n\n t = t1;\n var num = transposeX.mmul(t);\n var den = (t.transpose().mmul(t))[0][0];\n var p = num.div(den);\n var pnorm = Utils.norm(p);\n p.div(pnorm);\n t.mul(pnorm);\n w.mul(pnorm);\n\n num = u.transpose().mmul(t);\n den = (t.transpose().mmul(t))[0][0];\n var b = (num.div(den))[0][0];\n trainingSet.sub(t.mmul(p.transpose()));\n trainingValues.sub(t.clone().mul(b).mmul(q.transpose()));\n\n T.setColumn(k, t);\n P.setColumn(k, p);\n U.setColumn(k, u);\n Q.setColumn(k, q);\n W.setColumn(k, w);\n\n B[k][k] = b;\n k++;\n }\n\n k--;\n T = T.subMatrix(0, T.rows - 1, 0, k);\n P = P.subMatrix(0, P.rows - 1, 0, k);\n U = U.subMatrix(0, U.rows - 1, 0, k);\n Q = Q.subMatrix(0, Q.rows - 1, 0, k);\n W = W.subMatrix(0, W.rows - 1, 0, k);\n B = B.subMatrix(0, k, 0, k);\n\n // TODO: review of R2Y\n //this.R2Y = t.transpose().mmul(t).mul(q[k][0]*q[k][0]).divS(ssqYcal)[0][0];\n //\n this.ssqYcal = sumOfSquaresY;\n this.E = trainingSet;\n this.F = trainingValues;\n this.T = T;\n this.P = P;\n this.U = U;\n this.Q = Q;\n this.W = W;\n this.B = B;\n this.PBQ = P.mmul(B).mmul(Q.transpose());\n this.R2X = t.transpose().mmul(t).mmul(p.transpose().mmul(p)).div(ssqXcal)[0][0];\n }\n\n /**\n * Predicts the behavior of the given dataset.\n * @param {Matrix|Array} dataset - data to be predicted.\n * @return {Matrix} - predictions of each element of the dataset.\n */\n predict(dataset) {\n var X = Matrix.checkMatrix(dataset);\n if (this.scale) {\n X = X.subRowVector(this.meanX).divRowVector(this.stdDevX);\n }\n var Y = X.mmul(this.PBQ);\n Y = Y.mulRowVector(this.stdDevY).addRowVector(this.meanY);\n return Y;\n }\n\n /**\n * Returns the explained variance on training of the PLS model\n * @return {number}\n */\n getExplainedVariance() {\n return this.R2X;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n name: 'PLS',\n R2X: this.R2X,\n meanX: this.meanX,\n stdDevX: this.stdDevX,\n meanY: this.meanY,\n stdDevY: this.stdDevY,\n PBQ: this.PBQ,\n tolerance: this.tolerance,\n scale: this.scale,\n };\n }\n\n /**\n * Load a PLS model from a JSON Object\n * @param {object} model\n * @return {PLS} - PLS object from the given model\n */\n static load(model) {\n if (model.name !== 'PLS') {\n throw new RangeError('Invalid model: ' + model.name);\n }\n return new PLS(true, model);\n }\n}\n\n/**\n * @private\n * Function that returns the index where the sum of each\n * column vector is maximum.\n * @param {Matrix} data\n * @return {number} index of the maximum\n */\nfunction maxSumColIndex(data) {\n return data.sum('column').maxIndex()[0];\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-pls/src/pls.js","import {Matrix, SingularValueDecomposition, inverse} from 'ml-matrix';\nimport {initializeMatrices} from './utils';\n\n/**\n * @class KOPLS\n */\nexport class KOPLS {\n\n /**\n * Constructor for Kernel-based Orthogonal Projections to Latent Structures (K-OPLS)\n * @param {object} options\n * @param {number} [options.predictiveComponents] - Number of predictive components to use.\n * @param {number} [options.orthogonalComponents] - Number of Y-Orthogonal components.\n * @param {Kernel} [options.kernel] - Kernel object to apply, see [ml-kernel](https://github.com/mljs/kernel).\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.trainingSet = new Matrix(model.trainingSet);\n this.YLoadingMat = new Matrix(model.YLoadingMat);\n this.SigmaPow = new Matrix(model.SigmaPow);\n this.YScoreMat = new Matrix(model.YScoreMat);\n this.predScoreMat = initializeMatrices(model.predScoreMat, false);\n this.YOrthLoadingVec = initializeMatrices(model.YOrthLoadingVec, false);\n this.YOrthEigen = model.YOrthEigen;\n this.YOrthScoreMat = initializeMatrices(model.YOrthScoreMat, false);\n this.toNorm = initializeMatrices(model.toNorm, false);\n this.TURegressionCoeff = initializeMatrices(model.TURegressionCoeff, false);\n this.kernelX = initializeMatrices(model.kernelX, true);\n this.kernel = model.kernel;\n this.orthogonalComp = model.orthogonalComp;\n this.predictiveComp = model.predictiveComp;\n } else {\n if (options.predictiveComponents === undefined) {\n throw new RangeError('no predictive components found!');\n }\n if (options.orthogonalComponents === undefined) {\n throw new RangeError('no orthogonal components found!');\n }\n if (options.kernel === undefined) {\n throw new RangeError('no kernel found!');\n }\n\n this.orthogonalComp = options.orthogonalComponents;\n this.predictiveComp = options.predictiveComponents;\n this.kernel = options.kernel;\n }\n }\n\n /**\n * Train the K-OPLS model with the given training set and labels.\n * @param {Matrix|Array} trainingSet\n * @param {Matrix|Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n trainingValues = Matrix.checkMatrix(trainingValues);\n\n // to save and compute kernel with the prediction dataset.\n this.trainingSet = trainingSet.clone();\n\n var kernelX = this.kernel.compute(trainingSet);\n\n var Identity = Matrix.eye(kernelX.rows, kernelX.rows, 1);\n var temp = kernelX;\n kernelX = new Matrix(this.orthogonalComp + 1, this.orthogonalComp + 1);\n kernelX[0][0] = temp;\n\n var result = new SingularValueDecomposition(trainingValues.transpose().mmul(kernelX[0][0]).mmul(trainingValues), {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: false\n });\n var YLoadingMat = result.leftSingularVectors;\n var Sigma = result.diagonalMatrix;\n\n YLoadingMat = YLoadingMat.subMatrix(0, YLoadingMat.rows - 1, 0, this.predictiveComp - 1);\n Sigma = Sigma.subMatrix(0, this.predictiveComp - 1, 0, this.predictiveComp - 1);\n\n var YScoreMat = trainingValues.mmul(YLoadingMat);\n\n var predScoreMat = new Array(this.orthogonalComp + 1);\n var TURegressionCoeff = new Array(this.orthogonalComp + 1);\n var YOrthScoreMat = new Array(this.orthogonalComp);\n var YOrthLoadingVec = new Array(this.orthogonalComp);\n var YOrthEigen = new Array(this.orthogonalComp);\n var YOrthScoreNorm = new Array(this.orthogonalComp);\n\n var SigmaPow = Matrix.pow(Sigma, -0.5);\n // to avoid errors, check infinity\n SigmaPow.apply(function (i, j) {\n if (this[i][j] === Infinity) {\n this[i][j] = 0.0;\n }\n });\n\n for (var i = 0; i < this.orthogonalComp; ++i) {\n predScoreMat[i] = kernelX[0][i].transpose().mmul(YScoreMat).mmul(SigmaPow);\n\n var TpiPrime = predScoreMat[i].transpose();\n TURegressionCoeff[i] = inverse(TpiPrime.mmul(predScoreMat[i])).mmul(TpiPrime).mmul(YScoreMat);\n\n result = new SingularValueDecomposition(TpiPrime.mmul(Matrix.sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime))).mmul(predScoreMat[i]), {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: false\n });\n var CoTemp = result.leftSingularVectors;\n var SoTemp = result.diagonalMatrix;\n\n YOrthLoadingVec[i] = CoTemp.subMatrix(0, CoTemp.rows - 1, 0, 0);\n YOrthEigen[i] = SoTemp[0][0];\n\n YOrthScoreMat[i] = Matrix.sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime)).mmul(predScoreMat[i]).mmul(YOrthLoadingVec[i]).mul(Math.pow(YOrthEigen[i], -0.5));\n\n var toiPrime = YOrthScoreMat[i].transpose();\n YOrthScoreNorm[i] = Matrix.sqrt(toiPrime.mmul(YOrthScoreMat[i]));\n\n YOrthScoreMat[i] = YOrthScoreMat[i].divRowVector(YOrthScoreNorm[i]);\n\n var ITo = Matrix.sub(Identity, YOrthScoreMat[i].mmul(YOrthScoreMat[i].transpose()));\n\n kernelX[0][i + 1] = kernelX[0][i].mmul(ITo);\n kernelX[i + 1][i + 1] = ITo.mmul(kernelX[i][i]).mmul(ITo);\n }\n\n var lastScoreMat = predScoreMat[this.orthogonalComp] = kernelX[0][this.orthogonalComp].transpose().mmul(YScoreMat).mmul(SigmaPow);\n\n var lastTpPrime = lastScoreMat.transpose();\n TURegressionCoeff[this.orthogonalComp] = inverse(lastTpPrime.mmul(lastScoreMat)).mmul(lastTpPrime).mmul(YScoreMat);\n\n this.YLoadingMat = YLoadingMat;\n this.SigmaPow = SigmaPow;\n this.YScoreMat = YScoreMat;\n this.predScoreMat = predScoreMat;\n this.YOrthLoadingVec = YOrthLoadingVec;\n this.YOrthEigen = YOrthEigen;\n this.YOrthScoreMat = YOrthScoreMat;\n this.toNorm = YOrthScoreNorm;\n this.TURegressionCoeff = TURegressionCoeff;\n this.kernelX = kernelX;\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Matrix|Array} toPredict\n * @return {{y: Matrix, predScoreMat: Array, predYOrthVectors: Array}} predictions\n */\n predict(toPredict) {\n\n var KTestTrain = this.kernel.compute(toPredict, this.trainingSet);\n\n var temp = KTestTrain;\n KTestTrain = new Matrix(this.orthogonalComp + 1, this.orthogonalComp + 1);\n KTestTrain[0][0] = temp;\n\n var YOrthScoreVector = new Array(this.orthogonalComp);\n var predScoreMat = new Array(this.orthogonalComp);\n\n var i;\n for (i = 0; i < this.orthogonalComp; ++i) {\n predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow);\n\n YOrthScoreVector[i] = Matrix.sub(KTestTrain[i][i], predScoreMat[i].mmul(this.predScoreMat[i].transpose())).mmul(this.predScoreMat[i]).mmul(this.YOrthLoadingVec[i]).mul(Math.pow(this.YOrthEigen[i], -0.5));\n\n YOrthScoreVector[i] = YOrthScoreVector[i].divRowVector(this.toNorm[i]);\n\n var scoreMatPrime = this.YOrthScoreMat[i].transpose();\n KTestTrain[i + 1][0] = Matrix.sub(KTestTrain[i][0], YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[0][i].transpose()));\n\n var p1 = Matrix.sub(KTestTrain[i][0], KTestTrain[i][i].mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime));\n var p2 = YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[i][i]);\n var p3 = p2.mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime);\n\n KTestTrain[i + 1][i + 1] = p1.sub(p2).add(p3);\n }\n\n predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow);\n var prediction = predScoreMat[i].mmul(this.TURegressionCoeff[i]).mmul(this.YLoadingMat.transpose());\n\n return {\n prediction: prediction,\n predScoreMat: predScoreMat,\n predYOrthVectors: YOrthScoreVector\n };\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n name: 'K-OPLS',\n YLoadingMat: this.YLoadingMat,\n SigmaPow: this.SigmaPow,\n YScoreMat: this.YScoreMat,\n predScoreMat: this.predScoreMat,\n YOrthLoadingVec: this.YOrthLoadingVec,\n YOrthEigen: this.YOrthEigen,\n YOrthScoreMat: this.YOrthScoreMat,\n toNorm: this.toNorm,\n TURegressionCoeff: this.TURegressionCoeff,\n kernelX: this.kernelX,\n trainingSet: this.trainingSet,\n orthogonalComp: this.orthogonalComp,\n predictiveComp: this.predictiveComp\n };\n }\n\n /**\n * Load a K-OPLS with the given model.\n * @param {object} model\n * @param {Kernel} kernel - kernel used on the model, see [ml-kernel](https://github.com/mljs/kernel).\n * @return {KOPLS}\n */\n static load(model, kernel) {\n if (model.name !== 'K-OPLS') {\n throw new RangeError('Invalid model: ' + model.name);\n }\n\n if (!kernel) {\n throw new RangeError('You must provide a kernel for the model!');\n }\n\n model.kernel = kernel;\n return new KOPLS(true, model);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-pls/src/kopls.js","'use strict';\n\nconst ConfusionMatrix = require('ml-confusion-matrix');\n\nconst CV = {};\nconst combinations = require('ml-combinations');\n\n/**\n * Performs a leave-one-out cross-validation (LOO-CV) of the given samples. In LOO-CV, 1 observation is used as the\n * validation set while the rest is used as the training set. This is repeated once for each observation. LOO-CV is a\n * special case of LPO-CV. @see leavePout\n * @param {function} Classifier - The classifier's constructor to use for the cross validation. Expect ml-classifier\n * api.\n * @param {Array} features - The features for all samples of the data-set\n * @param {Array} labels - The classification class of all samples of the data-set\n * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated.\n * @return {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.leaveOneOut = function (Classifier, features, labels, classifierOptions) {\n if (typeof labels === 'function') {\n var callback = labels;\n labels = features;\n features = Classifier;\n return CV.leavePOut(features, labels, 1, callback);\n }\n return CV.leavePOut(Classifier, features, labels, classifierOptions, 1);\n};\n\n\n/**\n * Performs a leave-p-out cross-validation (LPO-CV) of the given samples. In LPO-CV, p observations are used as the\n * validation set while the rest is used as the training set. This is repeated as many times as there are possible\n * ways to combine p observations from the set (unordered without replacement). Be aware that for relatively small\n * data-set size this can require a very large number of training and testing to do!\n * @param {function} Classifier - The classifier's constructor to use for the cross validation. Expect ml-classifier\n * api.\n * @param {Array} features - The features for all samples of the data-set\n * @param {Array} labels - The classification class of all samples of the data-set\n * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated.\n * @param {number} p - The size of the validation sub-samples' set\n * @return {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.leavePOut = function (Classifier, features, labels, classifierOptions, p) {\n if (typeof classifierOptions === 'function') {\n var callback = classifierOptions;\n p = labels;\n labels = features;\n features = Classifier;\n }\n check(features, labels);\n const distinct = getDistinct(labels);\n const confusionMatrix = initMatrix(distinct.length, distinct.length);\n\n var N = features.length;\n var gen = combinations(p, N);\n var allIdx = new Array(N);\n for (let i = 0; i < N; i++) {\n allIdx[i] = i;\n }\n for (const testIdx of gen) {\n var trainIdx = allIdx.slice();\n\n for (let i = testIdx.length - 1; i >= 0; i--) {\n trainIdx.splice(testIdx[i], 1);\n }\n\n if (callback) {\n validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback);\n } else {\n validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct);\n }\n\n }\n\n return new ConfusionMatrix(confusionMatrix, distinct);\n};\n\n/**\n * Performs k-fold cross-validation (KF-CV). KF-CV separates the data-set into k random equally sized partitions, and\n * uses each as a validation set, with all other partitions used in the training set. Observations left over from if k\n * does not divide the number of observations are left out of the cross-validation process.\n * @param {function} Classifier - The classifier's to use for the cross validation. Expect ml-classifier api.\n * @param {Array} features - The features for all samples of the data-set\n * @param {Array} labels - The classification class of all samples of the data-set\n * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated.\n * @param {number} k - The number of partitions to create\n * @return {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.kFold = function (Classifier, features, labels, classifierOptions, k) {\n if (typeof classifierOptions === 'function') {\n var callback = classifierOptions;\n k = labels;\n labels = features;\n features = Classifier;\n }\n check(features, labels);\n const distinct = getDistinct(labels);\n const confusionMatrix = initMatrix(distinct.length, distinct.length);\n var N = features.length;\n var allIdx = new Array(N);\n for (var i = 0; i < N; i++) {\n allIdx[i] = i;\n }\n\n var l = Math.floor(N / k);\n // create random k-folds\n var current = [];\n var folds = [];\n while (allIdx.length) {\n var randi = Math.floor(Math.random() * allIdx.length);\n current.push(allIdx[randi]);\n allIdx.splice(randi, 1);\n if (current.length === l) {\n folds.push(current);\n current = [];\n }\n }\n if (current.length) folds.push(current);\n folds = folds.slice(0, k);\n\n\n for (i = 0; i < folds.length; i++) {\n var testIdx = folds[i];\n var trainIdx = [];\n for (var j = 0; j < folds.length; j++) {\n if (j !== i) trainIdx = trainIdx.concat(folds[j]);\n }\n\n if (callback) {\n validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback);\n } else {\n validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct);\n }\n }\n\n return new ConfusionMatrix(confusionMatrix, distinct);\n};\n\nfunction check(features, labels) {\n if (features.length !== labels.length) {\n throw new Error('features and labels should have the same length');\n }\n}\n\nfunction initMatrix(rows, columns) {\n return new Array(rows).fill(0).map(() => new Array(columns).fill(0));\n}\n\nfunction getDistinct(arr) {\n var s = new Set();\n for (let i = 0; i < arr.length; i++) {\n s.add(arr[i]);\n }\n return Array.from(s);\n}\n\nfunction validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct) {\n const {testFeatures, trainFeatures, testLabels, trainLabels} = getTrainTest(features, labels, testIdx, trainIdx);\n\n var classifier;\n if (Classifier.prototype.train) {\n classifier = new Classifier(classifierOptions);\n classifier.train(trainFeatures, trainLabels);\n } else {\n classifier = new Classifier(trainFeatures, trainLabels, classifierOptions);\n }\n\n var predictedLabels = classifier.predict(testFeatures);\n updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct);\n}\n\nfunction validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback) {\n const {testFeatures, trainFeatures, testLabels, trainLabels} = getTrainTest(features, labels, testIdx, trainIdx);\n const predictedLabels = callback(trainFeatures, trainLabels, testFeatures);\n updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct);\n}\n\nfunction updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct) {\n\n for (var i = 0; i < predictedLabels.length; i++) {\n const actualIdx = distinct.indexOf(testLabels[i]);\n const predictedIdx = distinct.indexOf(predictedLabels[i]);\n if (actualIdx < 0 || predictedIdx < 0) {\n // eslint-disable-next-line no-console\n console.warn(`ignore unknown predicted label ${predictedLabels[i]}`);\n }\n confusionMatrix[actualIdx][predictedIdx]++;\n }\n}\n\n\nfunction getTrainTest(features, labels, testIdx, trainIdx) {\n return {\n testFeatures: testIdx.map(function (index) {\n return features[index];\n }),\n trainFeatures: trainIdx.map(function (index) {\n return features[index];\n }),\n testLabels: testIdx.map(function (index) {\n return labels[index];\n }),\n trainLabels: trainIdx.map(function (index) {\n return labels[index];\n })\n };\n}\n\nmodule.exports = CV;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-cross-validation/src/index.js","(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? factory() :\n\ttypeof define === 'function' && define.amd ? define(factory) :\n\t(factory());\n}(this, (function () { 'use strict';\n\n\tfunction createCommonjsModule(fn, module) {\n\t\treturn module = { exports: {} }, fn(module, module.exports), module.exports;\n\t}\n\n\tvar runtime = createCommonjsModule(function (module) {\n\t/**\n\t * Copyright (c) 2014-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t */\n\n\t!(function(global) {\n\n\t var Op = Object.prototype;\n\t var hasOwn = Op.hasOwnProperty;\n\t var undefined; // More compressible than void 0.\n\t var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n\t var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n\t var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n\t var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\t var runtime = global.regeneratorRuntime;\n\t if (runtime) {\n\t {\n\t // If regeneratorRuntime is defined globally and we're in a module,\n\t // make the exports object identical to regeneratorRuntime.\n\t module.exports = runtime;\n\t }\n\t // Don't bother evaluating the rest of this file if the runtime was\n\t // already defined globally.\n\t return;\n\t }\n\n\t // Define the runtime globally (as expected by generated code) as either\n\t // module.exports (if we're in a module) or a new, empty object.\n\t runtime = global.regeneratorRuntime = module.exports;\n\n\t function wrap(innerFn, outerFn, self, tryLocsList) {\n\t // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n\t var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n\t var generator = Object.create(protoGenerator.prototype);\n\t var context = new Context(tryLocsList || []);\n\n\t // The ._invoke method unifies the implementations of the .next,\n\t // .throw, and .return methods.\n\t generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n\t return generator;\n\t }\n\t runtime.wrap = wrap;\n\n\t // Try/catch helper to minimize deoptimizations. Returns a completion\n\t // record like context.tryEntries[i].completion. This interface could\n\t // have been (and was previously) designed to take a closure to be\n\t // invoked without arguments, but in all the cases we care about we\n\t // already have an existing method we want to call, so there's no need\n\t // to create a new function object. We can even get away with assuming\n\t // the method takes exactly one argument, since that happens to be true\n\t // in every case, so we don't have to touch the arguments object. The\n\t // only additional allocation required is the completion record, which\n\t // has a stable shape and so hopefully should be cheap to allocate.\n\t function tryCatch(fn, obj, arg) {\n\t try {\n\t return { type: \"normal\", arg: fn.call(obj, arg) };\n\t } catch (err) {\n\t return { type: \"throw\", arg: err };\n\t }\n\t }\n\n\t var GenStateSuspendedStart = \"suspendedStart\";\n\t var GenStateSuspendedYield = \"suspendedYield\";\n\t var GenStateExecuting = \"executing\";\n\t var GenStateCompleted = \"completed\";\n\n\t // Returning this object from the innerFn has the same effect as\n\t // breaking out of the dispatch switch statement.\n\t var ContinueSentinel = {};\n\n\t // Dummy constructor functions that we use as the .constructor and\n\t // .constructor.prototype properties for functions that return Generator\n\t // objects. For full spec compliance, you may wish to configure your\n\t // minifier not to mangle the names of these two functions.\n\t function Generator() {}\n\t function GeneratorFunction() {}\n\t function GeneratorFunctionPrototype() {}\n\n\t // This is a polyfill for %IteratorPrototype% for environments that\n\t // don't natively support it.\n\t var IteratorPrototype = {};\n\t IteratorPrototype[iteratorSymbol] = function () {\n\t return this;\n\t };\n\n\t var getProto = Object.getPrototypeOf;\n\t var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n\t if (NativeIteratorPrototype &&\n\t NativeIteratorPrototype !== Op &&\n\t hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n\t // This environment has a native %IteratorPrototype%; use it instead\n\t // of the polyfill.\n\t IteratorPrototype = NativeIteratorPrototype;\n\t }\n\n\t var Gp = GeneratorFunctionPrototype.prototype =\n\t Generator.prototype = Object.create(IteratorPrototype);\n\t GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n\t GeneratorFunctionPrototype.constructor = GeneratorFunction;\n\t GeneratorFunctionPrototype[toStringTagSymbol] =\n\t GeneratorFunction.displayName = \"GeneratorFunction\";\n\n\t // Helper for defining the .next, .throw, and .return methods of the\n\t // Iterator interface in terms of a single ._invoke method.\n\t function defineIteratorMethods(prototype) {\n\t [\"next\", \"throw\", \"return\"].forEach(function(method) {\n\t prototype[method] = function(arg) {\n\t return this._invoke(method, arg);\n\t };\n\t });\n\t }\n\n\t runtime.isGeneratorFunction = function(genFun) {\n\t var ctor = typeof genFun === \"function\" && genFun.constructor;\n\t return ctor\n\t ? ctor === GeneratorFunction ||\n\t // For the native GeneratorFunction constructor, the best we can\n\t // do is to check its .name property.\n\t (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n\t : false;\n\t };\n\n\t runtime.mark = function(genFun) {\n\t if (Object.setPrototypeOf) {\n\t Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n\t } else {\n\t genFun.__proto__ = GeneratorFunctionPrototype;\n\t if (!(toStringTagSymbol in genFun)) {\n\t genFun[toStringTagSymbol] = \"GeneratorFunction\";\n\t }\n\t }\n\t genFun.prototype = Object.create(Gp);\n\t return genFun;\n\t };\n\n\t // Within the body of any async function, `await x` is transformed to\n\t // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n\t // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n\t // meant to be awaited.\n\t runtime.awrap = function(arg) {\n\t return { __await: arg };\n\t };\n\n\t function AsyncIterator(generator) {\n\t function invoke(method, arg, resolve, reject) {\n\t var record = tryCatch(generator[method], generator, arg);\n\t if (record.type === \"throw\") {\n\t reject(record.arg);\n\t } else {\n\t var result = record.arg;\n\t var value = result.value;\n\t if (value &&\n\t typeof value === \"object\" &&\n\t hasOwn.call(value, \"__await\")) {\n\t return Promise.resolve(value.__await).then(function(value) {\n\t invoke(\"next\", value, resolve, reject);\n\t }, function(err) {\n\t invoke(\"throw\", err, resolve, reject);\n\t });\n\t }\n\n\t return Promise.resolve(value).then(function(unwrapped) {\n\t // When a yielded Promise is resolved, its final value becomes\n\t // the .value of the Promise<{value,done}> result for the\n\t // current iteration. If the Promise is rejected, however, the\n\t // result for this iteration will be rejected with the same\n\t // reason. Note that rejections of yielded Promises are not\n\t // thrown back into the generator function, as is the case\n\t // when an awaited Promise is rejected. This difference in\n\t // behavior between yield and await is important, because it\n\t // allows the consumer to decide what to do with the yielded\n\t // rejection (swallow it and continue, manually .throw it back\n\t // into the generator, abandon iteration, whatever). With\n\t // await, by contrast, there is no opportunity to examine the\n\t // rejection reason outside the generator function, so the\n\t // only option is to throw it from the await expression, and\n\t // let the generator function handle the exception.\n\t result.value = unwrapped;\n\t resolve(result);\n\t }, reject);\n\t }\n\t }\n\n\t var previousPromise;\n\n\t function enqueue(method, arg) {\n\t function callInvokeWithMethodAndArg() {\n\t return new Promise(function(resolve, reject) {\n\t invoke(method, arg, resolve, reject);\n\t });\n\t }\n\n\t return previousPromise =\n\t // If enqueue has been called before, then we want to wait until\n\t // all previous Promises have been resolved before calling invoke,\n\t // so that results are always delivered in the correct order. If\n\t // enqueue has not been called before, then it is important to\n\t // call invoke immediately, without waiting on a callback to fire,\n\t // so that the async generator function has the opportunity to do\n\t // any necessary setup in a predictable way. This predictability\n\t // is why the Promise constructor synchronously invokes its\n\t // executor callback, and why async functions synchronously\n\t // execute code before the first await. Since we implement simple\n\t // async functions in terms of async generators, it is especially\n\t // important to get this right, even though it requires care.\n\t previousPromise ? previousPromise.then(\n\t callInvokeWithMethodAndArg,\n\t // Avoid propagating failures to Promises returned by later\n\t // invocations of the iterator.\n\t callInvokeWithMethodAndArg\n\t ) : callInvokeWithMethodAndArg();\n\t }\n\n\t // Define the unified helper method that is used to implement .next,\n\t // .throw, and .return (see defineIteratorMethods).\n\t this._invoke = enqueue;\n\t }\n\n\t defineIteratorMethods(AsyncIterator.prototype);\n\t AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n\t return this;\n\t };\n\t runtime.AsyncIterator = AsyncIterator;\n\n\t // Note that simple async functions are implemented on top of\n\t // AsyncIterator objects; they just return a Promise for the value of\n\t // the final result produced by the iterator.\n\t runtime.async = function(innerFn, outerFn, self, tryLocsList) {\n\t var iter = new AsyncIterator(\n\t wrap(innerFn, outerFn, self, tryLocsList)\n\t );\n\n\t return runtime.isGeneratorFunction(outerFn)\n\t ? iter // If outerFn is a generator, return the full iterator.\n\t : iter.next().then(function(result) {\n\t return result.done ? result.value : iter.next();\n\t });\n\t };\n\n\t function makeInvokeMethod(innerFn, self, context) {\n\t var state = GenStateSuspendedStart;\n\n\t return function invoke(method, arg) {\n\t if (state === GenStateExecuting) {\n\t throw new Error(\"Generator is already running\");\n\t }\n\n\t if (state === GenStateCompleted) {\n\t if (method === \"throw\") {\n\t throw arg;\n\t }\n\n\t // Be forgiving, per 25.3.3.3.3 of the spec:\n\t // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n\t return doneResult();\n\t }\n\n\t context.method = method;\n\t context.arg = arg;\n\n\t while (true) {\n\t var delegate = context.delegate;\n\t if (delegate) {\n\t var delegateResult = maybeInvokeDelegate(delegate, context);\n\t if (delegateResult) {\n\t if (delegateResult === ContinueSentinel) continue;\n\t return delegateResult;\n\t }\n\t }\n\n\t if (context.method === \"next\") {\n\t // Setting context._sent for legacy support of Babel's\n\t // function.sent implementation.\n\t context.sent = context._sent = context.arg;\n\n\t } else if (context.method === \"throw\") {\n\t if (state === GenStateSuspendedStart) {\n\t state = GenStateCompleted;\n\t throw context.arg;\n\t }\n\n\t context.dispatchException(context.arg);\n\n\t } else if (context.method === \"return\") {\n\t context.abrupt(\"return\", context.arg);\n\t }\n\n\t state = GenStateExecuting;\n\n\t var record = tryCatch(innerFn, self, context);\n\t if (record.type === \"normal\") {\n\t // If an exception is thrown from innerFn, we leave state ===\n\t // GenStateExecuting and loop back for another invocation.\n\t state = context.done\n\t ? GenStateCompleted\n\t : GenStateSuspendedYield;\n\n\t if (record.arg === ContinueSentinel) {\n\t continue;\n\t }\n\n\t return {\n\t value: record.arg,\n\t done: context.done\n\t };\n\n\t } else if (record.type === \"throw\") {\n\t state = GenStateCompleted;\n\t // Dispatch the exception by looping back around to the\n\t // context.dispatchException(context.arg) call above.\n\t context.method = \"throw\";\n\t context.arg = record.arg;\n\t }\n\t }\n\t };\n\t }\n\n\t // Call delegate.iterator[context.method](context.arg) and handle the\n\t // result, either by returning a { value, done } result from the\n\t // delegate iterator, or by modifying context.method and context.arg,\n\t // setting context.delegate to null, and returning the ContinueSentinel.\n\t function maybeInvokeDelegate(delegate, context) {\n\t var method = delegate.iterator[context.method];\n\t if (method === undefined) {\n\t // A .throw or .return when the delegate iterator has no .throw\n\t // method always terminates the yield* loop.\n\t context.delegate = null;\n\n\t if (context.method === \"throw\") {\n\t if (delegate.iterator.return) {\n\t // If the delegate iterator has a return method, give it a\n\t // chance to clean up.\n\t context.method = \"return\";\n\t context.arg = undefined;\n\t maybeInvokeDelegate(delegate, context);\n\n\t if (context.method === \"throw\") {\n\t // If maybeInvokeDelegate(context) changed context.method from\n\t // \"return\" to \"throw\", let that override the TypeError below.\n\t return ContinueSentinel;\n\t }\n\t }\n\n\t context.method = \"throw\";\n\t context.arg = new TypeError(\n\t \"The iterator does not provide a 'throw' method\");\n\t }\n\n\t return ContinueSentinel;\n\t }\n\n\t var record = tryCatch(method, delegate.iterator, context.arg);\n\n\t if (record.type === \"throw\") {\n\t context.method = \"throw\";\n\t context.arg = record.arg;\n\t context.delegate = null;\n\t return ContinueSentinel;\n\t }\n\n\t var info = record.arg;\n\n\t if (! info) {\n\t context.method = \"throw\";\n\t context.arg = new TypeError(\"iterator result is not an object\");\n\t context.delegate = null;\n\t return ContinueSentinel;\n\t }\n\n\t if (info.done) {\n\t // Assign the result of the finished delegate to the temporary\n\t // variable specified by delegate.resultName (see delegateYield).\n\t context[delegate.resultName] = info.value;\n\n\t // Resume execution at the desired location (see delegateYield).\n\t context.next = delegate.nextLoc;\n\n\t // If context.method was \"throw\" but the delegate handled the\n\t // exception, let the outer generator proceed normally. If\n\t // context.method was \"next\", forget context.arg since it has been\n\t // \"consumed\" by the delegate iterator. If context.method was\n\t // \"return\", allow the original .return call to continue in the\n\t // outer generator.\n\t if (context.method !== \"return\") {\n\t context.method = \"next\";\n\t context.arg = undefined;\n\t }\n\n\t } else {\n\t // Re-yield the result returned by the delegate method.\n\t return info;\n\t }\n\n\t // The delegate iterator is finished, so forget it and continue with\n\t // the outer generator.\n\t context.delegate = null;\n\t return ContinueSentinel;\n\t }\n\n\t // Define Generator.prototype.{next,throw,return} in terms of the\n\t // unified ._invoke helper method.\n\t defineIteratorMethods(Gp);\n\n\t Gp[toStringTagSymbol] = \"Generator\";\n\n\t // A Generator should always return itself as the iterator object when the\n\t // @@iterator function is called on it. Some browsers' implementations of the\n\t // iterator prototype chain incorrectly implement this, causing the Generator\n\t // object to not be returned from this call. This ensures that doesn't happen.\n\t // See https://github.com/facebook/regenerator/issues/274 for more details.\n\t Gp[iteratorSymbol] = function() {\n\t return this;\n\t };\n\n\t Gp.toString = function() {\n\t return \"[object Generator]\";\n\t };\n\n\t function pushTryEntry(locs) {\n\t var entry = { tryLoc: locs[0] };\n\n\t if (1 in locs) {\n\t entry.catchLoc = locs[1];\n\t }\n\n\t if (2 in locs) {\n\t entry.finallyLoc = locs[2];\n\t entry.afterLoc = locs[3];\n\t }\n\n\t this.tryEntries.push(entry);\n\t }\n\n\t function resetTryEntry(entry) {\n\t var record = entry.completion || {};\n\t record.type = \"normal\";\n\t delete record.arg;\n\t entry.completion = record;\n\t }\n\n\t function Context(tryLocsList) {\n\t // The root entry object (effectively a try statement without a catch\n\t // or a finally block) gives us a place to store values thrown from\n\t // locations where there is no enclosing try statement.\n\t this.tryEntries = [{ tryLoc: \"root\" }];\n\t tryLocsList.forEach(pushTryEntry, this);\n\t this.reset(true);\n\t }\n\n\t runtime.keys = function(object) {\n\t var keys = [];\n\t for (var key in object) {\n\t keys.push(key);\n\t }\n\t keys.reverse();\n\n\t // Rather than returning an object with a next method, we keep\n\t // things simple and return the next function itself.\n\t return function next() {\n\t while (keys.length) {\n\t var key = keys.pop();\n\t if (key in object) {\n\t next.value = key;\n\t next.done = false;\n\t return next;\n\t }\n\t }\n\n\t // To avoid creating an additional object, we just hang the .value\n\t // and .done properties off the next function object itself. This\n\t // also ensures that the minifier will not anonymize the function.\n\t next.done = true;\n\t return next;\n\t };\n\t };\n\n\t function values(iterable) {\n\t if (iterable) {\n\t var iteratorMethod = iterable[iteratorSymbol];\n\t if (iteratorMethod) {\n\t return iteratorMethod.call(iterable);\n\t }\n\n\t if (typeof iterable.next === \"function\") {\n\t return iterable;\n\t }\n\n\t if (!isNaN(iterable.length)) {\n\t var i = -1, next = function next() {\n\t while (++i < iterable.length) {\n\t if (hasOwn.call(iterable, i)) {\n\t next.value = iterable[i];\n\t next.done = false;\n\t return next;\n\t }\n\t }\n\n\t next.value = undefined;\n\t next.done = true;\n\n\t return next;\n\t };\n\n\t return next.next = next;\n\t }\n\t }\n\n\t // Return an iterator with no values.\n\t return { next: doneResult };\n\t }\n\t runtime.values = values;\n\n\t function doneResult() {\n\t return { value: undefined, done: true };\n\t }\n\n\t Context.prototype = {\n\t constructor: Context,\n\n\t reset: function(skipTempReset) {\n\t this.prev = 0;\n\t this.next = 0;\n\t // Resetting context._sent for legacy support of Babel's\n\t // function.sent implementation.\n\t this.sent = this._sent = undefined;\n\t this.done = false;\n\t this.delegate = null;\n\n\t this.method = \"next\";\n\t this.arg = undefined;\n\n\t this.tryEntries.forEach(resetTryEntry);\n\n\t if (!skipTempReset) {\n\t for (var name in this) {\n\t // Not sure about the optimal order of these conditions:\n\t if (name.charAt(0) === \"t\" &&\n\t hasOwn.call(this, name) &&\n\t !isNaN(+name.slice(1))) {\n\t this[name] = undefined;\n\t }\n\t }\n\t }\n\t },\n\n\t stop: function() {\n\t this.done = true;\n\n\t var rootEntry = this.tryEntries[0];\n\t var rootRecord = rootEntry.completion;\n\t if (rootRecord.type === \"throw\") {\n\t throw rootRecord.arg;\n\t }\n\n\t return this.rval;\n\t },\n\n\t dispatchException: function(exception) {\n\t if (this.done) {\n\t throw exception;\n\t }\n\n\t var context = this;\n\t function handle(loc, caught) {\n\t record.type = \"throw\";\n\t record.arg = exception;\n\t context.next = loc;\n\n\t if (caught) {\n\t // If the dispatched exception was caught by a catch block,\n\t // then let that catch block handle the exception normally.\n\t context.method = \"next\";\n\t context.arg = undefined;\n\t }\n\n\t return !! caught;\n\t }\n\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t var record = entry.completion;\n\n\t if (entry.tryLoc === \"root\") {\n\t // Exception thrown outside of any try block that could handle\n\t // it, so set the completion value of the entire function to\n\t // throw the exception.\n\t return handle(\"end\");\n\t }\n\n\t if (entry.tryLoc <= this.prev) {\n\t var hasCatch = hasOwn.call(entry, \"catchLoc\");\n\t var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n\t if (hasCatch && hasFinally) {\n\t if (this.prev < entry.catchLoc) {\n\t return handle(entry.catchLoc, true);\n\t } else if (this.prev < entry.finallyLoc) {\n\t return handle(entry.finallyLoc);\n\t }\n\n\t } else if (hasCatch) {\n\t if (this.prev < entry.catchLoc) {\n\t return handle(entry.catchLoc, true);\n\t }\n\n\t } else if (hasFinally) {\n\t if (this.prev < entry.finallyLoc) {\n\t return handle(entry.finallyLoc);\n\t }\n\n\t } else {\n\t throw new Error(\"try statement without catch or finally\");\n\t }\n\t }\n\t }\n\t },\n\n\t abrupt: function(type, arg) {\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t if (entry.tryLoc <= this.prev &&\n\t hasOwn.call(entry, \"finallyLoc\") &&\n\t this.prev < entry.finallyLoc) {\n\t var finallyEntry = entry;\n\t break;\n\t }\n\t }\n\n\t if (finallyEntry &&\n\t (type === \"break\" ||\n\t type === \"continue\") &&\n\t finallyEntry.tryLoc <= arg &&\n\t arg <= finallyEntry.finallyLoc) {\n\t // Ignore the finally entry if control is not jumping to a\n\t // location outside the try/catch block.\n\t finallyEntry = null;\n\t }\n\n\t var record = finallyEntry ? finallyEntry.completion : {};\n\t record.type = type;\n\t record.arg = arg;\n\n\t if (finallyEntry) {\n\t this.method = \"next\";\n\t this.next = finallyEntry.finallyLoc;\n\t return ContinueSentinel;\n\t }\n\n\t return this.complete(record);\n\t },\n\n\t complete: function(record, afterLoc) {\n\t if (record.type === \"throw\") {\n\t throw record.arg;\n\t }\n\n\t if (record.type === \"break\" ||\n\t record.type === \"continue\") {\n\t this.next = record.arg;\n\t } else if (record.type === \"return\") {\n\t this.rval = this.arg = record.arg;\n\t this.method = \"return\";\n\t this.next = \"end\";\n\t } else if (record.type === \"normal\" && afterLoc) {\n\t this.next = afterLoc;\n\t }\n\n\t return ContinueSentinel;\n\t },\n\n\t finish: function(finallyLoc) {\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t if (entry.finallyLoc === finallyLoc) {\n\t this.complete(entry.completion, entry.afterLoc);\n\t resetTryEntry(entry);\n\t return ContinueSentinel;\n\t }\n\t }\n\t },\n\n\t \"catch\": function(tryLoc) {\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t if (entry.tryLoc === tryLoc) {\n\t var record = entry.completion;\n\t if (record.type === \"throw\") {\n\t var thrown = record.arg;\n\t resetTryEntry(entry);\n\t }\n\t return thrown;\n\t }\n\t }\n\n\t // The context.catch method must only be called with a location\n\t // argument that corresponds to a known catch block.\n\t throw new Error(\"illegal catch attempt\");\n\t },\n\n\t delegateYield: function(iterable, resultName, nextLoc) {\n\t this.delegate = {\n\t iterator: values(iterable),\n\t resultName: resultName,\n\t nextLoc: nextLoc\n\t };\n\n\t if (this.method === \"next\") {\n\t // Deliberately forget the last sent value so that we don't\n\t // accidentally pass it on to the delegate.\n\t this.arg = undefined;\n\t }\n\n\t return ContinueSentinel;\n\t }\n\t };\n\t})(\n\t // In sloppy mode, unbound `this` refers to the global object, fallback to\n\t // Function constructor if we're in global strict mode. That is sadly a form\n\t // of indirect eval which violates Content Security Policy.\n\t (function() { return this })() || Function(\"return this\")()\n\t);\n\t});\n\n\t/**\n\t * Copyright (c) 2014-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t */\n\n\t// This method of obtaining a reference to the global object needs to be\n\t// kept identical to the way it is obtained in runtime.js\n\tvar g = (function() { return this })() || Function(\"return this\")();\n\n\t// Use `getOwnPropertyNames` because not all browsers support calling\n\t// `hasOwnProperty` on the global `self` object in a worker. See #183.\n\tvar hadRuntime = g.regeneratorRuntime &&\n\t Object.getOwnPropertyNames(g).indexOf(\"regeneratorRuntime\") >= 0;\n\n\t// Save the old regeneratorRuntime in case it needs to be restored later.\n\tvar oldRuntime = hadRuntime && g.regeneratorRuntime;\n\n\t// Force reevalutation of runtime.js.\n\tg.regeneratorRuntime = undefined;\n\n\tvar runtimeModule = runtime;\n\n\tif (hadRuntime) {\n\t // Restore the original runtime.\n\t g.regeneratorRuntime = oldRuntime;\n\t} else {\n\t // Remove the global property added by runtime.js.\n\t try {\n\t delete g.regeneratorRuntime;\n\t } catch(e) {\n\t g.regeneratorRuntime = undefined;\n\t }\n\t}\n\n\tvar regenerator = runtimeModule;\n\n\tvar defaultOptions = {\n\t mode: 'index'\n\t};\n\n\tmodule.exports = /*#__PURE__*/regenerator.mark(function _callee(M, N, options) {\n\t var a, c, b, p, x, y, z, i, twiddle;\n\t return regenerator.wrap(function _callee$(_context) {\n\t while (1) {\n\t switch (_context.prev = _context.next) {\n\t case 0:\n\t twiddle = function twiddle() {\n\t var i, j, k;\n\t j = 1;\n\t while (p[j] <= 0) {\n\t j++;\n\t }\n\t if (p[j - 1] === 0) {\n\t for (i = j - 1; i !== 1; i--) {\n\t p[i] = -1;\n\t }\n\t p[j] = 0;\n\t x = z = 0;\n\t p[1] = 1;\n\t y = j - 1;\n\t } else {\n\t if (j > 1) {\n\t p[j - 1] = 0;\n\t }\n\t do {\n\t j++;\n\t } while (p[j] > 0);\n\t k = j - 1;\n\t i = j;\n\t while (p[i] === 0) {\n\t p[i++] = -1;\n\t }\n\t if (p[i] === -1) {\n\t p[i] = p[k];\n\t z = p[k] - 1;\n\t x = i - 1;\n\t y = k - 1;\n\t p[k] = -1;\n\t } else {\n\t if (i === p[0]) {\n\t return 0;\n\t } else {\n\t p[j] = p[i];\n\t z = p[i] - 1;\n\t p[i] = 0;\n\t x = j - 1;\n\t y = i - 1;\n\t }\n\t }\n\t }\n\t return 1;\n\t };\n\n\t options = Object.assign({}, defaultOptions, options);\n\t a = new Array(N);\n\t c = new Array(M);\n\t b = new Array(N);\n\t p = new Array(N + 2);\n\n\n\t // init a and b\n\t for (i = 0; i < N; i++) {\n\t a[i] = i;\n\t if (i < N - M) b[i] = 0;else b[i] = 1;\n\t }\n\n\t // init c\n\t for (i = 0; i < M; i++) {\n\t c[i] = N - M + i;\n\t }\n\n\t // init p\n\t for (i = 0; i < p.length; i++) {\n\t if (i === 0) p[i] = N + 1;else if (i <= N - M) p[i] = 0;else if (i <= N) p[i] = i - N + M;else p[i] = -2;\n\t }\n\n\t if (!(options.mode === 'index')) {\n\t _context.next = 20;\n\t break;\n\t }\n\n\t _context.next = 12;\n\t return c.slice();\n\n\t case 12:\n\t if (!twiddle()) {\n\t _context.next = 18;\n\t break;\n\t }\n\n\t c[z] = a[x];\n\t _context.next = 16;\n\t return c.slice();\n\n\t case 16:\n\t _context.next = 12;\n\t break;\n\n\t case 18:\n\t _context.next = 33;\n\t break;\n\n\t case 20:\n\t if (!(options.mode === 'mask')) {\n\t _context.next = 32;\n\t break;\n\t }\n\n\t _context.next = 23;\n\t return b.slice();\n\n\t case 23:\n\t if (!twiddle()) {\n\t _context.next = 30;\n\t break;\n\t }\n\n\t b[x] = 1;\n\t b[y] = 0;\n\t _context.next = 28;\n\t return b.slice();\n\n\t case 28:\n\t _context.next = 23;\n\t break;\n\n\t case 30:\n\t _context.next = 33;\n\t break;\n\n\t case 32:\n\t throw new Error('Invalid mode');\n\n\t case 33:\n\t case 'end':\n\t return _context.stop();\n\t }\n\t }\n\t }, _callee, this);\n\t});\n\n})));\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-combinations/lib/index.js","'use strict';\n\nconst Matrix = require('ml-matrix').Matrix;\n\nconst Layer = require('./Layer');\nconst OutputLayer = require('./OutputLayer');\nconst Utils = require('./utils');\nconst ACTIVATION_FUNCTIONS = require('./activationFunctions');\n\nclass FeedForwardNeuralNetworks {\n\n /**\n * Create a new Feedforword neural network model.\n * @class FeedForwardNeuralNetworks\n * @param {object} [options]\n * @param {Array} [options.hiddenLayers=[10]] - Array that contains the sizes of the hidden layers.\n * @param {number} [options.iterations=50] - Number of iterations at the training step.\n * @param {number} [options.learningRate=0.01] - Learning rate of the neural net (also known as epsilon).\n * @param {number} [options.regularization=0.01] - Regularization parameter af the neural net.\n * @param {string} [options.activation='tanh'] - activation function to be used. (options: 'tanh'(default),\n * 'identity', 'logistic', 'arctan', 'softsign', 'relu', 'softplus', 'bent', 'sinusoid', 'sinc', 'gaussian').\n * (single-parametric options: 'parametric-relu', 'exponential-relu', 'soft-exponential').\n * @param {number} [options.activationParam=1] - if the selected activation function needs a parameter.\n */\n constructor(options) {\n options = options || {};\n if (options.model) {\n // load network\n this.hiddenLayers = options.hiddenLayers;\n this.iterations = options.iterations;\n this.learningRate = options.learningRate;\n this.regularization = options.regularization;\n this.dicts = options.dicts;\n this.activation = options.activation;\n this.activationParam = options.activationParam;\n this.model = new Array(options.layers.length);\n\n for (var i = 0; i < this.model.length - 1; ++i) {\n this.model[i] = Layer.load(options.layers[i]);\n }\n this.model[this.model.length - 1] = OutputLayer.load(options.layers[this.model.length - 1]);\n } else {\n // default constructor\n this.hiddenLayers = options.hiddenLayers || [10];\n this.iterations = options.iterations || 50;\n\n this.learningRate = options.learningRate || 0.01;\n this.regularization = options.regularization || 0.01;\n\n this.activation = options.activation || 'tanh';\n this.activationParam = options.activationParam || 1;\n if (!(this.activation in Object.keys(ACTIVATION_FUNCTIONS))) {\n this.activation = 'tanh';\n }\n }\n }\n\n /**\n * @private\n * Function that build and initialize the neural net.\n * @param {number} inputSize - total of features to fit.\n * @param {number} outputSize - total of labels of the prediction set.\n */\n buildNetwork(inputSize, outputSize) {\n var size = 2 + (this.hiddenLayers.length - 1);\n this.model = new Array(size);\n\n // input layer\n this.model[0] = new Layer({\n inputSize: inputSize,\n outputSize: this.hiddenLayers[0],\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n\n // hidden layers\n for (var i = 1; i < this.hiddenLayers.length; ++i) {\n this.model[i] = new Layer({\n inputSize: this.hiddenLayers[i - 1],\n outputSize: this.hiddenLayers[i],\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n }\n\n // output layer\n this.model[size - 1] = new OutputLayer({\n inputSize: this.hiddenLayers[this.hiddenLayers.length - 1],\n outputSize: outputSize,\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n }\n\n /**\n * Train the neural net with the given features and labels.\n * @param {Matrix|Array} features\n * @param {Matrix|Array} labels\n */\n train(features, labels) {\n features = Matrix.checkMatrix(features);\n this.dicts = Utils.dictOutputs(labels);\n\n var inputSize = features.columns;\n var outputSize = Object.keys(this.dicts.inputs).length;\n\n this.buildNetwork(inputSize, outputSize);\n\n for (var i = 0; i < this.iterations; ++i) {\n var probabilities = this.propagate(features);\n this.backpropagation(features, labels, probabilities);\n }\n }\n\n /**\n * @private\n * Propagate the input(training set) and retrives the probabilities of each class.\n * @param {Matrix} X\n * @return {Matrix} probabilities of each class.\n */\n propagate(X) {\n var input = X;\n for (var i = 0; i < this.model.length; ++i) {\n //console.log(i);\n input = this.model[i].forward(input);\n }\n\n // get probabilities\n return input.divColumnVector(Utils.sumRow(input));\n }\n\n /**\n * @private\n * Function that applies the backpropagation algorithm on each layer of the network\n * in order to fit the features and labels.\n * @param {Matrix} features\n * @param {Array} labels\n * @param {Matrix} probabilities - probabilities of each class of the feature set.\n */\n backpropagation(features, labels, probabilities) {\n for (var i = 0; i < probabilities.length; ++i) {\n probabilities[i][this.dicts.inputs[labels[i]]] -= 1;\n }\n\n // remember, the last delta doesn't matter\n var delta = probabilities;\n for (i = this.model.length - 1; i >= 0; --i) {\n var a = i > 0 ? this.model[i - 1].a : features;\n delta = this.model[i].backpropagation(delta, a);\n }\n\n for (i = 0; i < this.model.length; ++i) {\n this.model[i].update();\n }\n }\n\n /**\n * Predict the output given the feature set.\n * @param {Array|Matrix} features\n * @return {Array}\n */\n predict(features) {\n features = Matrix.checkMatrix(features);\n var outputs = new Array(features.rows);\n var probabilities = this.propagate(features);\n for (var i = 0; i < features.rows; ++i) {\n outputs[i] = this.dicts.outputs[probabilities.maxRowIndex(i)[1]];\n }\n\n return outputs;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} model\n */\n toJSON() {\n var model = {\n model: 'FNN',\n hiddenLayers: this.hiddenLayers,\n iterations: this.iterations,\n learningRate: this.learningRate,\n regularization: this.regularization,\n activation: this.activation,\n activationParam: this.activationParam,\n dicts: this.dicts,\n layers: new Array(this.model.length)\n };\n\n for (var i = 0; i < this.model.length; ++i) {\n model.layers[i] = this.model[i].toJSON();\n }\n\n return model;\n }\n\n /**\n * Load a Feedforward Neural Network with the current model.\n * @param {object} model\n * @return {FeedForwardNeuralNetworks}\n */\n static load(model) {\n if (model.model !== 'FNN') {\n throw new RangeError('the current model is not a feed forward network');\n }\n\n return new FeedForwardNeuralNetworks(model);\n }\n}\n\nmodule.exports = FeedForwardNeuralNetworks;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-fnn/src/FeedForwardNeuralNetwork.js","'use strict';\n\nvar Layer = require('./Layer');\n\nclass OutputLayer extends Layer {\n constructor(options) {\n super(options);\n\n this.activationFunction = function (i, j) {\n this[i][j] = Math.exp(this[i][j]);\n };\n }\n\n static load(model) {\n if (model.model !== 'Layer') {\n throw new RangeError('the current model is not a Layer model');\n }\n\n return new OutputLayer(model);\n }\n}\n\nmodule.exports = OutputLayer;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-fnn/src/OutputLayer.js","'use strict';\n\nvar NodeSquare = require('./node-square'),\n NodeHexagonal = require('./node-hexagonal');\n\nvar defaultOptions = {\n fields: 3,\n randomizer: Math.random,\n distance: squareEuclidean,\n iterations: 10,\n learningRate: 0.1,\n gridType: 'rect',\n torus: true,\n method: 'random'\n};\n\nfunction SOM(x, y, options, reload) {\n\n this.x = x;\n this.y = y;\n\n options = options || {};\n this.options = {};\n for (var i in defaultOptions) {\n if (options.hasOwnProperty(i)) {\n this.options[i] = options[i];\n } else {\n this.options[i] = defaultOptions[i];\n }\n }\n\n if (typeof this.options.fields === 'number') {\n this.numWeights = this.options.fields;\n } else if (Array.isArray(this.options.fields)) {\n this.numWeights = this.options.fields.length;\n var converters = getConverters(this.options.fields);\n this.extractor = converters.extractor;\n this.creator = converters.creator;\n } else {\n throw new Error('Invalid fields definition');\n }\n\n if (this.options.gridType === 'rect') {\n this.nodeType = NodeSquare;\n this.gridDim = {\n x: x,\n y: y\n };\n } else {\n this.nodeType = NodeHexagonal;\n var hx = this.x - Math.floor(this.y / 2);\n this.gridDim = {\n x: hx,\n y: this.y,\n z: -(0 - hx - this.y)\n };\n }\n\n this.torus = this.options.torus;\n this.distanceMethod = this.torus ? 'getDistanceTorus' : 'getDistance';\n\n this.distance = this.options.distance;\n\n this.maxDistance = getMaxDistance(this.distance, this.numWeights);\n\n if (reload === true) { // For model loading\n this.done = true;\n return;\n }\n if (!(x > 0 && y > 0)) {\n throw new Error('x and y must be positive');\n }\n\n this.times = {\n findBMU: 0,\n adjust: 0\n };\n\n this.randomizer = this.options.randomizer;\n\n this.iterationCount = 0;\n this.iterations = this.options.iterations;\n\n this.startLearningRate = this.learningRate = this.options.learningRate;\n\n this.mapRadius = Math.floor(Math.max(x, y) / 2);\n\n this.algorithmMethod = this.options.method;\n\n this._initNodes();\n\n this.done = false;\n}\n\nSOM.load = function loadModel(model, distance) {\n if (model.name === 'SOM') {\n var x = model.data.length,\n y = model.data[0].length;\n if (distance) {\n model.options.distance = distance;\n } else if (model.options.distance) {\n model.options.distance = eval('(' + model.options.distance + ')');\n }\n var som = new SOM(x, y, model.options, true);\n som.nodes = new Array(x);\n for (var i = 0; i < x; i++) {\n som.nodes[i] = new Array(y);\n for (var j = 0; j < y; j++) {\n som.nodes[i][j] = new som.nodeType(i, j, model.data[i][j], som);\n }\n }\n return som;\n } else {\n throw new Error('expecting a SOM model');\n }\n};\n\nSOM.prototype.export = function exportModel(includeDistance) {\n if (!this.done) {\n throw new Error('model is not ready yet');\n }\n var model = {\n name: 'SOM'\n };\n model.options = {\n fields: this.options.fields,\n gridType: this.options.gridType,\n torus: this.options.torus\n };\n model.data = new Array(this.x);\n for (var i = 0; i < this.x; i++) {\n model.data[i] = new Array(this.y);\n for (var j = 0; j < this.y; j++) {\n model.data[i][j] = this.nodes[i][j].weights;\n }\n }\n if (includeDistance) {\n model.options.distance = this.distance.toString();\n }\n return model;\n};\n\nSOM.prototype._initNodes = function initNodes() {\n var now = Date.now(),\n i, j, k;\n this.nodes = new Array(this.x);\n for (i = 0; i < this.x; i++) {\n this.nodes[i] = new Array(this.y);\n for (j = 0; j < this.y; j++) {\n var weights = new Array(this.numWeights);\n for (k = 0; k < this.numWeights; k++) {\n weights[k] = this.randomizer();\n }\n this.nodes[i][j] = new this.nodeType(i, j, weights, this);\n }\n }\n this.times.initNodes = Date.now() - now;\n};\n\nSOM.prototype.setTraining = function setTraining(trainingSet) {\n if (this.trainingSet) {\n throw new Error('training set has already been set');\n }\n var now = Date.now();\n var convertedSet = trainingSet;\n var i, l = trainingSet.length;\n if (this.extractor) {\n convertedSet = new Array(l);\n for (i = 0; i < l; i++) {\n convertedSet[i] = this.extractor(trainingSet[i]);\n }\n }\n this.numIterations = this.iterations * l;\n\n if (this.algorithmMethod === 'random') {\n this.timeConstant = this.numIterations / Math.log(this.mapRadius);\n } else {\n this.timeConstant = l / Math.log(this.mapRadius);\n }\n this.trainingSet = convertedSet;\n this.times.setTraining = Date.now() - now;\n};\n\nSOM.prototype.trainOne = function trainOne() {\n if (this.done) {\n\n return false;\n\n } else if (this.numIterations-- > 0) {\n\n var neighbourhoodRadius,\n trainingValue,\n trainingSetFactor;\n\n if (this.algorithmMethod === 'random') { // Pick a random value of the training set at each step\n neighbourhoodRadius = this.mapRadius * Math.exp(-this.iterationCount / this.timeConstant);\n trainingValue = getRandomValue(this.trainingSet, this.randomizer);\n this._adjust(trainingValue, neighbourhoodRadius);\n this.learningRate = this.startLearningRate * Math.exp(-this.iterationCount / this.numIterations);\n } else { // Get next input vector\n trainingSetFactor = -Math.floor(this.iterationCount / this.trainingSet.length);\n neighbourhoodRadius = this.mapRadius * Math.exp(trainingSetFactor / this.timeConstant);\n trainingValue = this.trainingSet[this.iterationCount % this.trainingSet.length];\n this._adjust(trainingValue, neighbourhoodRadius);\n if (((this.iterationCount + 1) % this.trainingSet.length) === 0) {\n this.learningRate = this.startLearningRate * Math.exp(trainingSetFactor / Math.floor(this.numIterations / this.trainingSet.length));\n }\n }\n\n this.iterationCount++;\n\n return true;\n\n } else {\n\n this.done = true;\n return false;\n\n }\n};\n\nSOM.prototype._adjust = function adjust(trainingValue, neighbourhoodRadius) {\n var now = Date.now(),\n x, y, dist, influence;\n\n var bmu = this._findBestMatchingUnit(trainingValue);\n\n var now2 = Date.now();\n this.times.findBMU += now2 - now;\n\n var radiusLimit = Math.floor(neighbourhoodRadius);\n var xMin = bmu.x - radiusLimit,\n xMax = bmu.x + radiusLimit,\n yMin = bmu.y - radiusLimit,\n yMax = bmu.y + radiusLimit;\n\n for (x = xMin; x <= xMax; x++) {\n var theX = x;\n if (x < 0) {\n theX += this.x;\n } else if (x >= this.x) {\n theX -= this.x;\n }\n for (y = yMin; y <= yMax; y++) {\n var theY = y;\n if (y < 0) {\n theY += this.y;\n } else if (y >= this.y) {\n theY -= this.y;\n }\n\n dist = bmu[this.distanceMethod](this.nodes[theX][theY]);\n\n if (dist < neighbourhoodRadius) {\n influence = Math.exp(-dist / (2 * neighbourhoodRadius));\n this.nodes[theX][theY].adjustWeights(trainingValue, this.learningRate, influence);\n }\n\n }\n }\n\n this.times.adjust += (Date.now() - now2);\n\n};\n\nSOM.prototype.train = function train(trainingSet) {\n if (!this.done) {\n this.setTraining(trainingSet);\n while (this.trainOne()) {\n }\n }\n};\n\nSOM.prototype.getConvertedNodes = function getConvertedNodes() {\n var result = new Array(this.x);\n for (var i = 0; i < this.x; i++) {\n result[i] = new Array(this.y);\n for (var j = 0; j < this.y; j++) {\n var node = this.nodes[i][j];\n result[i][j] = this.creator ? this.creator(node.weights) : node.weights;\n }\n }\n return result;\n};\n\nSOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) {\n\n var bmu,\n lowest = Infinity,\n dist;\n\n for (var i = 0; i < this.x; i++) {\n for (var j = 0; j < this.y; j++) {\n dist = this.distance(this.nodes[i][j].weights, candidate);\n if (dist < lowest) {\n lowest = dist;\n bmu = this.nodes[i][j];\n }\n }\n }\n\n return bmu;\n\n};\n\nSOM.prototype.predict = function predict(data, computePosition) {\n if (typeof data === 'boolean') {\n computePosition = data;\n data = null;\n }\n if (!data) {\n data = this.trainingSet;\n }\n if (Array.isArray(data) && (Array.isArray(data[0]) || (typeof data[0] === 'object'))) { // predict a dataset\n var self = this;\n return data.map(function (element) {\n return self._predict(element, computePosition);\n });\n } else { // predict a single element\n return this._predict(data, computePosition);\n }\n};\n\nSOM.prototype._predict = function _predict(element, computePosition) {\n if (!Array.isArray(element)) {\n element = this.extractor(element);\n }\n var bmu = this._findBestMatchingUnit(element);\n var result = [bmu.x, bmu.y];\n if (computePosition) {\n result[2] = bmu.getPosition(element);\n }\n return result;\n};\n\n// As seen in http://www.scholarpedia.org/article/Kohonen_network\nSOM.prototype.getQuantizationError = function getQuantizationError() {\n var fit = this.getFit(),\n l = fit.length,\n sum = 0;\n for (var i = 0; i < l; i++) {\n sum += fit[i];\n }\n return sum / l;\n};\n\nSOM.prototype.getFit = function getFit(dataset) {\n if (!dataset) {\n dataset = this.trainingSet;\n }\n var l = dataset.length,\n bmu,\n result = new Array(l);\n for (var i = 0; i < l; i++) {\n bmu = this._findBestMatchingUnit(dataset[i]);\n result[i] = Math.sqrt(this.distance(dataset[i], bmu.weights));\n }\n return result;\n};\n\nfunction getConverters(fields) {\n var l = fields.length,\n normalizers = new Array(l),\n denormalizers = new Array(l);\n for (var i = 0; i < l; i++) {\n normalizers[i] = getNormalizer(fields[i].range);\n denormalizers[i] = getDenormalizer(fields[i].range);\n }\n return {\n extractor: function extractor(value) {\n var result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = normalizers[i](value[fields[i].name]);\n }\n return result;\n },\n creator: function creator(value) {\n var result = {};\n for (var i = 0; i < l; i++) {\n result[fields[i].name] = denormalizers[i](value[i]);\n }\n return result;\n }\n };\n}\n\nfunction getNormalizer(minMax) {\n return function normalizer(value) {\n return (value - minMax[0]) / (minMax[1] - minMax[0]);\n };\n}\n\nfunction getDenormalizer(minMax) {\n return function denormalizer(value) {\n return (minMax[0] + value * (minMax[1] - minMax[0]));\n };\n}\n\nfunction squareEuclidean(a, b) {\n var d = 0;\n for (var i = 0, ii = a.length; i < ii; i++) {\n d += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return d;\n}\n\nfunction getRandomValue(arr, randomizer) {\n return arr[Math.floor(randomizer() * arr.length)];\n}\n\nfunction getMaxDistance(distance, numWeights) {\n var zero = new Array(numWeights),\n one = new Array(numWeights);\n for (var i = 0; i < numWeights; i++) {\n zero[i] = 0;\n one[i] = 1;\n }\n return distance(zero, one);\n}\n\nmodule.exports = SOM;\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-som/src/index.js","var NodeSquare = require('./node-square');\n\nfunction NodeHexagonal(x, y, weights, som) {\n\n NodeSquare.call(this, x, y, weights, som);\n\n this.hX = x - Math.floor(y / 2);\n this.z = 0 - this.hX - y;\n\n}\n\nNodeHexagonal.prototype = new NodeSquare;\nNodeHexagonal.prototype.constructor = NodeHexagonal;\n\nNodeHexagonal.prototype.getDistance = function getDistanceHexagonal(otherNode) {\n return Math.max(Math.abs(this.hX - otherNode.hX), Math.abs(this.y - otherNode.y), Math.abs(this.z - otherNode.z));\n};\n\nNodeHexagonal.prototype.getDistanceTorus = function getDistanceTorus(otherNode) {\n var distX = Math.abs(this.hX - otherNode.hX),\n distY = Math.abs(this.y - otherNode.y),\n distZ = Math.abs(this.z - otherNode.z);\n return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY), Math.min(distZ, this.som.gridDim.z - distZ));\n};\n\nNodeHexagonal.prototype.getPosition = function getPosition() {\n throw new Error('Unimplemented : cannot get position of the points for hexagonal grid');\n};\n\nmodule.exports = NodeHexagonal;\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-som/src/node-hexagonal.js","export default function maybeToPrecision(value, digits) {\n if (value < 0) {\n value = 0 - value;\n if (typeof digits === 'number') {\n return '- ' + value.toPrecision(digits);\n } else {\n return '- ' + value.toString();\n }\n } else {\n if (typeof digits === 'number') {\n return value.toPrecision(digits);\n } else {\n return value.toString();\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-regression-base/src/maybeToPrecision.js","export default function checkArraySize(x, y) {\n if (!Array.isArray(x) || !Array.isArray(y)) {\n throw new TypeError('x and y must be arrays');\n }\n if (x.length !== y.length) {\n throw new RangeError('x and y arrays must have the same length');\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-regression-base/src/checkArrayLength.js","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport SimpleLinearRegression from 'ml-regression-simple-linear';\n\nexport default class ExponentialRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) {\n this.A = y.A;\n this.B = y.B;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n _predict(input) {\n return this.B * Math.exp(input * this.A);\n }\n\n toJSON() {\n return {\n name: 'exponentialRegression',\n A: this.A,\n B: this.B\n };\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.B, precision) + ' * e^(' + maybeToPrecision(this.A, precision) + ' * x)';\n }\n\n toLaTeX(precision) {\n if (this.A >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.B, precision) + 'e^{' + maybeToPrecision(this.A, precision) + 'x}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.B, precision) + '}{e^{' + maybeToPrecision(-this.A, precision) + 'x}}';\n }\n\n }\n\n static load(json) {\n if (json.name !== 'exponentialRegression') {\n throw new TypeError('not a exponential regression model');\n }\n return new ExponentialRegression(true, json);\n }\n}\n\nfunction regress(er, x, y) {\n const n = x.length;\n const yl = new Array(n);\n for (let i = 0; i < n; i++) {\n yl[i] = Math.log(y[i]);\n }\n\n const linear = new SimpleLinearRegression(x, yl);\n er.A = linear.slope;\n er.B = Math.exp(linear.intercept);\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-regression-exponential/src/index.js","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport SimpleLinearRegression from 'ml-regression-simple-linear';\n\nexport default class PowerRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) { // reloading model\n this.A = y.A;\n this.B = y.B;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n _predict(newInputs) {\n return this.A * Math.pow(newInputs, this.B);\n }\n\n toJSON() {\n return {\n name: 'powerRegression',\n A: this.A,\n B: this.B\n };\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + maybeToPrecision(this.B, precision);\n }\n\n toLaTeX(precision) {\n if (this.B >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + maybeToPrecision(this.B, precision) + '}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + maybeToPrecision(-this.B, precision) + '}}';\n }\n }\n\n static load(json) {\n if (json.name !== 'powerRegression') {\n throw new TypeError('not a power regression model');\n }\n return new PowerRegression(true, json);\n }\n}\n\nfunction regress(pr, x, y) {\n const n = x.length;\n const xl = new Array(n);\n const yl = new Array(n);\n for (let i = 0; i < n; i++) {\n xl[i] = Math.log(x[i]);\n yl[i] = Math.log(y[i]);\n }\n\n const linear = new SimpleLinearRegression(xl, yl);\n pr.A = Math.exp(linear.intercept);\n pr.B = linear.slope;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-regression-power/src/index.js","import Matrix, { SVD } from 'ml-matrix';\nimport BaseRegression from 'ml-regression-base';\n\nexport default class MultivariateLinearRegression extends BaseRegression {\n constructor(x, y, options = {}) {\n const { intercept = true, statistics = true } = options;\n super();\n this.statistics = statistics;\n if (x === true) {\n this.weights = y.weights;\n this.inputs = y.inputs;\n this.outputs = y.outputs;\n this.intercept = y.intercept;\n } else {\n x = new Matrix(x);\n if (intercept) {\n x.addColumn(new Array(x.length).fill(1));\n }\n const beta = new SVD(x, { autoTranspose: true }).solve(y);\n this.weights = beta.to2DArray();\n this.inputs = x[0].length;\n this.outputs = y[0].length;\n if (intercept) this.inputs--;\n this.intercept = intercept;\n if (statistics) {\n /*\n * Let's add some basic statistics about the beta's to be able to interpret them.\n * source: http://dept.stat.lsa.umich.edu/~kshedden/Courses/Stat401/Notes/401-multreg.pdf\n * validated against Excel Regression AddIn\n * test: \"datamining statistics test\"\n */\n const fittedValues = x.mmul(beta);\n const residuals = new Matrix(y).addM(fittedValues.neg());\n const variance =\n residuals\n .to2DArray()\n .map((ri) => Math.pow(ri[0], 2))\n .reduce((a, b) => a + b) /\n (y.length - x.columns);\n this.stdError = Math.sqrt(variance);\n this.stdErrorMatrix = x\n .transposeView()\n .mmul(x)\n .pseudoInverse()\n .mul(variance);\n this.stdErrors = this.stdErrorMatrix.diagonal().map((d) => Math.sqrt(d));\n this.tStats = this.weights.map(\n (d, i) => (this.stdErrors[i] === 0 ? 0 : d[0] / this.stdErrors[i])\n );\n }\n }\n }\n\n predict(x) {\n if (Array.isArray(x)) {\n if (typeof x[0] === 'number') {\n return this._predict(x);\n } else if (Array.isArray(x[0])) {\n const y = new Array(x.length);\n for (let i = 0; i < x.length; i++) {\n y[i] = this._predict(x[i]);\n }\n return y;\n }\n }\n throw new TypeError('x must be a matrix or array of numbers');\n }\n\n _predict(x) {\n const result = new Array(this.outputs);\n if (this.intercept) {\n for (let i = 0; i < this.outputs; i++) {\n result[i] = this.weights[this.inputs][i];\n }\n } else {\n result.fill(0);\n }\n for (let i = 0; i < this.inputs; i++) {\n for (let j = 0; j < this.outputs; j++) {\n result[j] += this.weights[i][j] * x[i];\n }\n }\n return result;\n }\n\n score() {\n throw new Error('score method is not implemented yet');\n }\n\n toJSON() {\n return {\n name: 'multivariateLinearRegression',\n weights: this.weights,\n inputs: this.inputs,\n outputs: this.outputs,\n intercept: this.intercept,\n summary: (this.statistics)\n ? {\n regressionStatistics: {\n standardError: this.stdError,\n observations: this.outputs\n },\n variables: this.weights.map((d, i) => {\n return {\n label:\n i === this.weights.length - 1\n ? 'Intercept'\n : `X Variable ${i + 1}`,\n coefficients: d,\n standardError: this.stdErrors[i],\n tStat: this.tStats[i]\n };\n })\n }\n : undefined,\n };\n }\n\n static load(model) {\n if (model.name !== 'multivariateLinearRegression') {\n throw new Error('not a MLR model');\n }\n return new MultivariateLinearRegression(true, model);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-regression-multivariate-linear/src/index.js","import {Matrix, solve} from 'ml-matrix';\nimport Kernel from 'ml-kernel';\n\nimport BaseRegression from 'ml-regression-base';\n\nconst defaultOptions = {\n lambda: 0.1,\n kernelType: 'gaussian',\n kernelOptions: {},\n computeCoefficient: false\n};\n\n// Implements the Kernel ridge regression algorithm.\n// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf\nexport default class KernelRidgeRegression extends BaseRegression {\n constructor(inputs, outputs, options) {\n super();\n if (inputs === true) { // reloading model\n this.alpha = outputs.alpha;\n this.inputs = outputs.inputs;\n this.kernelType = outputs.kernelType;\n this.kernelOptions = outputs.kernelOptions;\n this.kernel = new Kernel(outputs.kernelType, outputs.kernelOptions);\n } else {\n options = Object.assign({}, defaultOptions, options);\n\n const kernelFunction = new Kernel(options.kernelType, options.kernelOptions);\n const K = kernelFunction.compute(inputs);\n const n = inputs.length;\n K.add(Matrix.eye(n, n).mul(options.lambda));\n\n this.alpha = solve(K, outputs);\n this.inputs = inputs;\n this.kernelType = options.kernelType;\n this.kernelOptions = options.kernelOptions;\n this.kernel = kernelFunction;\n }\n }\n\n _predict(newInputs) {\n return this.kernel.compute([newInputs], this.inputs).mmul(this.alpha)[0];\n }\n\n toJSON() {\n return {\n name: 'kernelRidgeRegression',\n alpha: this.alpha,\n inputs: this.inputs,\n kernelType: this.kernelType,\n kernelOptions: this.kernelOptions\n };\n }\n\n static load(json) {\n if (json.name !== 'kernelRidgeRegression') {\n throw new TypeError('not a KRR model');\n }\n return new KernelRidgeRegression(true, json);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-regression/src/regression/kernel-ridge-regression.js","import {Matrix, SVD} from 'ml-matrix';\nimport BaseRegression from 'ml-regression-base';\n\nconst defaultOptions = {\n order: 2\n};\n// Implements the Kernel ridge regression algorithm.\n// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf\nexport default class PolynomialFitRegression2D extends BaseRegression {\n /**\n * Constructor for the 2D polynomial fitting\n *\n * @param inputs\n * @param outputs\n * @param options\n * @constructor\n */\n constructor(inputs, outputs, options) {\n super();\n if (inputs === true) { // reloading model\n this.coefficients = Matrix.columnVector(outputs.coefficients);\n this.order = outputs.order;\n if (outputs.r) {\n this.r = outputs.r;\n this.r2 = outputs.r2;\n }\n if (outputs.chi2) {\n this.chi2 = outputs.chi2;\n }\n } else {\n options = Object.assign({}, defaultOptions, options);\n this.order = options.order;\n this.coefficients = [];\n this.X = inputs;\n this.y = outputs;\n\n this.train(this.X, this.y, options);\n }\n }\n\n /**\n * Function that fits the model given the data(X) and predictions(y).\n * The third argument is an object with the following options:\n * * order: order of the polynomial to fit.\n *\n * @param {Matrix} X - A matrix with n rows and 2 columns.\n * @param {Matrix} y - A vector of the prediction values.\n */\n train(X, y) {\n if (!Matrix.isMatrix(X)) X = new Matrix(X);\n if (!Matrix.isMatrix(y)) y = Matrix.columnVector(y);\n\n if (y.rows !== X.rows) {\n y = y.transpose();\n }\n\n if (X.columns !== 2) {\n throw new RangeError('You give X with ' + X.columns + ' columns and it must be 2');\n }\n if (X.rows !== y.rows) {\n throw new RangeError('X and y must have the same rows');\n }\n\n var examples = X.rows;\n var coefficients = ((this.order + 2) * (this.order + 1)) / 2;\n this.coefficients = new Array(coefficients);\n\n var x1 = X.getColumnVector(0);\n var x2 = X.getColumnVector(1);\n\n var scaleX1 = 1.0 / x1.clone().apply(abs).max();\n var scaleX2 = 1.0 / x2.clone().apply(abs).max();\n var scaleY = 1.0 / y.clone().apply(abs).max();\n\n x1.mulColumn(0, scaleX1);\n x2.mulColumn(0, scaleX2);\n y.mulColumn(0, scaleY);\n\n var A = new Matrix(examples, coefficients);\n var col = 0;\n\n for (var i = 0; i <= this.order; ++i) {\n var limit = this.order - i;\n for (var j = 0; j <= limit; ++j) {\n var result = powColVector(x1, i).mulColumnVector(powColVector(x2, j));\n A.setColumn(col, result);\n col++;\n }\n }\n\n var svd = new SVD(A.transpose(), {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: true,\n autoTranspose: false\n });\n\n var qqs = Matrix.rowVector(svd.diagonal);\n qqs = qqs.apply(function (i, j) {\n if (this[i][j] >= 1e-15) this[i][j] = 1 / this[i][j];\n else this[i][j] = 0;\n });\n\n var qqs1 = Matrix.zeros(examples, coefficients);\n for (i = 0; i < coefficients; ++i) {\n qqs1[i][i] = qqs[0][i];\n }\n\n qqs = qqs1;\n\n var U = svd.rightSingularVectors;\n var V = svd.leftSingularVectors;\n\n this.coefficients = V.mmul(qqs.transpose()).mmul(U.transpose()).mmul(y);\n\n col = 0;\n\n for (i = 0; i <= coefficients; ++i) {\n limit = this.order - i;\n for (j = 0; j <= limit; ++j) {\n this.coefficients[col][0] = (this.coefficients[col][0] * Math.pow(scaleX1, i) * Math.pow(scaleX2, j)) / scaleY;\n col++;\n }\n }\n }\n\n _predict(newInputs) {\n var x1 = newInputs[0];\n var x2 = newInputs[1];\n\n var y = 0;\n var column = 0;\n\n for (var i = 0; i <= this.order; i++) {\n for (var j = 0; j <= this.order - i; j++) {\n y += Math.pow(x1, i) * (Math.pow(x2, j)) * this.coefficients[column][0];\n column++;\n }\n }\n\n return y;\n }\n\n toJSON() {\n return {\n name: 'polyfit2D',\n order: this.order,\n coefficients: this.coefficients\n };\n }\n\n static load(json) {\n if (json.name !== 'polyfit2D') {\n throw new TypeError('not a polyfit2D model');\n }\n return new PolynomialFitRegression2D(true, json);\n }\n}\n\n/**\n * Function that given a column vector return this: vector^power\n *\n * @param x - Column vector.\n * @param power - Pow number.\n * @return {Suite|Matrix}\n */\nfunction powColVector(x, power) {\n var result = x.clone();\n for (var i = 0; i < x.rows; ++i) {\n result[i][0] = Math.pow(result[i][0], power);\n }\n return result;\n}\n\n/**\n * Function to use in the apply method to get the absolute value\n * of each element of the matrix\n *\n * @param i - current row.\n * @param j - current column.\n */\nfunction abs(i, j) {\n this[i][j] = Math.abs(this[i][j]);\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-regression/src/regression/poly-fit-regression2d.js","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport {array} from 'ml-stat';\nconst median = array.median;\n\nexport default class TheilSenRegression extends BaseRegression {\n\n /**\n * Theil–Sen estimator\n * https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator\n * @param {Array|boolean} x\n * @param {Array|object} y\n * @constructor\n */\n constructor(x, y) {\n super();\n if (x === true) {\n // loads the model\n this.slope = y.slope;\n this.intercept = y.intercept;\n this.coefficients = y.coefficients;\n } else {\n // creates the model\n checkArrayLength(x, y);\n theilSen(this, x, y);\n }\n\n }\n\n toJSON() {\n return {\n name: 'TheilSenRegression',\n slope: this.slope,\n intercept: this.intercept\n };\n }\n\n _predict(input) {\n return this.slope * input + this.intercept;\n }\n\n computeX(input) {\n return (input - this.intercept) / this.slope;\n }\n\n toString(precision) {\n var result = 'f(x) = ';\n if (this.slope) {\n var xFactor = maybeToPrecision(this.slope, precision);\n result += (Math.abs(xFactor - 1) < 1e-5 ? '' : xFactor + ' * ') + 'x';\n if (this.intercept) {\n var absIntercept = Math.abs(this.intercept);\n var operator = absIntercept === this.intercept ? '+' : '-';\n result += ' ' + operator + ' ' + maybeToPrecision(absIntercept, precision);\n }\n } else {\n result += maybeToPrecision(this.intercept, precision);\n }\n return result;\n }\n\n toLaTeX(precision) {\n return this.toString(precision);\n }\n\n static load(json) {\n if (json.name !== 'TheilSenRegression') {\n throw new TypeError('not a Theil-Sen model');\n }\n return new TheilSenRegression(true, json);\n }\n}\n\nfunction theilSen(regression, x, y) {\n let len = x.length;\n let slopes = new Array(len * len);\n let count = 0;\n for (let i = 0; i < len; ++i) {\n for (let j = i + 1; j < len; ++j) {\n if (x[i] !== x[j]) {\n slopes[count++] = (y[j] - y[i]) / (x[j] - x[i]);\n }\n }\n }\n slopes.length = count;\n let medianSlope = median(slopes);\n\n let cuts = new Array(len);\n for (let i = 0; i < len; ++i) {\n cuts[i] = y[i] - medianSlope * x[i];\n }\n\n regression.slope = medianSlope;\n regression.intercept = median(cuts);\n regression.coefficients = [regression.intercept, regression.slope];\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-regression-theil-sen/src/index.js","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport {solve} from 'ml-matrix';\n\nexport default class RobustPolynomialRegression extends BaseRegression {\n constructor(x, y, degree) {\n super();\n if (x === true) {\n this.degree = y.degree;\n this.powers = y.powers;\n this.coefficients = y.coefficients;\n } else {\n checkArrayLength(x, y);\n robustPolynomial(this, x, y, degree);\n }\n }\n\n toJSON() {\n return {\n name: 'robustPolynomialRegression',\n degree: this.degree,\n powers: this.powers,\n coefficients: this.coefficients\n };\n }\n\n _predict(x) {\n return predict(x, this.powers, this.coefficients);\n }\n\n toString(precision) {\n return this._toFormula(precision, false);\n }\n\n toLaTeX(precision) {\n return this._toFormula(precision, true);\n }\n\n _toFormula(precision, isLaTeX) {\n let sup = '^';\n let closeSup = '';\n let times = ' * ';\n if (isLaTeX) {\n sup = '^{';\n closeSup = '}';\n times = '';\n }\n\n let fn = '';\n let str = '';\n for (let k = 0; k < this.coefficients.length; k++) {\n str = '';\n if (this.coefficients[k] !== 0) {\n if (this.powers[k] === 0) {\n str = maybeToPrecision(this.coefficients[k], precision);\n } else {\n if (this.powers[k] === 1) {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x';\n } else {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup;\n }\n }\n\n if (this.coefficients[k] > 0 && k !== (this.coefficients.length - 1)) {\n str = ' + ' + str;\n } else if (k !== (this.coefficients.length - 1)) {\n str = ' ' + str;\n }\n }\n fn = str + fn;\n }\n if (fn.charAt(0) === '+') {\n fn = fn.slice(1);\n }\n\n return 'f(x) = ' + fn;\n }\n\n static load(json) {\n if (json.name !== 'robustPolynomialRegression') {\n throw new TypeError('not a RobustPolynomialRegression model');\n }\n return new RobustPolynomialRegression(true, json);\n }\n}\n\nfunction robustPolynomial(regression, x, y, degree) {\n let powers = new Array(degree);\n for (let k = 0; k < degree; k++) {\n powers[k] = k;\n }\n\n const tuples = getRandomTuples(x, y, degree);\n var min;\n\n for (var i = 0; i < tuples.length; i++) {\n var tuple = tuples[i];\n var coefficients = calcCoefficients(tuple, powers);\n\n var residuals = x.slice();\n for (var j = 0; j < x.length; j++) {\n residuals[j] = y[j] - predict(x[j], powers, coefficients);\n residuals[j] = {\n residual: residuals[j] * residuals[j],\n coefficients\n };\n }\n\n var median = residualsMedian(residuals);\n if (!min || median.residual < min.residual) {\n min = median;\n }\n }\n\n regression.degree = degree;\n regression.powers = powers;\n regression.coefficients = min.coefficients;\n}\n\n/**\n * @ignore\n * @param {Array} x\n * @param {Array} y\n * @param {number} degree\n * @return {Array<{x:number,y:number}>}\n */\nfunction getRandomTuples(x, y, degree) {\n var len = Math.floor(x.length / degree);\n var tuples = new Array(len);\n\n for (var i = 0; i < x.length; i++) {\n var pos = Math.floor(Math.random() * len);\n\n var counter = 0;\n while (counter < x.length) {\n if (!tuples[pos]) {\n tuples[pos] = [{\n x: x[i],\n y: y[i]\n }];\n break;\n } else if (tuples[pos].length < degree) {\n tuples[pos].push({\n x: x[i],\n y: y[i]\n });\n break;\n } else {\n counter++;\n pos = (pos + 1) % len;\n }\n }\n\n if (counter === x.length) {\n return tuples;\n }\n }\n return tuples;\n}\n\n/**\n * @ignore\n * @param {{x:number,y:number}} tuple\n * @param {Array} powers\n * @return {Array}\n */\nfunction calcCoefficients(tuple, powers) {\n var X = tuple.slice();\n var Y = tuple.slice();\n for (var i = 0; i < X.length; i++) {\n Y[i] = [tuple[i].y];\n X[i] = new Array(powers.length);\n for (var j = 0; j < powers.length; j++) {\n X[i][j] = Math.pow(tuple[i].x, powers[j]);\n }\n }\n\n return solve(X, Y).to1DArray();\n}\n\nfunction predict(x, powers, coefficients) {\n let y = 0;\n for (let k = 0; k < powers.length; k++) {\n y += coefficients[k] * Math.pow(x, powers[k]);\n }\n return y;\n}\n\nfunction residualsMedian(residuals) {\n residuals.sort((a, b) => a.residual - b.residual);\n\n var l = residuals.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return residuals[half - 1];\n } else {\n return residuals[half];\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-regression-robust-polynomial/src/index.js","import {maybeToPrecision} from 'ml-regression-base';\nimport PolynomialRegression from 'ml-regression-polynomial';\nimport BaseRegression from 'ml-regression-base';\n\n/*\n * Function that calculate the potential fit in the form f(x) = A*x^M\n * with a given M and return de A coefficient.\n *\n * @param {Vector} X - Vector of the x positions of the points.\n * @param {Vector} Y - Vector of the x positions of the points.\n * @param {Number} M - The exponent of the potential fit.\n * @return {Number} A - The A coefficient of the potential fit.\n */\nexport default class PotentialRegression extends BaseRegression {\n /**\n * @constructor\n * @param x: Independent variable\n * @param y: Dependent variable\n * @param M\n */\n constructor(x, y, M) {\n super();\n if (x === true) { // reloading model\n this.A = y.A;\n this.M = y.M;\n } else {\n var n = x.length;\n if (n !== y.length) {\n throw new RangeError('input and output array have a different length');\n }\n\n var linear = new PolynomialRegression(x, y, [M]);\n this.A = linear.coefficients[0];\n this.M = M;\n }\n }\n\n _predict(x) {\n return this.A * Math.pow(x, this.M);\n }\n\n toJSON() {\n return {\n name: 'potentialRegression',\n A: this.A,\n M: this.M\n };\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + this.M;\n }\n\n toLaTeX(precision) {\n if (this.M >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + this.M + '}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + (-this.M) + '}}';\n }\n }\n\n static load(json) {\n if (json.name !== 'potentialRegression') {\n throw new TypeError('not a potential regression model');\n }\n return new PotentialRegression(true, json);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-regression/src/regression/potential-regression.js","'use strict';\n\nvar mlMatrix = require('ml-matrix');\n\n/**\n * Calculate current error\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} parameters - Array of current parameter values\n * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @return {number}\n */\nfunction errorCalculation(\n data,\n parameters,\n parameterizedFunction\n) {\n var error = 0;\n const func = parameterizedFunction(parameters);\n\n for (var i = 0; i < data.x.length; i++) {\n error += Math.abs(data.y[i] - func(data.x[i]));\n }\n\n return error;\n}\n\n/**\n * Difference of the matrix function over the parameters\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} evaluatedData - Array of previous evaluated function values\n * @param {Array} params - Array of previous parameter values\n * @param {number} gradientDifference - Adjustment for decrease the damping parameter\n * @param {function} paramFunction - The parameters and returns a function with the independent variable as a parameter\n * @return {Matrix}\n */\nfunction gradientFunction(\n data,\n evaluatedData,\n params,\n gradientDifference,\n paramFunction\n) {\n const n = params.length;\n const m = data.x.length;\n\n var ans = new Array(n);\n\n for (var param = 0; param < n; param++) {\n ans[param] = new Array(m);\n var auxParams = params.concat();\n auxParams[param] += gradientDifference;\n var funcParam = paramFunction(auxParams);\n\n for (var point = 0; point < m; point++) {\n ans[param][point] = evaluatedData[point] - funcParam(data.x[point]);\n }\n }\n return new mlMatrix.Matrix(ans);\n}\n\n/**\n * Matrix function over the samples\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} evaluatedData - Array of previous evaluated function values\n * @return {Matrix}\n */\nfunction matrixFunction(data, evaluatedData) {\n const m = data.x.length;\n\n var ans = new Array(m);\n\n for (var point = 0; point < m; point++) {\n ans[point] = data.y[point] - evaluatedData[point];\n }\n\n return new mlMatrix.Matrix([ans]);\n}\n\n/**\n * Iteration for Levenberg-Marquardt\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} params - Array of previous parameter values\n * @param {number} damping - Levenberg-Marquardt parameter\n * @param {number} gradientDifference - Adjustment for decrease the damping parameter\n * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @return {Array}\n */\nfunction step(\n data,\n params,\n damping,\n gradientDifference,\n parameterizedFunction\n) {\n var identity = mlMatrix.Matrix.eye(params.length).mul(\n damping * gradientDifference * gradientDifference\n );\n\n var l = data.x.length;\n var evaluatedData = new Array(l);\n const func = parameterizedFunction(params);\n for (var i = 0; i < l; i++) {\n evaluatedData[i] = func(data.x[i]);\n }\n var gradientFunc = gradientFunction(\n data,\n evaluatedData,\n params,\n gradientDifference,\n parameterizedFunction\n );\n var matrixFunc = matrixFunction(data, evaluatedData).transposeView();\n var inverseMatrix = mlMatrix.inverse(\n identity.add(gradientFunc.mmul(gradientFunc.transposeView()))\n );\n params = new mlMatrix.Matrix([params]);\n params = params.sub(\n inverseMatrix\n .mmul(gradientFunc)\n .mmul(matrixFunc)\n .mul(gradientDifference)\n .transposeView()\n );\n\n return params.to1DArray();\n}\n\n/**\n * Curve fitting algorithm\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @param {object} [options] - Options object\n * @param {number} [options.damping] - Levenberg-Marquardt parameter\n * @param {number} [options.gradientDifference = 10e-2] - Adjustment for decrease the damping parameter\n * @param {Array} [options.initialValues] - Array of initial parameter values\n * @param {number} [options.maxIterations = 100] - Maximum of allowed iterations\n * @param {number} [options.errorTolerance = 10e-3] - Minimum uncertainty allowed for each point\n * @return {{parameterValues: Array, parameterError: number, iterations: number}}\n */\nfunction levenbergMarquardt(\n data,\n parameterizedFunction,\n options = {}\n) {\n let {\n maxIterations = 100,\n gradientDifference = 10e-2,\n damping = 0,\n errorTolerance = 10e-3,\n initialValues\n } = options;\n\n if (damping <= 0) {\n throw new Error('The damping option must be a positive number');\n } else if (!data.x || !data.y) {\n throw new Error('The data parameter must have x and y elements');\n } else if (\n !Array.isArray(data.x) ||\n data.x.length < 2 ||\n !Array.isArray(data.y) ||\n data.y.length < 2\n ) {\n throw new Error(\n 'The data parameter elements must be an array with more than 2 points'\n );\n } else {\n let dataLen = data.x.length;\n if (dataLen !== data.y.length) {\n throw new Error('The data parameter elements must have the same size');\n }\n }\n\n var parameters =\n initialValues || new Array(parameterizedFunction.length).fill(1);\n\n if (!Array.isArray(parameters)) {\n throw new Error('initialValues must be an array');\n }\n\n var error = errorCalculation(data, parameters, parameterizedFunction);\n\n var converged = error <= errorTolerance;\n\n for (\n var iteration = 0;\n iteration < maxIterations && !converged;\n iteration++\n ) {\n parameters = step(\n data,\n parameters,\n damping,\n gradientDifference,\n parameterizedFunction\n );\n error = errorCalculation(data, parameters, parameterizedFunction);\n converged = error <= errorTolerance;\n }\n\n return {\n parameterValues: parameters,\n parameterError: error,\n iterations: iteration\n };\n}\n\nmodule.exports = levenbergMarquardt;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-levenberg-marquardt/lib/index.js","import HashTable from 'ml-hash-table';\n\nexport class SparseMatrix {\n constructor(rows, columns, options = {}) {\n if (rows instanceof SparseMatrix) { // clone\n const other = rows;\n this._init(other.rows, other.columns, other.elements.clone(), other.threshold);\n return;\n }\n\n if (Array.isArray(rows)) {\n const matrix = rows;\n rows = matrix.length;\n options = columns || {};\n columns = matrix[0].length;\n this._init(rows, columns, new HashTable(options), options.threshold);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n var value = matrix[i][j];\n if (this.threshold && Math.abs(value) < this.threshold) value = 0;\n if (value !== 0) {\n this.elements.set(i * columns + j, matrix[i][j]);\n }\n }\n }\n } else {\n this._init(rows, columns, new HashTable(options), options.threshold);\n }\n }\n\n _init(rows, columns, elements, threshold) {\n this.rows = rows;\n this.columns = columns;\n this.elements = elements;\n this.threshold = threshold || 0;\n }\n\n static eye(rows = 1, columns = rows) {\n const min = Math.min(rows, columns);\n const matrix = new SparseMatrix(rows, columns, {initialCapacity: min});\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, 1);\n }\n return matrix;\n }\n\n clone() {\n return new SparseMatrix(this);\n }\n\n to2DArray() {\n const copy = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n copy[i] = new Array(this.columns);\n for (var j = 0; j < this.columns; j++) {\n copy[i][j] = this.get(i, j);\n }\n }\n return copy;\n }\n\n isSquare() {\n return this.rows === this.columns;\n }\n\n isSymmetric() {\n if (!this.isSquare()) return false;\n\n var symmetric = true;\n this.forEachNonZero((i, j, v) => {\n if (this.get(j, i) !== v) {\n symmetric = false;\n return false;\n }\n return v;\n });\n return symmetric;\n }\n\n /**\n * Search for the wither band in the main diagonals\n * @return {number}\n */\n bandWidth() {\n let min = this.columns;\n let max = -1;\n this.forEachNonZero((i, j, v) => {\n let diff = i - j;\n min = Math.min(min, diff);\n max = Math.max(max, diff);\n return v;\n });\n return max - min;\n }\n\n /**\n * Test if a matrix is consider banded using a threshold\n * @param {number} width\n * @return {boolean}\n */\n isBanded(width) {\n let bandWidth = this.bandWidth();\n return bandWidth <= width;\n }\n\n get cardinality() {\n return this.elements.size;\n }\n\n get size() {\n return this.rows * this.columns;\n }\n\n get(row, column) {\n return this.elements.get(row * this.columns + column);\n }\n\n set(row, column, value) {\n if (this.threshold && Math.abs(value) < this.threshold) value = 0;\n if (value === 0) {\n this.elements.remove(row * this.columns + column);\n } else {\n this.elements.set(row * this.columns + column, value);\n }\n return this;\n }\n\n mmul(other) {\n if (this.columns !== other.rows) {\n // eslint-disable-next-line no-console\n console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\n }\n\n const m = this.rows;\n const p = other.columns;\n\n const result = new SparseMatrix(m, p);\n this.forEachNonZero((i, j, v1) => {\n other.forEachNonZero((k, l, v2) => {\n if (j === k) {\n result.set(i, l, result.get(i, l) + v1 * v2);\n }\n return v2;\n });\n return v1;\n });\n return result;\n }\n\n kroneckerProduct(other) {\n const m = this.rows;\n const n = this.columns;\n const p = other.rows;\n const q = other.columns;\n\n const result = new SparseMatrix(m * p, n * q, {\n initialCapacity: this.cardinality * other.cardinality\n });\n this.forEachNonZero((i, j, v1) => {\n other.forEachNonZero((k, l, v2) => {\n result.set(p * i + k, q * j + l, v1 * v2);\n return v2;\n });\n return v1;\n });\n return result;\n }\n\n forEachNonZero(callback) {\n this.elements.forEachPair((key, value) => {\n const i = (key / this.columns) | 0;\n const j = key % this.columns;\n let r = callback(i, j, value);\n if (r === false) return false; // stop iteration\n if (this.threshold && Math.abs(r) < this.threshold) r = 0;\n if (r !== value) {\n if (r === 0) {\n this.elements.remove(key, true);\n } else {\n this.elements.set(key, r);\n }\n }\n return true;\n });\n this.elements.maybeShrinkCapacity();\n return this;\n }\n\n getNonZeros() {\n const cardinality = this.cardinality;\n const rows = new Array(cardinality);\n const columns = new Array(cardinality);\n const values = new Array(cardinality);\n var idx = 0;\n this.forEachNonZero((i, j, value) => {\n rows[idx] = i;\n columns[idx] = j;\n values[idx] = value;\n idx++;\n return value;\n });\n return {rows, columns, values};\n }\n\n setThreshold(newThreshold) {\n if (newThreshold !== 0 && newThreshold !== this.threshold) {\n this.threshold = newThreshold;\n this.forEachNonZero((i, j, v) => v);\n }\n return this;\n }\n\n /**\n * @return {SparseMatrix} - New transposed sparse matrix\n */\n transpose() {\n let trans = new SparseMatrix(this.columns, this.rows, {initialCapacity: this.cardinality});\n this.forEachNonZero((i, j, value) => {\n trans.set(j, i, value);\n return value;\n });\n return trans;\n }\n}\n\nSparseMatrix.prototype.klass = 'Matrix';\n\nSparseMatrix.identity = SparseMatrix.eye;\nSparseMatrix.prototype.tensorProduct = SparseMatrix.prototype.kroneckerProduct;\n\n/*\n Add dynamically instance and static methods for mathematical operations\n */\n\nvar inplaceOperator = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\nvar inplaceOperatorScalar = `\n(function %name%S(value) {\n this.forEachNonZero((i, j, v) => v %op% value);\n return this;\n})\n`;\n\nvar inplaceOperatorMatrix = `\n(function %name%M(matrix) {\n matrix.forEachNonZero((i, j, v) => {\n this.set(i, j, this.get(i, j) %op% v);\n return v;\n });\n return this;\n})\n`;\n\nvar staticOperator = `\n(function %name%(matrix, value) {\n var newMatrix = new SparseMatrix(matrix);\n return newMatrix.%name%(value);\n})\n`;\n\nvar inplaceMethod = `\n(function %name%() {\n this.forEachNonZero((i, j, v) => %method%(v));\n return this;\n})\n`;\n\nvar staticMethod = `\n(function %name%(matrix) {\n var newMatrix = new SparseMatrix(matrix);\n return newMatrix.%name%();\n})\n`;\n\nconst operators = [\n // Arithmetic operators\n ['+', 'add'],\n ['-', 'sub', 'subtract'],\n ['*', 'mul', 'multiply'],\n ['/', 'div', 'divide'],\n ['%', 'mod', 'modulus'],\n // Bitwise operators\n ['&', 'and'],\n ['|', 'or'],\n ['^', 'xor'],\n ['<<', 'leftShift'],\n ['>>', 'signPropagatingRightShift'],\n ['>>>', 'rightShift', 'zeroFillRightShift']\n];\n\nfor (const operator of operators) {\n for (let i = 1; i < operator.length; i++) {\n SparseMatrix.prototype[operator[i]] = eval(fillTemplateFunction(inplaceOperator, {name: operator[i], op: operator[0]}));\n SparseMatrix.prototype[operator[i] + 'S'] = eval(fillTemplateFunction(inplaceOperatorScalar, {name: operator[i] + 'S', op: operator[0]}));\n SparseMatrix.prototype[operator[i] + 'M'] = eval(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[i] + 'M', op: operator[0]}));\n\n SparseMatrix[operator[i]] = eval(fillTemplateFunction(staticOperator, {name: operator[i]}));\n }\n}\n\nvar methods = [\n ['~', 'not']\n];\n\n[\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\n].forEach(function (mathMethod) {\n methods.push(['Math.' + mathMethod, mathMethod]);\n});\n\nfor (const method of methods) {\n for (let i = 1; i < method.length; i++) {\n SparseMatrix.prototype[method[i]] = eval(fillTemplateFunction(inplaceMethod, {name: method[i], method: method[0]}));\n SparseMatrix[method[i]] = eval(fillTemplateFunction(staticMethod, {name: method[i]}));\n }\n}\n\nfunction fillTemplateFunction(template, values) {\n for (const i in values) {\n template = template.replace(new RegExp('%' + i + '%', 'g'), values[i]);\n }\n return template;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-sparse-matrix/src/index.js","module.exports = newArray\n\nfunction newArray (n, value) {\n n = n || 0\n var array = new Array(n)\n for (var i = 0; i < n; i++) {\n array[i] = value\n }\n return array\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/new-array/index.js","const binarySearch = require('binary-search');\nconst sortAsc = require('num-sort').asc;\n\nconst largestPrime = 0x7fffffff;\n\nconst primeNumbers = [\n //chunk #0\n largestPrime, // 2^31-1\n\n //chunk #1\n 5, 11, 23, 47, 97, 197, 397, 797, 1597, 3203, 6421, 12853, 25717, 51437, 102877, 205759,\n 411527, 823117, 1646237, 3292489, 6584983, 13169977, 26339969, 52679969, 105359939,\n 210719881, 421439783, 842879579, 1685759167,\n\n //chunk #2\n 433, 877, 1759, 3527, 7057, 14143, 28289, 56591, 113189, 226379, 452759, 905551, 1811107,\n 3622219, 7244441, 14488931, 28977863, 57955739, 115911563, 231823147, 463646329, 927292699,\n 1854585413,\n\n //chunk #3\n 953, 1907, 3821, 7643, 15287, 30577, 61169, 122347, 244703, 489407, 978821, 1957651, 3915341,\n 7830701, 15661423, 31322867, 62645741, 125291483, 250582987, 501165979, 1002331963,\n 2004663929,\n\n //chunk #4\n 1039, 2081, 4177, 8363, 16729, 33461, 66923, 133853, 267713, 535481, 1070981, 2141977, 4283963,\n 8567929, 17135863, 34271747, 68543509, 137087021, 274174111, 548348231, 1096696463,\n\n //chunk #5\n 31, 67, 137, 277, 557, 1117, 2237, 4481, 8963, 17929, 35863, 71741, 143483, 286973, 573953,\n 1147921, 2295859, 4591721, 9183457, 18366923, 36733847, 73467739, 146935499, 293871013,\n 587742049, 1175484103,\n\n //chunk #6\n 599, 1201, 2411, 4831, 9677, 19373, 38747, 77509, 155027, 310081, 620171, 1240361, 2480729,\n 4961459, 9922933, 19845871, 39691759, 79383533, 158767069, 317534141, 635068283, 1270136683,\n\n //chunk #7\n 311, 631, 1277, 2557, 5119, 10243, 20507, 41017, 82037, 164089, 328213, 656429, 1312867,\n 2625761, 5251529, 10503061, 21006137, 42012281, 84024581, 168049163, 336098327, 672196673,\n 1344393353,\n\n //chunk #8\n 3, 7, 17, 37, 79, 163, 331, 673, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899,\n 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557,\n 359339171, 718678369, 1437356741,\n\n //chunk #9\n 43, 89, 179, 359, 719, 1439, 2879, 5779, 11579, 23159, 46327, 92657, 185323, 370661, 741337,\n 1482707, 2965421, 5930887, 11861791, 23723597, 47447201, 94894427, 189788857, 379577741,\n 759155483, 1518310967,\n\n //chunk #10\n 379, 761, 1523, 3049, 6101, 12203, 24407, 48817, 97649, 195311, 390647, 781301, 1562611,\n 3125257, 6250537, 12501169, 25002389, 50004791, 100009607, 200019221, 400038451, 800076929,\n 1600153859,\n\n //chunk #11\n 13, 29, 59, 127, 257, 521, 1049, 2099, 4201, 8419, 16843, 33703, 67409, 134837, 269683,\n 539389, 1078787, 2157587, 4315183, 8630387, 17260781, 34521589, 69043189, 138086407,\n 276172823, 552345671, 1104691373,\n\n //chunk #12\n 19, 41, 83, 167, 337, 677,\n 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899,\n 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557,\n 359339171, 718678369, 1437356741,\n\n //chunk #13\n 53, 107, 223, 449, 907, 1823, 3659, 7321, 14653, 29311, 58631, 117269,\n 234539, 469099, 938207, 1876417, 3752839, 7505681, 15011389, 30022781,\n 60045577, 120091177, 240182359, 480364727, 960729461, 1921458943\n];\n\nprimeNumbers.sort(sortAsc);\n\nfunction nextPrime(value) {\n let index = binarySearch(primeNumbers, value, sortAsc);\n if (index < 0) {\n index = ~index;\n }\n return primeNumbers[index];\n}\n\nexports.nextPrime = nextPrime;\nexports.largestPrime = largestPrime;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-hash-table/src/primeFinder.js","'use strict';\nmodule.exports = Number.isNaN || function (x) {\n\treturn x !== x;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/number-is-nan/index.js","\"use strict\";\n\nexports.additiveSymmetric = require('./distances/additiveSymmetric');\nexports.avg = require('./distances/avg');\nexports.bhattacharyya = require('./distances/bhattacharyya');\nexports.canberra = require('./distances/canberra');\nexports.chebyshev = require('./distances/chebyshev');\nexports.clark = require('./distances/clark');\nexports.czekanowski = require('./distances/czekanowski');\nexports.dice = require('./distances/dice');\nexports.divergence = require('./distances/divergence');\nexports.euclidean = require('ml-distance-euclidean');\nexports.fidelity = require('./distances/fidelity');\nexports.gower = require('./distances/gower');\nexports.harmonicMean = require('./distances/harmonicMean');\nexports.hellinger = require('./distances/hellinger');\nexports.innerProduct = require('./distances/innerProduct');\nexports.intersection = require('./distances/intersection');\nexports.jaccard = require('./distances/jaccard');\nexports.jeffreys = require('./distances/jeffreys');\nexports.jensenDifference = require('./distances/jensenDifference');\nexports.jensenShannon = require('./distances/jensenShannon');\nexports.kdivergence = require('./distances/kdivergence');\nexports.kulczynski = require('./distances/kulczynski');\nexports.kullbackLeibler = require('./distances/kullbackLeibler');\nexports.kumarHassebrook = require('./distances/kumarHassebrook');\nexports.kumarJohnson = require('./distances/kumarJohnson');\nexports.lorentzian = require('./distances/lorentzian');\nexports.manhattan = require('./distances/manhattan');\nexports.matusita = require('./distances/matusita');\nexports.minkowski = require('./distances/minkowski');\nexports.motyka = require('./distances/motyka');\nexports.neyman = require('./distances/neyman');\nexports.pearson = require('./distances/pearson');\nexports.probabilisticSymmetric = require('./distances/probabilisticSymmetric');\nexports.ruzicka = require('./distances/ruzicka');\nexports.soergel = require('./distances/soergel');\nexports.sorensen = require('./distances/sorensen');\nexports.squared = require('./distances/squared');\nexports.squaredChord = require('./distances/squaredChord');\nexports.squaredEuclidean = require('ml-distance-euclidean').squared;\nexports.taneja = require('./distances/taneja');\nexports.tanimoto = require('./distances/tanimoto');\nexports.topsoe = require('./distances/topsoe');\nexports.tree = require('ml-tree-similarity');\nexports.waveHedges = require('./distances/waveHedges');\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances.js","module.exports = function additiveSymmetric(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i]) * (a[i] + b[i])) / (a[i] * b[i]);\n }\n return 2 * d;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/additiveSymmetric.js","module.exports = function avg(a, b) {\n var ii = a.length,\n max = 0,\n ans = 0,\n aux = 0;\n for (var i = 0; i < ii ; i++) {\n aux = Math.abs(a[i] - b[i]);\n ans += aux;\n if (max < aux) {\n max = aux;\n }\n }\n return (max + ans) / 2;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/avg.js","module.exports = function bhattacharyya(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return - Math.log(ans);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/bhattacharyya.js","module.exports = function canberra(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.abs(a[i] - b[i]) / (a[i] + b[i]);\n }\n return ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/canberra.js","module.exports = function chebyshev(a, b) {\n var ii = a.length,\n max = 0,\n aux = 0;\n for (var i = 0; i < ii ; i++) {\n aux = Math.abs(a[i] - b[i]);\n if (max < aux) {\n max = aux;\n }\n }\n return max;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/chebyshev.js","module.exports = function clark(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.sqrt(((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i])));\n }\n return 2 * d;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/clark.js","'use strict';\n\nconst czekanowskiSimilarity = require('../similarities/czekanowski');\n\nmodule.exports = function czekanowskiDistance(a, b) {\n return 1 - czekanowskiSimilarity(a, b);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/czekanowski.js","module.exports = function divergence(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i]));\n }\n return 2 * d;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/divergence.js","module.exports = function fidelity(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/fidelity.js","module.exports = function gower(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.abs(a[i] - b[i]);\n }\n return ans / ii;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/gower.js","module.exports = function harmonicMean(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] * b[i]) / (a[i] + b[i]);\n }\n return 2 * ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/harmonicMean.js","module.exports = function hellinger(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return 2 * Math.sqrt(1 - ans);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/hellinger.js","module.exports = function innerProduct(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * b[i];\n }\n return ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/innerProduct.js","module.exports = function jeffreys(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] - b[i]) * Math.log(a[i] / b[i]);\n }\n return ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/jeffreys.js","module.exports = function jensenDifference(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += ((a[i] * Math.log(a[i]) + b[i] * Math.log(b[i])) / 2) - ((a[i] + b[i]) / 2) * Math.log((a[i] + b[i]) / 2);\n }\n return ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/jensenDifference.js","module.exports = function jensenShannon(a, b) {\n var ii = a.length,\n p = 0,\n q = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * Math.log(2 * a[i] / (a[i] + b[i]));\n q += b[i] * Math.log(2 * b[i] / (a[i] + b[i]));\n }\n return (p + q) / 2;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/jensenShannon.js","module.exports = function kdivergence(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i]));\n }\n return ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/kdivergence.js","module.exports = function kullbackLeibler(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(a[i] / b[i]);\n }\n return ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/kullbackLeibler.js","module.exports = function kumarHassebrook(a, b) {\n var ii = a.length,\n p = 0,\n p2 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * b[i];\n p2 += a[i] * a[i];\n q2 += b[i] * b[i];\n }\n return p / (p2 + q2 - p);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/kumarHassebrook.js","module.exports = function kumarJohnson(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.pow(a[i] * a[i] - b[i] * b[i],2) / (2 * Math.pow(a[i] * b[i],1.5));\n }\n return ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/kumarJohnson.js","module.exports = function lorentzian(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.log(Math.abs(a[i] - b[i]) + 1);\n }\n return ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/lorentzian.js","module.exports = function manhattan(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.abs(a[i] - b[i]);\n }\n return d;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/manhattan.js","module.exports = function matusita(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return Math.sqrt(2 - 2 * ans);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/matusita.js","module.exports = function minkowski(a, b, p) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.pow(Math.abs(a[i] - b[i]),p);\n }\n return Math.pow(d,(1/p));\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/minkowski.js","module.exports = function neyman(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / a[i];\n }\n return d;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/neyman.js","module.exports = function pearson(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / b[i];\n }\n return d;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/pearson.js","module.exports = function probabilisticSymmetric(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]);\n }\n return 2 * d;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/probabilisticSymmetric.js","module.exports = function ruzicka(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.min(a[i],b[i]);\n down += Math.max(a[i],b[i]);\n }\n return up / down;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/ruzicka.js","module.exports = function soergel(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += Math.max(a[i],b[i]);\n }\n return up / down;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/soergel.js","module.exports = function sorensen(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += a[i] + b[i];\n }\n return up / down;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/sorensen.js","module.exports = function squared(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]);\n }\n return d;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/squared.js","module.exports = function taneja(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] + b[i]) / 2 * Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i])));\n }\n return ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/taneja.js","var tanimotoS = require('./../similarities/tanimoto');\n\nmodule.exports = function tanimoto(a, b, bitvector) {\n if (bitvector)\n return 1 - tanimotoS(a, b, bitvector);\n else {\n var ii = a.length,\n p = 0,\n q = 0,\n m = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i];\n q += b[i];\n m += Math.min(a[i],b[i]);\n }\n return (p + q - 2 * m) / (p + q - m);\n }\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/tanimoto.js","module.exports = function topsoe(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])) + b[i] * Math.log(2 * b[i] / (a[i] + b[i]));\n }\n return ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/topsoe.js","\"use strict\";\n\n/**\n * Function that creates the tree\n * @param {Array } X - chemical shifts of the signal\n * @param {Array } Y - intensity of the signal\n * @param {number} from - the low limit of x\n * @param {number} to - the top limit of x\n * @param {number} minWindow - smallest range to accept in x\n * @param {number} threshold - smallest range to accept in y\n * @returns {{sum: number, center: number, left: {json}, right: {json}}}\n * left and right have the same structure than the parent, or have a\n * undefined value if are leafs\n */\nfunction createTree (X, Y, from, to, minWindow, threshold) {\n minWindow = minWindow || 0.16;\n threshold = threshold || 0.01;\n if ((to - from) < minWindow)\n return undefined;\n var sum = 0;\n for (var i = 0; X[i] < to; i++) {\n if (X[i] > from)\n sum += Y[i];\n }\n if (sum < threshold) {\n return undefined;\n }\n var center = 0;\n for (var j = 0; X[j] < to; j++) {\n if (X[i] > from)\n center += X[j] * Y[j];\n }\n center = center / sum;\n if (((center - from) < 10e-6) || ((to - center) < 10e-6)) return undefined;\n if ((center - from) < (minWindow /4)) {\n return createTree(X, Y, center, to, minWindow, threshold);\n }\n else {\n if ((to - center) < (minWindow / 4)) {\n return createTree(X, Y, from, center, minWindow, threshold);\n }\n else {\n return {\n 'sum': sum,\n 'center': center,\n 'left': createTree(X, Y, from, center, minWindow, threshold),\n 'right': createTree(X, Y, center, to, minWindow, threshold)\n };\n }\n }\n}\n\n/**\n * Similarity between two nodes\n * @param {{sum: number, center: number, left: {json}, right: {json}}} a - tree A node\n * @param {{sum: number, center: number, left: {json}, right: {json}}} b - tree B node\n * @param {number} alpha - weights the relative importance of intensity vs. shift match\n * @param {number} beta - weights the relative importance of node matching and children matching\n * @param {number} gamma - controls the attenuation of the effect of chemical shift differences\n * @returns {number} similarity measure between tree nodes\n */\nfunction S(a, b, alpha, beta, gamma) {\n if (a === undefined || b === undefined) {\n return 0;\n }\n else {\n var C = (alpha*Math.min(a.sum, b.sum)/Math.max(a.sum, b.sum)+ (1-alpha)*Math.exp(-gamma*Math.abs(a.center - b.center)));\n }\n return beta*C + (1-beta)*(S(a.left, b.left, alpha, beta, gamma)+S(a.right, b.right, alpha, beta, gamma));\n}\n\n/**\n * @type {number} alpha - weights the relative importance of intensity vs. shift match\n * @type {number} beta - weights the relative importance of node matching and children matching\n * @type {number} gamma - controls the attenuation of the effect of chemical shift differences\n * @type {number} minWindow - smallest range to accept in x\n * @type {number} threshold - smallest range to accept in y\n */\nvar defaultOptions = {\n minWindow: 0.16,\n threshold : 0.01,\n alpha: 0.1,\n beta: 0.33,\n gamma: 0.001\n};\n\n/**\n * Builds a tree based in the spectra and compares this trees\n * @param {{x: Array, y: Array}} A - first spectra to be compared\n * @param {{x: Array, y: Array}} B - second spectra to be compared\n * @param {number} from - the low limit of x\n * @param {number} to - the top limit of x\n * @param {{minWindow: number, threshold: number, alpha: number, beta: number, gamma: number}} options\n * @returns {number} similarity measure between the spectra\n */\nfunction tree(A, B, from, to, options) {\n options = options || {};\n for (var o in defaultOptions)\n if (!options.hasOwnProperty(o)) {\n options[o] = defaultOptions[o];\n }\n var Atree, Btree;\n if (A.sum)\n Atree = A;\n else\n Atree = createTree(A.x, A.y, from, to, options.minWindow, options.threshold);\n if (B.sum)\n Btree = B;\n else\n Btree = createTree(B.x, B.y, from, to, options.minWindow, options.threshold);\n return S(Atree, Btree, options.alpha, options.beta, options.gamma);\n}\n\nmodule.exports = {\n calc: tree,\n createTree: createTree\n};\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-tree-similarity/src/index.js","module.exports = function waveHedges(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += 1 - (Math.min(a[i], b[i]) / Math.max(a[i], b[i]));\n }\n return ans;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/distances/waveHedges.js","\"use strict\";\n\nexports.cosine = require('./similarities/cosine');\nexports.czekanowski = require('./similarities/czekanowski');\nexports.dice = require('./similarities/dice');\nexports.intersection = require('./similarities/intersection');\nexports.jaccard = require('./similarities/jaccard');\nexports.kulczynski = require('./similarities/kulczynski');\nexports.motyka = require('./similarities/motyka');\nexports.pearson = require('./similarities/pearson');\nexports.squaredChord = require('./similarities/squaredChord');\nexports.tanimoto = require('./similarities/tanimoto');\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/similarities.js","var diceD = require('./../distances/dice');\n\nmodule.exports = function dice(a, b) {\n return 1 - diceD(a,b);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/similarities/dice.js","var intersectionD = require('./../distances/intersection');\n\nmodule.exports = function intersection(a, b) {\n return 1 - intersectionD(a,b);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/similarities/intersection.js","var jaccardD = require('./../distances/jaccard');\n\nmodule.exports = function jaccard(a, b) {\n return 1 - jaccardD(a, b);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/similarities/jaccard.js","var kulczynskiD = require('./../distances/kulczynski');\n\nmodule.exports = function kulczynski(a, b) {\n return 1 / kulczynskiD(a, b);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/similarities/kulczynski.js","var motykaD = require('./../distances/motyka');\n\nmodule.exports = function motyka(a, b) {\n return 1 - motykaD(a,b);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-distance/src/similarities/motyka.js","'use strict';\n\nvar stat=require('ml-stat').array;\nvar cosine=require('./cosine');\n\nmodule.exports = function pearson(a, b) {\n var avgA=stat.mean(a);\n var avgB=stat.mean(b);\n\n var newA=new Array(a.length);\n var newB=new Array(b.length);\n for (var i=0; i a.pred - b.pred);\n } else {\n predP.sort((a, b) => b.pred - a.pred);\n }\n \n const cutoffs = this.cutoffs = [isDistance ? Number.MIN_VALUE : Number.MAX_VALUE];\n const fp = this.fp = [0];\n const tp = this.tp = [0];\n\n var nPos = 0;\n var nNeg = 0;\n\n var currentPred = predP[0].pred;\n var nTp = 0;\n var nFp = 0;\n for (var i = 0; i < predP.length; i++) {\n if (predP[i].pred !== currentPred) {\n cutoffs.push(currentPred);\n fp.push(nFp);\n tp.push(nTp);\n currentPred = predP[i].pred;\n }\n if (predP[i].targ) {\n nPos++;\n nTp++;\n } else {\n nNeg++;\n nFp++;\n }\n }\n cutoffs.push(currentPred);\n fp.push(nFp);\n tp.push(nTp);\n\n const l = cutoffs.length;\n const fn = this.fn = new Array(l);\n const tn = this.tn = new Array(l);\n const nPosPred = this.nPosPred = new Array(l);\n const nNegPred = this.nNegPred = new Array(l);\n\n for (var i = 0; i < l; i++) {\n fn[i] = nPos - tp[i];\n tn[i] = nNeg - fp[i];\n\n nPosPred[i] = tp[i] + fp[i];\n nNegPred[i] = tn[i] + fn[i];\n }\n\n this.nPos = nPos;\n this.nNeg = nNeg;\n this.nSamples = nPos + nNeg;\n }\n\n /**\n * Computes a measure from the prediction object.\n *\n * Many measures are available and can be combined :\n * To create a ROC curve, you need fpr and tpr\n * To create a DET curve, you need fnr and fpr\n * To create a Lift chart, you need rpp and lift\n *\n * Possible measures are : threshold (Threshold), acc (Accuracy), err (Error rate),\n * fpr (False positive rate), tpr (True positive rate), fnr (False negative rate), tnr (True negative rate), ppv (Positive predictive value),\n * npv (Negative predictive value), pcfall (Prediction-conditioned fallout), pcmiss (Prediction-conditioned miss), lift (Lift value), rpp (Rate of positive predictions), rnp (Rate of negative predictions)\n *\n * @param measure - The short name of the measure\n *\n * @return [number]\n */\n getMeasure(measure) {\n if (typeof measure !== 'string') {\n throw new Error('No measure specified');\n }\n if (!measures[measure]) {\n throw new Error(`The specified measure (${measure}) does not exist`);\n }\n return measures[measure](this);\n }\n\n /**\n * Returns the area under the ROC curve\n */\n getAURC() {\n const l = this.cutoffs.length;\n const x = new Array(l);\n const y = new Array(l);\n for (var i = 0; i < l; i++) {\n x[i] = this.fp[i] / this.nNeg;\n y[i] = this.tp[i] / this.nPos;\n }\n var auc = 0;\n for (i = 1; i < l; i++) {\n auc += 0.5 * (x[i] - x[i - 1]) * (y[i] + y[i - 1]);\n }\n return auc;\n }\n\n /**\n * Returns the area under the DET curve\n */\n getAUDC() {\n const l = this.cutoffs.length;\n const x = new Array(l);\n const y = new Array(l);\n for (var i = 0; i < l; i++) {\n x[i] = this.fn[i] / this.nPos;\n y[i] = this.fp[i] / this.nNeg;\n }\n var auc = 0;\n for (i = 1; i < l; i++) {\n auc += 0.5 * (x[i] + x[i - 1]) * (y[i] - y[i - 1]);\n }\n return auc;\n }\n\n getDistribution(options) {\n options = options || {};\n var cutLength = this.cutoffs.length;\n var cutLow = options.xMin || Math.floor(this.cutoffs[cutLength - 1] * 100) / 100;\n var cutHigh = options.xMax || Math.ceil(this.cutoffs[1] * 100) / 100;\n var interval = options.interval || Math.floor(((cutHigh - cutLow) / 20 * 10000000) - 1) / 10000000; // Trick to avoid the precision problem of float numbers\n\n var xLabels = [];\n var interValues = [];\n var intraValues = [];\n var interCumPercent = [];\n var intraCumPercent = [];\n\n var nTP = this.tp[cutLength - 1], currentTP = 0;\n var nFP = this.fp[cutLength - 1], currentFP = 0;\n\n for (var i = cutLow, j = (cutLength - 1); i <= cutHigh; i += interval) {\n while (this.cutoffs[j] < i)\n j--;\n\n xLabels.push(i);\n\n var thisTP = nTP - currentTP - this.tp[j];\n var thisFP = nFP - currentFP - this.fp[j];\n\n currentTP += thisTP;\n currentFP += thisFP;\n\n interValues.push(thisFP);\n intraValues.push(thisTP);\n\n interCumPercent.push(100 - (nFP - this.fp[j]) / nFP * 100);\n intraCumPercent.push(100 - (nTP - this.tp[j]) / nTP * 100);\n }\n\n return {\n xLabels: xLabels,\n interValues: interValues,\n intraValues: intraValues,\n interCumPercent: interCumPercent,\n intraCumPercent: intraCumPercent\n };\n }\n}\n\nPerformance.names = {\n acc: 'Accuracy',\n err: 'Error rate',\n fpr: 'False positive rate',\n tpr: 'True positive rate',\n fnr: 'False negative rate',\n tnr: 'True negative rate',\n ppv: 'Positive predictive value',\n npv: 'Negative predictive value',\n pcfall: 'Prediction-conditioned fallout',\n pcmiss: 'Prediction-conditioned miss',\n lift: 'Lift value',\n rpp: 'Rate of positive predictions',\n rnp: 'Rate of negative predictions',\n threshold: 'Threshold'\n};\n\nmodule.exports = Performance;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-performance/src/index.js","'use strict';\n\n// Accuracy\nexports.acc = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.tn[i] + pred.tp[i]) / (l - 1);\n }\n return result;\n};\n\n// Error rate\nexports.err = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.fp[i] / (l - 1));\n }\n return result;\n};\n\n// False positive rate\nexports.fpr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.fp[i] / pred.nNeg;\n }\n return result;\n};\n\n// True positive rate\nexports.tpr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.tp[i] / pred.nPos;\n }\n return result;\n};\n\n// False negative rate\nexports.fnr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.fn[i] / pred.nPos;\n }\n return result;\n};\n\n// True negative rate\nexports.tnr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.tn[i] / pred.nNeg;\n }\n return result;\n};\n\n// Positive predictive value\nexports.ppv = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 0;\n }\n return result;\n};\n\n// Negative predictive value\nexports.npv = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 0;\n }\n return result;\n};\n\n// Prediction conditioned fallout\nexports.pcfall = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? 1 - (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 1;\n }\n return result;\n};\n\n// Prediction conditioned miss\nexports.pcmiss = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? 1 - (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 1;\n }\n return result;\n};\n\n// Lift value\nexports.lift = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.nPosPred[i] !== 0) ? ((pred.tp[i] / pred.nPos) / (pred.nPosPred[i] / pred.nSamples)) : 0;\n }\n return result;\n};\n\n// Rate of positive predictions\nexports.rpp = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.nPosPred[i] / pred.nSamples;\n }\n return result;\n};\n\n// Rate of negative predictions\nexports.rnp = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.nNegPred[i] / pred.nSamples;\n }\n return result;\n};\n\n// Threshold\nexports.threshold = pred => {\n const clone = pred.cutoffs.slice();\n clone[0] = clone[1]; // Remove the infinite value\n return clone;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-performance/src/measures.js","'use strict';\n\nvar matrixLib = require('ml-matrix');\nvar Matrix = matrixLib.Matrix;\nvar inverse = matrixLib.inverse;\nvar padArray = require('ml-pad-array');\nvar extend = require('extend');\n\nvar defaultOptions = {\n windowSize: 5,\n derivative: 1,\n polynomial: 2,\n pad: 'none',\n padValue: 'replicate'\n};\n\n/**\n * Savitzky-Golay filter\n * @param {Array } data\n * @param {number} h\n * @param {Object} options\n * @returns {Array}\n */\nfunction SavitzkyGolay (data, h, options) {\n options = extend({}, defaultOptions, options);\n if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize)))\n throw new RangeError('Invalid window size (should be odd and at least 5 integer number)');\n if ((options.derivative < 0) || !(Number.isInteger(options.derivative)))\n throw new RangeError('Derivative should be a positive integer');\n if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial)))\n throw new RangeError('Polynomial should be a positive integer');\n\n var C, norm;\n var step = Math.floor(options.windowSize / 2);\n\n if (options.pad === 'pre') {\n data = padArray(data, {size: step, value: options.padValue});\n }\n\n var ans = new Array(data.length - 2*step);\n\n if ((options.windowSize === 5) && (options.polynomial === 2) && ((options.derivative === 1) || (options.derivative === 2))) {\n if (options.derivative === 1) {\n C = [-2,-1,0,1,2];\n norm = 10;\n }\n else {\n C = [2, -1, -2, -1, 2];\n norm = 7;\n }\n }\n else {\n var J = Matrix.ones(options.windowSize, options.polynomial + 1);\n var inic = -(options.windowSize - 1) / 2;\n for (var i = 0; i < J.length; i++) {\n for (var j = 0; j < J[i].length; j++) {\n if ((inic + 1 !== 0) || (j !== 0))\n J[i][j] = Math.pow((inic + i), j);\n }\n }\n var Jtranspose = J.transposeView();\n var Jinv = inverse(Jtranspose.mmul(J));\n C = Jinv.mmul(Jtranspose);\n C = C[options.derivative];\n norm = 1;\n }\n var det = norm * Math.pow(h, options.derivative);\n for (var k = step; k < (data.length - step); k++) {\n var d = 0;\n for (var l = 0; l < C.length; l++)\n d += C[l] * data[l + k - step] / det;\n ans[k - step] = d;\n }\n\n if (options.pad === 'post') {\n ans = padArray(ans, {size: step, value: options.padValue});\n }\n\n return ans;\n}\n\nmodule.exports = SavitzkyGolay;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-savitzky-golay/src/index.js","//Code translate from Pascal source in http://pubs.acs.org/doi/pdf/10.1021/ac00205a007\nvar extend = require('extend');\nvar stat = require('ml-stat');\n\nvar defaultOptions = {\n windowSize: 9,\n derivative: 0,\n polynomial: 3,\n};\n\n\nfunction SavitzkyGolay(data, h, options) {\n options = extend({}, defaultOptions, options);\n\n if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize)))\n throw new RangeError('Invalid window size (should be odd and at least 5 integer number)')\n\n\n if (options.windowSize>data.length)\n throw new RangeError('Window size is higher than the data length '+options.windowSize+\">\"+data.length);\n if ((options.derivative < 0) || !(Number.isInteger(options.derivative)))\n throw new RangeError('Derivative should be a positive integer');\n if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial)))\n throw new RangeError('Polynomial should be a positive integer');\n if (options.polynomial >= 6)\n console.warn('You should not use polynomial grade higher than 5 if you are' +\n ' not sure that your data arises from such a model. Possible polynomial oscillation problems');\n\n var windowSize = options.windowSize;\n\n var half = Math.floor(windowSize/2);\n var np = data.length;\n var ans = new Array(np);\n var weights = fullWeights(windowSize,options.polynomial,options.derivative);\n var hs = 0;\n var constantH = true;\n if( Object.prototype.toString.call( h ) === '[object Array]' ) {\n constantH = false;\n }\n else{\n hs = Math.pow(h, options.derivative);\n }\n //console.log(\"Constant h: \"+constantH);\n //For the borders\n for(var i=0;i=0 && i < h.length-1){\n hs+= (h[i+1]-h[i]);\n count++;\n }\n }\n return Math.pow(hs/count,derivative);\n}\n\nfunction GramPoly(i,m,k,s){\n var Grampoly = 0;\n if(k>0){\n Grampoly = (4*k-2)/(k*(2*m-k+1))*(i*GramPoly(i,m,k-1,s) +\n s*GramPoly(i,m,k-1,s-1)) - ((k-1)*(2*m+k))/(k*(2*m-k+1))*GramPoly(i,m,k-2,s);\n }\n else{\n if(k==0&&s==0){\n Grampoly=1;\n }\n else{\n Grampoly=0;\n }\n }\n //console.log(Grampoly);\n return Grampoly;\n}\n\nfunction GenFact(a,b){\n var gf=1;\n if(a>=b){\n for(var j=a-b+1;j<=a;j++){\n gf*=j;\n }\n }\n return gf;\n}\n\nfunction Weight(i,t,m,n,s){\n var sum=0;\n for(var k=0;k<=n;k++){\n //console.log(k);\n sum+=(2*k+1)*(GenFact(2*m,k)/GenFact(2*m+k+1,k+1))*GramPoly(i,m,k,0)*GramPoly(t,m,k,s)\n }\n return sum;\n}\n\n/**\n *\n * @param m Number of points\n * @param n Polynomial grade\n * @param s Derivative\n */\nfunction fullWeights(m,n,s){\n var weights = new Array(m);\n var np = Math.floor(m/2);\n for(var t=-np;t<=np;t++){\n weights[t+np] = new Array(m);\n for(var j=-np;j<=np;j++){\n weights[t+np][j+np]=Weight(j,t,np,n,s);\n }\n }\n return weights;\n}\n\n/*function entropy(data,h,options){\n var trend = SavitzkyGolay(data,h,trendOptions);\n var copy = new Array(data.length);\n var sum = 0;\n var max = 0;\n for(var i=0;i> 8) & 0xff] + eightBits[(arr[i] >> 16) & 0xff] + eightBits[(arr[i] >> 24) & 0xff];\n }\n return c;\n}\n\n/**\n * Logical AND operation\n * @param {Array} arr1\n * @param {Array} arr2\n * @return {Array}\n */\nfunction and(arr1, arr2) {\n var ans = new Array(arr1.length);\n for (var i = 0; i < arr1.length; i++)\n ans[i] = arr1[i] & arr2[i];\n return ans;\n}\n\n/**\n * Logical OR operation\n * @param {Array} arr1\n * @param {Array} arr2\n * @return {Array}\n */\nfunction or(arr1, arr2) {\n var ans = new Array(arr1.length);\n for (var i = 0; i < arr1.length; i++)\n ans[i] = arr1[i] | arr2[i];\n return ans;\n}\n\n/**\n * Logical XOR operation\n * @param {Array} arr1\n * @param {Array} arr2\n * @return {Array}\n */\nfunction xor(arr1, arr2) {\n var ans = new Array(arr1.length);\n for (var i = 0; i < arr1.length; i++)\n ans[i] = arr1[i] ^ arr2[i];\n return ans;\n}\n\n/**\n * Logical NOT operation\n * @param {Array} arr\n * @return {Array}\n */\nfunction not(arr) {\n var ans = new Array(arr.length);\n for (var i = 0; i < ans.length; i++)\n ans[i] = ~arr[i];\n return ans;\n}\n\n/**\n * Gets the n value of array arr\n * @param {Array} arr\n * @param {number} n\n * @return {boolean}\n */\nfunction getBit(arr, n) {\n var index = n >> 5; // Same as Math.floor(n/32)\n var mask = 1 << (31 - n % 32);\n return Boolean(arr[index] & mask);\n}\n\n/**\n * Sets the n value of array arr to the value val\n * @param {Array} arr\n * @param {number} n\n * @param {boolean} val\n * @return {Array}\n */\nfunction setBit(arr, n, val) {\n var index = n >> 5; // Same as Math.floor(n/32)\n var mask = 1 << (31 - n % 32);\n if (val)\n arr[index] = mask | arr[index];\n else\n arr[index] = ~mask & arr[index];\n return arr;\n}\n\n/**\n * Translates an array of numbers to a string of bits\n * @param {Array} arr\n * @returns {string}\n */\nfunction toBinaryString(arr) {\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n var obj = (arr[i] >>> 0).toString(2);\n str += '00000000000000000000000000000000'.substr(obj.length) + obj;\n }\n return str;\n}\n\n/**\n * Creates an array of numbers based on a string of bits\n * @param {string} str\n * @returns {Array}\n */\nfunction parseBinaryString(str) {\n var len = str.length / 32;\n var ans = new Array(len);\n for (var i = 0; i < len; i++) {\n ans[i] = parseInt(str.substr(i*32, 32), 2) | 0;\n }\n return ans;\n}\n\n/**\n * Translates an array of numbers to a hex string\n * @param {Array} arr\n * @returns {string}\n */\nfunction toHexString(arr) {\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n var obj = (arr[i] >>> 0).toString(16);\n str += '00000000'.substr(obj.length) + obj;\n }\n return str;\n}\n\n/**\n * Creates an array of numbers based on a hex string\n * @param {string} str\n * @returns {Array}\n */\nfunction parseHexString(str) {\n var len = str.length / 8;\n var ans = new Array(len);\n for (var i = 0; i < len; i++) {\n ans[i] = parseInt(str.substr(i*8, 8), 16) | 0;\n }\n return ans;\n}\n\n/**\n * Creates a human readable string of the array\n * @param {Array} arr\n * @returns {string}\n */\nfunction toDebug(arr) {\n var binary = toBinaryString(arr);\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n str += '0000'.substr((i * 32).toString(16).length) + (i * 32).toString(16) + ':';\n for (var j = 0; j < 32; j += 4) {\n str += ' ' + binary.substr(i * 32 + j, 4);\n }\n if (i < arr.length - 1) str += '\\n';\n }\n return str\n}\n\nmodule.exports = {\n count: count,\n and: and,\n or: or,\n xor: xor,\n not: not,\n getBit: getBit,\n setBit: setBit,\n toBinaryString: toBinaryString,\n parseBinaryString: parseBinaryString,\n toHexString: toHexString,\n parseHexString: parseHexString,\n toDebug: toDebug\n};\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-bit-array/src/index.js","// auxiliary file to create the 256 look at table elements\n\nvar ans = new Array(256);\nfor (var i = 0; i < 256; i++) {\n var num = i;\n var c = 0;\n while (num) {\n num = num & (num - 1);\n c++;\n }\n ans[i] = c;\n}\n\nmodule.exports = ans;\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-bit-array/src/creator.js","'use strict';\n\nmodule.exports = exports = require('./ArrayUtils');\n\nexports.getEquallySpacedData = require('./getEquallySpaced').getEquallySpacedData;\nexports.SNV = require('./snv').SNV;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-array-utils/src/index.js","'use strict';\n\nconst Stat = require('ml-stat').array;\n/**\n * Function that returns an array of points given 1D array as follows:\n *\n * [x1, y1, .. , x2, y2, ..]\n *\n * And receive the number of dimensions of each point.\n * @param array\n * @param dimensions\n * @returns {Array} - Array of points.\n */\nfunction coordArrayToPoints(array, dimensions) {\n if (array.length % dimensions !== 0) {\n throw new RangeError('Dimensions number must be accordance with the size of the array.');\n }\n\n var length = array.length / dimensions;\n var pointsArr = new Array(length);\n\n var k = 0;\n for (var i = 0; i < array.length; i += dimensions) {\n var point = new Array(dimensions);\n for (var j = 0; j < dimensions; ++j) {\n point[j] = array[i + j];\n }\n\n pointsArr[k] = point;\n k++;\n }\n\n return pointsArr;\n}\n\n\n/**\n * Function that given an array as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * Returns an array as follows:\n * [[x1, x2, ..], [y1, y2, ..], [ .. ]]\n *\n * And receives the number of dimensions of each coordinate.\n * @param array\n * @param dimensions\n * @returns {Array} - Matrix of coordinates\n */\nfunction coordArrayToCoordMatrix(array, dimensions) {\n if (array.length % dimensions !== 0) {\n throw new RangeError('Dimensions number must be accordance with the size of the array.');\n }\n\n var coordinatesArray = new Array(dimensions);\n var points = array.length / dimensions;\n for (var i = 0; i < coordinatesArray.length; i++) {\n coordinatesArray[i] = new Array(points);\n }\n\n for (i = 0; i < array.length; i += dimensions) {\n for (var j = 0; j < dimensions; ++j) {\n var currentPoint = Math.floor(i / dimensions);\n coordinatesArray[j][currentPoint] = array[i + j];\n }\n }\n\n return coordinatesArray;\n}\n\n/**\n * Function that receives a coordinate matrix as follows:\n * [[x1, x2, ..], [y1, y2, ..], [ .. ]]\n *\n * Returns an array of coordinates as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * @param coordMatrix\n * @returns {Array}\n */\nfunction coordMatrixToCoordArray(coordMatrix) {\n var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length);\n var k = 0;\n for (var i = 0; i < coordMatrix[0].length; ++i) {\n for (var j = 0; j < coordMatrix.length; ++j) {\n coodinatesArray[k] = coordMatrix[j][i];\n ++k;\n }\n }\n\n return coodinatesArray;\n}\n\n/**\n * Tranpose a matrix, this method is for coordMatrixToPoints and\n * pointsToCoordMatrix, that because only transposing the matrix\n * you can change your representation.\n *\n * @param matrix\n * @returns {Array}\n */\nfunction transpose(matrix) {\n var resultMatrix = new Array(matrix[0].length);\n for (var i = 0; i < resultMatrix.length; ++i) {\n resultMatrix[i] = new Array(matrix.length);\n }\n\n for (i = 0; i < matrix.length; ++i) {\n for (var j = 0; j < matrix[0].length; ++j) {\n resultMatrix[j][i] = matrix[i][j];\n }\n }\n\n return resultMatrix;\n}\n\n/**\n * Function that transform an array of points into a coordinates array\n * as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * @param points\n * @returns {Array}\n */\nfunction pointsToCoordArray(points) {\n var coodinatesArray = new Array(points.length * points[0].length);\n var k = 0;\n for (var i = 0; i < points.length; ++i) {\n for (var j = 0; j < points[0].length; ++j) {\n coodinatesArray[k] = points[i][j];\n ++k;\n }\n }\n\n return coodinatesArray;\n}\n\n/**\n * Apply the dot product between the smaller vector and a subsets of the\n * largest one.\n *\n * @param firstVector\n * @param secondVector\n * @returns {Array} each dot product of size of the difference between the\n * larger and the smallest one.\n */\nfunction applyDotProduct(firstVector, secondVector) {\n var largestVector, smallestVector;\n if (firstVector.length <= secondVector.length) {\n smallestVector = firstVector;\n largestVector = secondVector;\n } else {\n smallestVector = secondVector;\n largestVector = firstVector;\n }\n\n var difference = largestVector.length - smallestVector.length + 1;\n var dotProductApplied = new Array(difference);\n\n for (var i = 0; i < difference; ++i) {\n var sum = 0;\n for (var j = 0; j < smallestVector.length; ++j) {\n sum += smallestVector[j] * largestVector[i + j];\n }\n dotProductApplied[i] = sum;\n }\n\n return dotProductApplied;\n}\n/**\n * To scale the input array between the specified min and max values. The operation is performed inplace\n * if the options.inplace is specified. If only one of the min or max parameters is specified, then the scaling\n * will multiply the input array by min/min(input) or max/max(input)\n * @param input\n * @param options\n * @returns {*}\n */\nfunction scale(input, options = {}) {\n const {\n min,\n max\n } = options;\n\n var y = options.inPlace ? input : (new Array(input.length));\n var minMax = Stat.minMax(input);\n\n if (typeof max === 'number') {\n if (typeof min === 'number') {\n let factor = (max - min) / (minMax.max - minMax.min);\n for (let i = 0; i < y.length; i++) {\n y[i] = (input[i] - minMax.min) * factor + min;\n }\n } else if (minMax.max !== 0) {\n let factor = max / minMax.max;\n for (let i = 0; i < y.length; i++) {\n y[i] = input[i] * factor;\n }\n } else {\n options.min = minMax.min;\n y = scale(input, options);\n }\n } else if (typeof min === 'number') {\n if (minMax.min !== 0) {\n let factor = min / minMax.min;\n for (let i = 0; i < y.length; i++) {\n y[i] = input[i] * factor;\n }\n\n } else {\n options.max = minMax.max;\n y = scale(input, options);\n }\n }\n return y;\n}\n\nmodule.exports = {\n coordArrayToPoints: coordArrayToPoints,\n coordArrayToCoordMatrix: coordArrayToCoordMatrix,\n coordMatrixToCoordArray: coordMatrixToCoordArray,\n coordMatrixToPoints: transpose,\n pointsToCoordArray: pointsToCoordArray,\n pointsToCoordMatrix: transpose,\n applyDotProduct: applyDotProduct,\n scale: scale\n};\n\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-array-utils/src/ArrayUtils.js","'use strict';\n\n/**\n *\n * Function that returns a Number array of equally spaced numberOfPoints\n * containing a representation of intensities of the spectra arguments x\n * and y.\n *\n * The options parameter contains an object in the following form:\n * from: starting point\n * to: last point\n * numberOfPoints: number of points between from and to\n * variant: \"slot\" or \"smooth\" - smooth is the default option\n *\n * The slot variant consist that each point in the new array is calculated\n * averaging the existing points between the slot that belongs to the current\n * value. The smooth variant is the same but takes the integral of the range\n * of the slot and divide by the step size between two points in the new array.\n *\n * @param x - sorted increasing x values\n * @param y\n * @param options\n * @returns {Array} new array with the equally spaced data.\n *\n */\nfunction getEquallySpacedData(x, y, options = {}) {\n var xLength = x.length;\n if (x.length > 1 && x[0] > x[1]) {\n x = x.slice().reverse();\n y = y.slice().reverse();\n }\n\n var {\n from = x[0],\n to = x[xLength - 1],\n variant = 'smooth',\n numberOfPoints = 100\n } = options;\n\n if (xLength !== y.length) {\n throw new RangeError(\"the x and y vector doesn't have the same size.\");\n }\n\n if (typeof from !== 'number' || isNaN(from)) {\n throw new RangeError(\"'from' option must be a number\");\n }\n\n if (typeof to !== 'number' || isNaN(to)) {\n throw new RangeError(\"'to' option must be a number\");\n }\n\n var reverse = from > to;\n if (reverse) {\n [from, to] = [to, from];\n }\n\n if (typeof numberOfPoints !== 'number' || isNaN(numberOfPoints)) {\n throw new RangeError(\"'numberOfPoints' option must be a number\");\n }\n if (numberOfPoints < 1) {\n throw new RangeError('the number of points must be at least 1');\n }\n\n var output = variant === 'slot' ? getEquallySpacedSlot(x, y, from, to, numberOfPoints) : getEquallySpacedSmooth(x, y, from, to, numberOfPoints);\n\n return reverse ? output.reverse() : output;\n}\n\n/**\n * function that retrieves the getEquallySpacedData with the variant \"smooth\"\n *\n * @param x\n * @param y\n * @param from - Initial point\n * @param to - Final point\n * @param numberOfPoints\n * @returns {Array} - Array of y's equally spaced with the variant \"smooth\"\n */\nfunction getEquallySpacedSmooth(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n\n var output = new Array(numberOfPoints);\n\n var initialOriginalStep = x[1] - x[0];\n var lastOriginalStep = x[xLength - 1] - x[xLength - 2];\n\n // Init main variables\n var min = from - halfStep;\n var max = from + halfStep;\n\n var previousX = Number.MIN_VALUE;\n var previousY = 0;\n var nextX = x[0] - initialOriginalStep;\n var nextY = 0;\n\n var currentValue = 0;\n var slope = 0;\n var intercept = 0;\n var sumAtMin = 0;\n var sumAtMax = 0;\n\n var i = 0; // index of input\n var j = 0; // index of output\n\n function getSlope(x0, y0, x1, y1) {\n return (y1 - y0) / (x1 - x0);\n }\n\n main: while (true) {\n\n if (previousX <= min && min <= nextX) {\n add = integral(0, min - previousX, slope, previousY);\n sumAtMin = currentValue + add;\n }\n\n while (nextX - max >= 0) {\n // no overlap with original point, just consume current value\n var add = integral(0, max - previousX, slope, previousY);\n sumAtMax = currentValue + add;\n\n output[j++] = (sumAtMax - sumAtMin) / step;\n\n if (j === numberOfPoints) {\n break main;\n }\n\n min = max;\n max += step;\n sumAtMin = sumAtMax;\n }\n\n currentValue += integral(previousX, nextX, slope, intercept);\n\n previousX = nextX;\n previousY = nextY;\n\n if (i < xLength) {\n nextX = x[i];\n nextY = y[i];\n i++;\n } else if (i === xLength) {\n nextX += lastOriginalStep;\n nextY = 0;\n }\n\n slope = getSlope(previousX, previousY, nextX, nextY);\n intercept = -slope * previousX + previousY;\n }\n\n return output;\n}\n\n/**\n * function that retrieves the getEquallySpacedData with the variant \"slot\"\n *\n * @param x\n * @param y\n * @param from - Initial point\n * @param to - Final point\n * @param numberOfPoints\n * @returns {Array} - Array of y's equally spaced with the variant \"slot\"\n */\nfunction getEquallySpacedSlot(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n var lastStep = x[x.length - 1] - x[x.length - 2];\n\n var start = from - halfStep;\n var output = new Array(numberOfPoints);\n\n // Init main variables\n var min = start;\n var max = start + step;\n\n var previousX = -Number.MAX_VALUE;\n var previousY = 0;\n var nextX = x[0];\n var nextY = y[0];\n var frontOutsideSpectra = 0;\n var backOutsideSpectra = true;\n\n var currentValue = 0;\n\n // for slot algorithm\n var currentPoints = 0;\n\n var i = 1; // index of input\n var j = 0; // index of output\n\n main: while (true) {\n if (previousX >= nextX) throw (new Error('x must be an increasing serie'));\n while (previousX - max > 0) {\n // no overlap with original point, just consume current value\n if (backOutsideSpectra) {\n currentPoints++;\n backOutsideSpectra = false;\n }\n\n output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints;\n j++;\n\n if (j === numberOfPoints) {\n break main;\n }\n\n min = max;\n max += step;\n currentValue = 0;\n currentPoints = 0;\n }\n\n if (previousX > min) {\n currentValue += previousY;\n currentPoints++;\n }\n\n if (previousX === -Number.MAX_VALUE || frontOutsideSpectra > 1) {\n currentPoints--;\n }\n\n previousX = nextX;\n previousY = nextY;\n\n if (i < xLength) {\n nextX = x[i];\n nextY = y[i];\n i++;\n } else {\n nextX += lastStep;\n nextY = 0;\n frontOutsideSpectra++;\n }\n }\n\n return output;\n}\n/**\n * Function that calculates the integral of the line between two\n * x-coordinates, given the slope and intercept of the line.\n * @param x0\n * @param x1\n * @param slope\n * @param intercept\n * @returns {number} integral value.\n */\nfunction integral(x0, x1, slope, intercept) {\n return (0.5 * slope * x1 * x1 + intercept * x1) - (0.5 * slope * x0 * x0 + intercept * x0);\n}\n\nexports.getEquallySpacedData = getEquallySpacedData;\nexports.integral = integral;\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-array-utils/src/getEquallySpaced.js","'use strict';\n\nexports.SNV = SNV;\nvar Stat = require('ml-stat').array;\n\n/**\n * Function that applies the standard normal variate (SNV) to an array of values.\n *\n * @param data - Array of values.\n * @returns {Array} - applied the SNV.\n */\nfunction SNV(data) {\n var mean = Stat.mean(data);\n var std = Stat.standardDeviation(data);\n var result = data.slice();\n for (var i = 0; i < data.length; i++) {\n result[i] = (result[i] - mean) / std;\n }\n return result;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-array-utils/src/snv.js","/**\n * Computes the mode of the given values\n * @param {Array} input\n * @return {number}\n */\nexport default function mode(input) {\n if (!Array.isArray(input)) {\n throw new Error('input must be an array');\n }\n if (input.length === 0) {\n throw new Error('input must not be empty');\n }\n\n var maxValue = 0;\n var maxCount = 0;\n var count = 0;\n var counts = {};\n\n for (var i = 0; i < input.length; ++i) {\n var element = input[i];\n count = counts[element];\n if (count) {\n counts[element]++;\n count++;\n } else {\n counts[element] = count = 1;\n }\n\n if (count > maxCount) {\n maxCount = count;\n maxValue = input[i];\n }\n }\n\n return maxValue;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-array-mode/src/index.js","import variance from 'ml-array-variance';\n\n/**\n * Computes the standard deviation of the given values\n * @param {Array} values\n * @param {object} [options]\n * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n.\n * @param {number} [options.mean = arrayMean] - precalculated mean, if any.\n * @return {number}\n */\nexport default function standardDeviation(values, options = {}) {\n return Math.sqrt(variance(values, options));\n}\n\n\n\n// WEBPACK FOOTER //\n// ./node_modules/ml-array-standard-deviation/src/index.js"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://ML/webpack/universalModuleDefinition","webpack://ML/webpack/bootstrap","webpack://ML/./node_modules/ml-matrix/src/dc/lu.js","webpack://ML/./node_modules/ml-matrix/src/dc/util.js","webpack://ML/./node_modules/ml-matrix/src/dc/svd.js","webpack://ML/./node_modules/ml-matrix/src/util.js","webpack://ML/./node_modules/ml-matrix/src/views/base.js","webpack://ML/./node_modules/ml-matrix/src/views/transpose.js","webpack://ML/./node_modules/ml-matrix/src/views/row.js","webpack://ML/./node_modules/ml-matrix/src/views/sub.js","webpack://ML/./node_modules/ml-matrix/src/views/selection.js","webpack://ML/./node_modules/ml-matrix/src/views/rowSelection.js","webpack://ML/./node_modules/ml-matrix/src/views/columnSelection.js","webpack://ML/./node_modules/ml-matrix/src/views/column.js","webpack://ML/./node_modules/ml-matrix/src/views/flipRow.js","webpack://ML/./node_modules/ml-matrix/src/views/flipColumn.js","webpack://ML/./node_modules/ml-matrix/src/abstractMatrix.js","webpack://ML/./node_modules/ml-matrix/src/matrix.js","webpack://ML/./node_modules/ml-matrix/src/wrap/WrapperMatrix1D.js","webpack://ML/./node_modules/ml-matrix/src/wrap/WrapperMatrix2D.js","webpack://ML/./node_modules/ml-matrix/src/wrap/wrap.js","webpack://ML/./node_modules/ml-matrix/src/dc/qr.js","webpack://ML/./node_modules/ml-matrix/src/decompositions.js","webpack://ML/./node_modules/ml-matrix/src/linearDependencies.js","webpack://ML/./node_modules/ml-matrix/src/dc/evd.js","webpack://ML/./node_modules/ml-matrix/src/dc/cholesky.js","webpack://ML/./node_modules/ml-matrix/src/index.js","webpack://ML/./node_modules/is-any-array/src/index.js","webpack://ML/./node_modules/ml-distance-euclidean/euclidean.js","webpack://ML/./node_modules/ml-stat/index.js","webpack://ML/./node_modules/ml-stat/matrix.js","webpack://ML/./node_modules/ml-array-mean/lib-es6/index.js","webpack://ML/./node_modules/binary-search/index.js","webpack://ML/./node_modules/num-sort/index.js","webpack://ML/./node_modules/ml-cart/src/utils.js","webpack://ML/./node_modules/ml-cart/src/TreeNode.js","webpack://ML/./node_modules/ml-cart/src/DecisionTreeClassifier.js","webpack://ML/./node_modules/ml-cart/src/DecisionTreeRegression.js","webpack://ML/./node_modules/ml-cart/src/index.js","webpack://ML/./node_modules/ml-array-max/lib-es6/index.js","webpack://ML/./node_modules/ml-kernel/src/kernel.js","webpack://ML/./node_modules/ml-random/lib-es6/choice.js","webpack://ML/./node_modules/ml-random/lib-es6/index.js","webpack://ML/./node_modules/random-js/lib/random.js","webpack://ML/./node_modules/ml-array-rescale/lib-es6/index.js","webpack://ML/./node_modules/ml-hash-table/src/HashTable.js","webpack://ML/./node_modules/ml-hclust/src/Cluster.js","webpack://ML/./node_modules/extend/index.js","webpack://ML/./node_modules/ml-array-min/lib-es6/index.js","webpack://ML/./node_modules/ml-array-median/lib-es6/index.js","webpack://ML/./node_modules/ml-xsadd/lib-es6/xsadd.js","webpack://ML/./node_modules/ml-array-sequential-fill/lib-es6/index.js","webpack://ML/./node_modules/ml-array-variance/lib-es6/index.js","webpack://ML/./node_modules/ml-stat/array.js","webpack://ML/./node_modules/ml-hclust/src/ClusterLeaf.js","webpack://ML/./node_modules/ml-distance-matrix/src/index.js","webpack://ML/./node_modules/ml-confusion-matrix/src/index.js","webpack://ML/./node_modules/ml-fnn/src/Layer.js","webpack://ML/./node_modules/ml-fnn/src/utils.js","webpack://ML/./node_modules/ml-fnn/src/activationFunctions.js","webpack://ML/./node_modules/ml-som/src/node-square.js","webpack://ML/./node_modules/ml-distance/src/index.js","webpack://ML/./node_modules/ml-distance/src/similarities/czekanowski.js","webpack://ML/./node_modules/ml-distance/src/distances/dice.js","webpack://ML/./node_modules/ml-distance/src/distances/intersection.js","webpack://ML/./node_modules/ml-distance/src/distances/jaccard.js","webpack://ML/./node_modules/ml-distance/src/distances/kulczynski.js","webpack://ML/./node_modules/ml-distance/src/distances/motyka.js","webpack://ML/./node_modules/ml-distance/src/distances/squaredChord.js","webpack://ML/./node_modules/ml-distance/src/similarities/tanimoto.js","webpack://ML/./node_modules/ml-distance/src/similarities/cosine.js","webpack://ML/./node_modules/ml-pad-array/src/index.js","webpack://ML/./node_modules/ml-regression-base/src/maybeToPrecision.js","webpack://ML/./node_modules/ml-regression-base/src/checkArrayLength.js","webpack://ML/./node_modules/ml-regression-base/src/index.js","webpack://ML/./node_modules/ml-regression-simple-linear/src/index.js","webpack://ML/./node_modules/ml-regression-polynomial/src/index.js","webpack://ML/./node_modules/ml-regression-exponential/src/index.js","webpack://ML/./node_modules/ml-regression-power/src/index.js","webpack://ML/./node_modules/ml-regression-multivariate-linear/src/index.js","webpack://ML/./node_modules/ml-regression/src/regression/potential-regression.js","webpack://ML/./node_modules/ml-regression/src/regression/kernel-ridge-regression.js","webpack://ML/./node_modules/ml-regression/src/regression/poly-fit-regression2d.js","webpack://ML/./node_modules/ml-regression-theil-sen/src/index.js","webpack://ML/./node_modules/ml-regression-robust-polynomial/src/index.js","webpack://ML/./node_modules/ml-regression/src/index.js","webpack://ML/./node_modules/median-quickselect/lib/median-quickselect.min.js","webpack://ML/./src/index.js","webpack://ML/./node_modules/ml-pca/src/pca.js","webpack://ML/./node_modules/ml-hclust/src/index.js","webpack://ML/./node_modules/ml-hclust/src/agnes.js","webpack://ML/./node_modules/heap/index.js","webpack://ML/./node_modules/heap/lib/heap.js","webpack://ML/./node_modules/util/util.js","webpack://ML/./node_modules/process/browser.js","webpack://ML/./node_modules/util/support/isBufferBrowser.js","webpack://ML/./node_modules/util/node_modules/inherits/inherits_browser.js","webpack://ML/./node_modules/ml-hclust/src/diana.js","webpack://ML/./node_modules/ml-svm/src/svm.js","webpack://ML/./node_modules/ml-kernel-gaussian/gaussian-kernel.js","webpack://ML/./node_modules/ml-kernel-polynomial/polynomial-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/anova-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/cauchy-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/exponential-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/histogram-intersection-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/laplacian-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/multiquadratic-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/rational-quadratic-kernel.js","webpack://ML/./node_modules/ml-kernel-sigmoid/sigmoid-kernel.js","webpack://ML/./node_modules/ml-cross-validation/src/index.js","webpack://ML/./node_modules/ml-combinations/lib/index.js","webpack://ML/./node_modules/ml-fnn/src/FeedForwardNeuralNetwork.js","webpack://ML/./node_modules/ml-fnn/src/OutputLayer.js","webpack://ML/./node_modules/ml-som/src/index.js","webpack://ML/./node_modules/ml-som/src/node-hexagonal.js","webpack://ML/./node_modules/ml-sparse-matrix/src/index.js","webpack://ML/./node_modules/new-array/index.js","webpack://ML/./node_modules/ml-hash-table/src/primeFinder.js","webpack://ML/./node_modules/number-is-nan/index.js","webpack://ML/./node_modules/ml-distance/src/distances.js","webpack://ML/./node_modules/ml-distance/src/distances/additiveSymmetric.js","webpack://ML/./node_modules/ml-distance/src/distances/avg.js","webpack://ML/./node_modules/ml-distance/src/distances/bhattacharyya.js","webpack://ML/./node_modules/ml-distance/src/distances/canberra.js","webpack://ML/./node_modules/ml-distance/src/distances/chebyshev.js","webpack://ML/./node_modules/ml-distance/src/distances/clark.js","webpack://ML/./node_modules/ml-distance/src/distances/czekanowski.js","webpack://ML/./node_modules/ml-distance/src/distances/divergence.js","webpack://ML/./node_modules/ml-distance/src/distances/fidelity.js","webpack://ML/./node_modules/ml-distance/src/distances/gower.js","webpack://ML/./node_modules/ml-distance/src/distances/harmonicMean.js","webpack://ML/./node_modules/ml-distance/src/distances/hellinger.js","webpack://ML/./node_modules/ml-distance/src/distances/innerProduct.js","webpack://ML/./node_modules/ml-distance/src/distances/jeffreys.js","webpack://ML/./node_modules/ml-distance/src/distances/jensenDifference.js","webpack://ML/./node_modules/ml-distance/src/distances/jensenShannon.js","webpack://ML/./node_modules/ml-distance/src/distances/kdivergence.js","webpack://ML/./node_modules/ml-distance/src/distances/kullbackLeibler.js","webpack://ML/./node_modules/ml-distance/src/distances/kumarHassebrook.js","webpack://ML/./node_modules/ml-distance/src/distances/kumarJohnson.js","webpack://ML/./node_modules/ml-distance/src/distances/lorentzian.js","webpack://ML/./node_modules/ml-distance/src/distances/manhattan.js","webpack://ML/./node_modules/ml-distance/src/distances/matusita.js","webpack://ML/./node_modules/ml-distance/src/distances/minkowski.js","webpack://ML/./node_modules/ml-distance/src/distances/neyman.js","webpack://ML/./node_modules/ml-distance/src/distances/pearson.js","webpack://ML/./node_modules/ml-distance/src/distances/probabilisticSymmetric.js","webpack://ML/./node_modules/ml-distance/src/distances/ruzicka.js","webpack://ML/./node_modules/ml-distance/src/distances/soergel.js","webpack://ML/./node_modules/ml-distance/src/distances/sorensen.js","webpack://ML/./node_modules/ml-distance/src/distances/squared.js","webpack://ML/./node_modules/ml-distance/src/distances/taneja.js","webpack://ML/./node_modules/ml-distance/src/distances/tanimoto.js","webpack://ML/./node_modules/ml-distance/src/distances/topsoe.js","webpack://ML/./node_modules/ml-tree-similarity/src/index.js","webpack://ML/./node_modules/ml-distance/src/distances/waveHedges.js","webpack://ML/./node_modules/ml-distance/src/similarities.js","webpack://ML/./node_modules/ml-distance/src/similarities/dice.js","webpack://ML/./node_modules/ml-distance/src/similarities/intersection.js","webpack://ML/./node_modules/ml-distance/src/similarities/jaccard.js","webpack://ML/./node_modules/ml-distance/src/similarities/kulczynski.js","webpack://ML/./node_modules/ml-distance/src/similarities/motyka.js","webpack://ML/./node_modules/ml-distance/src/similarities/pearson.js","webpack://ML/./node_modules/ml-distance/src/similarities/squaredChord.js","webpack://ML/./node_modules/ml-performance/src/index.js","webpack://ML/./node_modules/ml-performance/src/measures.js","webpack://ML/./node_modules/ml-savitzky-golay/src/index.js","webpack://ML/./node_modules/ml-savitzky-golay-generalized/src/index.js","webpack://ML/./node_modules/ml-bit-array/src/index.js","webpack://ML/./node_modules/ml-bit-array/src/creator.js","webpack://ML/./node_modules/ml-array-utils/src/index.js","webpack://ML/./node_modules/ml-array-utils/src/ArrayUtils.js","webpack://ML/./node_modules/ml-array-utils/src/getEquallySpaced.js","webpack://ML/./node_modules/ml-array-utils/src/snv.js","webpack://ML/./node_modules/ml-array-mode/lib-es6/index.js","webpack://ML/./node_modules/ml-array-normed/lib-es6/index.js","webpack://ML/./node_modules/ml-array-standard-deviation/lib-es6/index.js","webpack://ML/./node_modules/ml-array-xy-centroids-merge/src/index.js","webpack://ML/./node_modules/ml-arrayxy-closestx/src/index.js","webpack://ML/./node_modules/ml-array-xy-max-merge/src/index.js","webpack://ML/./node_modules/ml-array-xy-max-y/src/index.js","webpack://ML/./node_modules/ml-array-xy-sort-x/src/index.js","webpack://ML/./node_modules/ml-arrayxy-uniquex/src/index.js","webpack://ML/./node_modules/ml-array-xy-weighted-merge/src/index.js","webpack://ML/./node_modules/ml-kmeans/node_modules/ml-distance-euclidean/lib-es6/euclidean.js","webpack://ML/./node_modules/ml-nearest-vector/node_modules/ml-distance-euclidean/lib-es6/euclidean.js","webpack://ML/./node_modules/ml-nearest-vector/lib-es6/index.js","webpack://ML/./node_modules/ml-kmeans/src/utils.js","webpack://ML/./node_modules/ml-kmeans/src/initialization.js","webpack://ML/./node_modules/ml-kmeans/src/KMeansResult.js","webpack://ML/./node_modules/ml-kmeans/src/kmeans.js","webpack://ML/./node_modules/ml-random-forest/src/utils.js","webpack://ML/./node_modules/ml-random-forest/src/RandomForestBase.js","webpack://ML/./node_modules/ml-random-forest/src/RandomForestClassifier.js","webpack://ML/./node_modules/ml-random-forest/src/RandomForestRegression.js","webpack://ML/./node_modules/ml-random-forest/src/index.js","webpack://ML/./node_modules/ml-array-xy-equally-spaced/src/integral.js","webpack://ML/./node_modules/ml-array-xy-equally-spaced/src/equallySpacedSmooth.js","webpack://ML/./node_modules/ml-array-xy-equally-spaced/src/equallySpacedSlot.js","webpack://ML/./node_modules/ml-array-xy-equally-spaced/src/getZones.js","webpack://ML/./node_modules/ml-array-xy-equally-spaced/src/index.js","webpack://ML/./node_modules/ml-naivebayes/src/utils.js","webpack://ML/./node_modules/ml-naivebayes/src/GaussianNB.js","webpack://ML/./node_modules/ml-naivebayes/src/MultinomialNB.js","webpack://ML/./node_modules/ml-naivebayes/src/index.js","webpack://ML/./node_modules/ml-pls/src/utils.js","webpack://ML/./node_modules/ml-pls/src/pls.js","webpack://ML/./node_modules/ml-pls/src/kopls.js","webpack://ML/./node_modules/ml-pls/src/index.js","webpack://ML/./node_modules/ml-levenberg-marquardt/src/errorCalculation.js","webpack://ML/./node_modules/ml-levenberg-marquardt/src/step.js","webpack://ML/./node_modules/ml-levenberg-marquardt/src/index.js","webpack://ML/./node_modules/ml-array-xy-filter-x/src/getZones.js","webpack://ML/./node_modules/ml-array-xy-filter-x/src/index.js","webpack://ML/./node_modules/ml-knn/src/KDTree.js","webpack://ML/./node_modules/ml-knn/src/index.js"],"names":["LuDecomposition","constructor","matrix","WrapperMatrix2D","checkMatrix","lu","clone","rows","columns","pivotVector","Array","pivotSign","i","j","k","p","s","t","v","LUcolj","kmax","get","Math","min","set","abs","LU","isSingular","data","col","solve","value","Matrix","Error","count","X","subMatrixRow","determinant","isSquare","lowerTriangularMatrix","upperTriangularMatrix","pivotPermutationVector","slice","hypotenuse","a","b","r","sqrt","getFilled2DArray","array","SingularValueDecomposition","options","m","n","computeLeftSingularVectors","computeRightSingularVectors","autoTranspose","wantu","Boolean","wantv","swapped","console","warn","transpose","aux","nu","ni","U","V","e","work","si","nct","nrt","max","mrc","pp","iter","eps","Number","EPSILON","kase","alpha","MIN_VALUE","isNaN","ks","f","cs","sn","scale","sp","spm1","epm1","sk","ek","c","shift","g","tmp","Y","threshold","scols","length","Ls","zeros","rightSingularVectors","VL","mmul","vrows","urows","VLU","sum","solveForDiagonal","diag","inverse","vcols","ucols","condition","norm2","rank","tol","ii","diagonal","leftSingularVectors","isMatrix","diagonalMatrix","checkRowIndex","index","outer","RangeError","checkColumnIndex","checkRowVector","vector","to1DArray","checkColumnVector","checkIndices","rowIndices","columnIndices","row","checkRowIndices","column","checkColumnIndices","TypeError","rowOut","some","isArray","from","columnOut","checkRange","startRow","endRow","startColumn","endColumn","arguments","checkNumber","getRange","to","arr","sumByRow","sumByColumn","sumAll","name","BaseView","AbstractMatrix","Symbol","species","MatrixTransposeView","rowIndex","columnIndex","MatrixRowView","MatrixSubView","MatrixSelectionView","indices","MatrixRowSelectionView","MatrixColumnSelectionView","MatrixColumnView","MatrixFlipRowView","MatrixFlipColumnView","superCtor","undefined","Object","from1DArray","newRows","newColumns","newData","newMatrix","rowVector","columnVector","empty","fill","ones","rand","rng","random","randInt","maxValue","floor","eye","l","matrix1","matrix2","result","klass","size","apply","callback","jj","call","to2DArray","copy","isRowVector","isColumnVector","isVector","isSymmetric","isEchelonForm","previousColumn","checked","isReducedEchelonForm","repeat","rowRep","colRep","setSubMatrix","neg","mulS","getRow","getRowVector","setRow","swapRows","row1","row2","temp","getColumn","getColumnVector","setColumn","swapColumns","column1","column2","addRowVector","subRowVector","mulRowVector","divRowVector","addColumnVector","subColumnVector","mulColumnVector","divColumnVector","mulRow","mulColumn","maxIndex","idx","minIndex","maxRow","maxRowIndex","minRow","minRowIndex","maxColumn","maxColumnIndex","minColumn","minColumnIndex","by","mean","prod","norm","type","cumulativeSum","dot","vector2","vector1","other","Bcolj","strassen2x2","a11","b11","a12","b12","a21","b21","a22","b22","m1","m2","m3","m4","m5","m6","m7","c00","c01","c10","c11","strassen3x3","a00","a01","a02","a10","a20","b00","b01","b02","b10","b20","m8","m9","m10","m11","m12","m13","m14","m15","m16","m17","m18","m19","m20","m21","m22","m23","c02","c12","c20","c21","c22","mmulStrassen","y","x","r1","c1","r2","c2","embed","mat","cols","resultat","blockMult","halfRows","parseInt","halfCols","subMatrix","add","sub","scaleRows","scaled","rescale","scaleColumns","kroneckerProduct","q","sortRows","compareFunction","compareNumbers","sort","sortColumns","subMatrixColumn","selection","trace","transposeView","rowView","columnView","flipRowView","flipColumnView","subMatrixView","selectionView","rowSelectionView","columnSelectionView","det","d","subMatrix0","subMatrix1","subMatrix2","pseudoInverse","svdSolution","SvDecomposition","prototype","identity","negate","tensorProduct","inplaceOperator","inplaceOperatorScalar","inplaceOperatorMatrix","staticOperator","inplaceMethod","staticMethod","inplaceMethodWithArgs","staticMethodWithArgs","inplaceMethodWithOneArgScalar","inplaceMethodWithOneArgMatrix","inplaceMethodWithOneArg","staticMethodWithOneArg","operators","eval2","eval","operator","inplaceOp","fillTemplateFunction","op","inplaceOpS","inplaceOpM","staticOp","methods","forEach","mathMethod","push","method","inplaceMeth","staticMeth","methodsWithArgs","methodWithArg","args","inplaceMethWithArgs","staticMethWithArgs","tmplVar","inplaceMethod2","inplaceMethodS","inplaceMethodM","staticMethod2","template","values","replace","RegExp","nRows","nColumns","isInteger","concat","removeRow","splice","addRow","removeColumn","addColumn","WrapperMatrix1D","_calculateIndex","wrap","QrDecomposition","qr","rdiag","nrm","QR","Rdiag","isFullRank","orthogonalMatrix","useSVD","leftHandSide","rightHandSide","xrange","exception","range","dependenciesOneRow","error","thresholdValue","thresholdError","returnArray","linearDependencies","results","Abis","svd","EigenvalueDecomposition","assumeSymmetric","tred2","tql2","H","ort","orthes","hqr2","realEigenvalues","imaginaryEigenvalues","eigenvectorMatrix","h","hh","dl1","c3","el1","s2","tst1","low","high","nn","exshift","z","w","ra","sa","vr","vi","notlast","cdivres","cdiv","xr","xi","yr","yi","CholeskyDecomposition","dimension","positiveDefinite","Lrowj","Lrowk","L","B","toString","isAnyArray","object","endsWith","module","exports","squaredEuclidean","euclidean","squared","require","arrayStat","Infinity","minMax","entropy","l1","l2","log","theMean","N","theSum","product","theProduct","standardDeviation","means","unbiased","vari","variance","sum1","sum2","median","medians","mode","modes","itemCount","itemArray","indexOf","skewness","skew","s3","dev","pow","kurtosis","kurt","s4","standardError","samples","standardDeviations","standardErrors","sqrtN","covariance","scatter","divisor","cov","correlation","scores","zScores","cor","standardize","center","inPlace","resultRow","sourceRow","weightedVariance","weights","weightedMean","weightSum","weightedCovariance","s1","factor","weightedScatter","input","haystack","needle","comparator","mid","cmp","numberIsNan","assertNum","asc","desc","toDiscreteDistribution","numberOfClasses","counts","giniImpurity","probabilities","getNumberOfClasses","filter","val","giniGain","splitted","splitsImpurity","splits","currentSplit","squaredError","meanArray","currentElement","regressionError","matrixSplitter","lesserX","greaterX","lesserY","greaterY","zip","ret","gainFunctions","gini","Utils","regression","splitFunctions","TreeNode","kind","gainFunction","splitFunction","minNumSamples","maxDepth","bestSplit","XTranspose","bestGain","check","currentFeature","splitValues","featureSplit","currentSplitVal","split","gain","maxGain","splitValue","lesser","greater","calculatePrediction","distribution","train","currentDepth","parentGain","splitColumn","splittedMatrix","left","right","classify","setNodeParameters","node","defaultOptions","DecisionTreeClassifier","model","root","Tree","assign","trainingSet","trainingLabels","predict","toPredict","predictions","toJSON","load","DecisionTreeRegression","trainingValues","GaussianKernel","PolynomialKernel","ANOVAKernel","CauchyKernel","ExponentialKernel","HistogramKernel","LaplacianKernel","MultiquadraticKernel","RationalKernel","SigmoidKernel","kernelType","gaussian","rbf","polynomial","poly","anova","cauchy","exponential","histogram","laplacian","multiquadratic","rational","sigmoid","mlp","Kernel","toLowerCase","KernelConstructor","kernelFunction","compute","inputs","landmarks","kernelMatrix","PROB_TOLERANCE","randomChoice","valuesArr","cumSum","getArray","randomIndex","Random","seedOrRandom","xsadd","XSAdd","randomGenerator","choice","randomSample","GLOBAL_KEY","imul","ah","al","bh","bl","stringRepeat","String","pattern","engine","engines","nativeMath","proto","mt19937","Int32Array","refreshData","temper","seedWithArray","source","sourceLength","previous","uses","next","getUseCount","discard","seed","initial","autoSeed","generateEntropyArray","browserCrypto","crypto","getRandomValues","Date","getTime","returnValue","int32","uint32","uint53","uint53Full","int53","int53Full","generate","addend","integer","isPowerOfTwoMinusOne","bitmask","masking","downscaleToLoopCheckedRange","extendedRange","maximum","downscaleToRange","isEvenlyDivisibleByMaxInt32","upscaleWithHighMasking","upscaleToLoopCheckedRange","upscaleWithinU53","highRange","upscaleWithinI53AndLoopCheck","isFinite","realZeroToOneInclusive","realZeroToOneExclusive","real","multiply","multiplier","inclusive","bool","isLeastBitTrue","lessThan","probability","percentage","round","numerator","denominator","toInteger","number","ceil","convertSliceArgument","pick","begin","end","start","finish","returnUndefined","picker","shuffle","downTo","sample","population","sampleSize","tailLength","die","sideCount","dice","dieCount","uuid4","zeroPad","string","zeroCount","DEFAULT_STRING_POOL","pool","charAt","hex","LOWER_HEX_POOL","lowerHex","upperHex","toUpperCase","upper","date","define","output","currentMin","currentMax","_options$min","minValue","autoMinMax","_options$max","newArray","primeFinder","nextPrime","largestPrime","FREE","FULL","REMOVED","defaultInitialCapacity","defaultMinLoadFactor","defaultMaxLoadFactor","HashTable","table","state","minLoadFactor","maxLoadFactor","distinct","freeEntries","lowWaterMark","highWaterMark","initialCapacity","capacity","chooseHighWaterMark","key","indexOfKey","indexOfInsertion","newCapacity","chooseGrowCapacity","rehash","remove","noRehash","maybeShrinkCapacity","delete","chooseShrinkCapacity","containsKey","hash","decrement","containsValue","indexOfValue","ensureCapacity","minCapacity","oldCapacity","oldTable","oldValues","oldState","newTable","newValues","newState","chooseLowWaterMark","element","forEachKey","forEachValue","forEachPair","minLoad","maxLoad","Heap","Cluster","children","distance","cut","list","ans","group","minGroups","heap","first","pop","child","toArray","traverse","cb","visit","hasOwn","hasOwnProperty","toStr","defineProperty","gOPD","getOwnPropertyDescriptor","isPlainObject","obj","hasOwnConstructor","hasIsPrototypeOf","setProperty","target","enumerable","configurable","newValue","writable","getProperty","extend","src","copyIsArray","deep","quickSelectMedian","LOOP","FLOAT_MUL","sh1","sh2","sh3","multiply_uint32","nlo","nhi","XSadd","now","Uint32Array","init","getFloat","bind","getUint32","nextState","periodCertification","_typeof","iterator","sequentialFill","_options","_options$from","_options$to","_options$size","step","_i","_options$unbiased","_options$mean","arrayMean","sqrError","arithmeticMean","geometricMean","mul","logMean","lnsum","grandMean","truncatedMean","percent","alreadySorted","harmonicMean","contraHarmonicMean","half","theVariance","robustMeanAndStdev","stdev","averageDeviations","quartiles","quart","q1","q2","q3","pooledStandardDeviation","pooledVariance","mean1","mean2","weightedStandardDeviation","standardDev","util","ClusterLeaf","inherits","distanceMatrix","distanceFn","map","ConfusionMatrix","labels","fromLabels","actual","predicted","distinctLabels","Set","actualIdx","predictedIdx","getMatrix","getLabels","getTotalCount","getTrueCount","getFalseCount","getTruePositiveCount","label","getIndex","getTrueNegativeCount","getFalsePositiveCount","getFalseNegativeCount","getPositiveCount","getNegativeCount","getTruePositiveRate","getTrueNegativeRate","getPositivePredictiveValue","TP","getNegativePredictiveValue","TN","getFalseNegativeRate","getFalsePositiveRate","getFalseDiscoveryRate","FP","getFalseOmissionRate","FN","getF1Score","getMatthewsCorrelationCoefficient","getInformedness","getMarkedness","getConfusionTable","getAccuracy","correct","incorrect","getCount","actualIndex","predictedIndex","accuracy","total","ACTIVATION_FUNCTIONS","Layer","inputSize","outputSize","regularization","epsilon","activation","activationParam","selectedFunction","params","actFunction","derFunction","derivate","activationFunction","W","forward","backpropagation","delta","dW","db","sumCol","aCopy","update","sumRow","dictOutputs","outputs","logistic","exp","expELU","param","softExponential","softExponentialPrime","tanh","arctan","atan","softsign","relu","softplus","bent","sinusoid","sin","cos","sinc","NodeSquare","som","neighbors","adjustWeights","learningRate","influence","getDistance","otherNode","getDistanceTorus","distX","distY","gridDim","getNeighbors","xy","torus","nodes","getPos","bestNeighbor","direction","dist1","dist2","simA","simB","getPosition","similarity","czekanowskiSimilarity","up","down","intersection","jaccard","p1","p2","kulczynski","motyka","squaredChord","tanimoto","bitvector","inter","union","cosine","arrayCase","len","cond","matrixCase","padArray","maybeToPrecision","digits","toPrecision","checkArraySize","BaseRegression","new","_predict","toLaTeX","score","y2","xSum","ySum","chi2","rmsd","xSquared","ySquared","xY","SimpleLinearRegression","slope","intercept","coefficients","checkArrayLength","regress","computeX","precision","xFactor","absIntercept","json","slr","PolynomialRegression","degree","powers","_toFormula","isLaTeX","sup","closeSup","times","fn","str","pr","F","FT","A","ExponentialRegression","er","yl","linear","PowerRegression","newInputs","xl","MultivariateLinearRegression","statistics","beta","SVD","fittedValues","residuals","addM","ri","reduce","stdError","stdErrorMatrix","stdErrors","tStats","summary","regressionStatistics","observations","variables","tStat","PotentialRegression","M","lambda","kernelOptions","computeCoefficient","KernelRidgeRegression","kernel","K","order","PolynomialFitRegression2D","examples","x1","x2","scaleX1","scaleX2","scaleY","limit","powColVector","qqs","qqs1","power","TheilSenRegression","theilSen","slopes","medianSlope","cuts","RobustPolynomialRegression","robustPolynomial","tuples","getRandomTuples","tuple","calcCoefficients","residual","residualsMedian","pos","counter","NLR","_ref","window","mlCart","mlRandomForest","ML","PCA","HClust","KMeans","SVM","NaiveBayes","KNN","PLS","CrossValidation","RandomForestClassifier","FNN","SOM","Regression","RandomForestRegression","levenbergMarquardt","EVD","SparseMatrix","Distance","Similarity","default","Performance","savitzkyGolay","savitzkyGolayGeneralized","BitArray","binarySearch","numSort","ArrayUtils","MatrixUtil","ArrayStat","MatrixStat","normed","ArrayXY","centroidsMerge","closestX","maxMerge","maxY","sortX","uniqueX","weightedMerge","equallySpaced","filterX","matrixLib","Stat","isCovarianceMatrix","dataset","stdevs","S","_computeFromCovarianceMatrix","useCovarianceMatrix","_adjust","covarianceMatrix","div","singularValues","eigenvalues","nComponents","getExplainedVariance","getCumulativeVariance","explained","getEigenvectors","getEigenvalues","getStandardDeviations","getLoadings","evd","reverse","agnes","diana","simpleLink","cluster1","cluster2","disFun","completeLink","averageLink","centroidLink","dist","wardLink","disFunc","isDistanceMatrix","dis","fdistance","sdistance","toFixed","dmin","clustered","int","diff","indCount","defaultCmp","heapify","heappop","heappush","heappushpop","heapreplace","insort","nlargest","nsmallest","updateItem","_siftdown","_siftup","lo","hi","item","lastelt","returnitem","_j","_len","_ref1","_results","_results1","elem","los","startpos","newitem","parent","parentpos","childpos","endpos","rightpos","pushpop","peek","contains","clear","insert","top","front","has","factory","getOwnPropertyDescriptors","keys","descriptors","formatRegExp","format","isString","objects","inspect","join","JSON","stringify","_","isNull","isObject","deprecate","msg","process","noDeprecation","warned","deprecated","throwDeprecation","traceDeprecation","debugs","debugEnviron","debuglog","isUndefined","env","NODE_DEBUG","test","pid","opts","ctx","seen","stylize","stylizeNoColor","depth","colors","isBoolean","showHidden","_extend","customInspect","stylizeWithColor","formatValue","styles","styleType","style","arrayToHash","recurseTimes","isFunction","primitive","formatPrimitive","visibleKeys","getOwnPropertyNames","isError","formatError","isRegExp","isDate","base","braces","toUTCString","formatArray","formatProperty","reduceToSingleString","simple","isNumber","match","line","substr","numLinesEst","prev","cur","ar","arg","isNullOrUndefined","isSymbol","re","objectToString","isPrimitive","isBuffer","o","pad","months","timestamp","time","getHours","getMinutes","getSeconds","getDate","getMonth","origin","prop","kCustomPromisifiedSymbol","promisify","original","promiseResolve","promiseReject","promise","Promise","resolve","reject","err","setPrototypeOf","getPrototypeOf","defineProperties","custom","callbackifyOnRejected","reason","newReason","callbackify","callbackified","maybeCb","self","then","nextTick","rej","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","setTimeout","clearTimeout","runTimeout","fun","runClearTimeout","marker","queue","draining","currentQueue","queueIndex","cleanUpNextTick","drainQueue","timeout","run","Item","title","browser","argv","version","versions","noop","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","readUInt8","create","ctor","super_","TempCtor","y1","splitting","Ci","Cj","ndist","intrDist","tree","ind","clId","rebel","C","sG","spl","fData","sData","stat","maxPasses","maxIterations","alphaTol","whitening","features","_trained","_loaded","D","alphas","b1","b2","passes","Ei","Ej","ai","aj","eta","numChange","_marginOnePrecomputed","newaj","iterations","nX","nY","nAlphas","_supportVectorIdx","predictOne","margin","marginOne","noWhitening","_applyWhitening","supportVectors","svm","whitened","sigma","constant","HistogramIntersectionKernel","RationalQuadraticKernel","E","CV","combinations","leaveOneOut","Classifier","classifierOptions","leavePOut","getDistinct","confusionMatrix","initMatrix","gen","allIdx","testIdx","trainIdx","validateWithCallback","validate","kFold","current","folds","randi","testFeatures","trainFeatures","testLabels","trainLabels","getTrainTest","classifier","predictedLabels","updateConfusionMatrix","global","createCommonjsModule","runtime","Op","$Symbol","iteratorSymbol","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","regeneratorRuntime","innerFn","outerFn","tryLocsList","protoGenerator","Generator","generator","context","Context","_invoke","makeInvokeMethod","tryCatch","GenStateSuspendedStart","GenStateSuspendedYield","GenStateExecuting","GenStateCompleted","ContinueSentinel","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","getProto","NativeIteratorPrototype","Gp","displayName","defineIteratorMethods","isGeneratorFunction","genFun","mark","__proto__","awrap","__await","AsyncIterator","invoke","record","unwrapped","previousPromise","enqueue","callInvokeWithMethodAndArg","async","done","doneResult","delegate","delegateResult","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","return","info","resultName","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","resetTryEntry","completion","reset","iterable","iteratorMethod","skipTempReset","stop","rootEntry","rootRecord","rval","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","thrown","delegateYield","Function","hadRuntime","oldRuntime","runtimeModule","regenerator","_callee","twiddle","_callee$","_context","OutputLayer","FeedForwardNeuralNetworks","hiddenLayers","dicts","layers","buildNetwork","propagate","NodeHexagonal","fields","randomizer","squareEuclidean","gridType","reload","numWeights","converters","getConverters","extractor","creator","nodeType","hx","distanceMethod","maxDistance","getMaxDistance","findBMU","adjust","iterationCount","startLearningRate","mapRadius","algorithmMethod","_initNodes","loadModel","export","exportModel","includeDistance","initNodes","setTraining","convertedSet","numIterations","timeConstant","trainOne","neighbourhoodRadius","trainingValue","trainingSetFactor","getRandomValue","bmu","_findBestMatchingUnit","now2","radiusLimit","xMin","xMax","yMin","yMax","theX","theY","getConvertedNodes","findBestMatchingUnit","candidate","lowest","computePosition","getQuantizationError","fit","getFit","normalizers","denormalizers","getNormalizer","getDenormalizer","normalizer","denormalizer","zero","one","hX","getDistanceHexagonal","distZ","_init","elements","symmetric","forEachNonZero","bandWidth","isBanded","width","cardinality","v1","v2","getNonZeros","setThreshold","newThreshold","trans","sortAsc","primeNumbers","additiveSymmetric","avg","bhattacharyya","canberra","chebyshev","clark","czekanowski","divergence","fidelity","gower","hellinger","innerProduct","jeffreys","jensenDifference","jensenShannon","kdivergence","kullbackLeibler","kumarHassebrook","kumarJohnson","lorentzian","manhattan","matusita","minkowski","neyman","pearson","probabilisticSymmetric","ruzicka","soergel","sorensen","taneja","topsoe","waveHedges","czekanowskiDistance","tanimotoS","createTree","minWindow","gamma","Atree","Btree","calc","diceD","intersectionD","jaccardD","kulczynskiD","motykaD","avgA","avgB","newA","newB","squaredChordD","measures","prediction","isDistance","predP","all","pred","targ","cutoffs","MAX_VALUE","fp","tp","nPos","nNeg","currentPred","nTp","nFp","tn","nPosPred","nNegPred","nSamples","getMeasure","measure","getAURC","auc","getAUDC","getDistribution","cutLength","cutLow","cutHigh","interval","xLabels","interValues","intraValues","interCumPercent","intraCumPercent","nTP","currentTP","nFP","currentFP","thisTP","thisFP","names","acc","fpr","tpr","fnr","tnr","ppv","npv","pcfall","pcmiss","lift","rpp","rnp","windowSize","derivative","padValue","SavitzkyGolay","J","inic","Jtranspose","Jinv","np","fullWeights","hs","constantH","wg1","wg2","d1","d2","getHs","wg","GramPoly","Grampoly","GenFact","gf","Weight","eightBits","and","arr1","arr2","or","xor","not","getBit","mask","setBit","toBinaryString","parseBinaryString","toHexString","parseHexString","toDebug","binary","num","getEquallySpacedData","SNV","coordArrayToPoints","dimensions","pointsArr","point","coordArrayToCoordMatrix","coordinatesArray","points","currentPoint","coordMatrixToCoordArray","coordMatrix","coodinatesArray","resultMatrix","pointsToCoordArray","applyDotProduct","firstVector","secondVector","largestVector","smallestVector","difference","dotProductApplied","coordMatrixToPoints","pointsToCoordMatrix","xLength","variant","numberOfPoints","getEquallySpacedSlot","getEquallySpacedSmooth","halfStep","initialOriginalStep","lastOriginalStep","previousX","previousY","nextX","nextY","currentValue","sumAtMin","sumAtMax","getSlope","x0","y0","main","integral","lastStep","frontOutsideSpectra","backOutsideSpectra","currentPoints","std","maxCount","_options$algorithm","algorithm","absoluteSum","mergeByCentroids","originalPoints","centroids","mergedPoints","originalIndex","mergedIndex","groupWidth","merged","maxAbscissa","calculateIndex","currentIndex","sortFunc","grouped","response","weightedAbscissa","distanceFunction","nearestVector","listVectors","similarityFunction","vectorIndex","maxSim","sim","minDist","findNearestVector","vectorList","calculateDistanceMatrix","updateClusterID","centers","clusterID","updateCenters","prevCenters","nDim","centersLen","dim","id","hasConverged","oldCenters","tolerance","mostDistant","maxDist","minDistCent","kmeanspp","localTrials","firstCenterIdx","closestDistSquared","cumSumClosestDistSquared","candidateIdx","candidates","distanceToCandidates","euclidianDistances","bestCandidate","bestPot","bestDistSquared","newDistSquared","newPot","distanceSymbol","KMeansResult","clusters","converged","nearest","centroid","computeInformation","enrichedCentroids","withIterations","initialization","newCenters","kmeansGenerator","stepNumber","stepResult","kmeans","checkFloat","examplesBaggingWithReplacement","Xr","featureBagging","replacement","toRet","usedIndex","RandomForestBase","maxFeatures","nEstimators","treeOptions","isClassifier","indexes","useSampleBagging","Estimator","DTClassifier","DTRegression","estimators","est","res","predictionValues","baseModel","selectionMethods","arrayMedian","selectionMethod","equallySpacedSmooth","equallySpacedSlot","getZones","exclusions","exclusion","parse","toRemove","unitsPerPoint","zones","currentFrom","totalPoints","currentNbPoints","arrayXY","xResult","yResult","zone","zoneResult","processZone","separateClasses","classes","totalPerClasses","separatedClasses","GaussianNB","calculateProbabilities","C1","PI","logPriorProbability","currentStd","getCurrentClass","modelName","currentCase","maxProbability","predictedClass","currentProbability","calculateLogProbability","C2","MultinomialNB","conditionalProbability","priorProbability","separateClass","classValues","matrixLog","pow2array","featureNormalize","initializeMatrices","meanX","stdDevX","meanY","stdDevY","PBQ","R2X","scaleMethod","latentVectors","rx","cx","ry","cy","ssqXcal","sumOfSquaresY","T","P","Q","transposeX","transposeY","tIndex","maxSumColIndex","mulM","uIndex","t1","u","den","pnorm","ssqYcal","KOPLS","YLoadingMat","SigmaPow","YScoreMat","predScoreMat","YOrthLoadingVec","YOrthEigen","YOrthScoreMat","toNorm","TURegressionCoeff","kernelX","orthogonalComp","predictiveComp","predictiveComponents","orthogonalComponents","Identity","Sigma","YOrthScoreNorm","TpiPrime","CoTemp","SoTemp","toiPrime","ITo","lastScoreMat","lastTpPrime","KTestTrain","YOrthScoreVector","scoreMatPrime","p3","predYOrthVectors","errorCalculation","parameters","parameterizedFunction","func","gradientFunction","evaluatedData","gradientDifference","paramFunction","auxParams","funcParam","matrixFunction","damping","gradientFunc","matrixFunc","inverseMatrix","errorTolerance","minValues","maxValues","initialValues","parLen","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","iteration","parameterValues","parameterError","currentZoneIndex","newX","newY","position","Node","KDTree","metric","restoreParent","buildTree","toJSONImpl","maxNodes","bestNodes","BinaryHeap","nearestSearch","ownDistance","linearPoint","bestChild","linearDistance","otherChild","saveNode","content","dest","scoreFunction","bubbleUp","sinkDown","parentN","elemScore","child2N","child1N","swap","child1","child1Score","child2","child2Score","kdTree","isEuclidean","euclideanDistance","getSinglePrediction","knn","nearestPoints","pointsPerClass","maxPoints","lastElement","currentClass"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,kDAA0C,gCAAgC;AAC1E;AACA;;AAEA;AACA;AACA;AACA,gEAAwD,kBAAkB;AAC1E;AACA,yDAAiD,cAAc;AAC/D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAyC,iCAAiC;AAC1E,wHAAgH,mBAAmB,EAAE;AACrI;AACA;;AAEA;AACA;AACA;AACA,mCAA2B,0BAA0B,EAAE;AACvD,yCAAiC,eAAe;AAChD;AACA;AACA;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A5FoB;;AA+FzB,SAAS+hE,mBAAT,CAA6BC,GAA7B,EAAkCxI,WAAlC,EAA+C;AAC3C,MAAIyI,aAAa,GAAGD,GAAG,CAACJ,MAAJ,CAAWtM,OAAX,CAAmBkE,WAAnB,EAAgCwI,GAAG,CAAChqE,CAApC,CAApB;AACA,MAAIkqE,cAAc,GAAG,EAArB;AACA,MAAIxI,cAAc,GAAG,CAAC,CAAtB;AACA,MAAIyI,SAAS,GAAG,CAAC,CAAjB;AACA,MAAIC,WAAW,GAAGH,aAAa,CAAC,CAAD,CAAb,CAAiB,CAAjB,EAAoBzkE,MAApB,GAA6B,CAA/C;;AAEA,OAAK,IAAIovB,OAAT,IAAoBo1C,GAAG,CAACnJ,OAAxB,EAAiC;AAC7BqJ,kBAAc,CAACt1C,OAAD,CAAd,GAA0B,CAA1B;AACH;;AAED,OAAK,IAAI90B,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAGmqE,aAAa,CAACzkE,MAAlC,EAA0C,EAAE1F,CAA5C,EAA+C;AAC3C,QAAIuqE,YAAY,GAAGJ,aAAa,CAACnqE,CAAD,CAAb,CAAiB,CAAjB,EAAoBsqE,WAApB,CAAnB;AACA,QAAI/Q,aAAa,GAAG,EAAE6Q,cAAc,CAACG,YAAD,CAApC;;AACA,QAAIhR,aAAa,GAAG8Q,SAApB,EAA+B;AAC3BzI,oBAAc,GAAG2I,YAAjB;AACAF,eAAS,GAAG9Q,aAAZ;AACH;AACJ;;AAED,SAAOqI,cAAP;AACH,C","file":"ml.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"ML\"] = factory();\n\telse\n\t\troot[\"ML\"] = factory();\n})(typeof self !== 'undefined' ? self : this, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 43);\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\n/**\r\n * @class LuDecomposition\r\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs\r\n * @param {Matrix} matrix\r\n */\r\nexport default class LuDecomposition {\r\n constructor(matrix) {\r\n matrix = WrapperMatrix2D.checkMatrix(matrix);\r\n\r\n var lu = matrix.clone();\r\n var rows = lu.rows;\r\n var columns = lu.columns;\r\n var pivotVector = new Array(rows);\r\n var pivotSign = 1;\r\n var i, j, k, p, s, t, v;\r\n var LUcolj, kmax;\r\n\r\n for (i = 0; i < rows; i++) {\r\n pivotVector[i] = i;\r\n }\r\n\r\n LUcolj = new Array(rows);\r\n\r\n for (j = 0; j < columns; j++) {\r\n for (i = 0; i < rows; i++) {\r\n LUcolj[i] = lu.get(i, j);\r\n }\r\n\r\n for (i = 0; i < rows; i++) {\r\n kmax = Math.min(i, j);\r\n s = 0;\r\n for (k = 0; k < kmax; k++) {\r\n s += lu.get(i, k) * LUcolj[k];\r\n }\r\n LUcolj[i] -= s;\r\n lu.set(i, j, LUcolj[i]);\r\n }\r\n\r\n p = j;\r\n for (i = j + 1; i < rows; i++) {\r\n if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) {\r\n p = i;\r\n }\r\n }\r\n\r\n if (p !== j) {\r\n for (k = 0; k < columns; k++) {\r\n t = lu.get(p, k);\r\n lu.set(p, k, lu.get(j, k));\r\n lu.set(j, k, t);\r\n }\r\n\r\n v = pivotVector[p];\r\n pivotVector[p] = pivotVector[j];\r\n pivotVector[j] = v;\r\n\r\n pivotSign = -pivotSign;\r\n }\r\n\r\n if (j < rows && lu.get(j, j) !== 0) {\r\n for (i = j + 1; i < rows; i++) {\r\n lu.set(i, j, lu.get(i, j) / lu.get(j, j));\r\n }\r\n }\r\n }\r\n\r\n this.LU = lu;\r\n this.pivotVector = pivotVector;\r\n this.pivotSign = pivotSign;\r\n }\r\n\r\n /**\r\n *\r\n * @return {boolean}\r\n */\r\n isSingular() {\r\n var data = this.LU;\r\n var col = data.columns;\r\n for (var j = 0; j < col; j++) {\r\n if (data[j][j] === 0) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n *\r\n * @param {Matrix} value\r\n * @return {Matrix}\r\n */\r\n solve(value) {\r\n value = Matrix.checkMatrix(value);\r\n\r\n var lu = this.LU;\r\n var rows = lu.rows;\r\n\r\n if (rows !== value.rows) {\r\n throw new Error('Invalid matrix dimensions');\r\n }\r\n if (this.isSingular()) {\r\n throw new Error('LU matrix is singular');\r\n }\r\n\r\n var count = value.columns;\r\n var X = value.subMatrixRow(this.pivotVector, 0, count - 1);\r\n var columns = lu.columns;\r\n var i, j, k;\r\n\r\n for (k = 0; k < columns; k++) {\r\n for (i = k + 1; i < columns; i++) {\r\n for (j = 0; j < count; j++) {\r\n X[i][j] -= X[k][j] * lu[i][k];\r\n }\r\n }\r\n }\r\n for (k = columns - 1; k >= 0; k--) {\r\n for (j = 0; j < count; j++) {\r\n X[k][j] /= lu[k][k];\r\n }\r\n for (i = 0; i < k; i++) {\r\n for (j = 0; j < count; j++) {\r\n X[i][j] -= X[k][j] * lu[i][k];\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get determinant() {\r\n var data = this.LU;\r\n if (!data.isSquare()) {\r\n throw new Error('Matrix must be square');\r\n }\r\n var determinant = this.pivotSign;\r\n var col = data.columns;\r\n for (var j = 0; j < col; j++) {\r\n determinant *= data[j][j];\r\n }\r\n return determinant;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get lowerTriangularMatrix() {\r\n var data = this.LU;\r\n var rows = data.rows;\r\n var columns = data.columns;\r\n var X = new Matrix(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n if (i > j) {\r\n X[i][j] = data[i][j];\r\n } else if (i === j) {\r\n X[i][j] = 1;\r\n } else {\r\n X[i][j] = 0;\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get upperTriangularMatrix() {\r\n var data = this.LU;\r\n var rows = data.rows;\r\n var columns = data.columns;\r\n var X = new Matrix(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n if (i <= j) {\r\n X[i][j] = data[i][j];\r\n } else {\r\n X[i][j] = 0;\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Array}\r\n */\r\n get pivotPermutationVector() {\r\n return this.pivotVector.slice();\r\n }\r\n}\r\n","export function hypotenuse(a, b) {\r\n var r = 0;\r\n if (Math.abs(a) > Math.abs(b)) {\r\n r = b / a;\r\n return Math.abs(a) * Math.sqrt(1 + r * r);\r\n }\r\n if (b !== 0) {\r\n r = a / b;\r\n return Math.abs(b) * Math.sqrt(1 + r * r);\r\n }\r\n return 0;\r\n}\r\n\r\nexport function getFilled2DArray(rows, columns, value) {\r\n var array = new Array(rows);\r\n for (var i = 0; i < rows; i++) {\r\n array[i] = new Array(columns);\r\n for (var j = 0; j < columns; j++) {\r\n array[i][j] = value;\r\n }\r\n }\r\n return array;\r\n}\r\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\nimport { hypotenuse, getFilled2DArray } from './util';\r\n\r\n/**\r\n * @class SingularValueDecomposition\r\n * @see https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs\r\n * @param {Matrix} value\r\n * @param {object} [options]\r\n * @param {boolean} [options.computeLeftSingularVectors=true]\r\n * @param {boolean} [options.computeRightSingularVectors=true]\r\n * @param {boolean} [options.autoTranspose=false]\r\n */\r\nexport default class SingularValueDecomposition {\r\n constructor(value, options = {}) {\r\n value = WrapperMatrix2D.checkMatrix(value);\r\n\r\n var m = value.rows;\r\n var n = value.columns;\r\n\r\n const {\r\n computeLeftSingularVectors = true,\r\n computeRightSingularVectors = true,\r\n autoTranspose = false\r\n } = options;\r\n\r\n var wantu = Boolean(computeLeftSingularVectors);\r\n var wantv = Boolean(computeRightSingularVectors);\r\n\r\n var swapped = false;\r\n var a;\r\n if (m < n) {\r\n if (!autoTranspose) {\r\n a = value.clone();\r\n // eslint-disable-next-line no-console\r\n console.warn(\r\n 'Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose'\r\n );\r\n } else {\r\n a = value.transpose();\r\n m = a.rows;\r\n n = a.columns;\r\n swapped = true;\r\n var aux = wantu;\r\n wantu = wantv;\r\n wantv = aux;\r\n }\r\n } else {\r\n a = value.clone();\r\n }\r\n\r\n var nu = Math.min(m, n);\r\n var ni = Math.min(m + 1, n);\r\n var s = new Array(ni);\r\n var U = getFilled2DArray(m, nu, 0);\r\n var V = getFilled2DArray(n, n, 0);\r\n\r\n var e = new Array(n);\r\n var work = new Array(m);\r\n\r\n var si = new Array(ni);\r\n for (let i = 0; i < ni; i++) si[i] = i;\r\n\r\n var nct = Math.min(m - 1, n);\r\n var nrt = Math.max(0, Math.min(n - 2, m));\r\n var mrc = Math.max(nct, nrt);\r\n\r\n for (let k = 0; k < mrc; k++) {\r\n if (k < nct) {\r\n s[k] = 0;\r\n for (let i = k; i < m; i++) {\r\n s[k] = hypotenuse(s[k], a[i][k]);\r\n }\r\n if (s[k] !== 0) {\r\n if (a[k][k] < 0) {\r\n s[k] = -s[k];\r\n }\r\n for (let i = k; i < m; i++) {\r\n a[i][k] /= s[k];\r\n }\r\n a[k][k] += 1;\r\n }\r\n s[k] = -s[k];\r\n }\r\n\r\n for (let j = k + 1; j < n; j++) {\r\n if (k < nct && s[k] !== 0) {\r\n let t = 0;\r\n for (let i = k; i < m; i++) {\r\n t += a[i][k] * a[i][j];\r\n }\r\n t = -t / a[k][k];\r\n for (let i = k; i < m; i++) {\r\n a[i][j] += t * a[i][k];\r\n }\r\n }\r\n e[j] = a[k][j];\r\n }\r\n\r\n if (wantu && k < nct) {\r\n for (let i = k; i < m; i++) {\r\n U[i][k] = a[i][k];\r\n }\r\n }\r\n\r\n if (k < nrt) {\r\n e[k] = 0;\r\n for (let i = k + 1; i < n; i++) {\r\n e[k] = hypotenuse(e[k], e[i]);\r\n }\r\n if (e[k] !== 0) {\r\n if (e[k + 1] < 0) {\r\n e[k] = 0 - e[k];\r\n }\r\n for (let i = k + 1; i < n; i++) {\r\n e[i] /= e[k];\r\n }\r\n e[k + 1] += 1;\r\n }\r\n e[k] = -e[k];\r\n if (k + 1 < m && e[k] !== 0) {\r\n for (let i = k + 1; i < m; i++) {\r\n work[i] = 0;\r\n }\r\n for (let i = k + 1; i < m; i++) {\r\n for (let j = k + 1; j < n; j++) {\r\n work[i] += e[j] * a[i][j];\r\n }\r\n }\r\n for (let j = k + 1; j < n; j++) {\r\n let t = -e[j] / e[k + 1];\r\n for (let i = k + 1; i < m; i++) {\r\n a[i][j] += t * work[i];\r\n }\r\n }\r\n }\r\n if (wantv) {\r\n for (let i = k + 1; i < n; i++) {\r\n V[i][k] = e[i];\r\n }\r\n }\r\n }\r\n }\r\n\r\n let p = Math.min(n, m + 1);\r\n if (nct < n) {\r\n s[nct] = a[nct][nct];\r\n }\r\n if (m < p) {\r\n s[p - 1] = 0;\r\n }\r\n if (nrt + 1 < p) {\r\n e[nrt] = a[nrt][p - 1];\r\n }\r\n e[p - 1] = 0;\r\n\r\n if (wantu) {\r\n for (let j = nct; j < nu; j++) {\r\n for (let i = 0; i < m; i++) {\r\n U[i][j] = 0;\r\n }\r\n U[j][j] = 1;\r\n }\r\n for (let k = nct - 1; k >= 0; k--) {\r\n if (s[k] !== 0) {\r\n for (let j = k + 1; j < nu; j++) {\r\n let t = 0;\r\n for (let i = k; i < m; i++) {\r\n t += U[i][k] * U[i][j];\r\n }\r\n t = -t / U[k][k];\r\n for (let i = k; i < m; i++) {\r\n U[i][j] += t * U[i][k];\r\n }\r\n }\r\n for (let i = k; i < m; i++) {\r\n U[i][k] = -U[i][k];\r\n }\r\n U[k][k] = 1 + U[k][k];\r\n for (let i = 0; i < k - 1; i++) {\r\n U[i][k] = 0;\r\n }\r\n } else {\r\n for (let i = 0; i < m; i++) {\r\n U[i][k] = 0;\r\n }\r\n U[k][k] = 1;\r\n }\r\n }\r\n }\r\n\r\n if (wantv) {\r\n for (let k = n - 1; k >= 0; k--) {\r\n if (k < nrt && e[k] !== 0) {\r\n for (let j = k + 1; j < n; j++) {\r\n let t = 0;\r\n for (let i = k + 1; i < n; i++) {\r\n t += V[i][k] * V[i][j];\r\n }\r\n t = -t / V[k + 1][k];\r\n for (let i = k + 1; i < n; i++) {\r\n V[i][j] += t * V[i][k];\r\n }\r\n }\r\n }\r\n for (let i = 0; i < n; i++) {\r\n V[i][k] = 0;\r\n }\r\n V[k][k] = 1;\r\n }\r\n }\r\n\r\n var pp = p - 1;\r\n var iter = 0;\r\n var eps = Number.EPSILON;\r\n while (p > 0) {\r\n let k, kase;\r\n for (k = p - 2; k >= -1; k--) {\r\n if (k === -1) {\r\n break;\r\n }\r\n const alpha =\r\n Number.MIN_VALUE + eps * Math.abs(s[k] + Math.abs(s[k + 1]));\r\n if (Math.abs(e[k]) <= alpha || Number.isNaN(e[k])) {\r\n e[k] = 0;\r\n break;\r\n }\r\n }\r\n if (k === p - 2) {\r\n kase = 4;\r\n } else {\r\n let ks;\r\n for (ks = p - 1; ks >= k; ks--) {\r\n if (ks === k) {\r\n break;\r\n }\r\n let t =\r\n (ks !== p ? Math.abs(e[ks]) : 0) +\r\n (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0);\r\n if (Math.abs(s[ks]) <= eps * t) {\r\n s[ks] = 0;\r\n break;\r\n }\r\n }\r\n if (ks === k) {\r\n kase = 3;\r\n } else if (ks === p - 1) {\r\n kase = 1;\r\n } else {\r\n kase = 2;\r\n k = ks;\r\n }\r\n }\r\n\r\n k++;\r\n\r\n switch (kase) {\r\n case 1: {\r\n let f = e[p - 2];\r\n e[p - 2] = 0;\r\n for (let j = p - 2; j >= k; j--) {\r\n let t = hypotenuse(s[j], f);\r\n let cs = s[j] / t;\r\n let sn = f / t;\r\n s[j] = t;\r\n if (j !== k) {\r\n f = -sn * e[j - 1];\r\n e[j - 1] = cs * e[j - 1];\r\n }\r\n if (wantv) {\r\n for (let i = 0; i < n; i++) {\r\n t = cs * V[i][j] + sn * V[i][p - 1];\r\n V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1];\r\n V[i][j] = t;\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n case 2: {\r\n let f = e[k - 1];\r\n e[k - 1] = 0;\r\n for (let j = k; j < p; j++) {\r\n let t = hypotenuse(s[j], f);\r\n let cs = s[j] / t;\r\n let sn = f / t;\r\n s[j] = t;\r\n f = -sn * e[j];\r\n e[j] = cs * e[j];\r\n if (wantu) {\r\n for (let i = 0; i < m; i++) {\r\n t = cs * U[i][j] + sn * U[i][k - 1];\r\n U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1];\r\n U[i][j] = t;\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n case 3: {\r\n const scale = Math.max(\r\n Math.abs(s[p - 1]),\r\n Math.abs(s[p - 2]),\r\n Math.abs(e[p - 2]),\r\n Math.abs(s[k]),\r\n Math.abs(e[k])\r\n );\r\n const sp = s[p - 1] / scale;\r\n const spm1 = s[p - 2] / scale;\r\n const epm1 = e[p - 2] / scale;\r\n const sk = s[k] / scale;\r\n const ek = e[k] / scale;\r\n const b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;\r\n const c = sp * epm1 * (sp * epm1);\r\n let shift = 0;\r\n if (b !== 0 || c !== 0) {\r\n if (b < 0) {\r\n shift = 0 - Math.sqrt(b * b + c);\r\n } else {\r\n shift = Math.sqrt(b * b + c);\r\n }\r\n shift = c / (b + shift);\r\n }\r\n let f = (sk + sp) * (sk - sp) + shift;\r\n let g = sk * ek;\r\n for (let j = k; j < p - 1; j++) {\r\n let t = hypotenuse(f, g);\r\n if (t === 0) t = Number.MIN_VALUE;\r\n let cs = f / t;\r\n let sn = g / t;\r\n if (j !== k) {\r\n e[j - 1] = t;\r\n }\r\n f = cs * s[j] + sn * e[j];\r\n e[j] = cs * e[j] - sn * s[j];\r\n g = sn * s[j + 1];\r\n s[j + 1] = cs * s[j + 1];\r\n if (wantv) {\r\n for (let i = 0; i < n; i++) {\r\n t = cs * V[i][j] + sn * V[i][j + 1];\r\n V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1];\r\n V[i][j] = t;\r\n }\r\n }\r\n t = hypotenuse(f, g);\r\n if (t === 0) t = Number.MIN_VALUE;\r\n cs = f / t;\r\n sn = g / t;\r\n s[j] = t;\r\n f = cs * e[j] + sn * s[j + 1];\r\n s[j + 1] = -sn * e[j] + cs * s[j + 1];\r\n g = sn * e[j + 1];\r\n e[j + 1] = cs * e[j + 1];\r\n if (wantu && j < m - 1) {\r\n for (let i = 0; i < m; i++) {\r\n t = cs * U[i][j] + sn * U[i][j + 1];\r\n U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1];\r\n U[i][j] = t;\r\n }\r\n }\r\n }\r\n e[p - 2] = f;\r\n iter = iter + 1;\r\n break;\r\n }\r\n case 4: {\r\n if (s[k] <= 0) {\r\n s[k] = s[k] < 0 ? -s[k] : 0;\r\n if (wantv) {\r\n for (let i = 0; i <= pp; i++) {\r\n V[i][k] = -V[i][k];\r\n }\r\n }\r\n }\r\n while (k < pp) {\r\n if (s[k] >= s[k + 1]) {\r\n break;\r\n }\r\n let t = s[k];\r\n s[k] = s[k + 1];\r\n s[k + 1] = t;\r\n if (wantv && k < n - 1) {\r\n for (let i = 0; i < n; i++) {\r\n t = V[i][k + 1];\r\n V[i][k + 1] = V[i][k];\r\n V[i][k] = t;\r\n }\r\n }\r\n if (wantu && k < m - 1) {\r\n for (let i = 0; i < m; i++) {\r\n t = U[i][k + 1];\r\n U[i][k + 1] = U[i][k];\r\n U[i][k] = t;\r\n }\r\n }\r\n k++;\r\n }\r\n iter = 0;\r\n p--;\r\n break;\r\n }\r\n // no default\r\n }\r\n }\r\n\r\n if (swapped) {\r\n var tmp = V;\r\n V = U;\r\n U = tmp;\r\n }\r\n\r\n this.m = m;\r\n this.n = n;\r\n this.s = s;\r\n this.U = U;\r\n this.V = V;\r\n }\r\n\r\n /**\r\n * Solve a problem of least square (Ax=b) by using the SVD. Useful when A is singular. When A is not singular, it would be better to use qr.solve(value).\r\n * Example : We search to approximate x, with A matrix shape m*n, x vector size n, b vector size m (m > n). We will use :\r\n * var svd = SingularValueDecomposition(A);\r\n * var x = svd.solve(b);\r\n * @param {Matrix} value - Matrix 1D which is the vector b (in the equation Ax = b)\r\n * @return {Matrix} - The vector x\r\n */\r\n solve(value) {\r\n var Y = value;\r\n var e = this.threshold;\r\n var scols = this.s.length;\r\n var Ls = Matrix.zeros(scols, scols);\r\n\r\n for (let i = 0; i < scols; i++) {\r\n if (Math.abs(this.s[i]) <= e) {\r\n Ls[i][i] = 0;\r\n } else {\r\n Ls[i][i] = 1 / this.s[i];\r\n }\r\n }\r\n\r\n var U = this.U;\r\n var V = this.rightSingularVectors;\r\n\r\n var VL = V.mmul(Ls);\r\n var vrows = V.rows;\r\n var urows = U.length;\r\n var VLU = Matrix.zeros(vrows, urows);\r\n\r\n for (let i = 0; i < vrows; i++) {\r\n for (let j = 0; j < urows; j++) {\r\n let sum = 0;\r\n for (let k = 0; k < scols; k++) {\r\n sum += VL[i][k] * U[j][k];\r\n }\r\n VLU[i][j] = sum;\r\n }\r\n }\r\n\r\n return VLU.mmul(Y);\r\n }\r\n\r\n /**\r\n *\r\n * @param {Array} value\r\n * @return {Matrix}\r\n */\r\n solveForDiagonal(value) {\r\n return this.solve(Matrix.diag(value));\r\n }\r\n\r\n /**\r\n * Get the inverse of the matrix. We compute the inverse of a matrix using SVD when this matrix is singular or ill-conditioned. Example :\r\n * var svd = SingularValueDecomposition(A);\r\n * var inverseA = svd.inverse();\r\n * @return {Matrix} - The approximation of the inverse of the matrix\r\n */\r\n inverse() {\r\n var V = this.V;\r\n var e = this.threshold;\r\n var vrows = V.length;\r\n var vcols = V[0].length;\r\n var X = new Matrix(vrows, this.s.length);\r\n\r\n for (let i = 0; i < vrows; i++) {\r\n for (let j = 0; j < vcols; j++) {\r\n if (Math.abs(this.s[j]) > e) {\r\n X[i][j] = V[i][j] / this.s[j];\r\n } else {\r\n X[i][j] = 0;\r\n }\r\n }\r\n }\r\n\r\n var U = this.U;\r\n\r\n var urows = U.length;\r\n var ucols = U[0].length;\r\n var Y = new Matrix(vrows, urows);\r\n\r\n for (let i = 0; i < vrows; i++) {\r\n for (let j = 0; j < urows; j++) {\r\n let sum = 0;\r\n for (let k = 0; k < ucols; k++) {\r\n sum += X[i][k] * U[j][k];\r\n }\r\n Y[i][j] = sum;\r\n }\r\n }\r\n\r\n return Y;\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get condition() {\r\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get norm2() {\r\n return this.s[0];\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get rank() {\r\n var tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON;\r\n var r = 0;\r\n var s = this.s;\r\n for (var i = 0, ii = s.length; i < ii; i++) {\r\n if (s[i] > tol) {\r\n r++;\r\n }\r\n }\r\n return r;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Array}\r\n */\r\n get diagonal() {\r\n return this.s;\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get threshold() {\r\n return Number.EPSILON / 2 * Math.max(this.m, this.n) * this.s[0];\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get leftSingularVectors() {\r\n if (!Matrix.isMatrix(this.U)) {\r\n this.U = new Matrix(this.U);\r\n }\r\n return this.U;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get rightSingularVectors() {\r\n if (!Matrix.isMatrix(this.V)) {\r\n this.V = new Matrix(this.V);\r\n }\r\n return this.V;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get diagonalMatrix() {\r\n return Matrix.diag(this.s);\r\n }\r\n}\r\n","import Matrix from './matrix';\r\n\r\n/**\r\n * @private\r\n * Check that a row index is not out of bounds\r\n * @param {Matrix} matrix\r\n * @param {number} index\r\n * @param {boolean} [outer]\r\n */\r\nexport function checkRowIndex(matrix, index, outer) {\r\n var max = outer ? matrix.rows : matrix.rows - 1;\r\n if (index < 0 || index > max) {\r\n throw new RangeError('Row index out of range');\r\n }\r\n}\r\n\r\n/**\r\n * @private\r\n * Check that a column index is not out of bounds\r\n * @param {Matrix} matrix\r\n * @param {number} index\r\n * @param {boolean} [outer]\r\n */\r\nexport function checkColumnIndex(matrix, index, outer) {\r\n var max = outer ? matrix.columns : matrix.columns - 1;\r\n if (index < 0 || index > max) {\r\n throw new RangeError('Column index out of range');\r\n }\r\n}\r\n\r\n/**\r\n * @private\r\n * Check that the provided vector is an array with the right length\r\n * @param {Matrix} matrix\r\n * @param {Array|Matrix} vector\r\n * @return {Array}\r\n * @throws {RangeError}\r\n */\r\nexport function checkRowVector(matrix, vector) {\r\n if (vector.to1DArray) {\r\n vector = vector.to1DArray();\r\n }\r\n if (vector.length !== matrix.columns) {\r\n throw new RangeError(\r\n 'vector size must be the same as the number of columns'\r\n );\r\n }\r\n return vector;\r\n}\r\n\r\n/**\r\n * @private\r\n * Check that the provided vector is an array with the right length\r\n * @param {Matrix} matrix\r\n * @param {Array|Matrix} vector\r\n * @return {Array}\r\n * @throws {RangeError}\r\n */\r\nexport function checkColumnVector(matrix, vector) {\r\n if (vector.to1DArray) {\r\n vector = vector.to1DArray();\r\n }\r\n if (vector.length !== matrix.rows) {\r\n throw new RangeError('vector size must be the same as the number of rows');\r\n }\r\n return vector;\r\n}\r\n\r\nexport function checkIndices(matrix, rowIndices, columnIndices) {\r\n return {\r\n row: checkRowIndices(matrix, rowIndices),\r\n column: checkColumnIndices(matrix, columnIndices)\r\n };\r\n}\r\n\r\nexport function checkRowIndices(matrix, rowIndices) {\r\n if (typeof rowIndices !== 'object') {\r\n throw new TypeError('unexpected type for row indices');\r\n }\r\n\r\n var rowOut = rowIndices.some((r) => {\r\n return r < 0 || r >= matrix.rows;\r\n });\r\n\r\n if (rowOut) {\r\n throw new RangeError('row indices are out of range');\r\n }\r\n\r\n if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices);\r\n\r\n return rowIndices;\r\n}\r\n\r\nexport function checkColumnIndices(matrix, columnIndices) {\r\n if (typeof columnIndices !== 'object') {\r\n throw new TypeError('unexpected type for column indices');\r\n }\r\n\r\n var columnOut = columnIndices.some((c) => {\r\n return c < 0 || c >= matrix.columns;\r\n });\r\n\r\n if (columnOut) {\r\n throw new RangeError('column indices are out of range');\r\n }\r\n if (!Array.isArray(columnIndices)) columnIndices = Array.from(columnIndices);\r\n\r\n return columnIndices;\r\n}\r\n\r\nexport function checkRange(matrix, startRow, endRow, startColumn, endColumn) {\r\n if (arguments.length !== 5) {\r\n throw new RangeError('expected 4 arguments');\r\n }\r\n checkNumber('startRow', startRow);\r\n checkNumber('endRow', endRow);\r\n checkNumber('startColumn', startColumn);\r\n checkNumber('endColumn', endColumn);\r\n if (\r\n startRow > endRow ||\r\n startColumn > endColumn ||\r\n startRow < 0 ||\r\n startRow >= matrix.rows ||\r\n endRow < 0 ||\r\n endRow >= matrix.rows ||\r\n startColumn < 0 ||\r\n startColumn >= matrix.columns ||\r\n endColumn < 0 ||\r\n endColumn >= matrix.columns\r\n ) {\r\n throw new RangeError('Submatrix indices are out of range');\r\n }\r\n}\r\n\r\nexport function getRange(from, to) {\r\n var arr = new Array(to - from + 1);\r\n for (var i = 0; i < arr.length; i++) {\r\n arr[i] = from + i;\r\n }\r\n return arr;\r\n}\r\n\r\nexport function sumByRow(matrix) {\r\n var sum = Matrix.zeros(matrix.rows, 1);\r\n for (var i = 0; i < matrix.rows; ++i) {\r\n for (var j = 0; j < matrix.columns; ++j) {\r\n sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j));\r\n }\r\n }\r\n return sum;\r\n}\r\n\r\nexport function sumByColumn(matrix) {\r\n var sum = Matrix.zeros(1, matrix.columns);\r\n for (var i = 0; i < matrix.rows; ++i) {\r\n for (var j = 0; j < matrix.columns; ++j) {\r\n sum.set(0, j, sum.get(0, j) + matrix.get(i, j));\r\n }\r\n }\r\n return sum;\r\n}\r\n\r\nexport function sumAll(matrix) {\r\n var v = 0;\r\n for (var i = 0; i < matrix.rows; i++) {\r\n for (var j = 0; j < matrix.columns; j++) {\r\n v += matrix.get(i, j);\r\n }\r\n }\r\n return v;\r\n}\r\n\r\nfunction checkNumber(name, value) {\r\n if (typeof value !== 'number') {\r\n throw new TypeError(`${name} must be a number`);\r\n }\r\n}\r\n","import AbstractMatrix from '../abstractMatrix';\r\nimport Matrix from '../matrix';\r\n\r\nexport default class BaseView extends AbstractMatrix() {\r\n constructor(matrix, rows, columns) {\r\n super();\r\n this.matrix = matrix;\r\n this.rows = rows;\r\n this.columns = columns;\r\n }\r\n\r\n static get [Symbol.species]() {\r\n return Matrix;\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixTransposeView extends BaseView {\r\n constructor(matrix) {\r\n super(matrix, matrix.columns, matrix.rows);\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(columnIndex, rowIndex, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(columnIndex, rowIndex);\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixRowView extends BaseView {\r\n constructor(matrix, row) {\r\n super(matrix, 1, matrix.columns);\r\n this.row = row;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(this.row, columnIndex, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(this.row, columnIndex);\r\n }\r\n}\r\n","import { checkRange } from '../util';\r\n\r\nimport BaseView from './base';\r\n\r\nexport default class MatrixSubView extends BaseView {\r\n constructor(matrix, startRow, endRow, startColumn, endColumn) {\r\n checkRange(matrix, startRow, endRow, startColumn, endColumn);\r\n super(matrix, endRow - startRow + 1, endColumn - startColumn + 1);\r\n this.startRow = startRow;\r\n this.startColumn = startColumn;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(\r\n this.startRow + rowIndex,\r\n this.startColumn + columnIndex,\r\n value\r\n );\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(\r\n this.startRow + rowIndex,\r\n this.startColumn + columnIndex\r\n );\r\n }\r\n}\r\n","import { checkIndices } from '../util';\r\n\r\nimport BaseView from './base';\r\n\r\nexport default class MatrixSelectionView extends BaseView {\r\n constructor(matrix, rowIndices, columnIndices) {\r\n var indices = checkIndices(matrix, rowIndices, columnIndices);\r\n super(matrix, indices.row.length, indices.column.length);\r\n this.rowIndices = indices.row;\r\n this.columnIndices = indices.column;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(\r\n this.rowIndices[rowIndex],\r\n this.columnIndices[columnIndex],\r\n value\r\n );\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(\r\n this.rowIndices[rowIndex],\r\n this.columnIndices[columnIndex]\r\n );\r\n }\r\n}\r\n","import { checkRowIndices } from '../util';\r\n\r\nimport BaseView from './base';\r\n\r\nexport default class MatrixRowSelectionView extends BaseView {\r\n constructor(matrix, rowIndices) {\r\n rowIndices = checkRowIndices(matrix, rowIndices);\r\n super(matrix, rowIndices.length, matrix.columns);\r\n this.rowIndices = rowIndices;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(this.rowIndices[rowIndex], columnIndex, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(this.rowIndices[rowIndex], columnIndex);\r\n }\r\n}\r\n","import { checkColumnIndices } from '../util';\r\n\r\nimport BaseView from './base';\r\n\r\nexport default class MatrixColumnSelectionView extends BaseView {\r\n constructor(matrix, columnIndices) {\r\n columnIndices = checkColumnIndices(matrix, columnIndices);\r\n super(matrix, matrix.rows, columnIndices.length);\r\n this.columnIndices = columnIndices;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(rowIndex, this.columnIndices[columnIndex], value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(rowIndex, this.columnIndices[columnIndex]);\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixColumnView extends BaseView {\r\n constructor(matrix, column) {\r\n super(matrix, matrix.rows, 1);\r\n this.column = column;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(rowIndex, this.column, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex) {\r\n return this.matrix.get(rowIndex, this.column);\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixFlipRowView extends BaseView {\r\n constructor(matrix) {\r\n super(matrix, matrix.rows, matrix.columns);\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(this.rows - rowIndex - 1, columnIndex, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(this.rows - rowIndex - 1, columnIndex);\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixFlipColumnView extends BaseView {\r\n constructor(matrix) {\r\n super(matrix, matrix.rows, matrix.columns);\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(rowIndex, this.columns - columnIndex - 1, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(rowIndex, this.columns - columnIndex - 1);\r\n }\r\n}\r\n","import rescale from 'ml-array-rescale';\r\n\r\nimport LuDecomposition from './dc/lu';\r\nimport SvDecomposition from './dc/svd';\r\nimport {\r\n checkRowVector, checkRowIndex, checkColumnIndex, checkColumnVector,\r\n checkRange, checkIndices,\r\n sumByRow, sumByColumn, sumAll\r\n} from './util';\r\nimport MatrixTransposeView from './views/transpose';\r\nimport MatrixRowView from './views/row';\r\nimport MatrixSubView from './views/sub';\r\nimport MatrixSelectionView from './views/selection';\r\nimport MatrixRowSelectionView from './views/rowSelection';\r\nimport MatrixColumnSelectionView from './views/columnSelection';\r\nimport MatrixColumnView from './views/column';\r\nimport MatrixFlipRowView from './views/flipRow';\r\nimport MatrixFlipColumnView from './views/flipColumn';\r\n\r\nexport default function AbstractMatrix(superCtor) {\r\n if (superCtor === undefined) superCtor = Object;\r\n\r\n /**\r\n * Real matrix\r\n * @class Matrix\r\n * @param {number|Array|Matrix} nRows - Number of rows of the new matrix,\r\n * 2D array containing the data or Matrix instance to clone\r\n * @param {number} [nColumns] - Number of columns of the new matrix\r\n */\r\n class Matrix extends superCtor {\r\n static get [Symbol.species]() {\r\n return this;\r\n }\r\n\r\n /**\r\n * Constructs a Matrix with the chosen dimensions from a 1D array\r\n * @param {number} newRows - Number of rows\r\n * @param {number} newColumns - Number of columns\r\n * @param {Array} newData - A 1D array containing data for the matrix\r\n * @return {Matrix} - The new matrix\r\n */\r\n static from1DArray(newRows, newColumns, newData) {\r\n var length = newRows * newColumns;\r\n if (length !== newData.length) {\r\n throw new RangeError('Data length does not match given dimensions');\r\n }\r\n var newMatrix = new this(newRows, newColumns);\r\n for (var row = 0; row < newRows; row++) {\r\n for (var column = 0; column < newColumns; column++) {\r\n newMatrix.set(row, column, newData[row * newColumns + column]);\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Creates a row vector, a matrix with only one row.\r\n * @param {Array} newData - A 1D array containing data for the vector\r\n * @return {Matrix} - The new matrix\r\n */\r\n static rowVector(newData) {\r\n var vector = new this(1, newData.length);\r\n for (var i = 0; i < newData.length; i++) {\r\n vector.set(0, i, newData[i]);\r\n }\r\n return vector;\r\n }\r\n\r\n /**\r\n * Creates a column vector, a matrix with only one column.\r\n * @param {Array} newData - A 1D array containing data for the vector\r\n * @return {Matrix} - The new matrix\r\n */\r\n static columnVector(newData) {\r\n var vector = new this(newData.length, 1);\r\n for (var i = 0; i < newData.length; i++) {\r\n vector.set(i, 0, newData[i]);\r\n }\r\n return vector;\r\n }\r\n\r\n /**\r\n * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns).\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @return {Matrix} - The new matrix\r\n */\r\n static empty(rows, columns) {\r\n return new this(rows, columns);\r\n }\r\n\r\n /**\r\n * Creates a matrix with the given dimensions. Values will be set to zero.\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @return {Matrix} - The new matrix\r\n */\r\n static zeros(rows, columns) {\r\n return this.empty(rows, columns).fill(0);\r\n }\r\n\r\n /**\r\n * Creates a matrix with the given dimensions. Values will be set to one.\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @return {Matrix} - The new matrix\r\n */\r\n static ones(rows, columns) {\r\n return this.empty(rows, columns).fill(1);\r\n }\r\n\r\n /**\r\n * Creates a matrix with the given dimensions. Values will be randomly set.\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @param {function} [rng=Math.random] - Random number generator\r\n * @return {Matrix} The new matrix\r\n */\r\n static rand(rows, columns, rng) {\r\n if (rng === undefined) rng = Math.random;\r\n var matrix = this.empty(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n matrix.set(i, j, rng());\r\n }\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Creates a matrix with the given dimensions. Values will be random integers.\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @param {number} [maxValue=1000] - Maximum value\r\n * @param {function} [rng=Math.random] - Random number generator\r\n * @return {Matrix} The new matrix\r\n */\r\n static randInt(rows, columns, maxValue, rng) {\r\n if (maxValue === undefined) maxValue = 1000;\r\n if (rng === undefined) rng = Math.random;\r\n var matrix = this.empty(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n var value = Math.floor(rng() * maxValue);\r\n matrix.set(i, j, value);\r\n }\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0.\r\n * @param {number} rows - Number of rows\r\n * @param {number} [columns=rows] - Number of columns\r\n * @param {number} [value=1] - Value to fill the diagonal with\r\n * @return {Matrix} - The new identity matrix\r\n */\r\n static eye(rows, columns, value) {\r\n if (columns === undefined) columns = rows;\r\n if (value === undefined) value = 1;\r\n var min = Math.min(rows, columns);\r\n var matrix = this.zeros(rows, columns);\r\n for (var i = 0; i < min; i++) {\r\n matrix.set(i, i, value);\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Creates a diagonal matrix based on the given array.\r\n * @param {Array} data - Array containing the data for the diagonal\r\n * @param {number} [rows] - Number of rows (Default: data.length)\r\n * @param {number} [columns] - Number of columns (Default: rows)\r\n * @return {Matrix} - The new diagonal matrix\r\n */\r\n static diag(data, rows, columns) {\r\n var l = data.length;\r\n if (rows === undefined) rows = l;\r\n if (columns === undefined) columns = rows;\r\n var min = Math.min(l, rows, columns);\r\n var matrix = this.zeros(rows, columns);\r\n for (var i = 0; i < min; i++) {\r\n matrix.set(i, i, data[i]);\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Returns a matrix whose elements are the minimum between matrix1 and matrix2\r\n * @param {Matrix} matrix1\r\n * @param {Matrix} matrix2\r\n * @return {Matrix}\r\n */\r\n static min(matrix1, matrix2) {\r\n matrix1 = this.checkMatrix(matrix1);\r\n matrix2 = this.checkMatrix(matrix2);\r\n var rows = matrix1.rows;\r\n var columns = matrix1.columns;\r\n var result = new this(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a matrix whose elements are the maximum between matrix1 and matrix2\r\n * @param {Matrix} matrix1\r\n * @param {Matrix} matrix2\r\n * @return {Matrix}\r\n */\r\n static max(matrix1, matrix2) {\r\n matrix1 = this.checkMatrix(matrix1);\r\n matrix2 = this.checkMatrix(matrix2);\r\n var rows = matrix1.rows;\r\n var columns = matrix1.columns;\r\n var result = new this(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Check that the provided value is a Matrix and tries to instantiate one if not\r\n * @param {*} value - The value to check\r\n * @return {Matrix}\r\n */\r\n static checkMatrix(value) {\r\n return Matrix.isMatrix(value) ? value : new this(value);\r\n }\r\n\r\n /**\r\n * Returns true if the argument is a Matrix, false otherwise\r\n * @param {*} value - The value to check\r\n * @return {boolean}\r\n */\r\n static isMatrix(value) {\r\n return (value != null) && (value.klass === 'Matrix');\r\n }\r\n\r\n /**\r\n * @prop {number} size - The number of elements in the matrix.\r\n */\r\n get size() {\r\n return this.rows * this.columns;\r\n }\r\n\r\n /**\r\n * Applies a callback for each element of the matrix. The function is called in the matrix (this) context.\r\n * @param {function} callback - Function that will be called with two parameters : i (row) and j (column)\r\n * @return {Matrix} this\r\n */\r\n apply(callback) {\r\n if (typeof callback !== 'function') {\r\n throw new TypeError('callback must be a function');\r\n }\r\n var ii = this.rows;\r\n var jj = this.columns;\r\n for (var i = 0; i < ii; i++) {\r\n for (var j = 0; j < jj; j++) {\r\n callback.call(this, i, j);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns a new 1D array filled row by row with the matrix values\r\n * @return {Array}\r\n */\r\n to1DArray() {\r\n var array = new Array(this.size);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n array[i * this.columns + j] = this.get(i, j);\r\n }\r\n }\r\n return array;\r\n }\r\n\r\n /**\r\n * Returns a 2D array containing a copy of the data\r\n * @return {Array}\r\n */\r\n to2DArray() {\r\n var copy = new Array(this.rows);\r\n for (var i = 0; i < this.rows; i++) {\r\n copy[i] = new Array(this.columns);\r\n for (var j = 0; j < this.columns; j++) {\r\n copy[i][j] = this.get(i, j);\r\n }\r\n }\r\n return copy;\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix has one row\r\n */\r\n isRowVector() {\r\n return this.rows === 1;\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix has one column\r\n */\r\n isColumnVector() {\r\n return this.columns === 1;\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix has one row or one column\r\n */\r\n isVector() {\r\n return (this.rows === 1) || (this.columns === 1);\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix has the same number of rows and columns\r\n */\r\n isSquare() {\r\n return this.rows === this.columns;\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal\r\n */\r\n isSymmetric() {\r\n if (this.isSquare()) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j <= i; j++) {\r\n if (this.get(i, j) !== this.get(j, i)) {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * @return true if the matrix is in echelon form\r\n */\r\n isEchelonForm() {\r\n let i = 0;\r\n let j = 0;\r\n let previousColumn = -1;\r\n let isEchelonForm = true;\r\n let checked = false;\r\n while ((i < this.rows) && (isEchelonForm)) {\r\n j = 0;\r\n checked = false;\r\n while ((j < this.columns) && (checked === false)) {\r\n if (this.get(i, j) === 0) {\r\n j++;\r\n } else if ((this.get(i, j) === 1) && (j > previousColumn)) {\r\n checked = true;\r\n previousColumn = j;\r\n } else {\r\n isEchelonForm = false;\r\n checked = true;\r\n }\r\n }\r\n i++;\r\n }\r\n return isEchelonForm;\r\n }\r\n\r\n /**\r\n * @return true if the matrix is in reduced echelon form\r\n */\r\n isReducedEchelonForm() {\r\n let i = 0;\r\n let j = 0;\r\n let previousColumn = -1;\r\n let isReducedEchelonForm = true;\r\n let checked = false;\r\n while ((i < this.rows) && (isReducedEchelonForm)) {\r\n j = 0;\r\n checked = false;\r\n while ((j < this.columns) && (checked === false)) {\r\n if (this.get(i, j) === 0) {\r\n j++;\r\n } else if ((this.get(i, j) === 1) && (j > previousColumn)) {\r\n checked = true;\r\n previousColumn = j;\r\n } else {\r\n isReducedEchelonForm = false;\r\n checked = true;\r\n }\r\n }\r\n for (let k = j + 1; k < this.rows; k++) {\r\n if (this.get(i, k) !== 0) {\r\n isReducedEchelonForm = false;\r\n }\r\n }\r\n i++;\r\n }\r\n return isReducedEchelonForm;\r\n }\r\n\r\n /**\r\n * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1\r\n * @abstract\r\n * @param {number} rowIndex - Index of the row\r\n * @param {number} columnIndex - Index of the column\r\n * @param {number} value - The new value for the element\r\n * @return {Matrix} this\r\n */\r\n set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars\r\n throw new Error('set method is unimplemented');\r\n }\r\n\r\n /**\r\n * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4]\r\n * @abstract\r\n * @param {number} rowIndex - Index of the row\r\n * @param {number} columnIndex - Index of the column\r\n * @return {number}\r\n */\r\n get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars\r\n throw new Error('get method is unimplemented');\r\n }\r\n\r\n /**\r\n * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of\r\n * rows of the matrix, and colRep times the number of columns of the matrix\r\n * @param {number} rowRep - Number of times the rows should be repeated\r\n * @param {number} colRep - Number of times the columns should be re\r\n * @return {Matrix}\r\n * @example\r\n * var matrix = new Matrix([[1,2]]);\r\n * matrix.repeat(2); // [[1,2],[1,2]]\r\n */\r\n repeat(rowRep, colRep) {\r\n rowRep = rowRep || 1;\r\n colRep = colRep || 1;\r\n var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep);\r\n for (var i = 0; i < rowRep; i++) {\r\n for (var j = 0; j < colRep; j++) {\r\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\r\n }\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Fills the matrix with a given value. All elements will be set to this value.\r\n * @param {number} value - New value\r\n * @return {Matrix} this\r\n */\r\n fill(value) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, value);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Negates the matrix. All elements will be multiplied by (-1)\r\n * @return {Matrix} this\r\n */\r\n neg() {\r\n return this.mulS(-1);\r\n }\r\n\r\n /**\r\n * Returns a new array from the given row index\r\n * @param {number} index - Row index\r\n * @return {Array}\r\n */\r\n getRow(index) {\r\n checkRowIndex(this, index);\r\n var row = new Array(this.columns);\r\n for (var i = 0; i < this.columns; i++) {\r\n row[i] = this.get(index, i);\r\n }\r\n return row;\r\n }\r\n\r\n /**\r\n * Returns a new row vector from the given row index\r\n * @param {number} index - Row index\r\n * @return {Matrix}\r\n */\r\n getRowVector(index) {\r\n return this.constructor.rowVector(this.getRow(index));\r\n }\r\n\r\n /**\r\n * Sets a row at the given index\r\n * @param {number} index - Row index\r\n * @param {Array|Matrix} array - Array or vector\r\n * @return {Matrix} this\r\n */\r\n setRow(index, array) {\r\n checkRowIndex(this, index);\r\n array = checkRowVector(this, array);\r\n for (var i = 0; i < this.columns; i++) {\r\n this.set(index, i, array[i]);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Swaps two rows\r\n * @param {number} row1 - First row index\r\n * @param {number} row2 - Second row index\r\n * @return {Matrix} this\r\n */\r\n swapRows(row1, row2) {\r\n checkRowIndex(this, row1);\r\n checkRowIndex(this, row2);\r\n for (var i = 0; i < this.columns; i++) {\r\n var temp = this.get(row1, i);\r\n this.set(row1, i, this.get(row2, i));\r\n this.set(row2, i, temp);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns a new array from the given column index\r\n * @param {number} index - Column index\r\n * @return {Array}\r\n */\r\n getColumn(index) {\r\n checkColumnIndex(this, index);\r\n var column = new Array(this.rows);\r\n for (var i = 0; i < this.rows; i++) {\r\n column[i] = this.get(i, index);\r\n }\r\n return column;\r\n }\r\n\r\n /**\r\n * Returns a new column vector from the given column index\r\n * @param {number} index - Column index\r\n * @return {Matrix}\r\n */\r\n getColumnVector(index) {\r\n return this.constructor.columnVector(this.getColumn(index));\r\n }\r\n\r\n /**\r\n * Sets a column at the given index\r\n * @param {number} index - Column index\r\n * @param {Array|Matrix} array - Array or vector\r\n * @return {Matrix} this\r\n */\r\n setColumn(index, array) {\r\n checkColumnIndex(this, index);\r\n array = checkColumnVector(this, array);\r\n for (var i = 0; i < this.rows; i++) {\r\n this.set(i, index, array[i]);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Swaps two columns\r\n * @param {number} column1 - First column index\r\n * @param {number} column2 - Second column index\r\n * @return {Matrix} this\r\n */\r\n swapColumns(column1, column2) {\r\n checkColumnIndex(this, column1);\r\n checkColumnIndex(this, column2);\r\n for (var i = 0; i < this.rows; i++) {\r\n var temp = this.get(i, column1);\r\n this.set(i, column1, this.get(i, column2));\r\n this.set(i, column2, temp);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Adds the values of a vector to each row\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n addRowVector(vector) {\r\n vector = checkRowVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) + vector[j]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Subtracts the values of a vector from each row\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n subRowVector(vector) {\r\n vector = checkRowVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) - vector[j]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Multiplies the values of a vector with each row\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n mulRowVector(vector) {\r\n vector = checkRowVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) * vector[j]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Divides the values of each row by those of a vector\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n divRowVector(vector) {\r\n vector = checkRowVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) / vector[j]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Adds the values of a vector to each column\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n addColumnVector(vector) {\r\n vector = checkColumnVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) + vector[i]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Subtracts the values of a vector from each column\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n subColumnVector(vector) {\r\n vector = checkColumnVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) - vector[i]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Multiplies the values of a vector with each column\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n mulColumnVector(vector) {\r\n vector = checkColumnVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) * vector[i]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Divides the values of each column by those of a vector\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n divColumnVector(vector) {\r\n vector = checkColumnVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) / vector[i]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Multiplies the values of a row with a scalar\r\n * @param {number} index - Row index\r\n * @param {number} value\r\n * @return {Matrix} this\r\n */\r\n mulRow(index, value) {\r\n checkRowIndex(this, index);\r\n for (var i = 0; i < this.columns; i++) {\r\n this.set(index, i, this.get(index, i) * value);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Multiplies the values of a column with a scalar\r\n * @param {number} index - Column index\r\n * @param {number} value\r\n * @return {Matrix} this\r\n */\r\n mulColumn(index, value) {\r\n checkColumnIndex(this, index);\r\n for (var i = 0; i < this.rows; i++) {\r\n this.set(i, index, this.get(i, index) * value);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns the maximum value of the matrix\r\n * @return {number}\r\n */\r\n max() {\r\n var v = this.get(0, 0);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n if (this.get(i, j) > v) {\r\n v = this.get(i, j);\r\n }\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the maximum value\r\n * @return {Array}\r\n */\r\n maxIndex() {\r\n var v = this.get(0, 0);\r\n var idx = [0, 0];\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n if (this.get(i, j) > v) {\r\n v = this.get(i, j);\r\n idx[0] = i;\r\n idx[1] = j;\r\n }\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the minimum value of the matrix\r\n * @return {number}\r\n */\r\n min() {\r\n var v = this.get(0, 0);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n if (this.get(i, j) < v) {\r\n v = this.get(i, j);\r\n }\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the minimum value\r\n * @return {Array}\r\n */\r\n minIndex() {\r\n var v = this.get(0, 0);\r\n var idx = [0, 0];\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n if (this.get(i, j) < v) {\r\n v = this.get(i, j);\r\n idx[0] = i;\r\n idx[1] = j;\r\n }\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the maximum value of one row\r\n * @param {number} row - Row index\r\n * @return {number}\r\n */\r\n maxRow(row) {\r\n checkRowIndex(this, row);\r\n var v = this.get(row, 0);\r\n for (var i = 1; i < this.columns; i++) {\r\n if (this.get(row, i) > v) {\r\n v = this.get(row, i);\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the maximum value of one row\r\n * @param {number} row - Row index\r\n * @return {Array}\r\n */\r\n maxRowIndex(row) {\r\n checkRowIndex(this, row);\r\n var v = this.get(row, 0);\r\n var idx = [row, 0];\r\n for (var i = 1; i < this.columns; i++) {\r\n if (this.get(row, i) > v) {\r\n v = this.get(row, i);\r\n idx[1] = i;\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the minimum value of one row\r\n * @param {number} row - Row index\r\n * @return {number}\r\n */\r\n minRow(row) {\r\n checkRowIndex(this, row);\r\n var v = this.get(row, 0);\r\n for (var i = 1; i < this.columns; i++) {\r\n if (this.get(row, i) < v) {\r\n v = this.get(row, i);\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the maximum value of one row\r\n * @param {number} row - Row index\r\n * @return {Array}\r\n */\r\n minRowIndex(row) {\r\n checkRowIndex(this, row);\r\n var v = this.get(row, 0);\r\n var idx = [row, 0];\r\n for (var i = 1; i < this.columns; i++) {\r\n if (this.get(row, i) < v) {\r\n v = this.get(row, i);\r\n idx[1] = i;\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the maximum value of one column\r\n * @param {number} column - Column index\r\n * @return {number}\r\n */\r\n maxColumn(column) {\r\n checkColumnIndex(this, column);\r\n var v = this.get(0, column);\r\n for (var i = 1; i < this.rows; i++) {\r\n if (this.get(i, column) > v) {\r\n v = this.get(i, column);\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the maximum value of one column\r\n * @param {number} column - Column index\r\n * @return {Array}\r\n */\r\n maxColumnIndex(column) {\r\n checkColumnIndex(this, column);\r\n var v = this.get(0, column);\r\n var idx = [0, column];\r\n for (var i = 1; i < this.rows; i++) {\r\n if (this.get(i, column) > v) {\r\n v = this.get(i, column);\r\n idx[0] = i;\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the minimum value of one column\r\n * @param {number} column - Column index\r\n * @return {number}\r\n */\r\n minColumn(column) {\r\n checkColumnIndex(this, column);\r\n var v = this.get(0, column);\r\n for (var i = 1; i < this.rows; i++) {\r\n if (this.get(i, column) < v) {\r\n v = this.get(i, column);\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the minimum value of one column\r\n * @param {number} column - Column index\r\n * @return {Array}\r\n */\r\n minColumnIndex(column) {\r\n checkColumnIndex(this, column);\r\n var v = this.get(0, column);\r\n var idx = [0, column];\r\n for (var i = 1; i < this.rows; i++) {\r\n if (this.get(i, column) < v) {\r\n v = this.get(i, column);\r\n idx[0] = i;\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns an array containing the diagonal values of the matrix\r\n * @return {Array}\r\n */\r\n diag() {\r\n var min = Math.min(this.rows, this.columns);\r\n var diag = new Array(min);\r\n for (var i = 0; i < min; i++) {\r\n diag[i] = this.get(i, i);\r\n }\r\n return diag;\r\n }\r\n\r\n /**\r\n * Returns the sum by the argument given, if no argument given,\r\n * it returns the sum of all elements of the matrix.\r\n * @param {string} by - sum by 'row' or 'column'.\r\n * @return {Matrix|number}\r\n */\r\n sum(by) {\r\n switch (by) {\r\n case 'row':\r\n return sumByRow(this);\r\n case 'column':\r\n return sumByColumn(this);\r\n default:\r\n return sumAll(this);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the mean of all elements of the matrix\r\n * @return {number}\r\n */\r\n mean() {\r\n return this.sum() / this.size;\r\n }\r\n\r\n /**\r\n * Returns the product of all elements of the matrix\r\n * @return {number}\r\n */\r\n prod() {\r\n var prod = 1;\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n prod *= this.get(i, j);\r\n }\r\n }\r\n return prod;\r\n }\r\n\r\n /**\r\n * Returns the norm of a matrix.\r\n * @param {string} type - \"frobenius\" (default) or \"max\" return resp. the Frobenius norm and the max norm.\r\n * @return {number}\r\n */\r\n norm(type = 'frobenius') {\r\n var result = 0;\r\n if (type === 'max') {\r\n return this.max();\r\n } else if (type === 'frobenius') {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n result = result + this.get(i, j) * this.get(i, j);\r\n }\r\n }\r\n return Math.sqrt(result);\r\n } else {\r\n throw new RangeError(`unknown norm type: ${type}`);\r\n }\r\n }\r\n\r\n /**\r\n * Computes the cumulative sum of the matrix elements (in place, row by row)\r\n * @return {Matrix} this\r\n */\r\n cumulativeSum() {\r\n var sum = 0;\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n sum += this.get(i, j);\r\n this.set(i, j, sum);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Computes the dot (scalar) product between the matrix and another\r\n * @param {Matrix} vector2 vector\r\n * @return {number}\r\n */\r\n dot(vector2) {\r\n if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\r\n var vector1 = this.to1DArray();\r\n if (vector1.length !== vector2.length) {\r\n throw new RangeError('vectors do not have the same size');\r\n }\r\n var dot = 0;\r\n for (var i = 0; i < vector1.length; i++) {\r\n dot += vector1[i] * vector2[i];\r\n }\r\n return dot;\r\n }\r\n\r\n /**\r\n * Returns the matrix product between this and other\r\n * @param {Matrix} other\r\n * @return {Matrix}\r\n */\r\n mmul(other) {\r\n other = this.constructor.checkMatrix(other);\r\n if (this.columns !== other.rows) {\r\n // eslint-disable-next-line no-console\r\n console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\r\n }\r\n\r\n var m = this.rows;\r\n var n = this.columns;\r\n var p = other.columns;\r\n\r\n var result = new this.constructor[Symbol.species](m, p);\r\n\r\n var Bcolj = new Array(n);\r\n for (var j = 0; j < p; j++) {\r\n for (var k = 0; k < n; k++) {\r\n Bcolj[k] = other.get(k, j);\r\n }\r\n\r\n for (var i = 0; i < m; i++) {\r\n var s = 0;\r\n for (k = 0; k < n; k++) {\r\n s += this.get(i, k) * Bcolj[k];\r\n }\r\n\r\n result.set(i, j, s);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n strassen2x2(other) {\r\n var result = new this.constructor[Symbol.species](2, 2);\r\n const a11 = this.get(0, 0);\r\n const b11 = other.get(0, 0);\r\n const a12 = this.get(0, 1);\r\n const b12 = other.get(0, 1);\r\n const a21 = this.get(1, 0);\r\n const b21 = other.get(1, 0);\r\n const a22 = this.get(1, 1);\r\n const b22 = other.get(1, 1);\r\n\r\n // Compute intermediate values.\r\n const m1 = (a11 + a22) * (b11 + b22);\r\n const m2 = (a21 + a22) * b11;\r\n const m3 = a11 * (b12 - b22);\r\n const m4 = a22 * (b21 - b11);\r\n const m5 = (a11 + a12) * b22;\r\n const m6 = (a21 - a11) * (b11 + b12);\r\n const m7 = (a12 - a22) * (b21 + b22);\r\n\r\n // Combine intermediate values into the output.\r\n const c00 = m1 + m4 - m5 + m7;\r\n const c01 = m3 + m5;\r\n const c10 = m2 + m4;\r\n const c11 = m1 - m2 + m3 + m6;\r\n\r\n result.set(0, 0, c00);\r\n result.set(0, 1, c01);\r\n result.set(1, 0, c10);\r\n result.set(1, 1, c11);\r\n return result;\r\n }\r\n\r\n strassen3x3(other) {\r\n var result = new this.constructor[Symbol.species](3, 3);\r\n\r\n const a00 = this.get(0, 0);\r\n const a01 = this.get(0, 1);\r\n const a02 = this.get(0, 2);\r\n const a10 = this.get(1, 0);\r\n const a11 = this.get(1, 1);\r\n const a12 = this.get(1, 2);\r\n const a20 = this.get(2, 0);\r\n const a21 = this.get(2, 1);\r\n const a22 = this.get(2, 2);\r\n\r\n const b00 = other.get(0, 0);\r\n const b01 = other.get(0, 1);\r\n const b02 = other.get(0, 2);\r\n const b10 = other.get(1, 0);\r\n const b11 = other.get(1, 1);\r\n const b12 = other.get(1, 2);\r\n const b20 = other.get(2, 0);\r\n const b21 = other.get(2, 1);\r\n const b22 = other.get(2, 2);\r\n\r\n const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;\r\n const m2 = (a00 - a10) * (-b01 + b11);\r\n const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);\r\n const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);\r\n const m5 = (a10 + a11) * (-b00 + b01);\r\n const m6 = a00 * b00;\r\n const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);\r\n const m8 = (-a00 + a20) * (b02 - b12);\r\n const m9 = (a20 + a21) * (-b00 + b02);\r\n const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;\r\n const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);\r\n const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);\r\n const m13 = (a02 - a22) * (b11 - b21);\r\n const m14 = a02 * b20;\r\n const m15 = (a21 + a22) * (-b20 + b21);\r\n const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);\r\n const m17 = (a02 - a12) * (b12 - b22);\r\n const m18 = (a11 + a12) * (-b20 + b22);\r\n const m19 = a01 * b10;\r\n const m20 = a12 * b21;\r\n const m21 = a10 * b02;\r\n const m22 = a20 * b01;\r\n const m23 = a22 * b22;\r\n\r\n const c00 = m6 + m14 + m19;\r\n const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;\r\n const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;\r\n const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;\r\n const c11 = m2 + m4 + m5 + m6 + m20;\r\n const c12 = m14 + m16 + m17 + m18 + m21;\r\n const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;\r\n const c21 = m12 + m13 + m14 + m15 + m22;\r\n const c22 = m6 + m7 + m8 + m9 + m23;\r\n\r\n result.set(0, 0, c00);\r\n result.set(0, 1, c01);\r\n result.set(0, 2, c02);\r\n result.set(1, 0, c10);\r\n result.set(1, 1, c11);\r\n result.set(1, 2, c12);\r\n result.set(2, 0, c20);\r\n result.set(2, 1, c21);\r\n result.set(2, 2, c22);\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000.\r\n * @param {Matrix} y\r\n * @return {Matrix}\r\n */\r\n mmulStrassen(y) {\r\n var x = this.clone();\r\n var r1 = x.rows;\r\n var c1 = x.columns;\r\n var r2 = y.rows;\r\n var c2 = y.columns;\r\n if (c1 !== r2) {\r\n // eslint-disable-next-line no-console\r\n console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`);\r\n }\r\n\r\n // Put a matrix into the top left of a matrix of zeros.\r\n // `rows` and `cols` are the dimensions of the output matrix.\r\n function embed(mat, rows, cols) {\r\n var r = mat.rows;\r\n var c = mat.columns;\r\n if ((r === rows) && (c === cols)) {\r\n return mat;\r\n } else {\r\n var resultat = Matrix.zeros(rows, cols);\r\n resultat = resultat.setSubMatrix(mat, 0, 0);\r\n return resultat;\r\n }\r\n }\r\n\r\n\r\n // Make sure both matrices are the same size.\r\n // This is exclusively for simplicity:\r\n // this algorithm can be implemented with matrices of different sizes.\r\n\r\n var r = Math.max(r1, r2);\r\n var c = Math.max(c1, c2);\r\n x = embed(x, r, c);\r\n y = embed(y, r, c);\r\n\r\n // Our recursive multiplication function.\r\n function blockMult(a, b, rows, cols) {\r\n // For small matrices, resort to naive multiplication.\r\n if (rows <= 512 || cols <= 512) {\r\n return a.mmul(b); // a is equivalent to this\r\n }\r\n\r\n // Apply dynamic padding.\r\n if ((rows % 2 === 1) && (cols % 2 === 1)) {\r\n a = embed(a, rows + 1, cols + 1);\r\n b = embed(b, rows + 1, cols + 1);\r\n } else if (rows % 2 === 1) {\r\n a = embed(a, rows + 1, cols);\r\n b = embed(b, rows + 1, cols);\r\n } else if (cols % 2 === 1) {\r\n a = embed(a, rows, cols + 1);\r\n b = embed(b, rows, cols + 1);\r\n }\r\n\r\n var halfRows = parseInt(a.rows / 2, 10);\r\n var halfCols = parseInt(a.columns / 2, 10);\r\n // Subdivide input matrices.\r\n var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\r\n var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\r\n\r\n var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\r\n var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\r\n\r\n var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\r\n var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\r\n\r\n var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\r\n var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\r\n\r\n // Compute intermediate values.\r\n var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols);\r\n var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols);\r\n var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols);\r\n var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols);\r\n var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols);\r\n var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols);\r\n var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols);\r\n\r\n // Combine intermediate values into the output.\r\n var c11 = Matrix.add(m1, m4);\r\n c11.sub(m5);\r\n c11.add(m7);\r\n var c12 = Matrix.add(m3, m5);\r\n var c21 = Matrix.add(m2, m4);\r\n var c22 = Matrix.sub(m1, m2);\r\n c22.add(m3);\r\n c22.add(m6);\r\n\r\n // Crop output to the desired size (undo dynamic padding).\r\n var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns);\r\n resultat = resultat.setSubMatrix(c11, 0, 0);\r\n resultat = resultat.setSubMatrix(c12, c11.rows, 0);\r\n resultat = resultat.setSubMatrix(c21, 0, c11.columns);\r\n resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns);\r\n return resultat.subMatrix(0, rows - 1, 0, cols - 1);\r\n }\r\n return blockMult(x, y, r, c);\r\n }\r\n\r\n /**\r\n * Returns a row-by-row scaled matrix\r\n * @param {number} [min=0] - Minimum scaled value\r\n * @param {number} [max=1] - Maximum scaled value\r\n * @return {Matrix} - The scaled matrix\r\n */\r\n scaleRows(min, max) {\r\n min = min === undefined ? 0 : min;\r\n max = max === undefined ? 1 : max;\r\n if (min >= max) {\r\n throw new RangeError('min should be strictly smaller than max');\r\n }\r\n var newMatrix = this.constructor.empty(this.rows, this.columns);\r\n for (var i = 0; i < this.rows; i++) {\r\n var scaled = rescale(this.getRow(i), { min, max });\r\n newMatrix.setRow(i, scaled);\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Returns a new column-by-column scaled matrix\r\n * @param {number} [min=0] - Minimum scaled value\r\n * @param {number} [max=1] - Maximum scaled value\r\n * @return {Matrix} - The new scaled matrix\r\n * @example\r\n * var matrix = new Matrix([[1,2],[-1,0]]);\r\n * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]]\r\n */\r\n scaleColumns(min, max) {\r\n min = min === undefined ? 0 : min;\r\n max = max === undefined ? 1 : max;\r\n if (min >= max) {\r\n throw new RangeError('min should be strictly smaller than max');\r\n }\r\n var newMatrix = this.constructor.empty(this.rows, this.columns);\r\n for (var i = 0; i < this.columns; i++) {\r\n var scaled = rescale(this.getColumn(i), {\r\n min: min,\r\n max: max\r\n });\r\n newMatrix.setColumn(i, scaled);\r\n }\r\n return newMatrix;\r\n }\r\n\r\n\r\n /**\r\n * Returns the Kronecker product (also known as tensor product) between this and other\r\n * See https://en.wikipedia.org/wiki/Kronecker_product\r\n * @param {Matrix} other\r\n * @return {Matrix}\r\n */\r\n kroneckerProduct(other) {\r\n other = this.constructor.checkMatrix(other);\r\n\r\n var m = this.rows;\r\n var n = this.columns;\r\n var p = other.rows;\r\n var q = other.columns;\r\n\r\n var result = new this.constructor[Symbol.species](m * p, n * q);\r\n for (var i = 0; i < m; i++) {\r\n for (var j = 0; j < n; j++) {\r\n for (var k = 0; k < p; k++) {\r\n for (var l = 0; l < q; l++) {\r\n result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l);\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Transposes the matrix and returns a new one containing the result\r\n * @return {Matrix}\r\n */\r\n transpose() {\r\n var result = new this.constructor[Symbol.species](this.columns, this.rows);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n result.set(j, i, this.get(i, j));\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sorts the rows (in place)\r\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\r\n * @return {Matrix} this\r\n */\r\n sortRows(compareFunction) {\r\n if (compareFunction === undefined) compareFunction = compareNumbers;\r\n for (var i = 0; i < this.rows; i++) {\r\n this.setRow(i, this.getRow(i).sort(compareFunction));\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Sorts the columns (in place)\r\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\r\n * @return {Matrix} this\r\n */\r\n sortColumns(compareFunction) {\r\n if (compareFunction === undefined) compareFunction = compareNumbers;\r\n for (var i = 0; i < this.columns; i++) {\r\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns a subset of the matrix\r\n * @param {number} startRow - First row index\r\n * @param {number} endRow - Last row index\r\n * @param {number} startColumn - First column index\r\n * @param {number} endColumn - Last column index\r\n * @return {Matrix}\r\n */\r\n subMatrix(startRow, endRow, startColumn, endColumn) {\r\n checkRange(this, startRow, endRow, startColumn, endColumn);\r\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1);\r\n for (var i = startRow; i <= endRow; i++) {\r\n for (var j = startColumn; j <= endColumn; j++) {\r\n newMatrix[i - startRow][j - startColumn] = this.get(i, j);\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Returns a subset of the matrix based on an array of row indices\r\n * @param {Array} indices - Array containing the row indices\r\n * @param {number} [startColumn = 0] - First column index\r\n * @param {number} [endColumn = this.columns-1] - Last column index\r\n * @return {Matrix}\r\n */\r\n subMatrixRow(indices, startColumn, endColumn) {\r\n if (startColumn === undefined) startColumn = 0;\r\n if (endColumn === undefined) endColumn = this.columns - 1;\r\n if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) {\r\n throw new RangeError('Argument out of range');\r\n }\r\n\r\n var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1);\r\n for (var i = 0; i < indices.length; i++) {\r\n for (var j = startColumn; j <= endColumn; j++) {\r\n if (indices[i] < 0 || indices[i] >= this.rows) {\r\n throw new RangeError(`Row index out of range: ${indices[i]}`);\r\n }\r\n newMatrix.set(i, j - startColumn, this.get(indices[i], j));\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Returns a subset of the matrix based on an array of column indices\r\n * @param {Array} indices - Array containing the column indices\r\n * @param {number} [startRow = 0] - First row index\r\n * @param {number} [endRow = this.rows-1] - Last row index\r\n * @return {Matrix}\r\n */\r\n subMatrixColumn(indices, startRow, endRow) {\r\n if (startRow === undefined) startRow = 0;\r\n if (endRow === undefined) endRow = this.rows - 1;\r\n if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) {\r\n throw new RangeError('Argument out of range');\r\n }\r\n\r\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length);\r\n for (var i = 0; i < indices.length; i++) {\r\n for (var j = startRow; j <= endRow; j++) {\r\n if (indices[i] < 0 || indices[i] >= this.columns) {\r\n throw new RangeError(`Column index out of range: ${indices[i]}`);\r\n }\r\n newMatrix.set(j - startRow, i, this.get(j, indices[i]));\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Set a part of the matrix to the given sub-matrix\r\n * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values.\r\n * @param {number} startRow - The index of the first row to set\r\n * @param {number} startColumn - The index of the first column to set\r\n * @return {Matrix}\r\n */\r\n setSubMatrix(matrix, startRow, startColumn) {\r\n matrix = this.constructor.checkMatrix(matrix);\r\n var endRow = startRow + matrix.rows - 1;\r\n var endColumn = startColumn + matrix.columns - 1;\r\n checkRange(this, startRow, endRow, startColumn, endColumn);\r\n for (var i = 0; i < matrix.rows; i++) {\r\n for (var j = 0; j < matrix.columns; j++) {\r\n this[startRow + i][startColumn + j] = matrix.get(i, j);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Return a new matrix based on a selection of rows and columns\r\n * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once.\r\n * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once.\r\n * @return {Matrix} The new matrix\r\n */\r\n selection(rowIndices, columnIndices) {\r\n var indices = checkIndices(this, rowIndices, columnIndices);\r\n var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length);\r\n for (var i = 0; i < indices.row.length; i++) {\r\n var rowIndex = indices.row[i];\r\n for (var j = 0; j < indices.column.length; j++) {\r\n var columnIndex = indices.column[j];\r\n newMatrix[i][j] = this.get(rowIndex, columnIndex);\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Returns the trace of the matrix (sum of the diagonal elements)\r\n * @return {number}\r\n */\r\n trace() {\r\n var min = Math.min(this.rows, this.columns);\r\n var trace = 0;\r\n for (var i = 0; i < min; i++) {\r\n trace += this.get(i, i);\r\n }\r\n return trace;\r\n }\r\n\r\n /*\r\n Matrix views\r\n */\r\n\r\n /**\r\n * Returns a view of the transposition of the matrix\r\n * @return {MatrixTransposeView}\r\n */\r\n transposeView() {\r\n return new MatrixTransposeView(this);\r\n }\r\n\r\n /**\r\n * Returns a view of the row vector with the given index\r\n * @param {number} row - row index of the vector\r\n * @return {MatrixRowView}\r\n */\r\n rowView(row) {\r\n checkRowIndex(this, row);\r\n return new MatrixRowView(this, row);\r\n }\r\n\r\n /**\r\n * Returns a view of the column vector with the given index\r\n * @param {number} column - column index of the vector\r\n * @return {MatrixColumnView}\r\n */\r\n columnView(column) {\r\n checkColumnIndex(this, column);\r\n return new MatrixColumnView(this, column);\r\n }\r\n\r\n /**\r\n * Returns a view of the matrix flipped in the row axis\r\n * @return {MatrixFlipRowView}\r\n */\r\n flipRowView() {\r\n return new MatrixFlipRowView(this);\r\n }\r\n\r\n /**\r\n * Returns a view of the matrix flipped in the column axis\r\n * @return {MatrixFlipColumnView}\r\n */\r\n flipColumnView() {\r\n return new MatrixFlipColumnView(this);\r\n }\r\n\r\n /**\r\n * Returns a view of a submatrix giving the index boundaries\r\n * @param {number} startRow - first row index of the submatrix\r\n * @param {number} endRow - last row index of the submatrix\r\n * @param {number} startColumn - first column index of the submatrix\r\n * @param {number} endColumn - last column index of the submatrix\r\n * @return {MatrixSubView}\r\n */\r\n subMatrixView(startRow, endRow, startColumn, endColumn) {\r\n return new MatrixSubView(this, startRow, endRow, startColumn, endColumn);\r\n }\r\n\r\n /**\r\n * Returns a view of the cross of the row indices and the column indices\r\n * @example\r\n * // resulting vector is [[2], [2]]\r\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1])\r\n * @param {Array} rowIndices\r\n * @param {Array} columnIndices\r\n * @return {MatrixSelectionView}\r\n */\r\n selectionView(rowIndices, columnIndices) {\r\n return new MatrixSelectionView(this, rowIndices, columnIndices);\r\n }\r\n\r\n /**\r\n * Returns a view of the row indices\r\n * @example\r\n * // resulting vector is [[1,2,3], [1,2,3]]\r\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).rowSelectionView([0, 0])\r\n * @param {Array} rowIndices\r\n * @return {MatrixRowSelectionView}\r\n */\r\n rowSelectionView(rowIndices) {\r\n return new MatrixRowSelectionView(this, rowIndices);\r\n }\r\n\r\n /**\r\n * Returns a view of the column indices\r\n * @example\r\n * // resulting vector is [[2, 2], [5, 5]]\r\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).columnSelectionView([1, 1])\r\n * @param {Array} columnIndices\r\n * @return {MatrixColumnSelectionView}\r\n */\r\n columnSelectionView(columnIndices) {\r\n return new MatrixColumnSelectionView(this, columnIndices);\r\n }\r\n\r\n\r\n /**\r\n * Calculates and returns the determinant of a matrix as a Number\r\n * @example\r\n * new Matrix([[1,2,3], [4,5,6]]).det()\r\n * @return {number}\r\n */\r\n det() {\r\n if (this.isSquare()) {\r\n var a, b, c, d;\r\n if (this.columns === 2) {\r\n // 2 x 2 matrix\r\n a = this.get(0, 0);\r\n b = this.get(0, 1);\r\n c = this.get(1, 0);\r\n d = this.get(1, 1);\r\n\r\n return a * d - (b * c);\r\n } else if (this.columns === 3) {\r\n // 3 x 3 matrix\r\n var subMatrix0, subMatrix1, subMatrix2;\r\n subMatrix0 = this.selectionView([1, 2], [1, 2]);\r\n subMatrix1 = this.selectionView([1, 2], [0, 2]);\r\n subMatrix2 = this.selectionView([1, 2], [0, 1]);\r\n a = this.get(0, 0);\r\n b = this.get(0, 1);\r\n c = this.get(0, 2);\r\n\r\n return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det();\r\n } else {\r\n // general purpose determinant using the LU decomposition\r\n return new LuDecomposition(this).determinant;\r\n }\r\n } else {\r\n throw Error('Determinant can only be calculated for a square matrix.');\r\n }\r\n }\r\n\r\n /**\r\n * Returns inverse of a matrix if it exists or the pseudoinverse\r\n * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15)\r\n * @return {Matrix} the (pseudo)inverted matrix.\r\n */\r\n pseudoInverse(threshold) {\r\n if (threshold === undefined) threshold = Number.EPSILON;\r\n var svdSolution = new SvDecomposition(this, { autoTranspose: true });\r\n\r\n var U = svdSolution.leftSingularVectors;\r\n var V = svdSolution.rightSingularVectors;\r\n var s = svdSolution.diagonal;\r\n\r\n for (var i = 0; i < s.length; i++) {\r\n if (Math.abs(s[i]) > threshold) {\r\n s[i] = 1.0 / s[i];\r\n } else {\r\n s[i] = 0.0;\r\n }\r\n }\r\n\r\n // convert list to diagonal\r\n s = this.constructor[Symbol.species].diag(s);\r\n return V.mmul(s.mmul(U.transposeView()));\r\n }\r\n\r\n /**\r\n * Creates an exact and independent copy of the matrix\r\n * @return {Matrix}\r\n */\r\n clone() {\r\n var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns);\r\n for (var row = 0; row < this.rows; row++) {\r\n for (var column = 0; column < this.columns; column++) {\r\n newMatrix.set(row, column, this.get(row, column));\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n }\r\n\r\n Matrix.prototype.klass = 'Matrix';\r\n\r\n function compareNumbers(a, b) {\r\n return a - b;\r\n }\r\n\r\n /*\r\n Synonyms\r\n */\r\n\r\n Matrix.random = Matrix.rand;\r\n Matrix.diagonal = Matrix.diag;\r\n Matrix.prototype.diagonal = Matrix.prototype.diag;\r\n Matrix.identity = Matrix.eye;\r\n Matrix.prototype.negate = Matrix.prototype.neg;\r\n Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct;\r\n Matrix.prototype.determinant = Matrix.prototype.det;\r\n\r\n /*\r\n Add dynamically instance and static methods for mathematical operations\r\n */\r\n\r\n var inplaceOperator = `\r\n(function %name%(value) {\r\n if (typeof value === 'number') return this.%name%S(value);\r\n return this.%name%M(value);\r\n})\r\n`;\r\n\r\n var inplaceOperatorScalar = `\r\n(function %name%S(value) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) %op% value);\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var inplaceOperatorMatrix = `\r\n(function %name%M(matrix) {\r\n matrix = this.constructor.checkMatrix(matrix);\r\n if (this.rows !== matrix.rows ||\r\n this.columns !== matrix.columns) {\r\n throw new RangeError('Matrices dimensions must be equal');\r\n }\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) %op% matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var staticOperator = `\r\n(function %name%(matrix, value) {\r\n var newMatrix = new this[Symbol.species](matrix);\r\n return newMatrix.%name%(value);\r\n})\r\n`;\r\n\r\n var inplaceMethod = `\r\n(function %name%() {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, %method%(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var staticMethod = `\r\n(function %name%(matrix) {\r\n var newMatrix = new this[Symbol.species](matrix);\r\n return newMatrix.%name%();\r\n})\r\n`;\r\n\r\n var inplaceMethodWithArgs = `\r\n(function %name%(%args%) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, %method%(this.get(i, j), %args%));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var staticMethodWithArgs = `\r\n(function %name%(matrix, %args%) {\r\n var newMatrix = new this[Symbol.species](matrix);\r\n return newMatrix.%name%(%args%);\r\n})\r\n`;\r\n\r\n\r\n var inplaceMethodWithOneArgScalar = `\r\n(function %name%S(value) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, %method%(this.get(i, j), value));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n var inplaceMethodWithOneArgMatrix = `\r\n(function %name%M(matrix) {\r\n matrix = this.constructor.checkMatrix(matrix);\r\n if (this.rows !== matrix.rows ||\r\n this.columns !== matrix.columns) {\r\n throw new RangeError('Matrices dimensions must be equal');\r\n }\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, %method%(this.get(i, j), matrix.get(i, j)));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var inplaceMethodWithOneArg = `\r\n(function %name%(value) {\r\n if (typeof value === 'number') return this.%name%S(value);\r\n return this.%name%M(value);\r\n})\r\n`;\r\n\r\n var staticMethodWithOneArg = staticMethodWithArgs;\r\n\r\n var operators = [\r\n // Arithmetic operators\r\n ['+', 'add'],\r\n ['-', 'sub', 'subtract'],\r\n ['*', 'mul', 'multiply'],\r\n ['/', 'div', 'divide'],\r\n ['%', 'mod', 'modulus'],\r\n // Bitwise operators\r\n ['&', 'and'],\r\n ['|', 'or'],\r\n ['^', 'xor'],\r\n ['<<', 'leftShift'],\r\n ['>>', 'signPropagatingRightShift'],\r\n ['>>>', 'rightShift', 'zeroFillRightShift']\r\n ];\r\n\r\n var i;\r\n var eval2 = eval; // eslint-disable-line no-eval\r\n for (var operator of operators) {\r\n var inplaceOp = eval2(fillTemplateFunction(inplaceOperator, { name: operator[1], op: operator[0] }));\r\n var inplaceOpS = eval2(fillTemplateFunction(inplaceOperatorScalar, { name: `${operator[1]}S`, op: operator[0] }));\r\n var inplaceOpM = eval2(fillTemplateFunction(inplaceOperatorMatrix, { name: `${operator[1]}M`, op: operator[0] }));\r\n var staticOp = eval2(fillTemplateFunction(staticOperator, { name: operator[1] }));\r\n for (i = 1; i < operator.length; i++) {\r\n Matrix.prototype[operator[i]] = inplaceOp;\r\n Matrix.prototype[`${operator[i]}S`] = inplaceOpS;\r\n Matrix.prototype[`${operator[i]}M`] = inplaceOpM;\r\n Matrix[operator[i]] = staticOp;\r\n }\r\n }\r\n\r\n var methods = [['~', 'not']];\r\n\r\n [\r\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\r\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\r\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\r\n ].forEach(function (mathMethod) {\r\n methods.push([`Math.${mathMethod}`, mathMethod]);\r\n });\r\n\r\n for (var method of methods) {\r\n var inplaceMeth = eval2(fillTemplateFunction(inplaceMethod, { name: method[1], method: method[0] }));\r\n var staticMeth = eval2(fillTemplateFunction(staticMethod, { name: method[1] }));\r\n for (i = 1; i < method.length; i++) {\r\n Matrix.prototype[method[i]] = inplaceMeth;\r\n Matrix[method[i]] = staticMeth;\r\n }\r\n }\r\n\r\n var methodsWithArgs = [['Math.pow', 1, 'pow']];\r\n\r\n for (var methodWithArg of methodsWithArgs) {\r\n var args = 'arg0';\r\n for (i = 1; i < methodWithArg[1]; i++) {\r\n args += `, arg${i}`;\r\n }\r\n if (methodWithArg[1] !== 1) {\r\n var inplaceMethWithArgs = eval2(fillTemplateFunction(inplaceMethodWithArgs, {\r\n name: methodWithArg[2],\r\n method: methodWithArg[0],\r\n args: args\r\n }));\r\n var staticMethWithArgs = eval2(fillTemplateFunction(staticMethodWithArgs, { name: methodWithArg[2], args: args }));\r\n for (i = 2; i < methodWithArg.length; i++) {\r\n Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs;\r\n Matrix[methodWithArg[i]] = staticMethWithArgs;\r\n }\r\n } else {\r\n var tmplVar = {\r\n name: methodWithArg[2],\r\n args: args,\r\n method: methodWithArg[0]\r\n };\r\n var inplaceMethod2 = eval2(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar));\r\n var inplaceMethodS = eval2(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar));\r\n var inplaceMethodM = eval2(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar));\r\n var staticMethod2 = eval2(fillTemplateFunction(staticMethodWithOneArg, tmplVar));\r\n for (i = 2; i < methodWithArg.length; i++) {\r\n Matrix.prototype[methodWithArg[i]] = inplaceMethod2;\r\n Matrix.prototype[`${methodWithArg[i]}M`] = inplaceMethodM;\r\n Matrix.prototype[`${methodWithArg[i]}S`] = inplaceMethodS;\r\n Matrix[methodWithArg[i]] = staticMethod2;\r\n }\r\n }\r\n }\r\n\r\n function fillTemplateFunction(template, values) {\r\n for (var value in values) {\r\n template = template.replace(new RegExp(`%${value}%`, 'g'), values[value]);\r\n }\r\n return template;\r\n }\r\n\r\n return Matrix;\r\n}\r\n","import AbstractMatrix from './abstractMatrix';\r\nimport {\r\n checkColumnIndex,\r\n checkColumnVector,\r\n checkRowIndex,\r\n checkRowVector\r\n} from './util';\r\n\r\nexport default class Matrix extends AbstractMatrix(Array) {\r\n constructor(nRows, nColumns) {\r\n var i;\r\n if (arguments.length === 1 && typeof nRows === 'number') {\r\n return new Array(nRows);\r\n }\r\n if (Matrix.isMatrix(nRows)) {\r\n return nRows.clone();\r\n } else if (Number.isInteger(nRows) && nRows > 0) {\r\n // Create an empty matrix\r\n super(nRows);\r\n if (Number.isInteger(nColumns) && nColumns > 0) {\r\n for (i = 0; i < nRows; i++) {\r\n this[i] = new Array(nColumns);\r\n }\r\n } else {\r\n throw new TypeError('nColumns must be a positive integer');\r\n }\r\n } else if (Array.isArray(nRows)) {\r\n // Copy the values from the 2D array\r\n const matrix = nRows;\r\n nRows = matrix.length;\r\n nColumns = matrix[0].length;\r\n if (typeof nColumns !== 'number' || nColumns === 0) {\r\n throw new TypeError(\r\n 'Data must be a 2D array with at least one element'\r\n );\r\n }\r\n super(nRows);\r\n for (i = 0; i < nRows; i++) {\r\n if (matrix[i].length !== nColumns) {\r\n throw new RangeError('Inconsistent array dimensions');\r\n }\r\n this[i] = [].concat(matrix[i]);\r\n }\r\n } else {\r\n throw new TypeError(\r\n 'First argument must be a positive number or an array'\r\n );\r\n }\r\n this.rows = nRows;\r\n this.columns = nColumns;\r\n return this;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this[rowIndex][columnIndex] = value;\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this[rowIndex][columnIndex];\r\n }\r\n\r\n /**\r\n * Removes a row from the given index\r\n * @param {number} index - Row index\r\n * @return {Matrix} this\r\n */\r\n removeRow(index) {\r\n checkRowIndex(this, index);\r\n if (this.rows === 1) {\r\n throw new RangeError('A matrix cannot have less than one row');\r\n }\r\n this.splice(index, 1);\r\n this.rows -= 1;\r\n return this;\r\n }\r\n\r\n /**\r\n * Adds a row at the given index\r\n * @param {number} [index = this.rows] - Row index\r\n * @param {Array|Matrix} array - Array or vector\r\n * @return {Matrix} this\r\n */\r\n addRow(index, array) {\r\n if (array === undefined) {\r\n array = index;\r\n index = this.rows;\r\n }\r\n checkRowIndex(this, index, true);\r\n array = checkRowVector(this, array, true);\r\n this.splice(index, 0, array);\r\n this.rows += 1;\r\n return this;\r\n }\r\n\r\n /**\r\n * Removes a column from the given index\r\n * @param {number} index - Column index\r\n * @return {Matrix} this\r\n */\r\n removeColumn(index) {\r\n checkColumnIndex(this, index);\r\n if (this.columns === 1) {\r\n throw new RangeError('A matrix cannot have less than one column');\r\n }\r\n for (var i = 0; i < this.rows; i++) {\r\n this[i].splice(index, 1);\r\n }\r\n this.columns -= 1;\r\n return this;\r\n }\r\n\r\n /**\r\n * Adds a column at the given index\r\n * @param {number} [index = this.columns] - Column index\r\n * @param {Array|Matrix} array - Array or vector\r\n * @return {Matrix} this\r\n */\r\n addColumn(index, array) {\r\n if (typeof array === 'undefined') {\r\n array = index;\r\n index = this.columns;\r\n }\r\n checkColumnIndex(this, index, true);\r\n array = checkColumnVector(this, array);\r\n for (var i = 0; i < this.rows; i++) {\r\n this[i].splice(index, 0, array[i]);\r\n }\r\n this.columns += 1;\r\n return this;\r\n }\r\n}\r\n","import AbstractMatrix from '../abstractMatrix';\r\nimport Matrix from '../matrix';\r\n\r\nexport default class WrapperMatrix1D extends AbstractMatrix() {\r\n /**\r\n * @class WrapperMatrix1D\r\n * @param {Array} data\r\n * @param {object} [options]\r\n * @param {object} [options.rows = 1]\r\n */\r\n constructor(data, options = {}) {\r\n const { rows = 1 } = options;\r\n\r\n if (data.length % rows !== 0) {\r\n throw new Error('the data length is not divisible by the number of rows');\r\n }\r\n super();\r\n this.rows = rows;\r\n this.columns = data.length / rows;\r\n this.data = data;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n var index = this._calculateIndex(rowIndex, columnIndex);\r\n this.data[index] = value;\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n var index = this._calculateIndex(rowIndex, columnIndex);\r\n return this.data[index];\r\n }\r\n\r\n _calculateIndex(row, column) {\r\n return row * this.columns + column;\r\n }\r\n\r\n static get [Symbol.species]() {\r\n return Matrix;\r\n }\r\n}\r\n","import AbstractMatrix from '../abstractMatrix';\r\nimport Matrix from '../matrix';\r\n\r\nexport default class WrapperMatrix2D extends AbstractMatrix() {\r\n /**\r\n * @class WrapperMatrix2D\r\n * @param {Array>} data\r\n */\r\n constructor(data) {\r\n super();\r\n this.data = data;\r\n this.rows = data.length;\r\n this.columns = data[0].length;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.data[rowIndex][columnIndex] = value;\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.data[rowIndex][columnIndex];\r\n }\r\n\r\n static get [Symbol.species]() {\r\n return Matrix;\r\n }\r\n}\r\n","import WrapperMatrix1D from './WrapperMatrix1D';\r\nimport WrapperMatrix2D from './WrapperMatrix2D';\r\n\r\n/**\r\n * @param {Array>|Array} array\r\n * @param {object} [options]\r\n * @param {object} [options.rows = 1]\r\n * @return {WrapperMatrix1D|WrapperMatrix2D}\r\n */\r\nexport function wrap(array, options) {\r\n if (Array.isArray(array)) {\r\n if (array[0] && Array.isArray(array[0])) {\r\n return new WrapperMatrix2D(array);\r\n } else {\r\n return new WrapperMatrix1D(array, options);\r\n }\r\n } else {\r\n throw new Error('the argument is not an array');\r\n }\r\n}\r\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\nimport { hypotenuse } from './util';\r\n\r\n/**\r\n * @class QrDecomposition\r\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs\r\n * @param {Matrix} value\r\n */\r\nexport default class QrDecomposition {\r\n constructor(value) {\r\n value = WrapperMatrix2D.checkMatrix(value);\r\n\r\n var qr = value.clone();\r\n var m = value.rows;\r\n var n = value.columns;\r\n var rdiag = new Array(n);\r\n var i, j, k, s;\r\n\r\n for (k = 0; k < n; k++) {\r\n var nrm = 0;\r\n for (i = k; i < m; i++) {\r\n nrm = hypotenuse(nrm, qr.get(i, k));\r\n }\r\n if (nrm !== 0) {\r\n if (qr.get(k, k) < 0) {\r\n nrm = -nrm;\r\n }\r\n for (i = k; i < m; i++) {\r\n qr.set(i, k, qr.get(i, k) / nrm);\r\n }\r\n qr.set(k, k, qr.get(k, k) + 1);\r\n for (j = k + 1; j < n; j++) {\r\n s = 0;\r\n for (i = k; i < m; i++) {\r\n s += qr.get(i, k) * qr.get(i, j);\r\n }\r\n s = -s / qr.get(k, k);\r\n for (i = k; i < m; i++) {\r\n qr.set(i, j, qr.get(i, j) + s * qr.get(i, k));\r\n }\r\n }\r\n }\r\n rdiag[k] = -nrm;\r\n }\r\n\r\n this.QR = qr;\r\n this.Rdiag = rdiag;\r\n }\r\n\r\n /**\r\n * Solve a problem of least square (Ax=b) by using the QR decomposition. Useful when A is rectangular, but not working when A is singular.\r\n * Example : We search to approximate x, with A matrix shape m*n, x vector size n, b vector size m (m > n). We will use :\r\n * var qr = QrDecomposition(A);\r\n * var x = qr.solve(b);\r\n * @param {Matrix} value - Matrix 1D which is the vector b (in the equation Ax = b)\r\n * @return {Matrix} - The vector x\r\n */\r\n solve(value) {\r\n value = Matrix.checkMatrix(value);\r\n\r\n var qr = this.QR;\r\n var m = qr.rows;\r\n\r\n if (value.rows !== m) {\r\n throw new Error('Matrix row dimensions must agree');\r\n }\r\n if (!this.isFullRank()) {\r\n throw new Error('Matrix is rank deficient');\r\n }\r\n\r\n var count = value.columns;\r\n var X = value.clone();\r\n var n = qr.columns;\r\n var i, j, k, s;\r\n\r\n for (k = 0; k < n; k++) {\r\n for (j = 0; j < count; j++) {\r\n s = 0;\r\n for (i = k; i < m; i++) {\r\n s += qr[i][k] * X[i][j];\r\n }\r\n s = -s / qr[k][k];\r\n for (i = k; i < m; i++) {\r\n X[i][j] += s * qr[i][k];\r\n }\r\n }\r\n }\r\n for (k = n - 1; k >= 0; k--) {\r\n for (j = 0; j < count; j++) {\r\n X[k][j] /= this.Rdiag[k];\r\n }\r\n for (i = 0; i < k; i++) {\r\n for (j = 0; j < count; j++) {\r\n X[i][j] -= X[k][j] * qr[i][k];\r\n }\r\n }\r\n }\r\n\r\n return X.subMatrix(0, n - 1, 0, count - 1);\r\n }\r\n\r\n /**\r\n *\r\n * @return {boolean}\r\n */\r\n isFullRank() {\r\n var columns = this.QR.columns;\r\n for (var i = 0; i < columns; i++) {\r\n if (this.Rdiag[i] === 0) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get upperTriangularMatrix() {\r\n var qr = this.QR;\r\n var n = qr.columns;\r\n var X = new Matrix(n, n);\r\n var i, j;\r\n for (i = 0; i < n; i++) {\r\n for (j = 0; j < n; j++) {\r\n if (i < j) {\r\n X[i][j] = qr[i][j];\r\n } else if (i === j) {\r\n X[i][j] = this.Rdiag[i];\r\n } else {\r\n X[i][j] = 0;\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get orthogonalMatrix() {\r\n var qr = this.QR;\r\n var rows = qr.rows;\r\n var columns = qr.columns;\r\n var X = new Matrix(rows, columns);\r\n var i, j, k, s;\r\n\r\n for (k = columns - 1; k >= 0; k--) {\r\n for (i = 0; i < rows; i++) {\r\n X[i][k] = 0;\r\n }\r\n X[k][k] = 1;\r\n for (j = k; j < columns; j++) {\r\n if (qr[k][k] !== 0) {\r\n s = 0;\r\n for (i = k; i < rows; i++) {\r\n s += qr[i][k] * X[i][j];\r\n }\r\n\r\n s = -s / qr[k][k];\r\n\r\n for (i = k; i < rows; i++) {\r\n X[i][j] += s * qr[i][k];\r\n }\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n}\r\n","import LuDecomposition from './dc/lu';\r\nimport QrDecomposition from './dc/qr';\r\nimport SingularValueDecomposition from './dc/svd';\r\n\r\nimport { Matrix, WrapperMatrix2D } from './index';\r\n\r\n/**\r\n * Computes the inverse of a Matrix\r\n * @param {Matrix} matrix\r\n * @param {boolean} [useSVD=false]\r\n * @return {Matrix}\r\n */\r\nexport function inverse(matrix, useSVD = false) {\r\n matrix = WrapperMatrix2D.checkMatrix(matrix);\r\n if (useSVD) {\r\n return new SingularValueDecomposition(matrix).inverse();\r\n } else {\r\n return solve(matrix, Matrix.eye(matrix.rows));\r\n }\r\n}\r\n\r\n/**\r\n *\r\n * @param {Matrix} leftHandSide\r\n * @param {Matrix} rightHandSide\r\n * @param {boolean} [useSVD = false]\r\n * @return {Matrix}\r\n */\r\nexport function solve(leftHandSide, rightHandSide, useSVD = false) {\r\n leftHandSide = WrapperMatrix2D.checkMatrix(leftHandSide);\r\n rightHandSide = WrapperMatrix2D.checkMatrix(rightHandSide);\r\n if (useSVD) {\r\n return new SingularValueDecomposition(leftHandSide).solve(rightHandSide);\r\n } else {\r\n return leftHandSide.isSquare()\r\n ? new LuDecomposition(leftHandSide).solve(rightHandSide)\r\n : new QrDecomposition(leftHandSide).solve(rightHandSide);\r\n }\r\n}\r\n","import max from 'ml-array-max';\r\n\r\nimport Matrix from './matrix';\r\nimport SingularValueDecomposition from './dc/svd';\r\n\r\n// function used by rowsDependencies\r\nfunction xrange(n, exception) {\r\n var range = [];\r\n for (var i = 0; i < n; i++) {\r\n if (i !== exception) {\r\n range.push(i);\r\n }\r\n }\r\n return range;\r\n}\r\n\r\n// function used by rowsDependencies\r\nfunction dependenciesOneRow(\r\n error,\r\n matrix,\r\n index,\r\n thresholdValue = 10e-10,\r\n thresholdError = 10e-10\r\n) {\r\n if (error > thresholdError) {\r\n return new Array(matrix.rows + 1).fill(0);\r\n } else {\r\n var returnArray = matrix.addRow(index, [0]);\r\n for (var i = 0; i < returnArray.rows; i++) {\r\n if (Math.abs(returnArray.get(i, 0)) < thresholdValue) {\r\n returnArray.set(i, 0, 0);\r\n }\r\n }\r\n return returnArray.to1DArray();\r\n }\r\n}\r\n\r\n/**\r\n * Creates a matrix which represents the dependencies between rows.\r\n * If a row is a linear combination of others rows, the result will be a row with the coefficients of this combination.\r\n * For example : for A = [[2, 0, 0, 1], [0, 1, 6, 0], [0, 3, 0, 1], [0, 0, 1, 0], [0, 1, 2, 0]], the result will be [[0, 0, 0, 0, 0], [0, 0, 0, 4, 1], [0, 0, 0, 0, 0], [0, 0.25, 0, 0, -0.25], [0, 1, 0, -4, 0]]\r\n * @param {Matrix} matrix\r\n * @param {Object} [options] includes thresholdValue and thresholdError.\r\n * @param {number} [options.thresholdValue = 10e-10] If an absolute value is inferior to this threshold, it will equals zero.\r\n * @param {number} [options.thresholdError = 10e-10] If the error is inferior to that threshold, the linear combination found is accepted and the row is dependent from other rows.\r\n * @return {Matrix} the matrix which represents the dependencies between rows.\r\n */\r\n\r\nexport function linearDependencies(matrix, options = {}) {\r\n const { thresholdValue = 10e-10, thresholdError = 10e-10 } = options;\r\n\r\n var n = matrix.rows;\r\n var results = new Matrix(n, n);\r\n\r\n for (var i = 0; i < n; i++) {\r\n var b = Matrix.columnVector(matrix.getRow(i));\r\n var Abis = matrix.subMatrixRow(xrange(n, i)).transposeView();\r\n var svd = new SingularValueDecomposition(Abis);\r\n var x = svd.solve(b);\r\n var error = max(\r\n Matrix.sub(b, Abis.mmul(x))\r\n .abs()\r\n .to1DArray()\r\n );\r\n results.setRow(\r\n i,\r\n dependenciesOneRow(error, x, i, thresholdValue, thresholdError)\r\n );\r\n }\r\n return results;\r\n}\r\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\nimport { hypotenuse, getFilled2DArray } from './util';\r\n\r\n/**\r\n * @class EigenvalueDecomposition\r\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs\r\n * @param {Matrix} matrix\r\n * @param {object} [options]\r\n * @param {boolean} [options.assumeSymmetric=false]\r\n */\r\nexport default class EigenvalueDecomposition {\r\n constructor(matrix, options = {}) {\r\n const { assumeSymmetric = false } = options;\r\n\r\n matrix = WrapperMatrix2D.checkMatrix(matrix);\r\n if (!matrix.isSquare()) {\r\n throw new Error('Matrix is not a square matrix');\r\n }\r\n\r\n var n = matrix.columns;\r\n var V = getFilled2DArray(n, n, 0);\r\n var d = new Array(n);\r\n var e = new Array(n);\r\n var value = matrix;\r\n var i, j;\r\n\r\n var isSymmetric = false;\r\n if (assumeSymmetric) {\r\n isSymmetric = true;\r\n } else {\r\n isSymmetric = matrix.isSymmetric();\r\n }\r\n\r\n if (isSymmetric) {\r\n for (i = 0; i < n; i++) {\r\n for (j = 0; j < n; j++) {\r\n V[i][j] = value.get(i, j);\r\n }\r\n }\r\n tred2(n, e, d, V);\r\n tql2(n, e, d, V);\r\n } else {\r\n var H = getFilled2DArray(n, n, 0);\r\n var ort = new Array(n);\r\n for (j = 0; j < n; j++) {\r\n for (i = 0; i < n; i++) {\r\n H[i][j] = value.get(i, j);\r\n }\r\n }\r\n orthes(n, H, ort, V);\r\n hqr2(n, e, d, V, H);\r\n }\r\n\r\n this.n = n;\r\n this.e = e;\r\n this.d = d;\r\n this.V = V;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Array}\r\n */\r\n get realEigenvalues() {\r\n return this.d;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Array}\r\n */\r\n get imaginaryEigenvalues() {\r\n return this.e;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get eigenvectorMatrix() {\r\n if (!Matrix.isMatrix(this.V)) {\r\n this.V = new Matrix(this.V);\r\n }\r\n return this.V;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get diagonalMatrix() {\r\n var n = this.n;\r\n var e = this.e;\r\n var d = this.d;\r\n var X = new Matrix(n, n);\r\n var i, j;\r\n for (i = 0; i < n; i++) {\r\n for (j = 0; j < n; j++) {\r\n X[i][j] = 0;\r\n }\r\n X[i][i] = d[i];\r\n if (e[i] > 0) {\r\n X[i][i + 1] = e[i];\r\n } else if (e[i] < 0) {\r\n X[i][i - 1] = e[i];\r\n }\r\n }\r\n return X;\r\n }\r\n}\r\n\r\nfunction tred2(n, e, d, V) {\r\n var f, g, h, i, j, k, hh, scale;\r\n\r\n for (j = 0; j < n; j++) {\r\n d[j] = V[n - 1][j];\r\n }\r\n\r\n for (i = n - 1; i > 0; i--) {\r\n scale = 0;\r\n h = 0;\r\n for (k = 0; k < i; k++) {\r\n scale = scale + Math.abs(d[k]);\r\n }\r\n\r\n if (scale === 0) {\r\n e[i] = d[i - 1];\r\n for (j = 0; j < i; j++) {\r\n d[j] = V[i - 1][j];\r\n V[i][j] = 0;\r\n V[j][i] = 0;\r\n }\r\n } else {\r\n for (k = 0; k < i; k++) {\r\n d[k] /= scale;\r\n h += d[k] * d[k];\r\n }\r\n\r\n f = d[i - 1];\r\n g = Math.sqrt(h);\r\n if (f > 0) {\r\n g = -g;\r\n }\r\n\r\n e[i] = scale * g;\r\n h = h - f * g;\r\n d[i - 1] = f - g;\r\n for (j = 0; j < i; j++) {\r\n e[j] = 0;\r\n }\r\n\r\n for (j = 0; j < i; j++) {\r\n f = d[j];\r\n V[j][i] = f;\r\n g = e[j] + V[j][j] * f;\r\n for (k = j + 1; k <= i - 1; k++) {\r\n g += V[k][j] * d[k];\r\n e[k] += V[k][j] * f;\r\n }\r\n e[j] = g;\r\n }\r\n\r\n f = 0;\r\n for (j = 0; j < i; j++) {\r\n e[j] /= h;\r\n f += e[j] * d[j];\r\n }\r\n\r\n hh = f / (h + h);\r\n for (j = 0; j < i; j++) {\r\n e[j] -= hh * d[j];\r\n }\r\n\r\n for (j = 0; j < i; j++) {\r\n f = d[j];\r\n g = e[j];\r\n for (k = j; k <= i - 1; k++) {\r\n V[k][j] -= f * e[k] + g * d[k];\r\n }\r\n d[j] = V[i - 1][j];\r\n V[i][j] = 0;\r\n }\r\n }\r\n d[i] = h;\r\n }\r\n\r\n for (i = 0; i < n - 1; i++) {\r\n V[n - 1][i] = V[i][i];\r\n V[i][i] = 1;\r\n h = d[i + 1];\r\n if (h !== 0) {\r\n for (k = 0; k <= i; k++) {\r\n d[k] = V[k][i + 1] / h;\r\n }\r\n\r\n for (j = 0; j <= i; j++) {\r\n g = 0;\r\n for (k = 0; k <= i; k++) {\r\n g += V[k][i + 1] * V[k][j];\r\n }\r\n for (k = 0; k <= i; k++) {\r\n V[k][j] -= g * d[k];\r\n }\r\n }\r\n }\r\n\r\n for (k = 0; k <= i; k++) {\r\n V[k][i + 1] = 0;\r\n }\r\n }\r\n\r\n for (j = 0; j < n; j++) {\r\n d[j] = V[n - 1][j];\r\n V[n - 1][j] = 0;\r\n }\r\n\r\n V[n - 1][n - 1] = 1;\r\n e[0] = 0;\r\n}\r\n\r\nfunction tql2(n, e, d, V) {\r\n var g, h, i, j, k, l, m, p, r, dl1, c, c2, c3, el1, s, s2, iter;\r\n\r\n for (i = 1; i < n; i++) {\r\n e[i - 1] = e[i];\r\n }\r\n\r\n e[n - 1] = 0;\r\n\r\n var f = 0;\r\n var tst1 = 0;\r\n var eps = Number.EPSILON;\r\n\r\n for (l = 0; l < n; l++) {\r\n tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));\r\n m = l;\r\n while (m < n) {\r\n if (Math.abs(e[m]) <= eps * tst1) {\r\n break;\r\n }\r\n m++;\r\n }\r\n\r\n if (m > l) {\r\n iter = 0;\r\n do {\r\n iter = iter + 1;\r\n\r\n g = d[l];\r\n p = (d[l + 1] - g) / (2 * e[l]);\r\n r = hypotenuse(p, 1);\r\n if (p < 0) {\r\n r = -r;\r\n }\r\n\r\n d[l] = e[l] / (p + r);\r\n d[l + 1] = e[l] * (p + r);\r\n dl1 = d[l + 1];\r\n h = g - d[l];\r\n for (i = l + 2; i < n; i++) {\r\n d[i] -= h;\r\n }\r\n\r\n f = f + h;\r\n\r\n p = d[m];\r\n c = 1;\r\n c2 = c;\r\n c3 = c;\r\n el1 = e[l + 1];\r\n s = 0;\r\n s2 = 0;\r\n for (i = m - 1; i >= l; i--) {\r\n c3 = c2;\r\n c2 = c;\r\n s2 = s;\r\n g = c * e[i];\r\n h = c * p;\r\n r = hypotenuse(p, e[i]);\r\n e[i + 1] = s * r;\r\n s = e[i] / r;\r\n c = p / r;\r\n p = c * d[i] - s * g;\r\n d[i + 1] = h + s * (c * g + s * d[i]);\r\n\r\n for (k = 0; k < n; k++) {\r\n h = V[k][i + 1];\r\n V[k][i + 1] = s * V[k][i] + c * h;\r\n V[k][i] = c * V[k][i] - s * h;\r\n }\r\n }\r\n\r\n p = -s * s2 * c3 * el1 * e[l] / dl1;\r\n e[l] = s * p;\r\n d[l] = c * p;\r\n } while (Math.abs(e[l]) > eps * tst1);\r\n }\r\n d[l] = d[l] + f;\r\n e[l] = 0;\r\n }\r\n\r\n for (i = 0; i < n - 1; i++) {\r\n k = i;\r\n p = d[i];\r\n for (j = i + 1; j < n; j++) {\r\n if (d[j] < p) {\r\n k = j;\r\n p = d[j];\r\n }\r\n }\r\n\r\n if (k !== i) {\r\n d[k] = d[i];\r\n d[i] = p;\r\n for (j = 0; j < n; j++) {\r\n p = V[j][i];\r\n V[j][i] = V[j][k];\r\n V[j][k] = p;\r\n }\r\n }\r\n }\r\n}\r\n\r\nfunction orthes(n, H, ort, V) {\r\n var low = 0;\r\n var high = n - 1;\r\n var f, g, h, i, j, m;\r\n var scale;\r\n\r\n for (m = low + 1; m <= high - 1; m++) {\r\n scale = 0;\r\n for (i = m; i <= high; i++) {\r\n scale = scale + Math.abs(H[i][m - 1]);\r\n }\r\n\r\n if (scale !== 0) {\r\n h = 0;\r\n for (i = high; i >= m; i--) {\r\n ort[i] = H[i][m - 1] / scale;\r\n h += ort[i] * ort[i];\r\n }\r\n\r\n g = Math.sqrt(h);\r\n if (ort[m] > 0) {\r\n g = -g;\r\n }\r\n\r\n h = h - ort[m] * g;\r\n ort[m] = ort[m] - g;\r\n\r\n for (j = m; j < n; j++) {\r\n f = 0;\r\n for (i = high; i >= m; i--) {\r\n f += ort[i] * H[i][j];\r\n }\r\n\r\n f = f / h;\r\n for (i = m; i <= high; i++) {\r\n H[i][j] -= f * ort[i];\r\n }\r\n }\r\n\r\n for (i = 0; i <= high; i++) {\r\n f = 0;\r\n for (j = high; j >= m; j--) {\r\n f += ort[j] * H[i][j];\r\n }\r\n\r\n f = f / h;\r\n for (j = m; j <= high; j++) {\r\n H[i][j] -= f * ort[j];\r\n }\r\n }\r\n\r\n ort[m] = scale * ort[m];\r\n H[m][m - 1] = scale * g;\r\n }\r\n }\r\n\r\n for (i = 0; i < n; i++) {\r\n for (j = 0; j < n; j++) {\r\n V[i][j] = i === j ? 1 : 0;\r\n }\r\n }\r\n\r\n for (m = high - 1; m >= low + 1; m--) {\r\n if (H[m][m - 1] !== 0) {\r\n for (i = m + 1; i <= high; i++) {\r\n ort[i] = H[i][m - 1];\r\n }\r\n\r\n for (j = m; j <= high; j++) {\r\n g = 0;\r\n for (i = m; i <= high; i++) {\r\n g += ort[i] * V[i][j];\r\n }\r\n\r\n g = g / ort[m] / H[m][m - 1];\r\n for (i = m; i <= high; i++) {\r\n V[i][j] += g * ort[i];\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nfunction hqr2(nn, e, d, V, H) {\r\n var n = nn - 1;\r\n var low = 0;\r\n var high = nn - 1;\r\n var eps = Number.EPSILON;\r\n var exshift = 0;\r\n var norm = 0;\r\n var p = 0;\r\n var q = 0;\r\n var r = 0;\r\n var s = 0;\r\n var z = 0;\r\n var iter = 0;\r\n var i, j, k, l, m, t, w, x, y;\r\n var ra, sa, vr, vi;\r\n var notlast, cdivres;\r\n\r\n for (i = 0; i < nn; i++) {\r\n if (i < low || i > high) {\r\n d[i] = H[i][i];\r\n e[i] = 0;\r\n }\r\n\r\n for (j = Math.max(i - 1, 0); j < nn; j++) {\r\n norm = norm + Math.abs(H[i][j]);\r\n }\r\n }\r\n\r\n while (n >= low) {\r\n l = n;\r\n while (l > low) {\r\n s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]);\r\n if (s === 0) {\r\n s = norm;\r\n }\r\n if (Math.abs(H[l][l - 1]) < eps * s) {\r\n break;\r\n }\r\n l--;\r\n }\r\n\r\n if (l === n) {\r\n H[n][n] = H[n][n] + exshift;\r\n d[n] = H[n][n];\r\n e[n] = 0;\r\n n--;\r\n iter = 0;\r\n } else if (l === n - 1) {\r\n w = H[n][n - 1] * H[n - 1][n];\r\n p = (H[n - 1][n - 1] - H[n][n]) / 2;\r\n q = p * p + w;\r\n z = Math.sqrt(Math.abs(q));\r\n H[n][n] = H[n][n] + exshift;\r\n H[n - 1][n - 1] = H[n - 1][n - 1] + exshift;\r\n x = H[n][n];\r\n\r\n if (q >= 0) {\r\n z = p >= 0 ? p + z : p - z;\r\n d[n - 1] = x + z;\r\n d[n] = d[n - 1];\r\n if (z !== 0) {\r\n d[n] = x - w / z;\r\n }\r\n e[n - 1] = 0;\r\n e[n] = 0;\r\n x = H[n][n - 1];\r\n s = Math.abs(x) + Math.abs(z);\r\n p = x / s;\r\n q = z / s;\r\n r = Math.sqrt(p * p + q * q);\r\n p = p / r;\r\n q = q / r;\r\n\r\n for (j = n - 1; j < nn; j++) {\r\n z = H[n - 1][j];\r\n H[n - 1][j] = q * z + p * H[n][j];\r\n H[n][j] = q * H[n][j] - p * z;\r\n }\r\n\r\n for (i = 0; i <= n; i++) {\r\n z = H[i][n - 1];\r\n H[i][n - 1] = q * z + p * H[i][n];\r\n H[i][n] = q * H[i][n] - p * z;\r\n }\r\n\r\n for (i = low; i <= high; i++) {\r\n z = V[i][n - 1];\r\n V[i][n - 1] = q * z + p * V[i][n];\r\n V[i][n] = q * V[i][n] - p * z;\r\n }\r\n } else {\r\n d[n - 1] = x + p;\r\n d[n] = x + p;\r\n e[n - 1] = z;\r\n e[n] = -z;\r\n }\r\n\r\n n = n - 2;\r\n iter = 0;\r\n } else {\r\n x = H[n][n];\r\n y = 0;\r\n w = 0;\r\n if (l < n) {\r\n y = H[n - 1][n - 1];\r\n w = H[n][n - 1] * H[n - 1][n];\r\n }\r\n\r\n if (iter === 10) {\r\n exshift += x;\r\n for (i = low; i <= n; i++) {\r\n H[i][i] -= x;\r\n }\r\n s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]);\r\n x = y = 0.75 * s;\r\n w = -0.4375 * s * s;\r\n }\r\n\r\n if (iter === 30) {\r\n s = (y - x) / 2;\r\n s = s * s + w;\r\n if (s > 0) {\r\n s = Math.sqrt(s);\r\n if (y < x) {\r\n s = -s;\r\n }\r\n s = x - w / ((y - x) / 2 + s);\r\n for (i = low; i <= n; i++) {\r\n H[i][i] -= s;\r\n }\r\n exshift += s;\r\n x = y = w = 0.964;\r\n }\r\n }\r\n\r\n iter = iter + 1;\r\n\r\n m = n - 2;\r\n while (m >= l) {\r\n z = H[m][m];\r\n r = x - z;\r\n s = y - z;\r\n p = (r * s - w) / H[m + 1][m] + H[m][m + 1];\r\n q = H[m + 1][m + 1] - z - r - s;\r\n r = H[m + 2][m + 1];\r\n s = Math.abs(p) + Math.abs(q) + Math.abs(r);\r\n p = p / s;\r\n q = q / s;\r\n r = r / s;\r\n if (m === l) {\r\n break;\r\n }\r\n if (\r\n Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) <\r\n eps *\r\n (Math.abs(p) *\r\n (Math.abs(H[m - 1][m - 1]) +\r\n Math.abs(z) +\r\n Math.abs(H[m + 1][m + 1])))\r\n ) {\r\n break;\r\n }\r\n m--;\r\n }\r\n\r\n for (i = m + 2; i <= n; i++) {\r\n H[i][i - 2] = 0;\r\n if (i > m + 2) {\r\n H[i][i - 3] = 0;\r\n }\r\n }\r\n\r\n for (k = m; k <= n - 1; k++) {\r\n notlast = k !== n - 1;\r\n if (k !== m) {\r\n p = H[k][k - 1];\r\n q = H[k + 1][k - 1];\r\n r = notlast ? H[k + 2][k - 1] : 0;\r\n x = Math.abs(p) + Math.abs(q) + Math.abs(r);\r\n if (x !== 0) {\r\n p = p / x;\r\n q = q / x;\r\n r = r / x;\r\n }\r\n }\r\n\r\n if (x === 0) {\r\n break;\r\n }\r\n\r\n s = Math.sqrt(p * p + q * q + r * r);\r\n if (p < 0) {\r\n s = -s;\r\n }\r\n\r\n if (s !== 0) {\r\n if (k !== m) {\r\n H[k][k - 1] = -s * x;\r\n } else if (l !== m) {\r\n H[k][k - 1] = -H[k][k - 1];\r\n }\r\n\r\n p = p + s;\r\n x = p / s;\r\n y = q / s;\r\n z = r / s;\r\n q = q / p;\r\n r = r / p;\r\n\r\n for (j = k; j < nn; j++) {\r\n p = H[k][j] + q * H[k + 1][j];\r\n if (notlast) {\r\n p = p + r * H[k + 2][j];\r\n H[k + 2][j] = H[k + 2][j] - p * z;\r\n }\r\n\r\n H[k][j] = H[k][j] - p * x;\r\n H[k + 1][j] = H[k + 1][j] - p * y;\r\n }\r\n\r\n for (i = 0; i <= Math.min(n, k + 3); i++) {\r\n p = x * H[i][k] + y * H[i][k + 1];\r\n if (notlast) {\r\n p = p + z * H[i][k + 2];\r\n H[i][k + 2] = H[i][k + 2] - p * r;\r\n }\r\n\r\n H[i][k] = H[i][k] - p;\r\n H[i][k + 1] = H[i][k + 1] - p * q;\r\n }\r\n\r\n for (i = low; i <= high; i++) {\r\n p = x * V[i][k] + y * V[i][k + 1];\r\n if (notlast) {\r\n p = p + z * V[i][k + 2];\r\n V[i][k + 2] = V[i][k + 2] - p * r;\r\n }\r\n\r\n V[i][k] = V[i][k] - p;\r\n V[i][k + 1] = V[i][k + 1] - p * q;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (norm === 0) {\r\n return;\r\n }\r\n\r\n for (n = nn - 1; n >= 0; n--) {\r\n p = d[n];\r\n q = e[n];\r\n\r\n if (q === 0) {\r\n l = n;\r\n H[n][n] = 1;\r\n for (i = n - 1; i >= 0; i--) {\r\n w = H[i][i] - p;\r\n r = 0;\r\n for (j = l; j <= n; j++) {\r\n r = r + H[i][j] * H[j][n];\r\n }\r\n\r\n if (e[i] < 0) {\r\n z = w;\r\n s = r;\r\n } else {\r\n l = i;\r\n if (e[i] === 0) {\r\n H[i][n] = w !== 0 ? -r / w : -r / (eps * norm);\r\n } else {\r\n x = H[i][i + 1];\r\n y = H[i + 1][i];\r\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\r\n t = (x * s - z * r) / q;\r\n H[i][n] = t;\r\n H[i + 1][n] =\r\n Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z;\r\n }\r\n\r\n t = Math.abs(H[i][n]);\r\n if (eps * t * t > 1) {\r\n for (j = i; j <= n; j++) {\r\n H[j][n] = H[j][n] / t;\r\n }\r\n }\r\n }\r\n }\r\n } else if (q < 0) {\r\n l = n - 1;\r\n\r\n if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) {\r\n H[n - 1][n - 1] = q / H[n][n - 1];\r\n H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1];\r\n } else {\r\n cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q);\r\n H[n - 1][n - 1] = cdivres[0];\r\n H[n - 1][n] = cdivres[1];\r\n }\r\n\r\n H[n][n - 1] = 0;\r\n H[n][n] = 1;\r\n for (i = n - 2; i >= 0; i--) {\r\n ra = 0;\r\n sa = 0;\r\n for (j = l; j <= n; j++) {\r\n ra = ra + H[i][j] * H[j][n - 1];\r\n sa = sa + H[i][j] * H[j][n];\r\n }\r\n\r\n w = H[i][i] - p;\r\n\r\n if (e[i] < 0) {\r\n z = w;\r\n r = ra;\r\n s = sa;\r\n } else {\r\n l = i;\r\n if (e[i] === 0) {\r\n cdivres = cdiv(-ra, -sa, w, q);\r\n H[i][n - 1] = cdivres[0];\r\n H[i][n] = cdivres[1];\r\n } else {\r\n x = H[i][i + 1];\r\n y = H[i + 1][i];\r\n vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;\r\n vi = (d[i] - p) * 2 * q;\r\n if (vr === 0 && vi === 0) {\r\n vr =\r\n eps *\r\n norm *\r\n (Math.abs(w) +\r\n Math.abs(q) +\r\n Math.abs(x) +\r\n Math.abs(y) +\r\n Math.abs(z));\r\n }\r\n cdivres = cdiv(\r\n x * r - z * ra + q * sa,\r\n x * s - z * sa - q * ra,\r\n vr,\r\n vi\r\n );\r\n H[i][n - 1] = cdivres[0];\r\n H[i][n] = cdivres[1];\r\n if (Math.abs(x) > Math.abs(z) + Math.abs(q)) {\r\n H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x;\r\n H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x;\r\n } else {\r\n cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q);\r\n H[i + 1][n - 1] = cdivres[0];\r\n H[i + 1][n] = cdivres[1];\r\n }\r\n }\r\n\r\n t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n]));\r\n if (eps * t * t > 1) {\r\n for (j = i; j <= n; j++) {\r\n H[j][n - 1] = H[j][n - 1] / t;\r\n H[j][n] = H[j][n] / t;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n for (i = 0; i < nn; i++) {\r\n if (i < low || i > high) {\r\n for (j = i; j < nn; j++) {\r\n V[i][j] = H[i][j];\r\n }\r\n }\r\n }\r\n\r\n for (j = nn - 1; j >= low; j--) {\r\n for (i = low; i <= high; i++) {\r\n z = 0;\r\n for (k = low; k <= Math.min(j, high); k++) {\r\n z = z + V[i][k] * H[k][j];\r\n }\r\n V[i][j] = z;\r\n }\r\n }\r\n}\r\n\r\nfunction cdiv(xr, xi, yr, yi) {\r\n var r, d;\r\n if (Math.abs(yr) > Math.abs(yi)) {\r\n r = yi / yr;\r\n d = yr + r * yi;\r\n return [(xr + r * xi) / d, (xi - r * xr) / d];\r\n } else {\r\n r = yr / yi;\r\n d = yi + r * yr;\r\n return [(r * xr + xi) / d, (r * xi - xr) / d];\r\n }\r\n}\r\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\n/**\r\n * @class CholeskyDecomposition\r\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs\r\n * @param {Matrix} value\r\n */\r\nexport default class CholeskyDecomposition {\r\n constructor(value) {\r\n value = WrapperMatrix2D.checkMatrix(value);\r\n if (!value.isSymmetric()) {\r\n throw new Error('Matrix is not symmetric');\r\n }\r\n\r\n var a = value;\r\n var dimension = a.rows;\r\n var l = new Matrix(dimension, dimension);\r\n var positiveDefinite = true;\r\n var i, j, k;\r\n\r\n for (j = 0; j < dimension; j++) {\r\n var Lrowj = l[j];\r\n var d = 0;\r\n for (k = 0; k < j; k++) {\r\n var Lrowk = l[k];\r\n var s = 0;\r\n for (i = 0; i < k; i++) {\r\n s += Lrowk[i] * Lrowj[i];\r\n }\r\n Lrowj[k] = s = (a.get(j, k) - s) / l[k][k];\r\n d = d + s * s;\r\n }\r\n\r\n d = a.get(j, j) - d;\r\n\r\n positiveDefinite &= d > 0;\r\n l[j][j] = Math.sqrt(Math.max(d, 0));\r\n for (k = j + 1; k < dimension; k++) {\r\n l[j][k] = 0;\r\n }\r\n }\r\n\r\n if (!positiveDefinite) {\r\n throw new Error('Matrix is not positive definite');\r\n }\r\n\r\n this.L = l;\r\n }\r\n\r\n /**\r\n *\r\n * @param {Matrix} value\r\n * @return {Matrix}\r\n */\r\n solve(value) {\r\n value = WrapperMatrix2D.checkMatrix(value);\r\n\r\n var l = this.L;\r\n var dimension = l.rows;\r\n\r\n if (value.rows !== dimension) {\r\n throw new Error('Matrix dimensions do not match');\r\n }\r\n\r\n var count = value.columns;\r\n var B = value.clone();\r\n var i, j, k;\r\n\r\n for (k = 0; k < dimension; k++) {\r\n for (j = 0; j < count; j++) {\r\n for (i = 0; i < k; i++) {\r\n B[k][j] -= B[i][j] * l[k][i];\r\n }\r\n B[k][j] /= l[k][k];\r\n }\r\n }\r\n\r\n for (k = dimension - 1; k >= 0; k--) {\r\n for (j = 0; j < count; j++) {\r\n for (i = k + 1; i < dimension; i++) {\r\n B[k][j] -= B[i][j] * l[i][k];\r\n }\r\n B[k][j] /= l[k][k];\r\n }\r\n }\r\n\r\n return B;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get lowerTriangularMatrix() {\r\n return this.L;\r\n }\r\n}\r\n","export { default, default as Matrix } from './matrix';\r\nexport { default as abstractMatrix } from './abstractMatrix';\r\n\r\nexport { wrap } from './wrap/wrap';\r\nexport { default as WrapperMatrix2D } from './wrap/WrapperMatrix2D';\r\nexport { default as WrapperMatrix1D } from './wrap/WrapperMatrix1D';\r\n\r\nexport { solve, inverse } from './decompositions';\r\nexport { linearDependencies } from './linearDependencies';\r\nexport {\r\n default as SingularValueDecomposition,\r\n default as SVD\r\n} from './dc/svd.js';\r\nexport {\r\n default as EigenvalueDecomposition,\r\n default as EVD\r\n} from './dc/evd.js';\r\nexport {\r\n default as CholeskyDecomposition,\r\n default as CHO\r\n} from './dc/cholesky.js';\r\nexport { default as LuDecomposition, default as LU } from './dc/lu.js';\r\nexport { default as QrDecomposition, default as QR } from './dc/qr.js';\r\n","'use strict';\n\nconst toString = Object.prototype.toString;\n\nfunction isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n\nmodule.exports = isAnyArray;\n","'use strict';\n\nfunction squaredEuclidean(p, q) {\n var d = 0;\n for (var i = 0; i < p.length; i++) {\n d += (p[i] - q[i]) * (p[i] - q[i]);\n }\n return d;\n}\n\nfunction euclidean(p, q) {\n return Math.sqrt(squaredEuclidean(p, q));\n}\n\nmodule.exports = euclidean;\neuclidean.squared = squaredEuclidean;\n","'use strict';\n\nexports.array = require('./array');\nexports.matrix = require('./matrix');\n","'use strict';\n\nvar arrayStat = require('./array');\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nexports.max = function max(matrix) {\n var max = -Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] > max) max = matrix[i][j];\n }\n }\n return max;\n};\n\nexports.min = function min(matrix) {\n var min = Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] < min) min = matrix[i][j];\n }\n }\n return min;\n};\n\nexports.minMax = function minMax(matrix) {\n var min = Infinity;\n var max = -Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] < min) min = matrix[i][j];\n if (matrix[i][j] > max) max = matrix[i][j];\n }\n }\n return {\n min:min,\n max:max\n };\n};\n\nexports.entropy = function entropy(matrix, eps) {\n if (typeof (eps) === 'undefined') {\n eps = 0;\n }\n var sum = 0,\n l1 = matrix.length,\n l2 = matrix[0].length;\n for (var i = 0; i < l1; i++) {\n for (var j = 0; j < l2; j++) {\n sum += matrix[i][j] * Math.log(matrix[i][j] + eps);\n }\n }\n return -sum;\n};\n\nexports.mean = function mean(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theMean, N, i, j;\n\n if (dimension === -1) {\n theMean = [0];\n N = rows * cols;\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theMean[0] += matrix[i][j];\n }\n }\n theMean[0] /= N;\n } else if (dimension === 0) {\n theMean = new Array(cols);\n N = rows;\n for (j = 0; j < cols; j++) {\n theMean[j] = 0;\n for (i = 0; i < rows; i++) {\n theMean[j] += matrix[i][j];\n }\n theMean[j] /= N;\n }\n } else if (dimension === 1) {\n theMean = new Array(rows);\n N = cols;\n for (j = 0; j < rows; j++) {\n theMean[j] = 0;\n for (i = 0; i < cols; i++) {\n theMean[j] += matrix[j][i];\n }\n theMean[j] /= N;\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theMean;\n};\n\nexports.sum = function sum(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theSum, i, j;\n\n if (dimension === -1) {\n theSum = [0];\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theSum[0] += matrix[i][j];\n }\n }\n } else if (dimension === 0) {\n theSum = new Array(cols);\n for (j = 0; j < cols; j++) {\n theSum[j] = 0;\n for (i = 0; i < rows; i++) {\n theSum[j] += matrix[i][j];\n }\n }\n } else if (dimension === 1) {\n theSum = new Array(rows);\n for (j = 0; j < rows; j++) {\n theSum[j] = 0;\n for (i = 0; i < cols; i++) {\n theSum[j] += matrix[j][i];\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theSum;\n};\n\nexports.product = function product(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theProduct, i, j;\n\n if (dimension === -1) {\n theProduct = [1];\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theProduct[0] *= matrix[i][j];\n }\n }\n } else if (dimension === 0) {\n theProduct = new Array(cols);\n for (j = 0; j < cols; j++) {\n theProduct[j] = 1;\n for (i = 0; i < rows; i++) {\n theProduct[j] *= matrix[i][j];\n }\n }\n } else if (dimension === 1) {\n theProduct = new Array(rows);\n for (j = 0; j < rows; j++) {\n theProduct[j] = 1;\n for (i = 0; i < cols; i++) {\n theProduct[j] *= matrix[j][i];\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theProduct;\n};\n\nexports.standardDeviation = function standardDeviation(matrix, means, unbiased) {\n var vari = exports.variance(matrix, means, unbiased), l = vari.length;\n for (var i = 0; i < l; i++) {\n vari[i] = Math.sqrt(vari[i]);\n }\n return vari;\n};\n\nexports.variance = function variance(matrix, means, unbiased) {\n if (typeof (unbiased) === 'undefined') {\n unbiased = true;\n }\n means = means || exports.mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum1 = 0, sum2 = 0, x = 0;\n for (var i = 0; i < rows; i++) {\n x = matrix[i][j] - means[j];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / (rows - 1);\n } else {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / rows;\n }\n }\n return vari;\n};\n\nexports.median = function median(matrix) {\n var rows = matrix.length, cols = matrix[0].length;\n var medians = new Array(cols);\n\n for (var i = 0; i < cols; i++) {\n var data = new Array(rows);\n for (var j = 0; j < rows; j++) {\n data[j] = matrix[j][i];\n }\n data.sort(compareNumbers);\n var N = data.length;\n if (N % 2 === 0) {\n medians[i] = (data[N / 2] + data[(N / 2) - 1]) * 0.5;\n } else {\n medians[i] = data[Math.floor(N / 2)];\n }\n }\n return medians;\n};\n\nexports.mode = function mode(matrix) {\n var rows = matrix.length,\n cols = matrix[0].length,\n modes = new Array(cols),\n i, j;\n for (i = 0; i < cols; i++) {\n var itemCount = new Array(rows);\n for (var k = 0; k < rows; k++) {\n itemCount[k] = 0;\n }\n var itemArray = new Array(rows);\n var count = 0;\n\n for (j = 0; j < rows; j++) {\n var index = itemArray.indexOf(matrix[j][i]);\n if (index >= 0) {\n itemCount[index]++;\n } else {\n itemArray[count] = matrix[j][i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (j = 0; j < count; j++) {\n if (itemCount[j] > maxValue) {\n maxValue = itemCount[j];\n maxIndex = j;\n }\n }\n\n modes[i] = itemArray[maxIndex];\n }\n return modes;\n};\n\nexports.skewness = function skewness(matrix, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var means = exports.mean(matrix);\n var n = matrix.length, l = means.length;\n var skew = new Array(l);\n\n for (var j = 0; j < l; j++) {\n var s2 = 0, s3 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n\n var m2 = s2 / n;\n var m3 = s3 / n;\n var g = m3 / Math.pow(m2, 3 / 2);\n\n if (unbiased) {\n var a = Math.sqrt(n * (n - 1));\n var b = n - 2;\n skew[j] = (a / b) * g;\n } else {\n skew[j] = g;\n }\n }\n return skew;\n};\n\nexports.kurtosis = function kurtosis(matrix, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var means = exports.mean(matrix);\n var n = matrix.length, m = matrix[0].length;\n var kurt = new Array(m);\n\n for (var j = 0; j < m; j++) {\n var s2 = 0, s4 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n kurt[j] = a * b - 3 * c;\n } else {\n kurt[j] = m4 / (m2 * m2) - 3;\n }\n }\n return kurt;\n};\n\nexports.standardError = function standardError(matrix) {\n var samples = matrix.length;\n var standardDeviations = exports.standardDeviation(matrix);\n var l = standardDeviations.length;\n var standardErrors = new Array(l);\n var sqrtN = Math.sqrt(samples);\n\n for (var i = 0; i < l; i++) {\n standardErrors[i] = standardDeviations[i] / sqrtN;\n }\n return standardErrors;\n};\n\nexports.covariance = function covariance(matrix, dimension) {\n return exports.scatter(matrix, undefined, dimension);\n};\n\nexports.scatter = function scatter(matrix, divisor, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n if (typeof (divisor) === 'undefined') {\n if (dimension === 0) {\n divisor = matrix.length - 1;\n } else if (dimension === 1) {\n divisor = matrix[0].length - 1;\n }\n }\n var means = exports.mean(matrix, dimension);\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, s, k;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n};\n\nexports.correlation = function correlation(matrix) {\n var means = exports.mean(matrix),\n standardDeviations = exports.standardDeviation(matrix, true, means),\n scores = exports.zScores(matrix, means, standardDeviations),\n rows = matrix.length,\n cols = matrix[0].length,\n i, j;\n\n var cor = new Array(cols);\n for (i = 0; i < cols; i++) {\n cor[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n var c = 0;\n for (var k = 0, l = scores.length; k < l; k++) {\n c += scores[k][j] * scores[k][i];\n }\n c /= rows - 1;\n cor[i][j] = c;\n cor[j][i] = c;\n }\n }\n return cor;\n};\n\nexports.zScores = function zScores(matrix, means, standardDeviations) {\n means = means || exports.mean(matrix);\n if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix, true, means);\n return exports.standardize(exports.center(matrix, means, false), standardDeviations, true);\n};\n\nexports.center = function center(matrix, means, inPlace) {\n means = means || exports.mean(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var row = result[i];\n for (j = 0, jj = row.length; j < jj; j++) {\n row[j] = matrix[i][j] - means[j];\n }\n }\n return result;\n};\n\nexports.standardize = function standardize(matrix, standardDeviations, inPlace) {\n if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var resultRow = result[i];\n var sourceRow = matrix[i];\n for (j = 0, jj = resultRow.length; j < jj; j++) {\n if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) {\n resultRow[j] = sourceRow[j] / standardDeviations[j];\n }\n }\n }\n return result;\n};\n\nexports.weightedVariance = function weightedVariance(matrix, weights) {\n var means = exports.mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum = 0;\n var a = 0, b = 0;\n\n for (var i = 0; i < rows; i++) {\n var z = matrix[i][j] - means[j];\n var w = weights[i];\n\n sum += w * (z * z);\n b += w;\n a += w * w;\n }\n\n vari[j] = sum * (b / (b * b - a));\n }\n\n return vari;\n};\n\nexports.weightedMean = function weightedMean(matrix, weights, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length,\n means, i, ii, j, w, row;\n\n if (dimension === 0) {\n means = new Array(cols);\n for (i = 0; i < cols; i++) {\n means[i] = 0;\n }\n for (i = 0; i < rows; i++) {\n row = matrix[i];\n w = weights[i];\n for (j = 0; j < cols; j++) {\n means[j] += row[j] * w;\n }\n }\n } else if (dimension === 1) {\n means = new Array(rows);\n for (i = 0; i < rows; i++) {\n means[i] = 0;\n }\n for (j = 0; j < rows; j++) {\n row = matrix[j];\n w = weights[j];\n for (i = 0; i < cols; i++) {\n means[j] += row[i] * w;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n var weightSum = arrayStat.sum(weights);\n if (weightSum !== 0) {\n for (i = 0, ii = means.length; i < ii; i++) {\n means[i] /= weightSum;\n }\n }\n return means;\n};\n\nexports.weightedCovariance = function weightedCovariance(matrix, weights, means, dimension) {\n dimension = dimension || 0;\n means = means || exports.weightedMean(matrix, weights, dimension);\n var s1 = 0, s2 = 0;\n for (var i = 0, ii = weights.length; i < ii; i++) {\n s1 += weights[i];\n s2 += weights[i] * weights[i];\n }\n var factor = s1 / (s1 * s1 - s2);\n return exports.weightedScatter(matrix, weights, means, factor, dimension);\n};\n\nexports.weightedScatter = function weightedScatter(matrix, weights, means, factor, dimension) {\n dimension = dimension || 0;\n means = means || exports.weightedMean(matrix, weights, dimension);\n if (typeof (factor) === 'undefined') {\n factor = 1;\n }\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, k, s;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n};\n","import isArray from 'is-any-array';\n\n/**\n * Computes the mean of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction mean(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var sum = 0;\n\n for (var i = 0; i < input.length; i++) {\n sum += input[i];\n }\n\n return sum / input.length;\n}\n\nexport default mean;\n","module.exports = function(haystack, needle, comparator, low, high) {\n var mid, cmp;\n\n if(low === undefined)\n low = 0;\n\n else {\n low = low|0;\n if(low < 0 || low >= haystack.length)\n throw new RangeError(\"invalid lower bound\");\n }\n\n if(high === undefined)\n high = haystack.length - 1;\n\n else {\n high = high|0;\n if(high < low || high >= haystack.length)\n throw new RangeError(\"invalid upper bound\");\n }\n\n while(low <= high) {\n /* Note that \"(low + high) >>> 1\" may overflow, and results in a typecast\n * to double (which gives the wrong results). */\n mid = low + (high - low >> 1);\n cmp = +comparator(haystack[mid], needle, mid, haystack);\n\n /* Too low. */\n if(cmp < 0.0)\n low = mid + 1;\n\n /* Too high. */\n else if(cmp > 0.0)\n high = mid - 1;\n\n /* Key found. */\n else\n return mid;\n }\n\n /* Key not found. */\n return ~low;\n}\n","'use strict';\nvar numberIsNan = require('number-is-nan');\n\nfunction assertNum(x) {\n\tif (typeof x !== 'number' || numberIsNan(x)) {\n\t\tthrow new TypeError('Expected a number');\n\t}\n}\n\nexports.asc = function (a, b) {\n\tassertNum(a);\n\tassertNum(b);\n\treturn a - b;\n};\n\nexports.desc = function (a, b) {\n\tassertNum(a);\n\tassertNum(b);\n\treturn b - a;\n};\n","import Matrix from 'ml-matrix';\nimport meanArray from 'ml-array-mean';\n\n/**\n * @private\n * return an array of probabilities of each class\n * @param {Array} array - contains the classes\n * @param {number} numberOfClasses\n * @return {Matrix} - rowVector of probabilities.\n */\nexport function toDiscreteDistribution(array, numberOfClasses) {\n var counts = new Array(numberOfClasses).fill(0);\n for (var i = 0; i < array.length; ++i) {\n counts[array[i]] += 1 / array.length;\n }\n\n return Matrix.rowVector(counts);\n}\n\n/**\n * @private\n * Retrieves the impurity of array of predictions\n * @param {Array} array - predictions.\n * @return {number} Gini impurity\n */\nexport function giniImpurity(array) {\n if (array.length === 0) {\n return 0;\n }\n\n var probabilities = toDiscreteDistribution(array, getNumberOfClasses(array))[0];\n\n var sum = 0.0;\n for (var i = 0; i < probabilities.length; ++i) {\n sum += probabilities[i] * probabilities[i];\n }\n\n return 1 - sum;\n}\n\n/**\n * @private\n * Return the number of classes given the array of predictions.\n * @param {Array} array - predictions.\n * @return {number} Number of classes.\n */\nexport function getNumberOfClasses(array) {\n return array.filter(function (val, i, arr) {\n return arr.indexOf(val) === i;\n }).length;\n}\n\n/**\n * @private\n * Calculates the Gini Gain of an array of predictions and those predictions splitted by a feature.\n * @para {Array} array - Predictions\n * @param {object} splitted - Object with elements \"greater\" and \"lesser\" that contains an array of predictions splitted.\n * @return {number} - Gini Gain.\n */\n\nexport function giniGain(array, splitted) {\n var splitsImpurity = 0.0;\n var splits = ['greater', 'lesser'];\n\n for (var i = 0; i < splits.length; ++i) {\n var currentSplit = splitted[splits[i]];\n splitsImpurity += giniImpurity(currentSplit) * currentSplit.length / array.length;\n }\n\n return giniImpurity(array) - splitsImpurity;\n}\n\n/**\n * @private\n * Calculates the squared error of a predictions values.\n * @param {Array} array - predictions values\n * @return {number} squared error.\n */\nexport function squaredError(array) {\n var l = array.length;\n\n var m = meanArray(array);\n var squaredError = 0.0;\n\n for (var i = 0; i < l; ++i) {\n var currentElement = array[i];\n squaredError += (currentElement - m) * (currentElement - m);\n }\n\n return squaredError;\n}\n\n/**\n * @private\n * Calculates the sum of squared error of the two arrays that contains the splitted values.\n * @param {Array} array - this argument is no necessary but is used to fit with the main interface.\n * @param {object} splitted - Object with elements \"greater\" and \"lesser\" that contains an array of predictions splitted.\n * @return {number} - sum of squared errors.\n */\nexport function regressionError(array, splitted) {\n var error = 0.0;\n var splits = ['greater', 'lesser'];\n\n for (var i = 0; i < splits.length; ++i) {\n var currentSplit = splitted[splits[i]];\n error += squaredError(currentSplit);\n }\n return error;\n}\n\n/**\n * @private\n * Split the training set and values from a given column of the training set if is less than a value\n * @param {Matrix} X - Training set.\n * @param {Array} y - Training values.\n * @param {number} column - Column to split.\n * @param {number} value - value to split the Training set and values.\n * @return {object} - Object that contains the splitted values.\n */\nexport function matrixSplitter(X, y, column, value) {\n var lesserX = [];\n var greaterX = [];\n var lesserY = [];\n var greaterY = [];\n\n for (var i = 0; i < X.rows; ++i) {\n if (X[i][column] < value) {\n lesserX.push(X[i]);\n lesserY.push(y[i]);\n } else {\n greaterX.push(X[i]);\n greaterY.push(y[i]);\n }\n }\n\n return {\n greaterX: greaterX,\n greaterY: greaterY,\n lesserX: lesserX,\n lesserY: lesserY\n };\n}\n\n/**\n * @private\n * Calculates the mean between two values\n * @param {number} a\n * @param {number} b\n * @return {number}\n */\nexport function mean(a, b) {\n return (a + b) / 2;\n}\n\n/**\n * @private\n * Returns a list of tuples that contains the i-th element of each array.\n * @param {Array} a\n * @param {Array} b\n * @return {Array} list of tuples.\n */\nexport function zip(a, b) {\n if (a.length !== b.length) {\n throw new TypeError('Error on zip: the size of a: ' + a.length + ' is different from b: ' + b.length);\n }\n\n var ret = new Array(a.length);\n for (var i = 0; i < a.length; ++i) {\n ret[i] = [a[i], b[i]];\n }\n\n return ret;\n}\n","import Matrix from 'ml-matrix';\nimport * as Utils from './utils';\nimport mean from 'ml-array-mean';\n\nconst gainFunctions = {\n gini: Utils.giniGain,\n regression: Utils.regressionError\n};\n\nconst splitFunctions = {\n mean: Utils.mean\n};\n\nexport default class TreeNode {\n\n /**\n * @private\n * Constructor for a tree node given the options received on the main classes (DecisionTreeClassifier, DecisionTreeRegression)\n * @param {object|TreeNode} options for loading\n * @constructor\n */\n constructor(options) {\n // options parameters\n this.kind = options.kind;\n this.gainFunction = options.gainFunction;\n this.splitFunction = options.splitFunction;\n this.minNumSamples = options.minNumSamples;\n this.maxDepth = options.maxDepth;\n }\n\n /**\n * @private\n * Function that retrieve the best feature to make the split.\n * @param {Matrix} XTranspose - Training set transposed\n * @param {Array} y - labels or values (depending of the decision tree)\n * @return {object} - return tree values, the best gain, column and the split value.\n */\n bestSplit(XTranspose, y) {\n\n // Depending in the node tree class, we set the variables to check information gain (to classify)\n // or error (for regression)\n\n var bestGain = this.kind === 'classifier' ? -Infinity : Infinity;\n var check = this.kind === 'classifier' ? (a, b) => a > b : (a, b) => a < b;\n\n\n var maxColumn;\n var maxValue;\n\n for (var i = 0; i < XTranspose.rows; ++i) {\n var currentFeature = XTranspose[i];\n var splitValues = this.featureSplit(currentFeature, y);\n for (var j = 0; j < splitValues.length; ++j) {\n var currentSplitVal = splitValues[j];\n var splitted = this.split(currentFeature, y, currentSplitVal);\n\n var gain = gainFunctions[this.gainFunction](y, splitted);\n if (check(gain, bestGain)) {\n maxColumn = i;\n maxValue = currentSplitVal;\n bestGain = gain;\n }\n }\n }\n\n return {\n maxGain: bestGain,\n maxColumn: maxColumn,\n maxValue: maxValue\n };\n }\n\n /**\n * @private\n * Makes the split of the training labels or values from the training set feature given a split value.\n * @param {Array} x - Training set feature\n * @param {Array} y - Training set value or label\n * @param {number} splitValue\n * @return {object}\n */\n\n split(x, y, splitValue) {\n var lesser = [];\n var greater = [];\n\n for (var i = 0; i < x.length; ++i) {\n if (x[i] < splitValue) {\n lesser.push(y[i]);\n } else {\n greater.push(y[i]);\n }\n }\n\n return {\n greater: greater,\n lesser: lesser\n };\n }\n\n /**\n * @private\n * Calculates the possible points to split over the tree given a training set feature and corresponding labels or values.\n * @param {Array} x - Training set feature\n * @param {Array} y - Training set value or label\n * @return {Array} possible split values.\n */\n featureSplit(x, y) {\n var splitValues = [];\n var arr = Utils.zip(x, y);\n arr.sort(function (a, b) {\n return a[0] - b[0];\n });\n\n for (var i = 1; i < arr.length; ++i) {\n if (arr[i - 1][1] !== arr[i][1]) {\n splitValues.push(splitFunctions[this.splitFunction](arr[i - 1][0], arr[i][0]));\n }\n }\n\n return splitValues;\n }\n\n /**\n * @private\n * Calculate the predictions of a leaf tree node given the training labels or values\n * @param {Array} y\n */\n calculatePrediction(y) {\n if (this.kind === 'classifier') {\n this.distribution = Utils.toDiscreteDistribution(y, Utils.getNumberOfClasses(y));\n if (this.distribution.columns === 0) {\n throw new TypeError('Error on calculate the prediction');\n }\n } else {\n this.distribution = mean(y);\n }\n }\n\n /**\n * @private\n * Train a node given the training set and labels, because it trains recursively, it also receive\n * the current depth of the node, parent gain to avoid infinite recursion and boolean value to check if\n * the training set is transposed.\n * @param {Matrix} X - Training set (could be transposed or not given transposed).\n * @param {Array} y - Training labels or values.\n * @param {number} currentDepth - Current depth of the node.\n * @param {number} parentGain - parent node gain or error.\n */\n train(X, y, currentDepth, parentGain) {\n if (X.rows <= this.minNumSamples) {\n this.calculatePrediction(y);\n return;\n }\n if (parentGain === undefined) parentGain = 0.0;\n\n var XTranspose = X.transpose();\n var split = this.bestSplit(XTranspose, y);\n\n this.splitValue = split.maxValue;\n this.splitColumn = split.maxColumn;\n this.gain = split.maxGain;\n\n var splittedMatrix = Utils.matrixSplitter(X, y, this.splitColumn, this.splitValue);\n\n if (currentDepth < this.maxDepth &&\n (this.gain > 0.01 && this.gain !== parentGain) &&\n (splittedMatrix.lesserX.length > 0 && splittedMatrix.greaterX.length > 0)) {\n this.left = new TreeNode(this);\n this.right = new TreeNode(this);\n\n var lesserX = new Matrix(splittedMatrix.lesserX);\n var greaterX = new Matrix(splittedMatrix.greaterX);\n\n this.left.train(lesserX, splittedMatrix.lesserY, currentDepth + 1, this.gain);\n this.right.train(greaterX, splittedMatrix.greaterY, currentDepth + 1, this.gain);\n } else {\n this.calculatePrediction(y);\n }\n }\n\n /**\n * @private\n * Calculates the prediction of a given element.\n * @param {Array} row\n * @return {number|Array} prediction\n * * if a node is a classifier returns an array of probabilities of each class.\n * * if a node is for regression returns a number with the prediction.\n */\n classify(row) {\n if (this.right && this.left) {\n if (row[this.splitColumn] < this.splitValue) {\n return this.left.classify(row);\n } else {\n return this.right.classify(row);\n }\n }\n\n return this.distribution;\n }\n\n /**\n * @private\n * Set the parameter of the current node and their children.\n * @param {object} node - parameters of the current node and the children.\n */\n setNodeParameters(node) {\n if (node.distribution !== undefined) {\n this.distribution = node.distribution.constructor === Array ? new Matrix(node.distribution) :\n node.distribution;\n } else {\n this.distribution = undefined;\n this.splitValue = node.splitValue;\n this.splitColumn = node.splitColumn;\n this.gain = node.gain;\n\n this.left = new TreeNode(this);\n this.right = new TreeNode(this);\n\n if (node.left !== {}) {\n this.left.setNodeParameters(node.left);\n }\n if (node.right !== {}) {\n this.right.setNodeParameters(node.right);\n }\n }\n }\n}\n","import Matrix from 'ml-matrix';\nimport Tree from './TreeNode';\n\nconst defaultOptions = {\n gainFunction: 'gini',\n splitFunction: 'mean',\n minNumSamples: 3,\n maxDepth: Infinity\n};\n\nexport class DecisionTreeClassifier {\n\n /**\n * Create new Decision Tree Classifier with CART implementation with the given options\n * @param {object} options\n * @param {string} [options.gainFunction=\"gini\"] - gain function to get the best split, \"gini\" the only one supported.\n * @param {string} [options.splitFunction=\"mean\"] - given two integers from a split feature, get the value to split, \"mean\" the only one supported.\n * @param {number} [options.minNumSamples=3] - minimum number of samples to create a leaf node to decide a class.\n * @param {number} [options.maxDepth=Infinity] - Max depth of the tree.\n * @param {object} model - for load purposes.\n * @constructor\n */\n constructor(options, model) {\n if (options === true) {\n this.options = model.options;\n this.root = new Tree(model.options);\n this.root.setNodeParameters(model.root);\n } else {\n this.options = Object.assign({}, defaultOptions, options);\n this.options.kind = 'classifier';\n }\n }\n\n /**\n * Train the decision tree with the given training set and labels.\n * @param {Matrix|MatrixTransposeView|Array} trainingSet\n * @param {Array} trainingLabels\n */\n train(trainingSet, trainingLabels) {\n this.root = new Tree(this.options);\n trainingSet = Matrix.checkMatrix(trainingSet);\n this.root.train(trainingSet, trainingLabels, 0, null);\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Matrix|MatrixTransposeView|Array} toPredict\n * @return {Array} predictions\n */\n predict(toPredict) {\n toPredict = Matrix.checkMatrix(toPredict);\n var predictions = new Array(toPredict.rows);\n\n for (var i = 0; i < toPredict.rows; ++i) {\n predictions[i] = this.root.classify(toPredict.getRow(i)).maxRowIndex(0)[1];\n }\n\n return predictions;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n options: this.options,\n root: this.root,\n name: 'DTClassifier'\n };\n }\n\n /**\n * Load a Decision tree classifier with the given model.\n * @param {object} model\n * @return {DecisionTreeClassifier}\n */\n static load(model) {\n if (model.name !== 'DTClassifier') {\n throw new RangeError('Invalid model: ' + model.name);\n }\n\n return new DecisionTreeClassifier(true, model);\n }\n}\n","import Matrix from 'ml-matrix';\nimport Tree from './TreeNode';\n\nconst defaultOptions = {\n gainFunction: 'regression',\n splitFunction: 'mean',\n minNumSamples: 3,\n maxDepth: Infinity\n};\n\nexport class DecisionTreeRegression {\n\n /**\n * Create new Decision Tree Regression with CART implementation with the given options.\n * @param {object} options\n * @param {string} [options.gainFunction=\"regression\"] - gain function to get the best split, \"regression\" the only one supported.\n * @param {string} [options.splitFunction=\"mean\"] - given two integers from a split feature, get the value to split, \"mean\" the only one supported.\n * @param {number} [options.minNumSamples=3] - minimum number of samples to create a leaf node to decide a class.\n * @param {number} [options.maxDepth=Infinity] - Max depth of the tree.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.options = model.options;\n this.root = new Tree(model.options);\n this.root.setNodeParameters(model.root);\n } else {\n this.options = Object.assign({}, defaultOptions, options);\n this.options.kind = 'regression';\n }\n }\n\n /**\n * Train the decision tree with the given training set and values.\n * @param {Matrix|MatrixTransposeView|Array} trainingSet\n * @param {Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n this.root = new Tree(this.options);\n\n if (trainingSet[0].length === undefined) trainingSet = Matrix.columnVector(trainingSet);\n trainingSet = Matrix.checkMatrix(trainingSet);\n this.root.train(trainingSet, trainingValues, 0);\n }\n\n /**\n * Predicts the values given the matrix to predict.\n * @param {Matrix|MatrixTransposeView|Array} toPredict\n * @return {Array} predictions\n */\n predict(toPredict) {\n if (toPredict[0] !== undefined && toPredict[0].length === undefined) toPredict = Matrix.columnVector(toPredict);\n toPredict = Matrix.checkMatrix(toPredict);\n\n var predictions = new Array(toPredict.rows);\n for (var i = 0; i < toPredict.rows; ++i) {\n predictions[i] = this.root.classify(toPredict.getRow(i));\n }\n\n return predictions;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n options: this.options,\n root: this.root,\n name: 'DTRegression'\n };\n }\n\n /**\n * Load a Decision tree regression with the given model.\n * @param {object} model\n * @return {DecisionTreeRegression}\n */\n static load(model) {\n if (model.name !== 'DTRegression') {\n throw new RangeError('Invalid model:' + model.name);\n }\n\n return new DecisionTreeRegression(true, model);\n }\n}\n","export {DecisionTreeClassifier} from './DecisionTreeClassifier';\nexport {DecisionTreeRegression} from './DecisionTreeRegression';\n","import isArray from 'is-any-array';\n\n/**\n * Computes the maximum of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction max(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var max = input[0];\n\n for (var i = 1; i < input.length; i++) {\n if (input[i] > max) max = input[i];\n }\n\n return max;\n}\n\nexport default max;\n","'use strict';\n\nconst Matrix = require('ml-matrix').Matrix;\n\nconst GaussianKernel = require('ml-kernel-gaussian');\nconst PolynomialKernel = require('ml-kernel-polynomial');\nconst ANOVAKernel = require('./kernels/anova-kernel');\nconst CauchyKernel = require('./kernels/cauchy-kernel');\nconst ExponentialKernel = require('./kernels/exponential-kernel');\nconst HistogramKernel = require('./kernels/histogram-intersection-kernel');\nconst LaplacianKernel = require('./kernels/laplacian-kernel');\nconst MultiquadraticKernel = require('./kernels/multiquadratic-kernel');\nconst RationalKernel = require('./kernels/rational-quadratic-kernel');\nconst SigmoidKernel = require('ml-kernel-sigmoid');\n\nconst kernelType = {\n gaussian: GaussianKernel,\n rbf: GaussianKernel,\n polynomial: PolynomialKernel,\n poly: PolynomialKernel,\n anova: ANOVAKernel,\n cauchy: CauchyKernel,\n exponential: ExponentialKernel,\n histogram: HistogramKernel,\n min: HistogramKernel,\n laplacian: LaplacianKernel,\n multiquadratic: MultiquadraticKernel,\n rational: RationalKernel,\n sigmoid: SigmoidKernel,\n mlp: SigmoidKernel\n};\n\nclass Kernel {\n constructor(type, options) {\n this.kernelType = type;\n if (type === 'linear') return;\n\n if (typeof type === 'string') {\n type = type.toLowerCase();\n\n var KernelConstructor = kernelType[type];\n if (KernelConstructor) {\n this.kernelFunction = new KernelConstructor(options);\n } else {\n throw new Error('unsupported kernel type: ' + type);\n }\n } else if (typeof type === 'object' && typeof type.compute === 'function') {\n this.kernelFunction = type;\n } else {\n throw new TypeError('first argument must be a valid kernel type or instance');\n }\n }\n\n compute(inputs, landmarks) {\n if (landmarks === undefined) {\n landmarks = inputs;\n }\n\n if (this.kernelType === 'linear') {\n var matrix = new Matrix(inputs);\n return matrix.mmul(new Matrix(landmarks).transposeView());\n }\n\n const kernelMatrix = new Matrix(inputs.length, landmarks.length);\n var i, j;\n if (inputs === landmarks) { // fast path, matrix is symmetric\n for (i = 0; i < inputs.length; i++) {\n for (j = i; j < inputs.length; j++) {\n kernelMatrix[i][j] = kernelMatrix[j][i] = this.kernelFunction.compute(inputs[i], inputs[j]);\n }\n }\n } else {\n for (i = 0; i < inputs.length; i++) {\n for (j = 0; j < landmarks.length; j++) {\n kernelMatrix[i][j] = this.kernelFunction.compute(inputs[i], landmarks[j]);\n }\n }\n }\n return kernelMatrix;\n }\n}\n\nmodule.exports = Kernel;\n","const PROB_TOLERANCE = 0.00000001;\nfunction randomChoice(values, options = {}, random = Math.random) {\n const { size = 1, replace = false, probabilities } = options;\n let valuesArr;\n let cumSum;\n if (typeof values === 'number') {\n valuesArr = getArray(values);\n }\n else {\n valuesArr = values.slice();\n }\n if (probabilities) {\n if (!replace) {\n throw new Error('choice with probabilities and no replacement is not implemented');\n }\n // check input is sane\n if (probabilities.length !== valuesArr.length) {\n throw new Error('the length of probabilities option should be equal to the number of choices');\n }\n cumSum = [probabilities[0]];\n for (let i = 1; i < probabilities.length; i++) {\n cumSum[i] = cumSum[i - 1] + probabilities[i];\n }\n if (Math.abs(1 - cumSum[cumSum.length - 1]) > PROB_TOLERANCE) {\n throw new Error(`probabilities should sum to 1, but instead sums to ${cumSum[cumSum.length - 1]}`);\n }\n }\n if (replace === false && size > valuesArr.length) {\n throw new Error('size option is too large');\n }\n const result = [];\n for (let i = 0; i < size; i++) {\n const index = randomIndex(valuesArr.length, random, cumSum);\n result.push(valuesArr[index]);\n if (!replace) {\n valuesArr.splice(index, 1);\n }\n }\n return result;\n}\nfunction getArray(n) {\n const arr = [];\n for (let i = 0; i < n; i++) {\n arr.push(i);\n }\n return arr;\n}\nfunction randomIndex(n, random, cumSum) {\n const rand = random();\n if (!cumSum) {\n return Math.floor(rand * n);\n }\n else {\n let idx = 0;\n while (rand > cumSum[idx]) {\n idx++;\n }\n return idx;\n }\n}\nexport default randomChoice;\n","// tslint:disable-next-line\nimport XSAdd from 'ml-xsadd';\nimport choice from './choice';\n/**\n * @classdesc Random class\n */\nexport default class Random {\n /**\n * @param [seedOrRandom=Math.random] - Control the random number generator used by the Random class instance. Pass a random number generator function with a uniform distribution over the half-open interval [0, 1[. If seed will pass it to ml-xsadd to create a seeded random number generator. If undefined will use Math.random.\n */\n constructor(seedOrRandom = Math.random) {\n if (typeof seedOrRandom === 'number') {\n const xsadd = new XSAdd(seedOrRandom);\n this.randomGenerator = xsadd.random;\n }\n else {\n this.randomGenerator = seedOrRandom;\n }\n }\n choice(values, options) {\n if (typeof values === 'number') {\n return choice(values, options, this.randomGenerator);\n }\n return choice(values, options, this.randomGenerator);\n }\n /**\n * Draw a random number from a uniform distribution on [0,1)\n * @return The random number\n */\n random() {\n return this.randomGenerator();\n }\n /**\n * Draw a random integer from a uniform distribution on [low, high). If only low is specified, the number is drawn on [0, low)\n * @param low - The lower bound of the uniform distribution interval.\n * @param high - The higher bound of the uniform distribution interval.\n */\n randInt(low, high) {\n if (high === undefined) {\n high = low;\n low = 0;\n }\n return low + Math.floor(this.randomGenerator() * (high - low));\n }\n /**\n * Draw several random number from a uniform distribution on [0, 1)\n * @param size - The number of number to draw\n * @return - The list of drawn numbers.\n */\n randomSample(size) {\n const result = [];\n for (let i = 0; i < size; i++) {\n result.push(this.random());\n }\n return result;\n }\n}\n","/*jshint eqnull:true*/\n(function (root) {\n \"use strict\";\n\n var GLOBAL_KEY = \"Random\";\n\n var imul = (typeof Math.imul !== \"function\" || Math.imul(0xffffffff, 5) !== -5 ?\n function (a, b) {\n var ah = (a >>> 16) & 0xffff;\n var al = a & 0xffff;\n var bh = (b >>> 16) & 0xffff;\n var bl = b & 0xffff;\n // the shift by 0 fixes the sign on the high part\n // the final |0 converts the unsigned value into a signed value\n return (al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0;\n } :\n Math.imul);\n\n var stringRepeat = (typeof String.prototype.repeat === \"function\" && \"x\".repeat(3) === \"xxx\" ?\n function (x, y) {\n return x.repeat(y);\n } : function (pattern, count) {\n var result = \"\";\n while (count > 0) {\n if (count & 1) {\n result += pattern;\n }\n count >>= 1;\n pattern += pattern;\n }\n return result;\n });\n\n function Random(engine) {\n if (!(this instanceof Random)) {\n return new Random(engine);\n }\n\n if (engine == null) {\n engine = Random.engines.nativeMath;\n } else if (typeof engine !== \"function\") {\n throw new TypeError(\"Expected engine to be a function, got \" + typeof engine);\n }\n this.engine = engine;\n }\n var proto = Random.prototype;\n\n Random.engines = {\n nativeMath: function () {\n return (Math.random() * 0x100000000) | 0;\n },\n mt19937: (function (Int32Array) {\n // http://en.wikipedia.org/wiki/Mersenne_twister\n function refreshData(data) {\n var k = 0;\n var tmp = 0;\n for (;\n (k | 0) < 227; k = (k + 1) | 0) {\n tmp = (data[k] & 0x80000000) | (data[(k + 1) | 0] & 0x7fffffff);\n data[k] = data[(k + 397) | 0] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);\n }\n\n for (;\n (k | 0) < 623; k = (k + 1) | 0) {\n tmp = (data[k] & 0x80000000) | (data[(k + 1) | 0] & 0x7fffffff);\n data[k] = data[(k - 227) | 0] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);\n }\n\n tmp = (data[623] & 0x80000000) | (data[0] & 0x7fffffff);\n data[623] = data[396] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);\n }\n\n function temper(value) {\n value ^= value >>> 11;\n value ^= (value << 7) & 0x9d2c5680;\n value ^= (value << 15) & 0xefc60000;\n return value ^ (value >>> 18);\n }\n\n function seedWithArray(data, source) {\n var i = 1;\n var j = 0;\n var sourceLength = source.length;\n var k = Math.max(sourceLength, 624) | 0;\n var previous = data[0] | 0;\n for (;\n (k | 0) > 0; --k) {\n data[i] = previous = ((data[i] ^ imul((previous ^ (previous >>> 30)), 0x0019660d)) + (source[j] | 0) + (j | 0)) | 0;\n i = (i + 1) | 0;\n ++j;\n if ((i | 0) > 623) {\n data[0] = data[623];\n i = 1;\n }\n if (j >= sourceLength) {\n j = 0;\n }\n }\n for (k = 623;\n (k | 0) > 0; --k) {\n data[i] = previous = ((data[i] ^ imul((previous ^ (previous >>> 30)), 0x5d588b65)) - i) | 0;\n i = (i + 1) | 0;\n if ((i | 0) > 623) {\n data[0] = data[623];\n i = 1;\n }\n }\n data[0] = 0x80000000;\n }\n\n function mt19937() {\n var data = new Int32Array(624);\n var index = 0;\n var uses = 0;\n\n function next() {\n if ((index | 0) >= 624) {\n refreshData(data);\n index = 0;\n }\n\n var value = data[index];\n index = (index + 1) | 0;\n uses += 1;\n return temper(value) | 0;\n }\n next.getUseCount = function() {\n return uses;\n };\n next.discard = function (count) {\n uses += count;\n if ((index | 0) >= 624) {\n refreshData(data);\n index = 0;\n }\n while ((count - index) > 624) {\n count -= 624 - index;\n refreshData(data);\n index = 0;\n }\n index = (index + count) | 0;\n return next;\n };\n next.seed = function (initial) {\n var previous = 0;\n data[0] = previous = initial | 0;\n\n for (var i = 1; i < 624; i = (i + 1) | 0) {\n data[i] = previous = (imul((previous ^ (previous >>> 30)), 0x6c078965) + i) | 0;\n }\n index = 624;\n uses = 0;\n return next;\n };\n next.seedWithArray = function (source) {\n next.seed(0x012bd6aa);\n seedWithArray(data, source);\n return next;\n };\n next.autoSeed = function () {\n return next.seedWithArray(Random.generateEntropyArray());\n };\n return next;\n }\n\n return mt19937;\n }(typeof Int32Array === \"function\" ? Int32Array : Array)),\n browserCrypto: (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\" && typeof Int32Array === \"function\") ? (function () {\n var data = null;\n var index = 128;\n\n return function () {\n if (index >= 128) {\n if (data === null) {\n data = new Int32Array(128);\n }\n crypto.getRandomValues(data);\n index = 0;\n }\n\n return data[index++] | 0;\n };\n }()) : null\n };\n\n Random.generateEntropyArray = function () {\n var array = [];\n var engine = Random.engines.nativeMath;\n for (var i = 0; i < 16; ++i) {\n array[i] = engine() | 0;\n }\n array.push(new Date().getTime() | 0);\n return array;\n };\n\n function returnValue(value) {\n return function () {\n return value;\n };\n }\n\n // [-0x80000000, 0x7fffffff]\n Random.int32 = function (engine) {\n return engine() | 0;\n };\n proto.int32 = function () {\n return Random.int32(this.engine);\n };\n\n // [0, 0xffffffff]\n Random.uint32 = function (engine) {\n return engine() >>> 0;\n };\n proto.uint32 = function () {\n return Random.uint32(this.engine);\n };\n\n // [0, 0x1fffffffffffff]\n Random.uint53 = function (engine) {\n var high = engine() & 0x1fffff;\n var low = engine() >>> 0;\n return (high * 0x100000000) + low;\n };\n proto.uint53 = function () {\n return Random.uint53(this.engine);\n };\n\n // [0, 0x20000000000000]\n Random.uint53Full = function (engine) {\n while (true) {\n var high = engine() | 0;\n if (high & 0x200000) {\n if ((high & 0x3fffff) === 0x200000 && (engine() | 0) === 0) {\n return 0x20000000000000;\n }\n } else {\n var low = engine() >>> 0;\n return ((high & 0x1fffff) * 0x100000000) + low;\n }\n }\n };\n proto.uint53Full = function () {\n return Random.uint53Full(this.engine);\n };\n\n // [-0x20000000000000, 0x1fffffffffffff]\n Random.int53 = function (engine) {\n var high = engine() | 0;\n var low = engine() >>> 0;\n return ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);\n };\n proto.int53 = function () {\n return Random.int53(this.engine);\n };\n\n // [-0x20000000000000, 0x20000000000000]\n Random.int53Full = function (engine) {\n while (true) {\n var high = engine() | 0;\n if (high & 0x400000) {\n if ((high & 0x7fffff) === 0x400000 && (engine() | 0) === 0) {\n return 0x20000000000000;\n }\n } else {\n var low = engine() >>> 0;\n return ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);\n }\n }\n };\n proto.int53Full = function () {\n return Random.int53Full(this.engine);\n };\n\n function add(generate, addend) {\n if (addend === 0) {\n return generate;\n } else {\n return function (engine) {\n return generate(engine) + addend;\n };\n }\n }\n\n Random.integer = (function () {\n function isPowerOfTwoMinusOne(value) {\n return ((value + 1) & value) === 0;\n }\n\n function bitmask(masking) {\n return function (engine) {\n return engine() & masking;\n };\n }\n\n function downscaleToLoopCheckedRange(range) {\n var extendedRange = range + 1;\n var maximum = extendedRange * Math.floor(0x100000000 / extendedRange);\n return function (engine) {\n var value = 0;\n do {\n value = engine() >>> 0;\n } while (value >= maximum);\n return value % extendedRange;\n };\n }\n\n function downscaleToRange(range) {\n if (isPowerOfTwoMinusOne(range)) {\n return bitmask(range);\n } else {\n return downscaleToLoopCheckedRange(range);\n }\n }\n\n function isEvenlyDivisibleByMaxInt32(value) {\n return (value | 0) === 0;\n }\n\n function upscaleWithHighMasking(masking) {\n return function (engine) {\n var high = engine() & masking;\n var low = engine() >>> 0;\n return (high * 0x100000000) + low;\n };\n }\n\n function upscaleToLoopCheckedRange(extendedRange) {\n var maximum = extendedRange * Math.floor(0x20000000000000 / extendedRange);\n return function (engine) {\n var ret = 0;\n do {\n var high = engine() & 0x1fffff;\n var low = engine() >>> 0;\n ret = (high * 0x100000000) + low;\n } while (ret >= maximum);\n return ret % extendedRange;\n };\n }\n\n function upscaleWithinU53(range) {\n var extendedRange = range + 1;\n if (isEvenlyDivisibleByMaxInt32(extendedRange)) {\n var highRange = ((extendedRange / 0x100000000) | 0) - 1;\n if (isPowerOfTwoMinusOne(highRange)) {\n return upscaleWithHighMasking(highRange);\n }\n }\n return upscaleToLoopCheckedRange(extendedRange);\n }\n\n function upscaleWithinI53AndLoopCheck(min, max) {\n return function (engine) {\n var ret = 0;\n do {\n var high = engine() | 0;\n var low = engine() >>> 0;\n ret = ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);\n } while (ret < min || ret > max);\n return ret;\n };\n }\n\n return function (min, max) {\n min = Math.floor(min);\n max = Math.floor(max);\n if (min < -0x20000000000000 || !isFinite(min)) {\n throw new RangeError(\"Expected min to be at least \" + (-0x20000000000000));\n } else if (max > 0x20000000000000 || !isFinite(max)) {\n throw new RangeError(\"Expected max to be at most \" + 0x20000000000000);\n }\n\n var range = max - min;\n if (range <= 0 || !isFinite(range)) {\n return returnValue(min);\n } else if (range === 0xffffffff) {\n if (min === 0) {\n return Random.uint32;\n } else {\n return add(Random.int32, min + 0x80000000);\n }\n } else if (range < 0xffffffff) {\n return add(downscaleToRange(range), min);\n } else if (range === 0x1fffffffffffff) {\n return add(Random.uint53, min);\n } else if (range < 0x1fffffffffffff) {\n return add(upscaleWithinU53(range), min);\n } else if (max - 1 - min === 0x1fffffffffffff) {\n return add(Random.uint53Full, min);\n } else if (min === -0x20000000000000 && max === 0x20000000000000) {\n return Random.int53Full;\n } else if (min === -0x20000000000000 && max === 0x1fffffffffffff) {\n return Random.int53;\n } else if (min === -0x1fffffffffffff && max === 0x20000000000000) {\n return add(Random.int53, 1);\n } else if (max === 0x20000000000000) {\n return add(upscaleWithinI53AndLoopCheck(min - 1, max - 1), 1);\n } else {\n return upscaleWithinI53AndLoopCheck(min, max);\n }\n };\n }());\n proto.integer = function (min, max) {\n return Random.integer(min, max)(this.engine);\n };\n\n // [0, 1] (floating point)\n Random.realZeroToOneInclusive = function (engine) {\n return Random.uint53Full(engine) / 0x20000000000000;\n };\n proto.realZeroToOneInclusive = function () {\n return Random.realZeroToOneInclusive(this.engine);\n };\n\n // [0, 1) (floating point)\n Random.realZeroToOneExclusive = function (engine) {\n return Random.uint53(engine) / 0x20000000000000;\n };\n proto.realZeroToOneExclusive = function () {\n return Random.realZeroToOneExclusive(this.engine);\n };\n\n Random.real = (function () {\n function multiply(generate, multiplier) {\n if (multiplier === 1) {\n return generate;\n } else if (multiplier === 0) {\n return function () {\n return 0;\n };\n } else {\n return function (engine) {\n return generate(engine) * multiplier;\n };\n }\n }\n\n return function (left, right, inclusive) {\n if (!isFinite(left)) {\n throw new RangeError(\"Expected left to be a finite number\");\n } else if (!isFinite(right)) {\n throw new RangeError(\"Expected right to be a finite number\");\n }\n return add(\n multiply(\n inclusive ? Random.realZeroToOneInclusive : Random.realZeroToOneExclusive,\n right - left),\n left);\n };\n }());\n proto.real = function (min, max, inclusive) {\n return Random.real(min, max, inclusive)(this.engine);\n };\n\n Random.bool = (function () {\n function isLeastBitTrue(engine) {\n return (engine() & 1) === 1;\n }\n\n function lessThan(generate, value) {\n return function (engine) {\n return generate(engine) < value;\n };\n }\n\n function probability(percentage) {\n if (percentage <= 0) {\n return returnValue(false);\n } else if (percentage >= 1) {\n return returnValue(true);\n } else {\n var scaled = percentage * 0x100000000;\n if (scaled % 1 === 0) {\n return lessThan(Random.int32, (scaled - 0x80000000) | 0);\n } else {\n return lessThan(Random.uint53, Math.round(percentage * 0x20000000000000));\n }\n }\n }\n\n return function (numerator, denominator) {\n if (denominator == null) {\n if (numerator == null) {\n return isLeastBitTrue;\n }\n return probability(numerator);\n } else {\n if (numerator <= 0) {\n return returnValue(false);\n } else if (numerator >= denominator) {\n return returnValue(true);\n }\n return lessThan(Random.integer(0, denominator - 1), numerator);\n }\n };\n }());\n proto.bool = function (numerator, denominator) {\n return Random.bool(numerator, denominator)(this.engine);\n };\n\n function toInteger(value) {\n var number = +value;\n if (number < 0) {\n return Math.ceil(number);\n } else {\n return Math.floor(number);\n }\n }\n\n function convertSliceArgument(value, length) {\n if (value < 0) {\n return Math.max(value + length, 0);\n } else {\n return Math.min(value, length);\n }\n }\n Random.pick = function (engine, array, begin, end) {\n var length = array.length;\n var start = begin == null ? 0 : convertSliceArgument(toInteger(begin), length);\n var finish = end === void 0 ? length : convertSliceArgument(toInteger(end), length);\n if (start >= finish) {\n return void 0;\n }\n var distribution = Random.integer(start, finish - 1);\n return array[distribution(engine)];\n };\n proto.pick = function (array, begin, end) {\n return Random.pick(this.engine, array, begin, end);\n };\n\n function returnUndefined() {\n return void 0;\n }\n var slice = Array.prototype.slice;\n Random.picker = function (array, begin, end) {\n var clone = slice.call(array, begin, end);\n if (!clone.length) {\n return returnUndefined;\n }\n var distribution = Random.integer(0, clone.length - 1);\n return function (engine) {\n return clone[distribution(engine)];\n };\n };\n\n Random.shuffle = function (engine, array, downTo) {\n var length = array.length;\n if (length) {\n if (downTo == null) {\n downTo = 0;\n }\n for (var i = (length - 1) >>> 0; i > downTo; --i) {\n var distribution = Random.integer(0, i);\n var j = distribution(engine);\n if (i !== j) {\n var tmp = array[i];\n array[i] = array[j];\n array[j] = tmp;\n }\n }\n }\n return array;\n };\n proto.shuffle = function (array) {\n return Random.shuffle(this.engine, array);\n };\n\n Random.sample = function (engine, population, sampleSize) {\n if (sampleSize < 0 || sampleSize > population.length || !isFinite(sampleSize)) {\n throw new RangeError(\"Expected sampleSize to be within 0 and the length of the population\");\n }\n\n if (sampleSize === 0) {\n return [];\n }\n\n var clone = slice.call(population);\n var length = clone.length;\n if (length === sampleSize) {\n return Random.shuffle(engine, clone, 0);\n }\n var tailLength = length - sampleSize;\n return Random.shuffle(engine, clone, tailLength - 1).slice(tailLength);\n };\n proto.sample = function (population, sampleSize) {\n return Random.sample(this.engine, population, sampleSize);\n };\n\n Random.die = function (sideCount) {\n return Random.integer(1, sideCount);\n };\n proto.die = function (sideCount) {\n return Random.die(sideCount)(this.engine);\n };\n\n Random.dice = function (sideCount, dieCount) {\n var distribution = Random.die(sideCount);\n return function (engine) {\n var result = [];\n result.length = dieCount;\n for (var i = 0; i < dieCount; ++i) {\n result[i] = distribution(engine);\n }\n return result;\n };\n };\n proto.dice = function (sideCount, dieCount) {\n return Random.dice(sideCount, dieCount)(this.engine);\n };\n\n // http://en.wikipedia.org/wiki/Universally_unique_identifier\n Random.uuid4 = (function () {\n function zeroPad(string, zeroCount) {\n return stringRepeat(\"0\", zeroCount - string.length) + string;\n }\n\n return function (engine) {\n var a = engine() >>> 0;\n var b = engine() | 0;\n var c = engine() | 0;\n var d = engine() >>> 0;\n\n return (\n zeroPad(a.toString(16), 8) +\n \"-\" +\n zeroPad((b & 0xffff).toString(16), 4) +\n \"-\" +\n zeroPad((((b >> 4) & 0x0fff) | 0x4000).toString(16), 4) +\n \"-\" +\n zeroPad(((c & 0x3fff) | 0x8000).toString(16), 4) +\n \"-\" +\n zeroPad(((c >> 4) & 0xffff).toString(16), 4) +\n zeroPad(d.toString(16), 8));\n };\n }());\n proto.uuid4 = function () {\n return Random.uuid4(this.engine);\n };\n\n Random.string = (function () {\n // has 2**x chars, for faster uniform distribution\n var DEFAULT_STRING_POOL = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-\";\n\n return function (pool) {\n if (pool == null) {\n pool = DEFAULT_STRING_POOL;\n }\n\n var length = pool.length;\n if (!length) {\n throw new Error(\"Expected pool not to be an empty string\");\n }\n\n var distribution = Random.integer(0, length - 1);\n return function (engine, length) {\n var result = \"\";\n for (var i = 0; i < length; ++i) {\n var j = distribution(engine);\n result += pool.charAt(j);\n }\n return result;\n };\n };\n }());\n proto.string = function (length, pool) {\n return Random.string(pool)(this.engine, length);\n };\n\n Random.hex = (function () {\n var LOWER_HEX_POOL = \"0123456789abcdef\";\n var lowerHex = Random.string(LOWER_HEX_POOL);\n var upperHex = Random.string(LOWER_HEX_POOL.toUpperCase());\n\n return function (upper) {\n if (upper) {\n return upperHex;\n } else {\n return lowerHex;\n }\n };\n }());\n proto.hex = function (length, upper) {\n return Random.hex(upper)(this.engine, length);\n };\n\n Random.date = function (start, end) {\n if (!(start instanceof Date)) {\n throw new TypeError(\"Expected start to be a Date, got \" + typeof start);\n } else if (!(end instanceof Date)) {\n throw new TypeError(\"Expected end to be a Date, got \" + typeof end);\n }\n var distribution = Random.integer(start.getTime(), end.getTime());\n return function (engine) {\n return new Date(distribution(engine));\n };\n };\n proto.date = function (start, end) {\n return Random.date(start, end)(this.engine);\n };\n\n if (typeof define === \"function\" && define.amd) {\n define(function () {\n return Random;\n });\n } else if (typeof module !== \"undefined\" && typeof require === \"function\") {\n module.exports = Random;\n } else {\n (function () {\n var oldGlobal = root[GLOBAL_KEY];\n Random.noConflict = function () {\n root[GLOBAL_KEY] = oldGlobal;\n return this;\n };\n }());\n root[GLOBAL_KEY] = Random;\n }\n}(this));","import max from 'ml-array-max';\nimport min from 'ml-array-min';\nimport isArray from 'is-any-array';\n\nfunction rescale(input) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n } else if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var output;\n\n if (options.output !== undefined) {\n if (!isArray(options.output)) {\n throw new TypeError('output option must be an array if specified');\n }\n\n output = options.output;\n } else {\n output = new Array(input.length);\n }\n\n var currentMin = min(input);\n var currentMax = max(input);\n\n if (currentMin === currentMax) {\n throw new RangeError('minimum and maximum input values are equal. Cannot rescale a constant array');\n }\n\n var _options$min = options.min,\n minValue = _options$min === void 0 ? options.autoMinMax ? currentMin : 0 : _options$min,\n _options$max = options.max,\n maxValue = _options$max === void 0 ? options.autoMinMax ? currentMax : 1 : _options$max;\n\n if (minValue >= maxValue) {\n throw new RangeError('min option must be smaller than max option');\n }\n\n var factor = (maxValue - minValue) / (currentMax - currentMin);\n\n for (var i = 0; i < input.length; i++) {\n output[i] = (input[i] - currentMin) * factor + minValue;\n }\n\n return output;\n}\n\nexport default rescale;\n","'use strict';\n\nconst newArray = require('new-array');\n\nconst primeFinder = require('./primeFinder');\nconst nextPrime = primeFinder.nextPrime;\nconst largestPrime = primeFinder.largestPrime;\n\nconst FREE = 0;\nconst FULL = 1;\nconst REMOVED = 2;\n\nconst defaultInitialCapacity = 150;\nconst defaultMinLoadFactor = 1 / 6;\nconst defaultMaxLoadFactor = 2 / 3;\n\nclass HashTable {\n constructor(options = {}) {\n if (options instanceof HashTable) {\n this.table = options.table.slice();\n this.values = options.values.slice();\n this.state = options.state.slice();\n this.minLoadFactor = options.minLoadFactor;\n this.maxLoadFactor = options.maxLoadFactor;\n this.distinct = options.distinct;\n this.freeEntries = options.freeEntries;\n this.lowWaterMark = options.lowWaterMark;\n this.highWaterMark = options.maxLoadFactor;\n return;\n }\n\n const initialCapacity = options.initialCapacity === undefined ? defaultInitialCapacity : options.initialCapacity;\n if (initialCapacity < 0) {\n throw new RangeError(`initial capacity must not be less than zero: ${initialCapacity}`);\n }\n\n const minLoadFactor = options.minLoadFactor === undefined ? defaultMinLoadFactor : options.minLoadFactor;\n const maxLoadFactor = options.maxLoadFactor === undefined ? defaultMaxLoadFactor : options.maxLoadFactor;\n if (minLoadFactor < 0 || minLoadFactor >= 1) {\n throw new RangeError(`invalid minLoadFactor: ${minLoadFactor}`);\n }\n if (maxLoadFactor <= 0 || maxLoadFactor >= 1) {\n throw new RangeError(`invalid maxLoadFactor: ${maxLoadFactor}`);\n }\n if (minLoadFactor >= maxLoadFactor) {\n throw new RangeError(`minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`);\n }\n\n let capacity = initialCapacity;\n // User wants to put at least capacity elements. We need to choose the size based on the maxLoadFactor to\n // avoid the need to rehash before this capacity is reached.\n // actualCapacity * maxLoadFactor >= capacity\n capacity = (capacity / maxLoadFactor) | 0;\n capacity = nextPrime(capacity);\n if (capacity === 0) capacity = 1;\n\n this.table = newArray(capacity, 0);\n this.values = newArray(capacity, 0);\n this.state = newArray(capacity, 0);\n\n this.minLoadFactor = minLoadFactor;\n if (capacity === largestPrime) {\n this.maxLoadFactor = 1;\n } else {\n this.maxLoadFactor = maxLoadFactor;\n }\n\n this.distinct = 0;\n this.freeEntries = capacity;\n\n this.lowWaterMark = 0;\n this.highWaterMark = chooseHighWaterMark(capacity, this.maxLoadFactor);\n }\n\n clone() {\n return new HashTable(this);\n }\n\n get size() {\n return this.distinct;\n }\n\n get(key) {\n const i = this.indexOfKey(key);\n if (i < 0) return 0;\n return this.values[i];\n }\n\n set(key, value) {\n let i = this.indexOfInsertion(key);\n if (i < 0) {\n i = -i - 1;\n this.values[i] = value;\n return false;\n }\n\n if (this.distinct > this.highWaterMark) {\n const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n return this.set(key, value);\n }\n\n this.table[i] = key;\n this.values[i] = value;\n if (this.state[i] === FREE) this.freeEntries--;\n this.state[i] = FULL;\n this.distinct++;\n\n if (this.freeEntries < 1) {\n const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n }\n\n return true;\n }\n \n remove(key, noRehash) {\n const i = this.indexOfKey(key);\n if (i < 0) return false;\n\n this.state[i] = REMOVED;\n this.distinct--;\n\n if (!noRehash) this.maybeShrinkCapacity();\n\n return true;\n }\n\n delete(key, noRehash) {\n const i = this.indexOfKey(key);\n if (i < 0) return false;\n\n this.state[i] = FREE;\n this.distinct--;\n\n if (!noRehash) this.maybeShrinkCapacity();\n\n return true;\n }\n\n maybeShrinkCapacity() {\n if (this.distinct < this.lowWaterMark) {\n const newCapacity = chooseShrinkCapacity(this.distinct, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n }\n }\n\n containsKey(key) {\n return this.indexOfKey(key) >= 0;\n }\n\n indexOfKey(key) {\n const table = this.table;\n const state = this.state;\n const length = this.table.length;\n\n const hash = key & 0x7fffffff;\n let i = hash % length;\n let decrement = hash % (length - 2);\n if (decrement === 0) decrement = 1;\n\n while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) {\n i -= decrement;\n if (i < 0) i += length;\n }\n\n if (state[i] === FREE) return -1;\n return i;\n }\n\n containsValue(value) {\n return this.indexOfValue(value) >= 0;\n }\n\n indexOfValue(value) {\n const values = this.values;\n const state = this.state;\n\n for (var i = 0; i < state.length; i++) {\n if (state[i] === FULL && values[i] === value) {\n return i;\n }\n }\n\n return -1;\n }\n\n indexOfInsertion(key) {\n const table = this.table;\n const state = this.state;\n const length = table.length;\n\n\n const hash = key & 0x7fffffff;\n let i = hash % length;\n let decrement = hash % (length - 2);\n if (decrement === 0) decrement = 1;\n\n while (state[i] === FULL && table[i] !== key) {\n i -= decrement;\n if (i < 0) i += length;\n }\n\n if (state[i] === REMOVED) {\n const j = i;\n while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) {\n i -= decrement;\n if (i < 0) i += length;\n }\n if (state[i] === FREE) i = j;\n }\n\n if (state[i] === FULL) {\n return -i - 1;\n }\n\n return i;\n }\n\n ensureCapacity(minCapacity) {\n if (this.table.length < minCapacity) {\n const newCapacity = nextPrime(minCapacity);\n this.rehash(newCapacity);\n }\n }\n\n rehash(newCapacity) {\n const oldCapacity = this.table.length;\n\n if (newCapacity <= this.distinct) throw new Error('Unexpected');\n\n const oldTable = this.table;\n const oldValues = this.values;\n const oldState = this.state;\n\n const newTable = newArray(newCapacity, 0);\n const newValues = newArray(newCapacity, 0);\n const newState = newArray(newCapacity, 0);\n\n this.lowWaterMark = chooseLowWaterMark(newCapacity, this.minLoadFactor);\n this.highWaterMark = chooseHighWaterMark(newCapacity, this.maxLoadFactor);\n\n this.table = newTable;\n this.values = newValues;\n this.state = newState;\n this.freeEntries = newCapacity - this.distinct;\n\n for (var i = 0; i < oldCapacity; i++) {\n if (oldState[i] === FULL) {\n var element = oldTable[i];\n var index = this.indexOfInsertion(element);\n newTable[index] = element;\n newValues[index] = oldValues[i];\n newState[index] = FULL;\n }\n }\n }\n\n forEachKey(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.table[i])) return false;\n }\n }\n return true;\n }\n\n forEachValue(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.values[i])) return false;\n }\n }\n return true;\n }\n\n forEachPair(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.table[i], this.values[i])) return false;\n }\n }\n return true;\n }\n}\n\nmodule.exports = HashTable;\n\nfunction chooseLowWaterMark(capacity, minLoad) {\n return (capacity * minLoad) | 0;\n}\n\nfunction chooseHighWaterMark(capacity, maxLoad) {\n return Math.min(capacity - 2, (capacity * maxLoad) | 0);\n}\n\nfunction chooseGrowCapacity(size, minLoad, maxLoad) {\n return nextPrime(Math.max(size + 1, (4 * size / (3 * minLoad + maxLoad)) | 0));\n}\n\nfunction chooseShrinkCapacity(size, minLoad, maxLoad) {\n return nextPrime(Math.max(size + 1, (4 * size / (minLoad + 3 * maxLoad)) | 0));\n}\n","'use strict';\n\nconst Heap = require('heap');\n\nfunction Cluster() {\n this.children = [];\n this.distance = -1;\n this.index = [];\n}\n\n/**\n * Creates an array of values where maximum distance smaller than the threshold\n * @param {number} threshold\n * @return {Array }\n */\nCluster.prototype.cut = function (threshold) {\n if (threshold < 0) throw new RangeError('Threshold too small');\n var root = new Cluster();\n root.children = this.children;\n root.distance = this.distance;\n root.index = this.index;\n var list = [root];\n var ans = [];\n while (list.length > 0) {\n var aux = list.shift();\n if (threshold >= aux.distance) {\n ans.push(aux);\n } else {\n list = list.concat(aux.children);\n }\n }\n return ans;\n};\n\n/**\n * Merge the leaves in the minimum way to have 'minGroups' number of clusters\n * @param {number} minGroups - Them minimum number of children the first level of the tree should have\n * @return {Cluster}\n */\nCluster.prototype.group = function (minGroups) {\n if (!Number.isInteger(minGroups) || minGroups < 1) throw new RangeError('Number of groups must be a positive integer');\n\n const heap = new Heap(function (a, b) {\n return b.distance - a.distance;\n });\n\n heap.push(this);\n\n while (heap.size() < minGroups) {\n var first = heap.pop();\n if (first.children.length === 0) {\n break;\n }\n first.children.forEach(child => heap.push(child));\n }\n\n var root = new Cluster();\n root.children = heap.toArray();\n root.distance = this.distance;\n\n return root;\n};\n\n/**\n * Traverses the tree depth-first and provide callback to be called on each individual node\n * @param {function} cb - The callback to be called on each node encounter\n * @type {Cluster}\n */\nCluster.prototype.traverse = function (cb) {\n function visit(root, callback) {\n callback(root);\n if (root.children) {\n for (var i = root.children.length - 1; i >= 0; i--) {\n visit(root.children[i], callback);\n }\n }\n }\n visit(this, cb);\n};\n\nmodule.exports = Cluster;\n","'use strict';\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toStr = Object.prototype.toString;\nvar defineProperty = Object.defineProperty;\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nvar isArray = function isArray(arr) {\n\tif (typeof Array.isArray === 'function') {\n\t\treturn Array.isArray(arr);\n\t}\n\n\treturn toStr.call(arr) === '[object Array]';\n};\n\nvar isPlainObject = function isPlainObject(obj) {\n\tif (!obj || toStr.call(obj) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tvar hasOwnConstructor = hasOwn.call(obj, 'constructor');\n\tvar hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n\t\treturn false;\n\t}\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor (key in obj) { /**/ }\n\n\treturn typeof key === 'undefined' || hasOwn.call(obj, key);\n};\n\n// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target\nvar setProperty = function setProperty(target, options) {\n\tif (defineProperty && options.name === '__proto__') {\n\t\tdefineProperty(target, options.name, {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\tvalue: options.newValue,\n\t\t\twritable: true\n\t\t});\n\t} else {\n\t\ttarget[options.name] = options.newValue;\n\t}\n};\n\n// Return undefined instead of __proto__ if '__proto__' is not an own property\nvar getProperty = function getProperty(obj, name) {\n\tif (name === '__proto__') {\n\t\tif (!hasOwn.call(obj, name)) {\n\t\t\treturn void 0;\n\t\t} else if (gOPD) {\n\t\t\t// In early versions of node, obj['__proto__'] is buggy when obj has\n\t\t\t// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.\n\t\t\treturn gOPD(obj, name).value;\n\t\t}\n\t}\n\n\treturn obj[name];\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone;\n\tvar target = arguments[0];\n\tvar i = 1;\n\tvar length = arguments.length;\n\tvar deep = false;\n\n\t// Handle a deep copy situation\n\tif (typeof target === 'boolean') {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t}\n\tif (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n\t\ttarget = {};\n\t}\n\n\tfor (; i < length; ++i) {\n\t\toptions = arguments[i];\n\t\t// Only deal with non-null/undefined values\n\t\tif (options != null) {\n\t\t\t// Extend the base object\n\t\t\tfor (name in options) {\n\t\t\t\tsrc = getProperty(target, name);\n\t\t\t\tcopy = getProperty(options, name);\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif (target !== copy) {\n\t\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\t\tif (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {\n\t\t\t\t\t\tif (copyIsArray) {\n\t\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\t\tclone = src && isArray(src) ? src : [];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: extend(deep, clone, copy) });\n\n\t\t\t\t\t// Don't bring in undefined values\n\t\t\t\t\t} else if (typeof copy !== 'undefined') {\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: copy });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n","import isArray from 'is-any-array';\n\n/**\n * Computes the minimum of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction min(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var min = input[0];\n\n for (var i = 1; i < input.length; i++) {\n if (input[i] < min) min = input[i];\n }\n\n return min;\n}\n\nexport default min;\n","import quickSelectMedian from 'median-quickselect';\nimport isArray from 'is-any-array';\n\n/**\n * Computes the median of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction median(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n return quickSelectMedian(input.slice());\n}\n\nexport default median;\n","const LOOP = 8;\nconst FLOAT_MUL = 1 / 16777216;\nconst sh1 = 15;\nconst sh2 = 18;\nconst sh3 = 11;\nfunction multiply_uint32(n, m) {\n n >>>= 0;\n m >>>= 0;\n const nlo = n & 0xffff;\n const nhi = n - nlo;\n return (((nhi * m) >>> 0) + nlo * m) >>> 0;\n}\nexport default class XSadd {\n constructor(seed = Date.now()) {\n this.state = new Uint32Array(4);\n this.init(seed);\n this.random = this.getFloat.bind(this);\n }\n /**\n * Returns a 32-bit integer r (0 <= r < 2^32)\n */\n getUint32() {\n this.nextState();\n return (this.state[3] + this.state[2]) >>> 0;\n }\n /**\n * Returns a floating point number r (0.0 <= r < 1.0)\n */\n getFloat() {\n return (this.getUint32() >>> 8) * FLOAT_MUL;\n }\n init(seed) {\n if (!Number.isInteger(seed)) {\n throw new TypeError('seed must be an integer');\n }\n this.state[0] = seed;\n this.state[1] = 0;\n this.state[2] = 0;\n this.state[3] = 0;\n for (let i = 1; i < LOOP; i++) {\n this.state[i & 3] ^=\n (i +\n multiply_uint32(1812433253, this.state[(i - 1) & 3] ^ ((this.state[(i - 1) & 3] >>> 30) >>> 0))) >>>\n 0;\n }\n this.periodCertification();\n for (let i = 0; i < LOOP; i++) {\n this.nextState();\n }\n }\n periodCertification() {\n if (this.state[0] === 0 &&\n this.state[1] === 0 &&\n this.state[2] === 0 &&\n this.state[3] === 0) {\n this.state[0] = 88; // X\n this.state[1] = 83; // S\n this.state[2] = 65; // A\n this.state[3] = 68; // D\n }\n }\n nextState() {\n let t = this.state[0];\n t ^= t << sh1;\n t ^= t >>> sh2;\n t ^= this.state[3] << sh3;\n this.state[0] = this.state[1];\n this.state[1] = this.state[2];\n this.state[2] = this.state[3];\n this.state[3] = t;\n }\n}\n","import isArray from 'is-any-array';\n\nfunction _typeof(obj) {\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function (obj) {\n return typeof obj;\n };\n } else {\n _typeof = function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n}\n\n/**\n * Fill an array with sequential numbers\n * @param {Array} [input] - optional destination array (if not provided a new array will be created)\n * @param {object} [options={}]\n * @param {number} [options.from=0] - first value in the array\n * @param {number} [options.to=10] - last value in the array\n * @param {number} [options.size=input.length] - size of the array (if not provided calculated from step)\n * @param {number} [options.step] - if not provided calculated from size\n * @return {Array}\n */\n\nfunction sequentialFill() {\n var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n if (_typeof(input) === 'object' && !isArray(input)) {\n options = input;\n input = [];\n }\n\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n var _options = options,\n _options$from = _options.from,\n from = _options$from === void 0 ? 0 : _options$from,\n _options$to = _options.to,\n to = _options$to === void 0 ? 10 : _options$to,\n _options$size = _options.size,\n size = _options$size === void 0 ? input.length : _options$size,\n step = _options.step;\n\n if (size && step) {\n throw new Error('step is defined by the array size');\n }\n\n if (!size) {\n if (step) {\n size = Math.floor((to - from) / step) + 1;\n } else {\n size = to - from + 1;\n }\n }\n\n if (!step && size) {\n step = (to - from) / (size - 1);\n }\n\n if (Array.isArray(input)) {\n input.length = 0; // only works with normal array\n\n for (var i = 0; i < size; i++) {\n input.push(from);\n from += step;\n }\n } else {\n if (input.length !== size) {\n throw new Error('sequentialFill typed array must have the correct length');\n }\n\n for (var _i = 0; _i < size; _i++) {\n input[_i] = from;\n from += step;\n }\n }\n\n return input;\n}\n\nexport default sequentialFill;\n","import arrayMean from 'ml-array-mean';\nimport isArray from 'is-any-array';\n\n/**\n * Computes the variance of the given values\n * @param {Array} values\n * @param {object} [options]\n * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n.\n * @param {number} [options.mean = arrayMean] - precalculated mean, if any.\n * @return {number}\n */\n\nfunction variance(values) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n if (!isArray(values)) {\n throw new TypeError('input must be an array');\n }\n\n var _options$unbiased = options.unbiased,\n unbiased = _options$unbiased === void 0 ? true : _options$unbiased,\n _options$mean = options.mean,\n mean = _options$mean === void 0 ? arrayMean(values) : _options$mean;\n var sqrError = 0;\n\n for (var i = 0; i < values.length; i++) {\n var x = values[i] - mean;\n sqrError += x * x;\n }\n\n if (unbiased) {\n return sqrError / (values.length - 1);\n } else {\n return sqrError / values.length;\n }\n}\n\nexport default variance;\n","'use strict';\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\n/**\n * Computes the sum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.sum = function sum(values) {\n var sum = 0;\n for (var i = 0; i < values.length; i++) {\n sum += values[i];\n }\n return sum;\n};\n\n/**\n * Computes the maximum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.max = function max(values) {\n var max = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] > max) max = values[i];\n }\n return max;\n};\n\n/**\n * Computes the minimum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.min = function min(values) {\n var min = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] < min) min = values[i];\n }\n return min;\n};\n\n/**\n * Computes the min and max of the given values\n * @param {Array} values\n * @returns {{min: number, max: number}}\n */\nexports.minMax = function minMax(values) {\n var min = values[0];\n var max = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] < min) min = values[i];\n if (values[i] > max) max = values[i];\n }\n return {\n min: min,\n max: max\n };\n};\n\n/**\n * Computes the arithmetic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.arithmeticMean = function arithmeticMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n sum += values[i];\n }\n return sum / l;\n};\n\n/**\n * {@link arithmeticMean}\n */\nexports.mean = exports.arithmeticMean;\n\n/**\n * Computes the geometric mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.geometricMean = function geometricMean(values) {\n var mul = 1;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n mul *= values[i];\n }\n return Math.pow(mul, 1 / l);\n};\n\n/**\n * Computes the mean of the log of the given values\n * If the return value is exponentiated, it gives the same result as the\n * geometric mean.\n * @param {Array} values\n * @returns {number}\n */\nexports.logMean = function logMean(values) {\n var lnsum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n lnsum += Math.log(values[i]);\n }\n return lnsum / l;\n};\n\n/**\n * Computes the weighted grand mean for a list of means and sample sizes\n * @param {Array} means - Mean values for each set of samples\n * @param {Array} samples - Number of original values for each set of samples\n * @returns {number}\n */\nexports.grandMean = function grandMean(means, samples) {\n var sum = 0;\n var n = 0;\n var l = means.length;\n for (var i = 0; i < l; i++) {\n sum += samples[i] * means[i];\n n += samples[i];\n }\n return sum / n;\n};\n\n/**\n * Computes the truncated mean of the given values using a given percentage\n * @param {Array} values\n * @param {number} percent - The percentage of values to keep (range: [0,1])\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.truncatedMean = function truncatedMean(values, percent, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var k = Math.floor(l * percent);\n var sum = 0;\n for (var i = k; i < (l - k); i++) {\n sum += values[i];\n }\n return sum / (l - 2 * k);\n};\n\n/**\n * Computes the harmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.harmonicMean = function harmonicMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (values[i] === 0) {\n throw new RangeError('value at index ' + i + 'is zero');\n }\n sum += 1 / values[i];\n }\n return l / sum;\n};\n\n/**\n * Computes the contraharmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.contraHarmonicMean = function contraHarmonicMean(values) {\n var r1 = 0;\n var r2 = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n r1 += values[i] * values[i];\n r2 += values[i];\n }\n if (r2 < 0) {\n throw new RangeError('sum of values is negative');\n }\n return r1 / r2;\n};\n\n/**\n * Computes the median of the given values\n * @param {Array} values\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.median = function median(values, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return (values[half - 1] + values[half]) * 0.5;\n } else {\n return values[half];\n }\n};\n\n/**\n * Computes the variance of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.variance = function variance(values, unbiased) {\n if (unbiased === undefined) unbiased = true;\n var theMean = exports.mean(values);\n var theVariance = 0;\n var l = values.length;\n\n for (var i = 0; i < l; i++) {\n var x = values[i] - theMean;\n theVariance += x * x;\n }\n\n if (unbiased) {\n return theVariance / (l - 1);\n } else {\n return theVariance / l;\n }\n};\n\n/**\n * Computes the standard deviation of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.standardDeviation = function standardDeviation(values, unbiased) {\n return Math.sqrt(exports.variance(values, unbiased));\n};\n\nexports.standardError = function standardError(values) {\n return exports.standardDeviation(values) / Math.sqrt(values.length);\n};\n\n/**\n * IEEE Transactions on biomedical engineering, vol. 52, no. 1, january 2005, p. 76-\n * Calculate the standard deviation via the Median of the absolute deviation\n * The formula for the standard deviation only holds for Gaussian random variables.\n * @returns {{mean: number, stdev: number}}\n */\nexports.robustMeanAndStdev = function robustMeanAndStdev(y) {\n var mean = 0, stdev = 0;\n var length = y.length, i = 0;\n for (i = 0; i < length; i++) {\n mean += y[i];\n }\n mean /= length;\n var averageDeviations = new Array(length);\n for (i = 0; i < length; i++)\n averageDeviations[i] = Math.abs(y[i] - mean);\n averageDeviations.sort(compareNumbers);\n if (length % 2 === 1) {\n stdev = averageDeviations[(length - 1) / 2] / 0.6745;\n } else {\n stdev = 0.5 * (averageDeviations[length / 2] + averageDeviations[length / 2 - 1]) / 0.6745;\n }\n\n return {\n mean: mean,\n stdev: stdev\n };\n};\n\nexports.quartiles = function quartiles(values, alreadySorted) {\n if (typeof (alreadySorted) === 'undefined') alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n\n var quart = values.length / 4;\n var q1 = values[Math.ceil(quart) - 1];\n var q2 = exports.median(values, true);\n var q3 = values[Math.ceil(quart * 3) - 1];\n\n return {q1: q1, q2: q2, q3: q3};\n};\n\nexports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) {\n return Math.sqrt(exports.pooledVariance(samples, unbiased));\n};\n\nexports.pooledVariance = function pooledVariance(samples, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var sum = 0;\n var length = 0, l = samples.length;\n for (var i = 0; i < l; i++) {\n var values = samples[i];\n var vari = exports.variance(values);\n\n sum += (values.length - 1) * vari;\n\n if (unbiased)\n length += values.length - 1;\n else\n length += values.length;\n }\n return sum / length;\n};\n\nexports.mode = function mode(values) {\n var l = values.length,\n itemCount = new Array(l),\n i;\n for (i = 0; i < l; i++) {\n itemCount[i] = 0;\n }\n var itemArray = new Array(l);\n var count = 0;\n\n for (i = 0; i < l; i++) {\n var index = itemArray.indexOf(values[i]);\n if (index >= 0)\n itemCount[index]++;\n else {\n itemArray[count] = values[i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (i = 0; i < count; i++) {\n if (itemCount[i] > maxValue) {\n maxValue = itemCount[i];\n maxIndex = i;\n }\n }\n\n return itemArray[maxIndex];\n};\n\nexports.covariance = function covariance(vector1, vector2, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var mean1 = exports.mean(vector1);\n var mean2 = exports.mean(vector2);\n\n if (vector1.length !== vector2.length)\n throw 'Vectors do not have the same dimensions';\n\n var cov = 0, l = vector1.length;\n for (var i = 0; i < l; i++) {\n var x = vector1[i] - mean1;\n var y = vector2[i] - mean2;\n cov += x * y;\n }\n\n if (unbiased)\n return cov / (l - 1);\n else\n return cov / l;\n};\n\nexports.skewness = function skewness(values, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n\n var s2 = 0, s3 = 0, l = values.length;\n for (var i = 0; i < l; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n var m2 = s2 / l;\n var m3 = s3 / l;\n\n var g = m3 / (Math.pow(m2, 3 / 2.0));\n if (unbiased) {\n var a = Math.sqrt(l * (l - 1));\n var b = l - 2;\n return (a / b) * g;\n } else {\n return g;\n }\n};\n\nexports.kurtosis = function kurtosis(values, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n var n = values.length, s2 = 0, s4 = 0;\n\n for (var i = 0; i < n; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n\n return a * b - 3 * c;\n } else {\n return m4 / (m2 * m2) - 3;\n }\n};\n\nexports.entropy = function entropy(values, eps) {\n if (typeof (eps) === 'undefined') eps = 0;\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * Math.log(values[i] + eps);\n return -sum;\n};\n\nexports.weightedMean = function weightedMean(values, weights) {\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * weights[i];\n return sum;\n};\n\nexports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) {\n return Math.sqrt(exports.weightedVariance(values, weights));\n};\n\nexports.weightedVariance = function weightedVariance(values, weights) {\n var theMean = exports.weightedMean(values, weights);\n var vari = 0, l = values.length;\n var a = 0, b = 0;\n\n for (var i = 0; i < l; i++) {\n var z = values[i] - theMean;\n var w = weights[i];\n\n vari += w * (z * z);\n b += w;\n a += w * w;\n }\n\n return vari * (b / (b * b - a));\n};\n\nexports.center = function center(values, inPlace) {\n if (typeof (inPlace) === 'undefined') inPlace = false;\n\n var result = values;\n if (!inPlace)\n result = [].concat(values);\n\n var theMean = exports.mean(result), l = result.length;\n for (var i = 0; i < l; i++)\n result[i] -= theMean;\n};\n\nexports.standardize = function standardize(values, standardDev, inPlace) {\n if (typeof (standardDev) === 'undefined') standardDev = exports.standardDeviation(values);\n if (typeof (inPlace) === 'undefined') inPlace = false;\n var l = values.length;\n var result = inPlace ? values : new Array(l);\n for (var i = 0; i < l; i++)\n result[i] = values[i] / standardDev;\n return result;\n};\n\nexports.cumulativeSum = function cumulativeSum(array) {\n var l = array.length;\n var result = new Array(l);\n result[0] = array[0];\n for (var i = 1; i < l; i++)\n result[i] = result[i - 1] + array[i];\n return result;\n};\n","'use strict';\n\nconst Cluster = require('./Cluster');\nconst util = require('util');\n\nfunction ClusterLeaf(index) {\n Cluster.call(this);\n this.index = index;\n this.distance = 0;\n this.children = [];\n}\n\nutil.inherits(ClusterLeaf, Cluster);\n\nmodule.exports = ClusterLeaf;\n","'use strict';\n\n\n/**\n * Computes a distance/similarity matrix given an array of data and a distance/similarity function.\n * @param {Array} data An array of data\n * @param {function} distanceFn A function that accepts two arguments and computes a distance/similarity between them\n * @return {Array} The similarity matrix. The similarity matrix is square and has a size equal to the length of\n * the data array\n */\nfunction distanceMatrix(data, distanceFn) {\n const length = data.length;\n let result = Array.from({length}).map(() => Array.from({length}));\n\n // Compute upper distance matrix\n for (let i = 0; i < length; i++) {\n for (let j = 0; j <= i; j++) {\n result[i][j] = distanceFn(data[i], data[j]);\n }\n }\n\n // Copy to lower distance matrix\n for (let i = 0; i < length; i++) {\n for (let j = i + 1; j < length; j++) {\n result[i][j] = result[j][i];\n }\n }\n\n return result;\n}\n\nmodule.exports = distanceMatrix;\n","/**\n * Constructs a confusion matrix\n * @class ConfusionMatrix\n * @example\n * const CM = new ConfusionMatrix([[13, 2], [10, 5]], ['cat', 'dog'])\n * @param {Array>} matrix - The confusion matrix, a 2D Array. Rows represent the actual label and columns\n * the predicted label.\n * @param {Array} labels - Labels of the confusion matrix, a 1D Array\n */\nclass ConfusionMatrix {\n constructor(matrix, labels) {\n if (matrix.length !== matrix[0].length) {\n throw new Error('Confusion matrix must be square');\n }\n if (labels.length !== matrix.length) {\n throw new Error('Confusion matrix and labels should have the same length');\n }\n this.labels = labels;\n this.matrix = matrix;\n }\n\n\n /**\n * Construct confusion matrix from the predicted and actual labels (classes). Be sure to provide the arguments in\n * the correct order!\n * @param {Array} actual - The predicted labels of the classification\n * @param {Array} predicted - The actual labels of the classification. Has to be of same length as\n * predicted.\n * @param {object} [options] - Additional options\n * @param {Array} [options.labels] - The list of labels that should be used. If not provided the distinct set\n * of labels present in predicted and actual is used. Labels are compared using the strict equality operator\n * '==='\n * @return {ConfusionMatrix} - Confusion matrix\n */\n static fromLabels(actual, predicted, options = {}) {\n if (predicted.length !== actual.length) {\n throw new Error('predicted and actual must have the same length');\n }\n let distinctLabels;\n if (options.labels) {\n distinctLabels = new Set(options.labels);\n } else {\n distinctLabels = new Set([...actual, ...predicted]);\n }\n distinctLabels = Array.from(distinctLabels);\n if (options.sort) {\n distinctLabels.sort(options.sort);\n }\n\n // Create confusion matrix and fill with 0's\n const matrix = Array.from({length: distinctLabels.length});\n for (let i = 0; i < matrix.length; i++) {\n matrix[i] = new Array(matrix.length);\n matrix[i].fill(0);\n }\n\n for (let i = 0; i < predicted.length; i++) {\n const actualIdx = distinctLabels.indexOf(actual[i]);\n const predictedIdx = distinctLabels.indexOf(predicted[i]);\n if (actualIdx >= 0 && predictedIdx >= 0) {\n matrix[actualIdx][predictedIdx]++;\n }\n }\n\n return new ConfusionMatrix(matrix, distinctLabels);\n }\n\n /**\n * Get the confusion matrix\n * @return {Array >}\n */\n getMatrix() {\n return this.matrix;\n }\n\n getLabels() {\n return this.labels;\n }\n\n /**\n * Get the total number of samples\n * @return {number}\n */\n getTotalCount() {\n let predicted = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n for (var j = 0; j < this.matrix.length; j++) {\n predicted += this.matrix[i][j];\n }\n }\n return predicted;\n }\n\n /**\n * Get the total number of true predictions\n * @return {number}\n */\n getTrueCount() {\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n count += this.matrix[i][i];\n }\n return count;\n }\n\n /**\n * Get the total number of false predictions.\n * @return {number}\n */\n getFalseCount() {\n return this.getTotalCount() - this.getTrueCount();\n }\n\n /**\n * Get the number of true positive predictions.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getTruePositiveCount(label) {\n const index = this.getIndex(label);\n return this.matrix[index][index];\n }\n\n /**\n * Get the number of true negative predictions\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getTrueNegativeCount(label) {\n const index = this.getIndex(label);\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n for (var j = 0; j < this.matrix.length; j++) {\n if (i !== index && j !== index) {\n count += this.matrix[i][j];\n }\n }\n }\n return count;\n }\n\n /**\n * Get the number of false positive predictions.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalsePositiveCount(label) {\n const index = this.getIndex(label);\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n if (i !== index) {\n count += this.matrix[i][index];\n }\n }\n return count;\n }\n\n /**\n * Get the number of false negative predictions.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseNegativeCount(label) {\n const index = this.getIndex(label);\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n if (i !== index) {\n count += this.matrix[index][i];\n }\n }\n return count;\n }\n\n /**\n * Get the number of real positive samples.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getPositiveCount(label) {\n return this.getTruePositiveCount(label) + this.getFalseNegativeCount(label);\n }\n\n /**\n * Get the number of real negative samples.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getNegativeCount(label) {\n return this.getTrueNegativeCount(label) + this.getFalsePositiveCount(label);\n }\n\n /**\n * Get the index in the confusion matrix that corresponds to the given label\n * @param {any} label - The label to search for\n * @throws if the label is not found\n * @return {number}\n */\n getIndex(label) {\n const index = this.labels.indexOf(label);\n if (index === -1) throw new Error('The label does not exist');\n return index;\n }\n\n /**\n * Get the true positive rate a.k.a. sensitivity. Computes the ratio between the number of true positive predictions and the total number of positive samples.\n * {@link https://en.wikipedia.org/wiki/Sensitivity_and_specificity}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number} - The true positive rate [0-1]\n */\n getTruePositiveRate(label) {\n return this.getTruePositiveCount(label) / this.getPositiveCount(label);\n }\n\n /**\n * Get the true negative rate a.k.a. specificity. Computes the ration between the number of true negative predictions and the total number of negative samples.\n * {@link https://en.wikipedia.org/wiki/Sensitivity_and_specificity}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getTrueNegativeRate(label) {\n return this.getTrueNegativeCount(label) / this.getNegativeCount(label);\n }\n\n /**\n * Get the positive predictive value a.k.a. precision. Computes TP / (TP + FP)\n * {@link https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getPositivePredictiveValue(label) {\n const TP = this.getTruePositiveCount(label);\n return TP / (TP + this.getFalsePositiveCount(label));\n }\n\n /**\n * Negative predictive value\n * {@link https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getNegativePredictiveValue(label) {\n const TN = this.getTrueNegativeCount(label);\n return TN / (TN + this.getFalseNegativeCount(label));\n }\n\n /**\n * False negative rate a.k.a. miss rate.\n * {@link https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#False_positive_and_false_negative_rates}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseNegativeRate(label) {\n return 1 - this.getTruePositiveRate(label);\n }\n\n /**\n * False positive rate a.k.a. fall-out rate.\n * {@link https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#False_positive_and_false_negative_rates}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalsePositiveRate(label) {\n return 1 - this.getTrueNegativeRate(label);\n }\n\n /**\n * False discovery rate (FDR)\n * {@link https://en.wikipedia.org/wiki/False_discovery_rate}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseDiscoveryRate(label) {\n const FP = this.getFalsePositiveCount(label);\n return FP / (FP + this.getTruePositiveCount(label));\n }\n\n /**\n * False omission rate (FOR)\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseOmissionRate(label) {\n const FN = this.getFalseNegativeCount(label);\n return FN / (FN + this.getTruePositiveCount(label));\n }\n\n /**\n * F1 score\n * {@link https://en.wikipedia.org/wiki/F1_score}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getF1Score(label) {\n const TP = this.getTruePositiveCount(label);\n return 2 * TP / (2 * TP + this.getFalsePositiveCount(label) + this.getFalseNegativeCount(label));\n }\n\n /**\n * Matthews correlation coefficient (MCC)\n * {@link https://en.wikipedia.org/wiki/Matthews_correlation_coefficient}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getMatthewsCorrelationCoefficient(label) {\n const TP = this.getTruePositiveCount(label);\n const TN = this.getTrueNegativeCount(label);\n const FP = this.getFalsePositiveCount(label);\n const FN = this.getFalseNegativeCount(label);\n return (TP * TN - FP * FN) / Math.sqrt((TP + FP) * (TP + FN) * (TN + FP) * (TN + FN));\n }\n\n /**\n * Informedness\n * {@link https://en.wikipedia.org/wiki/Youden%27s_J_statistic}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getInformedness(label) {\n return this.getTruePositiveRate(label) + this.getTrueNegativeRate(label) - 1;\n }\n\n /**\n * Markedness\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getMarkedness(label) {\n return this.getPositivePredictiveValue(label) + this.getNegativePredictiveValue(label) - 1;\n }\n\n /**\n * Get the confusion table.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {Array >} - The 2x2 confusion table. [[TP, FN], [FP, TN]]\n */\n getConfusionTable(label) {\n return [\n [\n this.getTruePositiveCount(label),\n this.getFalseNegativeCount(label)\n ],\n [\n this.getFalsePositiveCount(label),\n this.getTrueNegativeCount(label)\n ]\n ];\n }\n\n /**\n * Get total accuracy.\n * @return {number} - The ratio between the number of true predictions and total number of classifications ([0-1])\n */\n getAccuracy() {\n let correct = 0;\n let incorrect = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n for (var j = 0; j < this.matrix.length; j++) {\n if (i === j) correct += this.matrix[i][j];\n else incorrect += this.matrix[i][j];\n }\n }\n return correct / (correct + incorrect);\n }\n\n\n /**\n * Returns the element in the confusion matrix that corresponds to the given actual and predicted labels.\n * @param {any} actual - The true label\n * @param {any} predicted - The predicted label\n * @return {number} - The element in the confusion matrix\n */\n getCount(actual, predicted) {\n const actualIndex = this.getIndex(actual);\n const predictedIndex = this.getIndex(predicted);\n return this.matrix[actualIndex][predictedIndex];\n }\n\n /**\n * Compute the general prediction accuracy\n * @deprecated Use getAccuracy\n * @return {number} - The prediction accuracy ([0-1]\n */\n get accuracy() {\n return this.getAccuracy();\n }\n\n /**\n * Compute the number of predicted observations\n * @deprecated Use getTotalCount\n * @return {number}\n */\n get total() {\n return this.getTotalCount();\n }\n}\n\nmodule.exports = ConfusionMatrix;\n","'use strict';\n\nvar Matrix = require('ml-matrix').Matrix;\n\nvar Utils = require('./utils');\nconst ACTIVATION_FUNCTIONS = require('./activationFunctions');\n\nclass Layer {\n /**\n * @private\n * Create a new layer with the given options\n * @param {object} options\n * @param {number} [options.inputSize] - Number of conections that enter the neurons.\n * @param {number} [options.outputSize] - Number of conections that leave the neurons.\n * @param {number} [options.regularization] - Regularization parameter.\n * @param {number} [options.epsilon] - Learning rate parameter.\n * @param {string} [options.activation] - Activation function parameter from the FeedForwardNeuralNetwork class.\n * @param {number} [options.activationParam] - Activation parameter if needed.\n */\n constructor(options) {\n this.inputSize = options.inputSize;\n this.outputSize = options.outputSize;\n this.regularization = options.regularization;\n this.epsilon = options.epsilon;\n this.activation = options.activation;\n this.activationParam = options.activationParam;\n\n var selectedFunction = ACTIVATION_FUNCTIONS[options.activation];\n var params = selectedFunction.activation.length;\n\n var actFunction = params > 1 ? val => selectedFunction.activation(val, options.activationParam) : selectedFunction.activation;\n var derFunction = params > 1 ? val => selectedFunction.derivate(val, options.activationParam) : selectedFunction.derivate;\n\n this.activationFunction = function (i, j) {\n this[i][j] = actFunction(this[i][j]);\n };\n this.derivate = function (i, j) {\n this[i][j] = derFunction(this[i][j]);\n };\n\n if (options.model) {\n // load model\n this.W = Matrix.checkMatrix(options.W);\n this.b = Matrix.checkMatrix(options.b);\n\n } else {\n // default constructor\n\n this.W = Matrix.rand(this.inputSize, this.outputSize);\n this.b = Matrix.zeros(1, this.outputSize);\n\n this.W.apply(function (i, j) {\n this[i][j] /= Math.sqrt(options.inputSize);\n });\n }\n }\n\n /**\n * @private\n * propagate the given input through the current layer.\n * @param {Matrix} X - input.\n * @return {Matrix} output at the current layer.\n */\n forward(X) {\n var z = X.mmul(this.W).addRowVector(this.b);\n z.apply(this.activationFunction);\n this.a = z.clone();\n return z;\n }\n\n /**\n * @private\n * apply backpropagation algorithm at the current layer\n * @param {Matrix} delta - delta values estimated at the following layer.\n * @param {Matrix} a - 'a' values from the following layer.\n * @return {Matrix} the new delta values for the next layer.\n */\n backpropagation(delta, a) {\n this.dW = a.transposeView().mmul(delta);\n this.db = Utils.sumCol(delta);\n\n var aCopy = a.clone();\n return delta.mmul(this.W.transposeView()).mul(aCopy.apply(this.derivate));\n }\n\n /**\n * @private\n * Function that updates the weights at the current layer with the derivatives.\n */\n update() {\n this.dW.add(this.W.clone().mul(this.regularization));\n this.W.add(this.dW.mul(-this.epsilon));\n this.b.add(this.db.mul(-this.epsilon));\n }\n\n /**\n * @private\n * Export the current layer to JSON.\n * @return {object} model\n */\n toJSON() {\n return {\n model: 'Layer',\n inputSize: this.inputSize,\n outputSize: this.outputSize,\n regularization: this.regularization,\n epsilon: this.epsilon,\n activation: this.activation,\n W: this.W,\n b: this.b\n };\n }\n\n /**\n * @private\n * Creates a new Layer with the given model.\n * @param {object} model\n * @return {Layer}\n */\n static load(model) {\n if (model.model !== 'Layer') {\n throw new RangeError('the current model is not a Layer model');\n }\n return new Layer(model);\n }\n\n}\n\nmodule.exports = Layer;\n","'use strict';\n\nvar Matrix = require('ml-matrix').Matrix;\n\n/**\n * @private\n * Retrieves the sum at each row of the given matrix.\n * @param {Matrix} matrix\n * @return {Matrix}\n */\nfunction sumRow(matrix) {\n var sum = Matrix.zeros(matrix.rows, 1);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum[i][0] += matrix[i][j];\n }\n }\n return sum;\n}\n\n/**\n * @private\n * Retrieves the sum at each column of the given matrix.\n * @param {Matrix} matrix\n * @return {Matrix}\n */\nfunction sumCol(matrix) {\n var sum = Matrix.zeros(1, matrix.columns);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum[0][j] += matrix[i][j];\n }\n }\n return sum;\n}\n\n/**\n * @private\n * Method that given an array of labels(predictions), returns two dictionaries, one to transform from labels to\n * numbers and other in the reverse way\n * @param {Array} array\n * @return {object}\n */\nfunction dictOutputs(array) {\n var inputs = {};\n var outputs = {};\n var index = 0;\n for (var i = 0; i < array.length; i += 1) {\n if (inputs[array[i]] === undefined) {\n inputs[array[i]] = index;\n outputs[index] = array[i];\n index++;\n }\n }\n\n return {\n inputs: inputs,\n outputs: outputs\n };\n}\n\nmodule.exports = {\n dictOutputs: dictOutputs,\n sumCol: sumCol,\n sumRow: sumRow\n};\n","'use strict';\n\nfunction logistic(val) {\n return 1 / (1 + Math.exp(-val));\n}\n\nfunction expELU(val, param) {\n return val < 0 ? param * (Math.exp(val) - 1) : val;\n}\n\nfunction softExponential(val, param) {\n if (param < 0) {\n return -Math.log(1 - param * (val + param)) / param;\n }\n if (param > 0) {\n return ((Math.exp(param * val) - 1) / param) + param;\n }\n return val;\n}\n\nfunction softExponentialPrime(val, param) {\n if (param < 0) {\n return 1 / (1 - param * (param + val));\n } else {\n return Math.exp(param * val);\n }\n}\n\nconst ACTIVATION_FUNCTIONS = {\n tanh: {\n activation: Math.tanh,\n derivate: val => 1 - (val * val)\n },\n identity: {\n activation: val => val,\n derivate: () => 1\n },\n logistic: {\n activation: logistic,\n derivate: val => logistic(val) * (1 - logistic(val))\n },\n arctan: {\n activation: Math.atan,\n derivate: val => 1 / (val * val + 1)\n },\n softsign: {\n activation: val => val / (1 + Math.abs(val)),\n derivate: val => 1 / ((1 + Math.abs(val)) * (1 + Math.abs(val)))\n },\n relu: {\n activation: val => val < 0 ? 0 : val,\n derivate: val => val < 0 ? 0 : 1\n },\n softplus: {\n activation: val => Math.log(1 + Math.exp(val)),\n derivate: val => 1 / (1 + Math.exp(-val))\n },\n bent: {\n activation: val => ((Math.sqrt(val * val + 1) - 1) / 2) + val,\n derivate: val => (val / (2 * Math.sqrt(val * val + 1))) + 1\n },\n sinusoid: {\n activation: Math.sin,\n derivate: Math.cos\n },\n sinc: {\n activation: val => val === 0 ? 1 : Math.sin(val) / val,\n derivate: val => val === 0 ? 0 : (Math.cos(val) / val) - (Math.sin(val) / (val * val))\n },\n gaussian: {\n activation: val => Math.exp(-(val * val)),\n derivate: val => -2 * val * Math.exp(-(val * val))\n },\n 'parametric-relu': {\n activation: (val, param) => val < 0 ? param * val : val,\n derivate: (val, param) => val < 0 ? param : 1\n },\n 'exponential-elu': {\n activation: expELU,\n derivate: (val, param) => val < 0 ? expELU(val, param) + param : 1\n },\n 'soft-exponential': {\n activation: softExponential,\n derivate: softExponentialPrime\n }\n};\n\nmodule.exports = ACTIVATION_FUNCTIONS;\n","function NodeSquare(x, y, weights, som) {\n this.x = x;\n this.y = y;\n this.weights = weights;\n this.som = som;\n this.neighbors = {};\n}\n\nNodeSquare.prototype.adjustWeights = function adjustWeights(target, learningRate, influence) {\n for (var i = 0, ii = this.weights.length; i < ii; i++) {\n this.weights[i] += learningRate * influence * (target[i] - this.weights[i]);\n }\n};\n\nNodeSquare.prototype.getDistance = function getDistance(otherNode) {\n return Math.max(Math.abs(this.x - otherNode.x), Math.abs(this.y - otherNode.y));\n};\n\nNodeSquare.prototype.getDistanceTorus = function getDistanceTorus(otherNode) {\n var distX = Math.abs(this.x - otherNode.x),\n distY = Math.abs(this.y - otherNode.y);\n return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY));\n};\n\nNodeSquare.prototype.getNeighbors = function getNeighbors(xy) {\n if (!this.neighbors[xy]) {\n this.neighbors[xy] = new Array(2);\n\n // left or bottom neighbor\n var v;\n if (this[xy] > 0) {\n v = this[xy] - 1;\n } else if (this.som.torus) {\n v = this.som.gridDim[xy] - 1\n }\n if (typeof v !== 'undefined') {\n var x, y;\n if (xy === 'x') {\n x = v;\n y = this.y;\n } else {\n x = this.x;\n y = v;\n }\n this.neighbors[xy][0] = this.som.nodes[x][y];\n }\n\n // top or right neighbor\n var w;\n if (this[xy] < (this.som.gridDim[xy] - 1)) {\n w = this[xy] + 1;\n } else if (this.som.torus) {\n w = 0;\n }\n if (typeof w !== 'undefined') {\n if (xy === 'x') {\n x = w;\n y = this.y;\n } else {\n x = this.x;\n y = w;\n }\n this.neighbors[xy][1] = this.som.nodes[x][y];\n }\n }\n return this.neighbors[xy];\n};\n\nNodeSquare.prototype.getPos = function getPos(xy, element) {\n var neighbors = this.getNeighbors(xy),\n distance = this.som.distance,\n bestNeighbor,\n direction;\n if(neighbors[0]) {\n if (neighbors[1]) {\n var dist1 = distance(element, neighbors[0].weights),\n dist2 = distance(element, neighbors[1].weights);\n if(dist1 < dist2) {\n bestNeighbor = neighbors[0];\n direction = -1;\n } else {\n bestNeighbor = neighbors[1];\n direction = 1;\n }\n } else {\n bestNeighbor = neighbors[0];\n direction = -1;\n }\n } else {\n bestNeighbor = neighbors[1];\n direction = 1;\n }\n var simA = 1 - distance(element, this.weights),\n simB = 1 - distance(element, bestNeighbor.weights);\n var factor = ((simA - simB) / (2 - simA - simB));\n return 0.5 + 0.5 * factor * direction;\n};\n\nNodeSquare.prototype.getPosition = function getPosition(element) {\n return [\n this.getPos('x', element),\n this.getPos('y', element)\n ];\n};\n\nmodule.exports = NodeSquare;","'use strict';\n\nexports.distance = require('./distances');\nexports.similarity = require('./similarities');","'use strict';\n\nmodule.exports = function czekanowskiSimilarity(a, b) {\n var up = 0;\n var down = 0;\n for (var i = 0; i < a.length; i++) {\n up += Math.min(a[i], b[i]);\n down += a[i] + b[i];\n }\n return 2 * up / down;\n};\n","module.exports = function dice(a, b) {\n var ii = a.length,\n p = 0,\n q1 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * a[i];\n q1 += b[i] * b[i];\n q2 += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return q2 / (p + q1);\n};\n","module.exports = function intersection(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.min(a[i], b[i]);\n }\n return 1 - ans;\n};\n","module.exports = function jaccard(a, b) {\n var ii = a.length,\n p1 = 0,\n p2 = 0,\n q1 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p1 += a[i] * b[i];\n p2 += a[i] * a[i];\n q1 += b[i] * b[i];\n q2 += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return q2 / (p2 + q1 - p1);\n};\n","module.exports = function kulczynski(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += Math.min(a[i],b[i]);\n }\n return up / down;\n};\n","module.exports = function motyka(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.min(a[i], b[i]);\n down += a[i] + b[i];\n }\n return 1 - (up / down);\n};\n","module.exports = function squaredChord(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i]));\n }\n return ans;\n};\n","module.exports = function tanimoto(a, b, bitvector) {\n if (bitvector) {\n var inter = 0,\n union = 0;\n for (var j = 0; j < a.length; j++) {\n inter += a[j] && b[j];\n union += a[j] || b[j];\n }\n if (union === 0)\n return 1;\n return inter / union;\n }\n else {\n var ii = a.length,\n p = 0,\n q = 0,\n m = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i];\n q += b[i];\n m += Math.min(a[i],b[i]);\n }\n return 1 - (p + q - 2 * m) / (p + q - m);\n }\n};\n","module.exports = function cosine(a, b) {\n var ii = a.length,\n p = 0,\n p2 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * b[i];\n p2 += a[i] * a[i];\n q2 += b[i] * b[i];\n }\n return p / (Math.sqrt(p2) * Math.sqrt(q2));\n};\n","'use strict';\n\nvar extend = require('extend');\n\nvar defaultOptions = {\n size: 1,\n value: 0\n};\n\n/**\n * Case when the entry is an array\n * @param data\n * @param options\n * @returns {Array}\n */\nfunction arrayCase(data, options) {\n var len = data.length;\n if (typeof options.size === 'number')\n options.size = [options.size, options.size];\n\n var cond = len + options.size[0] + options.size[1];\n\n var output;\n if (options.output) {\n if (options.output.length !== cond)\n throw new RangeError('Wrong output size');\n output = options.output;\n }\n else\n output = new Array(cond);\n\n var i;\n\n // circular option\n if (options.value === 'circular') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[((len - (options.size[0] % len)) + i) % len];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[(i - options.size[0]) % len];\n }\n }\n\n // replicate option\n else if (options.value === 'replicate') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[0];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[len - 1];\n }\n }\n\n // symmetric option\n else if (options.value === 'symmetric') {\n if ((options.size[0] > len) || (options.size[1] > len))\n throw new RangeError('expanded value should not be bigger than the data length');\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[options.size[0] - 1 - i];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[2*len + options.size[0] - i - 1];\n }\n }\n\n // default option\n else {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = options.value;\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = options.value;\n }\n }\n\n return output;\n}\n\n/**\n * Case when the entry is a matrix\n * @param data\n * @param options\n * @returns {Array}\n */\nfunction matrixCase(data, options) {\n var row = data.length;\n var col = data[0].length;\n if (options.size[0] === undefined)\n options.size = [options.size, options.size, options.size, options.size];\n throw new Error('matrix not supported yet, sorry');\n}\n\n/**\n * Pads and array\n * @param {Array } data\n * @param {object} options\n */\nfunction padArray (data, options) {\n options = extend({}, defaultOptions, options);\n\n if (Array.isArray(data)) {\n if (Array.isArray(data[0]))\n return matrixCase(data, options);\n else\n return arrayCase(data, options);\n }\n else\n throw new TypeError('data should be an array');\n}\n\nmodule.exports = padArray;\n","export default function maybeToPrecision(value, digits) {\n if (value < 0) {\n value = 0 - value;\n if (typeof digits === 'number') {\n return '- ' + value.toPrecision(digits);\n } else {\n return '- ' + value.toString();\n }\n } else {\n if (typeof digits === 'number') {\n return value.toPrecision(digits);\n } else {\n return value.toString();\n }\n }\n}\n","export default function checkArraySize(x, y) {\n if (!Array.isArray(x) || !Array.isArray(y)) {\n throw new TypeError('x and y must be arrays');\n }\n if (x.length !== y.length) {\n throw new RangeError('x and y arrays must have the same length');\n }\n}\n","export {default as maybeToPrecision} from './maybeToPrecision';\nexport {default as checkArrayLength} from './checkArrayLength';\n\nexport default class BaseRegression {\n constructor() {\n if (new.target === BaseRegression) {\n throw new Error('BaseRegression must be subclassed');\n }\n }\n\n predict(x) {\n if (typeof x === 'number') {\n return this._predict(x);\n } else if (Array.isArray(x)) {\n const y = new Array(x.length);\n for (let i = 0; i < x.length; i++) {\n y[i] = this._predict(x[i]);\n }\n return y;\n } else {\n throw new TypeError('x must be a number or array');\n }\n }\n\n _predict() {\n throw new Error('_predict must be implemented');\n }\n\n train() {\n //Do nothing for this package\n }\n\n toString() {\n return '';\n }\n\n toLaTeX() {\n return '';\n }\n\n /**\n * Return the correlation coefficient of determination (r) and chi-square.\n * @param {Array} x\n * @param {Array} y\n * @return {object}\n */\n score(x, y) {\n if (!Array.isArray(x) || !Array.isArray(y) || x.length !== y.length) {\n throw new Error('x and y must be arrays of the same length');\n }\n\n const n = x.length;\n const y2 = new Array(n);\n for (let i = 0; i < n; i++) {\n y2[i] = this._predict(x[i]);\n }\n\n let xSum = 0;\n let ySum = 0;\n let chi2 = 0;\n let rmsd = 0;\n let xSquared = 0;\n let ySquared = 0;\n let xY = 0;\n for (let i = 0; i < n; i++) {\n xSum += y2[i];\n ySum += y[i];\n xSquared += y2[i] * y2[i];\n ySquared += y[i] * y[i];\n xY += y2[i] * y[i];\n if (y[i] !== 0) {\n chi2 += (y[i] - y2[i]) * (y[i] - y2[i]) / y[i];\n }\n rmsd = (y[i] - y2[i]) * (y[i] - y2[i]);\n }\n\n const r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum));\n\n return {\n r: r,\n r2: r * r,\n chi2: chi2,\n rmsd: rmsd * rmsd / n\n };\n }\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\n\nexport default class SimpleLinearRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) {\n this.slope = y.slope;\n this.intercept = y.intercept;\n this.coefficients = [y.intercept, y.slope];\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n toJSON() {\n return {\n name: 'simpleLinearRegression',\n slope: this.slope,\n intercept: this.intercept\n };\n }\n\n _predict(x) {\n return this.slope * x + this.intercept;\n }\n\n computeX(y) {\n return (y - this.intercept) / this.slope;\n }\n\n toString(precision) {\n let result = 'f(x) = ';\n if (this.slope !== 0) {\n const xFactor = maybeToPrecision(this.slope, precision);\n result += (xFactor === '1' ? '' : xFactor + ' * ') + 'x';\n if (this.intercept) {\n const absIntercept = Math.abs(this.intercept);\n const operator = absIntercept === this.intercept ? '+' : '-';\n result += ` ${operator} ${maybeToPrecision(absIntercept, precision)}`;\n }\n } else {\n result += maybeToPrecision(this.intercept, precision);\n }\n return result;\n }\n\n toLaTeX(precision) {\n return this.toString(precision);\n }\n\n static load(json) {\n if (json.name !== 'simpleLinearRegression') {\n throw new TypeError('not a SLR model');\n }\n return new SimpleLinearRegression(true, json);\n }\n}\n\nfunction regress(slr, x, y) {\n const n = x.length;\n let xSum = 0;\n let ySum = 0;\n\n let xSquared = 0;\n let xY = 0;\n\n for (let i = 0; i < n; i++) {\n xSum += x[i];\n ySum += y[i];\n xSquared += x[i] * x[i];\n xY += x[i] * y[i];\n }\n\n const numerator = (n * xY - xSum * ySum);\n slr.slope = numerator / (n * xSquared - xSum * xSum);\n slr.intercept = (1 / n) * ySum - slr.slope * (1 / n) * xSum;\n slr.coefficients = [slr.intercept, slr.slope];\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport Matrix, {solve} from 'ml-matrix';\n\nexport default class PolynomialRegression extends BaseRegression {\n constructor(x, y, degree) {\n super();\n if (x === true) {\n this.degree = y.degree;\n this.powers = y.powers;\n this.coefficients = y.coefficients;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y, degree);\n }\n }\n\n _predict(x) {\n let y = 0;\n for (let k = 0; k < this.powers.length; k++) {\n y += this.coefficients[k] * Math.pow(x, this.powers[k]);\n }\n return y;\n }\n\n toJSON() {\n return {\n name: 'polynomialRegression',\n degree: this.degree,\n powers: this.powers,\n coefficients: this.coefficients\n };\n }\n\n toString(precision) {\n return this._toFormula(precision, false);\n }\n\n toLaTeX(precision) {\n return this._toFormula(precision, true);\n }\n\n _toFormula(precision, isLaTeX) {\n let sup = '^';\n let closeSup = '';\n let times = ' * ';\n if (isLaTeX) {\n sup = '^{';\n closeSup = '}';\n times = '';\n }\n\n let fn = '';\n let str = '';\n for (let k = 0; k < this.coefficients.length; k++) {\n str = '';\n if (this.coefficients[k] !== 0) {\n if (this.powers[k] === 0) {\n str = maybeToPrecision(this.coefficients[k], precision);\n } else {\n if (this.powers[k] === 1) {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x';\n } else {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup;\n }\n }\n\n if (this.coefficients[k] > 0 && k !== (this.coefficients.length - 1)) {\n str = ' + ' + str;\n } else if (k !== (this.coefficients.length - 1)) {\n str = ' ' + str;\n }\n }\n fn = str + fn;\n }\n if (fn.charAt(0) === '+') {\n fn = fn.slice(1);\n }\n\n return 'f(x) = ' + fn;\n }\n\n static load(json) {\n if (json.name !== 'polynomialRegression') {\n throw new TypeError('not a polynomial regression model');\n }\n return new PolynomialRegression(true, json);\n }\n}\n\nfunction regress(pr, x, y, degree) {\n const n = x.length;\n let powers;\n if (Array.isArray(degree)) {\n powers = degree;\n degree = powers.length;\n } else {\n degree++;\n powers = new Array(degree);\n for (let k = 0; k < degree; k++) {\n powers[k] = k;\n }\n }\n const F = new Matrix(n, degree);\n const Y = new Matrix([y]);\n for (let k = 0; k < degree; k++) {\n for (let i = 0; i < n; i++) {\n if (powers[k] === 0) {\n F[i][k] = 1;\n } else {\n F[i][k] = Math.pow(x[i], powers[k]);\n }\n }\n }\n\n const FT = F.transposeView();\n const A = FT.mmul(F);\n const B = FT.mmul(Y.transposeView());\n\n pr.degree = degree - 1;\n pr.powers = powers;\n pr.coefficients = solve(A, B).to1DArray();\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport SimpleLinearRegression from 'ml-regression-simple-linear';\n\nexport default class ExponentialRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) {\n this.A = y.A;\n this.B = y.B;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n _predict(input) {\n return this.B * Math.exp(input * this.A);\n }\n\n toJSON() {\n return {\n name: 'exponentialRegression',\n A: this.A,\n B: this.B\n };\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.B, precision) + ' * e^(' + maybeToPrecision(this.A, precision) + ' * x)';\n }\n\n toLaTeX(precision) {\n if (this.A >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.B, precision) + 'e^{' + maybeToPrecision(this.A, precision) + 'x}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.B, precision) + '}{e^{' + maybeToPrecision(-this.A, precision) + 'x}}';\n }\n\n }\n\n static load(json) {\n if (json.name !== 'exponentialRegression') {\n throw new TypeError('not a exponential regression model');\n }\n return new ExponentialRegression(true, json);\n }\n}\n\nfunction regress(er, x, y) {\n const n = x.length;\n const yl = new Array(n);\n for (let i = 0; i < n; i++) {\n yl[i] = Math.log(y[i]);\n }\n\n const linear = new SimpleLinearRegression(x, yl);\n er.A = linear.slope;\n er.B = Math.exp(linear.intercept);\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport SimpleLinearRegression from 'ml-regression-simple-linear';\n\nexport default class PowerRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) { // reloading model\n this.A = y.A;\n this.B = y.B;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n _predict(newInputs) {\n return this.A * Math.pow(newInputs, this.B);\n }\n\n toJSON() {\n return {\n name: 'powerRegression',\n A: this.A,\n B: this.B\n };\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + maybeToPrecision(this.B, precision);\n }\n\n toLaTeX(precision) {\n if (this.B >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + maybeToPrecision(this.B, precision) + '}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + maybeToPrecision(-this.B, precision) + '}}';\n }\n }\n\n static load(json) {\n if (json.name !== 'powerRegression') {\n throw new TypeError('not a power regression model');\n }\n return new PowerRegression(true, json);\n }\n}\n\nfunction regress(pr, x, y) {\n const n = x.length;\n const xl = new Array(n);\n const yl = new Array(n);\n for (let i = 0; i < n; i++) {\n xl[i] = Math.log(x[i]);\n yl[i] = Math.log(y[i]);\n }\n\n const linear = new SimpleLinearRegression(xl, yl);\n pr.A = Math.exp(linear.intercept);\n pr.B = linear.slope;\n}\n","import Matrix, { SVD } from 'ml-matrix';\nimport BaseRegression from 'ml-regression-base';\n\nexport default class MultivariateLinearRegression extends BaseRegression {\n constructor(x, y, options = {}) {\n const { intercept = true, statistics = true } = options;\n super();\n this.statistics = statistics;\n if (x === true) {\n this.weights = y.weights;\n this.inputs = y.inputs;\n this.outputs = y.outputs;\n this.intercept = y.intercept;\n } else {\n x = new Matrix(x);\n if (intercept) {\n x.addColumn(new Array(x.length).fill(1));\n }\n const beta = new SVD(x, { autoTranspose: true }).solve(y);\n this.weights = beta.to2DArray();\n this.inputs = x[0].length;\n this.outputs = y[0].length;\n if (intercept) this.inputs--;\n this.intercept = intercept;\n if (statistics) {\n /*\n * Let's add some basic statistics about the beta's to be able to interpret them.\n * source: http://dept.stat.lsa.umich.edu/~kshedden/Courses/Stat401/Notes/401-multreg.pdf\n * validated against Excel Regression AddIn\n * test: \"datamining statistics test\"\n */\n const fittedValues = x.mmul(beta);\n const residuals = new Matrix(y).addM(fittedValues.neg());\n const variance =\n residuals\n .to2DArray()\n .map((ri) => Math.pow(ri[0], 2))\n .reduce((a, b) => a + b) /\n (y.length - x.columns);\n this.stdError = Math.sqrt(variance);\n this.stdErrorMatrix = x\n .transposeView()\n .mmul(x)\n .pseudoInverse()\n .mul(variance);\n this.stdErrors = this.stdErrorMatrix.diagonal().map((d) => Math.sqrt(d));\n this.tStats = this.weights.map(\n (d, i) => (this.stdErrors[i] === 0 ? 0 : d[0] / this.stdErrors[i])\n );\n }\n }\n }\n\n predict(x) {\n if (Array.isArray(x)) {\n if (typeof x[0] === 'number') {\n return this._predict(x);\n } else if (Array.isArray(x[0])) {\n const y = new Array(x.length);\n for (let i = 0; i < x.length; i++) {\n y[i] = this._predict(x[i]);\n }\n return y;\n }\n }\n throw new TypeError('x must be a matrix or array of numbers');\n }\n\n _predict(x) {\n const result = new Array(this.outputs);\n if (this.intercept) {\n for (let i = 0; i < this.outputs; i++) {\n result[i] = this.weights[this.inputs][i];\n }\n } else {\n result.fill(0);\n }\n for (let i = 0; i < this.inputs; i++) {\n for (let j = 0; j < this.outputs; j++) {\n result[j] += this.weights[i][j] * x[i];\n }\n }\n return result;\n }\n\n score() {\n throw new Error('score method is not implemented yet');\n }\n\n toJSON() {\n return {\n name: 'multivariateLinearRegression',\n weights: this.weights,\n inputs: this.inputs,\n outputs: this.outputs,\n intercept: this.intercept,\n summary: (this.statistics)\n ? {\n regressionStatistics: {\n standardError: this.stdError,\n observations: this.outputs\n },\n variables: this.weights.map((d, i) => {\n return {\n label:\n i === this.weights.length - 1\n ? 'Intercept'\n : `X Variable ${i + 1}`,\n coefficients: d,\n standardError: this.stdErrors[i],\n tStat: this.tStats[i]\n };\n })\n }\n : undefined,\n };\n }\n\n static load(model) {\n if (model.name !== 'multivariateLinearRegression') {\n throw new Error('not a MLR model');\n }\n return new MultivariateLinearRegression(true, model);\n }\n}\n","import {maybeToPrecision} from 'ml-regression-base';\nimport PolynomialRegression from 'ml-regression-polynomial';\nimport BaseRegression from 'ml-regression-base';\n\n/*\n * Function that calculate the potential fit in the form f(x) = A*x^M\n * with a given M and return de A coefficient.\n *\n * @param {Vector} X - Vector of the x positions of the points.\n * @param {Vector} Y - Vector of the x positions of the points.\n * @param {Number} M - The exponent of the potential fit.\n * @return {Number} A - The A coefficient of the potential fit.\n */\nexport default class PotentialRegression extends BaseRegression {\n /**\n * @constructor\n * @param x: Independent variable\n * @param y: Dependent variable\n * @param M\n */\n constructor(x, y, M) {\n super();\n if (x === true) { // reloading model\n this.A = y.A;\n this.M = y.M;\n } else {\n var n = x.length;\n if (n !== y.length) {\n throw new RangeError('input and output array have a different length');\n }\n\n var linear = new PolynomialRegression(x, y, [M]);\n this.A = linear.coefficients[0];\n this.M = M;\n }\n }\n\n _predict(x) {\n return this.A * Math.pow(x, this.M);\n }\n\n toJSON() {\n return {\n name: 'potentialRegression',\n A: this.A,\n M: this.M\n };\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + this.M;\n }\n\n toLaTeX(precision) {\n if (this.M >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + this.M + '}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + (-this.M) + '}}';\n }\n }\n\n static load(json) {\n if (json.name !== 'potentialRegression') {\n throw new TypeError('not a potential regression model');\n }\n return new PotentialRegression(true, json);\n }\n}\n","import {Matrix, solve} from 'ml-matrix';\nimport Kernel from 'ml-kernel';\n\nimport BaseRegression from 'ml-regression-base';\n\nconst defaultOptions = {\n lambda: 0.1,\n kernelType: 'gaussian',\n kernelOptions: {},\n computeCoefficient: false\n};\n\n// Implements the Kernel ridge regression algorithm.\n// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf\nexport default class KernelRidgeRegression extends BaseRegression {\n constructor(inputs, outputs, options) {\n super();\n if (inputs === true) { // reloading model\n this.alpha = outputs.alpha;\n this.inputs = outputs.inputs;\n this.kernelType = outputs.kernelType;\n this.kernelOptions = outputs.kernelOptions;\n this.kernel = new Kernel(outputs.kernelType, outputs.kernelOptions);\n } else {\n options = Object.assign({}, defaultOptions, options);\n\n const kernelFunction = new Kernel(options.kernelType, options.kernelOptions);\n const K = kernelFunction.compute(inputs);\n const n = inputs.length;\n K.add(Matrix.eye(n, n).mul(options.lambda));\n\n this.alpha = solve(K, outputs);\n this.inputs = inputs;\n this.kernelType = options.kernelType;\n this.kernelOptions = options.kernelOptions;\n this.kernel = kernelFunction;\n }\n }\n\n _predict(newInputs) {\n return this.kernel.compute([newInputs], this.inputs).mmul(this.alpha)[0];\n }\n\n toJSON() {\n return {\n name: 'kernelRidgeRegression',\n alpha: this.alpha,\n inputs: this.inputs,\n kernelType: this.kernelType,\n kernelOptions: this.kernelOptions\n };\n }\n\n static load(json) {\n if (json.name !== 'kernelRidgeRegression') {\n throw new TypeError('not a KRR model');\n }\n return new KernelRidgeRegression(true, json);\n }\n}\n","import {Matrix, SVD} from 'ml-matrix';\nimport BaseRegression from 'ml-regression-base';\n\nconst defaultOptions = {\n order: 2\n};\n// Implements the Kernel ridge regression algorithm.\n// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf\nexport default class PolynomialFitRegression2D extends BaseRegression {\n /**\n * Constructor for the 2D polynomial fitting\n *\n * @param inputs\n * @param outputs\n * @param options\n * @constructor\n */\n constructor(inputs, outputs, options) {\n super();\n if (inputs === true) { // reloading model\n this.coefficients = Matrix.columnVector(outputs.coefficients);\n this.order = outputs.order;\n if (outputs.r) {\n this.r = outputs.r;\n this.r2 = outputs.r2;\n }\n if (outputs.chi2) {\n this.chi2 = outputs.chi2;\n }\n } else {\n options = Object.assign({}, defaultOptions, options);\n this.order = options.order;\n this.coefficients = [];\n this.X = inputs;\n this.y = outputs;\n\n this.train(this.X, this.y, options);\n }\n }\n\n /**\n * Function that fits the model given the data(X) and predictions(y).\n * The third argument is an object with the following options:\n * * order: order of the polynomial to fit.\n *\n * @param {Matrix} X - A matrix with n rows and 2 columns.\n * @param {Matrix} y - A vector of the prediction values.\n */\n train(X, y) {\n if (!Matrix.isMatrix(X)) X = new Matrix(X);\n if (!Matrix.isMatrix(y)) y = Matrix.columnVector(y);\n\n if (y.rows !== X.rows) {\n y = y.transpose();\n }\n\n if (X.columns !== 2) {\n throw new RangeError('You give X with ' + X.columns + ' columns and it must be 2');\n }\n if (X.rows !== y.rows) {\n throw new RangeError('X and y must have the same rows');\n }\n\n var examples = X.rows;\n var coefficients = ((this.order + 2) * (this.order + 1)) / 2;\n this.coefficients = new Array(coefficients);\n\n var x1 = X.getColumnVector(0);\n var x2 = X.getColumnVector(1);\n\n var scaleX1 = 1.0 / x1.clone().apply(abs).max();\n var scaleX2 = 1.0 / x2.clone().apply(abs).max();\n var scaleY = 1.0 / y.clone().apply(abs).max();\n\n x1.mulColumn(0, scaleX1);\n x2.mulColumn(0, scaleX2);\n y.mulColumn(0, scaleY);\n\n var A = new Matrix(examples, coefficients);\n var col = 0;\n\n for (var i = 0; i <= this.order; ++i) {\n var limit = this.order - i;\n for (var j = 0; j <= limit; ++j) {\n var result = powColVector(x1, i).mulColumnVector(powColVector(x2, j));\n A.setColumn(col, result);\n col++;\n }\n }\n\n var svd = new SVD(A.transpose(), {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: true,\n autoTranspose: false\n });\n\n var qqs = Matrix.rowVector(svd.diagonal);\n qqs = qqs.apply(function (i, j) {\n if (this[i][j] >= 1e-15) this[i][j] = 1 / this[i][j];\n else this[i][j] = 0;\n });\n\n var qqs1 = Matrix.zeros(examples, coefficients);\n for (i = 0; i < coefficients; ++i) {\n qqs1[i][i] = qqs[0][i];\n }\n\n qqs = qqs1;\n\n var U = svd.rightSingularVectors;\n var V = svd.leftSingularVectors;\n\n this.coefficients = V.mmul(qqs.transpose()).mmul(U.transpose()).mmul(y);\n\n col = 0;\n\n for (i = 0; i <= coefficients; ++i) {\n limit = this.order - i;\n for (j = 0; j <= limit; ++j) {\n this.coefficients[col][0] = (this.coefficients[col][0] * Math.pow(scaleX1, i) * Math.pow(scaleX2, j)) / scaleY;\n col++;\n }\n }\n }\n\n _predict(newInputs) {\n var x1 = newInputs[0];\n var x2 = newInputs[1];\n\n var y = 0;\n var column = 0;\n\n for (var i = 0; i <= this.order; i++) {\n for (var j = 0; j <= this.order - i; j++) {\n y += Math.pow(x1, i) * (Math.pow(x2, j)) * this.coefficients[column][0];\n column++;\n }\n }\n\n return y;\n }\n\n toJSON() {\n return {\n name: 'polyfit2D',\n order: this.order,\n coefficients: this.coefficients\n };\n }\n\n static load(json) {\n if (json.name !== 'polyfit2D') {\n throw new TypeError('not a polyfit2D model');\n }\n return new PolynomialFitRegression2D(true, json);\n }\n}\n\n/**\n * Function that given a column vector return this: vector^power\n *\n * @param x - Column vector.\n * @param power - Pow number.\n * @return {Suite|Matrix}\n */\nfunction powColVector(x, power) {\n var result = x.clone();\n for (var i = 0; i < x.rows; ++i) {\n result[i][0] = Math.pow(result[i][0], power);\n }\n return result;\n}\n\n/**\n * Function to use in the apply method to get the absolute value\n * of each element of the matrix\n *\n * @param i - current row.\n * @param j - current column.\n */\nfunction abs(i, j) {\n this[i][j] = Math.abs(this[i][j]);\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport {array} from 'ml-stat';\nconst median = array.median;\n\nexport default class TheilSenRegression extends BaseRegression {\n\n /**\n * Theil–Sen estimator\n * https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator\n * @param {Array|boolean} x\n * @param {Array|object} y\n * @constructor\n */\n constructor(x, y) {\n super();\n if (x === true) {\n // loads the model\n this.slope = y.slope;\n this.intercept = y.intercept;\n this.coefficients = y.coefficients;\n } else {\n // creates the model\n checkArrayLength(x, y);\n theilSen(this, x, y);\n }\n\n }\n\n toJSON() {\n return {\n name: 'TheilSenRegression',\n slope: this.slope,\n intercept: this.intercept\n };\n }\n\n _predict(input) {\n return this.slope * input + this.intercept;\n }\n\n computeX(input) {\n return (input - this.intercept) / this.slope;\n }\n\n toString(precision) {\n var result = 'f(x) = ';\n if (this.slope) {\n var xFactor = maybeToPrecision(this.slope, precision);\n result += (Math.abs(xFactor - 1) < 1e-5 ? '' : xFactor + ' * ') + 'x';\n if (this.intercept) {\n var absIntercept = Math.abs(this.intercept);\n var operator = absIntercept === this.intercept ? '+' : '-';\n result += ' ' + operator + ' ' + maybeToPrecision(absIntercept, precision);\n }\n } else {\n result += maybeToPrecision(this.intercept, precision);\n }\n return result;\n }\n\n toLaTeX(precision) {\n return this.toString(precision);\n }\n\n static load(json) {\n if (json.name !== 'TheilSenRegression') {\n throw new TypeError('not a Theil-Sen model');\n }\n return new TheilSenRegression(true, json);\n }\n}\n\nfunction theilSen(regression, x, y) {\n let len = x.length;\n let slopes = new Array(len * len);\n let count = 0;\n for (let i = 0; i < len; ++i) {\n for (let j = i + 1; j < len; ++j) {\n if (x[i] !== x[j]) {\n slopes[count++] = (y[j] - y[i]) / (x[j] - x[i]);\n }\n }\n }\n slopes.length = count;\n let medianSlope = median(slopes);\n\n let cuts = new Array(len);\n for (let i = 0; i < len; ++i) {\n cuts[i] = y[i] - medianSlope * x[i];\n }\n\n regression.slope = medianSlope;\n regression.intercept = median(cuts);\n regression.coefficients = [regression.intercept, regression.slope];\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport {solve} from 'ml-matrix';\n\nexport default class RobustPolynomialRegression extends BaseRegression {\n constructor(x, y, degree) {\n super();\n if (x === true) {\n this.degree = y.degree;\n this.powers = y.powers;\n this.coefficients = y.coefficients;\n } else {\n checkArrayLength(x, y);\n robustPolynomial(this, x, y, degree);\n }\n }\n\n toJSON() {\n return {\n name: 'robustPolynomialRegression',\n degree: this.degree,\n powers: this.powers,\n coefficients: this.coefficients\n };\n }\n\n _predict(x) {\n return predict(x, this.powers, this.coefficients);\n }\n\n toString(precision) {\n return this._toFormula(precision, false);\n }\n\n toLaTeX(precision) {\n return this._toFormula(precision, true);\n }\n\n _toFormula(precision, isLaTeX) {\n let sup = '^';\n let closeSup = '';\n let times = ' * ';\n if (isLaTeX) {\n sup = '^{';\n closeSup = '}';\n times = '';\n }\n\n let fn = '';\n let str = '';\n for (let k = 0; k < this.coefficients.length; k++) {\n str = '';\n if (this.coefficients[k] !== 0) {\n if (this.powers[k] === 0) {\n str = maybeToPrecision(this.coefficients[k], precision);\n } else {\n if (this.powers[k] === 1) {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x';\n } else {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup;\n }\n }\n\n if (this.coefficients[k] > 0 && k !== (this.coefficients.length - 1)) {\n str = ' + ' + str;\n } else if (k !== (this.coefficients.length - 1)) {\n str = ' ' + str;\n }\n }\n fn = str + fn;\n }\n if (fn.charAt(0) === '+') {\n fn = fn.slice(1);\n }\n\n return 'f(x) = ' + fn;\n }\n\n static load(json) {\n if (json.name !== 'robustPolynomialRegression') {\n throw new TypeError('not a RobustPolynomialRegression model');\n }\n return new RobustPolynomialRegression(true, json);\n }\n}\n\nfunction robustPolynomial(regression, x, y, degree) {\n let powers = new Array(degree);\n for (let k = 0; k < degree; k++) {\n powers[k] = k;\n }\n\n const tuples = getRandomTuples(x, y, degree);\n var min;\n\n for (var i = 0; i < tuples.length; i++) {\n var tuple = tuples[i];\n var coefficients = calcCoefficients(tuple, powers);\n\n var residuals = x.slice();\n for (var j = 0; j < x.length; j++) {\n residuals[j] = y[j] - predict(x[j], powers, coefficients);\n residuals[j] = {\n residual: residuals[j] * residuals[j],\n coefficients\n };\n }\n\n var median = residualsMedian(residuals);\n if (!min || median.residual < min.residual) {\n min = median;\n }\n }\n\n regression.degree = degree;\n regression.powers = powers;\n regression.coefficients = min.coefficients;\n}\n\n/**\n * @ignore\n * @param {Array} x\n * @param {Array} y\n * @param {number} degree\n * @return {Array<{x:number,y:number}>}\n */\nfunction getRandomTuples(x, y, degree) {\n var len = Math.floor(x.length / degree);\n var tuples = new Array(len);\n\n for (var i = 0; i < x.length; i++) {\n var pos = Math.floor(Math.random() * len);\n\n var counter = 0;\n while (counter < x.length) {\n if (!tuples[pos]) {\n tuples[pos] = [{\n x: x[i],\n y: y[i]\n }];\n break;\n } else if (tuples[pos].length < degree) {\n tuples[pos].push({\n x: x[i],\n y: y[i]\n });\n break;\n } else {\n counter++;\n pos = (pos + 1) % len;\n }\n }\n\n if (counter === x.length) {\n return tuples;\n }\n }\n return tuples;\n}\n\n/**\n * @ignore\n * @param {{x:number,y:number}} tuple\n * @param {Array} powers\n * @return {Array}\n */\nfunction calcCoefficients(tuple, powers) {\n var X = tuple.slice();\n var Y = tuple.slice();\n for (var i = 0; i < X.length; i++) {\n Y[i] = [tuple[i].y];\n X[i] = new Array(powers.length);\n for (var j = 0; j < powers.length; j++) {\n X[i][j] = Math.pow(tuple[i].x, powers[j]);\n }\n }\n\n return solve(X, Y).to1DArray();\n}\n\nfunction predict(x, powers, coefficients) {\n let y = 0;\n for (let k = 0; k < powers.length; k++) {\n y += coefficients[k] * Math.pow(x, powers[k]);\n }\n return y;\n}\n\nfunction residualsMedian(residuals) {\n residuals.sort((a, b) => a.residual - b.residual);\n\n var l = residuals.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return residuals[half - 1];\n } else {\n return residuals[half];\n }\n}\n","export {default as SimpleLinearRegression, default as SLR} from 'ml-regression-simple-linear';\nexport {default as PolynomialRegression} from 'ml-regression-polynomial';\nexport {default as ExponentialRegression} from 'ml-regression-exponential';\nexport {default as PowerRegression} from 'ml-regression-power';\nexport {default as MultivariateLinearRegression} from 'ml-regression-multivariate-linear';\n\nimport PotentialRegression from './regression/potential-regression';\nconst NLR = {\n PotentialRegression\n};\nexport {NLR, NLR as NonLinearRegression};\n\nexport {default as KernelRidgeRegression, default as KRR} from './regression/kernel-ridge-regression';\nexport {default as PolinomialFitting2D} from './regression/poly-fit-regression2d';\n\n// robust regressions\nexport {default as TheilSenRegression} from 'ml-regression-theil-sen';\nexport {default as RobustPolynomialRegression} from 'ml-regression-robust-polynomial';\n","(function(){function a(d){for(var e=0,f=d.length-1,g=void 0,h=void 0,i=void 0,j=c(e,f);!0;){if(f<=e)return d[j];if(f==e+1)return d[e]>d[f]&&b(d,e,f),d[j];for(g=c(e,f),d[g]>d[f]&&b(d,g,f),d[e]>d[f]&&b(d,e,f),d[g]>d[e]&&b(d,g,e),b(d,g,e+1),h=e+1,i=f;!0;){do h++;while(d[e]>d[h]);do i--;while(d[i]>d[e]);if(i=j&&(f=i-1)}}var b=function b(d,e,f){var _ref;return _ref=[d[f],d[e]],d[e]=_ref[0],d[f]=_ref[1],_ref},c=function c(d,e){return~~((d+e)/2)};'undefined'!=typeof module&&module.exports?module.exports=a:window.median=a})();\n","'use strict';\n\nconst mlCart = require('ml-cart');\nconst mlRandomForest = require('ml-random-forest');\n\nconst ML = exports;\n\n// Try to keep this list in the same structure as the README.\n\n// Unsupervised learning\nML.PCA = require('ml-pca');\nML.HClust = require('ml-hclust');\nML.KMeans = require('ml-kmeans');\n\n// Supervised learning\nML.SVM = require('ml-svm');\nML.NaiveBayes = require('ml-naivebayes');\nML.KNN = require('ml-knn');\nML.PLS = require('ml-pls');\nML.CrossValidation = require('ml-cross-validation');\nML.ConfusionMatrix = require('ml-confusion-matrix');\nML.DecisionTreeClassifier = mlCart.DecisionTreeClassifier;\nML.RandomForestClassifier = mlRandomForest.RandomForestClassifier;\n\n// Artificial neural networks\nML.FNN = require('ml-fnn');\nML.SOM = require('ml-som');\n\n// Regression\nconst Regression = require('ml-regression');\nML.SimpleLinearRegression = Regression.SimpleLinearRegression;\nML.PolynomialRegression = Regression.PolynomialRegression;\nML.MultivariateLinearRegression = Regression.MultivariateLinearRegression;\nML.PowerRegression = Regression.PowerRegression;\nML.ExponentialRegression = Regression.ExponentialRegression;\nML.TheilSenRegression = Regression.TheilSenRegression;\nML.RobustPolynomialRegression = Regression.RobustPolynomialRegression;\nML.DecisionTreeRegression = mlCart.DecisionTreeRegression;\nML.RandomForestRegression = mlRandomForest.RandomForestRegression;\n\n// Optimization\nML.levenbergMarquardt = require('ml-levenberg-marquardt');\n\n// Math\nconst Matrix = require('ml-matrix');\nML.Matrix = Matrix.Matrix;\nML.SVD = Matrix.SVD;\nML.EVD = Matrix.EVD;\nML.CholeskyDecomposition = Matrix.CholeskyDecomposition;\nML.LuDecomposition = Matrix.LuDecomposition;\nML.QrDecomposition = Matrix.QrDecomposition;\n\nML.SparseMatrix = require('ml-sparse-matrix');\nML.Kernel = require('ml-kernel');\nML.Distance = require('ml-distance').distance;\nML.Similarity = require('ml-distance').similarity;\nML.distanceMatrix = require('ml-distance-matrix');\nML.XSadd = require('ml-xsadd').default;\n\n// Statistics\nML.Performance = require('ml-performance');\n\n// Data preprocessing\nML.savitzkyGolay = require('ml-savitzky-golay');\nML.savitzkyGolayGeneralized = require('ml-savitzky-golay-generalized');\n\n// Utility\nML.BitArray = require('ml-bit-array');\nML.HashTable = require('ml-hash-table');\nML.padArray = require('ml-pad-array');\nML.binarySearch = require('binary-search');\nML.numSort = require('num-sort');\nML.Random = require('ml-random').default;\n\n// Undocumented/deprecated packages\nML.ArrayUtils = require('ml-array-utils');\nML.Regression = require('ml-regression');\nML.MatrixUtil = require('ml-matrix');\nML.ArrayStat = require('ml-stat').array;\nML.MatrixStat = require('ml-stat').matrix;\n\nML.Array = {\n min: require('ml-array-min').default,\n max: require('ml-array-max').default,\n median: require('ml-array-median').default,\n mean: require('ml-array-mean').default,\n mode: require('ml-array-mode').default,\n normed: require('ml-array-normed').default,\n rescale: require('ml-array-rescale').default,\n sequentialFill: require('ml-array-sequential-fill').default,\n standardDeviation: require('ml-array-standard-deviation').default,\n variance: require('ml-array-variance').default\n};\n\nML.ArrayXY = {\n centroidsMerge: require('ml-array-xy-centroids-merge').default,\n closestX: require('ml-arrayxy-closestx').default,\n maxMerge: require('ml-array-xy-max-merge').default,\n maxY: require('ml-array-xy-max-y').default,\n sortX: require('ml-array-xy-sort-x').default,\n uniqueX: require('ml-arrayxy-uniquex').default,\n weightedMerge: require('ml-array-xy-weighted-merge').default,\n equallySpaced: require('ml-array-xy-equally-spaced').default,\n filterX: require('ml-array-xy-filter-x').default\n};\n","'use strict';\n\nconst matrixLib = require('ml-matrix');\nconst Matrix = matrixLib.Matrix;\nconst EVD = matrixLib.EVD;\nconst SVD = matrixLib.SVD;\nconst Stat = require('ml-stat/matrix');\nconst mean = Stat.mean;\nconst stdev = Stat.standardDeviation;\n\nconst defaultOptions = {\n isCovarianceMatrix: false,\n center: true,\n scale: false\n};\n\n/**\n * Creates new PCA (Principal Component Analysis) from the dataset\n * @param {Matrix} dataset - dataset or covariance matrix\n * @param {Object} options\n * @param {boolean} [options.isCovarianceMatrix=false] - true if the dataset is a covariance matrix\n * @param {boolean} [options.center=true] - should the data be centered (subtract the mean)\n * @param {boolean} [options.scale=false] - should the data be scaled (divide by the standard deviation)\n * */\nclass PCA {\n constructor(dataset, options) {\n if (dataset === true) {\n const model = options;\n this.center = model.center;\n this.scale = model.scale;\n this.means = model.means;\n this.stdevs = model.stdevs;\n this.U = Matrix.checkMatrix(model.U);\n this.S = model.S;\n return;\n }\n\n options = Object.assign({}, defaultOptions, options);\n\n this.center = false;\n this.scale = false;\n this.means = null;\n this.stdevs = null;\n\n if (options.isCovarianceMatrix) { // user provided a covariance matrix instead of dataset\n this._computeFromCovarianceMatrix(dataset);\n return;\n }\n\n var useCovarianceMatrix;\n if (typeof options.useCovarianceMatrix === 'boolean') {\n useCovarianceMatrix = options.useCovarianceMatrix;\n } else {\n useCovarianceMatrix = dataset.length > dataset[0].length;\n }\n\n if (useCovarianceMatrix) { // user provided a dataset but wants us to compute and use the covariance matrix\n dataset = this._adjust(dataset, options);\n const covarianceMatrix = dataset.transposeView().mmul(dataset).div(dataset.rows - 1);\n this._computeFromCovarianceMatrix(covarianceMatrix);\n } else {\n dataset = this._adjust(dataset, options);\n var svd = new SVD(dataset, {\n computeLeftSingularVectors: false,\n computeRightSingularVectors: true,\n autoTranspose: true\n });\n\n this.U = svd.rightSingularVectors;\n\n const singularValues = svd.diagonal;\n const eigenvalues = new Array(singularValues.length);\n for (var i = 0; i < singularValues.length; i++) {\n eigenvalues[i] = singularValues[i] * singularValues[i] / (dataset.length - 1);\n }\n this.S = eigenvalues;\n }\n }\n\n /**\n * Load a PCA model from JSON\n * @param {Object} model\n * @return {PCA}\n */\n static load(model) {\n if (model.name !== 'PCA')\n throw new RangeError('Invalid model: ' + model.name);\n return new PCA(true, model);\n }\n\n\n /**\n * Project the dataset into the PCA space\n * @param {Matrix} dataset\n * @param {Object} options\n * @return {Matrix} dataset projected in the PCA space\n */\n predict(dataset, options = {}) {\n const {\n nComponents = this.U.columns\n } = options;\n\n dataset = new Matrix(dataset);\n if (this.center) {\n dataset.subRowVector(this.means);\n if (this.scale) {\n dataset.divRowVector(this.stdevs);\n }\n }\n\n var predictions = dataset.mmul(this.U);\n return predictions.subMatrix(0, predictions.rows - 1, 0, nComponents - 1);\n }\n\n /**\n * Returns the proportion of variance for each component\n * @return {[number]}\n */\n getExplainedVariance() {\n var sum = 0;\n for (var i = 0; i < this.S.length; i++) {\n sum += this.S[i];\n }\n return this.S.map(value => value / sum);\n }\n\n /**\n * Returns the cumulative proportion of variance\n * @return {[number]}\n */\n getCumulativeVariance() {\n var explained = this.getExplainedVariance();\n for (var i = 1; i < explained.length; i++) {\n explained[i] += explained[i - 1];\n }\n return explained;\n }\n\n /**\n * Returns the Eigenvectors of the covariance matrix\n * @returns {Matrix}\n */\n getEigenvectors() {\n return this.U;\n }\n\n /**\n * Returns the Eigenvalues (on the diagonal)\n * @returns {[number]}\n */\n getEigenvalues() {\n return this.S;\n }\n\n /**\n * Returns the standard deviations of the principal components\n * @returns {[number]}\n */\n getStandardDeviations() {\n return this.S.map(x => Math.sqrt(x));\n }\n\n /**\n * Returns the loadings matrix\n * @return {Matrix}\n */\n getLoadings() {\n return this.U.transpose();\n }\n\n /**\n * Export the current model to a JSON object\n * @return {Object} model\n */\n toJSON() {\n return {\n name: 'PCA',\n center: this.center,\n scale: this.scale,\n means: this.means,\n stdevs: this.stdevs,\n U: this.U,\n S: this.S,\n };\n }\n\n _adjust(dataset, options) {\n this.center = !!options.center;\n this.scale = !!options.scale;\n\n dataset = new Matrix(dataset);\n\n if (this.center) {\n const means = mean(dataset);\n const stdevs = this.scale ? stdev(dataset, means, true) : null;\n this.means = means;\n dataset.subRowVector(means);\n if (this.scale) {\n for (var i = 0; i < stdevs.length; i++) {\n if (stdevs[i] === 0) {\n throw new RangeError('Cannot scale the dataset (standard deviation is zero at index ' + i);\n }\n }\n this.stdevs = stdevs;\n dataset.divRowVector(stdevs);\n }\n }\n\n return dataset;\n }\n\n _computeFromCovarianceMatrix(dataset) {\n const evd = new EVD(dataset, {assumeSymmetric: true});\n this.U = evd.eigenvectorMatrix;\n for (var i = 0; i < this.U.length; i++) {\n this.U[i].reverse();\n }\n this.S = evd.realEigenvalues.reverse();\n }\n}\n\nmodule.exports = PCA;\n","'use strict';\n\nexports.agnes = require('./agnes');\nexports.diana = require('./diana');\n//exports.birch = require('./birch');\n//exports.cure = require('./cure');\n//exports.chameleon = require('./chameleon');\n","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\nconst ClusterLeaf = require('./ClusterLeaf');\nconst Cluster = require('./Cluster');\nconst distanceMatrix = require('ml-distance-matrix');\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction simpleLink(cluster1, cluster2, disFun) {\n var m = 10e100;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n var d = disFun[cluster1[i]][ cluster2[j]];\n m = Math.min(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction completeLink(cluster1, cluster2, disFun) {\n var m = -1;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n var d = disFun[cluster1[i]][ cluster2[j]];\n m = Math.max(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction averageLink(cluster1, cluster2, disFun) {\n var m = 0;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n m += disFun[cluster1[i]][ cluster2[j]];\n }\n }\n return m / (cluster1.length * cluster2.length);\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {*}\n */\nfunction centroidLink(cluster1, cluster2, disFun) {\n var dist = new Array(cluster1.length * cluster2.length);\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n dist[i * cluster2.length + j] = (disFun[cluster1[i]][ cluster2[j]]);\n }\n }\n return median(dist);\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction wardLink(cluster1, cluster2, disFun) {\n return centroidLink(cluster1, cluster2, disFun)\n * cluster1.length * cluster2.length / (cluster1.length + cluster2.length);\n}\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nfunction median(values, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return (values[half - 1] + values[half]) * 0.5;\n } else {\n return values[half];\n }\n}\n\nvar defaultOptions = {\n disFunc: euclidean,\n kind: 'single',\n isDistanceMatrix: false\n\n};\n\n/**\n * Continuously merge nodes that have the least dissimilarity\n * @param {Array >} distance - Array of points to be clustered\n * @param {json} options\n * @option isDistanceMatrix: Is the input a distance matrix?\n * @constructor\n */\nfunction agnes(data, options) {\n options = Object.assign({}, defaultOptions, options);\n var len = data.length;\n var distance = data;//If source\n if (!options.isDistanceMatrix) {\n distance = distanceMatrix(data, options.disFunc);\n }\n\n\n // allows to use a string or a given function\n if (typeof options.kind === 'string') {\n switch (options.kind) {\n case 'single':\n options.kind = simpleLink;\n break;\n case 'complete':\n options.kind = completeLink;\n break;\n case 'average':\n options.kind = averageLink;\n break;\n case 'centroid':\n options.kind = centroidLink;\n break;\n case 'ward':\n options.kind = wardLink;\n break;\n default:\n throw new RangeError('Unknown kind of similarity');\n }\n } else if (typeof options.kind !== 'function') {\n throw new TypeError('Undefined kind of similarity');\n }\n\n var list = new Array(len);\n for (var i = 0; i < distance.length; i++) {\n list[i] = new ClusterLeaf(i);\n }\n var min = 10e5,\n d = {},\n dis = 0;\n\n while (list.length > 1) {\n // calculates the minimum distance\n d = {};\n min = 10e5;\n for (var j = 0; j < list.length; j++) {\n for (var k = j + 1; k < list.length; k++) {\n var fdistance, sdistance;\n if (list[j] instanceof ClusterLeaf) {\n fdistance = [list[j].index];\n } else {\n fdistance = new Array(list[j].index.length);\n for (var e = 0; e < fdistance.length; e++) {\n fdistance[e] = list[j].index[e].index;\n }\n }\n if (list[k] instanceof ClusterLeaf) {\n sdistance = [list[k].index];\n } else {\n sdistance = new Array(list[k].index.length);\n for (var f = 0; f < sdistance.length; f++) {\n sdistance[f] = list[k].index[f].index;\n }\n }\n dis = options.kind(fdistance, sdistance, distance).toFixed(4);\n if (dis in d) {\n d[dis].push([list[j], list[k]]);\n } else {\n d[dis] = [[list[j], list[k]]];\n }\n min = Math.min(dis, min);\n }\n }\n // cluster dots\n var dmin = d[min.toFixed(4)];\n var clustered = new Array(dmin.length);\n var aux,\n count = 0;\n while (dmin.length > 0) {\n aux = dmin.shift();\n for (var q = 0; q < dmin.length; q++) {\n var int = dmin[q].filter(function (n) {\n //noinspection JSReferencingMutableVariableFromClosure\n return aux.indexOf(n) !== -1;\n });\n if (int.length > 0) {\n var diff = dmin[q].filter(function (n) {\n //noinspection JSReferencingMutableVariableFromClosure\n return aux.indexOf(n) === -1;\n });\n aux = aux.concat(diff);\n dmin.splice(q--, 1);\n }\n }\n clustered[count++] = aux;\n }\n clustered.length = count;\n\n for (var ii = 0; ii < clustered.length; ii++) {\n var obj = new Cluster();\n obj.children = clustered[ii].concat();\n obj.distance = min;\n obj.index = new Array(len);\n var indCount = 0;\n for (var jj = 0; jj < clustered[ii].length; jj++) {\n if (clustered[ii][jj] instanceof ClusterLeaf) {\n obj.index[indCount++] = clustered[ii][jj];\n } else {\n indCount += clustered[ii][jj].index.length;\n obj.index = clustered[ii][jj].index.concat(obj.index);\n }\n list.splice((list.indexOf(clustered[ii][jj])), 1);\n }\n obj.index.length = indCount;\n list.push(obj);\n }\n }\n return list[0];\n}\n\nmodule.exports = agnes;\n","module.exports = require('./lib/heap');\n","// Generated by CoffeeScript 1.8.0\n(function() {\n var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;\n\n floor = Math.floor, min = Math.min;\n\n\n /*\n Default comparison function to be used\n */\n\n defaultCmp = function(x, y) {\n if (x < y) {\n return -1;\n }\n if (x > y) {\n return 1;\n }\n return 0;\n };\n\n\n /*\n Insert item x in list a, and keep it sorted assuming a is sorted.\n \n If x is already in a, insert it to the right of the rightmost x.\n \n Optional args lo (default 0) and hi (default a.length) bound the slice\n of a to be searched.\n */\n\n insort = function(a, x, lo, hi, cmp) {\n var mid;\n if (lo == null) {\n lo = 0;\n }\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (lo < 0) {\n throw new Error('lo must be non-negative');\n }\n if (hi == null) {\n hi = a.length;\n }\n while (lo < hi) {\n mid = floor((lo + hi) / 2);\n if (cmp(x, a[mid]) < 0) {\n hi = mid;\n } else {\n lo = mid + 1;\n }\n }\n return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);\n };\n\n\n /*\n Push item onto heap, maintaining the heap invariant.\n */\n\n heappush = function(array, item, cmp) {\n if (cmp == null) {\n cmp = defaultCmp;\n }\n array.push(item);\n return _siftdown(array, 0, array.length - 1, cmp);\n };\n\n\n /*\n Pop the smallest item off the heap, maintaining the heap invariant.\n */\n\n heappop = function(array, cmp) {\n var lastelt, returnitem;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n lastelt = array.pop();\n if (array.length) {\n returnitem = array[0];\n array[0] = lastelt;\n _siftup(array, 0, cmp);\n } else {\n returnitem = lastelt;\n }\n return returnitem;\n };\n\n\n /*\n Pop and return the current smallest value, and add the new item.\n \n This is more efficient than heappop() followed by heappush(), and can be\n more appropriate when using a fixed size heap. Note that the value\n returned may be larger than item! That constrains reasonable use of\n this routine unless written as part of a conditional replacement:\n if item > array[0]\n item = heapreplace(array, item)\n */\n\n heapreplace = function(array, item, cmp) {\n var returnitem;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n returnitem = array[0];\n array[0] = item;\n _siftup(array, 0, cmp);\n return returnitem;\n };\n\n\n /*\n Fast version of a heappush followed by a heappop.\n */\n\n heappushpop = function(array, item, cmp) {\n var _ref;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (array.length && cmp(array[0], item) < 0) {\n _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];\n _siftup(array, 0, cmp);\n }\n return item;\n };\n\n\n /*\n Transform list into a heap, in-place, in O(array.length) time.\n */\n\n heapify = function(array, cmp) {\n var i, _i, _j, _len, _ref, _ref1, _results, _results1;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n _ref1 = (function() {\n _results1 = [];\n for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }\n return _results1;\n }).apply(this).reverse();\n _results = [];\n for (_i = 0, _len = _ref1.length; _i < _len; _i++) {\n i = _ref1[_i];\n _results.push(_siftup(array, i, cmp));\n }\n return _results;\n };\n\n\n /*\n Update the position of the given item in the heap.\n This function should be called every time the item is being modified.\n */\n\n updateItem = function(array, item, cmp) {\n var pos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n pos = array.indexOf(item);\n if (pos === -1) {\n return;\n }\n _siftdown(array, 0, pos, cmp);\n return _siftup(array, pos, cmp);\n };\n\n\n /*\n Find the n largest elements in a dataset.\n */\n\n nlargest = function(array, n, cmp) {\n var elem, result, _i, _len, _ref;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n result = array.slice(0, n);\n if (!result.length) {\n return result;\n }\n heapify(result, cmp);\n _ref = array.slice(n);\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n heappushpop(result, elem, cmp);\n }\n return result.sort(cmp).reverse();\n };\n\n\n /*\n Find the n smallest elements in a dataset.\n */\n\n nsmallest = function(array, n, cmp) {\n var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (n * 10 <= array.length) {\n result = array.slice(0, n).sort(cmp);\n if (!result.length) {\n return result;\n }\n los = result[result.length - 1];\n _ref = array.slice(n);\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n if (cmp(elem, los) < 0) {\n insort(result, elem, 0, null, cmp);\n result.pop();\n los = result[result.length - 1];\n }\n }\n return result;\n }\n heapify(array, cmp);\n _results = [];\n for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) {\n _results.push(heappop(array, cmp));\n }\n return _results;\n };\n\n _siftdown = function(array, startpos, pos, cmp) {\n var newitem, parent, parentpos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n newitem = array[pos];\n while (pos > startpos) {\n parentpos = (pos - 1) >> 1;\n parent = array[parentpos];\n if (cmp(newitem, parent) < 0) {\n array[pos] = parent;\n pos = parentpos;\n continue;\n }\n break;\n }\n return array[pos] = newitem;\n };\n\n _siftup = function(array, pos, cmp) {\n var childpos, endpos, newitem, rightpos, startpos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n endpos = array.length;\n startpos = pos;\n newitem = array[pos];\n childpos = 2 * pos + 1;\n while (childpos < endpos) {\n rightpos = childpos + 1;\n if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {\n childpos = rightpos;\n }\n array[pos] = array[childpos];\n pos = childpos;\n childpos = 2 * pos + 1;\n }\n array[pos] = newitem;\n return _siftdown(array, startpos, pos, cmp);\n };\n\n Heap = (function() {\n Heap.push = heappush;\n\n Heap.pop = heappop;\n\n Heap.replace = heapreplace;\n\n Heap.pushpop = heappushpop;\n\n Heap.heapify = heapify;\n\n Heap.updateItem = updateItem;\n\n Heap.nlargest = nlargest;\n\n Heap.nsmallest = nsmallest;\n\n function Heap(cmp) {\n this.cmp = cmp != null ? cmp : defaultCmp;\n this.nodes = [];\n }\n\n Heap.prototype.push = function(x) {\n return heappush(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.pop = function() {\n return heappop(this.nodes, this.cmp);\n };\n\n Heap.prototype.peek = function() {\n return this.nodes[0];\n };\n\n Heap.prototype.contains = function(x) {\n return this.nodes.indexOf(x) !== -1;\n };\n\n Heap.prototype.replace = function(x) {\n return heapreplace(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.pushpop = function(x) {\n return heappushpop(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.heapify = function() {\n return heapify(this.nodes, this.cmp);\n };\n\n Heap.prototype.updateItem = function(x) {\n return updateItem(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.clear = function() {\n return this.nodes = [];\n };\n\n Heap.prototype.empty = function() {\n return this.nodes.length === 0;\n };\n\n Heap.prototype.size = function() {\n return this.nodes.length;\n };\n\n Heap.prototype.clone = function() {\n var heap;\n heap = new Heap();\n heap.nodes = this.nodes.slice(0);\n return heap;\n };\n\n Heap.prototype.toArray = function() {\n return this.nodes.slice(0);\n };\n\n Heap.prototype.insert = Heap.prototype.push;\n\n Heap.prototype.top = Heap.prototype.peek;\n\n Heap.prototype.front = Heap.prototype.peek;\n\n Heap.prototype.has = Heap.prototype.contains;\n\n Heap.prototype.copy = Heap.prototype.clone;\n\n return Heap;\n\n })();\n\n (function(root, factory) {\n if (typeof define === 'function' && define.amd) {\n return define([], factory);\n } else if (typeof exports === 'object') {\n return module.exports = factory();\n } else {\n return root.Heap = factory();\n }\n })(this, function() {\n return Heap;\n });\n\n}).call(this);\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||\n function getOwnPropertyDescriptors(obj) {\n var keys = Object.keys(obj);\n var descriptors = {};\n for (var i = 0; i < keys.length; i++) {\n descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);\n }\n return descriptors;\n };\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n if (!isString(f)) {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j':\n try {\n return JSON.stringify(args[i++]);\n } catch (_) {\n return '[Circular]';\n }\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (isNull(x) || !isObject(x)) {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexports.deprecate = function(fn, msg) {\n if (typeof process !== 'undefined' && process.noDeprecation === true) {\n return fn;\n }\n\n // Allow for deprecating things in the process of starting up.\n if (typeof process === 'undefined') {\n return function() {\n return exports.deprecate(fn, msg).apply(this, arguments);\n };\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnviron;\nexports.debuglog = function(set) {\n if (isUndefined(debugEnviron))\n debugEnviron = process.env.NODE_DEBUG || '';\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (new RegExp('\\\\b' + set + '\\\\b', 'i').test(debugEnviron)) {\n var pid = process.pid;\n debugs[set] = function() {\n var msg = exports.format.apply(exports, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nfunction inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (isBoolean(opts)) {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n exports._extend(ctx, opts);\n }\n // set default options\n if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n if (isUndefined(ctx.depth)) ctx.depth = 2;\n if (isUndefined(ctx.colors)) ctx.colors = false;\n if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\nexports.inspect = inspect;\n\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect &&\n value &&\n isFunction(value.inspect) &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== exports.inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n var ret = value.inspect(recurseTimes, ctx);\n if (!isString(ret)) {\n ret = formatValue(ctx, ret, recurseTimes);\n }\n return ret;\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // IE doesn't make error fields non-enumerable\n // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n if (isError(value)\n && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n return formatError(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (isFunction(value)) {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (isFunction(value)) {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n if (isUndefined(value))\n return ctx.stylize('undefined', 'undefined');\n if (isString(value)) {\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n }\n if (isNumber(value))\n return ctx.stylize('' + value, 'number');\n if (isBoolean(value))\n return ctx.stylize('' + value, 'boolean');\n // For some reason typeof null is \"object\", so special case here.\n if (isNull(value))\n return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (isNull(recurseTimes)) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (isUndefined(name)) {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nfunction isArray(ar) {\n return Array.isArray(ar);\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return isObject(re) && objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return isObject(d) && objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return isObject(e) &&\n (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('./support/isBuffer');\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexports.log = function() {\n console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexports.inherits = require('inherits');\n\nexports._extend = function(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || !isObject(add)) return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nvar kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;\n\nexports.promisify = function promisify(original) {\n if (typeof original !== 'function')\n throw new TypeError('The \"original\" argument must be of type Function');\n\n if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {\n var fn = original[kCustomPromisifiedSymbol];\n if (typeof fn !== 'function') {\n throw new TypeError('The \"util.promisify.custom\" argument must be of type Function');\n }\n Object.defineProperty(fn, kCustomPromisifiedSymbol, {\n value: fn, enumerable: false, writable: false, configurable: true\n });\n return fn;\n }\n\n function fn() {\n var promiseResolve, promiseReject;\n var promise = new Promise(function (resolve, reject) {\n promiseResolve = resolve;\n promiseReject = reject;\n });\n\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n args.push(function (err, value) {\n if (err) {\n promiseReject(err);\n } else {\n promiseResolve(value);\n }\n });\n\n try {\n original.apply(this, args);\n } catch (err) {\n promiseReject(err);\n }\n\n return promise;\n }\n\n Object.setPrototypeOf(fn, Object.getPrototypeOf(original));\n\n if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {\n value: fn, enumerable: false, writable: false, configurable: true\n });\n return Object.defineProperties(\n fn,\n getOwnPropertyDescriptors(original)\n );\n}\n\nexports.promisify.custom = kCustomPromisifiedSymbol\n\nfunction callbackifyOnRejected(reason, cb) {\n // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).\n // Because `null` is a special error value in callbacks which means \"no error\n // occurred\", we error-wrap so the callback consumer can distinguish between\n // \"the promise rejected with null\" or \"the promise fulfilled with undefined\".\n if (!reason) {\n var newReason = new Error('Promise was rejected with a falsy value');\n newReason.reason = reason;\n reason = newReason;\n }\n return cb(reason);\n}\n\nfunction callbackify(original) {\n if (typeof original !== 'function') {\n throw new TypeError('The \"original\" argument must be of type Function');\n }\n\n // We DO NOT return the promise as it gives the user a false sense that\n // the promise is actually somehow related to the callback's execution\n // and that the callback throwing will reject the promise.\n function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }\n\n Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));\n Object.defineProperties(callbackified,\n getOwnPropertyDescriptors(original));\n return callbackified;\n}\nexports.callbackify = callbackify;\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","module.exports = function isBuffer(arg) {\n return arg && typeof arg === 'object'\n && typeof arg.copy === 'function'\n && typeof arg.fill === 'function'\n && typeof arg.readUInt8 === 'function';\n}","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\nconst ClusterLeaf = require('./ClusterLeaf');\nconst Cluster = require('./Cluster');\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction simpleLink(cluster1, cluster2, disFun) {\n var m = 10e100;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = i; j < cluster2.length; j++) {\n var d = disFun(cluster1[i], cluster2[j]);\n m = Math.min(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction completeLink(cluster1, cluster2, disFun) {\n var m = -1;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = i; j < cluster2.length; j++) {\n var d = disFun(cluster1[i], cluster2[j]);\n m = Math.max(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction averageLink(cluster1, cluster2, disFun) {\n var m = 0;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n m += disFun(cluster1[i], cluster2[j]);\n }\n }\n return m / (cluster1.length * cluster2.length);\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction centroidLink(cluster1, cluster2, disFun) {\n var x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0;\n for (var i = 0; i < cluster1.length; i++) {\n x1 += cluster1[i][0];\n y1 += cluster1[i][1];\n }\n for (var j = 0; j < cluster2.length; j++) {\n x2 += cluster2[j][0];\n y2 += cluster2[j][1];\n }\n x1 /= cluster1.length;\n y1 /= cluster1.length;\n x2 /= cluster2.length;\n y2 /= cluster2.length;\n return disFun([x1, y1], [x2, y2]);\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction wardLink(cluster1, cluster2, disFun) {\n var x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0;\n for (var i = 0; i < cluster1.length; i++) {\n x1 += cluster1[i][0];\n y1 += cluster1[i][1];\n }\n for (var j = 0; j < cluster2.length; j++) {\n x2 += cluster2[j][0];\n y2 += cluster2[j][1];\n }\n x1 /= cluster1.length;\n y1 /= cluster1.length;\n x2 /= cluster2.length;\n y2 /= cluster2.length;\n return disFun([x1, y1], [x2, y2]) * cluster1.length * cluster2.length / (cluster1.length + cluster2.length);\n}\n\n/**\n * @private\n * Returns the most distant point and his distance\n * @param {Array >} splitting - Clusters to split\n * @param {Array >} data - Original data\n * @param {function} disFun - Distance function\n * @returns {{d: number, p: number}} - d: maximum difference between points, p: the point more distant\n */\nfunction diff(splitting, data, disFun) {\n var ans = {\n d: 0,\n p: 0\n };\n\n var Ci = new Array(splitting[0].length);\n for (var e = 0; e < splitting[0].length; e++) {\n Ci[e] = data[splitting[0][e]];\n }\n var Cj = new Array(splitting[1].length);\n for (var f = 0; f < splitting[1].length; f++) {\n Cj[f] = data[splitting[1][f]];\n }\n\n var dist, ndist;\n for (var i = 0; i < Ci.length; i++) {\n dist = 0;\n for (var j = 0; j < Ci.length; j++) {\n if (i !== j) {\n dist += disFun(Ci[i], Ci[j]);\n }\n }\n dist /= (Ci.length - 1);\n ndist = 0;\n for (var k = 0; k < Cj.length; k++) {\n ndist += disFun(Ci[i], Cj[k]);\n }\n ndist /= Cj.length;\n if ((dist - ndist) > ans.d) {\n ans.d = (dist - ndist);\n ans.p = i;\n }\n }\n return ans;\n}\n\nvar defaultOptions = {\n dist: euclidean,\n kind: 'single'\n};\n\n/**\n * @private\n * Intra-cluster distance\n * @param {Array} index\n * @param {Array} data\n * @param {function} disFun\n * @returns {number}\n */\nfunction intrDist(index, data, disFun) {\n var dist = 0,\n count = 0;\n for (var i = 0; i < index.length; i++) {\n for (var j = i; j < index.length; j++) {\n dist += disFun(data[index[i].index], data[index[j].index]);\n count++;\n }\n }\n return dist / count;\n}\n\n/**\n * Splits the higher level clusters\n * @param {Array >} data - Array of points to be clustered\n * @param {json} options\n * @constructor\n */\nfunction diana(data, options) {\n options = Object.assign({}, defaultOptions, options);\n if (typeof options.kind === 'string') {\n switch (options.kind) {\n case 'single':\n options.kind = simpleLink;\n break;\n case 'complete':\n options.kind = completeLink;\n break;\n case 'average':\n options.kind = averageLink;\n break;\n case 'centroid':\n options.kind = centroidLink;\n break;\n case 'ward':\n options.kind = wardLink;\n break;\n default:\n throw new RangeError('Unknown kind of similarity');\n }\n } else if (typeof options.kind !== 'function') {\n throw new TypeError('Undefined kind of similarity');\n }\n var tree = new Cluster();\n tree.children = new Array(data.length);\n tree.index = new Array(data.length);\n for (var ind = 0; ind < data.length; ind++) {\n tree.children[ind] = new ClusterLeaf(ind);\n tree.index[ind] = new ClusterLeaf(ind);\n }\n\n tree.distance = intrDist(tree.index, data, options.dist);\n var m, M, clId,\n dist, rebel;\n var list = [tree];\n while (list.length > 0) {\n M = 0;\n clId = 0;\n for (var i = 0; i < list.length; i++) {\n m = 0;\n for (var j = 0; j < list[i].length; j++) {\n for (var l = (j + 1); l < list[i].length; l++) {\n m = Math.max(options.dist(data[list[i].index[j].index], data[list[i].index[l].index]), m);\n }\n }\n if (m > M) {\n M = m;\n clId = i;\n }\n }\n M = 0;\n if (list[clId].index.length === 2) {\n list[clId].children = [list[clId].index[0], list[clId].index[1]];\n list[clId].distance = options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]);\n } else if (list[clId].index.length === 3) {\n list[clId].children = [list[clId].index[0], list[clId].index[1], list[clId].index[2]];\n var d = [\n options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]),\n options.dist(data[list[clId].index[1].index], data[list[clId].index[2].index])\n ];\n list[clId].distance = (d[0] + d[1]) / 2;\n } else {\n var C = new Cluster();\n var sG = new Cluster();\n var splitting = [new Array(list[clId].index.length), []];\n for (var spl = 0; spl < splitting[0].length; spl++) {\n splitting[0][spl] = spl;\n }\n for (var ii = 0; ii < splitting[0].length; ii++) {\n dist = 0;\n for (var jj = 0; jj < splitting[0].length; jj++) {\n if (ii !== jj) {\n dist += options.dist(data[list[clId].index[splitting[0][jj]].index], data[list[clId].index[splitting[0][ii]].index]);\n }\n }\n dist /= (splitting[0].length - 1);\n if (dist > M) {\n M = dist;\n rebel = ii;\n }\n }\n splitting[1] = [rebel];\n splitting[0].splice(rebel, 1);\n dist = diff(splitting, data, options.dist);\n while (dist.d > 0) {\n splitting[1].push(splitting[0][dist.p]);\n splitting[0].splice(dist.p, 1);\n dist = diff(splitting, data, options.dist);\n }\n var fData = new Array(splitting[0].length);\n C.index = new Array(splitting[0].length);\n for (var e = 0; e < fData.length; e++) {\n fData[e] = data[list[clId].index[splitting[0][e]].index];\n C.index[e] = list[clId].index[splitting[0][e]];\n C.children[e] = list[clId].index[splitting[0][e]];\n }\n var sData = new Array(splitting[1].length);\n sG.index = new Array(splitting[1].length);\n for (var f = 0; f < sData.length; f++) {\n sData[f] = data[list[clId].index[splitting[1][f]].index];\n sG.index[f] = list[clId].index[splitting[1][f]];\n sG.children[f] = list[clId].index[splitting[1][f]];\n }\n C.distance = intrDist(C.index, data, options.dist);\n sG.distance = intrDist(sG.index, data, options.dist);\n list.push(C);\n list.push(sG);\n list[clId].children = [C, sG];\n }\n list.splice(clId, 1);\n }\n return tree;\n}\n\nmodule.exports = diana;\n","'use strict';\nconst Kernel = require('ml-kernel');\nconst stat = require('ml-stat').array;\n\nvar defaultOptions = {\n C: 1,\n tol: 1e-4,\n maxPasses: 10,\n maxIterations: 10000,\n kernel: 'linear',\n alphaTol: 1e-6,\n random: Math.random,\n whitening: true\n};\n\n/**\n * Simplified version of the Sequential Minimal Optimization algorithm for training\n * support vector machines\n * @param {{Object}} options - SVM options\n * @param {Number} [options.C=1] - regularization parameter\n * @param {Number} [options.tol=1e-4] - numerical tolerance\n * @param {Number} [options.alphaTol=1e-6] - alpha tolerance, threshold to decide support vectors\n * @param {Number} [options.maxPasses=10] - max number of times to iterate over alphas without changing\n * @param {Number} [options.maxIterations=10000] - max number of iterations\n * @param {String} [options.kernel=linear] - the kind of kernel. {@link https://github.com/mljs/kernel/tree/1252de5f9012776e6e0eb06c7b434b8631fb21f0 List of kernels}\n * @param {Function} [options.random=Math.random] - custom random number generator\n * @constructor\n */\nfunction SVM(options) {\n this.options = Object.assign({}, defaultOptions, options);\n\n this.kernel = new Kernel(this.options.kernel, this.options.kernelOptions);\n this.b = 0;\n}\n\n/**\n * Train the SVM model\n * @param {Array >} features - training data features\n * @param {Array } labels - training data labels in the domain {1,-1}\n */\nSVM.prototype.train = function (features, labels) {\n if (features.length !== labels.length) {\n throw new Error('Features and labels should have the same length');\n }\n if (features.length < 2) {\n throw new Error('Cannot train with less than 2 observations');\n }\n this._trained = false;\n this._loaded = false;\n this.N = labels.length;\n this.D = features[0].length;\n if (this.options.whitening) {\n this.X = new Array(this.N);\n for (var i = 0; i < this.N; i++) {\n this.X[i] = new Array(this.D);\n }\n this.minMax = new Array(this.D);\n // Apply normalization and keep normalization parameters\n for (var j = 0; j < this.D; j++) {\n var d = new Array(this.N);\n for (i = 0; i < this.N; i++) {\n d[i] = features[i][j];\n }\n this.minMax[j] = stat.minMax(d);\n for (i = 0; i < this.N; i++) {\n this.X[i][j] = (features[i][j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min);\n }\n }\n } else {\n this.X = features;\n }\n this.Y = labels;\n this.b = 0;\n this.W = undefined;\n\n var kernel = this.kernel.compute(this.X);\n var m = labels.length;\n var alpha = new Array(m).fill(0);\n this.alphas = alpha;\n for (var a = 0; a < m; a++)\n alpha[a] = 0;\n\n var b1 = 0,\n b2 = 0,\n iter = 0,\n passes = 0,\n Ei = 0,\n Ej = 0,\n ai = 0,\n aj = 0,\n L = 0,\n H = 0,\n eta = 0;\n\n while (passes < this.options.maxPasses && iter < this.options.maxIterations) {\n var numChange = 0;\n for (i = 0; i < m; i++) {\n Ei = this._marginOnePrecomputed(i, kernel) - labels[i];\n if (labels[i] * Ei < -this.options.tol && alpha[i] < this.options.C || labels[i] * Ei > this.options.tol && alpha[i] > 0) {\n j = i;\n while (j === i) j = Math.floor(this.options.random() * m);\n Ej = this._marginOnePrecomputed(j, kernel) - labels[j];\n ai = alpha[i];\n aj = alpha[j];\n if (labels[i] === labels[j]) {\n L = Math.max(0, ai + aj - this.options.C);\n H = Math.min(this.options.C, ai + aj);\n } else {\n L = Math.max(0, aj - ai);\n H = Math.min(this.options.C, this.options.C + aj + ai);\n }\n if (Math.abs(L - H) < 1e-4) continue;\n\n eta = 2 * kernel[i][j] - kernel[i][i] - kernel[j][j];\n if (eta >= 0) continue;\n var newaj = alpha[j] - labels[j] * (Ei - Ej) / eta;\n if (newaj > H)\n newaj = H;\n else if (newaj < L)\n newaj = L;\n if (Math.abs(aj - newaj) < 10e-4) continue;\n alpha[j] = newaj;\n alpha[i] = alpha[i] + labels[i] * labels[j] * (aj - newaj);\n b1 = this.b - Ei - labels[i] * (alpha[i] - ai) * kernel[i][i] - labels[j] * (alpha[j] - aj) * kernel[i][j];\n b2 = this.b - Ej - labels[i] * (alpha[i] - ai) * kernel[i][j] - labels[j] * (alpha[j] - aj) * kernel[j][j];\n this.b = (b1 + b2) / 2;\n if (alpha[i] < this.options.C && alpha[i] > 0) this.b = b1;\n if (alpha[j] < this.options.C && alpha[j] > 0) this.b = b2;\n numChange += 1;\n }\n }\n iter++;\n if (numChange === 0)\n passes += 1;\n else\n passes = 0;\n }\n if (iter === this.options.maxIterations) {\n throw new Error('max iterations reached');\n }\n\n this.iterations = iter;\n\n // Compute the weights (useful for fast decision on new test instances when linear SVM)\n if (this.options.kernel === 'linear') {\n this.W = new Array(this.D);\n for (var r = 0; r < this.D; r++) {\n this.W[r] = 0;\n for (var w = 0; w < m; w++)\n this.W[r] += labels[w] * alpha[w] * this.X[w][r];\n }\n }\n\n // Keep only support vectors\n // It will compute decision on new test instances faster\n // We also keep the index of the support vectors\n // in the original data\n var nX = [];\n var nY = [];\n var nAlphas = [];\n this._supportVectorIdx = [];\n for (i = 0; i < this.N; i++) {\n if (this.alphas[i] > this.options.alphaTol) {\n nX.push(this.X[i]);\n nY.push(labels[i]);\n nAlphas.push(this.alphas[i]);\n this._supportVectorIdx.push(i);\n\n }\n }\n this.X = nX;\n this.Y = nY;\n this.N = nX.length;\n this.alphas = nAlphas;\n\n\n // A flag to say this SVM has been trained\n this._trained = true;\n};\n\n/**\n * Get prediction ({-1,1}) given one observation's features.\n * @private\n * @param p The observation's features.\n * @returns {number} Classification result ({-1,1})\n */\nSVM.prototype.predictOne = function (p) {\n var margin = this.marginOne(p);\n return margin > 0 ? 1 : -1;\n};\n\n/**\n * Predict the classification outcome of a trained svm given one or several observations' features.\n * @param {Array} features - The observation(s)' features\n * @returns {Array|Number} An array of {-1, 1} if several observations are given or a number if one observation\n * is given\n */\nSVM.prototype.predict = function (features) {\n if (!this._trained && !this._loaded) throw new Error('Cannot predict, you need to train the SVM first');\n if (Array.isArray(features) && Array.isArray(features[0])) {\n return features.map(this.predictOne.bind(this));\n } else {\n return this.predictOne(features);\n }\n};\n\n/**\n * Get margin given one observation's features\n * @private\n * @param {Array} features - Features\n * @returns {Number} - The computed margin\n */\nSVM.prototype.marginOne = function (features, noWhitening) {\n // Apply normalization\n if (this.options.whitening && !noWhitening) {\n features = this._applyWhitening(features);\n }\n var ans = this.b, i;\n if (this.options.kernel === 'linear' && this.W) {\n // Use weights, it's faster\n for (i = 0; i < this.W.length; i++) {\n ans += this.W[i] * features[i];\n }\n } else {\n for (i = 0; i < this.N; i++) {\n ans += this.alphas[i] * this.Y[i] * this.kernel.compute([features], [this.X[i]])[0][0];\n }\n }\n return ans;\n};\n\n\n/**\n * Get a margin using the precomputed kernel. Much faster than normal margin computation\n * @private\n * @param {Number} index - Train data index\n * @param {Array< Array >} kernel - The precomputed kernel\n * @returns {number} Computed margin\n * @private\n */\nSVM.prototype._marginOnePrecomputed = function (index, kernel) {\n var ans = this.b, i;\n for (i = 0; i < this.N; i++) {\n ans += this.alphas[i] * this.Y[i] * kernel[index][i];\n }\n return ans;\n};\n\n\n/**\n * Returns the margin of one or several observations given its features\n * @param {Array >|Array} features - Features from on or several observations.\n * @returns {Number|Array} The computed margin. Is an Array if several observations' features given, or a Number if\n * only one observation's features given\n */\nSVM.prototype.margin = function (features) {\n if (Array.isArray(features)) {\n return features.map(this.marginOne.bind(this));\n } else {\n return this.marginOne(features);\n }\n};\n\n/**\n * Get support vectors indexes of the trained classifier. WARINNG: this method does not work for svm instances\n * created from {@link #SVM.load load} if linear kernel\n * @returns {Array} The indices in the training vector of the support vectors\n */\nSVM.prototype.supportVectors = function () {\n if (!this._trained && !this._loaded) throw new Error('Cannot get support vectors, you need to train the SVM first');\n if (this._loaded && this.options.kernel === 'linear') throw new Error('Cannot get support vectors from saved linear model, you need to train the SVM to have them');\n return this._supportVectorIdx;\n};\n\n/**\n * Create a SVM instance from a saved model\n * @param {Object} model - Object such as returned by a trained SVM instance with {@link #SVM#toJSON toJSON}\n * @returns {SVM} Instance of svm classifier\n */\nSVM.load = function (model) {\n this._loaded = true;\n this._trained = false;\n var svm = new SVM(model.options);\n if (model.options.kernel === 'linear') {\n svm.W = model.W.slice();\n svm.D = svm.W.length;\n } else {\n svm.X = model.X.slice();\n svm.Y = model.Y.slice();\n svm.alphas = model.alphas.slice();\n svm.N = svm.X.length;\n svm.D = svm.X[0].length;\n }\n svm.minMax = model.minMax;\n svm.b = model.b;\n svm._loaded = true;\n svm._trained = false;\n return svm;\n};\n\n/**\n * Export the minimal object that enables to reload the model\n * @returns {Object} Model object that can be reused with {@link #SVM.load load}\n */\nSVM.prototype.toJSON = function () {\n if (!this._trained && !this._loaded) throw new Error('Cannot export, you need to train the SVM first');\n var model = {};\n model.options = Object.assign({}, this.options);\n model.b = this.b;\n model.minMax = this.minMax;\n if (model.options.kernel === 'linear') {\n model.W = this.W.slice();\n } else {\n // Exporting non-linear models is heavier\n model.X = this.X.slice();\n model.Y = this.Y.slice();\n model.alphas = this.alphas.slice();\n }\n return model;\n};\n\nSVM.prototype._applyWhitening = function (features) {\n if (!this.minMax) throw new Error('Could not apply whitening');\n var whitened = new Array(features.length);\n for (var j = 0; j < features.length; j++) {\n whitened[j] = (features[j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min);\n }\n return whitened;\n};\n\nmodule.exports = SVM;\n","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass GaussianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = GaussianKernel;\n","'use strict';\n\nconst defaultOptions = {\n degree: 1,\n constant: 1,\n scale: 1\n};\n\nclass PolynomialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n\n this.degree = options.degree;\n this.constant = options.constant;\n this.scale = options.scale;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.pow(this.scale * sum + this.constant, this.degree);\n }\n}\n\nmodule.exports = PolynomialKernel;\n","'use strict';\n\nconst defaultOptions = {\n sigma: 1,\n degree: 1\n};\n\nclass ANOVAKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.degree = options.degree;\n }\n\n compute(x, y) {\n var sum = 0;\n var len = Math.min(x.length, y.length);\n for (var i = 1; i <= len; ++i) {\n sum += Math.pow(Math.exp(-this.sigma * Math.pow(Math.pow(x[i - 1], i) -\n Math.pow(y[i - 1], i), 2)), this.degree);\n }\n return sum;\n }\n}\n\nmodule.exports = ANOVAKernel;\n","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass CauchyKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n return 1 / (1 + squaredEuclidean(x, y) / (this.sigma * this.sigma));\n }\n}\n\nmodule.exports = CauchyKernel;\n","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass ExponentialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = ExponentialKernel;\n","'use strict';\n\nclass HistogramIntersectionKernel {\n compute(x, y) {\n var min = Math.min(x.length, y.length);\n var sum = 0;\n for (var i = 0; i < min; ++i) {\n sum += Math.min(x[i], y[i]);\n }\n\n return sum;\n }\n}\n\nmodule.exports = HistogramIntersectionKernel;\n","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass LaplacianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.sigma);\n }\n}\n\nmodule.exports = LaplacianKernel;\n","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass MultiquadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n return Math.sqrt(squaredEuclidean(x, y) + this.constant * this.constant);\n }\n}\n\nmodule.exports = MultiquadraticKernel;\n","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass RationalQuadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return 1 - (distance / (distance + this.constant));\n }\n}\n\nmodule.exports = RationalQuadraticKernel;\n","'use strict';\n\nconst defaultOptions = {\n alpha: 0.01,\n constant: -Math.E\n};\n\nclass SigmoidKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.alpha = options.alpha;\n this.constant = options.constant;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.tanh(this.alpha * sum + this.constant);\n }\n}\n\nmodule.exports = SigmoidKernel;\n","'use strict';\n\nconst ConfusionMatrix = require('ml-confusion-matrix');\n\nconst CV = {};\nconst combinations = require('ml-combinations');\n\n/**\n * Performs a leave-one-out cross-validation (LOO-CV) of the given samples. In LOO-CV, 1 observation is used as the\n * validation set while the rest is used as the training set. This is repeated once for each observation. LOO-CV is a\n * special case of LPO-CV. @see leavePout\n * @param {function} Classifier - The classifier's constructor to use for the cross validation. Expect ml-classifier\n * api.\n * @param {Array} features - The features for all samples of the data-set\n * @param {Array} labels - The classification class of all samples of the data-set\n * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated.\n * @return {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.leaveOneOut = function (Classifier, features, labels, classifierOptions) {\n if (typeof labels === 'function') {\n var callback = labels;\n labels = features;\n features = Classifier;\n return CV.leavePOut(features, labels, 1, callback);\n }\n return CV.leavePOut(Classifier, features, labels, classifierOptions, 1);\n};\n\n\n/**\n * Performs a leave-p-out cross-validation (LPO-CV) of the given samples. In LPO-CV, p observations are used as the\n * validation set while the rest is used as the training set. This is repeated as many times as there are possible\n * ways to combine p observations from the set (unordered without replacement). Be aware that for relatively small\n * data-set size this can require a very large number of training and testing to do!\n * @param {function} Classifier - The classifier's constructor to use for the cross validation. Expect ml-classifier\n * api.\n * @param {Array} features - The features for all samples of the data-set\n * @param {Array} labels - The classification class of all samples of the data-set\n * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated.\n * @param {number} p - The size of the validation sub-samples' set\n * @return {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.leavePOut = function (Classifier, features, labels, classifierOptions, p) {\n if (typeof classifierOptions === 'function') {\n var callback = classifierOptions;\n p = labels;\n labels = features;\n features = Classifier;\n }\n check(features, labels);\n const distinct = getDistinct(labels);\n const confusionMatrix = initMatrix(distinct.length, distinct.length);\n\n var N = features.length;\n var gen = combinations(p, N);\n var allIdx = new Array(N);\n for (let i = 0; i < N; i++) {\n allIdx[i] = i;\n }\n for (const testIdx of gen) {\n var trainIdx = allIdx.slice();\n\n for (let i = testIdx.length - 1; i >= 0; i--) {\n trainIdx.splice(testIdx[i], 1);\n }\n\n if (callback) {\n validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback);\n } else {\n validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct);\n }\n\n }\n\n return new ConfusionMatrix(confusionMatrix, distinct);\n};\n\n/**\n * Performs k-fold cross-validation (KF-CV). KF-CV separates the data-set into k random equally sized partitions, and\n * uses each as a validation set, with all other partitions used in the training set. Observations left over from if k\n * does not divide the number of observations are left out of the cross-validation process.\n * @param {function} Classifier - The classifier's to use for the cross validation. Expect ml-classifier api.\n * @param {Array} features - The features for all samples of the data-set\n * @param {Array} labels - The classification class of all samples of the data-set\n * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated.\n * @param {number} k - The number of partitions to create\n * @return {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.kFold = function (Classifier, features, labels, classifierOptions, k) {\n if (typeof classifierOptions === 'function') {\n var callback = classifierOptions;\n k = labels;\n labels = features;\n features = Classifier;\n }\n check(features, labels);\n const distinct = getDistinct(labels);\n const confusionMatrix = initMatrix(distinct.length, distinct.length);\n var N = features.length;\n var allIdx = new Array(N);\n for (var i = 0; i < N; i++) {\n allIdx[i] = i;\n }\n\n var l = Math.floor(N / k);\n // create random k-folds\n var current = [];\n var folds = [];\n while (allIdx.length) {\n var randi = Math.floor(Math.random() * allIdx.length);\n current.push(allIdx[randi]);\n allIdx.splice(randi, 1);\n if (current.length === l) {\n folds.push(current);\n current = [];\n }\n }\n if (current.length) folds.push(current);\n folds = folds.slice(0, k);\n\n\n for (i = 0; i < folds.length; i++) {\n var testIdx = folds[i];\n var trainIdx = [];\n for (var j = 0; j < folds.length; j++) {\n if (j !== i) trainIdx = trainIdx.concat(folds[j]);\n }\n\n if (callback) {\n validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback);\n } else {\n validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct);\n }\n }\n\n return new ConfusionMatrix(confusionMatrix, distinct);\n};\n\nfunction check(features, labels) {\n if (features.length !== labels.length) {\n throw new Error('features and labels should have the same length');\n }\n}\n\nfunction initMatrix(rows, columns) {\n return new Array(rows).fill(0).map(() => new Array(columns).fill(0));\n}\n\nfunction getDistinct(arr) {\n var s = new Set();\n for (let i = 0; i < arr.length; i++) {\n s.add(arr[i]);\n }\n return Array.from(s);\n}\n\nfunction validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct) {\n const {testFeatures, trainFeatures, testLabels, trainLabels} = getTrainTest(features, labels, testIdx, trainIdx);\n\n var classifier;\n if (Classifier.prototype.train) {\n classifier = new Classifier(classifierOptions);\n classifier.train(trainFeatures, trainLabels);\n } else {\n classifier = new Classifier(trainFeatures, trainLabels, classifierOptions);\n }\n\n var predictedLabels = classifier.predict(testFeatures);\n updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct);\n}\n\nfunction validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback) {\n const {testFeatures, trainFeatures, testLabels, trainLabels} = getTrainTest(features, labels, testIdx, trainIdx);\n const predictedLabels = callback(trainFeatures, trainLabels, testFeatures);\n updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct);\n}\n\nfunction updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct) {\n\n for (var i = 0; i < predictedLabels.length; i++) {\n const actualIdx = distinct.indexOf(testLabels[i]);\n const predictedIdx = distinct.indexOf(predictedLabels[i]);\n if (actualIdx < 0 || predictedIdx < 0) {\n // eslint-disable-next-line no-console\n console.warn(`ignore unknown predicted label ${predictedLabels[i]}`);\n }\n confusionMatrix[actualIdx][predictedIdx]++;\n }\n}\n\n\nfunction getTrainTest(features, labels, testIdx, trainIdx) {\n return {\n testFeatures: testIdx.map(function (index) {\n return features[index];\n }),\n trainFeatures: trainIdx.map(function (index) {\n return features[index];\n }),\n testLabels: testIdx.map(function (index) {\n return labels[index];\n }),\n trainLabels: trainIdx.map(function (index) {\n return labels[index];\n })\n };\n}\n\nmodule.exports = CV;\n","(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? factory() :\n\ttypeof define === 'function' && define.amd ? define(factory) :\n\t(factory());\n}(this, (function () { 'use strict';\n\n\tfunction createCommonjsModule(fn, module) {\n\t\treturn module = { exports: {} }, fn(module, module.exports), module.exports;\n\t}\n\n\tvar runtime = createCommonjsModule(function (module) {\n\t/**\n\t * Copyright (c) 2014-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t */\n\n\t!(function(global) {\n\n\t var Op = Object.prototype;\n\t var hasOwn = Op.hasOwnProperty;\n\t var undefined; // More compressible than void 0.\n\t var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n\t var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n\t var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n\t var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\t var runtime = global.regeneratorRuntime;\n\t if (runtime) {\n\t {\n\t // If regeneratorRuntime is defined globally and we're in a module,\n\t // make the exports object identical to regeneratorRuntime.\n\t module.exports = runtime;\n\t }\n\t // Don't bother evaluating the rest of this file if the runtime was\n\t // already defined globally.\n\t return;\n\t }\n\n\t // Define the runtime globally (as expected by generated code) as either\n\t // module.exports (if we're in a module) or a new, empty object.\n\t runtime = global.regeneratorRuntime = module.exports;\n\n\t function wrap(innerFn, outerFn, self, tryLocsList) {\n\t // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n\t var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n\t var generator = Object.create(protoGenerator.prototype);\n\t var context = new Context(tryLocsList || []);\n\n\t // The ._invoke method unifies the implementations of the .next,\n\t // .throw, and .return methods.\n\t generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n\t return generator;\n\t }\n\t runtime.wrap = wrap;\n\n\t // Try/catch helper to minimize deoptimizations. Returns a completion\n\t // record like context.tryEntries[i].completion. This interface could\n\t // have been (and was previously) designed to take a closure to be\n\t // invoked without arguments, but in all the cases we care about we\n\t // already have an existing method we want to call, so there's no need\n\t // to create a new function object. We can even get away with assuming\n\t // the method takes exactly one argument, since that happens to be true\n\t // in every case, so we don't have to touch the arguments object. The\n\t // only additional allocation required is the completion record, which\n\t // has a stable shape and so hopefully should be cheap to allocate.\n\t function tryCatch(fn, obj, arg) {\n\t try {\n\t return { type: \"normal\", arg: fn.call(obj, arg) };\n\t } catch (err) {\n\t return { type: \"throw\", arg: err };\n\t }\n\t }\n\n\t var GenStateSuspendedStart = \"suspendedStart\";\n\t var GenStateSuspendedYield = \"suspendedYield\";\n\t var GenStateExecuting = \"executing\";\n\t var GenStateCompleted = \"completed\";\n\n\t // Returning this object from the innerFn has the same effect as\n\t // breaking out of the dispatch switch statement.\n\t var ContinueSentinel = {};\n\n\t // Dummy constructor functions that we use as the .constructor and\n\t // .constructor.prototype properties for functions that return Generator\n\t // objects. For full spec compliance, you may wish to configure your\n\t // minifier not to mangle the names of these two functions.\n\t function Generator() {}\n\t function GeneratorFunction() {}\n\t function GeneratorFunctionPrototype() {}\n\n\t // This is a polyfill for %IteratorPrototype% for environments that\n\t // don't natively support it.\n\t var IteratorPrototype = {};\n\t IteratorPrototype[iteratorSymbol] = function () {\n\t return this;\n\t };\n\n\t var getProto = Object.getPrototypeOf;\n\t var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n\t if (NativeIteratorPrototype &&\n\t NativeIteratorPrototype !== Op &&\n\t hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n\t // This environment has a native %IteratorPrototype%; use it instead\n\t // of the polyfill.\n\t IteratorPrototype = NativeIteratorPrototype;\n\t }\n\n\t var Gp = GeneratorFunctionPrototype.prototype =\n\t Generator.prototype = Object.create(IteratorPrototype);\n\t GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n\t GeneratorFunctionPrototype.constructor = GeneratorFunction;\n\t GeneratorFunctionPrototype[toStringTagSymbol] =\n\t GeneratorFunction.displayName = \"GeneratorFunction\";\n\n\t // Helper for defining the .next, .throw, and .return methods of the\n\t // Iterator interface in terms of a single ._invoke method.\n\t function defineIteratorMethods(prototype) {\n\t [\"next\", \"throw\", \"return\"].forEach(function(method) {\n\t prototype[method] = function(arg) {\n\t return this._invoke(method, arg);\n\t };\n\t });\n\t }\n\n\t runtime.isGeneratorFunction = function(genFun) {\n\t var ctor = typeof genFun === \"function\" && genFun.constructor;\n\t return ctor\n\t ? ctor === GeneratorFunction ||\n\t // For the native GeneratorFunction constructor, the best we can\n\t // do is to check its .name property.\n\t (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n\t : false;\n\t };\n\n\t runtime.mark = function(genFun) {\n\t if (Object.setPrototypeOf) {\n\t Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n\t } else {\n\t genFun.__proto__ = GeneratorFunctionPrototype;\n\t if (!(toStringTagSymbol in genFun)) {\n\t genFun[toStringTagSymbol] = \"GeneratorFunction\";\n\t }\n\t }\n\t genFun.prototype = Object.create(Gp);\n\t return genFun;\n\t };\n\n\t // Within the body of any async function, `await x` is transformed to\n\t // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n\t // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n\t // meant to be awaited.\n\t runtime.awrap = function(arg) {\n\t return { __await: arg };\n\t };\n\n\t function AsyncIterator(generator) {\n\t function invoke(method, arg, resolve, reject) {\n\t var record = tryCatch(generator[method], generator, arg);\n\t if (record.type === \"throw\") {\n\t reject(record.arg);\n\t } else {\n\t var result = record.arg;\n\t var value = result.value;\n\t if (value &&\n\t typeof value === \"object\" &&\n\t hasOwn.call(value, \"__await\")) {\n\t return Promise.resolve(value.__await).then(function(value) {\n\t invoke(\"next\", value, resolve, reject);\n\t }, function(err) {\n\t invoke(\"throw\", err, resolve, reject);\n\t });\n\t }\n\n\t return Promise.resolve(value).then(function(unwrapped) {\n\t // When a yielded Promise is resolved, its final value becomes\n\t // the .value of the Promise<{value,done}> result for the\n\t // current iteration. If the Promise is rejected, however, the\n\t // result for this iteration will be rejected with the same\n\t // reason. Note that rejections of yielded Promises are not\n\t // thrown back into the generator function, as is the case\n\t // when an awaited Promise is rejected. This difference in\n\t // behavior between yield and await is important, because it\n\t // allows the consumer to decide what to do with the yielded\n\t // rejection (swallow it and continue, manually .throw it back\n\t // into the generator, abandon iteration, whatever). With\n\t // await, by contrast, there is no opportunity to examine the\n\t // rejection reason outside the generator function, so the\n\t // only option is to throw it from the await expression, and\n\t // let the generator function handle the exception.\n\t result.value = unwrapped;\n\t resolve(result);\n\t }, reject);\n\t }\n\t }\n\n\t var previousPromise;\n\n\t function enqueue(method, arg) {\n\t function callInvokeWithMethodAndArg() {\n\t return new Promise(function(resolve, reject) {\n\t invoke(method, arg, resolve, reject);\n\t });\n\t }\n\n\t return previousPromise =\n\t // If enqueue has been called before, then we want to wait until\n\t // all previous Promises have been resolved before calling invoke,\n\t // so that results are always delivered in the correct order. If\n\t // enqueue has not been called before, then it is important to\n\t // call invoke immediately, without waiting on a callback to fire,\n\t // so that the async generator function has the opportunity to do\n\t // any necessary setup in a predictable way. This predictability\n\t // is why the Promise constructor synchronously invokes its\n\t // executor callback, and why async functions synchronously\n\t // execute code before the first await. Since we implement simple\n\t // async functions in terms of async generators, it is especially\n\t // important to get this right, even though it requires care.\n\t previousPromise ? previousPromise.then(\n\t callInvokeWithMethodAndArg,\n\t // Avoid propagating failures to Promises returned by later\n\t // invocations of the iterator.\n\t callInvokeWithMethodAndArg\n\t ) : callInvokeWithMethodAndArg();\n\t }\n\n\t // Define the unified helper method that is used to implement .next,\n\t // .throw, and .return (see defineIteratorMethods).\n\t this._invoke = enqueue;\n\t }\n\n\t defineIteratorMethods(AsyncIterator.prototype);\n\t AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n\t return this;\n\t };\n\t runtime.AsyncIterator = AsyncIterator;\n\n\t // Note that simple async functions are implemented on top of\n\t // AsyncIterator objects; they just return a Promise for the value of\n\t // the final result produced by the iterator.\n\t runtime.async = function(innerFn, outerFn, self, tryLocsList) {\n\t var iter = new AsyncIterator(\n\t wrap(innerFn, outerFn, self, tryLocsList)\n\t );\n\n\t return runtime.isGeneratorFunction(outerFn)\n\t ? iter // If outerFn is a generator, return the full iterator.\n\t : iter.next().then(function(result) {\n\t return result.done ? result.value : iter.next();\n\t });\n\t };\n\n\t function makeInvokeMethod(innerFn, self, context) {\n\t var state = GenStateSuspendedStart;\n\n\t return function invoke(method, arg) {\n\t if (state === GenStateExecuting) {\n\t throw new Error(\"Generator is already running\");\n\t }\n\n\t if (state === GenStateCompleted) {\n\t if (method === \"throw\") {\n\t throw arg;\n\t }\n\n\t // Be forgiving, per 25.3.3.3.3 of the spec:\n\t // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n\t return doneResult();\n\t }\n\n\t context.method = method;\n\t context.arg = arg;\n\n\t while (true) {\n\t var delegate = context.delegate;\n\t if (delegate) {\n\t var delegateResult = maybeInvokeDelegate(delegate, context);\n\t if (delegateResult) {\n\t if (delegateResult === ContinueSentinel) continue;\n\t return delegateResult;\n\t }\n\t }\n\n\t if (context.method === \"next\") {\n\t // Setting context._sent for legacy support of Babel's\n\t // function.sent implementation.\n\t context.sent = context._sent = context.arg;\n\n\t } else if (context.method === \"throw\") {\n\t if (state === GenStateSuspendedStart) {\n\t state = GenStateCompleted;\n\t throw context.arg;\n\t }\n\n\t context.dispatchException(context.arg);\n\n\t } else if (context.method === \"return\") {\n\t context.abrupt(\"return\", context.arg);\n\t }\n\n\t state = GenStateExecuting;\n\n\t var record = tryCatch(innerFn, self, context);\n\t if (record.type === \"normal\") {\n\t // If an exception is thrown from innerFn, we leave state ===\n\t // GenStateExecuting and loop back for another invocation.\n\t state = context.done\n\t ? GenStateCompleted\n\t : GenStateSuspendedYield;\n\n\t if (record.arg === ContinueSentinel) {\n\t continue;\n\t }\n\n\t return {\n\t value: record.arg,\n\t done: context.done\n\t };\n\n\t } else if (record.type === \"throw\") {\n\t state = GenStateCompleted;\n\t // Dispatch the exception by looping back around to the\n\t // context.dispatchException(context.arg) call above.\n\t context.method = \"throw\";\n\t context.arg = record.arg;\n\t }\n\t }\n\t };\n\t }\n\n\t // Call delegate.iterator[context.method](context.arg) and handle the\n\t // result, either by returning a { value, done } result from the\n\t // delegate iterator, or by modifying context.method and context.arg,\n\t // setting context.delegate to null, and returning the ContinueSentinel.\n\t function maybeInvokeDelegate(delegate, context) {\n\t var method = delegate.iterator[context.method];\n\t if (method === undefined) {\n\t // A .throw or .return when the delegate iterator has no .throw\n\t // method always terminates the yield* loop.\n\t context.delegate = null;\n\n\t if (context.method === \"throw\") {\n\t if (delegate.iterator.return) {\n\t // If the delegate iterator has a return method, give it a\n\t // chance to clean up.\n\t context.method = \"return\";\n\t context.arg = undefined;\n\t maybeInvokeDelegate(delegate, context);\n\n\t if (context.method === \"throw\") {\n\t // If maybeInvokeDelegate(context) changed context.method from\n\t // \"return\" to \"throw\", let that override the TypeError below.\n\t return ContinueSentinel;\n\t }\n\t }\n\n\t context.method = \"throw\";\n\t context.arg = new TypeError(\n\t \"The iterator does not provide a 'throw' method\");\n\t }\n\n\t return ContinueSentinel;\n\t }\n\n\t var record = tryCatch(method, delegate.iterator, context.arg);\n\n\t if (record.type === \"throw\") {\n\t context.method = \"throw\";\n\t context.arg = record.arg;\n\t context.delegate = null;\n\t return ContinueSentinel;\n\t }\n\n\t var info = record.arg;\n\n\t if (! info) {\n\t context.method = \"throw\";\n\t context.arg = new TypeError(\"iterator result is not an object\");\n\t context.delegate = null;\n\t return ContinueSentinel;\n\t }\n\n\t if (info.done) {\n\t // Assign the result of the finished delegate to the temporary\n\t // variable specified by delegate.resultName (see delegateYield).\n\t context[delegate.resultName] = info.value;\n\n\t // Resume execution at the desired location (see delegateYield).\n\t context.next = delegate.nextLoc;\n\n\t // If context.method was \"throw\" but the delegate handled the\n\t // exception, let the outer generator proceed normally. If\n\t // context.method was \"next\", forget context.arg since it has been\n\t // \"consumed\" by the delegate iterator. If context.method was\n\t // \"return\", allow the original .return call to continue in the\n\t // outer generator.\n\t if (context.method !== \"return\") {\n\t context.method = \"next\";\n\t context.arg = undefined;\n\t }\n\n\t } else {\n\t // Re-yield the result returned by the delegate method.\n\t return info;\n\t }\n\n\t // The delegate iterator is finished, so forget it and continue with\n\t // the outer generator.\n\t context.delegate = null;\n\t return ContinueSentinel;\n\t }\n\n\t // Define Generator.prototype.{next,throw,return} in terms of the\n\t // unified ._invoke helper method.\n\t defineIteratorMethods(Gp);\n\n\t Gp[toStringTagSymbol] = \"Generator\";\n\n\t // A Generator should always return itself as the iterator object when the\n\t // @@iterator function is called on it. Some browsers' implementations of the\n\t // iterator prototype chain incorrectly implement this, causing the Generator\n\t // object to not be returned from this call. This ensures that doesn't happen.\n\t // See https://github.com/facebook/regenerator/issues/274 for more details.\n\t Gp[iteratorSymbol] = function() {\n\t return this;\n\t };\n\n\t Gp.toString = function() {\n\t return \"[object Generator]\";\n\t };\n\n\t function pushTryEntry(locs) {\n\t var entry = { tryLoc: locs[0] };\n\n\t if (1 in locs) {\n\t entry.catchLoc = locs[1];\n\t }\n\n\t if (2 in locs) {\n\t entry.finallyLoc = locs[2];\n\t entry.afterLoc = locs[3];\n\t }\n\n\t this.tryEntries.push(entry);\n\t }\n\n\t function resetTryEntry(entry) {\n\t var record = entry.completion || {};\n\t record.type = \"normal\";\n\t delete record.arg;\n\t entry.completion = record;\n\t }\n\n\t function Context(tryLocsList) {\n\t // The root entry object (effectively a try statement without a catch\n\t // or a finally block) gives us a place to store values thrown from\n\t // locations where there is no enclosing try statement.\n\t this.tryEntries = [{ tryLoc: \"root\" }];\n\t tryLocsList.forEach(pushTryEntry, this);\n\t this.reset(true);\n\t }\n\n\t runtime.keys = function(object) {\n\t var keys = [];\n\t for (var key in object) {\n\t keys.push(key);\n\t }\n\t keys.reverse();\n\n\t // Rather than returning an object with a next method, we keep\n\t // things simple and return the next function itself.\n\t return function next() {\n\t while (keys.length) {\n\t var key = keys.pop();\n\t if (key in object) {\n\t next.value = key;\n\t next.done = false;\n\t return next;\n\t }\n\t }\n\n\t // To avoid creating an additional object, we just hang the .value\n\t // and .done properties off the next function object itself. This\n\t // also ensures that the minifier will not anonymize the function.\n\t next.done = true;\n\t return next;\n\t };\n\t };\n\n\t function values(iterable) {\n\t if (iterable) {\n\t var iteratorMethod = iterable[iteratorSymbol];\n\t if (iteratorMethod) {\n\t return iteratorMethod.call(iterable);\n\t }\n\n\t if (typeof iterable.next === \"function\") {\n\t return iterable;\n\t }\n\n\t if (!isNaN(iterable.length)) {\n\t var i = -1, next = function next() {\n\t while (++i < iterable.length) {\n\t if (hasOwn.call(iterable, i)) {\n\t next.value = iterable[i];\n\t next.done = false;\n\t return next;\n\t }\n\t }\n\n\t next.value = undefined;\n\t next.done = true;\n\n\t return next;\n\t };\n\n\t return next.next = next;\n\t }\n\t }\n\n\t // Return an iterator with no values.\n\t return { next: doneResult };\n\t }\n\t runtime.values = values;\n\n\t function doneResult() {\n\t return { value: undefined, done: true };\n\t }\n\n\t Context.prototype = {\n\t constructor: Context,\n\n\t reset: function(skipTempReset) {\n\t this.prev = 0;\n\t this.next = 0;\n\t // Resetting context._sent for legacy support of Babel's\n\t // function.sent implementation.\n\t this.sent = this._sent = undefined;\n\t this.done = false;\n\t this.delegate = null;\n\n\t this.method = \"next\";\n\t this.arg = undefined;\n\n\t this.tryEntries.forEach(resetTryEntry);\n\n\t if (!skipTempReset) {\n\t for (var name in this) {\n\t // Not sure about the optimal order of these conditions:\n\t if (name.charAt(0) === \"t\" &&\n\t hasOwn.call(this, name) &&\n\t !isNaN(+name.slice(1))) {\n\t this[name] = undefined;\n\t }\n\t }\n\t }\n\t },\n\n\t stop: function() {\n\t this.done = true;\n\n\t var rootEntry = this.tryEntries[0];\n\t var rootRecord = rootEntry.completion;\n\t if (rootRecord.type === \"throw\") {\n\t throw rootRecord.arg;\n\t }\n\n\t return this.rval;\n\t },\n\n\t dispatchException: function(exception) {\n\t if (this.done) {\n\t throw exception;\n\t }\n\n\t var context = this;\n\t function handle(loc, caught) {\n\t record.type = \"throw\";\n\t record.arg = exception;\n\t context.next = loc;\n\n\t if (caught) {\n\t // If the dispatched exception was caught by a catch block,\n\t // then let that catch block handle the exception normally.\n\t context.method = \"next\";\n\t context.arg = undefined;\n\t }\n\n\t return !! caught;\n\t }\n\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t var record = entry.completion;\n\n\t if (entry.tryLoc === \"root\") {\n\t // Exception thrown outside of any try block that could handle\n\t // it, so set the completion value of the entire function to\n\t // throw the exception.\n\t return handle(\"end\");\n\t }\n\n\t if (entry.tryLoc <= this.prev) {\n\t var hasCatch = hasOwn.call(entry, \"catchLoc\");\n\t var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n\t if (hasCatch && hasFinally) {\n\t if (this.prev < entry.catchLoc) {\n\t return handle(entry.catchLoc, true);\n\t } else if (this.prev < entry.finallyLoc) {\n\t return handle(entry.finallyLoc);\n\t }\n\n\t } else if (hasCatch) {\n\t if (this.prev < entry.catchLoc) {\n\t return handle(entry.catchLoc, true);\n\t }\n\n\t } else if (hasFinally) {\n\t if (this.prev < entry.finallyLoc) {\n\t return handle(entry.finallyLoc);\n\t }\n\n\t } else {\n\t throw new Error(\"try statement without catch or finally\");\n\t }\n\t }\n\t }\n\t },\n\n\t abrupt: function(type, arg) {\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t if (entry.tryLoc <= this.prev &&\n\t hasOwn.call(entry, \"finallyLoc\") &&\n\t this.prev < entry.finallyLoc) {\n\t var finallyEntry = entry;\n\t break;\n\t }\n\t }\n\n\t if (finallyEntry &&\n\t (type === \"break\" ||\n\t type === \"continue\") &&\n\t finallyEntry.tryLoc <= arg &&\n\t arg <= finallyEntry.finallyLoc) {\n\t // Ignore the finally entry if control is not jumping to a\n\t // location outside the try/catch block.\n\t finallyEntry = null;\n\t }\n\n\t var record = finallyEntry ? finallyEntry.completion : {};\n\t record.type = type;\n\t record.arg = arg;\n\n\t if (finallyEntry) {\n\t this.method = \"next\";\n\t this.next = finallyEntry.finallyLoc;\n\t return ContinueSentinel;\n\t }\n\n\t return this.complete(record);\n\t },\n\n\t complete: function(record, afterLoc) {\n\t if (record.type === \"throw\") {\n\t throw record.arg;\n\t }\n\n\t if (record.type === \"break\" ||\n\t record.type === \"continue\") {\n\t this.next = record.arg;\n\t } else if (record.type === \"return\") {\n\t this.rval = this.arg = record.arg;\n\t this.method = \"return\";\n\t this.next = \"end\";\n\t } else if (record.type === \"normal\" && afterLoc) {\n\t this.next = afterLoc;\n\t }\n\n\t return ContinueSentinel;\n\t },\n\n\t finish: function(finallyLoc) {\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t if (entry.finallyLoc === finallyLoc) {\n\t this.complete(entry.completion, entry.afterLoc);\n\t resetTryEntry(entry);\n\t return ContinueSentinel;\n\t }\n\t }\n\t },\n\n\t \"catch\": function(tryLoc) {\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t if (entry.tryLoc === tryLoc) {\n\t var record = entry.completion;\n\t if (record.type === \"throw\") {\n\t var thrown = record.arg;\n\t resetTryEntry(entry);\n\t }\n\t return thrown;\n\t }\n\t }\n\n\t // The context.catch method must only be called with a location\n\t // argument that corresponds to a known catch block.\n\t throw new Error(\"illegal catch attempt\");\n\t },\n\n\t delegateYield: function(iterable, resultName, nextLoc) {\n\t this.delegate = {\n\t iterator: values(iterable),\n\t resultName: resultName,\n\t nextLoc: nextLoc\n\t };\n\n\t if (this.method === \"next\") {\n\t // Deliberately forget the last sent value so that we don't\n\t // accidentally pass it on to the delegate.\n\t this.arg = undefined;\n\t }\n\n\t return ContinueSentinel;\n\t }\n\t };\n\t})(\n\t // In sloppy mode, unbound `this` refers to the global object, fallback to\n\t // Function constructor if we're in global strict mode. That is sadly a form\n\t // of indirect eval which violates Content Security Policy.\n\t (function() { return this })() || Function(\"return this\")()\n\t);\n\t});\n\n\t/**\n\t * Copyright (c) 2014-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t */\n\n\t// This method of obtaining a reference to the global object needs to be\n\t// kept identical to the way it is obtained in runtime.js\n\tvar g = (function() { return this })() || Function(\"return this\")();\n\n\t// Use `getOwnPropertyNames` because not all browsers support calling\n\t// `hasOwnProperty` on the global `self` object in a worker. See #183.\n\tvar hadRuntime = g.regeneratorRuntime &&\n\t Object.getOwnPropertyNames(g).indexOf(\"regeneratorRuntime\") >= 0;\n\n\t// Save the old regeneratorRuntime in case it needs to be restored later.\n\tvar oldRuntime = hadRuntime && g.regeneratorRuntime;\n\n\t// Force reevalutation of runtime.js.\n\tg.regeneratorRuntime = undefined;\n\n\tvar runtimeModule = runtime;\n\n\tif (hadRuntime) {\n\t // Restore the original runtime.\n\t g.regeneratorRuntime = oldRuntime;\n\t} else {\n\t // Remove the global property added by runtime.js.\n\t try {\n\t delete g.regeneratorRuntime;\n\t } catch(e) {\n\t g.regeneratorRuntime = undefined;\n\t }\n\t}\n\n\tvar regenerator = runtimeModule;\n\n\tvar defaultOptions = {\n\t mode: 'index'\n\t};\n\n\tmodule.exports = /*#__PURE__*/regenerator.mark(function _callee(M, N, options) {\n\t var a, c, b, p, x, y, z, i, twiddle;\n\t return regenerator.wrap(function _callee$(_context) {\n\t while (1) {\n\t switch (_context.prev = _context.next) {\n\t case 0:\n\t twiddle = function twiddle() {\n\t var i, j, k;\n\t j = 1;\n\t while (p[j] <= 0) {\n\t j++;\n\t }\n\t if (p[j - 1] === 0) {\n\t for (i = j - 1; i !== 1; i--) {\n\t p[i] = -1;\n\t }\n\t p[j] = 0;\n\t x = z = 0;\n\t p[1] = 1;\n\t y = j - 1;\n\t } else {\n\t if (j > 1) {\n\t p[j - 1] = 0;\n\t }\n\t do {\n\t j++;\n\t } while (p[j] > 0);\n\t k = j - 1;\n\t i = j;\n\t while (p[i] === 0) {\n\t p[i++] = -1;\n\t }\n\t if (p[i] === -1) {\n\t p[i] = p[k];\n\t z = p[k] - 1;\n\t x = i - 1;\n\t y = k - 1;\n\t p[k] = -1;\n\t } else {\n\t if (i === p[0]) {\n\t return 0;\n\t } else {\n\t p[j] = p[i];\n\t z = p[i] - 1;\n\t p[i] = 0;\n\t x = j - 1;\n\t y = i - 1;\n\t }\n\t }\n\t }\n\t return 1;\n\t };\n\n\t options = Object.assign({}, defaultOptions, options);\n\t a = new Array(N);\n\t c = new Array(M);\n\t b = new Array(N);\n\t p = new Array(N + 2);\n\n\n\t // init a and b\n\t for (i = 0; i < N; i++) {\n\t a[i] = i;\n\t if (i < N - M) b[i] = 0;else b[i] = 1;\n\t }\n\n\t // init c\n\t for (i = 0; i < M; i++) {\n\t c[i] = N - M + i;\n\t }\n\n\t // init p\n\t for (i = 0; i < p.length; i++) {\n\t if (i === 0) p[i] = N + 1;else if (i <= N - M) p[i] = 0;else if (i <= N) p[i] = i - N + M;else p[i] = -2;\n\t }\n\n\t if (!(options.mode === 'index')) {\n\t _context.next = 20;\n\t break;\n\t }\n\n\t _context.next = 12;\n\t return c.slice();\n\n\t case 12:\n\t if (!twiddle()) {\n\t _context.next = 18;\n\t break;\n\t }\n\n\t c[z] = a[x];\n\t _context.next = 16;\n\t return c.slice();\n\n\t case 16:\n\t _context.next = 12;\n\t break;\n\n\t case 18:\n\t _context.next = 33;\n\t break;\n\n\t case 20:\n\t if (!(options.mode === 'mask')) {\n\t _context.next = 32;\n\t break;\n\t }\n\n\t _context.next = 23;\n\t return b.slice();\n\n\t case 23:\n\t if (!twiddle()) {\n\t _context.next = 30;\n\t break;\n\t }\n\n\t b[x] = 1;\n\t b[y] = 0;\n\t _context.next = 28;\n\t return b.slice();\n\n\t case 28:\n\t _context.next = 23;\n\t break;\n\n\t case 30:\n\t _context.next = 33;\n\t break;\n\n\t case 32:\n\t throw new Error('Invalid mode');\n\n\t case 33:\n\t case 'end':\n\t return _context.stop();\n\t }\n\t }\n\t }, _callee, this);\n\t});\n\n})));\n","'use strict';\n\nconst Matrix = require('ml-matrix').Matrix;\n\nconst Layer = require('./Layer');\nconst OutputLayer = require('./OutputLayer');\nconst Utils = require('./utils');\nconst ACTIVATION_FUNCTIONS = require('./activationFunctions');\n\nclass FeedForwardNeuralNetworks {\n\n /**\n * Create a new Feedforword neural network model.\n * @class FeedForwardNeuralNetworks\n * @param {object} [options]\n * @param {Array} [options.hiddenLayers=[10]] - Array that contains the sizes of the hidden layers.\n * @param {number} [options.iterations=50] - Number of iterations at the training step.\n * @param {number} [options.learningRate=0.01] - Learning rate of the neural net (also known as epsilon).\n * @param {number} [options.regularization=0.01] - Regularization parameter af the neural net.\n * @param {string} [options.activation='tanh'] - activation function to be used. (options: 'tanh'(default),\n * 'identity', 'logistic', 'arctan', 'softsign', 'relu', 'softplus', 'bent', 'sinusoid', 'sinc', 'gaussian').\n * (single-parametric options: 'parametric-relu', 'exponential-relu', 'soft-exponential').\n * @param {number} [options.activationParam=1] - if the selected activation function needs a parameter.\n */\n constructor(options) {\n options = options || {};\n if (options.model) {\n // load network\n this.hiddenLayers = options.hiddenLayers;\n this.iterations = options.iterations;\n this.learningRate = options.learningRate;\n this.regularization = options.regularization;\n this.dicts = options.dicts;\n this.activation = options.activation;\n this.activationParam = options.activationParam;\n this.model = new Array(options.layers.length);\n\n for (var i = 0; i < this.model.length - 1; ++i) {\n this.model[i] = Layer.load(options.layers[i]);\n }\n this.model[this.model.length - 1] = OutputLayer.load(options.layers[this.model.length - 1]);\n } else {\n // default constructor\n this.hiddenLayers = options.hiddenLayers || [10];\n this.iterations = options.iterations || 50;\n\n this.learningRate = options.learningRate || 0.01;\n this.regularization = options.regularization || 0.01;\n\n this.activation = options.activation || 'tanh';\n this.activationParam = options.activationParam || 1;\n if (!(this.activation in Object.keys(ACTIVATION_FUNCTIONS))) {\n this.activation = 'tanh';\n }\n }\n }\n\n /**\n * @private\n * Function that build and initialize the neural net.\n * @param {number} inputSize - total of features to fit.\n * @param {number} outputSize - total of labels of the prediction set.\n */\n buildNetwork(inputSize, outputSize) {\n var size = 2 + (this.hiddenLayers.length - 1);\n this.model = new Array(size);\n\n // input layer\n this.model[0] = new Layer({\n inputSize: inputSize,\n outputSize: this.hiddenLayers[0],\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n\n // hidden layers\n for (var i = 1; i < this.hiddenLayers.length; ++i) {\n this.model[i] = new Layer({\n inputSize: this.hiddenLayers[i - 1],\n outputSize: this.hiddenLayers[i],\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n }\n\n // output layer\n this.model[size - 1] = new OutputLayer({\n inputSize: this.hiddenLayers[this.hiddenLayers.length - 1],\n outputSize: outputSize,\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n }\n\n /**\n * Train the neural net with the given features and labels.\n * @param {Matrix|Array} features\n * @param {Matrix|Array} labels\n */\n train(features, labels) {\n features = Matrix.checkMatrix(features);\n this.dicts = Utils.dictOutputs(labels);\n\n var inputSize = features.columns;\n var outputSize = Object.keys(this.dicts.inputs).length;\n\n this.buildNetwork(inputSize, outputSize);\n\n for (var i = 0; i < this.iterations; ++i) {\n var probabilities = this.propagate(features);\n this.backpropagation(features, labels, probabilities);\n }\n }\n\n /**\n * @private\n * Propagate the input(training set) and retrives the probabilities of each class.\n * @param {Matrix} X\n * @return {Matrix} probabilities of each class.\n */\n propagate(X) {\n var input = X;\n for (var i = 0; i < this.model.length; ++i) {\n //console.log(i);\n input = this.model[i].forward(input);\n }\n\n // get probabilities\n return input.divColumnVector(Utils.sumRow(input));\n }\n\n /**\n * @private\n * Function that applies the backpropagation algorithm on each layer of the network\n * in order to fit the features and labels.\n * @param {Matrix} features\n * @param {Array} labels\n * @param {Matrix} probabilities - probabilities of each class of the feature set.\n */\n backpropagation(features, labels, probabilities) {\n for (var i = 0; i < probabilities.length; ++i) {\n probabilities[i][this.dicts.inputs[labels[i]]] -= 1;\n }\n\n // remember, the last delta doesn't matter\n var delta = probabilities;\n for (i = this.model.length - 1; i >= 0; --i) {\n var a = i > 0 ? this.model[i - 1].a : features;\n delta = this.model[i].backpropagation(delta, a);\n }\n\n for (i = 0; i < this.model.length; ++i) {\n this.model[i].update();\n }\n }\n\n /**\n * Predict the output given the feature set.\n * @param {Array|Matrix} features\n * @return {Array}\n */\n predict(features) {\n features = Matrix.checkMatrix(features);\n var outputs = new Array(features.rows);\n var probabilities = this.propagate(features);\n for (var i = 0; i < features.rows; ++i) {\n outputs[i] = this.dicts.outputs[probabilities.maxRowIndex(i)[1]];\n }\n\n return outputs;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} model\n */\n toJSON() {\n var model = {\n model: 'FNN',\n hiddenLayers: this.hiddenLayers,\n iterations: this.iterations,\n learningRate: this.learningRate,\n regularization: this.regularization,\n activation: this.activation,\n activationParam: this.activationParam,\n dicts: this.dicts,\n layers: new Array(this.model.length)\n };\n\n for (var i = 0; i < this.model.length; ++i) {\n model.layers[i] = this.model[i].toJSON();\n }\n\n return model;\n }\n\n /**\n * Load a Feedforward Neural Network with the current model.\n * @param {object} model\n * @return {FeedForwardNeuralNetworks}\n */\n static load(model) {\n if (model.model !== 'FNN') {\n throw new RangeError('the current model is not a feed forward network');\n }\n\n return new FeedForwardNeuralNetworks(model);\n }\n}\n\nmodule.exports = FeedForwardNeuralNetworks;\n","'use strict';\n\nvar Layer = require('./Layer');\n\nclass OutputLayer extends Layer {\n constructor(options) {\n super(options);\n\n this.activationFunction = function (i, j) {\n this[i][j] = Math.exp(this[i][j]);\n };\n }\n\n static load(model) {\n if (model.model !== 'Layer') {\n throw new RangeError('the current model is not a Layer model');\n }\n\n return new OutputLayer(model);\n }\n}\n\nmodule.exports = OutputLayer;\n","'use strict';\n\nvar NodeSquare = require('./node-square'),\n NodeHexagonal = require('./node-hexagonal');\n\nvar defaultOptions = {\n fields: 3,\n randomizer: Math.random,\n distance: squareEuclidean,\n iterations: 10,\n learningRate: 0.1,\n gridType: 'rect',\n torus: true,\n method: 'random'\n};\n\nfunction SOM(x, y, options, reload) {\n\n this.x = x;\n this.y = y;\n\n options = options || {};\n this.options = {};\n for (var i in defaultOptions) {\n if (options.hasOwnProperty(i)) {\n this.options[i] = options[i];\n } else {\n this.options[i] = defaultOptions[i];\n }\n }\n\n if (typeof this.options.fields === 'number') {\n this.numWeights = this.options.fields;\n } else if (Array.isArray(this.options.fields)) {\n this.numWeights = this.options.fields.length;\n var converters = getConverters(this.options.fields);\n this.extractor = converters.extractor;\n this.creator = converters.creator;\n } else {\n throw new Error('Invalid fields definition');\n }\n\n if (this.options.gridType === 'rect') {\n this.nodeType = NodeSquare;\n this.gridDim = {\n x: x,\n y: y\n };\n } else {\n this.nodeType = NodeHexagonal;\n var hx = this.x - Math.floor(this.y / 2);\n this.gridDim = {\n x: hx,\n y: this.y,\n z: -(0 - hx - this.y)\n };\n }\n\n this.torus = this.options.torus;\n this.distanceMethod = this.torus ? 'getDistanceTorus' : 'getDistance';\n\n this.distance = this.options.distance;\n\n this.maxDistance = getMaxDistance(this.distance, this.numWeights);\n\n if (reload === true) { // For model loading\n this.done = true;\n return;\n }\n if (!(x > 0 && y > 0)) {\n throw new Error('x and y must be positive');\n }\n\n this.times = {\n findBMU: 0,\n adjust: 0\n };\n\n this.randomizer = this.options.randomizer;\n\n this.iterationCount = 0;\n this.iterations = this.options.iterations;\n\n this.startLearningRate = this.learningRate = this.options.learningRate;\n\n this.mapRadius = Math.floor(Math.max(x, y) / 2);\n\n this.algorithmMethod = this.options.method;\n\n this._initNodes();\n\n this.done = false;\n}\n\nSOM.load = function loadModel(model, distance) {\n if (model.name === 'SOM') {\n var x = model.data.length,\n y = model.data[0].length;\n if (distance) {\n model.options.distance = distance;\n } else if (model.options.distance) {\n model.options.distance = eval('(' + model.options.distance + ')');\n }\n var som = new SOM(x, y, model.options, true);\n som.nodes = new Array(x);\n for (var i = 0; i < x; i++) {\n som.nodes[i] = new Array(y);\n for (var j = 0; j < y; j++) {\n som.nodes[i][j] = new som.nodeType(i, j, model.data[i][j], som);\n }\n }\n return som;\n } else {\n throw new Error('expecting a SOM model');\n }\n};\n\nSOM.prototype.export = function exportModel(includeDistance) {\n if (!this.done) {\n throw new Error('model is not ready yet');\n }\n var model = {\n name: 'SOM'\n };\n model.options = {\n fields: this.options.fields,\n gridType: this.options.gridType,\n torus: this.options.torus\n };\n model.data = new Array(this.x);\n for (var i = 0; i < this.x; i++) {\n model.data[i] = new Array(this.y);\n for (var j = 0; j < this.y; j++) {\n model.data[i][j] = this.nodes[i][j].weights;\n }\n }\n if (includeDistance) {\n model.options.distance = this.distance.toString();\n }\n return model;\n};\n\nSOM.prototype._initNodes = function initNodes() {\n var now = Date.now(),\n i, j, k;\n this.nodes = new Array(this.x);\n for (i = 0; i < this.x; i++) {\n this.nodes[i] = new Array(this.y);\n for (j = 0; j < this.y; j++) {\n var weights = new Array(this.numWeights);\n for (k = 0; k < this.numWeights; k++) {\n weights[k] = this.randomizer();\n }\n this.nodes[i][j] = new this.nodeType(i, j, weights, this);\n }\n }\n this.times.initNodes = Date.now() - now;\n};\n\nSOM.prototype.setTraining = function setTraining(trainingSet) {\n if (this.trainingSet) {\n throw new Error('training set has already been set');\n }\n var now = Date.now();\n var convertedSet = trainingSet;\n var i, l = trainingSet.length;\n if (this.extractor) {\n convertedSet = new Array(l);\n for (i = 0; i < l; i++) {\n convertedSet[i] = this.extractor(trainingSet[i]);\n }\n }\n this.numIterations = this.iterations * l;\n\n if (this.algorithmMethod === 'random') {\n this.timeConstant = this.numIterations / Math.log(this.mapRadius);\n } else {\n this.timeConstant = l / Math.log(this.mapRadius);\n }\n this.trainingSet = convertedSet;\n this.times.setTraining = Date.now() - now;\n};\n\nSOM.prototype.trainOne = function trainOne() {\n if (this.done) {\n\n return false;\n\n } else if (this.numIterations-- > 0) {\n\n var neighbourhoodRadius,\n trainingValue,\n trainingSetFactor;\n\n if (this.algorithmMethod === 'random') { // Pick a random value of the training set at each step\n neighbourhoodRadius = this.mapRadius * Math.exp(-this.iterationCount / this.timeConstant);\n trainingValue = getRandomValue(this.trainingSet, this.randomizer);\n this._adjust(trainingValue, neighbourhoodRadius);\n this.learningRate = this.startLearningRate * Math.exp(-this.iterationCount / this.numIterations);\n } else { // Get next input vector\n trainingSetFactor = -Math.floor(this.iterationCount / this.trainingSet.length);\n neighbourhoodRadius = this.mapRadius * Math.exp(trainingSetFactor / this.timeConstant);\n trainingValue = this.trainingSet[this.iterationCount % this.trainingSet.length];\n this._adjust(trainingValue, neighbourhoodRadius);\n if (((this.iterationCount + 1) % this.trainingSet.length) === 0) {\n this.learningRate = this.startLearningRate * Math.exp(trainingSetFactor / Math.floor(this.numIterations / this.trainingSet.length));\n }\n }\n\n this.iterationCount++;\n\n return true;\n\n } else {\n\n this.done = true;\n return false;\n\n }\n};\n\nSOM.prototype._adjust = function adjust(trainingValue, neighbourhoodRadius) {\n var now = Date.now(),\n x, y, dist, influence;\n\n var bmu = this._findBestMatchingUnit(trainingValue);\n\n var now2 = Date.now();\n this.times.findBMU += now2 - now;\n\n var radiusLimit = Math.floor(neighbourhoodRadius);\n var xMin = bmu.x - radiusLimit,\n xMax = bmu.x + radiusLimit,\n yMin = bmu.y - radiusLimit,\n yMax = bmu.y + radiusLimit;\n\n for (x = xMin; x <= xMax; x++) {\n var theX = x;\n if (x < 0) {\n theX += this.x;\n } else if (x >= this.x) {\n theX -= this.x;\n }\n for (y = yMin; y <= yMax; y++) {\n var theY = y;\n if (y < 0) {\n theY += this.y;\n } else if (y >= this.y) {\n theY -= this.y;\n }\n\n dist = bmu[this.distanceMethod](this.nodes[theX][theY]);\n\n if (dist < neighbourhoodRadius) {\n influence = Math.exp(-dist / (2 * neighbourhoodRadius));\n this.nodes[theX][theY].adjustWeights(trainingValue, this.learningRate, influence);\n }\n\n }\n }\n\n this.times.adjust += (Date.now() - now2);\n\n};\n\nSOM.prototype.train = function train(trainingSet) {\n if (!this.done) {\n this.setTraining(trainingSet);\n while (this.trainOne()) {\n }\n }\n};\n\nSOM.prototype.getConvertedNodes = function getConvertedNodes() {\n var result = new Array(this.x);\n for (var i = 0; i < this.x; i++) {\n result[i] = new Array(this.y);\n for (var j = 0; j < this.y; j++) {\n var node = this.nodes[i][j];\n result[i][j] = this.creator ? this.creator(node.weights) : node.weights;\n }\n }\n return result;\n};\n\nSOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) {\n\n var bmu,\n lowest = Infinity,\n dist;\n\n for (var i = 0; i < this.x; i++) {\n for (var j = 0; j < this.y; j++) {\n dist = this.distance(this.nodes[i][j].weights, candidate);\n if (dist < lowest) {\n lowest = dist;\n bmu = this.nodes[i][j];\n }\n }\n }\n\n return bmu;\n\n};\n\nSOM.prototype.predict = function predict(data, computePosition) {\n if (typeof data === 'boolean') {\n computePosition = data;\n data = null;\n }\n if (!data) {\n data = this.trainingSet;\n }\n if (Array.isArray(data) && (Array.isArray(data[0]) || (typeof data[0] === 'object'))) { // predict a dataset\n var self = this;\n return data.map(function (element) {\n return self._predict(element, computePosition);\n });\n } else { // predict a single element\n return this._predict(data, computePosition);\n }\n};\n\nSOM.prototype._predict = function _predict(element, computePosition) {\n if (!Array.isArray(element)) {\n element = this.extractor(element);\n }\n var bmu = this._findBestMatchingUnit(element);\n var result = [bmu.x, bmu.y];\n if (computePosition) {\n result[2] = bmu.getPosition(element);\n }\n return result;\n};\n\n// As seen in http://www.scholarpedia.org/article/Kohonen_network\nSOM.prototype.getQuantizationError = function getQuantizationError() {\n var fit = this.getFit(),\n l = fit.length,\n sum = 0;\n for (var i = 0; i < l; i++) {\n sum += fit[i];\n }\n return sum / l;\n};\n\nSOM.prototype.getFit = function getFit(dataset) {\n if (!dataset) {\n dataset = this.trainingSet;\n }\n var l = dataset.length,\n bmu,\n result = new Array(l);\n for (var i = 0; i < l; i++) {\n bmu = this._findBestMatchingUnit(dataset[i]);\n result[i] = Math.sqrt(this.distance(dataset[i], bmu.weights));\n }\n return result;\n};\n\nfunction getConverters(fields) {\n var l = fields.length,\n normalizers = new Array(l),\n denormalizers = new Array(l);\n for (var i = 0; i < l; i++) {\n normalizers[i] = getNormalizer(fields[i].range);\n denormalizers[i] = getDenormalizer(fields[i].range);\n }\n return {\n extractor: function extractor(value) {\n var result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = normalizers[i](value[fields[i].name]);\n }\n return result;\n },\n creator: function creator(value) {\n var result = {};\n for (var i = 0; i < l; i++) {\n result[fields[i].name] = denormalizers[i](value[i]);\n }\n return result;\n }\n };\n}\n\nfunction getNormalizer(minMax) {\n return function normalizer(value) {\n return (value - minMax[0]) / (minMax[1] - minMax[0]);\n };\n}\n\nfunction getDenormalizer(minMax) {\n return function denormalizer(value) {\n return (minMax[0] + value * (minMax[1] - minMax[0]));\n };\n}\n\nfunction squareEuclidean(a, b) {\n var d = 0;\n for (var i = 0, ii = a.length; i < ii; i++) {\n d += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return d;\n}\n\nfunction getRandomValue(arr, randomizer) {\n return arr[Math.floor(randomizer() * arr.length)];\n}\n\nfunction getMaxDistance(distance, numWeights) {\n var zero = new Array(numWeights),\n one = new Array(numWeights);\n for (var i = 0; i < numWeights; i++) {\n zero[i] = 0;\n one[i] = 1;\n }\n return distance(zero, one);\n}\n\nmodule.exports = SOM;","var NodeSquare = require('./node-square');\n\nfunction NodeHexagonal(x, y, weights, som) {\n\n NodeSquare.call(this, x, y, weights, som);\n\n this.hX = x - Math.floor(y / 2);\n this.z = 0 - this.hX - y;\n\n}\n\nNodeHexagonal.prototype = new NodeSquare;\nNodeHexagonal.prototype.constructor = NodeHexagonal;\n\nNodeHexagonal.prototype.getDistance = function getDistanceHexagonal(otherNode) {\n return Math.max(Math.abs(this.hX - otherNode.hX), Math.abs(this.y - otherNode.y), Math.abs(this.z - otherNode.z));\n};\n\nNodeHexagonal.prototype.getDistanceTorus = function getDistanceTorus(otherNode) {\n var distX = Math.abs(this.hX - otherNode.hX),\n distY = Math.abs(this.y - otherNode.y),\n distZ = Math.abs(this.z - otherNode.z);\n return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY), Math.min(distZ, this.som.gridDim.z - distZ));\n};\n\nNodeHexagonal.prototype.getPosition = function getPosition() {\n throw new Error('Unimplemented : cannot get position of the points for hexagonal grid');\n};\n\nmodule.exports = NodeHexagonal;","import HashTable from 'ml-hash-table';\n\nexport class SparseMatrix {\n constructor(rows, columns, options = {}) {\n if (rows instanceof SparseMatrix) { // clone\n const other = rows;\n this._init(other.rows, other.columns, other.elements.clone(), other.threshold);\n return;\n }\n\n if (Array.isArray(rows)) {\n const matrix = rows;\n rows = matrix.length;\n options = columns || {};\n columns = matrix[0].length;\n this._init(rows, columns, new HashTable(options), options.threshold);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n var value = matrix[i][j];\n if (this.threshold && Math.abs(value) < this.threshold) value = 0;\n if (value !== 0) {\n this.elements.set(i * columns + j, matrix[i][j]);\n }\n }\n }\n } else {\n this._init(rows, columns, new HashTable(options), options.threshold);\n }\n }\n\n _init(rows, columns, elements, threshold) {\n this.rows = rows;\n this.columns = columns;\n this.elements = elements;\n this.threshold = threshold || 0;\n }\n\n static eye(rows = 1, columns = rows) {\n const min = Math.min(rows, columns);\n const matrix = new SparseMatrix(rows, columns, {initialCapacity: min});\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, 1);\n }\n return matrix;\n }\n\n clone() {\n return new SparseMatrix(this);\n }\n\n to2DArray() {\n const copy = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n copy[i] = new Array(this.columns);\n for (var j = 0; j < this.columns; j++) {\n copy[i][j] = this.get(i, j);\n }\n }\n return copy;\n }\n\n isSquare() {\n return this.rows === this.columns;\n }\n\n isSymmetric() {\n if (!this.isSquare()) return false;\n\n var symmetric = true;\n this.forEachNonZero((i, j, v) => {\n if (this.get(j, i) !== v) {\n symmetric = false;\n return false;\n }\n return v;\n });\n return symmetric;\n }\n\n /**\n * Search for the wither band in the main diagonals\n * @return {number}\n */\n bandWidth() {\n let min = this.columns;\n let max = -1;\n this.forEachNonZero((i, j, v) => {\n let diff = i - j;\n min = Math.min(min, diff);\n max = Math.max(max, diff);\n return v;\n });\n return max - min;\n }\n\n /**\n * Test if a matrix is consider banded using a threshold\n * @param {number} width\n * @return {boolean}\n */\n isBanded(width) {\n let bandWidth = this.bandWidth();\n return bandWidth <= width;\n }\n\n get cardinality() {\n return this.elements.size;\n }\n\n get size() {\n return this.rows * this.columns;\n }\n\n get(row, column) {\n return this.elements.get(row * this.columns + column);\n }\n\n set(row, column, value) {\n if (this.threshold && Math.abs(value) < this.threshold) value = 0;\n if (value === 0) {\n this.elements.remove(row * this.columns + column);\n } else {\n this.elements.set(row * this.columns + column, value);\n }\n return this;\n }\n\n mmul(other) {\n if (this.columns !== other.rows) {\n // eslint-disable-next-line no-console\n console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\n }\n\n const m = this.rows;\n const p = other.columns;\n\n const result = new SparseMatrix(m, p);\n this.forEachNonZero((i, j, v1) => {\n other.forEachNonZero((k, l, v2) => {\n if (j === k) {\n result.set(i, l, result.get(i, l) + v1 * v2);\n }\n return v2;\n });\n return v1;\n });\n return result;\n }\n\n kroneckerProduct(other) {\n const m = this.rows;\n const n = this.columns;\n const p = other.rows;\n const q = other.columns;\n\n const result = new SparseMatrix(m * p, n * q, {\n initialCapacity: this.cardinality * other.cardinality\n });\n this.forEachNonZero((i, j, v1) => {\n other.forEachNonZero((k, l, v2) => {\n result.set(p * i + k, q * j + l, v1 * v2);\n return v2;\n });\n return v1;\n });\n return result;\n }\n\n forEachNonZero(callback) {\n this.elements.forEachPair((key, value) => {\n const i = (key / this.columns) | 0;\n const j = key % this.columns;\n let r = callback(i, j, value);\n if (r === false) return false; // stop iteration\n if (this.threshold && Math.abs(r) < this.threshold) r = 0;\n if (r !== value) {\n if (r === 0) {\n this.elements.remove(key, true);\n } else {\n this.elements.set(key, r);\n }\n }\n return true;\n });\n this.elements.maybeShrinkCapacity();\n return this;\n }\n\n getNonZeros() {\n const cardinality = this.cardinality;\n const rows = new Array(cardinality);\n const columns = new Array(cardinality);\n const values = new Array(cardinality);\n var idx = 0;\n this.forEachNonZero((i, j, value) => {\n rows[idx] = i;\n columns[idx] = j;\n values[idx] = value;\n idx++;\n return value;\n });\n return {rows, columns, values};\n }\n\n setThreshold(newThreshold) {\n if (newThreshold !== 0 && newThreshold !== this.threshold) {\n this.threshold = newThreshold;\n this.forEachNonZero((i, j, v) => v);\n }\n return this;\n }\n\n /**\n * @return {SparseMatrix} - New transposed sparse matrix\n */\n transpose() {\n let trans = new SparseMatrix(this.columns, this.rows, {initialCapacity: this.cardinality});\n this.forEachNonZero((i, j, value) => {\n trans.set(j, i, value);\n return value;\n });\n return trans;\n }\n}\n\nSparseMatrix.prototype.klass = 'Matrix';\n\nSparseMatrix.identity = SparseMatrix.eye;\nSparseMatrix.prototype.tensorProduct = SparseMatrix.prototype.kroneckerProduct;\n\n/*\n Add dynamically instance and static methods for mathematical operations\n */\n\nvar inplaceOperator = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\nvar inplaceOperatorScalar = `\n(function %name%S(value) {\n this.forEachNonZero((i, j, v) => v %op% value);\n return this;\n})\n`;\n\nvar inplaceOperatorMatrix = `\n(function %name%M(matrix) {\n matrix.forEachNonZero((i, j, v) => {\n this.set(i, j, this.get(i, j) %op% v);\n return v;\n });\n return this;\n})\n`;\n\nvar staticOperator = `\n(function %name%(matrix, value) {\n var newMatrix = new SparseMatrix(matrix);\n return newMatrix.%name%(value);\n})\n`;\n\nvar inplaceMethod = `\n(function %name%() {\n this.forEachNonZero((i, j, v) => %method%(v));\n return this;\n})\n`;\n\nvar staticMethod = `\n(function %name%(matrix) {\n var newMatrix = new SparseMatrix(matrix);\n return newMatrix.%name%();\n})\n`;\n\nconst operators = [\n // Arithmetic operators\n ['+', 'add'],\n ['-', 'sub', 'subtract'],\n ['*', 'mul', 'multiply'],\n ['/', 'div', 'divide'],\n ['%', 'mod', 'modulus'],\n // Bitwise operators\n ['&', 'and'],\n ['|', 'or'],\n ['^', 'xor'],\n ['<<', 'leftShift'],\n ['>>', 'signPropagatingRightShift'],\n ['>>>', 'rightShift', 'zeroFillRightShift']\n];\n\nfor (const operator of operators) {\n for (let i = 1; i < operator.length; i++) {\n SparseMatrix.prototype[operator[i]] = eval(fillTemplateFunction(inplaceOperator, {name: operator[i], op: operator[0]}));\n SparseMatrix.prototype[operator[i] + 'S'] = eval(fillTemplateFunction(inplaceOperatorScalar, {name: operator[i] + 'S', op: operator[0]}));\n SparseMatrix.prototype[operator[i] + 'M'] = eval(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[i] + 'M', op: operator[0]}));\n\n SparseMatrix[operator[i]] = eval(fillTemplateFunction(staticOperator, {name: operator[i]}));\n }\n}\n\nvar methods = [\n ['~', 'not']\n];\n\n[\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\n].forEach(function (mathMethod) {\n methods.push(['Math.' + mathMethod, mathMethod]);\n});\n\nfor (const method of methods) {\n for (let i = 1; i < method.length; i++) {\n SparseMatrix.prototype[method[i]] = eval(fillTemplateFunction(inplaceMethod, {name: method[i], method: method[0]}));\n SparseMatrix[method[i]] = eval(fillTemplateFunction(staticMethod, {name: method[i]}));\n }\n}\n\nfunction fillTemplateFunction(template, values) {\n for (const i in values) {\n template = template.replace(new RegExp('%' + i + '%', 'g'), values[i]);\n }\n return template;\n}\n","module.exports = newArray\n\nfunction newArray (n, value) {\n n = n || 0\n var array = new Array(n)\n for (var i = 0; i < n; i++) {\n array[i] = value\n }\n return array\n}\n","const binarySearch = require('binary-search');\nconst sortAsc = require('num-sort').asc;\n\nconst largestPrime = 0x7fffffff;\n\nconst primeNumbers = [\n //chunk #0\n largestPrime, // 2^31-1\n\n //chunk #1\n 5, 11, 23, 47, 97, 197, 397, 797, 1597, 3203, 6421, 12853, 25717, 51437, 102877, 205759,\n 411527, 823117, 1646237, 3292489, 6584983, 13169977, 26339969, 52679969, 105359939,\n 210719881, 421439783, 842879579, 1685759167,\n\n //chunk #2\n 433, 877, 1759, 3527, 7057, 14143, 28289, 56591, 113189, 226379, 452759, 905551, 1811107,\n 3622219, 7244441, 14488931, 28977863, 57955739, 115911563, 231823147, 463646329, 927292699,\n 1854585413,\n\n //chunk #3\n 953, 1907, 3821, 7643, 15287, 30577, 61169, 122347, 244703, 489407, 978821, 1957651, 3915341,\n 7830701, 15661423, 31322867, 62645741, 125291483, 250582987, 501165979, 1002331963,\n 2004663929,\n\n //chunk #4\n 1039, 2081, 4177, 8363, 16729, 33461, 66923, 133853, 267713, 535481, 1070981, 2141977, 4283963,\n 8567929, 17135863, 34271747, 68543509, 137087021, 274174111, 548348231, 1096696463,\n\n //chunk #5\n 31, 67, 137, 277, 557, 1117, 2237, 4481, 8963, 17929, 35863, 71741, 143483, 286973, 573953,\n 1147921, 2295859, 4591721, 9183457, 18366923, 36733847, 73467739, 146935499, 293871013,\n 587742049, 1175484103,\n\n //chunk #6\n 599, 1201, 2411, 4831, 9677, 19373, 38747, 77509, 155027, 310081, 620171, 1240361, 2480729,\n 4961459, 9922933, 19845871, 39691759, 79383533, 158767069, 317534141, 635068283, 1270136683,\n\n //chunk #7\n 311, 631, 1277, 2557, 5119, 10243, 20507, 41017, 82037, 164089, 328213, 656429, 1312867,\n 2625761, 5251529, 10503061, 21006137, 42012281, 84024581, 168049163, 336098327, 672196673,\n 1344393353,\n\n //chunk #8\n 3, 7, 17, 37, 79, 163, 331, 673, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899,\n 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557,\n 359339171, 718678369, 1437356741,\n\n //chunk #9\n 43, 89, 179, 359, 719, 1439, 2879, 5779, 11579, 23159, 46327, 92657, 185323, 370661, 741337,\n 1482707, 2965421, 5930887, 11861791, 23723597, 47447201, 94894427, 189788857, 379577741,\n 759155483, 1518310967,\n\n //chunk #10\n 379, 761, 1523, 3049, 6101, 12203, 24407, 48817, 97649, 195311, 390647, 781301, 1562611,\n 3125257, 6250537, 12501169, 25002389, 50004791, 100009607, 200019221, 400038451, 800076929,\n 1600153859,\n\n //chunk #11\n 13, 29, 59, 127, 257, 521, 1049, 2099, 4201, 8419, 16843, 33703, 67409, 134837, 269683,\n 539389, 1078787, 2157587, 4315183, 8630387, 17260781, 34521589, 69043189, 138086407,\n 276172823, 552345671, 1104691373,\n\n //chunk #12\n 19, 41, 83, 167, 337, 677,\n 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899,\n 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557,\n 359339171, 718678369, 1437356741,\n\n //chunk #13\n 53, 107, 223, 449, 907, 1823, 3659, 7321, 14653, 29311, 58631, 117269,\n 234539, 469099, 938207, 1876417, 3752839, 7505681, 15011389, 30022781,\n 60045577, 120091177, 240182359, 480364727, 960729461, 1921458943\n];\n\nprimeNumbers.sort(sortAsc);\n\nfunction nextPrime(value) {\n let index = binarySearch(primeNumbers, value, sortAsc);\n if (index < 0) {\n index = ~index;\n }\n return primeNumbers[index];\n}\n\nexports.nextPrime = nextPrime;\nexports.largestPrime = largestPrime;\n","'use strict';\nmodule.exports = Number.isNaN || function (x) {\n\treturn x !== x;\n};\n","\"use strict\";\n\nexports.additiveSymmetric = require('./distances/additiveSymmetric');\nexports.avg = require('./distances/avg');\nexports.bhattacharyya = require('./distances/bhattacharyya');\nexports.canberra = require('./distances/canberra');\nexports.chebyshev = require('./distances/chebyshev');\nexports.clark = require('./distances/clark');\nexports.czekanowski = require('./distances/czekanowski');\nexports.dice = require('./distances/dice');\nexports.divergence = require('./distances/divergence');\nexports.euclidean = require('ml-distance-euclidean');\nexports.fidelity = require('./distances/fidelity');\nexports.gower = require('./distances/gower');\nexports.harmonicMean = require('./distances/harmonicMean');\nexports.hellinger = require('./distances/hellinger');\nexports.innerProduct = require('./distances/innerProduct');\nexports.intersection = require('./distances/intersection');\nexports.jaccard = require('./distances/jaccard');\nexports.jeffreys = require('./distances/jeffreys');\nexports.jensenDifference = require('./distances/jensenDifference');\nexports.jensenShannon = require('./distances/jensenShannon');\nexports.kdivergence = require('./distances/kdivergence');\nexports.kulczynski = require('./distances/kulczynski');\nexports.kullbackLeibler = require('./distances/kullbackLeibler');\nexports.kumarHassebrook = require('./distances/kumarHassebrook');\nexports.kumarJohnson = require('./distances/kumarJohnson');\nexports.lorentzian = require('./distances/lorentzian');\nexports.manhattan = require('./distances/manhattan');\nexports.matusita = require('./distances/matusita');\nexports.minkowski = require('./distances/minkowski');\nexports.motyka = require('./distances/motyka');\nexports.neyman = require('./distances/neyman');\nexports.pearson = require('./distances/pearson');\nexports.probabilisticSymmetric = require('./distances/probabilisticSymmetric');\nexports.ruzicka = require('./distances/ruzicka');\nexports.soergel = require('./distances/soergel');\nexports.sorensen = require('./distances/sorensen');\nexports.squared = require('./distances/squared');\nexports.squaredChord = require('./distances/squaredChord');\nexports.squaredEuclidean = require('ml-distance-euclidean').squared;\nexports.taneja = require('./distances/taneja');\nexports.tanimoto = require('./distances/tanimoto');\nexports.topsoe = require('./distances/topsoe');\nexports.tree = require('ml-tree-similarity');\nexports.waveHedges = require('./distances/waveHedges');\n","module.exports = function additiveSymmetric(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i]) * (a[i] + b[i])) / (a[i] * b[i]);\n }\n return 2 * d;\n};\n","module.exports = function avg(a, b) {\n var ii = a.length,\n max = 0,\n ans = 0,\n aux = 0;\n for (var i = 0; i < ii ; i++) {\n aux = Math.abs(a[i] - b[i]);\n ans += aux;\n if (max < aux) {\n max = aux;\n }\n }\n return (max + ans) / 2;\n};\n","module.exports = function bhattacharyya(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return - Math.log(ans);\n};\n","module.exports = function canberra(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.abs(a[i] - b[i]) / (a[i] + b[i]);\n }\n return ans;\n};\n","module.exports = function chebyshev(a, b) {\n var ii = a.length,\n max = 0,\n aux = 0;\n for (var i = 0; i < ii ; i++) {\n aux = Math.abs(a[i] - b[i]);\n if (max < aux) {\n max = aux;\n }\n }\n return max;\n};\n","module.exports = function clark(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.sqrt(((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i])));\n }\n return 2 * d;\n};\n","'use strict';\n\nconst czekanowskiSimilarity = require('../similarities/czekanowski');\n\nmodule.exports = function czekanowskiDistance(a, b) {\n return 1 - czekanowskiSimilarity(a, b);\n};\n","module.exports = function divergence(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i]));\n }\n return 2 * d;\n};\n","module.exports = function fidelity(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return ans;\n};\n","module.exports = function gower(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.abs(a[i] - b[i]);\n }\n return ans / ii;\n};\n","module.exports = function harmonicMean(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] * b[i]) / (a[i] + b[i]);\n }\n return 2 * ans;\n};\n","module.exports = function hellinger(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return 2 * Math.sqrt(1 - ans);\n};\n","module.exports = function innerProduct(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * b[i];\n }\n return ans;\n};\n","module.exports = function jeffreys(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] - b[i]) * Math.log(a[i] / b[i]);\n }\n return ans;\n};\n","module.exports = function jensenDifference(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += ((a[i] * Math.log(a[i]) + b[i] * Math.log(b[i])) / 2) - ((a[i] + b[i]) / 2) * Math.log((a[i] + b[i]) / 2);\n }\n return ans;\n};\n","module.exports = function jensenShannon(a, b) {\n var ii = a.length,\n p = 0,\n q = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * Math.log(2 * a[i] / (a[i] + b[i]));\n q += b[i] * Math.log(2 * b[i] / (a[i] + b[i]));\n }\n return (p + q) / 2;\n};\n","module.exports = function kdivergence(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i]));\n }\n return ans;\n};\n","module.exports = function kullbackLeibler(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(a[i] / b[i]);\n }\n return ans;\n};\n","module.exports = function kumarHassebrook(a, b) {\n var ii = a.length,\n p = 0,\n p2 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * b[i];\n p2 += a[i] * a[i];\n q2 += b[i] * b[i];\n }\n return p / (p2 + q2 - p);\n};\n","module.exports = function kumarJohnson(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.pow(a[i] * a[i] - b[i] * b[i],2) / (2 * Math.pow(a[i] * b[i],1.5));\n }\n return ans;\n};\n","module.exports = function lorentzian(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.log(Math.abs(a[i] - b[i]) + 1);\n }\n return ans;\n};\n","module.exports = function manhattan(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.abs(a[i] - b[i]);\n }\n return d;\n};\n","module.exports = function matusita(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return Math.sqrt(2 - 2 * ans);\n};\n","module.exports = function minkowski(a, b, p) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.pow(Math.abs(a[i] - b[i]),p);\n }\n return Math.pow(d,(1/p));\n};\n","module.exports = function neyman(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / a[i];\n }\n return d;\n};\n","module.exports = function pearson(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / b[i];\n }\n return d;\n};\n","module.exports = function probabilisticSymmetric(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]);\n }\n return 2 * d;\n};\n","module.exports = function ruzicka(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.min(a[i],b[i]);\n down += Math.max(a[i],b[i]);\n }\n return up / down;\n};\n","module.exports = function soergel(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += Math.max(a[i],b[i]);\n }\n return up / down;\n};\n","module.exports = function sorensen(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += a[i] + b[i];\n }\n return up / down;\n};\n","module.exports = function squared(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]);\n }\n return d;\n};\n","module.exports = function taneja(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] + b[i]) / 2 * Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i])));\n }\n return ans;\n};\n","var tanimotoS = require('./../similarities/tanimoto');\n\nmodule.exports = function tanimoto(a, b, bitvector) {\n if (bitvector)\n return 1 - tanimotoS(a, b, bitvector);\n else {\n var ii = a.length,\n p = 0,\n q = 0,\n m = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i];\n q += b[i];\n m += Math.min(a[i],b[i]);\n }\n return (p + q - 2 * m) / (p + q - m);\n }\n};\n","module.exports = function topsoe(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])) + b[i] * Math.log(2 * b[i] / (a[i] + b[i]));\n }\n return ans;\n};\n","\"use strict\";\n\n/**\n * Function that creates the tree\n * @param {Array } X - chemical shifts of the signal\n * @param {Array } Y - intensity of the signal\n * @param {number} from - the low limit of x\n * @param {number} to - the top limit of x\n * @param {number} minWindow - smallest range to accept in x\n * @param {number} threshold - smallest range to accept in y\n * @returns {{sum: number, center: number, left: {json}, right: {json}}}\n * left and right have the same structure than the parent, or have a\n * undefined value if are leafs\n */\nfunction createTree (X, Y, from, to, minWindow, threshold) {\n minWindow = minWindow || 0.16;\n threshold = threshold || 0.01;\n if ((to - from) < minWindow)\n return undefined;\n var sum = 0;\n for (var i = 0; X[i] < to; i++) {\n if (X[i] > from)\n sum += Y[i];\n }\n if (sum < threshold) {\n return undefined;\n }\n var center = 0;\n for (var j = 0; X[j] < to; j++) {\n if (X[i] > from)\n center += X[j] * Y[j];\n }\n center = center / sum;\n if (((center - from) < 10e-6) || ((to - center) < 10e-6)) return undefined;\n if ((center - from) < (minWindow /4)) {\n return createTree(X, Y, center, to, minWindow, threshold);\n }\n else {\n if ((to - center) < (minWindow / 4)) {\n return createTree(X, Y, from, center, minWindow, threshold);\n }\n else {\n return {\n 'sum': sum,\n 'center': center,\n 'left': createTree(X, Y, from, center, minWindow, threshold),\n 'right': createTree(X, Y, center, to, minWindow, threshold)\n };\n }\n }\n}\n\n/**\n * Similarity between two nodes\n * @param {{sum: number, center: number, left: {json}, right: {json}}} a - tree A node\n * @param {{sum: number, center: number, left: {json}, right: {json}}} b - tree B node\n * @param {number} alpha - weights the relative importance of intensity vs. shift match\n * @param {number} beta - weights the relative importance of node matching and children matching\n * @param {number} gamma - controls the attenuation of the effect of chemical shift differences\n * @returns {number} similarity measure between tree nodes\n */\nfunction S(a, b, alpha, beta, gamma) {\n if (a === undefined || b === undefined) {\n return 0;\n }\n else {\n var C = (alpha*Math.min(a.sum, b.sum)/Math.max(a.sum, b.sum)+ (1-alpha)*Math.exp(-gamma*Math.abs(a.center - b.center)));\n }\n return beta*C + (1-beta)*(S(a.left, b.left, alpha, beta, gamma)+S(a.right, b.right, alpha, beta, gamma));\n}\n\n/**\n * @type {number} alpha - weights the relative importance of intensity vs. shift match\n * @type {number} beta - weights the relative importance of node matching and children matching\n * @type {number} gamma - controls the attenuation of the effect of chemical shift differences\n * @type {number} minWindow - smallest range to accept in x\n * @type {number} threshold - smallest range to accept in y\n */\nvar defaultOptions = {\n minWindow: 0.16,\n threshold : 0.01,\n alpha: 0.1,\n beta: 0.33,\n gamma: 0.001\n};\n\n/**\n * Builds a tree based in the spectra and compares this trees\n * @param {{x: Array, y: Array}} A - first spectra to be compared\n * @param {{x: Array, y: Array}} B - second spectra to be compared\n * @param {number} from - the low limit of x\n * @param {number} to - the top limit of x\n * @param {{minWindow: number, threshold: number, alpha: number, beta: number, gamma: number}} options\n * @returns {number} similarity measure between the spectra\n */\nfunction tree(A, B, from, to, options) {\n options = options || {};\n for (var o in defaultOptions)\n if (!options.hasOwnProperty(o)) {\n options[o] = defaultOptions[o];\n }\n var Atree, Btree;\n if (A.sum)\n Atree = A;\n else\n Atree = createTree(A.x, A.y, from, to, options.minWindow, options.threshold);\n if (B.sum)\n Btree = B;\n else\n Btree = createTree(B.x, B.y, from, to, options.minWindow, options.threshold);\n return S(Atree, Btree, options.alpha, options.beta, options.gamma);\n}\n\nmodule.exports = {\n calc: tree,\n createTree: createTree\n};","module.exports = function waveHedges(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += 1 - (Math.min(a[i], b[i]) / Math.max(a[i], b[i]));\n }\n return ans;\n};\n","\"use strict\";\n\nexports.cosine = require('./similarities/cosine');\nexports.czekanowski = require('./similarities/czekanowski');\nexports.dice = require('./similarities/dice');\nexports.intersection = require('./similarities/intersection');\nexports.jaccard = require('./similarities/jaccard');\nexports.kulczynski = require('./similarities/kulczynski');\nexports.motyka = require('./similarities/motyka');\nexports.pearson = require('./similarities/pearson');\nexports.squaredChord = require('./similarities/squaredChord');\nexports.tanimoto = require('./similarities/tanimoto');\n","var diceD = require('./../distances/dice');\n\nmodule.exports = function dice(a, b) {\n return 1 - diceD(a,b);\n};\n","var intersectionD = require('./../distances/intersection');\n\nmodule.exports = function intersection(a, b) {\n return 1 - intersectionD(a,b);\n};\n","var jaccardD = require('./../distances/jaccard');\n\nmodule.exports = function jaccard(a, b) {\n return 1 - jaccardD(a, b);\n};\n","var kulczynskiD = require('./../distances/kulczynski');\n\nmodule.exports = function kulczynski(a, b) {\n return 1 / kulczynskiD(a, b);\n};\n","var motykaD = require('./../distances/motyka');\n\nmodule.exports = function motyka(a, b) {\n return 1 - motykaD(a,b);\n};\n","'use strict';\n\nvar stat=require('ml-stat').array;\nvar cosine=require('./cosine');\n\nmodule.exports = function pearson(a, b) {\n var avgA=stat.mean(a);\n var avgB=stat.mean(b);\n\n var newA=new Array(a.length);\n var newB=new Array(b.length);\n for (var i=0; i a.pred - b.pred);\n } else {\n predP.sort((a, b) => b.pred - a.pred);\n }\n \n const cutoffs = this.cutoffs = [isDistance ? Number.MIN_VALUE : Number.MAX_VALUE];\n const fp = this.fp = [0];\n const tp = this.tp = [0];\n\n var nPos = 0;\n var nNeg = 0;\n\n var currentPred = predP[0].pred;\n var nTp = 0;\n var nFp = 0;\n for (var i = 0; i < predP.length; i++) {\n if (predP[i].pred !== currentPred) {\n cutoffs.push(currentPred);\n fp.push(nFp);\n tp.push(nTp);\n currentPred = predP[i].pred;\n }\n if (predP[i].targ) {\n nPos++;\n nTp++;\n } else {\n nNeg++;\n nFp++;\n }\n }\n cutoffs.push(currentPred);\n fp.push(nFp);\n tp.push(nTp);\n\n const l = cutoffs.length;\n const fn = this.fn = new Array(l);\n const tn = this.tn = new Array(l);\n const nPosPred = this.nPosPred = new Array(l);\n const nNegPred = this.nNegPred = new Array(l);\n\n for (var i = 0; i < l; i++) {\n fn[i] = nPos - tp[i];\n tn[i] = nNeg - fp[i];\n\n nPosPred[i] = tp[i] + fp[i];\n nNegPred[i] = tn[i] + fn[i];\n }\n\n this.nPos = nPos;\n this.nNeg = nNeg;\n this.nSamples = nPos + nNeg;\n }\n\n /**\n * Computes a measure from the prediction object.\n *\n * Many measures are available and can be combined :\n * To create a ROC curve, you need fpr and tpr\n * To create a DET curve, you need fnr and fpr\n * To create a Lift chart, you need rpp and lift\n *\n * Possible measures are : threshold (Threshold), acc (Accuracy), err (Error rate),\n * fpr (False positive rate), tpr (True positive rate), fnr (False negative rate), tnr (True negative rate), ppv (Positive predictive value),\n * npv (Negative predictive value), pcfall (Prediction-conditioned fallout), pcmiss (Prediction-conditioned miss), lift (Lift value), rpp (Rate of positive predictions), rnp (Rate of negative predictions)\n *\n * @param measure - The short name of the measure\n *\n * @return [number]\n */\n getMeasure(measure) {\n if (typeof measure !== 'string') {\n throw new Error('No measure specified');\n }\n if (!measures[measure]) {\n throw new Error(`The specified measure (${measure}) does not exist`);\n }\n return measures[measure](this);\n }\n\n /**\n * Returns the area under the ROC curve\n */\n getAURC() {\n const l = this.cutoffs.length;\n const x = new Array(l);\n const y = new Array(l);\n for (var i = 0; i < l; i++) {\n x[i] = this.fp[i] / this.nNeg;\n y[i] = this.tp[i] / this.nPos;\n }\n var auc = 0;\n for (i = 1; i < l; i++) {\n auc += 0.5 * (x[i] - x[i - 1]) * (y[i] + y[i - 1]);\n }\n return auc;\n }\n\n /**\n * Returns the area under the DET curve\n */\n getAUDC() {\n const l = this.cutoffs.length;\n const x = new Array(l);\n const y = new Array(l);\n for (var i = 0; i < l; i++) {\n x[i] = this.fn[i] / this.nPos;\n y[i] = this.fp[i] / this.nNeg;\n }\n var auc = 0;\n for (i = 1; i < l; i++) {\n auc += 0.5 * (x[i] + x[i - 1]) * (y[i] - y[i - 1]);\n }\n return auc;\n }\n\n getDistribution(options) {\n options = options || {};\n var cutLength = this.cutoffs.length;\n var cutLow = options.xMin || Math.floor(this.cutoffs[cutLength - 1] * 100) / 100;\n var cutHigh = options.xMax || Math.ceil(this.cutoffs[1] * 100) / 100;\n var interval = options.interval || Math.floor(((cutHigh - cutLow) / 20 * 10000000) - 1) / 10000000; // Trick to avoid the precision problem of float numbers\n\n var xLabels = [];\n var interValues = [];\n var intraValues = [];\n var interCumPercent = [];\n var intraCumPercent = [];\n\n var nTP = this.tp[cutLength - 1], currentTP = 0;\n var nFP = this.fp[cutLength - 1], currentFP = 0;\n\n for (var i = cutLow, j = (cutLength - 1); i <= cutHigh; i += interval) {\n while (this.cutoffs[j] < i)\n j--;\n\n xLabels.push(i);\n\n var thisTP = nTP - currentTP - this.tp[j];\n var thisFP = nFP - currentFP - this.fp[j];\n\n currentTP += thisTP;\n currentFP += thisFP;\n\n interValues.push(thisFP);\n intraValues.push(thisTP);\n\n interCumPercent.push(100 - (nFP - this.fp[j]) / nFP * 100);\n intraCumPercent.push(100 - (nTP - this.tp[j]) / nTP * 100);\n }\n\n return {\n xLabels: xLabels,\n interValues: interValues,\n intraValues: intraValues,\n interCumPercent: interCumPercent,\n intraCumPercent: intraCumPercent\n };\n }\n}\n\nPerformance.names = {\n acc: 'Accuracy',\n err: 'Error rate',\n fpr: 'False positive rate',\n tpr: 'True positive rate',\n fnr: 'False negative rate',\n tnr: 'True negative rate',\n ppv: 'Positive predictive value',\n npv: 'Negative predictive value',\n pcfall: 'Prediction-conditioned fallout',\n pcmiss: 'Prediction-conditioned miss',\n lift: 'Lift value',\n rpp: 'Rate of positive predictions',\n rnp: 'Rate of negative predictions',\n threshold: 'Threshold'\n};\n\nmodule.exports = Performance;\n","'use strict';\n\n// Accuracy\nexports.acc = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.tn[i] + pred.tp[i]) / (l - 1);\n }\n return result;\n};\n\n// Error rate\nexports.err = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.fp[i] / (l - 1));\n }\n return result;\n};\n\n// False positive rate\nexports.fpr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.fp[i] / pred.nNeg;\n }\n return result;\n};\n\n// True positive rate\nexports.tpr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.tp[i] / pred.nPos;\n }\n return result;\n};\n\n// False negative rate\nexports.fnr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.fn[i] / pred.nPos;\n }\n return result;\n};\n\n// True negative rate\nexports.tnr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.tn[i] / pred.nNeg;\n }\n return result;\n};\n\n// Positive predictive value\nexports.ppv = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 0;\n }\n return result;\n};\n\n// Negative predictive value\nexports.npv = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 0;\n }\n return result;\n};\n\n// Prediction conditioned fallout\nexports.pcfall = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? 1 - (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 1;\n }\n return result;\n};\n\n// Prediction conditioned miss\nexports.pcmiss = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? 1 - (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 1;\n }\n return result;\n};\n\n// Lift value\nexports.lift = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.nPosPred[i] !== 0) ? ((pred.tp[i] / pred.nPos) / (pred.nPosPred[i] / pred.nSamples)) : 0;\n }\n return result;\n};\n\n// Rate of positive predictions\nexports.rpp = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.nPosPred[i] / pred.nSamples;\n }\n return result;\n};\n\n// Rate of negative predictions\nexports.rnp = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.nNegPred[i] / pred.nSamples;\n }\n return result;\n};\n\n// Threshold\nexports.threshold = pred => {\n const clone = pred.cutoffs.slice();\n clone[0] = clone[1]; // Remove the infinite value\n return clone;\n};\n","'use strict';\n\nvar matrixLib = require('ml-matrix');\nvar Matrix = matrixLib.Matrix;\nvar inverse = matrixLib.inverse;\nvar padArray = require('ml-pad-array');\nvar extend = require('extend');\n\nvar defaultOptions = {\n windowSize: 5,\n derivative: 1,\n polynomial: 2,\n pad: 'none',\n padValue: 'replicate'\n};\n\n/**\n * Savitzky-Golay filter\n * @param {Array } data\n * @param {number} h\n * @param {Object} options\n * @returns {Array}\n */\nfunction SavitzkyGolay (data, h, options) {\n options = extend({}, defaultOptions, options);\n if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize)))\n throw new RangeError('Invalid window size (should be odd and at least 5 integer number)');\n if ((options.derivative < 0) || !(Number.isInteger(options.derivative)))\n throw new RangeError('Derivative should be a positive integer');\n if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial)))\n throw new RangeError('Polynomial should be a positive integer');\n\n var C, norm;\n var step = Math.floor(options.windowSize / 2);\n\n if (options.pad === 'pre') {\n data = padArray(data, {size: step, value: options.padValue});\n }\n\n var ans = new Array(data.length - 2*step);\n\n if ((options.windowSize === 5) && (options.polynomial === 2) && ((options.derivative === 1) || (options.derivative === 2))) {\n if (options.derivative === 1) {\n C = [-2,-1,0,1,2];\n norm = 10;\n }\n else {\n C = [2, -1, -2, -1, 2];\n norm = 7;\n }\n }\n else {\n var J = Matrix.ones(options.windowSize, options.polynomial + 1);\n var inic = -(options.windowSize - 1) / 2;\n for (var i = 0; i < J.length; i++) {\n for (var j = 0; j < J[i].length; j++) {\n if ((inic + 1 !== 0) || (j !== 0))\n J[i][j] = Math.pow((inic + i), j);\n }\n }\n var Jtranspose = J.transposeView();\n var Jinv = inverse(Jtranspose.mmul(J));\n C = Jinv.mmul(Jtranspose);\n C = C[options.derivative];\n norm = 1;\n }\n var det = norm * Math.pow(h, options.derivative);\n for (var k = step; k < (data.length - step); k++) {\n var d = 0;\n for (var l = 0; l < C.length; l++)\n d += C[l] * data[l + k - step] / det;\n ans[k - step] = d;\n }\n\n if (options.pad === 'post') {\n ans = padArray(ans, {size: step, value: options.padValue});\n }\n\n return ans;\n}\n\nmodule.exports = SavitzkyGolay;\n","//Code translate from Pascal source in http://pubs.acs.org/doi/pdf/10.1021/ac00205a007\nvar extend = require('extend');\nvar stat = require('ml-stat');\n\nvar defaultOptions = {\n windowSize: 9,\n derivative: 0,\n polynomial: 3,\n};\n\n\nfunction SavitzkyGolay(data, h, options) {\n options = extend({}, defaultOptions, options);\n\n if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize)))\n throw new RangeError('Invalid window size (should be odd and at least 5 integer number)')\n\n\n if (options.windowSize>data.length)\n throw new RangeError('Window size is higher than the data length '+options.windowSize+\">\"+data.length);\n if ((options.derivative < 0) || !(Number.isInteger(options.derivative)))\n throw new RangeError('Derivative should be a positive integer');\n if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial)))\n throw new RangeError('Polynomial should be a positive integer');\n if (options.polynomial >= 6)\n console.warn('You should not use polynomial grade higher than 5 if you are' +\n ' not sure that your data arises from such a model. Possible polynomial oscillation problems');\n\n var windowSize = options.windowSize;\n\n var half = Math.floor(windowSize/2);\n var np = data.length;\n var ans = new Array(np);\n var weights = fullWeights(windowSize,options.polynomial,options.derivative);\n var hs = 0;\n var constantH = true;\n if( Object.prototype.toString.call( h ) === '[object Array]' ) {\n constantH = false;\n }\n else{\n hs = Math.pow(h, options.derivative);\n }\n //console.log(\"Constant h: \"+constantH);\n //For the borders\n for(var i=0;i=0 && i < h.length-1){\n hs+= (h[i+1]-h[i]);\n count++;\n }\n }\n return Math.pow(hs/count,derivative);\n}\n\nfunction GramPoly(i,m,k,s){\n var Grampoly = 0;\n if(k>0){\n Grampoly = (4*k-2)/(k*(2*m-k+1))*(i*GramPoly(i,m,k-1,s) +\n s*GramPoly(i,m,k-1,s-1)) - ((k-1)*(2*m+k))/(k*(2*m-k+1))*GramPoly(i,m,k-2,s);\n }\n else{\n if(k==0&&s==0){\n Grampoly=1;\n }\n else{\n Grampoly=0;\n }\n }\n //console.log(Grampoly);\n return Grampoly;\n}\n\nfunction GenFact(a,b){\n var gf=1;\n if(a>=b){\n for(var j=a-b+1;j<=a;j++){\n gf*=j;\n }\n }\n return gf;\n}\n\nfunction Weight(i,t,m,n,s){\n var sum=0;\n for(var k=0;k<=n;k++){\n //console.log(k);\n sum+=(2*k+1)*(GenFact(2*m,k)/GenFact(2*m+k+1,k+1))*GramPoly(i,m,k,0)*GramPoly(t,m,k,s)\n }\n return sum;\n}\n\n/**\n *\n * @param m Number of points\n * @param n Polynomial grade\n * @param s Derivative\n */\nfunction fullWeights(m,n,s){\n var weights = new Array(m);\n var np = Math.floor(m/2);\n for(var t=-np;t<=np;t++){\n weights[t+np] = new Array(m);\n for(var j=-np;j<=np;j++){\n weights[t+np][j+np]=Weight(j,t,np,n,s);\n }\n }\n return weights;\n}\n\n/*function entropy(data,h,options){\n var trend = SavitzkyGolay(data,h,trendOptions);\n var copy = new Array(data.length);\n var sum = 0;\n var max = 0;\n for(var i=0;i> 8) & 0xff] + eightBits[(arr[i] >> 16) & 0xff] + eightBits[(arr[i] >> 24) & 0xff];\n }\n return c;\n}\n\n/**\n * Logical AND operation\n * @param {Array} arr1\n * @param {Array} arr2\n * @return {Array}\n */\nfunction and(arr1, arr2) {\n var ans = new Array(arr1.length);\n for (var i = 0; i < arr1.length; i++)\n ans[i] = arr1[i] & arr2[i];\n return ans;\n}\n\n/**\n * Logical OR operation\n * @param {Array} arr1\n * @param {Array} arr2\n * @return {Array}\n */\nfunction or(arr1, arr2) {\n var ans = new Array(arr1.length);\n for (var i = 0; i < arr1.length; i++)\n ans[i] = arr1[i] | arr2[i];\n return ans;\n}\n\n/**\n * Logical XOR operation\n * @param {Array} arr1\n * @param {Array} arr2\n * @return {Array}\n */\nfunction xor(arr1, arr2) {\n var ans = new Array(arr1.length);\n for (var i = 0; i < arr1.length; i++)\n ans[i] = arr1[i] ^ arr2[i];\n return ans;\n}\n\n/**\n * Logical NOT operation\n * @param {Array} arr\n * @return {Array}\n */\nfunction not(arr) {\n var ans = new Array(arr.length);\n for (var i = 0; i < ans.length; i++)\n ans[i] = ~arr[i];\n return ans;\n}\n\n/**\n * Gets the n value of array arr\n * @param {Array} arr\n * @param {number} n\n * @return {boolean}\n */\nfunction getBit(arr, n) {\n var index = n >> 5; // Same as Math.floor(n/32)\n var mask = 1 << (31 - n % 32);\n return Boolean(arr[index] & mask);\n}\n\n/**\n * Sets the n value of array arr to the value val\n * @param {Array} arr\n * @param {number} n\n * @param {boolean} val\n * @return {Array}\n */\nfunction setBit(arr, n, val) {\n var index = n >> 5; // Same as Math.floor(n/32)\n var mask = 1 << (31 - n % 32);\n if (val)\n arr[index] = mask | arr[index];\n else\n arr[index] = ~mask & arr[index];\n return arr;\n}\n\n/**\n * Translates an array of numbers to a string of bits\n * @param {Array} arr\n * @returns {string}\n */\nfunction toBinaryString(arr) {\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n var obj = (arr[i] >>> 0).toString(2);\n str += '00000000000000000000000000000000'.substr(obj.length) + obj;\n }\n return str;\n}\n\n/**\n * Creates an array of numbers based on a string of bits\n * @param {string} str\n * @returns {Array}\n */\nfunction parseBinaryString(str) {\n var len = str.length / 32;\n var ans = new Array(len);\n for (var i = 0; i < len; i++) {\n ans[i] = parseInt(str.substr(i*32, 32), 2) | 0;\n }\n return ans;\n}\n\n/**\n * Translates an array of numbers to a hex string\n * @param {Array} arr\n * @returns {string}\n */\nfunction toHexString(arr) {\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n var obj = (arr[i] >>> 0).toString(16);\n str += '00000000'.substr(obj.length) + obj;\n }\n return str;\n}\n\n/**\n * Creates an array of numbers based on a hex string\n * @param {string} str\n * @returns {Array}\n */\nfunction parseHexString(str) {\n var len = str.length / 8;\n var ans = new Array(len);\n for (var i = 0; i < len; i++) {\n ans[i] = parseInt(str.substr(i*8, 8), 16) | 0;\n }\n return ans;\n}\n\n/**\n * Creates a human readable string of the array\n * @param {Array} arr\n * @returns {string}\n */\nfunction toDebug(arr) {\n var binary = toBinaryString(arr);\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n str += '0000'.substr((i * 32).toString(16).length) + (i * 32).toString(16) + ':';\n for (var j = 0; j < 32; j += 4) {\n str += ' ' + binary.substr(i * 32 + j, 4);\n }\n if (i < arr.length - 1) str += '\\n';\n }\n return str\n}\n\nmodule.exports = {\n count: count,\n and: and,\n or: or,\n xor: xor,\n not: not,\n getBit: getBit,\n setBit: setBit,\n toBinaryString: toBinaryString,\n parseBinaryString: parseBinaryString,\n toHexString: toHexString,\n parseHexString: parseHexString,\n toDebug: toDebug\n};\n","// auxiliary file to create the 256 look at table elements\n\nvar ans = new Array(256);\nfor (var i = 0; i < 256; i++) {\n var num = i;\n var c = 0;\n while (num) {\n num = num & (num - 1);\n c++;\n }\n ans[i] = c;\n}\n\nmodule.exports = ans;","'use strict';\n\nmodule.exports = exports = require('./ArrayUtils');\n\nexports.getEquallySpacedData = require('./getEquallySpaced').getEquallySpacedData;\nexports.SNV = require('./snv').SNV;\n","'use strict';\n\nconst Stat = require('ml-stat').array;\n/**\n * Function that returns an array of points given 1D array as follows:\n *\n * [x1, y1, .. , x2, y2, ..]\n *\n * And receive the number of dimensions of each point.\n * @param array\n * @param dimensions\n * @returns {Array} - Array of points.\n */\nfunction coordArrayToPoints(array, dimensions) {\n if (array.length % dimensions !== 0) {\n throw new RangeError('Dimensions number must be accordance with the size of the array.');\n }\n\n var length = array.length / dimensions;\n var pointsArr = new Array(length);\n\n var k = 0;\n for (var i = 0; i < array.length; i += dimensions) {\n var point = new Array(dimensions);\n for (var j = 0; j < dimensions; ++j) {\n point[j] = array[i + j];\n }\n\n pointsArr[k] = point;\n k++;\n }\n\n return pointsArr;\n}\n\n\n/**\n * Function that given an array as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * Returns an array as follows:\n * [[x1, x2, ..], [y1, y2, ..], [ .. ]]\n *\n * And receives the number of dimensions of each coordinate.\n * @param array\n * @param dimensions\n * @returns {Array} - Matrix of coordinates\n */\nfunction coordArrayToCoordMatrix(array, dimensions) {\n if (array.length % dimensions !== 0) {\n throw new RangeError('Dimensions number must be accordance with the size of the array.');\n }\n\n var coordinatesArray = new Array(dimensions);\n var points = array.length / dimensions;\n for (var i = 0; i < coordinatesArray.length; i++) {\n coordinatesArray[i] = new Array(points);\n }\n\n for (i = 0; i < array.length; i += dimensions) {\n for (var j = 0; j < dimensions; ++j) {\n var currentPoint = Math.floor(i / dimensions);\n coordinatesArray[j][currentPoint] = array[i + j];\n }\n }\n\n return coordinatesArray;\n}\n\n/**\n * Function that receives a coordinate matrix as follows:\n * [[x1, x2, ..], [y1, y2, ..], [ .. ]]\n *\n * Returns an array of coordinates as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * @param coordMatrix\n * @returns {Array}\n */\nfunction coordMatrixToCoordArray(coordMatrix) {\n var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length);\n var k = 0;\n for (var i = 0; i < coordMatrix[0].length; ++i) {\n for (var j = 0; j < coordMatrix.length; ++j) {\n coodinatesArray[k] = coordMatrix[j][i];\n ++k;\n }\n }\n\n return coodinatesArray;\n}\n\n/**\n * Tranpose a matrix, this method is for coordMatrixToPoints and\n * pointsToCoordMatrix, that because only transposing the matrix\n * you can change your representation.\n *\n * @param matrix\n * @returns {Array}\n */\nfunction transpose(matrix) {\n var resultMatrix = new Array(matrix[0].length);\n for (var i = 0; i < resultMatrix.length; ++i) {\n resultMatrix[i] = new Array(matrix.length);\n }\n\n for (i = 0; i < matrix.length; ++i) {\n for (var j = 0; j < matrix[0].length; ++j) {\n resultMatrix[j][i] = matrix[i][j];\n }\n }\n\n return resultMatrix;\n}\n\n/**\n * Function that transform an array of points into a coordinates array\n * as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * @param points\n * @returns {Array}\n */\nfunction pointsToCoordArray(points) {\n var coodinatesArray = new Array(points.length * points[0].length);\n var k = 0;\n for (var i = 0; i < points.length; ++i) {\n for (var j = 0; j < points[0].length; ++j) {\n coodinatesArray[k] = points[i][j];\n ++k;\n }\n }\n\n return coodinatesArray;\n}\n\n/**\n * Apply the dot product between the smaller vector and a subsets of the\n * largest one.\n *\n * @param firstVector\n * @param secondVector\n * @returns {Array} each dot product of size of the difference between the\n * larger and the smallest one.\n */\nfunction applyDotProduct(firstVector, secondVector) {\n var largestVector, smallestVector;\n if (firstVector.length <= secondVector.length) {\n smallestVector = firstVector;\n largestVector = secondVector;\n } else {\n smallestVector = secondVector;\n largestVector = firstVector;\n }\n\n var difference = largestVector.length - smallestVector.length + 1;\n var dotProductApplied = new Array(difference);\n\n for (var i = 0; i < difference; ++i) {\n var sum = 0;\n for (var j = 0; j < smallestVector.length; ++j) {\n sum += smallestVector[j] * largestVector[i + j];\n }\n dotProductApplied[i] = sum;\n }\n\n return dotProductApplied;\n}\n/**\n * To scale the input array between the specified min and max values. The operation is performed inplace\n * if the options.inplace is specified. If only one of the min or max parameters is specified, then the scaling\n * will multiply the input array by min/min(input) or max/max(input)\n * @param input\n * @param options\n * @returns {*}\n */\nfunction scale(input, options = {}) {\n const {\n min,\n max\n } = options;\n\n var y = options.inPlace ? input : (new Array(input.length));\n var minMax = Stat.minMax(input);\n\n if (typeof max === 'number') {\n if (typeof min === 'number') {\n let factor = (max - min) / (minMax.max - minMax.min);\n for (let i = 0; i < y.length; i++) {\n y[i] = (input[i] - minMax.min) * factor + min;\n }\n } else if (minMax.max !== 0) {\n let factor = max / minMax.max;\n for (let i = 0; i < y.length; i++) {\n y[i] = input[i] * factor;\n }\n } else {\n options.min = minMax.min;\n y = scale(input, options);\n }\n } else if (typeof min === 'number') {\n if (minMax.min !== 0) {\n let factor = min / minMax.min;\n for (let i = 0; i < y.length; i++) {\n y[i] = input[i] * factor;\n }\n\n } else {\n options.max = minMax.max;\n y = scale(input, options);\n }\n }\n return y;\n}\n\nmodule.exports = {\n coordArrayToPoints: coordArrayToPoints,\n coordArrayToCoordMatrix: coordArrayToCoordMatrix,\n coordMatrixToCoordArray: coordMatrixToCoordArray,\n coordMatrixToPoints: transpose,\n pointsToCoordArray: pointsToCoordArray,\n pointsToCoordMatrix: transpose,\n applyDotProduct: applyDotProduct,\n scale: scale\n};\n\n","'use strict';\n\n/**\n *\n * Function that returns a Number array of equally spaced numberOfPoints\n * containing a representation of intensities of the spectra arguments x\n * and y.\n *\n * The options parameter contains an object in the following form:\n * from: starting point\n * to: last point\n * numberOfPoints: number of points between from and to\n * variant: \"slot\" or \"smooth\" - smooth is the default option\n *\n * The slot variant consist that each point in the new array is calculated\n * averaging the existing points between the slot that belongs to the current\n * value. The smooth variant is the same but takes the integral of the range\n * of the slot and divide by the step size between two points in the new array.\n *\n * @param x - sorted increasing x values\n * @param y\n * @param options\n * @returns {Array} new array with the equally spaced data.\n *\n */\nfunction getEquallySpacedData(x, y, options = {}) {\n var xLength = x.length;\n if (x.length > 1 && x[0] > x[1]) {\n x = x.slice().reverse();\n y = y.slice().reverse();\n }\n\n var {\n from = x[0],\n to = x[xLength - 1],\n variant = 'smooth',\n numberOfPoints = 100\n } = options;\n\n if (xLength !== y.length) {\n throw new RangeError(\"the x and y vector doesn't have the same size.\");\n }\n\n if (typeof from !== 'number' || isNaN(from)) {\n throw new RangeError(\"'from' option must be a number\");\n }\n\n if (typeof to !== 'number' || isNaN(to)) {\n throw new RangeError(\"'to' option must be a number\");\n }\n\n var reverse = from > to;\n if (reverse) {\n [from, to] = [to, from];\n }\n\n if (typeof numberOfPoints !== 'number' || isNaN(numberOfPoints)) {\n throw new RangeError(\"'numberOfPoints' option must be a number\");\n }\n if (numberOfPoints < 1) {\n throw new RangeError('the number of points must be at least 1');\n }\n\n var output = variant === 'slot' ? getEquallySpacedSlot(x, y, from, to, numberOfPoints) : getEquallySpacedSmooth(x, y, from, to, numberOfPoints);\n\n return reverse ? output.reverse() : output;\n}\n\n/**\n * function that retrieves the getEquallySpacedData with the variant \"smooth\"\n *\n * @param x\n * @param y\n * @param from - Initial point\n * @param to - Final point\n * @param numberOfPoints\n * @returns {Array} - Array of y's equally spaced with the variant \"smooth\"\n */\nfunction getEquallySpacedSmooth(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n\n var output = new Array(numberOfPoints);\n\n var initialOriginalStep = x[1] - x[0];\n var lastOriginalStep = x[xLength - 1] - x[xLength - 2];\n\n // Init main variables\n var min = from - halfStep;\n var max = from + halfStep;\n\n var previousX = Number.MIN_VALUE;\n var previousY = 0;\n var nextX = x[0] - initialOriginalStep;\n var nextY = 0;\n\n var currentValue = 0;\n var slope = 0;\n var intercept = 0;\n var sumAtMin = 0;\n var sumAtMax = 0;\n\n var i = 0; // index of input\n var j = 0; // index of output\n\n function getSlope(x0, y0, x1, y1) {\n return (y1 - y0) / (x1 - x0);\n }\n\n main: while (true) {\n\n if (previousX <= min && min <= nextX) {\n add = integral(0, min - previousX, slope, previousY);\n sumAtMin = currentValue + add;\n }\n\n while (nextX - max >= 0) {\n // no overlap with original point, just consume current value\n var add = integral(0, max - previousX, slope, previousY);\n sumAtMax = currentValue + add;\n\n output[j++] = (sumAtMax - sumAtMin) / step;\n\n if (j === numberOfPoints) {\n break main;\n }\n\n min = max;\n max += step;\n sumAtMin = sumAtMax;\n }\n\n currentValue += integral(previousX, nextX, slope, intercept);\n\n previousX = nextX;\n previousY = nextY;\n\n if (i < xLength) {\n nextX = x[i];\n nextY = y[i];\n i++;\n } else if (i === xLength) {\n nextX += lastOriginalStep;\n nextY = 0;\n }\n\n slope = getSlope(previousX, previousY, nextX, nextY);\n intercept = -slope * previousX + previousY;\n }\n\n return output;\n}\n\n/**\n * function that retrieves the getEquallySpacedData with the variant \"slot\"\n *\n * @param x\n * @param y\n * @param from - Initial point\n * @param to - Final point\n * @param numberOfPoints\n * @returns {Array} - Array of y's equally spaced with the variant \"slot\"\n */\nfunction getEquallySpacedSlot(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n var lastStep = x[x.length - 1] - x[x.length - 2];\n\n var start = from - halfStep;\n var output = new Array(numberOfPoints);\n\n // Init main variables\n var min = start;\n var max = start + step;\n\n var previousX = -Number.MAX_VALUE;\n var previousY = 0;\n var nextX = x[0];\n var nextY = y[0];\n var frontOutsideSpectra = 0;\n var backOutsideSpectra = true;\n\n var currentValue = 0;\n\n // for slot algorithm\n var currentPoints = 0;\n\n var i = 1; // index of input\n var j = 0; // index of output\n\n main: while (true) {\n if (previousX >= nextX) throw (new Error('x must be an increasing serie'));\n while (previousX - max > 0) {\n // no overlap with original point, just consume current value\n if (backOutsideSpectra) {\n currentPoints++;\n backOutsideSpectra = false;\n }\n\n output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints;\n j++;\n\n if (j === numberOfPoints) {\n break main;\n }\n\n min = max;\n max += step;\n currentValue = 0;\n currentPoints = 0;\n }\n\n if (previousX > min) {\n currentValue += previousY;\n currentPoints++;\n }\n\n if (previousX === -Number.MAX_VALUE || frontOutsideSpectra > 1) {\n currentPoints--;\n }\n\n previousX = nextX;\n previousY = nextY;\n\n if (i < xLength) {\n nextX = x[i];\n nextY = y[i];\n i++;\n } else {\n nextX += lastStep;\n nextY = 0;\n frontOutsideSpectra++;\n }\n }\n\n return output;\n}\n/**\n * Function that calculates the integral of the line between two\n * x-coordinates, given the slope and intercept of the line.\n * @param x0\n * @param x1\n * @param slope\n * @param intercept\n * @returns {number} integral value.\n */\nfunction integral(x0, x1, slope, intercept) {\n return (0.5 * slope * x1 * x1 + intercept * x1) - (0.5 * slope * x0 * x0 + intercept * x0);\n}\n\nexports.getEquallySpacedData = getEquallySpacedData;\nexports.integral = integral;\n","'use strict';\n\nexports.SNV = SNV;\nvar Stat = require('ml-stat').array;\n\n/**\n * Function that applies the standard normal variate (SNV) to an array of values.\n *\n * @param data - Array of values.\n * @returns {Array} - applied the SNV.\n */\nfunction SNV(data) {\n var mean = Stat.mean(data);\n var std = Stat.standardDeviation(data);\n var result = data.slice();\n for (var i = 0; i < data.length; i++) {\n result[i] = (result[i] - mean) / std;\n }\n return result;\n}\n","import isArray from 'is-any-array';\n\n/**\n * Computes the mode of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction mode(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var maxValue = 0;\n var maxCount = 0;\n var count = 0;\n var counts = {};\n\n for (var i = 0; i < input.length; ++i) {\n var element = input[i];\n count = counts[element];\n\n if (count) {\n counts[element]++;\n count++;\n } else {\n counts[element] = count = 1;\n }\n\n if (count > maxCount) {\n maxCount = count;\n maxValue = input[i];\n }\n }\n\n return maxValue;\n}\n\nexport default mode;\n","/**\n * Computes the norm of the given values\n * @param {Array} input\n * @param {object} [options={}]\n * @param {string} [algorithm='absolute']\n * @return {number}\n */\nfunction norm(input) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var _options$algorithm = options.algorithm,\n algorithm = _options$algorithm === void 0 ? 'absolute' : _options$algorithm;\n\n if (!Array.isArray(input)) {\n throw new Error('input must be an array');\n }\n\n if (input.length === 0) {\n throw new Error('input must not be empty');\n }\n\n switch (algorithm.toLowerCase()) {\n case 'absolute':\n var sum = absoluteSum(input);\n if (sum === 0) return input.slice(0);\n return input.map(function (element) {\n return element / sum;\n });\n\n default:\n throw new Error(\"norm: unknown algorithm: \".concat(algorithm));\n }\n}\n\nfunction absoluteSum(input) {\n var sum = 0;\n\n for (var i = 0; i < input.length; i++) {\n sum += Math.abs(input[i]);\n }\n\n return sum;\n}\n\nexport default norm;\n","import variance from 'ml-array-variance';\n\n/**\n * Computes the standard deviation of the given values\n * @param {Array} values\n * @param {object} [options]\n * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n.\n * @param {number} [options.mean = arrayMean] - precalculated mean, if any.\n * @return {number}\n */\n\nfunction standardDeviation(values) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return Math.sqrt(variance(values, options));\n}\n\nexport default standardDeviation;\n","/**\n * Merge abscissa values if the ordinate value is in a list of centroids\n * @param {object} originalPoints\n * @param {Array} originalPoints.x\n * @param {Array} originalPoints.y\n * @param {Array} centroids\n * @param {object} [options]\n * @param {number} [options.window = 0.01] - has to be a positive number\n * @return {{x: Array, y: Array}}\n */\nexport default function mergeByCentroids(\n originalPoints,\n centroids,\n options = {}\n) {\n const { window = 0.01 } = options;\n\n var mergedPoints = {\n x: centroids.slice(),\n y: new Array(centroids.length).fill(0)\n };\n\n var originalIndex = 0;\n var mergedIndex = 0;\n while (\n originalIndex < originalPoints.x.length &&\n mergedIndex < centroids.length\n ) {\n var diff = originalPoints.x[originalIndex] - centroids[mergedIndex];\n if (Math.abs(diff) < window) {\n mergedPoints.y[mergedIndex] += originalPoints.y[originalIndex++];\n } else if (diff < 0) {\n originalIndex++;\n } else {\n mergedIndex++;\n }\n }\n\n return mergedPoints;\n}\n","import binarySearch from 'binary-search';\nimport { asc, desc } from 'num-sort';\n\n/**\n *\n * @param {object} points\n * @param {Array} originalPoints.x\n * @param {Array} originalPoints.y\n * @param {*} options\n * @return {{x: Array, y: Array}}\n */\nexport default function closestX(points, options) {\n const { x, y } = points;\n const { target = x[0], reverse = false } = options;\n\n let index;\n if (reverse) {\n index = binarySearch(x, target, desc);\n } else {\n index = binarySearch(x, target, asc);\n }\n\n if (index >= 0) {\n return {\n x: x[index],\n y: y[index]\n };\n } else {\n index = ~index;\n if (\n (index !== 0 && Math.abs(x[index] - target) > 0.5) ||\n index === x.length\n ) {\n return {\n x: x[index - 1],\n y: y[index - 1]\n };\n } else {\n return {\n x: x[index],\n y: y[index]\n };\n }\n }\n}\n","/**\n * Merge abscissas values on similar ordinates and weight the group of abscissas\n * @param {object} points\n * @param {Array} points.x - sorted abscissas values\n * @param {Array} points.y - ordinates values\n * @param {object} [options]\n * @param {number} [options.groupWidth = 0.001] - window for abscissas to merge\n * @return {{x: Array, y: Array}}\n */\nexport default function maxMerge(points, options = {}) {\n const { x, y } = points;\n const { groupWidth = 0.001 } = options;\n\n var merged = { x: [], y: [] };\n var maxAbscissa = { x: [], y: [] };\n var size = 0;\n var index = 0;\n\n while (index < x.length) {\n if (size === 0 || x[index] - merged.x[size - 1] > groupWidth) {\n maxAbscissa.x.push(x[index]);\n maxAbscissa.y.push(y[index]);\n merged.x.push(x[index]);\n merged.y.push(y[index]);\n index++;\n size++;\n } else {\n if (y[index] > maxAbscissa.y[size - 1]) {\n maxAbscissa.x[size - 1] = x[index];\n maxAbscissa.y[size - 1] = y[index];\n }\n merged.x[size - 1] = x[index];\n merged.y[size - 1] += y[index];\n index++;\n }\n }\n\n merged.x = maxAbscissa.x.slice();\n\n return merged;\n}\n","import binarySearch from 'binary-search';\nimport { asc, desc } from 'num-sort';\n\n/**\n * @param {object} points\n * @param {Array} points.x - sorted abscissas values\n * @param {Array} points.y - ordinates values\n * @param {object} [options]\n * @param {object} [options.from = {index: 0}]\n * @param {object} [options.to = {index: x.length-1}]\n * @param {boolean} [options.reverse = false]\n * @return {{index: number, value: number}}\n */\nexport default function maxY(points, options = {}) {\n const { x, y } = points;\n let {\n from = { index: 0 },\n to = { index: x.length },\n reverse = false\n } = options;\n\n if (from.value !== undefined && from.index === undefined) {\n from.index = calculateIndex(from.value, x, reverse);\n }\n\n if (to.value !== undefined && to.index === undefined) {\n to.index = calculateIndex(to.value, x, reverse);\n }\n\n var currentMax = Number.MIN_VALUE;\n var currentIndex;\n for (var i = from.index; i < to.index; i++) {\n if (currentMax < y[i]) {\n currentMax = y[i];\n currentIndex = i;\n }\n }\n\n return {\n index: currentIndex,\n value: currentMax\n };\n}\n\n/**\n * @param {number} value\n * @param {Array} x\n * @param {boolean} reverse\n * @return {number} index of the value in the array\n */\nfunction calculateIndex(value, x, reverse) {\n let index;\n if (reverse) {\n index = binarySearch(x, value, desc);\n } else {\n index = binarySearch(x, value, asc);\n }\n\n if (index < 0) {\n throw new Error(`the value ${value} doesn't belongs to the abscissa value`);\n }\n\n return index;\n}\n","export default function sortX(points, options = {}) {\n const { x, y } = points;\n const { reverse = false } = options;\n\n var sortFunc;\n if (!reverse) {\n sortFunc = (a, b) => a.x - b.x;\n } else {\n sortFunc = (a, b) => b.x - a.x;\n }\n\n var grouped = x\n .map((val, index) => ({\n x: val,\n y: y[index]\n }))\n .sort(sortFunc);\n\n var response = { x: x.slice(), y: y.slice() };\n for (var i = 0; i < x.length; i++) {\n response.x[i] = grouped[i].x;\n response.y[i] = grouped[i].y;\n }\n\n return response;\n}\n","\n/**\n * In place modification of the 2 arrays to make X unique and sum the Y if X has the same value\n * @param {object} [points={}] : Object of points contains property x (an array) and y (an array)\n * @return points\n */\n\nexport default function uniqueX(points = {}) {\n const { x, y } = points;\n if (x.length < 2) return;\n if (x.length !== y.length) {\n throw new Error('The X and Y arrays mush have the same length');\n }\n\n let current = x[0];\n let counter = 0;\n\n for (let i = 1; i < x.length; i++) {\n if (current !== x[i]) {\n counter++;\n current = x[i];\n x[counter] = x[i];\n if (i !== counter) {\n y[counter] = 0;\n }\n }\n if (i !== counter) {\n y[counter] += y[i];\n }\n }\n\n x.length = counter + 1;\n y.length = counter + 1;\n}\n","/**\n * Merge abscissas values on similar ordinates and weight the group of abscissas\n * @param {object} points\n * @param {Array} points.x - sorted abscissas values\n * @param {Array} points.y - ordinates values\n * @param {object} [options]\n * @param {number} [options.groupWidth = 0.001] - window for abscissas to merge\n * @return {{x: Array, y: Array}}\n */\nexport default function weightedMerge(points, options = {}) {\n const { x, y } = points;\n const { groupWidth = 0.001 } = options;\n\n var merged = { x: [], y: [] };\n var weightedAbscissa = { x: [], y: [] };\n var size = 0;\n var index = 0;\n\n while (index < x.length) {\n if (size === 0 || x[index] - merged.x[size - 1] > groupWidth) {\n weightedAbscissa.x.push(x[index] * y[index]);\n weightedAbscissa.y.push(y[index]);\n merged.x.push(x[index]);\n merged.y.push(y[index]);\n index++;\n size++;\n } else {\n weightedAbscissa.x[size - 1] += x[index] * y[index];\n weightedAbscissa.y[size - 1] += y[index];\n merged.x[size - 1] = x[index];\n merged.y[size - 1] += y[index];\n index++;\n }\n }\n\n for (var i = 0; i < merged.x.length; i++) {\n merged.x[i] = weightedAbscissa.x[i] / weightedAbscissa.y[i];\n }\n\n return merged;\n}\n","export function squaredEuclidean(p, q) {\r\n let d = 0;\r\n for (let i = 0; i < p.length; i++) {\r\n d += (p[i] - q[i]) * (p[i] - q[i]);\r\n }\r\n return d;\r\n}\r\nexport function euclidean(p, q) {\r\n return Math.sqrt(squaredEuclidean(p, q));\r\n}\r\n","export function squaredEuclidean(p, q) {\r\n let d = 0;\r\n for (let i = 0; i < p.length; i++) {\r\n d += (p[i] - q[i]) * (p[i] - q[i]);\r\n }\r\n return d;\r\n}\r\nexport function euclidean(p, q) {\r\n return Math.sqrt(squaredEuclidean(p, q));\r\n}\r\n","'use strict';\nimport { squaredEuclidean } from 'ml-distance-euclidean';\nconst defaultOptions = {\n distanceFunction: squaredEuclidean\n};\nexport default function nearestVector(listVectors, vector, options = defaultOptions) {\n const distanceFunction = options.distanceFunction || defaultOptions.distanceFunction;\n const similarityFunction = options.similarityFunction || defaultOptions.similarityFunction;\n let vectorIndex = -1;\n if (typeof similarityFunction === 'function') {\n // maximum similarity\n let maxSim = Number.MIN_VALUE;\n for (let j = 0; j < listVectors.length; j++) {\n const sim = similarityFunction(vector, listVectors[j]);\n if (sim > maxSim) {\n maxSim = sim;\n vectorIndex = j;\n }\n }\n }\n else if (typeof distanceFunction === 'function') {\n // minimum distance\n let minDist = Number.MAX_VALUE;\n for (let i = 0; i < listVectors.length; i++) {\n const dist = distanceFunction(vector, listVectors[i]);\n if (dist < minDist) {\n minDist = dist;\n vectorIndex = i;\n }\n }\n }\n else {\n throw new Error(\"A similarity or distance function it's required\");\n }\n return vectorIndex;\n}\nexport function findNearestVector(vectorList, vector, options = defaultOptions) {\n const index = nearestVector(vectorList, vector, options);\n return vectorList[index];\n}\n","import nearestVector from 'ml-nearest-vector';\n\n/**\n * Calculates the distance matrix for a given array of points\n * @ignore\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @param {function} distance - Distance function to use between the points\n * @return {Array>} - matrix with the distance values\n */\nexport function calculateDistanceMatrix(data, distance) {\n var distanceMatrix = new Array(data.length);\n for (var i = 0; i < data.length; ++i) {\n for (var j = i; j < data.length; ++j) {\n if (!distanceMatrix[i]) {\n distanceMatrix[i] = new Array(data.length);\n }\n if (!distanceMatrix[j]) {\n distanceMatrix[j] = new Array(data.length);\n }\n const dist = distance(data[i], data[j]);\n distanceMatrix[i][j] = dist;\n distanceMatrix[j][i] = dist;\n }\n }\n return distanceMatrix;\n}\n\n/**\n * Updates the cluster identifier based in the new data\n * @ignore\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @param {Array>} centers - the K centers in format [x,y,z,...]\n * @param {Array } clusterID - the cluster identifier for each data dot\n * @param {function} distance - Distance function to use between the points\n * @return {Array} the cluster identifier for each data dot\n */\nexport function updateClusterID(data, centers, clusterID, distance) {\n for (var i = 0; i < data.length; i++) {\n clusterID[i] = nearestVector(centers, data[i], {\n distanceFunction: distance\n });\n }\n return clusterID;\n}\n\n/**\n * Update the center values based in the new configurations of the clusters\n * @ignore\n * @param {Array>} prevCenters - Centroids from the previous iteration\n * @param {Array >} data - the [x,y,z,...] points to cluster\n * @param {Array } clusterID - the cluster identifier for each data dot\n * @param {number} K - Number of clusters\n * @return {Array} he K centers in format [x,y,z,...]\n */\nexport function updateCenters(prevCenters, data, clusterID, K) {\n const nDim = data[0].length;\n\n // copy previous centers\n var centers = new Array(K);\n var centersLen = new Array(K);\n for (var i = 0; i < K; i++) {\n centers[i] = new Array(nDim);\n centersLen[i] = 0;\n for (var j = 0; j < nDim; j++) {\n centers[i][j] = 0;\n }\n }\n\n // add the value for all dimensions of the point\n for (var l = 0; l < data.length; l++) {\n centersLen[clusterID[l]]++;\n for (var dim = 0; dim < nDim; dim++) {\n centers[clusterID[l]][dim] += data[l][dim];\n }\n }\n\n // divides by length\n for (var id = 0; id < K; id++) {\n for (var d = 0; d < nDim; d++) {\n if (centersLen[id]) {\n centers[id][d] /= centersLen[id];\n } else {\n centers[id][d] = prevCenters[id][d];\n }\n }\n }\n return centers;\n}\n\n/**\n * The centers have moved more than the tolerance value?\n * @ignore\n * @param {Array>} centers - the K centers in format [x,y,z,...]\n * @param {Array>} oldCenters - the K old centers in format [x,y,z,...]\n * @param {function} distanceFunction - Distance function to use between the points\n * @param {number} tolerance - Allowed distance for the centroids to move\n * @return {boolean}\n */\nexport function hasConverged(centers, oldCenters, distanceFunction, tolerance) {\n for (var i = 0; i < centers.length; i++) {\n if (distanceFunction(centers[i], oldCenters[i]) > tolerance) {\n return false;\n }\n }\n return true;\n}\n","import Random from 'ml-random';\nimport { squaredEuclidean } from 'ml-distance-euclidean';\nimport { Matrix } from 'ml-matrix';\n\n/**\n * Choose K different random points from the original data\n * @ignore\n * @param {Array>} data - Points in the format to cluster [x,y,z,...]\n * @param {number} K - number of clusters\n * @param {number} seed - seed for random number generation\n * @return {Array>} - Initial random points\n */\nexport function random(data, K, seed) {\n const random = new Random(seed);\n return random.choice(data, { size: K });\n}\n\n/**\n * Chooses the most distant points to a first random pick\n * @ignore\n * @param {Array>} data - Points in the format to cluster [x,y,z,...]\n * @param {number} K - number of clusters\n * @param {Array>} distanceMatrix - matrix with the distance values\n * @param {number} seed - seed for random number generation\n * @return {Array>} - Initial random points\n */\nexport function mostDistant(data, K, distanceMatrix, seed) {\n const random = new Random(seed);\n var ans = new Array(K);\n // chooses a random point as initial cluster\n ans[0] = Math.floor(random.random() * data.length);\n\n if (K > 1) {\n // chooses the more distant point\n var maxDist = { dist: -1, index: -1 };\n for (var l = 0; l < data.length; ++l) {\n if (distanceMatrix[ans[0]][l] > maxDist.dist) {\n maxDist.dist = distanceMatrix[ans[0]][l];\n maxDist.index = l;\n }\n }\n ans[1] = maxDist.index;\n\n if (K > 2) {\n // chooses the set of points that maximises the min distance\n for (var k = 2; k < K; ++k) {\n var center = { dist: -1, index: -1 };\n for (var m = 0; m < data.length; ++m) {\n // minimum distance to centers\n var minDistCent = { dist: Number.MAX_VALUE, index: -1 };\n for (var n = 0; n < k; ++n) {\n if (\n distanceMatrix[n][m] < minDistCent.dist &&\n ans.indexOf(m) === -1\n ) {\n minDistCent = {\n dist: distanceMatrix[n][m],\n index: m\n };\n }\n }\n\n if (\n minDistCent.dist !== Number.MAX_VALUE &&\n minDistCent.dist > center.dist\n ) {\n center = Object.assign({}, minDistCent);\n }\n }\n\n ans[k] = center.index;\n }\n }\n }\n\n return ans.map((index) => data[index]);\n}\n\n// Implementation inspired from scikit\nexport function kmeanspp(X, K, options = {}) {\n X = new Matrix(X);\n const nSamples = X.length;\n const random = new Random(options.seed);\n // Set the number of trials\n const centers = [];\n const localTrials = options.localTrials || 2 + Math.floor(Math.log(K));\n\n // Pick the first center at random from the dataset\n const firstCenterIdx = random.randInt(nSamples);\n centers.push(X[firstCenterIdx].slice());\n\n // Init closest distances\n let closestDistSquared = [X.map((x) => squaredEuclidean(x, centers[0]))];\n let cumSumClosestDistSquared = [cumSum(closestDistSquared[0])];\n const factor = 1 / cumSumClosestDistSquared[0][nSamples - 1];\n let probabilities = Matrix.mul(closestDistSquared, factor);\n\n // Iterate over the remaining centers\n for (let i = 1; i < K; i++) {\n const candidateIdx = random.choice(nSamples, {\n replace: true,\n size: localTrials,\n probabilities: probabilities[0]\n });\n\n const candidates = X.selection(candidateIdx, range(X[0].length));\n const distanceToCandidates = euclidianDistances(candidates, X);\n\n let bestCandidate;\n let bestPot;\n let bestDistSquared;\n\n for (let j = 0; j < localTrials; j++) {\n const newDistSquared = Matrix.min(closestDistSquared, [distanceToCandidates[j]]);\n const newPot = newDistSquared.sum();\n if (bestCandidate === undefined || newPot < bestPot) {\n bestCandidate = candidateIdx[j];\n bestPot = newPot;\n bestDistSquared = newDistSquared;\n }\n }\n centers[i] = X[bestCandidate].slice();\n closestDistSquared = bestDistSquared;\n cumSumClosestDistSquared = [cumSum(closestDistSquared[0])];\n probabilities = Matrix.mul(\n closestDistSquared,\n 1 / cumSumClosestDistSquared[0][nSamples - 1]\n );\n }\n return centers;\n}\n\nfunction euclidianDistances(A, B) {\n const result = new Matrix(A.length, B.length);\n for (let i = 0; i < A.length; i++) {\n for (let j = 0; j < B.length; j++) {\n result.set(i, j, squaredEuclidean(A.getRow(i), B.getRow(j)));\n }\n }\n return result;\n}\n\nfunction range(l) {\n let r = [];\n for (let i = 0; i < l; i++) {\n r.push(i);\n }\n return r;\n}\n\nfunction cumSum(arr) {\n let cumSum = [arr[0]];\n for (let i = 1; i < arr.length; i++) {\n cumSum[i] = cumSum[i - 1] + arr[i];\n }\n return cumSum;\n}\n","import { updateClusterID } from './utils';\n\nconst distanceSymbol = Symbol('distance');\n\nexport default class KMeansResult {\n /**\n * Result of the kmeans algorithm\n * @param {Array} clusters - the cluster identifier for each data dot\n * @param {Array>} centroids - the K centers in format [x,y,z,...], the error and size of the cluster\n * @param {boolean} converged - Converge criteria satisfied\n * @param {number} iterations - Current number of iterations\n * @param {function} distance - (*Private*) Distance function to use between the points\n * @constructor\n */\n constructor(clusters, centroids, converged, iterations, distance) {\n this.clusters = clusters;\n this.centroids = centroids;\n this.converged = converged;\n this.iterations = iterations;\n this[distanceSymbol] = distance;\n }\n\n /**\n * Allows to compute for a new array of points their cluster id\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @return {Array} - cluster id for each point\n */\n nearest(data) {\n const clusterID = new Array(data.length);\n const centroids = this.centroids.map(function (centroid) {\n return centroid.centroid;\n });\n return updateClusterID(data, centroids, clusterID, this[distanceSymbol]);\n }\n\n /**\n * Returns a KMeansResult with the error and size of the cluster\n * @ignore\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @return {KMeansResult}\n */\n computeInformation(data) {\n var enrichedCentroids = this.centroids.map(function (centroid) {\n return {\n centroid: centroid,\n error: 0,\n size: 0\n };\n });\n\n for (var i = 0; i < data.length; i++) {\n enrichedCentroids[this.clusters[i]].error += this[distanceSymbol](\n data[i],\n this.centroids[this.clusters[i]]\n );\n enrichedCentroids[this.clusters[i]].size++;\n }\n\n for (var j = 0; j < this.centroids.length; j++) {\n if (enrichedCentroids[j].size) {\n enrichedCentroids[j].error /= enrichedCentroids[j].size;\n } else {\n enrichedCentroids[j].error = null;\n }\n }\n\n return new KMeansResult(\n this.clusters,\n enrichedCentroids,\n this.converged,\n this.iterations,\n this[distanceSymbol]\n );\n }\n}\n","import { squaredEuclidean } from 'ml-distance-euclidean';\n\nimport {\n updateClusterID,\n updateCenters,\n hasConverged,\n calculateDistanceMatrix\n} from './utils';\nimport { mostDistant, random, kmeanspp } from './initialization';\nimport KMeansResult from './KMeansResult';\n\nconst defaultOptions = {\n maxIterations: 100,\n tolerance: 1e-6,\n withIterations: false,\n initialization: 'kmeans++',\n distanceFunction: squaredEuclidean\n};\n\n/**\n * Each step operation for kmeans\n * @ignore\n * @param {Array>} centers - K centers in format [x,y,z,...]\n * @param {Array>} data - Points [x,y,z,...] to cluster\n * @param {Array} clusterID - Cluster identifier for each data dot\n * @param {number} K - Number of clusters\n * @param {object} [options] - Option object\n * @param {number} iterations - Current number of iterations\n * @return {KMeansResult}\n */\nfunction step(centers, data, clusterID, K, options, iterations) {\n clusterID = updateClusterID(\n data,\n centers,\n clusterID,\n options.distanceFunction\n );\n var newCenters = updateCenters(centers, data, clusterID, K);\n var converged = hasConverged(\n newCenters,\n centers,\n options.distanceFunction,\n options.tolerance\n );\n return new KMeansResult(\n clusterID,\n newCenters,\n converged,\n iterations,\n options.distanceFunction\n );\n}\n\n/**\n * Generator version for the algorithm\n * @ignore\n * @param {Array>} centers - K centers in format [x,y,z,...]\n * @param {Array>} data - Points [x,y,z,...] to cluster\n * @param {Array} clusterID - Cluster identifier for each data dot\n * @param {number} K - Number of clusters\n * @param {object} [options] - Option object\n */\nfunction* kmeansGenerator(centers, data, clusterID, K, options) {\n var converged = false;\n var stepNumber = 0;\n var stepResult;\n while (!converged && stepNumber < options.maxIterations) {\n stepResult = step(centers, data, clusterID, K, options, ++stepNumber);\n yield stepResult.computeInformation(data);\n converged = stepResult.converged;\n centers = stepResult.centroids;\n }\n}\n\n/**\n * K-means algorithm\n * @param {Array>} data - Points in the format to cluster [x,y,z,...]\n * @param {number} K - Number of clusters\n * @param {object} [options] - Option object\n * @param {number} [options.maxIterations = 100] - Maximum of iterations allowed\n * @param {number} [options.tolerance = 1e-6] - Error tolerance\n * @param {boolean} [options.withIterations = false] - Store clusters and centroids for each iteration\n * @param {function} [options.distanceFunction = squaredDistance] - Distance function to use between the points\n * @param {number} [options.seed] - Seed for random initialization.\n * @param {string|Array>} [options.initialization = 'kmeans++'] - K centers in format [x,y,z,...] or a method for initialize the data:\n * * You can either specify your custom start centroids, or select one of the following initialization method:\n * * `'kmeans++'` will use the kmeans++ method as described by http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf\n * * `'random'` will choose K random different values.\n * * `'mostDistant'` will choose the more distant points to a first random pick\n * @return {KMeansResult} - Cluster identifier for each data dot and centroids with the following fields:\n * * `'clusters'`: Array of indexes for the clusters.\n * * `'centroids'`: Array with the resulting centroids.\n * * `'iterations'`: Number of iterations that took to converge\n */\nexport default function kmeans(data, K, options) {\n options = Object.assign({}, defaultOptions, options);\n\n if (K <= 0 || K > data.length || !Number.isInteger(K)) {\n throw new Error(\n 'K should be a positive integer smaller than the number of points'\n );\n }\n\n var centers;\n if (Array.isArray(options.initialization)) {\n if (options.initialization.length !== K) {\n throw new Error('The initial centers should have the same length as K');\n } else {\n centers = options.initialization;\n }\n } else {\n switch (options.initialization) {\n case 'kmeans++':\n centers = kmeanspp(data, K, options);\n break;\n case 'random':\n centers = random(data, K, options.seed);\n break;\n case 'mostDistant':\n centers = mostDistant(\n data,\n K,\n calculateDistanceMatrix(data, options.distanceFunction),\n options.seed\n );\n break;\n default:\n throw new Error(\n `Unknown initialization method: \"${options.initialization}\"`\n );\n }\n }\n\n // infinite loop until convergence\n if (options.maxIterations === 0) {\n options.maxIterations = Number.MAX_VALUE;\n }\n\n var clusterID = new Array(data.length);\n if (options.withIterations) {\n return kmeansGenerator(centers, data, clusterID, K, options);\n } else {\n var converged = false;\n var stepNumber = 0;\n var stepResult;\n while (!converged && stepNumber < options.maxIterations) {\n stepResult = step(centers, data, clusterID, K, options, ++stepNumber);\n converged = stepResult.converged;\n centers = stepResult.centroids;\n }\n return stepResult.computeInformation(data);\n }\n}\n","import Random from 'random-js';\nimport Matrix from 'ml-matrix';\n\nexport function checkFloat(n) {\n return n > 0.0 && n <= 1.0;\n}\n\n/**\n * Select n with replacement elements on the training set and values, where n is the size of the training set.\n * @ignore\n * @param {Matrix} trainingSet\n * @param {Array} trainingValue\n * @param {number} seed - seed for the random selection, must be a 32-bit integer.\n * @return {object} with new X and y.\n */\nexport function examplesBaggingWithReplacement(trainingSet, trainingValue, seed) {\n var engine = Random.engines.mt19937();\n var distribution = Random.integer(0, trainingSet.rows - 1);\n if (seed === undefined) {\n engine = engine.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = engine.seed(seed);\n } else {\n throw new RangeError(`Expected seed must be undefined or integer not ${seed}`);\n }\n\n var Xr = new Array(trainingSet.rows);\n var yr = new Array(trainingSet.rows);\n\n for (var i = 0; i < trainingSet.rows; ++i) {\n var index = distribution(engine);\n Xr[i] = trainingSet[index];\n yr[i] = trainingValue[index];\n }\n\n return {\n X: new Matrix(Xr),\n y: yr\n };\n}\n\n/**\n * selects n features from the training set with or without replacement, returns the new training set and the indexes used.\n * @ignore\n * @param {Matrix} trainingSet\n * @param {number} n - features.\n * @param {boolean} replacement\n * @param {number} seed - seed for the random selection, must be a 32-bit integer.\n * @return {object}\n */\nexport function featureBagging(trainingSet, n, replacement, seed) {\n if (trainingSet.columns < n) {\n throw new RangeError('N should be less or equal to the number of columns of X');\n }\n\n var distribution = Random.integer(0, trainingSet.columns - 1);\n var engine = Random.engines.mt19937();\n if (seed === undefined) {\n engine = engine.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = engine.seed(seed);\n } else {\n throw new RangeError(`Expected seed must be undefined or integer not ${seed}`);\n }\n\n var toRet = new Matrix(trainingSet.rows, n);\n\n if (replacement) {\n var usedIndex = new Array(n);\n for (var i = 0; i < n; ++i) {\n var index = distribution(engine);\n usedIndex[i] = index;\n toRet.setColumn(i, trainingSet.getColumn(index));\n }\n } else {\n usedIndex = new Set();\n index = distribution(engine);\n for (i = 0; i < n; ++i) {\n while (usedIndex.has(index)) {\n index = distribution(engine);\n }\n toRet.setColumn(i, trainingSet.getColumn(index));\n usedIndex.add(index);\n }\n usedIndex = Array.from(usedIndex);\n }\n\n return {\n X: toRet,\n usedIndex: usedIndex\n };\n}\n","import {\n DecisionTreeClassifier as DTClassifier,\n DecisionTreeRegression as DTRegression\n} from 'ml-cart';\nimport { Matrix, WrapperMatrix2D } from 'ml-matrix';\n\nimport * as Utils from './utils';\n\n/**\n * @class RandomForestBase\n */\nexport class RandomForestBase {\n /**\n * Create a new base random forest for a classifier or regression model.\n * @constructor\n * @param {object} options\n * @param {number|String} [options.maxFeatures] - the number of features used on each estimator.\n * * if is an integer it selects maxFeatures elements over the sample features.\n * * if is a float between (0, 1), it takes the percentage of features.\n * @param {boolean} [options.replacement] - use replacement over the sample features.\n * @param {number} [options.seed] - seed for feature and samples selection, must be a 32-bit integer.\n * @param {number} [options.nEstimators] - number of estimator to use.\n * @param {object} [options.treeOptions] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/}\n * @param {boolean} [options.isClassifier] - boolean to check if is a classifier or regression model (used by subclasses).\n * @param {boolean} [options.useSampleBagging] - use bagging over training samples.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.replacement = model.replacement;\n this.maxFeatures = model.maxFeatures;\n this.nEstimators = model.nEstimators;\n this.treeOptions = model.treeOptions;\n this.isClassifier = model.isClassifier;\n this.seed = model.seed;\n this.n = model.n;\n this.indexes = model.indexes;\n this.useSampleBagging = model.useSampleBagging;\n\n var Estimator = this.isClassifier ? DTClassifier : DTRegression;\n this.estimators = model.estimators.map((est) => Estimator.load(est));\n } else {\n this.replacement = options.replacement;\n this.maxFeatures = options.maxFeatures;\n this.nEstimators = options.nEstimators;\n this.treeOptions = options.treeOptions;\n this.isClassifier = options.isClassifier;\n this.seed = options.seed;\n this.useSampleBagging = options.useSampleBagging;\n }\n }\n\n /**\n * Train the decision tree with the given training set and labels.\n * @param {Matrix|Array} trainingSet\n * @param {Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n\n this.maxFeatures = this.maxFeatures || trainingSet.columns;\n\n if (Utils.checkFloat(this.maxFeatures)) {\n this.n = Math.floor(trainingSet.columns * this.maxFeatures);\n } else if (Number.isInteger(this.maxFeatures)) {\n if (this.maxFeatures > trainingSet.columns) {\n throw new RangeError(`The maxFeatures parameter should be less than ${trainingSet.columns}`);\n } else {\n this.n = this.maxFeatures;\n }\n } else {\n throw new RangeError(`Cannot process the maxFeatures parameter ${this.maxFeatures}`);\n }\n\n\n if (this.isClassifier) {\n var Estimator = DTClassifier;\n } else {\n Estimator = DTRegression;\n }\n\n this.estimators = new Array(this.nEstimators);\n this.indexes = new Array(this.nEstimators);\n\n for (var i = 0; i < this.nEstimators; ++i) {\n var res = this.useSampleBagging ? Utils.examplesBaggingWithReplacement(trainingSet, trainingValues, this.seed) : { X: trainingSet, y: trainingValues };\n var X = res.X;\n var y = res.y;\n\n res = Utils.featureBagging(X, this.n, this.replacement, this.seed);\n X = res.X;\n\n this.indexes[i] = res.usedIndex;\n this.estimators[i] = new Estimator(this.treeOptions);\n this.estimators[i].train(X, y);\n }\n }\n\n /**\n * Method that returns the way the algorithm generates the predictions, for example, in classification\n * you can return the mode of all predictions retrieved by the trees, or in case of regression you can\n * use the mean or the median.\n * @abstract\n * @param {Array} values - predictions of the estimators.\n * @return {number} prediction.\n */\n // eslint-disable-next-line no-unused-vars\n selection(values) {\n throw new Error('Abstract method \\'selection\\' not implemented!');\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Matrix|Array} toPredict\n * @return {Array} predictions\n */\n predict(toPredict) {\n var predictionValues = new Array(this.nEstimators);\n toPredict = Matrix.checkMatrix(toPredict);\n for (var i = 0; i < this.nEstimators; ++i) {\n var X = toPredict.columnSelectionView(this.indexes[i]); // get features for estimator\n predictionValues[i] = this.estimators[i].predict(X);\n }\n\n predictionValues = new WrapperMatrix2D(predictionValues).transposeView();\n var predictions = new Array(predictionValues.rows);\n for (i = 0; i < predictionValues.rows; ++i) {\n predictions[i] = this.selection(predictionValues.getRow(i));\n }\n\n return predictions;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n indexes: this.indexes,\n n: this.n,\n replacement: this.replacement,\n maxFeatures: this.maxFeatures,\n nEstimators: this.nEstimators,\n treeOptions: this.treeOptions,\n isClassifier: this.isClassifier,\n seed: this.seed,\n estimators: this.estimators.map((est) => est.toJSON()),\n useSampleBagging: this.useSampleBagging\n };\n }\n}\n","import { RandomForestBase } from './RandomForestBase';\n\nconst defaultOptions = {\n maxFeatures: 1.0,\n replacement: true,\n nEstimators: 10,\n seed: 42,\n useSampleBagging: false\n};\n\n/**\n * @class RandomForestClassifier\n * @augments RandomForestBase\n */\nexport class RandomForestClassifier extends RandomForestBase {\n /**\n * Create a new base random forest for a classifier or regression model.\n * @constructor\n * @param {object} options\n * @param {number} [options.maxFeatures=1.0] - the number of features used on each estimator.\n * * if is an integer it selects maxFeatures elements over the sample features.\n * * if is a float between (0, 1), it takes the percentage of features.\n * @param {boolean} [options.replacement=true] - use replacement over the sample features.\n * @param {number} [options.seed=42] - seed for feature and samples selection, must be a 32-bit integer.\n * @param {number} [options.nEstimators=10] - number of estimator to use.\n * @param {object} [options.treeOptions={}] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/}\n * @param {boolean} [options.useSampleBagging=false] - use bagging over training samples.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n super(true, model.baseModel);\n } else {\n options = Object.assign({}, defaultOptions, options);\n options.isClassifier = true;\n super(options);\n }\n }\n\n /**\n * retrieve the prediction given the selection method.\n * @param {Array} values - predictions of the estimators.\n * @return {number} prediction\n */\n selection(values) {\n return mode(values);\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n var baseModel = super.toJSON();\n return {\n baseModel: baseModel,\n name: 'RFClassifier'\n };\n }\n\n /**\n * Load a Decision tree classifier with the given model.\n * @param {object} model\n * @return {RandomForestClassifier}\n */\n static load(model) {\n if (model.name !== 'RFClassifier') {\n throw new RangeError(`Invalid model: ${model.name}`);\n }\n\n return new RandomForestClassifier(true, model);\n }\n}\n\n/**\n * Return the most repeated element on the array.\n * @param {Array} arr\n * @return {number} mode\n */\nfunction mode(arr) {\n return arr.sort((a, b) =>\n arr.filter((v) => v === a).length\n - arr.filter((v) => v === b).length\n ).pop();\n}\n","import arrayMean from 'ml-array-mean';\nimport arrayMedian from 'ml-array-median';\n\nimport { RandomForestBase } from './RandomForestBase';\n\nconst selectionMethods = {\n mean: arrayMean,\n median: arrayMedian\n};\n\nconst defaultOptions = {\n maxFeatures: 1.0,\n replacement: false,\n nEstimators: 10,\n treeOptions: {},\n selectionMethod: 'mean',\n seed: 42,\n useSampleBagging: false\n};\n\n/**\n * @class RandomForestRegression\n * @augments RandomForestBase\n */\nexport class RandomForestRegression extends RandomForestBase {\n /**\n * Create a new base random forest for a classifier or regression model.\n * @constructor\n * @param {object} options\n * @param {number} [options.maxFeatures=1.0] - the number of features used on each estimator.\n * * if is an integer it selects maxFeatures elements over the sample features.\n * * if is a float between (0, 1), it takes the percentage of features.\n * @param {boolean} [options.replacement=true] - use replacement over the sample features.\n * @param {number} [options.seed=42] - seed for feature and samples selection, must be a 32-bit integer.\n * @param {number} [options.nEstimators=10] - number of estimator to use.\n * @param {object} [options.treeOptions={}] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/}\n * @param {string} [options.selectionMethod=\"mean\"] - the way to calculate the prediction from estimators, \"mean\" and \"median\" are supported.\n * @param {boolean} [options.useSampleBagging=false] - use bagging over training samples.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n super(true, model.baseModel);\n this.selectionMethod = model.selectionMethod;\n } else {\n options = Object.assign({}, defaultOptions, options);\n\n if (!(options.selectionMethod === 'mean' || options.selectionMethod === 'median')) {\n throw new RangeError(`Unsupported selection method ${options.selectionMethod}`);\n }\n\n options.isClassifier = false;\n\n super(options);\n this.selectionMethod = options.selectionMethod;\n }\n }\n\n /**\n * retrieve the prediction given the selection method.\n * @param {Array} values - predictions of the estimators.\n * @return {number} prediction\n */\n selection(values) {\n return selectionMethods[this.selectionMethod](values);\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n var baseModel = super.toJSON();\n return {\n baseModel: baseModel,\n selectionMethod: this.selectionMethod,\n name: 'RFRegression'\n };\n }\n\n /**\n * Load a Decision tree classifier with the given model.\n * @param {object} model\n * @return {RandomForestRegression}\n */\n static load(model) {\n if (model.name !== 'RFRegression') {\n throw new RangeError(`Invalid model: ${model.name}`);\n }\n\n return new RandomForestRegression(true, model);\n }\n}\n","export { RandomForestClassifier } from './RandomForestClassifier';\nexport { RandomForestRegression } from './RandomForestRegression';\n","/**\n * Function that calculates the integral of the line between two\n * x-coordinates, given the slope and intercept of the line.\n * @param {number} x0\n * @param {number} x1\n * @param {number} slope\n * @param {number} intercept\n * @return {number} integral value.\n */\nexport default function integral(x0, x1, slope, intercept) {\n return (\n 0.5 * slope * x1 * x1 +\n intercept * x1 -\n (0.5 * slope * x0 * x0 + intercept * x0)\n );\n}\n","import integral from './integral';\n\n/**\n * function that retrieves the getEquallySpacedData with the variant \"smooth\"\n *\n * @param {Array} x\n * @param {Array} y\n * @param {number} from - Initial point\n * @param {number} to - Final point\n * @param {number} numberOfPoints\n * @return {Array} - Array of y's equally spaced with the variant \"smooth\"\n */\nexport default function equallySpacedSmooth(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n\n var output = new Array(numberOfPoints);\n\n var initialOriginalStep = x[1] - x[0];\n var lastOriginalStep = x[xLength - 1] - x[xLength - 2];\n\n // Init main variables\n var min = from - halfStep;\n var max = from + halfStep;\n\n var previousX = Number.MIN_VALUE;\n var previousY = 0;\n var nextX = x[0] - initialOriginalStep;\n var nextY = 0;\n\n var currentValue = 0;\n var slope = 0;\n var intercept = 0;\n var sumAtMin = 0;\n var sumAtMax = 0;\n\n var i = 0; // index of input\n var j = 0; // index of output\n\n function getSlope(x0, y0, x1, y1) {\n return (y1 - y0) / (x1 - x0);\n }\n\n main: while (true) {\n if (previousX <= min && min <= nextX) {\n add = integral(0, min - previousX, slope, previousY);\n sumAtMin = currentValue + add;\n }\n\n while (nextX - max >= 0) {\n // no overlap with original point, just consume current value\n var add = integral(0, max - previousX, slope, previousY);\n sumAtMax = currentValue + add;\n\n output[j++] = (sumAtMax - sumAtMin) / step;\n\n if (j === numberOfPoints) {\n break main;\n }\n\n min = max;\n max += step;\n sumAtMin = sumAtMax;\n }\n\n currentValue += integral(previousX, nextX, slope, intercept);\n\n previousX = nextX;\n previousY = nextY;\n\n if (i < xLength) {\n nextX = x[i];\n nextY = y[i];\n i++;\n } else if (i === xLength) {\n nextX += lastOriginalStep;\n nextY = 0;\n }\n\n slope = getSlope(previousX, previousY, nextX, nextY);\n intercept = -slope * previousX + previousY;\n }\n\n return output;\n}\n","/**\n * function that retrieves the getEquallySpacedData with the variant \"slot\"\n *\n * @param {Array} x\n * @param {Array} y\n * @param {number} from - Initial point\n * @param {number} to - Final point\n * @param {number} numberOfPoints\n * @return {Array} - Array of y's equally spaced with the variant \"slot\"\n */\nexport default function equallySpacedSlot(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n var lastStep = x[x.length - 1] - x[x.length - 2];\n\n var start = from - halfStep;\n var output = new Array(numberOfPoints);\n\n // Init main variables\n var min = start;\n var max = start + step;\n\n var previousX = -Number.MAX_VALUE;\n var previousY = 0;\n var nextX = x[0];\n var nextY = y[0];\n var frontOutsideSpectra = 0;\n var backOutsideSpectra = true;\n\n var currentValue = 0;\n\n // for slot algorithm\n var currentPoints = 0;\n\n var i = 1; // index of input\n var j = 0; // index of output\n\n main: while (true) {\n if (previousX >= nextX) throw new Error('x must be an increasing serie');\n while (previousX - max > 0) {\n // no overlap with original point, just consume current value\n if (backOutsideSpectra) {\n currentPoints++;\n backOutsideSpectra = false;\n }\n\n output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints;\n j++;\n\n if (j === numberOfPoints) {\n break main;\n }\n\n min = max;\n max += step;\n currentValue = 0;\n currentPoints = 0;\n }\n\n if (previousX > min) {\n currentValue += previousY;\n currentPoints++;\n }\n\n if (previousX === -Number.MAX_VALUE || frontOutsideSpectra > 1) {\n currentPoints--;\n }\n\n previousX = nextX;\n previousY = nextY;\n\n if (i < xLength) {\n nextX = x[i];\n nextY = y[i];\n i++;\n } else {\n nextX += lastStep;\n nextY = 0;\n frontOutsideSpectra++;\n }\n }\n\n return output;\n}\n","export default function getZones(from, to, numberOfPoints, exclusions = []) {\n if (from > to) {\n [from, to] = [to, from];\n }\n\n // in exclusions from and to have to be defined\n exclusions = exclusions.filter(\n (exclusion) => exclusion.from !== undefined && exclusion.to !== undefined\n );\n\n exclusions = JSON.parse(JSON.stringify(exclusions));\n // we ensure that from before to\n exclusions.forEach((exclusion) => {\n if (exclusion.from > exclusion.to) {\n [exclusion.to, exclusion.from] = [exclusion.from, exclusion.to];\n }\n });\n\n exclusions.sort((a, b) => a.from - b.from);\n\n // we will rework the exclusions in order to remove overlap and outside range (from / to)\n exclusions.forEach((exclusion) => {\n if (exclusion.from < from) exclusion.from = from;\n if (exclusion.to > to) exclusion.to = to;\n });\n for (let i = 0; i < exclusions.length - 1; i++) {\n if (exclusions[i].to > exclusions[i + 1].from) {\n exclusions[i].to = exclusions[i + 1].from;\n }\n }\n exclusions = exclusions.filter((exclusion) => exclusion.from < exclusion.to);\n\n if (!exclusions || exclusions.length === 0) {\n return [{ from, to, numberOfPoints }];\n }\n\n // need to deal with overlapping exclusions and out of bound exclusions\n\n let toRemove = exclusions.reduce(\n (previous, exclusion) => (previous += exclusion.to - exclusion.from),\n 0\n );\n let total = to - from;\n let unitsPerPoint = (total - toRemove) / numberOfPoints;\n let zones = [];\n let currentFrom = from;\n let totalPoints = 0;\n for (let exclusion of exclusions) {\n let currentNbPoints = Math.round(\n (exclusion.from - currentFrom) / unitsPerPoint\n );\n totalPoints += currentNbPoints;\n if (currentNbPoints > 0) {\n zones.push({\n from: currentFrom,\n to: exclusion.from,\n numberOfPoints: currentNbPoints\n });\n }\n\n currentFrom = exclusion.to;\n }\n if (numberOfPoints - totalPoints > 0) {\n zones.push({\n from: currentFrom,\n to: to,\n numberOfPoints: numberOfPoints - totalPoints\n });\n }\n\n return zones;\n}\n","import sequentialFill from 'ml-array-sequential-fill';\n\nimport equallySpacedSmooth from './equallySpacedSmooth';\nimport equallySpacedSlot from './equallySpacedSlot';\nimport getZones from './getZones';\n\n/**\n * Function that returns a Number array of equally spaced numberOfPoints\n * containing a representation of intensities of the spectra arguments x\n * and y.\n *\n * The options parameter contains an object in the following form:\n * from: starting point\n * to: last point\n * numberOfPoints: number of points between from and to\n * variant: \"slot\" or \"smooth\" - smooth is the default option\n *\n * The slot variant consist that each point in the new array is calculated\n * averaging the existing points between the slot that belongs to the current\n * value. The smooth variant is the same but takes the integral of the range\n * of the slot and divide by the step size between two points in the new array.\n *\n * @param {object} [arrayXY={}] - object containing 2 properties x and y (both an array)\n * @param {object} [options={}]\n * @param {number} [options.from=x[0]]\n * @param {number} [options.to=x[x.length-1]]\n * @param {string} [options.variant='smooth']\n * @param {number} [options.numberOfPoints=100]\n * @param {Array} [options.exclusions=[]] array of from / to that should be skipped for the generation of the points\n * @return {object} new object with x / y array with the equally spaced data.\n */\n\nexport default function equallySpaced(arrayXY = {}, options = {}) {\n let { x, y } = arrayXY;\n let xLength = x.length;\n let reverse = false;\n if (x.length > 1 && x[0] > x[1]) {\n x = x.slice().reverse();\n y = y.slice().reverse();\n reverse = true;\n }\n\n let {\n from = x[0],\n to = x[xLength - 1],\n variant = 'smooth',\n numberOfPoints = 100,\n exclusions = []\n } = options;\n\n if (xLength !== y.length) {\n throw new RangeError(\"the x and y vector doesn't have the same size.\");\n }\n\n if (typeof from !== 'number' || isNaN(from)) {\n throw new RangeError(\"'from' option must be a number\");\n }\n\n if (typeof to !== 'number' || isNaN(to)) {\n throw new RangeError(\"'to' option must be a number\");\n }\n\n if (typeof numberOfPoints !== 'number' || isNaN(numberOfPoints)) {\n throw new RangeError(\"'numberOfPoints' option must be a number\");\n }\n\n let zones = getZones(from, to, numberOfPoints, exclusions);\n\n let xResult = [];\n let yResult = [];\n for (let zone of zones) {\n let zoneResult = processZone(\n x,\n y,\n zone.from,\n zone.to,\n zone.numberOfPoints,\n variant,\n reverse\n );\n xResult.push(...zoneResult.x);\n yResult.push(...zoneResult.y);\n }\n\n if (reverse) {\n if (from < to) {\n return { x: xResult.reverse(), y: yResult.reverse() };\n } else {\n return { x: xResult, y: yResult };\n }\n } else {\n if (from < to) {\n return { x: xResult, y: yResult };\n } else {\n return { x: xResult.reverse(), y: yResult.reverse() };\n }\n }\n}\n\nfunction processZone(x, y, from, to, numberOfPoints, variant) {\n if (numberOfPoints < 1) {\n throw new RangeError('the number of points must be at least 1');\n }\n\n var output =\n variant === 'slot'\n ? equallySpacedSlot(x, y, from, to, numberOfPoints)\n : equallySpacedSmooth(x, y, from, to, numberOfPoints);\n\n return {\n x: sequentialFill({\n from,\n to,\n size: numberOfPoints\n }),\n y: output\n };\n}\n","import Matrix from 'ml-matrix';\n\n/**\n * @private\n * Function that retuns an array of matrices of the cases that belong to each class.\n * @param {Matrix} X - dataset\n * @param {Array} y - predictions\n * @return {Array}\n */\nexport function separateClasses(X, y) {\n var features = X.columns;\n\n var classes = 0;\n var totalPerClasses = new Array(10000); // max upperbound of classes\n for (var i = 0; i < y.length; i++) {\n if (totalPerClasses[y[i]] === undefined) {\n totalPerClasses[y[i]] = 0;\n classes++;\n }\n totalPerClasses[y[i]]++;\n }\n var separatedClasses = new Array(classes);\n var currentIndex = new Array(classes);\n for (i = 0; i < classes; ++i) {\n separatedClasses[i] = new Matrix(totalPerClasses[i], features);\n currentIndex[i] = 0;\n }\n for (i = 0; i < X.rows; ++i) {\n separatedClasses[y[i]].setRow(currentIndex[y[i]], X.getRow(i));\n currentIndex[y[i]]++;\n }\n return separatedClasses;\n}\n","import Matrix from 'ml-matrix';\nimport Stat from 'ml-stat';\nimport {separateClasses} from './utils';\n\n/**\n * @class GaussianNB\n */\nexport class GaussianNB {\n\n /**\n * @constructor\n * Constructor for the Gaussian Naive Bayes classifier, the parameters here is just for loading purposes.\n *\n * @param {boolean} reload\n * @param {object} model\n */\n constructor(reload, model) {\n if (reload) {\n this.means = model.means;\n this.calculateProbabilities = model.calculateProbabilities;\n }\n }\n\n /**\n * Function that trains the classifier with a matrix that represents the training set and an array that\n * represents the label of each row in the training set. the labels must be numbers between 0 to n-1 where\n * n represents the number of classes.\n *\n * WARNING: in the case that one class, all the cases in one or more features have the same value, the\n * Naive Bayes classifier will not work well.\n * @param {Matrix|Array} trainingSet\n * @param {Matrix|Array} trainingLabels\n */\n train(trainingSet, trainingLabels) {\n var C1 = Math.sqrt(2 * Math.PI); // constant to precalculate the squared root\n trainingSet = Matrix.checkMatrix(trainingSet);//if (!Matrix.isMatrix(trainingSet)) trainingSet = new Matrix(trainingSet);\n\n if (trainingSet.rows !== trainingLabels.length) {\n throw new RangeError('the size of the training set and the training labels must be the same.');\n }\n\n var separatedClasses = separateClasses(trainingSet, trainingLabels);\n var calculateProbabilities = new Array(separatedClasses.length);\n this.means = new Array(separatedClasses.length);\n for (var i = 0; i < separatedClasses.length; ++i) {\n var means = Stat.matrix.mean(separatedClasses[i]);\n var std = Stat.matrix.standardDeviation(separatedClasses[i], means);\n\n var logPriorProbability = Math.log(separatedClasses[i].rows / trainingSet.rows);\n calculateProbabilities[i] = new Array(means.length + 1);\n\n calculateProbabilities[i][0] = logPriorProbability;\n for (var j = 1; j < means.length + 1; ++j) {\n var currentStd = std[j - 1];\n calculateProbabilities[i][j] = [(1 / (C1 * currentStd)), -2 * currentStd * currentStd];\n }\n\n this.means[i] = means;\n }\n\n this.calculateProbabilities = calculateProbabilities;\n }\n\n /**\n * function that predicts each row of the dataset (must be a matrix).\n *\n * @param {Matrix|Array} dataset\n * @return {Array}\n */\n predict(dataset) {\n if (dataset[0].length === this.calculateProbabilities[0].length) {\n throw new RangeError('the dataset must have the same features as the training set');\n }\n\n var predictions = new Array(dataset.length);\n\n for (var i = 0; i < predictions.length; ++i) {\n predictions[i] = getCurrentClass(dataset[i], this.means, this.calculateProbabilities);\n }\n\n return predictions;\n }\n\n /**\n * Function that export the NaiveBayes model.\n * @return {object}\n */\n toJSON() {\n return {\n modelName: 'NaiveBayes',\n means: this.means,\n calculateProbabilities: this.calculateProbabilities\n };\n }\n\n /**\n * Function that create a GaussianNB classifier with the given model.\n * @param {object} model\n * @return {GaussianNB}\n */\n static load(model) {\n if (model.modelName !== 'NaiveBayes') {\n throw new RangeError('The current model is not a Multinomial Naive Bayes, current model:', model.name);\n }\n\n return new GaussianNB(true, model);\n }\n}\n\n/**\n * @private\n * Function the retrieves a prediction with one case.\n *\n * @param {Array} currentCase\n * @param {Array} mean - Precalculated means of each class trained\n * @param {Array} classes - Precalculated value of each class (Prior probability and probability function of each feature)\n * @return {number}\n */\nfunction getCurrentClass(currentCase, mean, classes) {\n var maxProbability = 0;\n var predictedClass = -1;\n\n // going through all precalculated values for the classes\n for (var i = 0; i < classes.length; ++i) {\n var currentProbability = classes[i][0]; // initialize with the prior probability\n for (var j = 1; j < classes[0][1].length + 1; ++j) {\n currentProbability += calculateLogProbability(currentCase[j - 1], mean[i][j - 1], classes[i][j][0], classes[i][j][1]);\n }\n\n currentProbability = Math.exp(currentProbability);\n if (currentProbability > maxProbability) {\n maxProbability = currentProbability;\n predictedClass = i;\n }\n }\n\n return predictedClass;\n}\n\n/**\n * @private\n * function that retrieves the probability of the feature given the class.\n * @param {number} value - value of the feature.\n * @param {number} mean - mean of the feature for the given class.\n * @param {number} C1 - precalculated value of (1 / (sqrt(2*pi) * std)).\n * @param {number} C2 - precalculated value of (2 * std^2) for the denominator of the exponential.\n * @return {number}\n */\nfunction calculateLogProbability(value, mean, C1, C2) {\n value = value - mean;\n return Math.log(C1 * Math.exp((value * value) / C2));\n}\n","import Matrix from 'ml-matrix';\nimport {separateClasses} from './utils';\n\n/**\n * @class MultinomialNB\n */\nexport class MultinomialNB {\n\n /**\n * @constructor\n * Constructor for Multinomial Naive Bayes, the model parameter is for load purposes.\n *\n * @param {object} model - for load purposes.\n */\n constructor(model) {\n if (model) {\n this.conditionalProbability = Matrix.checkMatrix(model.conditionalProbability);\n this.priorProbability = Matrix.checkMatrix(model.priorProbability);\n }\n }\n\n /**\n * Train the classifier with the current training set and labels, the labels must be numbers between 0 and n.\n * @param {Matrix|Array} trainingSet\n * @param {Array} trainingLabels\n */\n train(trainingSet, trainingLabels) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n\n if (trainingSet.rows !== trainingLabels.length) {\n throw new RangeError('the size of the training set and the training labels must be the same.');\n }\n\n var separateClass = separateClasses(trainingSet, trainingLabels);\n this.priorProbability = new Matrix(separateClass.length, 1);\n\n for (var i = 0; i < separateClass.length; ++i) {\n this.priorProbability[i][0] = Math.log(separateClass[i].length / trainingSet.rows);\n }\n\n var features = trainingSet.columns;\n this.conditionalProbability = new Matrix(separateClass.length, features);\n for (i = 0; i < separateClass.length; ++i) {\n var classValues = Matrix.checkMatrix(separateClass[i]);\n var total = classValues.sum();\n var divisor = total + features;\n this.conditionalProbability.setRow(i, classValues.sum('column').add(1).div(divisor).apply(matrixLog));\n }\n }\n\n /**\n * Retrieves the predictions for the dataset with the current model.\n * @param {Matrix|Array} dataset\n * @return {Array} - predictions from the dataset.\n */\n predict(dataset) {\n dataset = Matrix.checkMatrix(dataset);\n var predictions = new Array(dataset.rows);\n for (var i = 0; i < dataset.rows; ++i) {\n var currentElement = dataset.getRowVector(i);\n predictions[i] = this.conditionalProbability.clone().mulRowVector(currentElement).sum('row')\n .add(this.priorProbability).maxIndex()[0];\n }\n\n return predictions;\n }\n\n /**\n * Function that saves the current model.\n * @return {object} - model in JSON format.\n */\n toJSON() {\n return {\n name: 'MultinomialNB',\n priorProbability: this.priorProbability,\n conditionalProbability: this.conditionalProbability\n };\n }\n\n /**\n * Creates a new MultinomialNB from the given model\n * @param {object} model\n * @return {MultinomialNB}\n */\n static load(model) {\n if (model.name !== 'MultinomialNB') {\n throw new RangeError(`${model.name} is not a Multinomial Naive Bayes`);\n }\n\n return new MultinomialNB(model);\n }\n}\n\nfunction matrixLog(i, j) {\n this[i][j] = Math.log(this[i][j]);\n}\n","export {GaussianNB} from './GaussianNB';\nexport {MultinomialNB} from './MultinomialNB';\n","import Matrix from 'ml-matrix';\nimport Stat from 'ml-stat/matrix';\n\n/**\n * @private\n * Function that given vector, returns his norm\n * @param {Vector} X\n * @return {number} Norm of the vector\n */\nexport function norm(X) {\n return Math.sqrt(X.clone().apply(pow2array).sum());\n}\n\n/**\n * @private\n * Function that pow 2 each element of a Matrix or a Vector,\n * used in the apply method of the Matrix object\n * @param {number} i - index i.\n * @param {number} j - index j.\n * @return {Matrix} The Matrix object modified at the index i, j.\n * */\nexport function pow2array(i, j) {\n this[i][j] = this[i][j] * this[i][j];\n return this;\n}\n\n/**\n * @private\n * Function that normalize the dataset and return the means and\n * standard deviation of each feature.\n * @param {Matrix} dataset\n * @return {object} dataset normalized, means and standard deviations\n */\nexport function featureNormalize(dataset) {\n var means = Stat.mean(dataset);\n var std = Stat.standardDeviation(dataset, means, true);\n var result = Matrix.checkMatrix(dataset).subRowVector(means);\n return {result: result.divRowVector(std), means: means, std: std};\n}\n\n/**\n * @private\n * Function that initialize an array of matrices.\n * @param {Array} array\n * @param {boolean} isMatrix\n * @return {Array} array with the matrices initialized.\n */\nexport function initializeMatrices(array, isMatrix) {\n if (isMatrix) {\n for (var i = 0; i < array.length; ++i) {\n for (var j = 0; j < array[i].length; ++j) {\n var elem = array[i][j];\n array[i][j] = elem !== null ? new Matrix(array[i][j]) : undefined;\n }\n }\n } else {\n for (i = 0; i < array.length; ++i) {\n array[i] = new Matrix(array[i]);\n }\n }\n\n return array;\n}\n","import Matrix from 'ml-matrix';\nimport Stat from 'ml-stat/matrix';\nimport * as Utils from './utils';\n\n/**\n * @class PLS\n */\nexport class PLS {\n\n /**\n * Constructor for Partial Least Squares (PLS)\n * @param {object} options\n * @param {number} [options.latentVectors] - Number of latent vector to get (if the algorithm doesn't find a good model below the tolerance)\n * @param {number} [options.tolerance=1e-5]\n * @param {boolean} [options.scale=true] - rescale dataset using mean.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.meanX = model.meanX;\n this.stdDevX = model.stdDevX;\n this.meanY = model.meanY;\n this.stdDevY = model.stdDevY;\n this.PBQ = Matrix.checkMatrix(model.PBQ);\n this.R2X = model.R2X;\n this.scale = model.scale;\n this.scaleMethod = model.scaleMethod;\n this.tolerance = model.tolerance;\n } else {\n var {\n tolerance = 1e-5,\n scale = true,\n } = options;\n this.tolerance = tolerance;\n this.scale = scale;\n this.latentVectors = options.latentVectors;\n }\n }\n\n /**\n * Fits the model with the given data and predictions, in this function is calculated the\n * following outputs:\n *\n * T - Score matrix of X\n * P - Loading matrix of X\n * U - Score matrix of Y\n * Q - Loading matrix of Y\n * B - Matrix of regression coefficient\n * W - Weight matrix of X\n *\n * @param {Matrix|Array} trainingSet\n * @param {Matrix|Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n trainingValues = Matrix.checkMatrix(trainingValues);\n\n if (trainingSet.length !== trainingValues.length) {\n throw new RangeError('The number of X rows must be equal to the number of Y rows');\n }\n\n this.meanX = Stat.mean(trainingSet);\n this.stdDevX = Stat.standardDeviation(trainingSet, this.meanX, true);\n this.meanY = Stat.mean(trainingValues);\n this.stdDevY = Stat.standardDeviation(trainingValues, this.meanY, true);\n\n if (this.scale) { // here should be the ml-preprocess project\n trainingSet = trainingSet.clone().subRowVector(this.meanX).divRowVector(this.stdDevX);\n trainingValues = trainingValues.clone().subRowVector(this.meanY).divRowVector(this.stdDevY);\n }\n\n if (this.latentVectors === undefined) {\n this.latentVectors = Math.min(trainingSet.length - 1, trainingSet[0].length);\n }\n\n var rx = trainingSet.rows;\n var cx = trainingSet.columns;\n var ry = trainingValues.rows;\n var cy = trainingValues.columns;\n\n var ssqXcal = trainingSet.clone().mul(trainingSet).sum(); // for the r²\n var sumOfSquaresY = trainingValues.clone().mul(trainingValues).sum();\n\n var tolerance = this.tolerance;\n var n = this.latentVectors;\n var T = Matrix.zeros(rx, n);\n var P = Matrix.zeros(cx, n);\n var U = Matrix.zeros(ry, n);\n var Q = Matrix.zeros(cy, n);\n var B = Matrix.zeros(n, n);\n var W = P.clone();\n var k = 0;\n\n while (Utils.norm(trainingValues) > tolerance && k < n) {\n var transposeX = trainingSet.transpose();\n var transposeY = trainingValues.transpose();\n\n var tIndex = maxSumColIndex(trainingSet.clone().mulM(trainingSet));\n var uIndex = maxSumColIndex(trainingValues.clone().mulM(trainingValues));\n\n var t1 = trainingSet.getColumnVector(tIndex);\n var u = trainingValues.getColumnVector(uIndex);\n var t = Matrix.zeros(rx, 1);\n\n while (Utils.norm(t1.clone().sub(t)) > tolerance) {\n var w = transposeX.mmul(u);\n w.div(Utils.norm(w));\n t = t1;\n t1 = trainingSet.mmul(w);\n var q = transposeY.mmul(t1);\n q.div(Utils.norm(q));\n u = trainingValues.mmul(q);\n }\n\n t = t1;\n var num = transposeX.mmul(t);\n var den = (t.transpose().mmul(t))[0][0];\n var p = num.div(den);\n var pnorm = Utils.norm(p);\n p.div(pnorm);\n t.mul(pnorm);\n w.mul(pnorm);\n\n num = u.transpose().mmul(t);\n den = (t.transpose().mmul(t))[0][0];\n var b = (num.div(den))[0][0];\n trainingSet.sub(t.mmul(p.transpose()));\n trainingValues.sub(t.clone().mul(b).mmul(q.transpose()));\n\n T.setColumn(k, t);\n P.setColumn(k, p);\n U.setColumn(k, u);\n Q.setColumn(k, q);\n W.setColumn(k, w);\n\n B[k][k] = b;\n k++;\n }\n\n k--;\n T = T.subMatrix(0, T.rows - 1, 0, k);\n P = P.subMatrix(0, P.rows - 1, 0, k);\n U = U.subMatrix(0, U.rows - 1, 0, k);\n Q = Q.subMatrix(0, Q.rows - 1, 0, k);\n W = W.subMatrix(0, W.rows - 1, 0, k);\n B = B.subMatrix(0, k, 0, k);\n\n // TODO: review of R2Y\n //this.R2Y = t.transpose().mmul(t).mul(q[k][0]*q[k][0]).divS(ssqYcal)[0][0];\n //\n this.ssqYcal = sumOfSquaresY;\n this.E = trainingSet;\n this.F = trainingValues;\n this.T = T;\n this.P = P;\n this.U = U;\n this.Q = Q;\n this.W = W;\n this.B = B;\n this.PBQ = P.mmul(B).mmul(Q.transpose());\n this.R2X = t.transpose().mmul(t).mmul(p.transpose().mmul(p)).div(ssqXcal)[0][0];\n }\n\n /**\n * Predicts the behavior of the given dataset.\n * @param {Matrix|Array} dataset - data to be predicted.\n * @return {Matrix} - predictions of each element of the dataset.\n */\n predict(dataset) {\n var X = Matrix.checkMatrix(dataset);\n if (this.scale) {\n X = X.subRowVector(this.meanX).divRowVector(this.stdDevX);\n }\n var Y = X.mmul(this.PBQ);\n Y = Y.mulRowVector(this.stdDevY).addRowVector(this.meanY);\n return Y;\n }\n\n /**\n * Returns the explained variance on training of the PLS model\n * @return {number}\n */\n getExplainedVariance() {\n return this.R2X;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n name: 'PLS',\n R2X: this.R2X,\n meanX: this.meanX,\n stdDevX: this.stdDevX,\n meanY: this.meanY,\n stdDevY: this.stdDevY,\n PBQ: this.PBQ,\n tolerance: this.tolerance,\n scale: this.scale,\n };\n }\n\n /**\n * Load a PLS model from a JSON Object\n * @param {object} model\n * @return {PLS} - PLS object from the given model\n */\n static load(model) {\n if (model.name !== 'PLS') {\n throw new RangeError('Invalid model: ' + model.name);\n }\n return new PLS(true, model);\n }\n}\n\n/**\n * @private\n * Function that returns the index where the sum of each\n * column vector is maximum.\n * @param {Matrix} data\n * @return {number} index of the maximum\n */\nfunction maxSumColIndex(data) {\n return data.sum('column').maxIndex()[0];\n}\n","import {Matrix, SingularValueDecomposition, inverse} from 'ml-matrix';\nimport {initializeMatrices} from './utils';\n\n/**\n * @class KOPLS\n */\nexport class KOPLS {\n\n /**\n * Constructor for Kernel-based Orthogonal Projections to Latent Structures (K-OPLS)\n * @param {object} options\n * @param {number} [options.predictiveComponents] - Number of predictive components to use.\n * @param {number} [options.orthogonalComponents] - Number of Y-Orthogonal components.\n * @param {Kernel} [options.kernel] - Kernel object to apply, see [ml-kernel](https://github.com/mljs/kernel).\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.trainingSet = new Matrix(model.trainingSet);\n this.YLoadingMat = new Matrix(model.YLoadingMat);\n this.SigmaPow = new Matrix(model.SigmaPow);\n this.YScoreMat = new Matrix(model.YScoreMat);\n this.predScoreMat = initializeMatrices(model.predScoreMat, false);\n this.YOrthLoadingVec = initializeMatrices(model.YOrthLoadingVec, false);\n this.YOrthEigen = model.YOrthEigen;\n this.YOrthScoreMat = initializeMatrices(model.YOrthScoreMat, false);\n this.toNorm = initializeMatrices(model.toNorm, false);\n this.TURegressionCoeff = initializeMatrices(model.TURegressionCoeff, false);\n this.kernelX = initializeMatrices(model.kernelX, true);\n this.kernel = model.kernel;\n this.orthogonalComp = model.orthogonalComp;\n this.predictiveComp = model.predictiveComp;\n } else {\n if (options.predictiveComponents === undefined) {\n throw new RangeError('no predictive components found!');\n }\n if (options.orthogonalComponents === undefined) {\n throw new RangeError('no orthogonal components found!');\n }\n if (options.kernel === undefined) {\n throw new RangeError('no kernel found!');\n }\n\n this.orthogonalComp = options.orthogonalComponents;\n this.predictiveComp = options.predictiveComponents;\n this.kernel = options.kernel;\n }\n }\n\n /**\n * Train the K-OPLS model with the given training set and labels.\n * @param {Matrix|Array} trainingSet\n * @param {Matrix|Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n trainingValues = Matrix.checkMatrix(trainingValues);\n\n // to save and compute kernel with the prediction dataset.\n this.trainingSet = trainingSet.clone();\n\n var kernelX = this.kernel.compute(trainingSet);\n\n var Identity = Matrix.eye(kernelX.rows, kernelX.rows, 1);\n var temp = kernelX;\n kernelX = new Matrix(this.orthogonalComp + 1, this.orthogonalComp + 1);\n kernelX[0][0] = temp;\n\n var result = new SingularValueDecomposition(trainingValues.transpose().mmul(kernelX[0][0]).mmul(trainingValues), {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: false\n });\n var YLoadingMat = result.leftSingularVectors;\n var Sigma = result.diagonalMatrix;\n\n YLoadingMat = YLoadingMat.subMatrix(0, YLoadingMat.rows - 1, 0, this.predictiveComp - 1);\n Sigma = Sigma.subMatrix(0, this.predictiveComp - 1, 0, this.predictiveComp - 1);\n\n var YScoreMat = trainingValues.mmul(YLoadingMat);\n\n var predScoreMat = new Array(this.orthogonalComp + 1);\n var TURegressionCoeff = new Array(this.orthogonalComp + 1);\n var YOrthScoreMat = new Array(this.orthogonalComp);\n var YOrthLoadingVec = new Array(this.orthogonalComp);\n var YOrthEigen = new Array(this.orthogonalComp);\n var YOrthScoreNorm = new Array(this.orthogonalComp);\n\n var SigmaPow = Matrix.pow(Sigma, -0.5);\n // to avoid errors, check infinity\n SigmaPow.apply(function (i, j) {\n if (this[i][j] === Infinity) {\n this[i][j] = 0.0;\n }\n });\n\n for (var i = 0; i < this.orthogonalComp; ++i) {\n predScoreMat[i] = kernelX[0][i].transpose().mmul(YScoreMat).mmul(SigmaPow);\n\n var TpiPrime = predScoreMat[i].transpose();\n TURegressionCoeff[i] = inverse(TpiPrime.mmul(predScoreMat[i])).mmul(TpiPrime).mmul(YScoreMat);\n\n result = new SingularValueDecomposition(TpiPrime.mmul(Matrix.sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime))).mmul(predScoreMat[i]), {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: false\n });\n var CoTemp = result.leftSingularVectors;\n var SoTemp = result.diagonalMatrix;\n\n YOrthLoadingVec[i] = CoTemp.subMatrix(0, CoTemp.rows - 1, 0, 0);\n YOrthEigen[i] = SoTemp[0][0];\n\n YOrthScoreMat[i] = Matrix.sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime)).mmul(predScoreMat[i]).mmul(YOrthLoadingVec[i]).mul(Math.pow(YOrthEigen[i], -0.5));\n\n var toiPrime = YOrthScoreMat[i].transpose();\n YOrthScoreNorm[i] = Matrix.sqrt(toiPrime.mmul(YOrthScoreMat[i]));\n\n YOrthScoreMat[i] = YOrthScoreMat[i].divRowVector(YOrthScoreNorm[i]);\n\n var ITo = Matrix.sub(Identity, YOrthScoreMat[i].mmul(YOrthScoreMat[i].transpose()));\n\n kernelX[0][i + 1] = kernelX[0][i].mmul(ITo);\n kernelX[i + 1][i + 1] = ITo.mmul(kernelX[i][i]).mmul(ITo);\n }\n\n var lastScoreMat = predScoreMat[this.orthogonalComp] = kernelX[0][this.orthogonalComp].transpose().mmul(YScoreMat).mmul(SigmaPow);\n\n var lastTpPrime = lastScoreMat.transpose();\n TURegressionCoeff[this.orthogonalComp] = inverse(lastTpPrime.mmul(lastScoreMat)).mmul(lastTpPrime).mmul(YScoreMat);\n\n this.YLoadingMat = YLoadingMat;\n this.SigmaPow = SigmaPow;\n this.YScoreMat = YScoreMat;\n this.predScoreMat = predScoreMat;\n this.YOrthLoadingVec = YOrthLoadingVec;\n this.YOrthEigen = YOrthEigen;\n this.YOrthScoreMat = YOrthScoreMat;\n this.toNorm = YOrthScoreNorm;\n this.TURegressionCoeff = TURegressionCoeff;\n this.kernelX = kernelX;\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Matrix|Array} toPredict\n * @return {{y: Matrix, predScoreMat: Array, predYOrthVectors: Array}} predictions\n */\n predict(toPredict) {\n\n var KTestTrain = this.kernel.compute(toPredict, this.trainingSet);\n\n var temp = KTestTrain;\n KTestTrain = new Matrix(this.orthogonalComp + 1, this.orthogonalComp + 1);\n KTestTrain[0][0] = temp;\n\n var YOrthScoreVector = new Array(this.orthogonalComp);\n var predScoreMat = new Array(this.orthogonalComp);\n\n var i;\n for (i = 0; i < this.orthogonalComp; ++i) {\n predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow);\n\n YOrthScoreVector[i] = Matrix.sub(KTestTrain[i][i], predScoreMat[i].mmul(this.predScoreMat[i].transpose())).mmul(this.predScoreMat[i]).mmul(this.YOrthLoadingVec[i]).mul(Math.pow(this.YOrthEigen[i], -0.5));\n\n YOrthScoreVector[i] = YOrthScoreVector[i].divRowVector(this.toNorm[i]);\n\n var scoreMatPrime = this.YOrthScoreMat[i].transpose();\n KTestTrain[i + 1][0] = Matrix.sub(KTestTrain[i][0], YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[0][i].transpose()));\n\n var p1 = Matrix.sub(KTestTrain[i][0], KTestTrain[i][i].mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime));\n var p2 = YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[i][i]);\n var p3 = p2.mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime);\n\n KTestTrain[i + 1][i + 1] = p1.sub(p2).add(p3);\n }\n\n predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow);\n var prediction = predScoreMat[i].mmul(this.TURegressionCoeff[i]).mmul(this.YLoadingMat.transpose());\n\n return {\n prediction: prediction,\n predScoreMat: predScoreMat,\n predYOrthVectors: YOrthScoreVector\n };\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n name: 'K-OPLS',\n YLoadingMat: this.YLoadingMat,\n SigmaPow: this.SigmaPow,\n YScoreMat: this.YScoreMat,\n predScoreMat: this.predScoreMat,\n YOrthLoadingVec: this.YOrthLoadingVec,\n YOrthEigen: this.YOrthEigen,\n YOrthScoreMat: this.YOrthScoreMat,\n toNorm: this.toNorm,\n TURegressionCoeff: this.TURegressionCoeff,\n kernelX: this.kernelX,\n trainingSet: this.trainingSet,\n orthogonalComp: this.orthogonalComp,\n predictiveComp: this.predictiveComp\n };\n }\n\n /**\n * Load a K-OPLS with the given model.\n * @param {object} model\n * @param {Kernel} kernel - kernel used on the model, see [ml-kernel](https://github.com/mljs/kernel).\n * @return {KOPLS}\n */\n static load(model, kernel) {\n if (model.name !== 'K-OPLS') {\n throw new RangeError('Invalid model: ' + model.name);\n }\n\n if (!kernel) {\n throw new RangeError('You must provide a kernel for the model!');\n }\n\n model.kernel = kernel;\n return new KOPLS(true, model);\n }\n}\n","export {PLS} from './pls';\nexport {KOPLS} from './kopls';\n","/**\n * Calculate current error\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} parameters - Array of current parameter values\n * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @return {number}\n */\nexport default function errorCalculation(\n data,\n parameters,\n parameterizedFunction\n) {\n var error = 0;\n const func = parameterizedFunction(parameters);\n\n for (var i = 0; i < data.x.length; i++) {\n error += Math.abs(data.y[i] - func(data.x[i]));\n }\n\n return error;\n}\n","import { inverse, Matrix } from 'ml-matrix';\n\n/**\n * Difference of the matrix function over the parameters\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} evaluatedData - Array of previous evaluated function values\n * @param {Array} params - Array of previous parameter values\n * @param {number} gradientDifference - Adjustment for decrease the damping parameter\n * @param {function} paramFunction - The parameters and returns a function with the independent variable as a parameter\n * @return {Matrix}\n */\nfunction gradientFunction(\n data,\n evaluatedData,\n params,\n gradientDifference,\n paramFunction\n) {\n const n = params.length;\n const m = data.x.length;\n\n var ans = new Array(n);\n\n for (var param = 0; param < n; param++) {\n ans[param] = new Array(m);\n var auxParams = params.concat();\n auxParams[param] += gradientDifference;\n var funcParam = paramFunction(auxParams);\n\n for (var point = 0; point < m; point++) {\n ans[param][point] = evaluatedData[point] - funcParam(data.x[point]);\n }\n }\n return new Matrix(ans);\n}\n\n/**\n * Matrix function over the samples\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} evaluatedData - Array of previous evaluated function values\n * @return {Matrix}\n */\nfunction matrixFunction(data, evaluatedData) {\n const m = data.x.length;\n\n var ans = new Array(m);\n\n for (var point = 0; point < m; point++) {\n ans[point] = [data.y[point] - evaluatedData[point]];\n }\n\n return new Matrix(ans);\n}\n\n/**\n * Iteration for Levenberg-Marquardt\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} params - Array of previous parameter values\n * @param {number} damping - Levenberg-Marquardt parameter\n * @param {number} gradientDifference - Adjustment for decrease the damping parameter\n * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @return {Array}\n */\nexport default function step(\n data,\n params,\n damping,\n gradientDifference,\n parameterizedFunction\n) {\n var value = damping * gradientDifference * gradientDifference;\n var identity = Matrix.eye(params.length, params.length, value);\n\n const func = parameterizedFunction(params);\n var evaluatedData = data.x.map((e) => func(e));\n\n var gradientFunc = gradientFunction(\n data,\n evaluatedData,\n params,\n gradientDifference,\n parameterizedFunction\n );\n var matrixFunc = matrixFunction(data, evaluatedData);\n var inverseMatrix = inverse(\n identity.add(gradientFunc.mmul(gradientFunc.transpose()))\n );\n\n params = new Matrix([params]);\n params = params.sub(\n inverseMatrix\n .mmul(gradientFunc)\n .mmul(matrixFunc)\n .mul(gradientDifference)\n .transpose()\n );\n\n return params.to1DArray();\n}\n","import errorCalculation from './errorCalculation';\nimport step from './step';\n\n/**\n * Curve fitting algorithm\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @param {object} [options] - Options object\n * @param {number} [options.damping] - Levenberg-Marquardt parameter\n * @param {number} [options.gradientDifference = 10e-2] - Adjustment for decrease the damping parameter\n * @param {Array} [options.minValues] - Minimum allowed values for parameters\n * @param {Array} [options.maxValues] - Maximum allowed values for parameters\n * @param {Array} [options.initialValues] - Array of initial parameter values\n * @param {number} [options.maxIterations = 100] - Maximum of allowed iterations\n * @param {number} [options.errorTolerance = 10e-3] - Minimum uncertainty allowed for each point\n * @return {{parameterValues: Array, parameterError: number, iterations: number}}\n */\nexport default function levenbergMarquardt(\n data,\n parameterizedFunction,\n options = {}\n) {\n let {\n maxIterations = 100,\n gradientDifference = 10e-2,\n damping = 0,\n errorTolerance = 10e-3,\n minValues,\n maxValues,\n initialValues\n } = options;\n\n if (damping <= 0) {\n throw new Error('The damping option must be a positive number');\n } else if (!data.x || !data.y) {\n throw new Error('The data parameter must have x and y elements');\n } else if (\n !Array.isArray(data.x) ||\n data.x.length < 2 ||\n !Array.isArray(data.y) ||\n data.y.length < 2\n ) {\n throw new Error(\n 'The data parameter elements must be an array with more than 2 points'\n );\n } else if (data.x.length !== data.y.length) {\n throw new Error('The data parameter elements must have the same size');\n }\n\n var parameters =\n initialValues || new Array(parameterizedFunction.length).fill(1);\n let parLen = parameters.length;\n maxValues = maxValues || new Array(parLen).fill(Number.MAX_SAFE_INTEGER);\n minValues = minValues || new Array(parLen).fill(Number.MIN_SAFE_INTEGER);\n\n if (maxValues.length !== minValues.length) {\n throw new Error('minValues and maxValues must be the same size');\n }\n\n if (!Array.isArray(parameters)) {\n throw new Error('initialValues must be an array');\n }\n\n var error = errorCalculation(data, parameters, parameterizedFunction);\n\n var converged = error <= errorTolerance;\n\n for (\n var iteration = 0;\n iteration < maxIterations && !converged;\n iteration++\n ) {\n parameters = step(\n data,\n parameters,\n damping,\n gradientDifference,\n parameterizedFunction\n );\n\n for (let k = 0; k < parLen; k++) {\n parameters[k] = Math.min(\n Math.max(minValues[k], parameters[k]),\n maxValues[k]\n );\n }\n\n error = errorCalculation(data, parameters, parameterizedFunction);\n if (isNaN(error)) break;\n converged = error <= errorTolerance;\n }\n\n return {\n parameterValues: parameters,\n parameterError: error,\n iterations: iteration\n };\n}\n","export default function getZones(from, to, exclusions = []) {\n if (from > to) {\n [from, to] = [to, from];\n }\n\n // in exclusions from and to have to be defined\n exclusions = exclusions.filter(\n (exclusion) => exclusion.from !== undefined && exclusion.to !== undefined\n );\n\n exclusions = JSON.parse(JSON.stringify(exclusions));\n // we ensure that from before to\n exclusions.forEach((exclusion) => {\n if (exclusion.from > exclusion.to) {\n [exclusion.to, exclusion.from] = [exclusion.from, exclusion.to];\n }\n });\n\n exclusions.sort((a, b) => a.from - b.from);\n\n // we will rework the exclusions in order to remove overlap and outside range (from / to)\n exclusions.forEach((exclusion) => {\n if (exclusion.from < from) exclusion.from = from;\n if (exclusion.to > to) exclusion.to = to;\n });\n for (let i = 0; i < exclusions.length - 1; i++) {\n if (exclusions[i].to > exclusions[i + 1].from) {\n exclusions[i].to = exclusions[i + 1].from;\n }\n }\n exclusions = exclusions.filter((exclusion) => exclusion.from < exclusion.to);\n\n if (!exclusions || exclusions.length === 0) {\n return [{ from, to }];\n }\n\n let zones = [];\n let currentFrom = from;\n for (let exclusion of exclusions) {\n if (currentFrom < exclusion.from) {\n zones.push({\n from: currentFrom,\n to: exclusion.from\n });\n }\n\n currentFrom = exclusion.to;\n }\n if (currentFrom < to) {\n zones.push({\n from: currentFrom,\n to: to\n });\n }\n\n return zones;\n}\n","import getZones from './getZones';\n\n/**\n * Filter an array x/y based on various criteria\n * x points are expected to be sorted\n *\n * @param {object} points\n * @param {object} [options={}]\n * @param {array} [options.from]\n * @param {array} [options.to]\n * @param {array} [options.exclusions=[]]\n * @return {{x: Array, y: Array}}\n */\n\nexport default function filterX(points, options = {}) {\n const { x, y } = points;\n const { from = x[0], to = x[x.length - 1], exclusions = [] } = options;\n\n let zones = getZones(from, to, exclusions);\n\n\n let currentZoneIndex = 0;\n let newX = [];\n let newY = [];\n let position = 0;\n while (position < x.length) {\n if (\n x[position] <= zones[currentZoneIndex].to &&\n x[position] >= zones[currentZoneIndex].from\n ) {\n newX.push(x[position]);\n newY.push(y[position]);\n } else {\n if (x[position] > zones[currentZoneIndex].to) {\n currentZoneIndex++;\n if (!zones[currentZoneIndex]) break;\n }\n }\n position++;\n }\n\n return {\n x: newX,\n y: newY\n };\n}\n","/*\n * Original code from:\n *\n * k-d Tree JavaScript - V 1.01\n *\n * https://github.com/ubilabs/kd-tree-javascript\n *\n * @author Mircea Pricop , 2012\n * @author Martin Kleppe , 2012\n * @author Ubilabs http://ubilabs.net, 2012\n * @license MIT License \n */\n\nfunction Node(obj, dimension, parent) {\n this.obj = obj;\n this.left = null;\n this.right = null;\n this.parent = parent;\n this.dimension = dimension;\n}\n\nexport default class KDTree {\n constructor(points, metric) {\n // If points is not an array, assume we're loading a pre-built tree\n if (!Array.isArray(points)) {\n this.dimensions = points.dimensions;\n this.root = points;\n restoreParent(this.root);\n } else {\n this.dimensions = new Array(points[0].length);\n for (var i = 0; i < this.dimensions.length; i++) {\n this.dimensions[i] = i;\n }\n this.root = buildTree(points, 0, null, this.dimensions);\n }\n this.metric = metric;\n }\n\n // Convert to a JSON serializable structure; this just requires removing\n // the `parent` property\n toJSON() {\n const result = toJSONImpl(this.root, true);\n result.dimensions = this.dimensions;\n return result;\n }\n\n nearest(point, maxNodes, maxDistance) {\n const metric = this.metric;\n const dimensions = this.dimensions;\n var i;\n\n const bestNodes = new BinaryHeap(\n function (e) {\n return -e[1];\n }\n );\n\n function nearestSearch(node) {\n const dimension = dimensions[node.dimension];\n const ownDistance = metric(point, node.obj);\n const linearPoint = {};\n var bestChild,\n linearDistance,\n otherChild,\n i;\n\n function saveNode(node, distance) {\n bestNodes.push([node, distance]);\n if (bestNodes.size() > maxNodes) {\n bestNodes.pop();\n }\n }\n\n for (i = 0; i < dimensions.length; i += 1) {\n if (i === node.dimension) {\n linearPoint[dimensions[i]] = point[dimensions[i]];\n } else {\n linearPoint[dimensions[i]] = node.obj[dimensions[i]];\n }\n }\n\n linearDistance = metric(linearPoint, node.obj);\n\n if (node.right === null && node.left === null) {\n if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {\n saveNode(node, ownDistance);\n }\n return;\n }\n\n if (node.right === null) {\n bestChild = node.left;\n } else if (node.left === null) {\n bestChild = node.right;\n } else {\n if (point[dimension] < node.obj[dimension]) {\n bestChild = node.left;\n } else {\n bestChild = node.right;\n }\n }\n\n nearestSearch(bestChild);\n\n if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {\n saveNode(node, ownDistance);\n }\n\n if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) {\n if (bestChild === node.left) {\n otherChild = node.right;\n } else {\n otherChild = node.left;\n }\n if (otherChild !== null) {\n nearestSearch(otherChild);\n }\n }\n }\n\n if (maxDistance) {\n for (i = 0; i < maxNodes; i += 1) {\n bestNodes.push([null, maxDistance]);\n }\n }\n\n if (this.root) {\n nearestSearch(this.root);\n }\n\n const result = [];\n for (i = 0; i < Math.min(maxNodes, bestNodes.content.length); i += 1) {\n if (bestNodes.content[i][0]) {\n result.push([bestNodes.content[i][0].obj, bestNodes.content[i][1]]);\n }\n }\n return result;\n }\n}\n\nfunction toJSONImpl(src) {\n const dest = new Node(src.obj, src.dimension, null);\n if (src.left) dest.left = toJSONImpl(src.left);\n if (src.right) dest.right = toJSONImpl(src.right);\n return dest;\n}\n\nfunction buildTree(points, depth, parent, dimensions) {\n const dim = depth % dimensions.length;\n\n if (points.length === 0) {\n return null;\n }\n if (points.length === 1) {\n return new Node(points[0], dim, parent);\n }\n\n points.sort((a, b) => a[dimensions[dim]] - b[dimensions[dim]]);\n\n const median = Math.floor(points.length / 2);\n const node = new Node(points[median], dim, parent);\n node.left = buildTree(points.slice(0, median), depth + 1, node, dimensions);\n node.right = buildTree(points.slice(median + 1), depth + 1, node, dimensions);\n\n return node;\n}\n\nfunction restoreParent(root) {\n if (root.left) {\n root.left.parent = root;\n restoreParent(root.left);\n }\n\n if (root.right) {\n root.right.parent = root;\n restoreParent(root.right);\n }\n}\n\n// Binary heap implementation from:\n// http://eloquentjavascript.net/appendix2.html\nclass BinaryHeap {\n constructor(scoreFunction) {\n this.content = [];\n this.scoreFunction = scoreFunction;\n }\n\n push(element) {\n // Add the new element to the end of the array.\n this.content.push(element);\n // Allow it to bubble up.\n this.bubbleUp(this.content.length - 1);\n }\n\n pop() {\n // Store the first element so we can return it later.\n var result = this.content[0];\n // Get the element at the end of the array.\n var end = this.content.pop();\n // If there are any elements left, put the end element at the\n // start, and let it sink down.\n if (this.content.length > 0) {\n this.content[0] = end;\n this.sinkDown(0);\n }\n return result;\n }\n\n peek() {\n return this.content[0];\n }\n\n size() {\n return this.content.length;\n }\n\n bubbleUp(n) {\n // Fetch the element that has to be moved.\n var element = this.content[n];\n // When at 0, an element can not go up any further.\n while (n > 0) {\n // Compute the parent element's index, and fetch it.\n const parentN = Math.floor((n + 1) / 2) - 1;\n const parent = this.content[parentN];\n // Swap the elements if the parent is greater.\n if (this.scoreFunction(element) < this.scoreFunction(parent)) {\n this.content[parentN] = element;\n this.content[n] = parent;\n // Update 'n' to continue at the new position.\n n = parentN;\n } else { // Found a parent that is less, no need to move it further.\n break;\n }\n }\n }\n\n sinkDown(n) {\n // Look up the target element and its score.\n var length = this.content.length;\n var element = this.content[n];\n var elemScore = this.scoreFunction(element);\n\n while (true) {\n // Compute the indices of the child elements.\n var child2N = (n + 1) * 2;\n var child1N = child2N - 1;\n // This is used to store the new position of the element,\n // if any.\n var swap = null;\n // If the first child exists (is inside the array)...\n if (child1N < length) {\n // Look it up and compute its score.\n var child1 = this.content[child1N];\n var child1Score = this.scoreFunction(child1);\n // If the score is less than our element's, we need to swap.\n if (child1Score < elemScore) {\n swap = child1N;\n }\n }\n // Do the same checks for the other child.\n if (child2N < length) {\n var child2 = this.content[child2N];\n var child2Score = this.scoreFunction(child2);\n if (child2Score < (swap === null ? elemScore : child1Score)) {\n swap = child2N;\n }\n }\n\n // If the element needs to be moved, swap it, and continue.\n if (swap !== null) {\n this.content[n] = this.content[swap];\n this.content[swap] = element;\n n = swap;\n } else {\n // Otherwise, we are done.\n break;\n }\n }\n }\n}\n","import KDTree from './KDTree';\nimport euclideanDistance from 'ml-distance-euclidean';\n\nexport default class KNN {\n\n /**\n * @param {Array} dataset\n * @param {Array} labels\n * @param {object} options\n * @param {number} [options.k=numberOfClasses + 1] - Number of neighbors to classify.\n * @param {function} [options.distance=euclideanDistance] - Distance function that takes two parameters.\n */\n constructor(dataset, labels, options = {}) {\n if (dataset === true) {\n const model = labels;\n this.kdTree = new KDTree(model.kdTree, options);\n this.k = model.k;\n this.classes = new Set(model.classes);\n this.isEuclidean = model.isEuclidean;\n return;\n }\n\n const classes = new Set(labels);\n\n const {\n distance = euclideanDistance,\n k = classes.size + 1\n } = options;\n\n const points = new Array(dataset.length);\n for (var i = 0; i < points.length; ++i) {\n points[i] = dataset[i].slice();\n }\n\n for (i = 0; i < labels.length; ++i) {\n points[i].push(labels[i]);\n }\n\n this.kdTree = new KDTree(points, distance);\n this.k = k;\n this.classes = classes;\n this.isEuclidean = distance === euclideanDistance;\n }\n\n /**\n * Create a new KNN instance with the given model.\n * @param {object} model\n * @param {function} distance=euclideanDistance - distance function must be provided if the model wasn't trained with euclidean distance.\n * @return {KNN}\n */\n static load(model, distance = euclideanDistance) {\n if (model.name !== 'KNN') {\n throw new Error('invalid model: ' + model.name);\n }\n if (!model.isEuclidean && distance === euclideanDistance) {\n throw new Error('a custom distance function was used to create the model. Please provide it again');\n }\n if (model.isEuclidean && distance !== euclideanDistance) {\n throw new Error('the model was created with the default distance function. Do not load it with another one');\n }\n return new KNN(true, model, distance);\n }\n\n /**\n * Return a JSON containing the kd-tree model.\n * @return {object} JSON KNN model.\n */\n toJSON() {\n return {\n name: 'KNN',\n kdTree: this.kdTree,\n k: this.k,\n classes: Array.from(this.classes),\n isEuclidean: this.isEuclidean\n };\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Array} dataset\n * @return {Array} predictions\n */\n predict(dataset) {\n if (Array.isArray(dataset)) {\n if (typeof dataset[0] === 'number') {\n return getSinglePrediction(this, dataset);\n } else if (Array.isArray(dataset[0]) && typeof dataset[0][0] === 'number') {\n const predictions = new Array(dataset.length);\n for (var i = 0; i < dataset.length; i++) {\n predictions[i] = getSinglePrediction(this, dataset[i]);\n }\n return predictions;\n }\n }\n throw new TypeError('dataset to predict must be an array or a matrix');\n }\n}\n\nfunction getSinglePrediction(knn, currentCase) {\n var nearestPoints = knn.kdTree.nearest(currentCase, knn.k);\n var pointsPerClass = {};\n var predictedClass = -1;\n var maxPoints = -1;\n var lastElement = nearestPoints[0][0].length - 1;\n\n for (var element of knn.classes) {\n pointsPerClass[element] = 0;\n }\n\n for (var i = 0; i < nearestPoints.length; ++i) {\n var currentClass = nearestPoints[i][0][lastElement];\n var currentPoints = ++pointsPerClass[currentClass];\n if (currentPoints > maxPoints) {\n predictedClass = currentClass;\n maxPoints = currentPoints;\n }\n }\n\n return predictedClass;\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/ml.min.js b/dist/ml.min.js index 021ca94..8a80fce 100644 --- a/dist/ml.min.js +++ b/dist/ml.min.js @@ -1,4 +1,4 @@ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ML=e():t.ML=e()}("undefined"!=typeof self?self:this,function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var i=e[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)r.d(n,i,function(e){return t[e]}.bind(null,i));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=42)}([function(t,e,r){"use strict";r.r(e);var n=r(13);class i{constructor(t){var e,r,n,i,o,s,a,h,u,l=(t=T.checkMatrix(t)).clone(),c=l.rows,f=l.columns,g=new Array(c),d=1;for(e=0;eMath.abs(h[i])&&(i=e);if(i!==r){for(n=0;n=0;i--){for(n=0;no?t[i][o]:i===o?1:0;return n}get upperTriangularMatrix(){for(var t=this.LU,e=t.rows,r=t.columns,n=new O(e,r),i=0;iMath.abs(e)?(r=e/t,Math.abs(t)*Math.sqrt(1+r*r)):0!==e?(r=t/e,Math.abs(e)*Math.sqrt(1+r*r)):0}function s(t,e,r){for(var n=new Array(t),i=0;i1&&void 0!==arguments[1]?arguments[1]:{};var r=(t=T.checkMatrix(t)).rows,n=t.columns;const i=e.computeLeftSingularVectors,a=void 0===i||i,h=e.computeRightSingularVectors,u=void 0===h||h,l=e.autoTranspose,c=void 0!==l&&l;var f,g=Boolean(a),d=Boolean(u),m=!1;if(r=0;t--)if(0!==y[t]){for(let e=t+1;e=0;t--){if(t0;){let t,e;for(t=O-2;t>=-1&&-1!==t;t--){const e=Number.MIN_VALUE+P*Math.abs(y[t]+Math.abs(y[t+1]));if(Math.abs(M[t])<=e||Number.isNaN(M[t])){M[t]=0;break}}if(t===O-2)e=4;else{let r;for(r=O-1;r>=t&&r!==t;r--){let e=(r!==O?Math.abs(M[r]):0)+(r!==t+1?Math.abs(M[r-1]):0);if(Math.abs(y[r])<=P*e){y[r]=0;break}}r===t?e=3:r===O-1?e=1:(e=2,t=r)}switch(t++,e){case 1:{let e=M[O-2];M[O-2]=0;for(let r=O-2;r>=t;r--){let i=o(y[r],e),s=y[r]/i,a=e/i;if(y[r]=i,r!==t&&(e=-a*M[r-1],M[r-1]=s*M[r-1]),d)for(let t=0;t=y[t+1]);){let e=y[t];if(y[t]=y[t+1],y[t+1]=e,d&&te?i[o][r]=t[o][r]/this.s[r]:i[o][r]=0;var o=this.U,s=o.length,a=o[0].length,h=new O(r,s);for(let t=0;tt&&e++;return e}get diagonal(){return this.s}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return O.isMatrix(this.U)||(this.U=new O(this.U)),this.U}get rightSingularVectors(){return O.isMatrix(this.V)||(this.V=new O(this.V)),this.V}get diagonalMatrix(){return O.diag(this.s)}}function h(t,e,r){var n=r?t.rows:t.rows-1;if(e<0||e>n)throw new RangeError("Row index out of range")}function u(t,e,r){var n=r?t.columns:t.columns-1;if(e<0||e>n)throw new RangeError("Column index out of range")}function l(t,e){if(e.to1DArray&&(e=e.to1DArray()),e.length!==t.columns)throw new RangeError("vector size must be the same as the number of columns");return e}function c(t,e){if(e.to1DArray&&(e=e.to1DArray()),e.length!==t.rows)throw new RangeError("vector size must be the same as the number of rows");return e}function f(t,e,r){return{row:g(t,e),column:d(t,r)}}function g(t,e){if("object"!=typeof e)throw new TypeError("unexpected type for row indices");if(e.some(e=>e<0||e>=t.rows))throw new RangeError("row indices are out of range");return Array.isArray(e)||(e=Array.from(e)),e}function d(t,e){if("object"!=typeof e)throw new TypeError("unexpected type for column indices");if(e.some(e=>e<0||e>=t.columns))throw new RangeError("column indices are out of range");return Array.isArray(e)||(e=Array.from(e)),e}function m(t,e,r,n,i){if(5!==arguments.length)throw new RangeError("expected 4 arguments");if(p("startRow",e),p("endRow",r),p("startColumn",n),p("endColumn",i),e>r||n>i||e<0||e>=t.rows||r<0||r>=t.rows||n<0||n>=t.columns||i<0||i>=t.columns)throw new RangeError("Submatrix indices are out of range")}function p(t,e){if("number"!=typeof e)throw new TypeError("".concat(t," must be a number"))}class v extends(k()){constructor(t,e,r){super(),this.matrix=t,this.rows=e,this.columns=r}static get[Symbol.species](){return O}}class w extends v{constructor(t){super(t,t.columns,t.rows)}set(t,e,r){return this.matrix.set(e,t,r),this}get(t,e){return this.matrix.get(e,t)}}class y extends v{constructor(t,e){super(t,1,t.columns),this.row=e}set(t,e,r){return this.matrix.set(this.row,e,r),this}get(t,e){return this.matrix.get(this.row,e)}}class x extends v{constructor(t,e,r,n,i){m(t,e,r,n,i),super(t,r-e+1,i-n+1),this.startRow=e,this.startColumn=n}set(t,e,r){return this.matrix.set(this.startRow+t,this.startColumn+e,r),this}get(t,e){return this.matrix.get(this.startRow+t,this.startColumn+e)}}class b extends v{constructor(t,e,r){var n=f(t,e,r);super(t,n.row.length,n.column.length),this.rowIndices=n.row,this.columnIndices=n.column}set(t,e,r){return this.matrix.set(this.rowIndices[t],this.columnIndices[e],r),this}get(t,e){return this.matrix.get(this.rowIndices[t],this.columnIndices[e])}}class M extends v{constructor(t,e){super(t,(e=g(t,e)).length,t.columns),this.rowIndices=e}set(t,e,r){return this.matrix.set(this.rowIndices[t],e,r),this}get(t,e){return this.matrix.get(this.rowIndices[t],e)}}class S extends v{constructor(t,e){e=d(t,e),super(t,t.rows,e.length),this.columnIndices=e}set(t,e,r){return this.matrix.set(t,this.columnIndices[e],r),this}get(t,e){return this.matrix.get(t,this.columnIndices[e])}}class A extends v{constructor(t,e){super(t,t.rows,1),this.column=e}set(t,e,r){return this.matrix.set(t,this.column,r),this}get(t){return this.matrix.get(t,this.column)}}class E extends v{constructor(t){super(t,t.rows,t.columns)}set(t,e,r){return this.matrix.set(this.rows-t-1,e,r),this}get(t,e){return this.matrix.get(this.rows-t-1,e)}}class R extends v{constructor(t){super(t,t.rows,t.columns)}set(t,e,r){return this.matrix.set(t,this.columns-e-1,r),this}get(t,e){return this.matrix.get(t,this.columns-e-1)}}function k(t){void 0===t&&(t=Object);class e extends t{static get[Symbol.species](){return this}static from1DArray(t,e,r){if(t*e!==r.length)throw new RangeError("Data length does not match given dimensions");for(var n=new this(t,e),i=0;ir?(i=!0,r=e):(n=!1,i=!0);t++}return n}isReducedEchelonForm(){let t=0,e=0,r=-1,n=!0,i=!1;for(;tr?(i=!0,r=e):(n=!1,i=!0);for(let r=e+1;rt&&(t=this.get(e,r));return t}maxIndex(){for(var t=this.get(0,0),e=[0,0],r=0;rt&&(t=this.get(r,n),e[0]=r,e[1]=n);return e}min(){for(var t=this.get(0,0),e=0;ee&&(e=this.get(t,r));return e}maxRowIndex(t){h(this,t);for(var e=this.get(t,0),r=[t,0],n=1;ne&&(e=this.get(t,n),r[1]=n);return r}minRow(t){h(this,t);for(var e=this.get(t,0),r=1;re&&(e=this.get(r,t));return e}maxColumnIndex(t){u(this,t);for(var e=this.get(0,t),r=[0,t],n=1;ne&&(e=this.get(n,t),r[0]=n);return r}minColumn(t){u(this,t);for(var e=this.get(0,t),r=1;r0&&void 0!==arguments[0]?arguments[0]:"frobenius";var e=0;if("max"===t)return this.max();if("frobenius"===t){for(var r=0;r=(e=void 0===e?1:e))throw new RangeError("min should be strictly smaller than max");for(var r=this.constructor.empty(this.rows,this.columns),i=0;i=(e=void 0===e?1:e))throw new RangeError("min should be strictly smaller than max");for(var r=this.constructor.empty(this.rows,this.columns),i=0;ir||e<0||e>=this.columns||r<0||r>=this.columns)throw new RangeError("Argument out of range");for(var n=new this.constructor[Symbol.species](t.length,r-e+1),i=0;i=this.rows)throw new RangeError("Row index out of range: ".concat(t[i]));n.set(i,o-e,this.get(t[i],o))}return n}subMatrixColumn(t,e,r){if(void 0===e&&(e=0),void 0===r&&(r=this.rows-1),e>r||e<0||e>=this.rows||r<0||r>=this.rows)throw new RangeError("Argument out of range");for(var n=new this.constructor[Symbol.species](r-e+1,t.length),i=0;i=this.columns)throw new RangeError("Column index out of range: ".concat(t[i]));n.set(o-e,i,this.get(o,t[i]))}return n}setSubMatrix(t,e,r){m(this,e,e+(t=this.constructor.checkMatrix(t)).rows-1,r,r+t.columns-1);for(var n=0;nt?i[o]=1/i[o]:i[o]=0;return i=this.constructor[Symbol.species].diag(i),n.mmul(i.mmul(r.transposeView()))}clone(){for(var t=new this.constructor[Symbol.species](this.rows,this.columns),e=0;e>","signPropagatingRightShift"],[">>>","rightShift","zeroFillRightShift"]]){var p=g(U("\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n",{name:d[1],op:d[0]})),v=g(U("\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% value);\n }\n }\n return this;\n})\n",{name:"".concat(d[1],"S"),op:d[0]})),k=g(U("\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% matrix.get(i, j));\n }\n }\n return this;\n})\n",{name:"".concat(d[1],"M"),op:d[0]})),C=g(U("\n(function %name%(matrix, value) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(value);\n})\n",{name:d[1]}));for(o=1;o0){if(super(t),!(Number.isInteger(e)&&e>0))throw new TypeError("nColumns must be a positive integer");for(r=0;r1&&void 0!==arguments[1]?arguments[1]:{}).rows,r=void 0===e?1:e;if(t.length%r!=0)throw new Error("the data length is not divisible by the number of rows");super(),this.rows=r,this.columns=t.length/r,this.data=t}set(t,e,r){var n=this._calculateIndex(t,e);return this.data[n]=r,this}get(t,e){var r=this._calculateIndex(t,e);return this.data[r]}_calculateIndex(t,e){return t*this.columns+e}static get[Symbol.species](){return O}}class T extends(k()){constructor(t){super(),this.data=t,this.rows=t.length,this.columns=t[0].length}set(t,e,r){return this.data[t][e]=r,this}get(t,e){return this.data[t][e]}static get[Symbol.species](){return O}}function P(t,e){if(Array.isArray(t))return t[0]&&Array.isArray(t[0])?new T(t):new C(t,e);throw new Error("the argument is not an array")}class N{constructor(t){var e,r,n,i,s=(t=T.checkMatrix(t)).clone(),a=t.rows,h=t.columns,u=new Array(h);for(n=0;n=0;o--){for(i=0;i=0;r--){for(t=0;t1&&void 0!==arguments[1]&&arguments[1];return t=T.checkMatrix(t),e?new a(t).inverse():z(t,O.eye(t.rows))}function z(t,e){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=T.checkMatrix(t),e=T.checkMatrix(e),r?new a(t).solve(e):t.isSquare()?new i(t).solve(e):new N(t).solve(e)}var V=r(9);function D(t,e){for(var r=[],n=0;n3&&void 0!==arguments[3]?arguments[3]:1e-9;if(t>(arguments.length>4&&void 0!==arguments[4]?arguments[4]:1e-9))return new Array(e.rows+1).fill(0);for(var i=e.addRow(r,[0]),o=0;o1&&void 0!==arguments[1]?arguments[1]:{};const r=e.thresholdValue,n=void 0===r?1e-9:r,i=e.thresholdError,o=void 0===i?1e-9:i;for(var s=t.rows,h=new O(s,s),u=0;u1&&void 0!==arguments[1]?arguments[1]:{}).assumeSymmetric,r=void 0!==e&&e;if(!(t=T.checkMatrix(t)).isSquare())throw new Error("Matrix is not a square matrix");var n,i,a=t.columns,h=s(a,a,0),u=new Array(a),l=new Array(a),c=t;if(!!r||t.isSymmetric()){for(n=0;n0;a--){for(c=0,s=0,u=0;u0&&(o=-o),e[a]=c*o,s-=i*o,r[a-1]=i-o,h=0;hl){0;do{for(1,i=r[l],f=(r[l+1]-i)/(2*e[l]),g=o(f,1),f<0&&(g=-g),r[l]=e[l]/(f+g),r[l+1]=e[l]*(f+g),d=r[l+1],s=i-r[l],a=l+2;a=l;a--)for(v=p,p=m,x=y,i=m*e[a],s=m*f,g=o(f,e[a]),e[a+1]=y*g,y=e[a]/g,f=(m=f/g)*r[a]-y*i,r[a+1]=s+y*(m*i+y*r[a]),u=0;uS*M)}r[l]=r[l]+b,e[l]=0}for(a=0;a=u;a--)r[a]=e[a][u-1]/l,s+=r[a]*r[a];for(o=Math.sqrt(s),r[u]>0&&(o=-o),s-=r[u]*o,r[u]=r[u]-o,h=u;h=u;a--)i+=r[a]*e[a][h];for(i/=s,a=u;a<=c;a++)e[a][h]-=i*r[a]}for(a=0;a<=c;a++){for(i=0,h=c;h>=u;h--)i+=r[h]*e[a][h];for(i/=s,h=u;h<=c;h++)e[a][h]-=i*r[h]}r[u]=l*r[u],e[u][u-1]=l*o}}for(a=0;a=1;u--)if(0!==e[u][u-1]){for(a=u+1;a<=c;a++)r[a]=e[a][u-1];for(h=u;h<=c;h++){for(o=0,a=u;a<=c;a++)o+=r[a]*n[a][h];for(o=o/r[u]/e[u][u-1],a=u;a<=c;a++)n[a][h]+=o*r[a]}}}(a,f,g,h),function(t,e,r,n,i){var o,s,a,h,u,l,c,f,g,d,m,p,v,w,y,x=t-1,b=t-1,M=Number.EPSILON,S=0,A=0,E=0,R=0,k=0,O=0,C=0,T=0;for(o=0;ob)&&(r[o]=i[o][o],e[o]=0),s=Math.max(o-1,0);s=0;){for(h=x;h>0&&(0===(O=Math.abs(i[h-1][h-1])+Math.abs(i[h][h]))&&(O=A),!(Math.abs(i[h][h-1])=0){for(C=E>=0?E+C:E-C,r[x-1]=f+C,r[x]=r[x-1],0!==C&&(r[x]=f-c/C),e[x-1]=0,e[x]=0,f=i[x][x-1],O=Math.abs(f)+Math.abs(C),E=f/O,R=C/O,k=Math.sqrt(E*E+R*R),E/=k,R/=k,s=x-1;s0){for(O=Math.sqrt(O),g=h&&(C=i[u][u],E=((k=f-C)*(O=g-C)-c)/i[u+1][u]+i[u][u+1],R=i[u+1][u+1]-C-k-O,k=i[u+2][u+1],O=Math.abs(E)+Math.abs(R)+Math.abs(k),E/=O,R/=O,k/=O,u!==h)&&!(Math.abs(i[u][u-1])*(Math.abs(R)+Math.abs(k))u+2&&(i[o][o-3]=0);for(a=u;a<=x-1&&(w=a!==x-1,a!==u&&(E=i[a][a-1],R=i[a+1][a-1],k=w?i[a+2][a-1]:0,0!==(f=Math.abs(E)+Math.abs(R)+Math.abs(k))&&(E/=f,R/=f,k/=f)),0!==f);a++)if(O=Math.sqrt(E*E+R*R+k*k),E<0&&(O=-O),0!==O){for(a!==u?i[a][a-1]=-O*f:h!==u&&(i[a][a-1]=-i[a][a-1]),f=(E+=O)/O,g=R/O,C=k/O,R/=E,k/=E,s=a;s=0;x--)if(E=r[x],0===(R=e[x]))for(h=x,i[x][x]=1,o=x-1;o>=0;o--){for(c=i[o][o]-E,k=0,s=h;s<=x;s++)k+=i[o][s]*i[s][x];if(e[o]<0)C=c,O=k;else if(h=o,0===e[o]?i[o][x]=0!==c?-k/c:-k/(M*A):(f=i[o][o+1],g=i[o+1][o],R=(r[o]-E)*(r[o]-E)+e[o]*e[o],l=(f*O-C*k)/R,i[o][x]=l,i[o+1][x]=Math.abs(f)>Math.abs(C)?(-k-c*l)/f:(-O-g*l)/C),l=Math.abs(i[o][x]),M*l*l>1)for(s=o;s<=x;s++)i[s][x]=i[s][x]/l}else if(R<0)for(h=x-1,Math.abs(i[x][x-1])>Math.abs(i[x-1][x])?(i[x-1][x-1]=R/i[x][x-1],i[x-1][x]=-(i[x][x]-E)/i[x][x-1]):(y=I(0,-i[x-1][x],i[x-1][x-1]-E,R),i[x-1][x-1]=y[0],i[x-1][x]=y[1]),i[x][x-1]=0,i[x][x]=1,o=x-2;o>=0;o--){for(d=0,m=0,s=h;s<=x;s++)d+=i[o][s]*i[s][x-1],m+=i[o][s]*i[s][x];if(c=i[o][o]-E,e[o]<0)C=c,k=d,O=m;else if(h=o,0===e[o]?(y=I(-d,-m,c,R),i[o][x-1]=y[0],i[o][x]=y[1]):(f=i[o][o+1],g=i[o+1][o],p=(r[o]-E)*(r[o]-E)+e[o]*e[o]-R*R,v=2*(r[o]-E)*R,0===p&&0===v&&(p=M*A*(Math.abs(c)+Math.abs(R)+Math.abs(f)+Math.abs(g)+Math.abs(C))),y=I(f*k-C*d+R*m,f*O-C*m-R*d,p,v),i[o][x-1]=y[0],i[o][x]=y[1],Math.abs(f)>Math.abs(C)+Math.abs(R)?(i[o+1][x-1]=(-d-c*i[o][x-1]+R*i[o][x])/f,i[o+1][x]=(-m-c*i[o][x]-R*i[o][x-1])/f):(y=I(-k-g*i[o][x-1],-O-g*i[o][x],C,R),i[o+1][x-1]=y[0],i[o+1][x]=y[1])),l=Math.max(Math.abs(i[o][x-1]),Math.abs(i[o][x])),M*l*l>1)for(s=o;s<=x;s++)i[s][x-1]=i[s][x-1]/l,i[s][x]=i[s][x]/l}for(o=0;ob)for(s=o;s=0;s--)for(o=0;o<=b;o++){for(C=0,a=0;a<=Math.min(s,b);a++)C+=n[o][a]*i[a][s];n[o][s]=C}}(a,l,u,h,f)}this.n=a,this.e=l,this.d=u,this.V=h}get realEigenvalues(){return this.d}get imaginaryEigenvalues(){return this.e}get eigenvectorMatrix(){return O.isMatrix(this.V)||(this.V=new O(this.V)),this.V}get diagonalMatrix(){var t,e,r=this.n,n=this.e,i=this.d,o=new O(r,r);for(t=0;t0?o[t][t+1]=n[t]:n[t]<0&&(o[t][t-1]=n[t])}return o}}function I(t,e,r,n){var i,o;return Math.abs(r)>Math.abs(n)?[(t+(i=n/r)*e)/(o=r+i*n),(e-i*t)/o]:[((i=r/n)*t+e)/(o=n+i*r),(i*e-t)/o]}class q{constructor(t){if(!(t=T.checkMatrix(t)).isSymmetric())throw new Error("Matrix is not symmetric");var e,r,n,i=t,o=i.rows,s=new O(o,o),a=!0;for(r=0;r0,s[r][r]=Math.sqrt(Math.max(u,0)),n=r+1;n=0;o--)for(i=0;ie&&(e=t[r][n]);return e},e.min=function(t){for(var e=1/0,r=0;rr&&(r=t[n][i]);return{min:e,max:r}},e.entropy=function(t,e){void 0===e&&(e=0);for(var r=0,n=t.length,i=t[0].length,o=0;o=0?s[l]++:(h[u]=t[r][e],s[u]=1,u++)}var c=0,f=0;for(r=0;rc&&(c=s[r],f=r);o[e]=h[f]}return o},e.skewness=function(t,r){void 0===r&&(r=!0);for(var n=e.mean(t),i=t.length,o=n.length,s=new Array(o),a=0;a=t.length)throw new RangeError("invalid lower bound");if(void 0===i)i=t.length-1;else if((i|=0)=t.length)throw new RangeError("invalid upper bound");for(;n<=i;)if((s=+r(t[o=n+(i-n>>1)],e,o,t))<0)n=o+1;else{if(!(s>0))return o;i=o-1}return~n}},function(t,e,r){"use strict";var n=r(74);function i(t){if("number"!=typeof t||n(t))throw new TypeError("Expected a number")}e.asc=function(t,e){return i(t),i(e),t-e},e.desc=function(t,e){return i(t),i(e),e-t}},function(t,e,r){"use strict";r.r(e);var n=r(0),i=r(5);function o(t,e){for(var r=new Array(e).fill(0),i=0;it>e:(t,e)=>t.01&&this.gain!==i&&a.lesserX.length>0&&a.greaterX.length>0){this.left=new c(this),this.right=new c(this);var h=new n.default(a.lesserX),u=new n.default(a.greaterX);this.left.train(h,a.lesserY,r+1,this.gain),this.right.train(u,a.greaterY,r+1,this.gain)}else this.calculatePrediction(e)}}classify(t){return this.right&&this.left?t[this.splitColumn]e&&(e=t[r]);return e}},function(t,e,r){"use strict";const n=r(0).Matrix,i=r(54),o=r(55),s=r(56),a=r(57),h=r(58),u=r(59),l=r(60),c=r(61),f=r(62),g=r(63),d={gaussian:i,rbf:i,polynomial:o,poly:o,anova:s,cauchy:a,exponential:h,histogram:u,min:u,laplacian:l,multiquadratic:c,rational:f,sigmoid:g,mlp:g};t.exports=class{constructor(t,e){if(this.kernelType=t,"linear"!==t)if("string"==typeof t){t=t.toLowerCase();var r=d[t];if(!r)throw new Error("unsupported kernel type: "+t);this.kernelFunction=new r(e)}else{if("object"!=typeof t||"function"!=typeof t.compute)throw new TypeError("first argument must be a valid kernel type or instance");this.kernelFunction=t}}compute(t,e){if(void 0===e&&(e=t),"linear"===this.kernelType)return new n(t).mmul(new n(e).transposeView());const r=new n(t.length,e.length);var i,o;if(t===e)for(i=0;ir[t];)t++;return t}return Math.floor(n*t)}var s=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Math.random;const n=e.size,s=void 0===n?1:n,a=e.replace,h=void 0!==a&&a,u=e.probabilities;let l,c;if(l="number"==typeof t?function(t){const e=[];for(let r=0;ri)throw new Error("probabilities should sum to 1, but instead sums to ".concat(c[c.length-1]))}if(!1===h&&s>l.length)throw new Error("size option is too large");const f=[];for(let t=0;t0&&void 0!==arguments[0]?arguments[0]:Math.random;if("number"==typeof t){const e=new n.default(t);this.randomGenerator=e.random}else this.randomGenerator=t}choice(t,e){return s(t,e,this.randomGenerator)}random(){return this.randomGenerator()}randInt(t,e){return void 0===e&&(e=t,t=0),t+Math.floor(this.randomGenerator()*(e-t))}randomSample(t){const e=[];for(let r=0;r>>16&65535)*n+r*(e>>>16&65535)<<16>>>0)|0}:Math.imul,s="function"==typeof String.prototype.repeat&&"xxx"==="x".repeat(3)?function(t,e){return t.repeat(e)}:function(t,e){for(var r="";e>0;)1&e&&(r+=t),e>>=1,t+=t;return r};function a(t){if(!(this instanceof a))return new a(t);if(null==t)t=a.engines.nativeMath;else if("function"!=typeof t)throw new TypeError("Expected engine to be a function, got "+typeof t);this.engine=t}var h,u,l=a.prototype;function c(t){return function(){return t}}function f(t,e){return 0===e?t:function(r){return t(r)+e}}function g(t){var e=+t;return e<0?Math.ceil(e):Math.floor(e)}function d(t,e){return t<0?Math.max(t+e,0):Math.min(t,e)}function m(){}a.engines={nativeMath:function(){return 4294967296*Math.random()|0},mt19937:function(t){function e(t){for(var e=0,r=0;(0|e)<227;e=e+1|0)r=2147483648&t[e]|2147483647&t[e+1|0],t[e]=t[e+397|0]^r>>>1^(1&r?2567483615:0);for(;(0|e)<623;e=e+1|0)r=2147483648&t[e]|2147483647&t[e+1|0],t[e]=t[e-227|0]^r>>>1^(1&r?2567483615:0);r=2147483648&t[623]|2147483647&t[0],t[623]=t[396]^r>>>1^(1&r?2567483615:0)}return function(){var r=new t(624),n=0,i=0;function s(){(0|n)>=624&&(e(r),n=0);var t=r[n];return n=n+1|0,i+=1,0|function(t){return t^=t>>>11,t^=t<<7&2636928640,(t^=t<<15&4022730752)^t>>>18}(t)}return s.getUseCount=function(){return i},s.discard=function(t){for(i+=t,(0|n)>=624&&(e(r),n=0);t-n>624;)t-=624-n,e(r),n=0;return n=n+t|0,s},s.seed=function(t){var e=0;r[0]=e=0|t;for(var a=1;a<624;a=a+1|0)r[a]=e=o(e^e>>>30,1812433253)+a|0;return n=624,i=0,s},s.seedWithArray=function(t){return s.seed(19650218),function(t,e){for(var r=1,n=0,i=e.length,s=0|Math.max(i,624),a=0|t[0];(0|s)>0;--s)t[r]=a=(t[r]^o(a^a>>>30,1664525))+(0|e[n])+(0|n)|0,++n,(0|(r=r+1|0))>623&&(t[0]=t[623],r=1),n>=i&&(n=0);for(s=623;(0|s)>0;--s)t[r]=a=(t[r]^o(a^a>>>30,1566083941))-r|0,(0|(r=r+1|0))>623&&(t[0]=t[623],r=1);t[0]=2147483648}(r,t),s},s.autoSeed=function(){return s.seedWithArray(a.generateEntropyArray())},s}}("function"==typeof Int32Array?Int32Array:Array),browserCrypto:"undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&"function"==typeof Int32Array?(h=null,u=128,function(){return u>=128&&(null===h&&(h=new Int32Array(128)),crypto.getRandomValues(h),u=0),0|h[u++]}):null},a.generateEntropyArray=function(){for(var t=[],e=a.engines.nativeMath,r=0;r<16;++r)t[r]=0|e();return t.push(0|(new Date).getTime()),t},a.int32=function(t){return 0|t()},l.int32=function(){return a.int32(this.engine)},a.uint32=function(t){return t()>>>0},l.uint32=function(){return a.uint32(this.engine)},a.uint53=function(t){return 4294967296*(2097151&t())+(t()>>>0)},l.uint53=function(){return a.uint53(this.engine)},a.uint53Full=function(t){for(;;){var e=0|t();if(!(2097152&e))return 4294967296*(2097151&e)+(t()>>>0);if(2097152==(4194303&e)&&0==(0|t()))return 9007199254740992}},l.uint53Full=function(){return a.uint53Full(this.engine)},a.int53=function(t){var e=0|t();return 4294967296*(2097151&e)+(t()>>>0)+(2097152&e?-9007199254740992:0)},l.int53=function(){return a.int53(this.engine)},a.int53Full=function(t){for(;;){var e=0|t();if(!(4194304&e))return 4294967296*(2097151&e)+(t()>>>0)+(2097152&e?-9007199254740992:0);if(4194304==(8388607&e)&&0==(0|t()))return 9007199254740992}},l.int53Full=function(){return a.int53Full(this.engine)},a.integer=function(){function t(t){return 0==(t+1&t)}function e(e){return t(e)?(r=e,function(t){return t()&r}):function(t){var e=t+1,r=e*Math.floor(4294967296/e);return function(t){var n=0;do{n=t()>>>0}while(n>=r);return n%e}}(e);var r}function r(e){var r,n=e+1;if(0==(0|n)){var i=(n/4294967296|0)-1;if(t(i))return r=i,function(t){return 4294967296*(t()&r)+(t()>>>0)}}return function(t){var e=t*Math.floor(9007199254740992/t);return function(r){var n=0;do{n=4294967296*(2097151&r())+(r()>>>0)}while(n>=e);return n%t}}(n)}function n(t,e){return function(r){var n=0;do{var i=0|r();n=4294967296*(2097151&i)+(r()>>>0)+(2097152&i?-9007199254740992:0)}while(ne);return n}}return function(t,i){if(t=Math.floor(t),i=Math.floor(i),t<-9007199254740992||!isFinite(t))throw new RangeError("Expected min to be at least -9007199254740992");if(i>9007199254740992||!isFinite(i))throw new RangeError("Expected max to be at most 9007199254740992");var o=i-t;return o<=0||!isFinite(o)?c(t):4294967295===o?0===t?a.uint32:f(a.int32,t+2147483648):o<4294967295?f(e(o),t):9007199254740991===o?f(a.uint53,t):o<9007199254740991?f(r(o),t):i-1-t==9007199254740991?f(a.uint53Full,t):-9007199254740992===t&&9007199254740992===i?a.int53Full:-9007199254740992===t&&9007199254740991===i?a.int53:-9007199254740991===t&&9007199254740992===i?f(a.int53,1):9007199254740992===i?f(n(t-1,i-1),1):n(t,i)}}(),l.integer=function(t,e){return a.integer(t,e)(this.engine)},a.realZeroToOneInclusive=function(t){return a.uint53Full(t)/9007199254740992},l.realZeroToOneInclusive=function(){return a.realZeroToOneInclusive(this.engine)},a.realZeroToOneExclusive=function(t){return a.uint53(t)/9007199254740992},l.realZeroToOneExclusive=function(){return a.realZeroToOneExclusive(this.engine)},a.real=function(){return function(t,e,r){if(!isFinite(t))throw new RangeError("Expected left to be a finite number");if(!isFinite(e))throw new RangeError("Expected right to be a finite number");return f((n=r?a.realZeroToOneInclusive:a.realZeroToOneExclusive,1===(i=e-t)?n:0===i?function(){return 0}:function(t){return n(t)*i}),t);var n,i}}(),l.real=function(t,e,r){return a.real(t,e,r)(this.engine)},a.bool=function(){function t(t){return 1==(1&t())}function e(t,e){return function(r){return t(r)=1)return c(!0);var r=4294967296*t;return r%1==0?e(a.int32,r-2147483648|0):e(a.uint53,Math.round(9007199254740992*t))}(r):r<=0?c(!1):r>=n?c(!0):e(a.integer(0,n-1),r)}}(),l.bool=function(t,e){return a.bool(t,e)(this.engine)},a.pick=function(t,e,r,n){var i=e.length,o=null==r?0:d(g(r),i),s=void 0===n?i:d(g(n),i);if(!(o>=s))return e[a.integer(o,s-1)(t)]},l.pick=function(t,e,r){return a.pick(this.engine,t,e,r)};var p,v,w=Array.prototype.slice;a.picker=function(t,e,r){var n=w.call(t,e,r);if(!n.length)return m;var i=a.integer(0,n.length-1);return function(t){return n[i(t)]}},a.shuffle=function(t,e,r){var n=e.length;if(n){null==r&&(r=0);for(var i=n-1>>>0;i>r;--i){var o=a.integer(0,i)(t);if(i!==o){var s=e[i];e[i]=e[o],e[o]=s}}}return e},l.shuffle=function(t){return a.shuffle(this.engine,t)},a.sample=function(t,e,r){if(r<0||r>e.length||!isFinite(r))throw new RangeError("Expected sampleSize to be within 0 and the length of the population");if(0===r)return[];var n=w.call(e),i=n.length;if(i===r)return a.shuffle(t,n,0);var o=i-r;return a.shuffle(t,n,o-1).slice(o)},l.sample=function(t,e){return a.sample(this.engine,t,e)},a.die=function(t){return a.integer(1,t)},l.die=function(t){return a.die(t)(this.engine)},a.dice=function(t,e){var r=a.die(t);return function(t){var n=[];n.length=e;for(var i=0;i>>0,n=0|e(),i=0|e(),o=e()>>>0;return t(r.toString(16),8)+"-"+t((65535&n).toString(16),4)+"-"+t((n>>4&4095|16384).toString(16),4)+"-"+t((16383&i|32768).toString(16),4)+"-"+t((i>>4&65535).toString(16),4)+t(o.toString(16),8)}}(),l.uuid4=function(){return a.uuid4(this.engine)},a.string=function(t){null==t&&(t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-");var e=t.length;if(!e)throw new Error("Expected pool not to be an empty string");var r=a.integer(0,e-1);return function(e,n){for(var i="",o=0;o1&&void 0!==arguments[1]?arguments[1]:{};if(!s()(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");if(void 0!==r.output){if(!s()(r.output))throw new TypeError("output option must be an array if specified");e=r.output}else e=new Array(t.length);var o=Object(i.default)(t),a=Object(n.default)(t);if(o===a)throw new RangeError("minimum and maximum input values are equal. Cannot rescale a constant array");var h=r.min,u=void 0===h?r.autoMinMax?o:0:h,l=r.max,c=void 0===l?r.autoMinMax?a:1:l;if(u>=c)throw new RangeError("min option must be smaller than max option");for(var f=(c-u)/(a-o),g=0;g0&&void 0!==arguments[0]?arguments[0]:{};if(t instanceof g)return this.table=t.table.slice(),this.values=t.values.slice(),this.state=t.state.slice(),this.minLoadFactor=t.minLoadFactor,this.maxLoadFactor=t.maxLoadFactor,this.distinct=t.distinct,this.freeEntries=t.freeEntries,this.lowWaterMark=t.lowWaterMark,void(this.highWaterMark=t.maxLoadFactor);const e=void 0===t.initialCapacity?l:t.initialCapacity;if(e<0)throw new RangeError("initial capacity must not be less than zero: ".concat(e));const r=void 0===t.minLoadFactor?c:t.minLoadFactor,i=void 0===t.maxLoadFactor?f:t.maxLoadFactor;if(r<0||r>=1)throw new RangeError("invalid minLoadFactor: ".concat(r));if(i<=0||i>=1)throw new RangeError("invalid maxLoadFactor: ".concat(i));if(r>=i)throw new RangeError("minLoadFactor (".concat(r,") must be smaller than maxLoadFactor (").concat(i,")"));let a=e;0===(a=o(a=a/i|0))&&(a=1),this.table=n(a,0),this.values=n(a,0),this.state=n(a,0),this.minLoadFactor=r,this.maxLoadFactor=a===s?1:i,this.distinct=0,this.freeEntries=a,this.lowWaterMark=0,this.highWaterMark=d(a,this.maxLoadFactor)}clone(){return new g(this)}get size(){return this.distinct}get(t){const e=this.indexOfKey(t);return e<0?0:this.values[e]}set(t,e){let r=this.indexOfInsertion(t);if(r<0)return r=-r-1,this.values[r]=e,!1;if(this.distinct>this.highWaterMark){const r=m(this.distinct+1,this.minLoadFactor,this.maxLoadFactor);return this.rehash(r),this.set(t,e)}if(this.table[r]=t,this.values[r]=e,this.state[r]===a&&this.freeEntries--,this.state[r]=h,this.distinct++,this.freeEntries<1){const t=m(this.distinct+1,this.minLoadFactor,this.maxLoadFactor);this.rehash(t)}return!0}remove(t,e){const r=this.indexOfKey(t);return!(r<0)&&(this.state[r]=u,this.distinct--,e||this.maybeShrinkCapacity(),!0)}delete(t,e){const r=this.indexOfKey(t);return!(r<0)&&(this.state[r]=a,this.distinct--,e||this.maybeShrinkCapacity(),!0)}maybeShrinkCapacity(){if(this.distinct=0}indexOfKey(t){const e=this.table,r=this.state,n=this.table.length,i=2147483647&t;let o=i%n,s=i%(n-2);for(0===s&&(s=1);r[o]!==a&&(r[o]===u||e[o]!==t);)(o-=s)<0&&(o+=n);return r[o]===a?-1:o}containsValue(t){return this.indexOfValue(t)>=0}indexOfValue(t){const e=this.values,r=this.state;for(var n=0;n0;){var o=r.shift();t>=o.distance?n.push(o):r=r.concat(o.children)}return n},i.prototype.group=function(t){if(!Number.isInteger(t)||t<1)throw new RangeError("Number of groups must be a positive integer");const e=new n(function(t,e){return e.distance-t.distance});for(e.push(this);e.size()e.push(t))}var o=new i;return o.children=e.toArray(),o.distance=this.distance,o},i.prototype.traverse=function(t){!function t(e,r){if(r(e),e.children)for(var n=e.children.length-1;n>=0;n--)t(e.children[n],r)}(this,t)},t.exports=i},function(t,e,r){"use strict";var n=Object.prototype.hasOwnProperty,i=Object.prototype.toString,o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(t){return"function"==typeof Array.isArray?Array.isArray(t):"[object Array]"===i.call(t)},h=function(t){if(!t||"[object Object]"!==i.call(t))return!1;var e,r=n.call(t,"constructor"),o=t.constructor&&t.constructor.prototype&&n.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!r&&!o)return!1;for(e in t);return void 0===e||n.call(t,e)},u=function(t,e){o&&"__proto__"===e.name?o(t,e.name,{enumerable:!0,configurable:!0,value:e.newValue,writable:!0}):t[e.name]=e.newValue},l=function(t,e){if("__proto__"===e){if(!n.call(t,e))return;if(s)return s(t,e).value}return t[e]};t.exports=function t(){var e,r,n,i,o,s,c=arguments[0],f=1,g=arguments.length,d=!1;for("boolean"==typeof c&&(d=c,c=arguments[1]||{},f=2),(null==c||"object"!=typeof c&&"function"!=typeof c)&&(c={});f>>=0);return((t-r)*(e>>>=0)>>>0)+r*e>>>0}class u{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Date.now();this.state=new Uint32Array(4),this.init(t),this.random=this.getFloat.bind(this)}getUint32(){return this.nextState(),this.state[3]+this.state[2]>>>0}getFloat(){return(this.getUint32()>>>8)*i}init(t){if(!Number.isInteger(t))throw new TypeError("seed must be an integer");this.state[0]=t,this.state[1]=0,this.state[2]=0,this.state[3]=0;for(let t=1;t>>30>>>0)>>>0;this.periodCertification();for(let t=0;t>>s,t^=this.state[3]<1&&void 0!==arguments[1]?arguments[1]:{};if(!o()(t))throw new TypeError("input must be an array");for(var r=e.unbiased,i=void 0===r||r,s=e.mean,a=void 0===s?Object(n.default)(t):s,h=0,u=0;ue&&(e=t[n]);return e},e.min=function(t){for(var e=t[0],r=t.length,n=1;nr&&(r=t[i]);return{min:e,max:r}},e.arithmeticMean=function(t){for(var e=0,r=t.length,n=0;n=0?n[s]++:(i[o]=t[e],n[o]=1,o++)}var a=0,h=0;for(e=0;ea&&(a=n[e],h=e);return i[h]},e.covariance=function(t,r,n){void 0===n&&(n=!0);var i=e.mean(t),o=e.mean(r);if(t.length!==r.length)throw"Vectors do not have the same dimensions";for(var s=0,a=t.length,h=0;hArray.from({length:r}));for(let i=0;i2&&void 0!==arguments[2]?arguments[2]:{};if(e.length!==t.length)throw new Error("predicted and actual must have the same length");n=i.labels?new Set(i.labels):new Set([...t,...e]),n=Array.from(n),i.sort&&n.sort(i.sort);const o=Array.from({length:n.length});for(let t=0;t=0&&s>=0&&o[i][s]++}return new r(o,n)}getMatrix(){return this.matrix}getLabels(){return this.labels}getTotalCount(){let t=0;for(var e=0;e1?r=>e.activation(r,t.activationParam):e.activation,s=r>1?r=>e.derivate(r,t.activationParam):e.derivate;this.activationFunction=function(t,e){this[t][e]=i(this[t][e])},this.derivate=function(t,e){this[t][e]=s(this[t][e])},t.model?(this.W=n.checkMatrix(t.W),this.b=n.checkMatrix(t.b)):(this.W=n.rand(this.inputSize,this.outputSize),this.b=n.zeros(1,this.outputSize),this.W.apply(function(e,r){this[e][r]/=Math.sqrt(t.inputSize)}))}forward(t){var e=t.mmul(this.W).addRowVector(this.b);return e.apply(this.activationFunction),this.a=e.clone(),e}backpropagation(t,e){this.dW=e.transposeView().mmul(t),this.db=i.sumCol(t);var r=e.clone();return t.mmul(this.W.transposeView()).mul(r.apply(this.derivate))}update(){this.dW.add(this.W.clone().mul(this.regularization)),this.W.add(this.dW.mul(-this.epsilon)),this.b.add(this.db.mul(-this.epsilon))}toJSON(){return{model:"Layer",inputSize:this.inputSize,outputSize:this.outputSize,regularization:this.regularization,epsilon:this.epsilon,activation:this.activation,W:this.W,b:this.b}}static load(t){if("Layer"!==t.model)throw new RangeError("the current model is not a Layer model");return new s(t)}}t.exports=s},function(t,e,r){"use strict";var n=r(0).Matrix;t.exports={dictOutputs:function(t){for(var e={},r={},n=0,i=0;i1-t*t},identity:{activation:t=>t,derivate:()=>1},logistic:{activation:n,derivate:t=>n(t)*(1-n(t))},arctan:{activation:Math.atan,derivate:t=>1/(t*t+1)},softsign:{activation:t=>t/(1+Math.abs(t)),derivate:t=>1/((1+Math.abs(t))*(1+Math.abs(t)))},relu:{activation:t=>t<0?0:t,derivate:t=>t<0?0:1},softplus:{activation:t=>Math.log(1+Math.exp(t)),derivate:t=>1/(1+Math.exp(-t))},bent:{activation:t=>(Math.sqrt(t*t+1)-1)/2+t,derivate:t=>t/(2*Math.sqrt(t*t+1))+1},sinusoid:{activation:Math.sin,derivate:Math.cos},sinc:{activation:t=>0===t?1:Math.sin(t)/t,derivate:t=>0===t?0:Math.cos(t)/t-Math.sin(t)/(t*t)},gaussian:{activation:t=>Math.exp(-t*t),derivate:t=>-2*t*Math.exp(-t*t)},"parametric-relu":{activation:(t,e)=>t<0?e*t:t,derivate:(t,e)=>t<0?e:1},"exponential-elu":{activation:i,derivate:(t,e)=>t<0?i(t,e)+e:1},"soft-exponential":{activation:function(t,e){return e<0?-Math.log(1-e*(t+e))/e:e>0?(Math.exp(e*t)-1)/e+e:t},derivate:function(t,e){return e<0?1/(1-e*(e+t)):Math.exp(e*t)}}};t.exports=o},function(t,e){function r(t,e,r,n){this.x=t,this.y=e,this.weights=r,this.som=n,this.neighbors={}}r.prototype.adjustWeights=function(t,e,r){for(var n=0,i=this.weights.length;n0?e=this[t]-1:this.som.torus&&(e=this.som.gridDim[t]-1),void 0!==e)"x"===t?(r=e,n=this.y):(r=this.x,n=e),this.neighbors[t][0]=this.som.nodes[r][n];this[t]r||e.size[1]>r)throw new RangeError("expanded value should not be bigger than the data length");for(i=0;i0&&e!==this.coefficients.length-1?a=" + "+a:e!==this.coefficients.length-1&&(a=" "+a)),s=a+s;return"+"===s.charAt(0)&&(s=s.slice(1)),"f(x) = "+s}static load(t){if("polynomialRegression"!==t.name)throw new TypeError("not a polynomial regression model");return new h(!0,t)}}class u extends o{constructor(t,e){super(),!0===t?(this.A=e.A,this.B=e.B):(i(t,e),function(t,e,r){const n=e.length,i=new Array(n);for(let t=0;t=0?"f(x) = "+n(this.B,t)+"e^{"+n(this.A,t)+"x}":"f(x) = \\frac{"+n(this.B,t)+"}{e^{"+n(-this.A,t)+"x}}"}static load(t){if("exponentialRegression"!==t.name)throw new TypeError("not a exponential regression model");return new u(!0,t)}}class l extends o{constructor(t,e){super(),!0===t?(this.A=e.A,this.B=e.B):(i(t,e),function(t,e,r){const n=e.length,i=new Array(n),o=new Array(n);for(let t=0;t=0?"f(x) = "+n(this.A,t)+"x^{"+n(this.B,t)+"}":"f(x) = \\frac{"+n(this.A,t)+"}{x^{"+n(-this.B,t)+"}}"}static load(t){if("powerRegression"!==t.name)throw new TypeError("not a power regression model");return new l(!0,t)}}class c extends o{constructor(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=r.intercept,i=void 0===n||n,o=r.statistics,s=void 0===o||o;if(super(),this.statistics=s,!0===t)this.weights=e.weights,this.inputs=e.inputs,this.outputs=e.outputs,this.intercept=e.intercept;else{t=new a.default(t),i&&t.addColumn(new Array(t.length).fill(1));const r=new a.SVD(t,{autoTranspose:!0}).solve(e);if(this.weights=r.to2DArray(),this.inputs=t[0].length,this.outputs=e[0].length,i&&this.inputs--,this.intercept=i,s){const n=t.mmul(r),i=new a.default(e).addM(n.neg()).to2DArray().map(t=>Math.pow(t[0],2)).reduce((t,e)=>t+e)/(e.length-t.columns);this.stdError=Math.sqrt(i),this.stdErrorMatrix=t.transposeView().mmul(t).pseudoInverse().mul(i),this.stdErrors=this.stdErrorMatrix.diagonal().map(t=>Math.sqrt(t)),this.tStats=this.weights.map((t,e)=>0===this.stdErrors[e]?0:t[0]/this.stdErrors[e])}}}predict(t){if(Array.isArray(t)){if("number"==typeof t[0])return this._predict(t);if(Array.isArray(t[0])){const e=new Array(t.length);for(let r=0;r({label:e===this.weights.length-1?"Intercept":"X Variable ".concat(e+1),coefficients:t,standardError:this.stdErrors[e],tStat:this.tStats[e]}))}:void 0}}static load(t){if("multivariateLinearRegression"!==t.name)throw new Error("not a MLR model");return new c(!0,t)}}class f extends o{constructor(t,e,r){if(super(),!0===t)this.A=e.A,this.M=e.M;else{if(t.length!==e.length)throw new RangeError("input and output array have a different length");var n=new h(t,e,[r]);this.A=n.coefficients[0],this.M=r}}_predict(t){return this.A*Math.pow(t,this.M)}toJSON(){return{name:"potentialRegression",A:this.A,M:this.M}}toString(t){return"f(x) = "+n(this.A,t)+" * x^"+this.M}toLaTeX(t){return this.M>=0?"f(x) = "+n(this.A,t)+"x^{"+this.M+"}":"f(x) = \\frac{"+n(this.A,t)+"}{x^{"+-this.M+"}}"}static load(t){if("potentialRegression"!==t.name)throw new TypeError("not a potential regression model");return new f(!0,t)}}var g=r(10),d=r.n(g);const m={lambda:.1,kernelType:"gaussian",kernelOptions:{},computeCoefficient:!1};class p extends o{constructor(t,e,r){if(super(),!0===t)this.alpha=e.alpha,this.inputs=e.inputs,this.kernelType=e.kernelType,this.kernelOptions=e.kernelOptions,this.kernel=new d.a(e.kernelType,e.kernelOptions);else{r=Object.assign({},m,r);const n=new d.a(r.kernelType,r.kernelOptions),i=n.compute(t),o=t.length;i.add(a.Matrix.eye(o,o).mul(r.lambda)),this.alpha=Object(a.solve)(i,e),this.inputs=t,this.kernelType=r.kernelType,this.kernelOptions=r.kernelOptions,this.kernel=n}}_predict(t){return this.kernel.compute([t],this.inputs).mmul(this.alpha)[0]}toJSON(){return{name:"kernelRidgeRegression",alpha:this.alpha,inputs:this.inputs,kernelType:this.kernelType,kernelOptions:this.kernelOptions}}static load(t){if("kernelRidgeRegression"!==t.name)throw new TypeError("not a KRR model");return new p(!0,t)}}const v={order:2};class w extends o{constructor(t,e,r){super(),!0===t?(this.coefficients=a.Matrix.columnVector(e.coefficients),this.order=e.order,e.r&&(this.r=e.r,this.r2=e.r2),e.chi2&&(this.chi2=e.chi2)):(r=Object.assign({},v,r),this.order=r.order,this.coefficients=[],this.X=t,this.y=e,this.train(this.X,this.y,r))}train(t,e){if(a.Matrix.isMatrix(t)||(t=new a.Matrix(t)),a.Matrix.isMatrix(e)||(e=a.Matrix.columnVector(e)),e.rows!==t.rows&&(e=e.transpose()),2!==t.columns)throw new RangeError("You give X with "+t.columns+" columns and it must be 2");if(t.rows!==e.rows)throw new RangeError("X and y must have the same rows");var r=t.rows,n=(this.order+2)*(this.order+1)/2;this.coefficients=new Array(n);var i=t.getColumnVector(0),o=t.getColumnVector(1),s=1/i.clone().apply(x).max(),h=1/o.clone().apply(x).max(),u=1/e.clone().apply(x).max();i.mulColumn(0,s),o.mulColumn(0,h),e.mulColumn(0,u);for(var l=new a.Matrix(r,n),c=0,f=0;f<=this.order;++f)for(var g=this.order-f,d=0;d<=g;++d){var m=y(i,f).mulColumnVector(y(o,d));l.setColumn(c,m),c++}var p=new a.SVD(l.transpose(),{computeLeftSingularVectors:!0,computeRightSingularVectors:!0,autoTranspose:!1}),v=a.Matrix.rowVector(p.diagonal);v=v.apply(function(t,e){this[t][e]>=1e-15?this[t][e]=1/this[t][e]:this[t][e]=0});var w=a.Matrix.zeros(r,n);for(f=0;f0&&e!==this.coefficients.length-1?a=" + "+a:e!==this.coefficients.length-1&&(a=" "+a)),s=a+s;return"+"===s.charAt(0)&&(s=s.slice(1)),"f(x) = "+s}static load(t){if("robustPolynomialRegression"!==t.name)throw new TypeError("not a RobustPolynomialRegression model");return new S(!0,t)}}function A(t,e){for(var r=t.slice(),n=t.slice(),i=0;it.residual-e.residual);var e=t.length,r=Math.floor(e/2);return e%2==0?t[r-1]:t[r]}r.d(e,"NLR",function(){return k}),r.d(e,"NonLinearRegression",function(){return k}),r.d(e,"SimpleLinearRegression",function(){return s}),r.d(e,"SLR",function(){return s}),r.d(e,"PolynomialRegression",function(){return h}),r.d(e,"ExponentialRegression",function(){return u}),r.d(e,"PowerRegression",function(){return l}),r.d(e,"MultivariateLinearRegression",function(){return c}),r.d(e,"KernelRidgeRegression",function(){return p}),r.d(e,"KRR",function(){return p}),r.d(e,"PolinomialFitting2D",function(){return w}),r.d(e,"TheilSenRegression",function(){return M}),r.d(e,"RobustPolynomialRegression",function(){return S});const k={PotentialRegression:f}},function(t,e,r){!function(){function e(t){for(var e=0,i=t.length-1,o=void 0,s=void 0,a=void 0,h=n(e,i);;){if(i<=e)return t[h];if(i==e+1)return t[e]>t[i]&&r(t,e,i),t[h];for(t[o=n(e,i)]>t[i]&&r(t,o,i),t[e]>t[i]&&r(t,e,i),t[o]>t[e]&&r(t,o,e),r(t,o,e+1),s=e+1,a=i;;){do{s++}while(t[e]>t[s]);do{a--}while(t[a]>t[e]);if(a=h&&(i=a-1)}}var r=function(t,e,r){var n;return n=[t[r],t[e]],t[e]=n[0],t[r]=n[1],n},n=function(t,e){return~~((t+e)/2)};t.exports?t.exports=e:window.median=e}()},function(t,e,r){"use strict";const n=r(8),i=r(142),o=e;o.PCA=r(43),o.HClust=r(44),o.KMeans=r(141),o.SVM=r(53),o.NaiveBayes=r(144),o.KNN=r(145),o.PLS=r(143),o.CrossValidation=r(64),o.ConfusionMatrix=r(24),o.DecisionTreeClassifier=n.DecisionTreeClassifier,o.RandomForestClassifier=i.RandomForestClassifier,o.FNN=r(66),o.SOM=r(68);const s=r(40);o.SimpleLinearRegression=s.SimpleLinearRegression,o.PolynomialRegression=s.PolynomialRegression,o.MultivariateLinearRegression=s.MultivariateLinearRegression,o.PowerRegression=s.PowerRegression,o.ExponentialRegression=s.ExponentialRegression,o.TheilSenRegression=s.TheilSenRegression,o.RobustPolynomialRegression=s.RobustPolynomialRegression,o.DecisionTreeRegression=n.DecisionTreeRegression,o.RandomForestRegression=i.RandomForestRegression,o.levenbergMarquardt=r(70);const a=r(0);o.Matrix=a.Matrix,o.SVD=a.SVD,o.EVD=a.EVD,o.CholeskyDecomposition=a.CholeskyDecomposition,o.LuDecomposition=a.LuDecomposition,o.QrDecomposition=a.QrDecomposition,o.SparseMatrix=r(71),o.Kernel=r(10),o.Distance=r(29).distance,o.Similarity=r(29).similarity,o.distanceMatrix=r(23),o.XSadd=r(19).default,o.Performance=r(120),o.savitzkyGolay=r(122),o.savitzkyGolayGeneralized=r(123),o.BitArray=r(124),o.HashTable=r(14),o.padArray=r(39),o.binarySearch=r(6),o.numSort=r(7),o.Random=r(11).default,o.ArrayUtils=r(126),o.Regression=r(40),o.MatrixUtil=r(0),o.ArrayStat=r(3).array,o.MatrixStat=r(3).matrix,o.Array={min:r(17).default,max:r(9).default,median:r(18).default,mean:r(5).default,mode:r(130).default,normed:r(131).default,rescale:r(13).default,sequentialFill:r(132).default,standardDeviation:r(133).default,variance:r(20).default},o.ArrayXY={centroidsMerge:r(134).default,closestX:r(135).default,maxMerge:r(136).default,maxY:r(137).default,sortX:r(138).default,uniqueX:r(139).default,weightedMerge:r(140).default}},function(t,e,r){"use strict";const n=r(0),i=n.Matrix,o=n.EVD,s=n.SVD,a=r(4),h=a.mean,u=a.standardDeviation,l={isCovarianceMatrix:!1,center:!0,scale:!1};class c{constructor(t,e){if(!0===t){const t=e;return this.center=t.center,this.scale=t.scale,this.means=t.means,this.stdevs=t.stdevs,this.U=i.checkMatrix(t.U),void(this.S=t.S)}if(e=Object.assign({},l,e),this.center=!1,this.scale=!1,this.means=null,this.stdevs=null,e.isCovarianceMatrix)this._computeFromCovarianceMatrix(t);else if("boolean"==typeof e.useCovarianceMatrix?e.useCovarianceMatrix:t.length>t[0].length){const r=(t=this._adjust(t,e)).transposeView().mmul(t).div(t.rows-1);this._computeFromCovarianceMatrix(r)}else{t=this._adjust(t,e);var r=new s(t,{computeLeftSingularVectors:!1,computeRightSingularVectors:!0,autoTranspose:!0});this.U=r.rightSingularVectors;const i=r.diagonal,o=new Array(i.length);for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:{}).nComponents,r=void 0===e?this.U.columns:e;t=new i(t),this.center&&(t.subRowVector(this.means),this.scale&&t.divRowVector(this.stdevs));var n=t.mmul(this.U);return n.subMatrix(0,n.rows-1,0,r-1)}getExplainedVariance(){for(var t=0,e=0;ee/t)}getCumulativeVariance(){for(var t=this.getExplainedVariance(),e=1;eMath.sqrt(t))}getLoadings(){return this.U.transpose()}toJSON(){return{name:"PCA",center:this.center,scale:this.scale,means:this.means,stdevs:this.stdevs,U:this.U,S:this.S}}_adjust(t,e){if(this.center=!!e.center,this.scale=!!e.scale,t=new i(t),this.center){const e=h(t),n=this.scale?u(t,e,!0):null;if(this.means=e,t.subRowVector(e),this.scale){for(var r=0;r1;){p={},m=1e6;for(var w=0;w0;){A=E.shift();for(var O=0;O0){var C=E[O].filter(function(t){return-1===A.indexOf(t)});A=A.concat(C),E.splice(O--,1)}R[k++]=A}R.length=k;for(var T=0;Te?1:0},g=function(t,e,r,n,i){var o;if(null==r&&(r=0),null==i&&(i=s),r<0)throw new Error("lo must be non-negative");for(null==n&&(n=t.length);rr;0<=r?e++:e--)u.push(e);return u}.apply(this).reverse()).length;nm;0<=m?++l:--l)p.push(u(t,r));return p},w=function(t,e,r,n){var i,o,a;for(null==n&&(n=s),i=t[r];r>e&&n(i,o=t[a=r-1>>1])<0;)t[r]=o,r=a;return t[r]=i},y=function(t,e,r){var n,i,o,a,h;for(null==r&&(r=s),i=t.length,h=e,o=t[e],n=2*e+1;n=o)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}}),h=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),d(r)?n.showHidden=r:r&&e._extend(n,r),w(n.showHidden)&&(n.showHidden=!1),w(n.depth)&&(n.depth=2),w(n.colors)&&(n.colors=!1),w(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=h),l(n,t,n.depth)}function h(t,e){var r=a.styles[e];return r?"["+a.colors[r][0]+"m"+t+"["+a.colors[r][1]+"m":t}function u(t,e){return t}function l(t,r,n){if(t.customInspect&&r&&S(r.inspect)&&r.inspect!==e.inspect&&(!r.constructor||r.constructor.prototype!==r)){var i=r.inspect(n,t);return v(i)||(i=l(t,i,n)),i}var o=function(t,e){if(w(e))return t.stylize("undefined","undefined");if(v(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(p(e))return t.stylize(""+e,"number");if(d(e))return t.stylize(""+e,"boolean");if(m(e))return t.stylize("null","null")}(t,r);if(o)return o;var s=Object.keys(r),a=function(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}(s);if(t.showHidden&&(s=Object.getOwnPropertyNames(r)),M(r)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return c(r);if(0===s.length){if(S(r)){var h=r.name?": "+r.name:"";return t.stylize("[Function"+h+"]","special")}if(y(r))return t.stylize(RegExp.prototype.toString.call(r),"regexp");if(b(r))return t.stylize(Date.prototype.toString.call(r),"date");if(M(r))return c(r)}var u,x="",A=!1,E=["{","}"];(g(r)&&(A=!0,E=["[","]"]),S(r))&&(x=" [Function"+(r.name?": "+r.name:"")+"]");return y(r)&&(x=" "+RegExp.prototype.toString.call(r)),b(r)&&(x=" "+Date.prototype.toUTCString.call(r)),M(r)&&(x=" "+c(r)),0!==s.length||A&&0!=r.length?n<0?y(r)?t.stylize(RegExp.prototype.toString.call(r),"regexp"):t.stylize("[Object]","special"):(t.seen.push(r),u=A?function(t,e,r,n,i){for(var o=[],s=0,a=e.length;s=0&&0,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(u,x,E)):E[0]+x+E[1]}function c(t){return"["+Error.prototype.toString.call(t)+"]"}function f(t,e,r,n,i,o){var s,a,h;if((h=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?a=h.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):h.set&&(a=t.stylize("[Setter]","special")),k(n,i)||(s="["+i+"]"),a||(t.seen.indexOf(h.value)<0?(a=m(r)?l(t,h.value,null):l(t,h.value,r-1)).indexOf("\n")>-1&&(a=o?a.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+a.split("\n").map(function(t){return" "+t}).join("\n")):a=t.stylize("[Circular]","special")),w(s)){if(o&&i.match(/^\d+$/))return a;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+a}function g(t){return Array.isArray(t)}function d(t){return"boolean"==typeof t}function m(t){return null===t}function p(t){return"number"==typeof t}function v(t){return"string"==typeof t}function w(t){return void 0===t}function y(t){return x(t)&&"[object RegExp]"===A(t)}function x(t){return"object"==typeof t&&null!==t}function b(t){return x(t)&&"[object Date]"===A(t)}function M(t){return x(t)&&("[object Error]"===A(t)||t instanceof Error)}function S(t){return"function"==typeof t}function A(t){return Object.prototype.toString.call(t)}function E(t){return t<10?"0"+t.toString(10):t.toString(10)}e.debuglog=function(r){if(w(o)&&(o=t.env.NODE_DEBUG||""),r=r.toUpperCase(),!s[r])if(new RegExp("\\b"+r+"\\b","i").test(o)){var n=t.pid;s[r]=function(){var t=e.format.apply(e,arguments);console.error("%s %d: %s",r,n,t)}}else s[r]=function(){};return s[r]},e.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},e.isArray=g,e.isBoolean=d,e.isNull=m,e.isNullOrUndefined=function(t){return null==t},e.isNumber=p,e.isString=v,e.isSymbol=function(t){return"symbol"==typeof t},e.isUndefined=w,e.isRegExp=y,e.isObject=x,e.isDate=b,e.isError=M,e.isFunction=S,e.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},e.isBuffer=r(50);var R=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function k(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.log=function(){var t,r;console.log("%s - %s",(t=new Date,r=[E(t.getHours()),E(t.getMinutes()),E(t.getSeconds())].join(":"),[t.getDate(),R[t.getMonth()],r].join(" ")),e.format.apply(e,arguments))},e.inherits=r(51),e._extend=function(t,e){if(!e||!x(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t};var O="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function C(t,e){if(!t){var r=new Error("Promise was rejected with a falsy value");r.reason=t,t=r}return e(t)}e.promisify=function(t){if("function"!=typeof t)throw new TypeError('The "original" argument must be of type Function');if(O&&t[O]){var e;if("function"!=typeof(e=t[O]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(e,O,{value:e,enumerable:!1,writable:!1,configurable:!0}),e}function e(){for(var e,r,n=new Promise(function(t,n){e=t,r=n}),i=[],o=0;o1)for(var r=1;rn.d&&(n.d=s-a,n.p=l)}return n}var f={dist:n,kind:"single"};function g(t,e,r){for(var n=0,i=0,o=0;o0;){n=0,d=0;for(var x=0;xn&&(n=r,d=x)}if(n=0,2===y[d].index.length)y[d].children=[y[d].index[0],y[d].index[1]],y[d].distance=e.dist(t[y[d].index[0].index],t[y[d].index[1].index]);else if(3===y[d].index.length){y[d].children=[y[d].index[0],y[d].index[1],y[d].index[2]];var S=[e.dist(t[y[d].index[0].index],t[y[d].index[1].index]),e.dist(t[y[d].index[1].index],t[y[d].index[2].index])];y[d].distance=(S[0]+S[1])/2}else{for(var A=new o,E=new o,R=[new Array(y[d].index.length),[]],k=0;kn&&(n=m,p=O)}for(R[1]=[p],R[0].splice(p,1),m=c(R,t,e.dist);m.d>0;)R[1].push(R[0][m.p]),R[0].splice(m.p,1),m=c(R,t,e.dist);var T=new Array(R[0].length);A.index=new Array(R[0].length);for(var P=0;Pthis.options.tol&&h[r]>0){for(n=r;n===r;)n=Math.floor(this.options.random()*a);if(m=this._marginOnePrecomputed(n,s)-e[n],p=h[r],v=h[n],e[r]===e[n]?(w=Math.max(0,p+v-this.options.C),y=Math.min(this.options.C,p+v)):(w=Math.max(0,v-p),y=Math.min(this.options.C,this.options.C+v+p)),Math.abs(w-y)<1e-4)continue;if((x=2*s[r][n]-s[r][r]-s[n][n])>=0)continue;var M=h[n]-e[n]*(d-m)/x;if(M>y?M=y:M0&&(this.b=l),h[n]0&&(this.b=c),b+=1}f++,0===b?g+=1:g=0}if(f===this.options.maxIterations)throw new Error("max iterations reached");if(this.iterations=f,"linear"===this.options.kernel){this.W=new Array(this.D);for(var S=0;Sthis.options.alphaTol&&(E.push(this.X[r]),R.push(e[r]),k.push(this.alphas[r]),this._supportVectorIdx.push(r));this.X=E,this.Y=R,this.N=E.length,this.alphas=k,this._trained=!0},s.prototype.predictOne=function(t){return this.marginOne(t)>0?1:-1},s.prototype.predict=function(t){if(!this._trained&&!this._loaded)throw new Error("Cannot predict, you need to train the SVM first");return Array.isArray(t)&&Array.isArray(t[0])?t.map(this.predictOne.bind(this)):this.predictOne(t)},s.prototype.marginOne=function(t,e){this.options.whitening&&!e&&(t=this._applyWhitening(t));var r,n=this.b;if("linear"===this.options.kernel&&this.W)for(r=0;rnew Array(e).fill(0))}function h(t){var e=new Set;for(let r=0;r=0;t--)w.splice(n[t],1);f?l(e,r,n,w,d,g,f):u(t,e,r,i,n,w,d,g)}return new n(d,g)},i.kFold=function(t,e,r,i,o){if("function"==typeof i){var c=i;o=r,r=e,e=t}s(e,r);const f=h(r),g=a(f.length,f.length);for(var d=e.length,m=new Array(d),p=0;p=0;--o){var s=this.tryEntries[o],a=s.completion;if("root"===s.tryLoc)return n("end");if(s.tryLoc<=this.prev){var h=i.call(s,"catchLoc"),u=i.call(s,"finallyLoc");if(h&&u){if(this.prev=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&i.call(n,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),O(r),d}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;O(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:T(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=r),d}}}function y(t,e,r,n){var i=e&&e.prototype instanceof b?e:b,o=Object.create(i.prototype),s=new C(n||[]);return o._invoke=function(t,e,r){var n=l;return function(i,o){if(n===f)throw new Error("Generator is already running");if(n===g){if("throw"===i)throw o;return P()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var a=R(s,r);if(a){if(a===d)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===l)throw n=g,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=f;var h=x(t,e,r);if("normal"===h.type){if(n=r.done?g:c,h.arg===d)continue;return{value:h.arg,done:r.done}}"throw"===h.type&&(n=g,r.method="throw",r.arg=h.arg)}}}(t,r,s),o}function x(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}function b(){}function M(){}function S(){}function A(t){["next","throw","return"].forEach(function(e){t[e]=function(t){return this._invoke(e,t)}})}function E(t){var e;this._invoke=function(r,n){function o(){return new Promise(function(e,o){!function e(r,n,o,s){var a=x(t[r],t,n);if("throw"!==a.type){var h=a.arg,u=h.value;return u&&"object"==typeof u&&i.call(u,"__await")?Promise.resolve(u.__await).then(function(t){e("next",t,o,s)},function(t){e("throw",t,o,s)}):Promise.resolve(u).then(function(t){h.value=t,o(h)},s)}s(a.arg)}(r,n,e,o)})}return e=e?e.then(o,o):o()}}function R(t,e){var n=t.iterator[e.method];if(n===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=r,R(t,e),"throw"===e.method))return d;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return d}var i=x(n,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,d;var o=i.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=r),e.delegate=null,d):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,d)}function k(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function O(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function C(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(k,this),this.reset(!0)}function T(t){if(t){var e=t[s];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,o=function e(){for(;++n=0,i=n&&r.regeneratorRuntime;r.regeneratorRuntime=void 0;var o=e;if(n)r.regeneratorRuntime=i;else try{delete r.regeneratorRuntime}catch(t){r.regeneratorRuntime=void 0}var s=o,a={mode:"index"};t.exports=s.mark(function t(e,r,n){var i,o,h,u,l,c,f,g,d;return s.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:for(d=function(){var t,e,r;for(e=1;u[e]<=0;)e++;if(0===u[e-1]){for(t=e-1;1!==t;t--)u[t]=-1;u[e]=0,l=f=0,u[1]=1,c=e-1}else{e>1&&(u[e-1]=0);do{e++}while(u[e]>0);for(r=e-1,t=e;0===u[t];)u[t++]=-1;if(-1===u[t])u[t]=u[r],f=u[r]-1,l=t-1,c=r-1,u[r]=-1;else{if(t===u[0])return 0;u[e]=u[t],f=u[t]-1,u[t]=0,l=e-1,c=t-1}}return 1},n=Object.assign({},a,n),i=new Array(r),o=new Array(e),h=new Array(r),u=new Array(r+2),g=0;g=0;--n){var o=n>0?this.model[n-1].a:t;i=this.model[n].backpropagation(i,o)}for(n=0;n0&&e>0))throw new Error("x and y must be positive");this.times={findBMU:0,adjust:0},this.randomizer=this.options.randomizer,this.iterationCount=0,this.iterations=this.options.iterations,this.startLearningRate=this.learningRate=this.options.learningRate,this.mapRadius=Math.floor(Math.max(t,e)/2),this.algorithmMethod=this.options.method,this._initNodes(),this.done=!1}else this.done=!0}function getConverters(t){for(var e=t.length,r=new Array(e),n=new Array(e),i=0;i0?("random"===this.algorithmMethod?(t=this.mapRadius*Math.exp(-this.iterationCount/this.timeConstant),e=getRandomValue(this.trainingSet,this.randomizer),this._adjust(e,t),this.learningRate=this.startLearningRate*Math.exp(-this.iterationCount/this.numIterations)):(r=-Math.floor(this.iterationCount/this.trainingSet.length),t=this.mapRadius*Math.exp(r/this.timeConstant),e=this.trainingSet[this.iterationCount%this.trainingSet.length],this._adjust(e,t),(this.iterationCount+1)%this.trainingSet.length==0&&(this.learningRate=this.startLearningRate*Math.exp(r/Math.floor(this.numIterations/this.trainingSet.length)))),this.iterationCount++,!0):(this.done=!0,!1));var t,e,r},SOM.prototype._adjust=function(t,e){var r,n,i,o,s=Date.now(),a=this._findBestMatchingUnit(t),h=Date.now();this.times.findBMU+=h-s;var u=Math.floor(e),l=a.x-u,c=a.x+u,f=a.y-u,g=a.y+u;for(r=l;r<=c;r++){var d=r;for(r<0?d+=this.x:r>=this.x&&(d-=this.x),n=f;n<=g;n++){var m=n;n<0?m+=this.y:n>=this.y&&(m-=this.y),(i=a[this.distanceMethod](this.nodes[d][m]))2&&void 0!==arguments[2]?arguments[2]:{},n=r.maxIterations,s=void 0===n?100:n,a=r.gradientDifference,h=void 0===a?.1:a,u=r.damping,l=void 0===u?0:u,c=r.errorTolerance,f=void 0===c?.01:c,g=r.initialValues;if(l<=0)throw new Error("The damping option must be a positive number");if(!t.x||!t.y)throw new Error("The data parameter must have x and y elements");if(!Array.isArray(t.x)||t.x.length<2||!Array.isArray(t.y)||t.y.length<2)throw new Error("The data parameter elements must be an array with more than 2 points");if(t.x.length!==t.y.length)throw new Error("The data parameter elements must have the same size");var d=g||new Array(e.length).fill(1);if(!Array.isArray(d))throw new Error("initialValues must be an array");for(var m=i(t,d,e),p=m<=f,v=0;v2&&void 0!==arguments[2]?arguments[2]:{};if(t instanceof SparseMatrix){const e=t;this._init(e.rows,e.columns,e.elements.clone(),e.threshold)}else if(Array.isArray(t)){const s=t;t=s.length,r=e||{},e=s[0].length,this._init(t,e,new ml_hash_table__WEBPACK_IMPORTED_MODULE_0___default.a(r),r.threshold);for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:1,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t;const r=Math.min(t,e),n=new SparseMatrix(t,e,{initialCapacity:r});for(var i=0;ithis.get(r,e)!==n?(t=!1,!1):n),t}bandWidth(){let t=this.columns,e=-1;return this.forEachNonZero((r,n,i)=>{let o=r-n;return t=Math.min(t,o),e=Math.max(e,o),i}),e-t}isBanded(t){return this.bandWidth()<=t}get cardinality(){return this.elements.size}get size(){return this.rows*this.columns}get(t,e){return this.elements.get(t*this.columns+e)}set(t,e,r){return this.threshold&&Math.abs(r)(t.forEachNonZero((t,o,s)=>(r===t&&n.set(e,o,n.get(e,o)+i*s),s)),i)),n}kroneckerProduct(t){const e=this.rows,r=this.columns,n=t.rows,i=t.columns,o=new SparseMatrix(e*n,r*i,{initialCapacity:this.cardinality*t.cardinality});return this.forEachNonZero((e,r,s)=>(t.forEachNonZero((t,a,h)=>(o.set(n*e+t,i*r+a,s*h),h)),s)),o}forEachNonZero(t){return this.elements.forEachPair((e,r)=>{const n=e/this.columns|0,i=e%this.columns;let o=t(n,i,r);return!1!==o&&(this.threshold&&Math.abs(o)(e[i]=t,r[i]=o,n[i]=s,i++,s)),{rows:e,columns:r,values:n}}setThreshold(t){return 0!==t&&t!==this.threshold&&(this.threshold=t,this.forEachNonZero((t,e,r)=>r)),this}transpose(){let t=new SparseMatrix(this.columns,this.rows,{initialCapacity:this.cardinality});return this.forEachNonZero((e,r,n)=>(t.set(r,e,n),n)),t}}SparseMatrix.prototype.klass="Matrix",SparseMatrix.identity=SparseMatrix.eye,SparseMatrix.prototype.tensorProduct=SparseMatrix.prototype.kroneckerProduct;var inplaceOperator="\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n",inplaceOperatorScalar="\n(function %name%S(value) {\n this.forEachNonZero((i, j, v) => v %op% value);\n return this;\n})\n",inplaceOperatorMatrix="\n(function %name%M(matrix) {\n matrix.forEachNonZero((i, j, v) => {\n this.set(i, j, this.get(i, j) %op% v);\n return v;\n });\n return this;\n})\n",staticOperator="\n(function %name%(matrix, value) {\n var newMatrix = new SparseMatrix(matrix);\n return newMatrix.%name%(value);\n})\n",inplaceMethod="\n(function %name%() {\n this.forEachNonZero((i, j, v) => %method%(v));\n return this;\n})\n",staticMethod="\n(function %name%(matrix) {\n var newMatrix = new SparseMatrix(matrix);\n return newMatrix.%name%();\n})\n";const operators=[["+","add"],["-","sub","subtract"],["*","mul","multiply"],["/","div","divide"],["%","mod","modulus"],["&","and"],["|","or"],["^","xor"],["<<","leftShift"],[">>","signPropagatingRightShift"],[">>>","rightShift","zeroFillRightShift"]];for(const operator of operators)for(let i=1;ir&&(a+=e[h]);if(!(ar&&(u+=t[l]*e[l]);if(!((u/=a)-r<1e-5||i-u<1e-5))return u-rt.pred-e.pred):s.sort((t,e)=>e.pred-t.pred);const u=this.cutoffs=[o?Number.MIN_VALUE:Number.MAX_VALUE],l=this.fp=[0],c=this.tp=[0];var f=0,g=0,d=s[0].pred,m=0,p=0;for(a=0;a{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.slice();return e[0]=e[1],e})},function(t,e,r){"use strict";var n=r(0),i=n.Matrix,o=n.inverse,s=r(39),a=r(16),h={windowSize:5,derivative:1,polynomial:2,pad:"none",padValue:"replicate"};t.exports=function(t,e,r){if((r=a({},h,r)).windowSize%2==0||r.windowSize<5||!Number.isInteger(r.windowSize))throw new RangeError("Invalid window size (should be odd and at least 5 integer number)");if(r.derivative<0||!Number.isInteger(r.derivative))throw new RangeError("Derivative should be a positive integer");if(r.polynomial<1||!Number.isInteger(r.polynomial))throw new RangeError("Polynomial should be a positive integer");var n,u,l=Math.floor(r.windowSize/2);"pre"===r.pad&&(t=s(t,{size:l,value:r.padValue}));var c=new Array(t.length-2*l);if(5!==r.windowSize||2!==r.polynomial||1!==r.derivative&&2!==r.derivative){for(var f=i.ones(r.windowSize,r.polynomial+1),g=-(r.windowSize-1)/2,d=0;d=0&&s0?(4*r-2)/(r*(2*e-r+1))*(t*s(t,e,r-1,n)+n*s(t,e,r-1,n-1))-(r-1)*(2*e+r)/(r*(2*e-r+1))*s(t,e,r-2,n):0==r&&0==n?1:0}function a(t,e){var r=1;if(t>=e)for(var n=t-e+1;n<=t;n++)r*=n;return r}function h(t,e,r,n,i){for(var o=0,h=0;h<=n;h++)o+=(2*h+1)*(a(2*r,h)/a(2*r+h+1,h+1))*s(t,r,h,0)*s(e,r,h,i);return o}t.exports=function(t,e,r){if((r=n({},i,r)).windowSize%2==0||r.windowSize<5||!Number.isInteger(r.windowSize))throw new RangeError("Invalid window size (should be odd and at least 5 integer number)");if(r.windowSize>t.length)throw new RangeError("Window size is higher than the data length "+r.windowSize+">"+t.length);if(r.derivative<0||!Number.isInteger(r.derivative))throw new RangeError("Derivative should be a positive integer");if(r.polynomial<1||!Number.isInteger(r.polynomial))throw new RangeError("Polynomial should be a positive integer");r.polynomial>=6&&console.warn("You should not use polynomial grade higher than 5 if you are not sure that your data arises from such a model. Possible polynomial oscillation problems");var s=r.windowSize,a=Math.floor(s/2),u=t.length,l=new Array(u),c=function(t,e,r){for(var n=new Array(t),i=Math.floor(t/2),o=-i;o<=i;o++){n[o+i]=new Array(t);for(var s=-i;s<=i;s++)n[o+i][s+i]=h(s,o,i,e,r)}return n}(s,r.polynomial,r.derivative),f=0,g=!0;"[object Array]"===Object.prototype.toString.call(e)?g=!1:f=Math.pow(e,r.derivative);for(var d=0;d>>0).toString(2);e+="00000000000000000000000000000000".substr(n.length)+n}return e}t.exports={count:function(t){for(var e=0,r=0;r>8&255]+n[t[r]>>16&255]+n[t[r]>>24&255];return e},and:function(t,e){for(var r=new Array(t.length),n=0;n>5]&r)},setBit:function(t,e,r){var n=e>>5,i=1<<31-e%32;return t[n]=r?i|t[n]:~i&t[n],t},toBinaryString:i,parseBinaryString:function(t){for(var e=t.length/32,r=new Array(e),n=0;n>>0).toString(16);e+="00000000".substr(n.length)+n}return e},parseHexString:function(t){for(var e=t.length/8,r=new Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:{};const i=r.min,o=r.max;var s=r.inPlace?e:new Array(e.length),a=n.minMax(e);if("number"==typeof o)if("number"==typeof i){let t=(o-i)/(a.max-a.min);for(let r=0;r2&&void 0!==arguments[2]?arguments[2]:{};var i=t.length;t.length>1&&t[0]>t[1]&&(t=t.slice().reverse(),e=e.slice().reverse());var o=r.from,s=void 0===o?t[0]:o,a=r.to,h=void 0===a?t[i-1]:a,u=r.variant,l=void 0===u?"smooth":u,c=r.numberOfPoints,f=void 0===c?100:c;if(i!==e.length)throw new RangeError("the x and y vector doesn't have the same size.");if("number"!=typeof s||isNaN(s))throw new RangeError("'from' option must be a number");if("number"!=typeof h||isNaN(h))throw new RangeError("'to' option must be a number");var g=s>h;if(g){var d=[h,s];s=d[0],h=d[1]}if("number"!=typeof f||isNaN(f))throw new RangeError("'numberOfPoints' option must be a number");if(f<1)throw new RangeError("the number of points must be at least 1");var m="slot"===l?function(t,e,r,n,i){var o=t.length,s=(n-r)/(i-1),a=s/2,h=t[t.length-1]-t[t.length-2],u=r-a,l=new Array(i),c=u,f=u+s,g=-Number.MAX_VALUE,d=0,m=t[0],p=e[0],v=0,w=!0,y=0,x=0,b=1,M=0;t:for(;;){if(g>=m)throw new Error("x must be an increasing serie");for(;g-f>0;){if(w&&(x++,w=!1),l[M]=x<=0?0:y/x,++M===i)break t;c=f,f+=s,y=0,x=0}g>c&&(y+=d,x++),(g===-Number.MAX_VALUE||v>1)&&x--,g=m,d=p,b=0;){var E=n(0,g-d,y,m);if(M=w+E,u[A++]=(M-b)/a,A===o)break t;f=g,g+=a,b=M}w+=n(d,p,y,x),d=p,m=v,Sr&&(r=n,e=t[s])}return e}},function(t,e,r){"use strict";r.r(e),e.default=function(t){var e=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).algorithm,r=void 0===e?"absolute":e;if(!Array.isArray(t))throw new Error("input must be an array");if(0===t.length)throw new Error("input must not be empty");switch(r.toLowerCase()){case"absolute":var n=function(t){for(var e=0,r=0;r0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("object"!==o(t)||i()(t)||(e=t,t=[]),!i()(t))throw new TypeError("input must be an array");var r=e,n=r.from,s=void 0===n?0:n,a=r.to,h=void 0===a?10:a,u=r.size,l=void 0===u?t.length:u,c=r.step;if(l&&c)throw new Error("step is defined by the array size");if(l||(l=c?Math.floor((h-s)/c)+1:h-s+1),!c&&l&&(c=(h-s)/(l-1)),Array.isArray(t)){t.length=0;for(var f=0;f1&&void 0!==arguments[1]?arguments[1]:{};return Math.sqrt(Object(n.default)(t,e))}},function(t,e,r){"use strict";function n(t,e){const r=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).window,n=void 0===r?.01:r;for(var i={x:e.slice(),y:new Array(e.length).fill(0)},o=0,s=0;o=0?{x:r[u],y:n[u]}:0!==(u=~u)&&Math.abs(r[u]-a)>.5||u===r.length?{x:r[u-1],y:n[u-1]}:{x:r[u],y:n[u]}}},function(t,e,r){"use strict";function n(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=t.x,n=t.y,i=e.groupWidth,o=void 0===i?.001:i;for(var s={x:[],y:[]},a={x:[],y:[]},h=0,u=0;uo?(a.x.push(r[u]),a.y.push(n[u]),s.x.push(r[u]),s.y.push(n[u]),u++,h++):(n[u]>a.y[h-1]&&(a.x[h-1]=r[u],a.y[h-1]=n[u]),s.x[h-1]=r[u],s.y[h-1]+=n[u],u++);return s.x=a.x.slice(),s}r.r(e),r.d(e,"default",function(){return n})},function(t,e,r){"use strict";r.r(e),r.d(e,"default",function(){return s});var n=r(6),i=r.n(n),o=r(7);function s(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=t.x,n=t.y;let i=e.from,o=void 0===i?{index:0}:i,s=e.to,h=void 0===s?{index:r.length}:s,u=e.reverse,l=void 0!==u&&u;void 0!==o.value&&void 0===o.index&&(o.index=a(o.value,r,l)),void 0!==h.value&&void 0===h.index&&(h.index=a(h.value,r,l));for(var c,f=Number.MIN_VALUE,g=o.index;g1&&void 0!==arguments[1]?arguments[1]:{};const r=t.x,n=t.y,i=e.reverse;var o;o=void 0!==i&&i?(t,e)=>e.x-t.x:(t,e)=>t.x-e.x;for(var s=r.map((t,e)=>({x:t,y:n[e]})).sort(o),a={x:r.slice(),y:n.slice()},h=0;h0&&void 0!==arguments[0]?arguments[0]:{};const e=t.x,r=t.y;if(e.length<2)return;if(e.length!==r.length)throw new Error("The X and Y arrays mush have the same length");let n=e[0],i=0;for(let t=1;t1&&void 0!==arguments[1]?arguments[1]:{};const r=t.x,n=t.y,i=e.groupWidth,o=void 0===i?.001:i;for(var s={x:[],y:[]},a={x:[],y:[]},h=0,u=0;uo?(a.x.push(r[u]*n[u]),a.y.push(n[u]),s.x.push(r[u]),s.y.push(n[u]),u++,h++):(a.x[h-1]+=r[u]*n[u],a.y[h-1]+=n[u],s.x[h-1]=r[u],s.y[h-1]+=n[u],u++);for(var l=0;l2&&void 0!==arguments[2]?arguments[2]:o;const n=r.distanceFunction||o.distanceFunction,i=r.similarityFunction||o.similarityFunction;let s=-1;if("function"==typeof i){let r=Number.MIN_VALUE;for(let n=0;nr&&(r=o,s=n)}}else{if("function"!=typeof n)throw new Error("A similarity or distance function it's required");{let r=Number.MAX_VALUE;for(let i=0;in)return!1;return!0}(s,t,i.distanceFunction,i.tolerance);return new d(r,s,h,o,i.distanceFunction)}function v(t,e,r){if(r=Object.assign({},m,r),e<=0||e>t.length||!Number.isInteger(e))throw new Error("K should be a positive integer smaller than the number of points");var i;if(Array.isArray(r.initialization)){if(r.initialization.length!==e)throw new Error("The initial centers should have the same length as K");i=r.initialization}else switch(r.initialization){case"kmeans++":i=function(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const i=(t=new u.Matrix(t)).length,o=new h.default(r.seed),s=[],a=r.localTrials||2+Math.floor(Math.log(e)),g=o.randInt(i);s.push(t[g].slice());let d=[t.map(t=>n(t,s[0]))],m=[f(d[0])];const p=1/m[0][i-1];let v=u.Matrix.mul(d,p);for(let r=1;r1){for(var s={dist:-1,index:-1},a=0;as.dist&&(s.dist=r[o[0]][a],s.index=a);if(o[1]=s.index,e>2)for(var u=2;ul.dist&&(l=Object.assign({},f))}o[u]=l.index}}return o.map(e=>t[e])}(t,e,function(t,e){for(var r=new Array(t.length),n=0;nr.load(t))}else this.replacement=t.replacement,this.maxFeatures=t.maxFeatures,this.nEstimators=t.nEstimators,this.treeOptions=t.treeOptions,this.isClassifier=t.isClassifier,this.seed=t.seed,this.useSampleBagging=t.useSampleBagging}train(t,e){if(t=i.Matrix.checkMatrix(t),this.maxFeatures=this.maxFeatures||t.columns,(r=this.maxFeatures)>0&&r<=1)this.n=Math.floor(t.columns*this.maxFeatures);else{if(!Number.isInteger(this.maxFeatures))throw new RangeError("Cannot process the maxFeatures parameter ".concat(this.maxFeatures));if(this.maxFeatures>t.columns)throw new RangeError("The maxFeatures parameter should be less than ".concat(t.columns));this.n=this.maxFeatures}var r;if(this.isClassifier)var o=n.DecisionTreeClassifier;else o=n.DecisionTreeRegression;this.estimators=new Array(this.nEstimators),this.indexes=new Array(this.nEstimators);for(var s=0;st.toJSON()),useSampleBagging:this.useSampleBagging}}}const l={maxFeatures:1,replacement:!0,nEstimators:10,seed:42,useSampleBagging:!1};class c extends u{constructor(t,e){!0===t?super(!0,e.baseModel):((t=Object.assign({},l,t)).isClassifier=!0,super(t))}selection(t){return(e=t).sort((t,r)=>e.filter(e=>e===t).length-e.filter(t=>t===r).length).pop();var e}toJSON(){return{baseModel:super.toJSON(),name:"RFClassifier"}}static load(t){if("RFClassifier"!==t.name)throw new RangeError("Invalid model: ".concat(t.name));return new c(!0,t)}}var f=r(5),g=r(18);const d={mean:f.default,median:g.default},m={maxFeatures:1,replacement:!1,nEstimators:10,treeOptions:{},selectionMethod:"mean",seed:42,useSampleBagging:!1};class p extends u{constructor(t,e){if(!0===t)super(!0,e.baseModel),this.selectionMethod=e.selectionMethod;else{if("mean"!==(t=Object.assign({},m,t)).selectionMethod&&"median"!==t.selectionMethod)throw new RangeError("Unsupported selection method ".concat(t.selectionMethod));t.isClassifier=!1,super(t),this.selectionMethod=t.selectionMethod}}selection(t){return d[this.selectionMethod](t)}toJSON(){return{baseModel:super.toJSON(),selectionMethod:this.selectionMethod,name:"RFRegression"}}static load(t){if("RFRegression"!==t.name)throw new RangeError("Invalid model: ".concat(t.name));return new p(!0,t)}}r.d(e,"RandomForestClassifier",function(){return c}),r.d(e,"RandomForestRegression",function(){return p})},function(t,e,r){"use strict";r.r(e);var n=r(0),i=r(4),o=r.n(i);function s(t){return Math.sqrt(t.clone().apply(a).sum())}function a(t,e){return this[t][e]=this[t][e]*this[t][e],this}function h(t,e){if(e)for(var r=0;rf&&xf;){var O=b.mmul(R);O.div(s(O)),k=E,E=t.mmul(O);var C=M.mmul(E);C.div(s(C)),R=e.mmul(C)}k=E;var T=b.mmul(k),P=k.transpose().mmul(k)[0][0],N=T.div(P),_=s(N);N.div(_),k.mul(_),O.mul(_),T=R.transpose().mmul(k),P=k.transpose().mmul(k)[0][0];var z=T.div(P)[0][0];t.sub(k.mmul(N.transpose())),e.sub(k.clone().mul(z).mmul(C.transpose())),d.setColumn(x,k),m.setColumn(x,N),p.setColumn(x,R),v.setColumn(x,C),y.setColumn(x,O),w[x][x]=z,x++}x--,d=d.subMatrix(0,d.rows-1,0,x),m=m.subMatrix(0,m.rows-1,0,x),p=p.subMatrix(0,p.rows-1,0,x),v=v.subMatrix(0,v.rows-1,0,x),y=y.subMatrix(0,y.rows-1,0,x),w=w.subMatrix(0,x,0,x),this.ssqYcal=c,this.E=t,this.F=e,this.T=d,this.P=m,this.U=p,this.Q=v,this.W=y,this.B=w,this.PBQ=m.mmul(w).mmul(v.transpose()),this.R2X=k.transpose().mmul(k).mmul(N.transpose().mmul(N)).div(u)[0][0]}predict(t){var e=n.default.checkMatrix(t);this.scale&&(e=e.subRowVector(this.meanX).divRowVector(this.stdDevX));var r=e.mmul(this.PBQ);return r=r.mulRowVector(this.stdDevY).addRowVector(this.meanY)}getExplainedVariance(){return this.R2X}toJSON(){return{name:"PLS",R2X:this.R2X,meanX:this.meanX,stdDevX:this.stdDevX,meanY:this.meanY,stdDevY:this.stdDevY,PBQ:this.PBQ,tolerance:this.tolerance,scale:this.scale}}static load(t){if("PLS"!==t.name)throw new RangeError("Invalid model: "+t.name);return new u(!0,t)}}function l(t){return t.sum("column").maxIndex()[0]}class c{constructor(t,e){if(!0===t)this.trainingSet=new n.Matrix(e.trainingSet),this.YLoadingMat=new n.Matrix(e.YLoadingMat),this.SigmaPow=new n.Matrix(e.SigmaPow),this.YScoreMat=new n.Matrix(e.YScoreMat),this.predScoreMat=h(e.predScoreMat,!1),this.YOrthLoadingVec=h(e.YOrthLoadingVec,!1),this.YOrthEigen=e.YOrthEigen,this.YOrthScoreMat=h(e.YOrthScoreMat,!1),this.toNorm=h(e.toNorm,!1),this.TURegressionCoeff=h(e.TURegressionCoeff,!1),this.kernelX=h(e.kernelX,!0),this.kernel=e.kernel,this.orthogonalComp=e.orthogonalComp,this.predictiveComp=e.predictiveComp;else{if(void 0===t.predictiveComponents)throw new RangeError("no predictive components found!");if(void 0===t.orthogonalComponents)throw new RangeError("no orthogonal components found!");if(void 0===t.kernel)throw new RangeError("no kernel found!");this.orthogonalComp=t.orthogonalComponents,this.predictiveComp=t.predictiveComponents,this.kernel=t.kernel}}train(t,e){t=n.Matrix.checkMatrix(t),e=n.Matrix.checkMatrix(e),this.trainingSet=t.clone();var r=this.kernel.compute(t),i=n.Matrix.eye(r.rows,r.rows,1),o=r;(r=new n.Matrix(this.orthogonalComp+1,this.orthogonalComp+1))[0][0]=o;var s=new n.SingularValueDecomposition(e.transpose().mmul(r[0][0]).mmul(e),{computeLeftSingularVectors:!0,computeRightSingularVectors:!1}),a=s.leftSingularVectors,h=s.diagonalMatrix;a=a.subMatrix(0,a.rows-1,0,this.predictiveComp-1),h=h.subMatrix(0,this.predictiveComp-1,0,this.predictiveComp-1);var u=e.mmul(a),l=new Array(this.orthogonalComp+1),c=new Array(this.orthogonalComp+1),f=new Array(this.orthogonalComp),g=new Array(this.orthogonalComp),d=new Array(this.orthogonalComp),m=new Array(this.orthogonalComp),p=n.Matrix.pow(h,-.5);p.apply(function(t,e){this[t][e]===1/0&&(this[t][e]=0)});for(var v=0;vn&&(n=s,i=o)}return i}function u(t,e,r,n){return t-=e,Math.log(r*Math.exp(t*t/n))}class l{constructor(t){t&&(this.conditionalProbability=n.default.checkMatrix(t.conditionalProbability),this.priorProbability=n.default.checkMatrix(t.priorProbability))}train(t,e){if((t=n.default.checkMatrix(t)).rows!==e.length)throw new RangeError("the size of the training set and the training labels must be the same.");var r=s(t,e);this.priorProbability=new n.default(r.length,1);for(var i=0;iMath.abs(h[i])&&(i=e);if(i!==r){for(n=0;n=0;i--){for(n=0;no?t[i][o]:i===o?1:0;return n}get upperTriangularMatrix(){for(var t=this.LU,e=t.rows,r=t.columns,n=new O(e,r),i=0;iMath.abs(e)?(r=e/t,Math.abs(t)*Math.sqrt(1+r*r)):0!==e?(r=t/e,Math.abs(e)*Math.sqrt(1+r*r)):0}function s(t,e,r){for(var n=new Array(t),i=0;i1&&void 0!==arguments[1]?arguments[1]:{};var r=(t=N.checkMatrix(t)).rows,n=t.columns;const{computeLeftSingularVectors:i=!0,computeRightSingularVectors:a=!0,autoTranspose:h=!1}=e;var u,l=Boolean(i),c=Boolean(a),f=!1;if(r=0;t--)if(0!==p[t]){for(let e=t+1;e=0;t--){if(t0;){let t,e;for(t=E-2;t>=-1&&-1!==t;t--){const e=Number.MIN_VALUE+k*Math.abs(p[t]+Math.abs(p[t+1]));if(Math.abs(y[t])<=e||Number.isNaN(y[t])){y[t]=0;break}}if(t===E-2)e=4;else{let r;for(r=E-1;r>=t&&r!==t;r--){let e=(r!==E?Math.abs(y[r]):0)+(r!==t+1?Math.abs(y[r-1]):0);if(Math.abs(p[r])<=k*e){p[r]=0;break}}r===t?e=3:r===E-1?e=1:(e=2,t=r)}switch(t++,e){case 1:{let e=y[E-2];y[E-2]=0;for(let r=E-2;r>=t;r--){let i=o(p[r],e),s=p[r]/i,a=e/i;if(p[r]=i,r!==t&&(e=-a*y[r-1],y[r-1]=s*y[r-1]),c)for(let t=0;t=p[t+1]);){let e=p[t];if(p[t]=p[t+1],p[t+1]=e,c&&te?i[o][r]=t[o][r]/this.s[r]:i[o][r]=0;var o=this.U,s=o.length,a=o[0].length,h=new O(r,s);for(let t=0;tt&&e++;return e}get diagonal(){return this.s}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return O.isMatrix(this.U)||(this.U=new O(this.U)),this.U}get rightSingularVectors(){return O.isMatrix(this.V)||(this.V=new O(this.V)),this.V}get diagonalMatrix(){return O.diag(this.s)}}function h(t,e,r){var n=r?t.rows:t.rows-1;if(e<0||e>n)throw new RangeError("Row index out of range")}function u(t,e,r){var n=r?t.columns:t.columns-1;if(e<0||e>n)throw new RangeError("Column index out of range")}function l(t,e){if(e.to1DArray&&(e=e.to1DArray()),e.length!==t.columns)throw new RangeError("vector size must be the same as the number of columns");return e}function c(t,e){if(e.to1DArray&&(e=e.to1DArray()),e.length!==t.rows)throw new RangeError("vector size must be the same as the number of rows");return e}function f(t,e,r){return{row:g(t,e),column:m(t,r)}}function g(t,e){if("object"!=typeof e)throw new TypeError("unexpected type for row indices");if(e.some(e=>e<0||e>=t.rows))throw new RangeError("row indices are out of range");return Array.isArray(e)||(e=Array.from(e)),e}function m(t,e){if("object"!=typeof e)throw new TypeError("unexpected type for column indices");if(e.some(e=>e<0||e>=t.columns))throw new RangeError("column indices are out of range");return Array.isArray(e)||(e=Array.from(e)),e}function d(t,e,r,n,i){if(5!==arguments.length)throw new RangeError("expected 4 arguments");if(p("startRow",e),p("endRow",r),p("startColumn",n),p("endColumn",i),e>r||n>i||e<0||e>=t.rows||r<0||r>=t.rows||n<0||n>=t.columns||i<0||i>=t.columns)throw new RangeError("Submatrix indices are out of range")}function p(t,e){if("number"!=typeof e)throw new TypeError("".concat(t," must be a number"))}class v extends(k()){constructor(t,e,r){super(),this.matrix=t,this.rows=e,this.columns=r}static get[Symbol.species](){return O}}class w extends v{constructor(t){super(t,t.columns,t.rows)}set(t,e,r){return this.matrix.set(e,t,r),this}get(t,e){return this.matrix.get(e,t)}}class y extends v{constructor(t,e){super(t,1,t.columns),this.row=e}set(t,e,r){return this.matrix.set(this.row,e,r),this}get(t,e){return this.matrix.get(this.row,e)}}class x extends v{constructor(t,e,r,n,i){d(t,e,r,n,i),super(t,r-e+1,i-n+1),this.startRow=e,this.startColumn=n}set(t,e,r){return this.matrix.set(this.startRow+t,this.startColumn+e,r),this}get(t,e){return this.matrix.get(this.startRow+t,this.startColumn+e)}}class b extends v{constructor(t,e,r){var n=f(t,e,r);super(t,n.row.length,n.column.length),this.rowIndices=n.row,this.columnIndices=n.column}set(t,e,r){return this.matrix.set(this.rowIndices[t],this.columnIndices[e],r),this}get(t,e){return this.matrix.get(this.rowIndices[t],this.columnIndices[e])}}class M extends v{constructor(t,e){super(t,(e=g(t,e)).length,t.columns),this.rowIndices=e}set(t,e,r){return this.matrix.set(this.rowIndices[t],e,r),this}get(t,e){return this.matrix.get(this.rowIndices[t],e)}}class S extends v{constructor(t,e){e=m(t,e),super(t,t.rows,e.length),this.columnIndices=e}set(t,e,r){return this.matrix.set(t,this.columnIndices[e],r),this}get(t,e){return this.matrix.get(t,this.columnIndices[e])}}class A extends v{constructor(t,e){super(t,t.rows,1),this.column=e}set(t,e,r){return this.matrix.set(t,this.column,r),this}get(t){return this.matrix.get(t,this.column)}}class E extends v{constructor(t){super(t,t.rows,t.columns)}set(t,e,r){return this.matrix.set(this.rows-t-1,e,r),this}get(t,e){return this.matrix.get(this.rows-t-1,e)}}class R extends v{constructor(t){super(t,t.rows,t.columns)}set(t,e,r){return this.matrix.set(t,this.columns-e-1,r),this}get(t,e){return this.matrix.get(t,this.columns-e-1)}}function k(t){void 0===t&&(t=Object);class e extends t{static get[Symbol.species](){return this}static from1DArray(t,e,r){if(t*e!==r.length)throw new RangeError("Data length does not match given dimensions");for(var n=new this(t,e),i=0;ir?(i=!0,r=e):(n=!1,i=!0);t++}return n}isReducedEchelonForm(){let t=0,e=0,r=-1,n=!0,i=!1;for(;tr?(i=!0,r=e):(n=!1,i=!0);for(let r=e+1;rt&&(t=this.get(e,r));return t}maxIndex(){for(var t=this.get(0,0),e=[0,0],r=0;rt&&(t=this.get(r,n),e[0]=r,e[1]=n);return e}min(){for(var t=this.get(0,0),e=0;ee&&(e=this.get(t,r));return e}maxRowIndex(t){h(this,t);for(var e=this.get(t,0),r=[t,0],n=1;ne&&(e=this.get(t,n),r[1]=n);return r}minRow(t){h(this,t);for(var e=this.get(t,0),r=1;re&&(e=this.get(r,t));return e}maxColumnIndex(t){u(this,t);for(var e=this.get(0,t),r=[0,t],n=1;ne&&(e=this.get(n,t),r[0]=n);return r}minColumn(t){u(this,t);for(var e=this.get(0,t),r=1;r0&&void 0!==arguments[0]?arguments[0]:"frobenius";var e=0;if("max"===t)return this.max();if("frobenius"===t){for(var r=0;r=(e=void 0===e?1:e))throw new RangeError("min should be strictly smaller than max");for(var r=this.constructor.empty(this.rows,this.columns),i=0;i=(e=void 0===e?1:e))throw new RangeError("min should be strictly smaller than max");for(var r=this.constructor.empty(this.rows,this.columns),i=0;ir||e<0||e>=this.columns||r<0||r>=this.columns)throw new RangeError("Argument out of range");for(var n=new this.constructor[Symbol.species](t.length,r-e+1),i=0;i=this.rows)throw new RangeError("Row index out of range: ".concat(t[i]));n.set(i,o-e,this.get(t[i],o))}return n}subMatrixColumn(t,e,r){if(void 0===e&&(e=0),void 0===r&&(r=this.rows-1),e>r||e<0||e>=this.rows||r<0||r>=this.rows)throw new RangeError("Argument out of range");for(var n=new this.constructor[Symbol.species](r-e+1,t.length),i=0;i=this.columns)throw new RangeError("Column index out of range: ".concat(t[i]));n.set(o-e,i,this.get(o,t[i]))}return n}setSubMatrix(t,e,r){d(this,e,e+(t=this.constructor.checkMatrix(t)).rows-1,r,r+t.columns-1);for(var n=0;nt?i[o]=1/i[o]:i[o]=0;return i=this.constructor[Symbol.species].diag(i),n.mmul(i.mmul(r.transposeView()))}clone(){for(var t=new this.constructor[Symbol.species](this.rows,this.columns),e=0;e>","signPropagatingRightShift"],[">>>","rightShift","zeroFillRightShift"]]){var p=g(U("\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n",{name:m[1],op:m[0]})),v=g(U("\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% value);\n }\n }\n return this;\n})\n",{name:"".concat(m[1],"S"),op:m[0]})),k=g(U("\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% matrix.get(i, j));\n }\n }\n return this;\n})\n",{name:"".concat(m[1],"M"),op:m[0]})),C=g(U("\n(function %name%(matrix, value) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(value);\n})\n",{name:m[1]}));for(o=1;o0){if(super(t),!(Number.isInteger(e)&&e>0))throw new TypeError("nColumns must be a positive integer");for(r=0;r1&&void 0!==arguments[1]?arguments[1]:{};const{rows:r=1}=e;if(t.length%r!=0)throw new Error("the data length is not divisible by the number of rows");super(),this.rows=r,this.columns=t.length/r,this.data=t}set(t,e,r){var n=this._calculateIndex(t,e);return this.data[n]=r,this}get(t,e){var r=this._calculateIndex(t,e);return this.data[r]}_calculateIndex(t,e){return t*this.columns+e}static get[Symbol.species](){return O}}class N extends(k()){constructor(t){super(),this.data=t,this.rows=t.length,this.columns=t[0].length}set(t,e,r){return this.data[t][e]=r,this}get(t,e){return this.data[t][e]}static get[Symbol.species](){return O}}function T(t,e){if(Array.isArray(t))return t[0]&&Array.isArray(t[0])?new N(t):new C(t,e);throw new Error("the argument is not an array")}class P{constructor(t){var e,r,n,i,s=(t=N.checkMatrix(t)).clone(),a=t.rows,h=t.columns,u=new Array(h);for(n=0;n=0;o--){for(i=0;i=0;r--){for(t=0;t1&&void 0!==arguments[1]&&arguments[1];return t=N.checkMatrix(t),e?new a(t).inverse():z(t,O.eye(t.rows))}function z(t,e){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=N.checkMatrix(t),e=N.checkMatrix(e),r?new a(t).solve(e):t.isSquare()?new i(t).solve(e):new P(t).solve(e)}var V=r(9);function D(t,e){for(var r=[],n=0;n3&&void 0!==arguments[3]?arguments[3]:1e-9;if(t>(arguments.length>4&&void 0!==arguments[4]?arguments[4]:1e-9))return new Array(e.rows+1).fill(0);for(var i=e.addRow(r,[0]),o=0;o1&&void 0!==arguments[1]?arguments[1]:{};const{thresholdValue:r=1e-9,thresholdError:n=1e-9}=e;for(var i=t.rows,o=new O(i,i),s=0;s1&&void 0!==arguments[1]?arguments[1]:{};const{assumeSymmetric:r=!1}=e;if(!(t=N.checkMatrix(t)).isSquare())throw new Error("Matrix is not a square matrix");var n,i,a=t.columns,h=s(a,a,0),u=new Array(a),l=new Array(a),c=t;if(!!r||t.isSymmetric()){for(n=0;n0;a--){for(c=0,s=0,u=0;u0&&(o=-o),e[a]=c*o,s-=i*o,r[a-1]=i-o,h=0;hl){0;do{for(1,i=r[l],f=(r[l+1]-i)/(2*e[l]),g=o(f,1),f<0&&(g=-g),r[l]=e[l]/(f+g),r[l+1]=e[l]*(f+g),m=r[l+1],s=i-r[l],a=l+2;a=l;a--)for(v=p,p=d,x=y,i=d*e[a],s=d*f,g=o(f,e[a]),e[a+1]=y*g,y=e[a]/g,f=(d=f/g)*r[a]-y*i,r[a+1]=s+y*(d*i+y*r[a]),u=0;uS*M)}r[l]=r[l]+b,e[l]=0}for(a=0;a=u;a--)r[a]=e[a][u-1]/l,s+=r[a]*r[a];for(o=Math.sqrt(s),r[u]>0&&(o=-o),s-=r[u]*o,r[u]=r[u]-o,h=u;h=u;a--)i+=r[a]*e[a][h];for(i/=s,a=u;a<=c;a++)e[a][h]-=i*r[a]}for(a=0;a<=c;a++){for(i=0,h=c;h>=u;h--)i+=r[h]*e[a][h];for(i/=s,h=u;h<=c;h++)e[a][h]-=i*r[h]}r[u]=l*r[u],e[u][u-1]=l*o}}for(a=0;a=1;u--)if(0!==e[u][u-1]){for(a=u+1;a<=c;a++)r[a]=e[a][u-1];for(h=u;h<=c;h++){for(o=0,a=u;a<=c;a++)o+=r[a]*n[a][h];for(o=o/r[u]/e[u][u-1],a=u;a<=c;a++)n[a][h]+=o*r[a]}}}(a,f,g,h),function(t,e,r,n,i){var o,s,a,h,u,l,c,f,g,m,d,p,v,w,y,x=t-1,b=t-1,M=Number.EPSILON,S=0,A=0,E=0,R=0,k=0,O=0,C=0,N=0;for(o=0;ob)&&(r[o]=i[o][o],e[o]=0),s=Math.max(o-1,0);s=0;){for(h=x;h>0&&(0===(O=Math.abs(i[h-1][h-1])+Math.abs(i[h][h]))&&(O=A),!(Math.abs(i[h][h-1])=0){for(C=E>=0?E+C:E-C,r[x-1]=f+C,r[x]=r[x-1],0!==C&&(r[x]=f-c/C),e[x-1]=0,e[x]=0,f=i[x][x-1],O=Math.abs(f)+Math.abs(C),E=f/O,R=C/O,k=Math.sqrt(E*E+R*R),E/=k,R/=k,s=x-1;s0){for(O=Math.sqrt(O),g=h&&(C=i[u][u],E=((k=f-C)*(O=g-C)-c)/i[u+1][u]+i[u][u+1],R=i[u+1][u+1]-C-k-O,k=i[u+2][u+1],O=Math.abs(E)+Math.abs(R)+Math.abs(k),E/=O,R/=O,k/=O,u!==h)&&!(Math.abs(i[u][u-1])*(Math.abs(R)+Math.abs(k))u+2&&(i[o][o-3]=0);for(a=u;a<=x-1&&(w=a!==x-1,a!==u&&(E=i[a][a-1],R=i[a+1][a-1],k=w?i[a+2][a-1]:0,0!==(f=Math.abs(E)+Math.abs(R)+Math.abs(k))&&(E/=f,R/=f,k/=f)),0!==f);a++)if(O=Math.sqrt(E*E+R*R+k*k),E<0&&(O=-O),0!==O){for(a!==u?i[a][a-1]=-O*f:h!==u&&(i[a][a-1]=-i[a][a-1]),f=(E+=O)/O,g=R/O,C=k/O,R/=E,k/=E,s=a;s=0;x--)if(E=r[x],0===(R=e[x]))for(h=x,i[x][x]=1,o=x-1;o>=0;o--){for(c=i[o][o]-E,k=0,s=h;s<=x;s++)k+=i[o][s]*i[s][x];if(e[o]<0)C=c,O=k;else if(h=o,0===e[o]?i[o][x]=0!==c?-k/c:-k/(M*A):(f=i[o][o+1],g=i[o+1][o],R=(r[o]-E)*(r[o]-E)+e[o]*e[o],l=(f*O-C*k)/R,i[o][x]=l,i[o+1][x]=Math.abs(f)>Math.abs(C)?(-k-c*l)/f:(-O-g*l)/C),l=Math.abs(i[o][x]),M*l*l>1)for(s=o;s<=x;s++)i[s][x]=i[s][x]/l}else if(R<0)for(h=x-1,Math.abs(i[x][x-1])>Math.abs(i[x-1][x])?(i[x-1][x-1]=R/i[x][x-1],i[x-1][x]=-(i[x][x]-E)/i[x][x-1]):(y=I(0,-i[x-1][x],i[x-1][x-1]-E,R),i[x-1][x-1]=y[0],i[x-1][x]=y[1]),i[x][x-1]=0,i[x][x]=1,o=x-2;o>=0;o--){for(m=0,d=0,s=h;s<=x;s++)m+=i[o][s]*i[s][x-1],d+=i[o][s]*i[s][x];if(c=i[o][o]-E,e[o]<0)C=c,k=m,O=d;else if(h=o,0===e[o]?(y=I(-m,-d,c,R),i[o][x-1]=y[0],i[o][x]=y[1]):(f=i[o][o+1],g=i[o+1][o],p=(r[o]-E)*(r[o]-E)+e[o]*e[o]-R*R,v=2*(r[o]-E)*R,0===p&&0===v&&(p=M*A*(Math.abs(c)+Math.abs(R)+Math.abs(f)+Math.abs(g)+Math.abs(C))),y=I(f*k-C*m+R*d,f*O-C*d-R*m,p,v),i[o][x-1]=y[0],i[o][x]=y[1],Math.abs(f)>Math.abs(C)+Math.abs(R)?(i[o+1][x-1]=(-m-c*i[o][x-1]+R*i[o][x])/f,i[o+1][x]=(-d-c*i[o][x]-R*i[o][x-1])/f):(y=I(-k-g*i[o][x-1],-O-g*i[o][x],C,R),i[o+1][x-1]=y[0],i[o+1][x]=y[1])),l=Math.max(Math.abs(i[o][x-1]),Math.abs(i[o][x])),M*l*l>1)for(s=o;s<=x;s++)i[s][x-1]=i[s][x-1]/l,i[s][x]=i[s][x]/l}for(o=0;ob)for(s=o;s=0;s--)for(o=0;o<=b;o++){for(C=0,a=0;a<=Math.min(s,b);a++)C+=n[o][a]*i[a][s];n[o][s]=C}}(a,l,u,h,f)}this.n=a,this.e=l,this.d=u,this.V=h}get realEigenvalues(){return this.d}get imaginaryEigenvalues(){return this.e}get eigenvectorMatrix(){return O.isMatrix(this.V)||(this.V=new O(this.V)),this.V}get diagonalMatrix(){var t,e,r=this.n,n=this.e,i=this.d,o=new O(r,r);for(t=0;t0?o[t][t+1]=n[t]:n[t]<0&&(o[t][t-1]=n[t])}return o}}function I(t,e,r,n){var i,o;return Math.abs(r)>Math.abs(n)?[(t+(i=n/r)*e)/(o=r+i*n),(e-i*t)/o]:[((i=r/n)*t+e)/(o=n+i*r),(i*e-t)/o]}class q{constructor(t){if(!(t=N.checkMatrix(t)).isSymmetric())throw new Error("Matrix is not symmetric");var e,r,n,i=t,o=i.rows,s=new O(o,o),a=!0;for(r=0;r0,s[r][r]=Math.sqrt(Math.max(u,0)),n=r+1;n=0;o--)for(i=0;ie&&(e=t[r][n]);return e},e.min=function(t){for(var e=1/0,r=0;rr&&(r=t[n][i]);return{min:e,max:r}},e.entropy=function(t,e){void 0===e&&(e=0);for(var r=0,n=t.length,i=t[0].length,o=0;o=0?s[l]++:(h[u]=t[r][e],s[u]=1,u++)}var c=0,f=0;for(r=0;rc&&(c=s[r],f=r);o[e]=h[f]}return o},e.skewness=function(t,r){void 0===r&&(r=!0);for(var n=e.mean(t),i=t.length,o=n.length,s=new Array(o),a=0;a=t.length)throw new RangeError("invalid lower bound");if(void 0===i)i=t.length-1;else if((i|=0)=t.length)throw new RangeError("invalid upper bound");for(;n<=i;)if((s=+r(t[o=n+(i-n>>1)],e,o,t))<0)n=o+1;else{if(!(s>0))return o;i=o-1}return~n}},function(t,e,r){"use strict";var n=r(74);function i(t){if("number"!=typeof t||n(t))throw new TypeError("Expected a number")}e.asc=function(t,e){return i(t),i(e),t-e},e.desc=function(t,e){return i(t),i(e),e-t}},function(t,e,r){"use strict";r.r(e);var n=r(0),i=r(5);function o(t,e){for(var r=new Array(e).fill(0),i=0;it>e:(t,e)=>t.01&&this.gain!==i&&a.lesserX.length>0&&a.greaterX.length>0){this.left=new c(this),this.right=new c(this);var h=new n.default(a.lesserX),u=new n.default(a.greaterX);this.left.train(h,a.lesserY,r+1,this.gain),this.right.train(u,a.greaterY,r+1,this.gain)}else this.calculatePrediction(e)}}classify(t){return this.right&&this.left?t[this.splitColumn]e&&(e=t[r]);return e}},function(t,e,r){"use strict";const n=r(0).Matrix,i=r(55),o=r(56),s=r(57),a=r(58),h=r(59),u=r(60),l=r(61),c=r(62),f=r(63),g=r(64),m={gaussian:i,rbf:i,polynomial:o,poly:o,anova:s,cauchy:a,exponential:h,histogram:u,min:u,laplacian:l,multiquadratic:c,rational:f,sigmoid:g,mlp:g};t.exports=class{constructor(t,e){if(this.kernelType=t,"linear"!==t)if("string"==typeof t){t=t.toLowerCase();var r=m[t];if(!r)throw new Error("unsupported kernel type: "+t);this.kernelFunction=new r(e)}else{if("object"!=typeof t||"function"!=typeof t.compute)throw new TypeError("first argument must be a valid kernel type or instance");this.kernelFunction=t}}compute(t,e){if(void 0===e&&(e=t),"linear"===this.kernelType)return new n(t).mmul(new n(e).transposeView());const r=new n(t.length,e.length);var i,o;if(t===e)for(i=0;ir[t];)t++;return t}return Math.floor(n*t)}var s=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Math.random;const{size:n=1,replace:s=!1,probabilities:a}=e;let h,u;if(h="number"==typeof t?function(t){const e=[];for(let r=0;ri)throw new Error("probabilities should sum to 1, but instead sums to ".concat(u[u.length-1]))}if(!1===s&&n>h.length)throw new Error("size option is too large");const l=[];for(let t=0;t0&&void 0!==arguments[0]?arguments[0]:Math.random;if("number"==typeof t){const e=new n.default(t);this.randomGenerator=e.random}else this.randomGenerator=t}choice(t,e){return s(t,e,this.randomGenerator)}random(){return this.randomGenerator()}randInt(t,e){return void 0===e&&(e=t,t=0),t+Math.floor(this.randomGenerator()*(e-t))}randomSample(t){const e=[];for(let r=0;r>>16&65535)*n+r*(e>>>16&65535)<<16>>>0)|0}:Math.imul,s="function"==typeof String.prototype.repeat&&"xxx"==="x".repeat(3)?function(t,e){return t.repeat(e)}:function(t,e){for(var r="";e>0;)1&e&&(r+=t),e>>=1,t+=t;return r};function a(t){if(!(this instanceof a))return new a(t);if(null==t)t=a.engines.nativeMath;else if("function"!=typeof t)throw new TypeError("Expected engine to be a function, got "+typeof t);this.engine=t}var h,u,l=a.prototype;function c(t){return function(){return t}}function f(t,e){return 0===e?t:function(r){return t(r)+e}}function g(t){var e=+t;return e<0?Math.ceil(e):Math.floor(e)}function m(t,e){return t<0?Math.max(t+e,0):Math.min(t,e)}function d(){}a.engines={nativeMath:function(){return 4294967296*Math.random()|0},mt19937:function(t){function e(t){for(var e=0,r=0;(0|e)<227;e=e+1|0)r=2147483648&t[e]|2147483647&t[e+1|0],t[e]=t[e+397|0]^r>>>1^(1&r?2567483615:0);for(;(0|e)<623;e=e+1|0)r=2147483648&t[e]|2147483647&t[e+1|0],t[e]=t[e-227|0]^r>>>1^(1&r?2567483615:0);r=2147483648&t[623]|2147483647&t[0],t[623]=t[396]^r>>>1^(1&r?2567483615:0)}return function(){var r=new t(624),n=0,i=0;function s(){(0|n)>=624&&(e(r),n=0);var t=r[n];return n=n+1|0,i+=1,0|function(t){return t^=t>>>11,t^=t<<7&2636928640,(t^=t<<15&4022730752)^t>>>18}(t)}return s.getUseCount=function(){return i},s.discard=function(t){for(i+=t,(0|n)>=624&&(e(r),n=0);t-n>624;)t-=624-n,e(r),n=0;return n=n+t|0,s},s.seed=function(t){var e=0;r[0]=e=0|t;for(var a=1;a<624;a=a+1|0)r[a]=e=o(e^e>>>30,1812433253)+a|0;return n=624,i=0,s},s.seedWithArray=function(t){return s.seed(19650218),function(t,e){for(var r=1,n=0,i=e.length,s=0|Math.max(i,624),a=0|t[0];(0|s)>0;--s)t[r]=a=(t[r]^o(a^a>>>30,1664525))+(0|e[n])+(0|n)|0,++n,(0|(r=r+1|0))>623&&(t[0]=t[623],r=1),n>=i&&(n=0);for(s=623;(0|s)>0;--s)t[r]=a=(t[r]^o(a^a>>>30,1566083941))-r|0,(0|(r=r+1|0))>623&&(t[0]=t[623],r=1);t[0]=2147483648}(r,t),s},s.autoSeed=function(){return s.seedWithArray(a.generateEntropyArray())},s}}("function"==typeof Int32Array?Int32Array:Array),browserCrypto:"undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&"function"==typeof Int32Array?(h=null,u=128,function(){return u>=128&&(null===h&&(h=new Int32Array(128)),crypto.getRandomValues(h),u=0),0|h[u++]}):null},a.generateEntropyArray=function(){for(var t=[],e=a.engines.nativeMath,r=0;r<16;++r)t[r]=0|e();return t.push(0|(new Date).getTime()),t},a.int32=function(t){return 0|t()},l.int32=function(){return a.int32(this.engine)},a.uint32=function(t){return t()>>>0},l.uint32=function(){return a.uint32(this.engine)},a.uint53=function(t){return 4294967296*(2097151&t())+(t()>>>0)},l.uint53=function(){return a.uint53(this.engine)},a.uint53Full=function(t){for(;;){var e=0|t();if(!(2097152&e))return 4294967296*(2097151&e)+(t()>>>0);if(2097152==(4194303&e)&&0==(0|t()))return 9007199254740992}},l.uint53Full=function(){return a.uint53Full(this.engine)},a.int53=function(t){var e=0|t();return 4294967296*(2097151&e)+(t()>>>0)+(2097152&e?-9007199254740992:0)},l.int53=function(){return a.int53(this.engine)},a.int53Full=function(t){for(;;){var e=0|t();if(!(4194304&e))return 4294967296*(2097151&e)+(t()>>>0)+(2097152&e?-9007199254740992:0);if(4194304==(8388607&e)&&0==(0|t()))return 9007199254740992}},l.int53Full=function(){return a.int53Full(this.engine)},a.integer=function(){function t(t){return 0==(t+1&t)}function e(e){return t(e)?(r=e,function(t){return t()&r}):function(t){var e=t+1,r=e*Math.floor(4294967296/e);return function(t){var n=0;do{n=t()>>>0}while(n>=r);return n%e}}(e);var r}function r(e){var r,n=e+1;if(0==(0|n)){var i=(n/4294967296|0)-1;if(t(i))return r=i,function(t){return 4294967296*(t()&r)+(t()>>>0)}}return function(t){var e=t*Math.floor(9007199254740992/t);return function(r){var n=0;do{n=4294967296*(2097151&r())+(r()>>>0)}while(n>=e);return n%t}}(n)}function n(t,e){return function(r){var n=0;do{var i=0|r();n=4294967296*(2097151&i)+(r()>>>0)+(2097152&i?-9007199254740992:0)}while(ne);return n}}return function(t,i){if(t=Math.floor(t),i=Math.floor(i),t<-9007199254740992||!isFinite(t))throw new RangeError("Expected min to be at least -9007199254740992");if(i>9007199254740992||!isFinite(i))throw new RangeError("Expected max to be at most 9007199254740992");var o=i-t;return o<=0||!isFinite(o)?c(t):4294967295===o?0===t?a.uint32:f(a.int32,t+2147483648):o<4294967295?f(e(o),t):9007199254740991===o?f(a.uint53,t):o<9007199254740991?f(r(o),t):i-1-t==9007199254740991?f(a.uint53Full,t):-9007199254740992===t&&9007199254740992===i?a.int53Full:-9007199254740992===t&&9007199254740991===i?a.int53:-9007199254740991===t&&9007199254740992===i?f(a.int53,1):9007199254740992===i?f(n(t-1,i-1),1):n(t,i)}}(),l.integer=function(t,e){return a.integer(t,e)(this.engine)},a.realZeroToOneInclusive=function(t){return a.uint53Full(t)/9007199254740992},l.realZeroToOneInclusive=function(){return a.realZeroToOneInclusive(this.engine)},a.realZeroToOneExclusive=function(t){return a.uint53(t)/9007199254740992},l.realZeroToOneExclusive=function(){return a.realZeroToOneExclusive(this.engine)},a.real=function(){return function(t,e,r){if(!isFinite(t))throw new RangeError("Expected left to be a finite number");if(!isFinite(e))throw new RangeError("Expected right to be a finite number");return f((n=r?a.realZeroToOneInclusive:a.realZeroToOneExclusive,1===(i=e-t)?n:0===i?function(){return 0}:function(t){return n(t)*i}),t);var n,i}}(),l.real=function(t,e,r){return a.real(t,e,r)(this.engine)},a.bool=function(){function t(t){return 1==(1&t())}function e(t,e){return function(r){return t(r)=1)return c(!0);var r=4294967296*t;return r%1==0?e(a.int32,r-2147483648|0):e(a.uint53,Math.round(9007199254740992*t))}(r):r<=0?c(!1):r>=n?c(!0):e(a.integer(0,n-1),r)}}(),l.bool=function(t,e){return a.bool(t,e)(this.engine)},a.pick=function(t,e,r,n){var i=e.length,o=null==r?0:m(g(r),i),s=void 0===n?i:m(g(n),i);if(!(o>=s))return e[a.integer(o,s-1)(t)]},l.pick=function(t,e,r){return a.pick(this.engine,t,e,r)};var p,v,w=Array.prototype.slice;a.picker=function(t,e,r){var n=w.call(t,e,r);if(!n.length)return d;var i=a.integer(0,n.length-1);return function(t){return n[i(t)]}},a.shuffle=function(t,e,r){var n=e.length;if(n){null==r&&(r=0);for(var i=n-1>>>0;i>r;--i){var o=a.integer(0,i)(t);if(i!==o){var s=e[i];e[i]=e[o],e[o]=s}}}return e},l.shuffle=function(t){return a.shuffle(this.engine,t)},a.sample=function(t,e,r){if(r<0||r>e.length||!isFinite(r))throw new RangeError("Expected sampleSize to be within 0 and the length of the population");if(0===r)return[];var n=w.call(e),i=n.length;if(i===r)return a.shuffle(t,n,0);var o=i-r;return a.shuffle(t,n,o-1).slice(o)},l.sample=function(t,e){return a.sample(this.engine,t,e)},a.die=function(t){return a.integer(1,t)},l.die=function(t){return a.die(t)(this.engine)},a.dice=function(t,e){var r=a.die(t);return function(t){var n=[];n.length=e;for(var i=0;i>>0,n=0|e(),i=0|e(),o=e()>>>0;return t(r.toString(16),8)+"-"+t((65535&n).toString(16),4)+"-"+t((n>>4&4095|16384).toString(16),4)+"-"+t((16383&i|32768).toString(16),4)+"-"+t((i>>4&65535).toString(16),4)+t(o.toString(16),8)}}(),l.uuid4=function(){return a.uuid4(this.engine)},a.string=function(t){null==t&&(t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-");var e=t.length;if(!e)throw new Error("Expected pool not to be an empty string");var r=a.integer(0,e-1);return function(e,n){for(var i="",o=0;o1&&void 0!==arguments[1]?arguments[1]:{};if(!s()(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");if(void 0!==r.output){if(!s()(r.output))throw new TypeError("output option must be an array if specified");e=r.output}else e=new Array(t.length);var o=Object(i.default)(t),a=Object(n.default)(t);if(o===a)throw new RangeError("minimum and maximum input values are equal. Cannot rescale a constant array");var h=r.min,u=void 0===h?r.autoMinMax?o:0:h,l=r.max,c=void 0===l?r.autoMinMax?a:1:l;if(u>=c)throw new RangeError("min option must be smaller than max option");for(var f=(c-u)/(a-o),g=0;g0&&void 0!==arguments[0]?arguments[0]:{};if(t instanceof g)return this.table=t.table.slice(),this.values=t.values.slice(),this.state=t.state.slice(),this.minLoadFactor=t.minLoadFactor,this.maxLoadFactor=t.maxLoadFactor,this.distinct=t.distinct,this.freeEntries=t.freeEntries,this.lowWaterMark=t.lowWaterMark,void(this.highWaterMark=t.maxLoadFactor);const e=void 0===t.initialCapacity?l:t.initialCapacity;if(e<0)throw new RangeError("initial capacity must not be less than zero: ".concat(e));const r=void 0===t.minLoadFactor?c:t.minLoadFactor,i=void 0===t.maxLoadFactor?f:t.maxLoadFactor;if(r<0||r>=1)throw new RangeError("invalid minLoadFactor: ".concat(r));if(i<=0||i>=1)throw new RangeError("invalid maxLoadFactor: ".concat(i));if(r>=i)throw new RangeError("minLoadFactor (".concat(r,") must be smaller than maxLoadFactor (").concat(i,")"));let a=e;0===(a=o(a=a/i|0))&&(a=1),this.table=n(a,0),this.values=n(a,0),this.state=n(a,0),this.minLoadFactor=r,this.maxLoadFactor=a===s?1:i,this.distinct=0,this.freeEntries=a,this.lowWaterMark=0,this.highWaterMark=m(a,this.maxLoadFactor)}clone(){return new g(this)}get size(){return this.distinct}get(t){const e=this.indexOfKey(t);return e<0?0:this.values[e]}set(t,e){let r=this.indexOfInsertion(t);if(r<0)return r=-r-1,this.values[r]=e,!1;if(this.distinct>this.highWaterMark){const r=d(this.distinct+1,this.minLoadFactor,this.maxLoadFactor);return this.rehash(r),this.set(t,e)}if(this.table[r]=t,this.values[r]=e,this.state[r]===a&&this.freeEntries--,this.state[r]=h,this.distinct++,this.freeEntries<1){const t=d(this.distinct+1,this.minLoadFactor,this.maxLoadFactor);this.rehash(t)}return!0}remove(t,e){const r=this.indexOfKey(t);return!(r<0)&&(this.state[r]=u,this.distinct--,e||this.maybeShrinkCapacity(),!0)}delete(t,e){const r=this.indexOfKey(t);return!(r<0)&&(this.state[r]=a,this.distinct--,e||this.maybeShrinkCapacity(),!0)}maybeShrinkCapacity(){if(this.distinct=0}indexOfKey(t){const e=this.table,r=this.state,n=this.table.length,i=2147483647&t;let o=i%n,s=i%(n-2);for(0===s&&(s=1);r[o]!==a&&(r[o]===u||e[o]!==t);)(o-=s)<0&&(o+=n);return r[o]===a?-1:o}containsValue(t){return this.indexOfValue(t)>=0}indexOfValue(t){const e=this.values,r=this.state;for(var n=0;n0;){var o=r.shift();t>=o.distance?n.push(o):r=r.concat(o.children)}return n},i.prototype.group=function(t){if(!Number.isInteger(t)||t<1)throw new RangeError("Number of groups must be a positive integer");const e=new n(function(t,e){return e.distance-t.distance});for(e.push(this);e.size()e.push(t))}var o=new i;return o.children=e.toArray(),o.distance=this.distance,o},i.prototype.traverse=function(t){!function t(e,r){if(r(e),e.children)for(var n=e.children.length-1;n>=0;n--)t(e.children[n],r)}(this,t)},t.exports=i},function(t,e,r){"use strict";var n=Object.prototype.hasOwnProperty,i=Object.prototype.toString,o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(t){return"function"==typeof Array.isArray?Array.isArray(t):"[object Array]"===i.call(t)},h=function(t){if(!t||"[object Object]"!==i.call(t))return!1;var e,r=n.call(t,"constructor"),o=t.constructor&&t.constructor.prototype&&n.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!r&&!o)return!1;for(e in t);return void 0===e||n.call(t,e)},u=function(t,e){o&&"__proto__"===e.name?o(t,e.name,{enumerable:!0,configurable:!0,value:e.newValue,writable:!0}):t[e.name]=e.newValue},l=function(t,e){if("__proto__"===e){if(!n.call(t,e))return;if(s)return s(t,e).value}return t[e]};t.exports=function t(){var e,r,n,i,o,s,c=arguments[0],f=1,g=arguments.length,m=!1;for("boolean"==typeof c&&(m=c,c=arguments[1]||{},f=2),(null==c||"object"!=typeof c&&"function"!=typeof c)&&(c={});f>>=0);return((t-r)*(e>>>=0)>>>0)+r*e>>>0}class u{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Date.now();this.state=new Uint32Array(4),this.init(t),this.random=this.getFloat.bind(this)}getUint32(){return this.nextState(),this.state[3]+this.state[2]>>>0}getFloat(){return(this.getUint32()>>>8)*i}init(t){if(!Number.isInteger(t))throw new TypeError("seed must be an integer");this.state[0]=t,this.state[1]=0,this.state[2]=0,this.state[3]=0;for(let t=1;t>>30>>>0)>>>0;this.periodCertification();for(let t=0;t>>s,t^=this.state[3]<0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("object"!==o(t)||i()(t)||(e=t,t=[]),!i()(t))throw new TypeError("input must be an array");var r=e,n=r.from,s=void 0===n?0:n,a=r.to,h=void 0===a?10:a,u=r.size,l=void 0===u?t.length:u,c=r.step;if(l&&c)throw new Error("step is defined by the array size");if(l||(l=c?Math.floor((h-s)/c)+1:h-s+1),!c&&l&&(c=(h-s)/(l-1)),Array.isArray(t)){t.length=0;for(var f=0;f1&&void 0!==arguments[1]?arguments[1]:{};if(!o()(t))throw new TypeError("input must be an array");for(var r=e.unbiased,i=void 0===r||r,s=e.mean,a=void 0===s?Object(n.default)(t):s,h=0,u=0;ue&&(e=t[n]);return e},e.min=function(t){for(var e=t[0],r=t.length,n=1;nr&&(r=t[i]);return{min:e,max:r}},e.arithmeticMean=function(t){for(var e=0,r=t.length,n=0;n=0?n[s]++:(i[o]=t[e],n[o]=1,o++)}var a=0,h=0;for(e=0;ea&&(a=n[e],h=e);return i[h]},e.covariance=function(t,r,n){void 0===n&&(n=!0);var i=e.mean(t),o=e.mean(r);if(t.length!==r.length)throw"Vectors do not have the same dimensions";for(var s=0,a=t.length,h=0;hArray.from({length:r}));for(let i=0;i2&&void 0!==arguments[2]?arguments[2]:{};if(e.length!==t.length)throw new Error("predicted and actual must have the same length");n=i.labels?new Set(i.labels):new Set([...t,...e]),n=Array.from(n),i.sort&&n.sort(i.sort);const o=Array.from({length:n.length});for(let t=0;t=0&&s>=0&&o[i][s]++}return new r(o,n)}getMatrix(){return this.matrix}getLabels(){return this.labels}getTotalCount(){let t=0;for(var e=0;e1?r=>e.activation(r,t.activationParam):e.activation,s=r>1?r=>e.derivate(r,t.activationParam):e.derivate;this.activationFunction=function(t,e){this[t][e]=i(this[t][e])},this.derivate=function(t,e){this[t][e]=s(this[t][e])},t.model?(this.W=n.checkMatrix(t.W),this.b=n.checkMatrix(t.b)):(this.W=n.rand(this.inputSize,this.outputSize),this.b=n.zeros(1,this.outputSize),this.W.apply(function(e,r){this[e][r]/=Math.sqrt(t.inputSize)}))}forward(t){var e=t.mmul(this.W).addRowVector(this.b);return e.apply(this.activationFunction),this.a=e.clone(),e}backpropagation(t,e){this.dW=e.transposeView().mmul(t),this.db=i.sumCol(t);var r=e.clone();return t.mmul(this.W.transposeView()).mul(r.apply(this.derivate))}update(){this.dW.add(this.W.clone().mul(this.regularization)),this.W.add(this.dW.mul(-this.epsilon)),this.b.add(this.db.mul(-this.epsilon))}toJSON(){return{model:"Layer",inputSize:this.inputSize,outputSize:this.outputSize,regularization:this.regularization,epsilon:this.epsilon,activation:this.activation,W:this.W,b:this.b}}static load(t){if("Layer"!==t.model)throw new RangeError("the current model is not a Layer model");return new s(t)}}t.exports=s},function(t,e,r){"use strict";var n=r(0).Matrix;t.exports={dictOutputs:function(t){for(var e={},r={},n=0,i=0;i1-t*t},identity:{activation:t=>t,derivate:()=>1},logistic:{activation:n,derivate:t=>n(t)*(1-n(t))},arctan:{activation:Math.atan,derivate:t=>1/(t*t+1)},softsign:{activation:t=>t/(1+Math.abs(t)),derivate:t=>1/((1+Math.abs(t))*(1+Math.abs(t)))},relu:{activation:t=>t<0?0:t,derivate:t=>t<0?0:1},softplus:{activation:t=>Math.log(1+Math.exp(t)),derivate:t=>1/(1+Math.exp(-t))},bent:{activation:t=>(Math.sqrt(t*t+1)-1)/2+t,derivate:t=>t/(2*Math.sqrt(t*t+1))+1},sinusoid:{activation:Math.sin,derivate:Math.cos},sinc:{activation:t=>0===t?1:Math.sin(t)/t,derivate:t=>0===t?0:Math.cos(t)/t-Math.sin(t)/(t*t)},gaussian:{activation:t=>Math.exp(-t*t),derivate:t=>-2*t*Math.exp(-t*t)},"parametric-relu":{activation:(t,e)=>t<0?e*t:t,derivate:(t,e)=>t<0?e:1},"exponential-elu":{activation:i,derivate:(t,e)=>t<0?i(t,e)+e:1},"soft-exponential":{activation:function(t,e){return e<0?-Math.log(1-e*(t+e))/e:e>0?(Math.exp(e*t)-1)/e+e:t},derivate:function(t,e){return e<0?1/(1-e*(e+t)):Math.exp(e*t)}}};t.exports=o},function(t,e){function r(t,e,r,n){this.x=t,this.y=e,this.weights=r,this.som=n,this.neighbors={}}r.prototype.adjustWeights=function(t,e,r){for(var n=0,i=this.weights.length;n0?e=this[t]-1:this.som.torus&&(e=this.som.gridDim[t]-1),void 0!==e)"x"===t?(r=e,n=this.y):(r=this.x,n=e),this.neighbors[t][0]=this.som.nodes[r][n];this[t]r||e.size[1]>r)throw new RangeError("expanded value should not be bigger than the data length");for(i=0;i0&&e!==this.coefficients.length-1?a=" + "+a:e!==this.coefficients.length-1&&(a=" "+a)),s=a+s;return"+"===s.charAt(0)&&(s=s.slice(1)),"f(x) = "+s}static load(t){if("polynomialRegression"!==t.name)throw new TypeError("not a polynomial regression model");return new h(!0,t)}}class u extends o{constructor(t,e){super(),!0===t?(this.A=e.A,this.B=e.B):(i(t,e),function(t,e,r){const n=e.length,i=new Array(n);for(let t=0;t=0?"f(x) = "+n(this.B,t)+"e^{"+n(this.A,t)+"x}":"f(x) = \\frac{"+n(this.B,t)+"}{e^{"+n(-this.A,t)+"x}}"}static load(t){if("exponentialRegression"!==t.name)throw new TypeError("not a exponential regression model");return new u(!0,t)}}class l extends o{constructor(t,e){super(),!0===t?(this.A=e.A,this.B=e.B):(i(t,e),function(t,e,r){const n=e.length,i=new Array(n),o=new Array(n);for(let t=0;t=0?"f(x) = "+n(this.A,t)+"x^{"+n(this.B,t)+"}":"f(x) = \\frac{"+n(this.A,t)+"}{x^{"+n(-this.B,t)+"}}"}static load(t){if("powerRegression"!==t.name)throw new TypeError("not a power regression model");return new l(!0,t)}}class c extends o{constructor(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{intercept:n=!0,statistics:i=!0}=r;if(super(),this.statistics=i,!0===t)this.weights=e.weights,this.inputs=e.inputs,this.outputs=e.outputs,this.intercept=e.intercept;else{t=new a.default(t),n&&t.addColumn(new Array(t.length).fill(1));const r=new a.SVD(t,{autoTranspose:!0}).solve(e);if(this.weights=r.to2DArray(),this.inputs=t[0].length,this.outputs=e[0].length,n&&this.inputs--,this.intercept=n,i){const n=t.mmul(r),i=new a.default(e).addM(n.neg()).to2DArray().map(t=>Math.pow(t[0],2)).reduce((t,e)=>t+e)/(e.length-t.columns);this.stdError=Math.sqrt(i),this.stdErrorMatrix=t.transposeView().mmul(t).pseudoInverse().mul(i),this.stdErrors=this.stdErrorMatrix.diagonal().map(t=>Math.sqrt(t)),this.tStats=this.weights.map((t,e)=>0===this.stdErrors[e]?0:t[0]/this.stdErrors[e])}}}predict(t){if(Array.isArray(t)){if("number"==typeof t[0])return this._predict(t);if(Array.isArray(t[0])){const e=new Array(t.length);for(let r=0;r({label:e===this.weights.length-1?"Intercept":"X Variable ".concat(e+1),coefficients:t,standardError:this.stdErrors[e],tStat:this.tStats[e]}))}:void 0}}static load(t){if("multivariateLinearRegression"!==t.name)throw new Error("not a MLR model");return new c(!0,t)}}class f extends o{constructor(t,e,r){if(super(),!0===t)this.A=e.A,this.M=e.M;else{if(t.length!==e.length)throw new RangeError("input and output array have a different length");var n=new h(t,e,[r]);this.A=n.coefficients[0],this.M=r}}_predict(t){return this.A*Math.pow(t,this.M)}toJSON(){return{name:"potentialRegression",A:this.A,M:this.M}}toString(t){return"f(x) = "+n(this.A,t)+" * x^"+this.M}toLaTeX(t){return this.M>=0?"f(x) = "+n(this.A,t)+"x^{"+this.M+"}":"f(x) = \\frac{"+n(this.A,t)+"}{x^{"+-this.M+"}}"}static load(t){if("potentialRegression"!==t.name)throw new TypeError("not a potential regression model");return new f(!0,t)}}var g=r(10),m=r.n(g);const d={lambda:.1,kernelType:"gaussian",kernelOptions:{},computeCoefficient:!1};class p extends o{constructor(t,e,r){if(super(),!0===t)this.alpha=e.alpha,this.inputs=e.inputs,this.kernelType=e.kernelType,this.kernelOptions=e.kernelOptions,this.kernel=new m.a(e.kernelType,e.kernelOptions);else{r=Object.assign({},d,r);const n=new m.a(r.kernelType,r.kernelOptions),i=n.compute(t),o=t.length;i.add(a.Matrix.eye(o,o).mul(r.lambda)),this.alpha=Object(a.solve)(i,e),this.inputs=t,this.kernelType=r.kernelType,this.kernelOptions=r.kernelOptions,this.kernel=n}}_predict(t){return this.kernel.compute([t],this.inputs).mmul(this.alpha)[0]}toJSON(){return{name:"kernelRidgeRegression",alpha:this.alpha,inputs:this.inputs,kernelType:this.kernelType,kernelOptions:this.kernelOptions}}static load(t){if("kernelRidgeRegression"!==t.name)throw new TypeError("not a KRR model");return new p(!0,t)}}const v={order:2};class w extends o{constructor(t,e,r){super(),!0===t?(this.coefficients=a.Matrix.columnVector(e.coefficients),this.order=e.order,e.r&&(this.r=e.r,this.r2=e.r2),e.chi2&&(this.chi2=e.chi2)):(r=Object.assign({},v,r),this.order=r.order,this.coefficients=[],this.X=t,this.y=e,this.train(this.X,this.y,r))}train(t,e){if(a.Matrix.isMatrix(t)||(t=new a.Matrix(t)),a.Matrix.isMatrix(e)||(e=a.Matrix.columnVector(e)),e.rows!==t.rows&&(e=e.transpose()),2!==t.columns)throw new RangeError("You give X with "+t.columns+" columns and it must be 2");if(t.rows!==e.rows)throw new RangeError("X and y must have the same rows");var r=t.rows,n=(this.order+2)*(this.order+1)/2;this.coefficients=new Array(n);var i=t.getColumnVector(0),o=t.getColumnVector(1),s=1/i.clone().apply(x).max(),h=1/o.clone().apply(x).max(),u=1/e.clone().apply(x).max();i.mulColumn(0,s),o.mulColumn(0,h),e.mulColumn(0,u);for(var l=new a.Matrix(r,n),c=0,f=0;f<=this.order;++f)for(var g=this.order-f,m=0;m<=g;++m){var d=y(i,f).mulColumnVector(y(o,m));l.setColumn(c,d),c++}var p=new a.SVD(l.transpose(),{computeLeftSingularVectors:!0,computeRightSingularVectors:!0,autoTranspose:!1}),v=a.Matrix.rowVector(p.diagonal);v=v.apply(function(t,e){this[t][e]>=1e-15?this[t][e]=1/this[t][e]:this[t][e]=0});var w=a.Matrix.zeros(r,n);for(f=0;f0&&e!==this.coefficients.length-1?a=" + "+a:e!==this.coefficients.length-1&&(a=" "+a)),s=a+s;return"+"===s.charAt(0)&&(s=s.slice(1)),"f(x) = "+s}static load(t){if("robustPolynomialRegression"!==t.name)throw new TypeError("not a RobustPolynomialRegression model");return new S(!0,t)}}function A(t,e){for(var r=t.slice(),n=t.slice(),i=0;it.residual-e.residual);var e=t.length,r=Math.floor(e/2);return e%2==0?t[r-1]:t[r]}r.d(e,"NLR",function(){return k}),r.d(e,"NonLinearRegression",function(){return k}),r.d(e,"SimpleLinearRegression",function(){return s}),r.d(e,"SLR",function(){return s}),r.d(e,"PolynomialRegression",function(){return h}),r.d(e,"ExponentialRegression",function(){return u}),r.d(e,"PowerRegression",function(){return l}),r.d(e,"MultivariateLinearRegression",function(){return c}),r.d(e,"KernelRidgeRegression",function(){return p}),r.d(e,"KRR",function(){return p}),r.d(e,"PolinomialFitting2D",function(){return w}),r.d(e,"TheilSenRegression",function(){return M}),r.d(e,"RobustPolynomialRegression",function(){return S});const k={PotentialRegression:f}},function(t,e,r){!function(){function e(t){for(var e=0,i=t.length-1,o=void 0,s=void 0,a=void 0,h=n(e,i);;){if(i<=e)return t[h];if(i==e+1)return t[e]>t[i]&&r(t,e,i),t[h];for(t[o=n(e,i)]>t[i]&&r(t,o,i),t[e]>t[i]&&r(t,e,i),t[o]>t[e]&&r(t,o,e),r(t,o,e+1),s=e+1,a=i;;){do{s++}while(t[e]>t[s]);do{a--}while(t[a]>t[e]);if(a=h&&(i=a-1)}}var r=function(t,e,r){var n;return n=[t[r],t[e]],t[e]=n[0],t[r]=n[1],n},n=function(t,e){return~~((t+e)/2)};t.exports?t.exports=e:window.median=e}()},function(t,e,r){"use strict";const n=r(8),i=r(141),o=e;o.PCA=r(44),o.HClust=r(45),o.KMeans=r(140),o.SVM=r(54),o.NaiveBayes=r(143),o.KNN=r(147),o.PLS=r(144),o.CrossValidation=r(65),o.ConfusionMatrix=r(25),o.DecisionTreeClassifier=n.DecisionTreeClassifier,o.RandomForestClassifier=i.RandomForestClassifier,o.FNN=r(67),o.SOM=r(69);const s=r(41);o.SimpleLinearRegression=s.SimpleLinearRegression,o.PolynomialRegression=s.PolynomialRegression,o.MultivariateLinearRegression=s.MultivariateLinearRegression,o.PowerRegression=s.PowerRegression,o.ExponentialRegression=s.ExponentialRegression,o.TheilSenRegression=s.TheilSenRegression,o.RobustPolynomialRegression=s.RobustPolynomialRegression,o.DecisionTreeRegression=n.DecisionTreeRegression,o.RandomForestRegression=i.RandomForestRegression,o.levenbergMarquardt=r(145);const a=r(0);o.Matrix=a.Matrix,o.SVD=a.SVD,o.EVD=a.EVD,o.CholeskyDecomposition=a.CholeskyDecomposition,o.LuDecomposition=a.LuDecomposition,o.QrDecomposition=a.QrDecomposition,o.SparseMatrix=r(71),o.Kernel=r(10),o.Distance=r(30).distance,o.Similarity=r(30).similarity,o.distanceMatrix=r(24),o.XSadd=r(19).default,o.Performance=r(120),o.savitzkyGolay=r(122),o.savitzkyGolayGeneralized=r(123),o.BitArray=r(124),o.HashTable=r(14),o.padArray=r(40),o.binarySearch=r(6),o.numSort=r(7),o.Random=r(11).default,o.ArrayUtils=r(126),o.Regression=r(41),o.MatrixUtil=r(0),o.ArrayStat=r(3).array,o.MatrixStat=r(3).matrix,o.Array={min:r(17).default,max:r(9).default,median:r(18).default,mean:r(5).default,mode:r(130).default,normed:r(131).default,rescale:r(13).default,sequentialFill:r(20).default,standardDeviation:r(132).default,variance:r(21).default},o.ArrayXY={centroidsMerge:r(133).default,closestX:r(134).default,maxMerge:r(135).default,maxY:r(136).default,sortX:r(137).default,uniqueX:r(138).default,weightedMerge:r(139).default,equallySpaced:r(142).default,filterX:r(146).default}},function(t,e,r){"use strict";const n=r(0),i=n.Matrix,o=n.EVD,s=n.SVD,a=r(4),h=a.mean,u=a.standardDeviation,l={isCovarianceMatrix:!1,center:!0,scale:!1};class c{constructor(t,e){if(!0===t){const t=e;return this.center=t.center,this.scale=t.scale,this.means=t.means,this.stdevs=t.stdevs,this.U=i.checkMatrix(t.U),void(this.S=t.S)}if(e=Object.assign({},l,e),this.center=!1,this.scale=!1,this.means=null,this.stdevs=null,e.isCovarianceMatrix)this._computeFromCovarianceMatrix(t);else if("boolean"==typeof e.useCovarianceMatrix?e.useCovarianceMatrix:t.length>t[0].length){const r=(t=this._adjust(t,e)).transposeView().mmul(t).div(t.rows-1);this._computeFromCovarianceMatrix(r)}else{t=this._adjust(t,e);var r=new s(t,{computeLeftSingularVectors:!1,computeRightSingularVectors:!0,autoTranspose:!0});this.U=r.rightSingularVectors;const i=r.diagonal,o=new Array(i.length);for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:{};const{nComponents:r=this.U.columns}=e;t=new i(t),this.center&&(t.subRowVector(this.means),this.scale&&t.divRowVector(this.stdevs));var n=t.mmul(this.U);return n.subMatrix(0,n.rows-1,0,r-1)}getExplainedVariance(){for(var t=0,e=0;ee/t)}getCumulativeVariance(){for(var t=this.getExplainedVariance(),e=1;eMath.sqrt(t))}getLoadings(){return this.U.transpose()}toJSON(){return{name:"PCA",center:this.center,scale:this.scale,means:this.means,stdevs:this.stdevs,U:this.U,S:this.S}}_adjust(t,e){if(this.center=!!e.center,this.scale=!!e.scale,t=new i(t),this.center){const e=h(t),n=this.scale?u(t,e,!0):null;if(this.means=e,t.subRowVector(e),this.scale){for(var r=0;r1;){p={},d=1e6;for(var w=0;w0;){A=E.shift();for(var O=0;O0){var C=E[O].filter(function(t){return-1===A.indexOf(t)});A=A.concat(C),E.splice(O--,1)}R[k++]=A}R.length=k;for(var N=0;Ne?1:0},g=function(t,e,r,n,i){var o;if(null==r&&(r=0),null==i&&(i=s),r<0)throw new Error("lo must be non-negative");for(null==n&&(n=t.length);rr;0<=r?e++:e--)u.push(e);return u}.apply(this).reverse()).length;nd;0<=d?++l:--l)p.push(u(t,r));return p},w=function(t,e,r,n){var i,o,a;for(null==n&&(n=s),i=t[r];r>e&&n(i,o=t[a=r-1>>1])<0;)t[r]=o,r=a;return t[r]=i},y=function(t,e,r){var n,i,o,a,h;for(null==r&&(r=s),i=t.length,h=e,o=t[e],n=2*e+1;n=o)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}}),h=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),m(r)?n.showHidden=r:r&&e._extend(n,r),w(n.showHidden)&&(n.showHidden=!1),w(n.depth)&&(n.depth=2),w(n.colors)&&(n.colors=!1),w(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=h),l(n,t,n.depth)}function h(t,e){var r=a.styles[e];return r?"["+a.colors[r][0]+"m"+t+"["+a.colors[r][1]+"m":t}function u(t,e){return t}function l(t,r,n){if(t.customInspect&&r&&S(r.inspect)&&r.inspect!==e.inspect&&(!r.constructor||r.constructor.prototype!==r)){var i=r.inspect(n,t);return v(i)||(i=l(t,i,n)),i}var o=function(t,e){if(w(e))return t.stylize("undefined","undefined");if(v(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(p(e))return t.stylize(""+e,"number");if(m(e))return t.stylize(""+e,"boolean");if(d(e))return t.stylize("null","null")}(t,r);if(o)return o;var s=Object.keys(r),a=function(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}(s);if(t.showHidden&&(s=Object.getOwnPropertyNames(r)),M(r)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return c(r);if(0===s.length){if(S(r)){var h=r.name?": "+r.name:"";return t.stylize("[Function"+h+"]","special")}if(y(r))return t.stylize(RegExp.prototype.toString.call(r),"regexp");if(b(r))return t.stylize(Date.prototype.toString.call(r),"date");if(M(r))return c(r)}var u,x="",A=!1,E=["{","}"];(g(r)&&(A=!0,E=["[","]"]),S(r))&&(x=" [Function"+(r.name?": "+r.name:"")+"]");return y(r)&&(x=" "+RegExp.prototype.toString.call(r)),b(r)&&(x=" "+Date.prototype.toUTCString.call(r)),M(r)&&(x=" "+c(r)),0!==s.length||A&&0!=r.length?n<0?y(r)?t.stylize(RegExp.prototype.toString.call(r),"regexp"):t.stylize("[Object]","special"):(t.seen.push(r),u=A?function(t,e,r,n,i){for(var o=[],s=0,a=e.length;s=0&&0,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(u,x,E)):E[0]+x+E[1]}function c(t){return"["+Error.prototype.toString.call(t)+"]"}function f(t,e,r,n,i,o){var s,a,h;if((h=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?a=h.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):h.set&&(a=t.stylize("[Setter]","special")),k(n,i)||(s="["+i+"]"),a||(t.seen.indexOf(h.value)<0?(a=d(r)?l(t,h.value,null):l(t,h.value,r-1)).indexOf("\n")>-1&&(a=o?a.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+a.split("\n").map(function(t){return" "+t}).join("\n")):a=t.stylize("[Circular]","special")),w(s)){if(o&&i.match(/^\d+$/))return a;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+a}function g(t){return Array.isArray(t)}function m(t){return"boolean"==typeof t}function d(t){return null===t}function p(t){return"number"==typeof t}function v(t){return"string"==typeof t}function w(t){return void 0===t}function y(t){return x(t)&&"[object RegExp]"===A(t)}function x(t){return"object"==typeof t&&null!==t}function b(t){return x(t)&&"[object Date]"===A(t)}function M(t){return x(t)&&("[object Error]"===A(t)||t instanceof Error)}function S(t){return"function"==typeof t}function A(t){return Object.prototype.toString.call(t)}function E(t){return t<10?"0"+t.toString(10):t.toString(10)}e.debuglog=function(r){if(w(o)&&(o=t.env.NODE_DEBUG||""),r=r.toUpperCase(),!s[r])if(new RegExp("\\b"+r+"\\b","i").test(o)){var n=t.pid;s[r]=function(){var t=e.format.apply(e,arguments);console.error("%s %d: %s",r,n,t)}}else s[r]=function(){};return s[r]},e.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},e.isArray=g,e.isBoolean=m,e.isNull=d,e.isNullOrUndefined=function(t){return null==t},e.isNumber=p,e.isString=v,e.isSymbol=function(t){return"symbol"==typeof t},e.isUndefined=w,e.isRegExp=y,e.isObject=x,e.isDate=b,e.isError=M,e.isFunction=S,e.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},e.isBuffer=r(51);var R=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function k(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.log=function(){var t,r;console.log("%s - %s",(t=new Date,r=[E(t.getHours()),E(t.getMinutes()),E(t.getSeconds())].join(":"),[t.getDate(),R[t.getMonth()],r].join(" ")),e.format.apply(e,arguments))},e.inherits=r(52),e._extend=function(t,e){if(!e||!x(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t};var O="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function C(t,e){if(!t){var r=new Error("Promise was rejected with a falsy value");r.reason=t,t=r}return e(t)}e.promisify=function(t){if("function"!=typeof t)throw new TypeError('The "original" argument must be of type Function');if(O&&t[O]){var e;if("function"!=typeof(e=t[O]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(e,O,{value:e,enumerable:!1,writable:!1,configurable:!0}),e}function e(){for(var e,r,n=new Promise(function(t,n){e=t,r=n}),i=[],o=0;o1)for(var r=1;rn.d&&(n.d=s-a,n.p=l)}return n}var f={dist:n,kind:"single"};function g(t,e,r){for(var n=0,i=0,o=0;o0;){n=0,m=0;for(var x=0;xn&&(n=r,m=x)}if(n=0,2===y[m].index.length)y[m].children=[y[m].index[0],y[m].index[1]],y[m].distance=e.dist(t[y[m].index[0].index],t[y[m].index[1].index]);else if(3===y[m].index.length){y[m].children=[y[m].index[0],y[m].index[1],y[m].index[2]];var S=[e.dist(t[y[m].index[0].index],t[y[m].index[1].index]),e.dist(t[y[m].index[1].index],t[y[m].index[2].index])];y[m].distance=(S[0]+S[1])/2}else{for(var A=new o,E=new o,R=[new Array(y[m].index.length),[]],k=0;kn&&(n=d,p=O)}for(R[1]=[p],R[0].splice(p,1),d=c(R,t,e.dist);d.d>0;)R[1].push(R[0][d.p]),R[0].splice(d.p,1),d=c(R,t,e.dist);var N=new Array(R[0].length);A.index=new Array(R[0].length);for(var T=0;Tthis.options.tol&&h[r]>0){for(n=r;n===r;)n=Math.floor(this.options.random()*a);if(d=this._marginOnePrecomputed(n,s)-e[n],p=h[r],v=h[n],e[r]===e[n]?(w=Math.max(0,p+v-this.options.C),y=Math.min(this.options.C,p+v)):(w=Math.max(0,v-p),y=Math.min(this.options.C,this.options.C+v+p)),Math.abs(w-y)<1e-4)continue;if((x=2*s[r][n]-s[r][r]-s[n][n])>=0)continue;var M=h[n]-e[n]*(m-d)/x;if(M>y?M=y:M0&&(this.b=l),h[n]0&&(this.b=c),b+=1}f++,0===b?g+=1:g=0}if(f===this.options.maxIterations)throw new Error("max iterations reached");if(this.iterations=f,"linear"===this.options.kernel){this.W=new Array(this.D);for(var S=0;Sthis.options.alphaTol&&(E.push(this.X[r]),R.push(e[r]),k.push(this.alphas[r]),this._supportVectorIdx.push(r));this.X=E,this.Y=R,this.N=E.length,this.alphas=k,this._trained=!0},s.prototype.predictOne=function(t){return this.marginOne(t)>0?1:-1},s.prototype.predict=function(t){if(!this._trained&&!this._loaded)throw new Error("Cannot predict, you need to train the SVM first");return Array.isArray(t)&&Array.isArray(t[0])?t.map(this.predictOne.bind(this)):this.predictOne(t)},s.prototype.marginOne=function(t,e){this.options.whitening&&!e&&(t=this._applyWhitening(t));var r,n=this.b;if("linear"===this.options.kernel&&this.W)for(r=0;rnew Array(e).fill(0))}function h(t){var e=new Set;for(let r=0;r=0;t--)w.splice(n[t],1);f?l(e,r,n,w,m,g,f):u(t,e,r,i,n,w,m,g)}return new n(m,g)},i.kFold=function(t,e,r,i,o){if("function"==typeof i){var c=i;o=r,r=e,e=t}s(e,r);const f=h(r),g=a(f.length,f.length);for(var m=e.length,d=new Array(m),p=0;p=0;--o){var s=this.tryEntries[o],a=s.completion;if("root"===s.tryLoc)return n("end");if(s.tryLoc<=this.prev){var h=i.call(s,"catchLoc"),u=i.call(s,"finallyLoc");if(h&&u){if(this.prev=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&i.call(n,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),O(r),m}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;O(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:N(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=r),m}}}function y(t,e,r,n){var i=e&&e.prototype instanceof b?e:b,o=Object.create(i.prototype),s=new C(n||[]);return o._invoke=function(t,e,r){var n=l;return function(i,o){if(n===f)throw new Error("Generator is already running");if(n===g){if("throw"===i)throw o;return T()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var a=R(s,r);if(a){if(a===m)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===l)throw n=g,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=f;var h=x(t,e,r);if("normal"===h.type){if(n=r.done?g:c,h.arg===m)continue;return{value:h.arg,done:r.done}}"throw"===h.type&&(n=g,r.method="throw",r.arg=h.arg)}}}(t,r,s),o}function x(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}function b(){}function M(){}function S(){}function A(t){["next","throw","return"].forEach(function(e){t[e]=function(t){return this._invoke(e,t)}})}function E(t){var e;this._invoke=function(r,n){function o(){return new Promise(function(e,o){!function e(r,n,o,s){var a=x(t[r],t,n);if("throw"!==a.type){var h=a.arg,u=h.value;return u&&"object"==typeof u&&i.call(u,"__await")?Promise.resolve(u.__await).then(function(t){e("next",t,o,s)},function(t){e("throw",t,o,s)}):Promise.resolve(u).then(function(t){h.value=t,o(h)},s)}s(a.arg)}(r,n,e,o)})}return e=e?e.then(o,o):o()}}function R(t,e){var n=t.iterator[e.method];if(n===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=r,R(t,e),"throw"===e.method))return m;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return m}var i=x(n,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,m;var o=i.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=r),e.delegate=null,m):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,m)}function k(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function O(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function C(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(k,this),this.reset(!0)}function N(t){if(t){var e=t[s];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,o=function e(){for(;++n=0,i=n&&r.regeneratorRuntime;r.regeneratorRuntime=void 0;var o=e;if(n)r.regeneratorRuntime=i;else try{delete r.regeneratorRuntime}catch(t){r.regeneratorRuntime=void 0}var s=o,a={mode:"index"};t.exports=s.mark(function t(e,r,n){var i,o,h,u,l,c,f,g,m;return s.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:for(m=function(){var t,e,r;for(e=1;u[e]<=0;)e++;if(0===u[e-1]){for(t=e-1;1!==t;t--)u[t]=-1;u[e]=0,l=f=0,u[1]=1,c=e-1}else{e>1&&(u[e-1]=0);do{e++}while(u[e]>0);for(r=e-1,t=e;0===u[t];)u[t++]=-1;if(-1===u[t])u[t]=u[r],f=u[r]-1,l=t-1,c=r-1,u[r]=-1;else{if(t===u[0])return 0;u[e]=u[t],f=u[t]-1,u[t]=0,l=e-1,c=t-1}}return 1},n=Object.assign({},a,n),i=new Array(r),o=new Array(e),h=new Array(r),u=new Array(r+2),g=0;g=0;--n){var o=n>0?this.model[n-1].a:t;i=this.model[n].backpropagation(i,o)}for(n=0;n0&&e>0))throw new Error("x and y must be positive");this.times={findBMU:0,adjust:0},this.randomizer=this.options.randomizer,this.iterationCount=0,this.iterations=this.options.iterations,this.startLearningRate=this.learningRate=this.options.learningRate,this.mapRadius=Math.floor(Math.max(t,e)/2),this.algorithmMethod=this.options.method,this._initNodes(),this.done=!1}else this.done=!0}function getConverters(t){for(var e=t.length,r=new Array(e),n=new Array(e),i=0;i0?("random"===this.algorithmMethod?(t=this.mapRadius*Math.exp(-this.iterationCount/this.timeConstant),e=getRandomValue(this.trainingSet,this.randomizer),this._adjust(e,t),this.learningRate=this.startLearningRate*Math.exp(-this.iterationCount/this.numIterations)):(r=-Math.floor(this.iterationCount/this.trainingSet.length),t=this.mapRadius*Math.exp(r/this.timeConstant),e=this.trainingSet[this.iterationCount%this.trainingSet.length],this._adjust(e,t),(this.iterationCount+1)%this.trainingSet.length==0&&(this.learningRate=this.startLearningRate*Math.exp(r/Math.floor(this.numIterations/this.trainingSet.length)))),this.iterationCount++,!0):(this.done=!0,!1));var t,e,r},SOM.prototype._adjust=function(t,e){var r,n,i,o,s=Date.now(),a=this._findBestMatchingUnit(t),h=Date.now();this.times.findBMU+=h-s;var u=Math.floor(e),l=a.x-u,c=a.x+u,f=a.y-u,g=a.y+u;for(r=l;r<=c;r++){var m=r;for(r<0?m+=this.x:r>=this.x&&(m-=this.x),n=f;n<=g;n++){var d=n;n<0?d+=this.y:n>=this.y&&(d-=this.y),(i=a[this.distanceMethod](this.nodes[m][d]))2&&void 0!==arguments[2]?arguments[2]:{};if(t instanceof SparseMatrix){const e=t;this._init(e.rows,e.columns,e.elements.clone(),e.threshold)}else if(Array.isArray(t)){const s=t;t=s.length,r=e||{},e=s[0].length,this._init(t,e,new ml_hash_table__WEBPACK_IMPORTED_MODULE_0___default.a(r),r.threshold);for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:1,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t;const r=Math.min(t,e),n=new SparseMatrix(t,e,{initialCapacity:r});for(var i=0;ithis.get(r,e)!==n?(t=!1,!1):n),t}bandWidth(){let t=this.columns,e=-1;return this.forEachNonZero((r,n,i)=>{let o=r-n;return t=Math.min(t,o),e=Math.max(e,o),i}),e-t}isBanded(t){return this.bandWidth()<=t}get cardinality(){return this.elements.size}get size(){return this.rows*this.columns}get(t,e){return this.elements.get(t*this.columns+e)}set(t,e,r){return this.threshold&&Math.abs(r)(t.forEachNonZero((t,o,s)=>(r===t&&n.set(e,o,n.get(e,o)+i*s),s)),i)),n}kroneckerProduct(t){const e=this.rows,r=this.columns,n=t.rows,i=t.columns,o=new SparseMatrix(e*n,r*i,{initialCapacity:this.cardinality*t.cardinality});return this.forEachNonZero((e,r,s)=>(t.forEachNonZero((t,a,h)=>(o.set(n*e+t,i*r+a,s*h),h)),s)),o}forEachNonZero(t){return this.elements.forEachPair((e,r)=>{const n=e/this.columns|0,i=e%this.columns;let o=t(n,i,r);return!1!==o&&(this.threshold&&Math.abs(o)(e[i]=t,r[i]=o,n[i]=s,i++,s)),{rows:e,columns:r,values:n}}setThreshold(t){return 0!==t&&t!==this.threshold&&(this.threshold=t,this.forEachNonZero((t,e,r)=>r)),this}transpose(){let t=new SparseMatrix(this.columns,this.rows,{initialCapacity:this.cardinality});return this.forEachNonZero((e,r,n)=>(t.set(r,e,n),n)),t}}SparseMatrix.prototype.klass="Matrix",SparseMatrix.identity=SparseMatrix.eye,SparseMatrix.prototype.tensorProduct=SparseMatrix.prototype.kroneckerProduct;var inplaceOperator="\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n",inplaceOperatorScalar="\n(function %name%S(value) {\n this.forEachNonZero((i, j, v) => v %op% value);\n return this;\n})\n",inplaceOperatorMatrix="\n(function %name%M(matrix) {\n matrix.forEachNonZero((i, j, v) => {\n this.set(i, j, this.get(i, j) %op% v);\n return v;\n });\n return this;\n})\n",staticOperator="\n(function %name%(matrix, value) {\n var newMatrix = new SparseMatrix(matrix);\n return newMatrix.%name%(value);\n})\n",inplaceMethod="\n(function %name%() {\n this.forEachNonZero((i, j, v) => %method%(v));\n return this;\n})\n",staticMethod="\n(function %name%(matrix) {\n var newMatrix = new SparseMatrix(matrix);\n return newMatrix.%name%();\n})\n";const operators=[["+","add"],["-","sub","subtract"],["*","mul","multiply"],["/","div","divide"],["%","mod","modulus"],["&","and"],["|","or"],["^","xor"],["<<","leftShift"],[">>","signPropagatingRightShift"],[">>>","rightShift","zeroFillRightShift"]];for(const operator of operators)for(let i=1;ir&&(a+=e[h]);if(!(ar&&(u+=t[l]*e[l]);if(!((u/=a)-r<1e-5||i-u<1e-5))return u-rt.pred-e.pred):s.sort((t,e)=>e.pred-t.pred);const u=this.cutoffs=[o?Number.MIN_VALUE:Number.MAX_VALUE],l=this.fp=[0],c=this.tp=[0];var f=0,g=0,m=s[0].pred,d=0,p=0;for(a=0;a{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.length,r=new Array(e);for(var n=0;n{const e=t.cutoffs.slice();return e[0]=e[1],e}},function(t,e,r){"use strict";var n=r(0),i=n.Matrix,o=n.inverse,s=r(40),a=r(16),h={windowSize:5,derivative:1,polynomial:2,pad:"none",padValue:"replicate"};t.exports=function(t,e,r){if((r=a({},h,r)).windowSize%2==0||r.windowSize<5||!Number.isInteger(r.windowSize))throw new RangeError("Invalid window size (should be odd and at least 5 integer number)");if(r.derivative<0||!Number.isInteger(r.derivative))throw new RangeError("Derivative should be a positive integer");if(r.polynomial<1||!Number.isInteger(r.polynomial))throw new RangeError("Polynomial should be a positive integer");var n,u,l=Math.floor(r.windowSize/2);"pre"===r.pad&&(t=s(t,{size:l,value:r.padValue}));var c=new Array(t.length-2*l);if(5!==r.windowSize||2!==r.polynomial||1!==r.derivative&&2!==r.derivative){for(var f=i.ones(r.windowSize,r.polynomial+1),g=-(r.windowSize-1)/2,m=0;m=0&&s0?(4*r-2)/(r*(2*e-r+1))*(t*s(t,e,r-1,n)+n*s(t,e,r-1,n-1))-(r-1)*(2*e+r)/(r*(2*e-r+1))*s(t,e,r-2,n):0==r&&0==n?1:0}function a(t,e){var r=1;if(t>=e)for(var n=t-e+1;n<=t;n++)r*=n;return r}function h(t,e,r,n,i){for(var o=0,h=0;h<=n;h++)o+=(2*h+1)*(a(2*r,h)/a(2*r+h+1,h+1))*s(t,r,h,0)*s(e,r,h,i);return o}t.exports=function(t,e,r){if((r=n({},i,r)).windowSize%2==0||r.windowSize<5||!Number.isInteger(r.windowSize))throw new RangeError("Invalid window size (should be odd and at least 5 integer number)");if(r.windowSize>t.length)throw new RangeError("Window size is higher than the data length "+r.windowSize+">"+t.length);if(r.derivative<0||!Number.isInteger(r.derivative))throw new RangeError("Derivative should be a positive integer");if(r.polynomial<1||!Number.isInteger(r.polynomial))throw new RangeError("Polynomial should be a positive integer");r.polynomial>=6&&console.warn("You should not use polynomial grade higher than 5 if you are not sure that your data arises from such a model. Possible polynomial oscillation problems");var s=r.windowSize,a=Math.floor(s/2),u=t.length,l=new Array(u),c=function(t,e,r){for(var n=new Array(t),i=Math.floor(t/2),o=-i;o<=i;o++){n[o+i]=new Array(t);for(var s=-i;s<=i;s++)n[o+i][s+i]=h(s,o,i,e,r)}return n}(s,r.polynomial,r.derivative),f=0,g=!0;"[object Array]"===Object.prototype.toString.call(e)?g=!1:f=Math.pow(e,r.derivative);for(var m=0;m>>0).toString(2);e+="00000000000000000000000000000000".substr(n.length)+n}return e}t.exports={count:function(t){for(var e=0,r=0;r>8&255]+n[t[r]>>16&255]+n[t[r]>>24&255];return e},and:function(t,e){for(var r=new Array(t.length),n=0;n>5]&r)},setBit:function(t,e,r){var n=e>>5,i=1<<31-e%32;return t[n]=r?i|t[n]:~i&t[n],t},toBinaryString:i,parseBinaryString:function(t){for(var e=t.length/32,r=new Array(e),n=0;n>>0).toString(16);e+="00000000".substr(n.length)+n}return e},parseHexString:function(t){for(var e=t.length/8,r=new Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:{};const{min:i,max:o}=r;var s=r.inPlace?e:new Array(e.length),a=n.minMax(e);if("number"==typeof o)if("number"==typeof i){let t=(o-i)/(a.max-a.min);for(let r=0;r2&&void 0!==arguments[2]?arguments[2]:{};var i=t.length;t.length>1&&t[0]>t[1]&&(t=t.slice().reverse(),e=e.slice().reverse());var{from:o=t[0],to:s=t[i-1],variant:a="smooth",numberOfPoints:h=100}=r;if(i!==e.length)throw new RangeError("the x and y vector doesn't have the same size.");if("number"!=typeof o||isNaN(o))throw new RangeError("'from' option must be a number");if("number"!=typeof s||isNaN(s))throw new RangeError("'to' option must be a number");var u=o>s;if(u&&([o,s]=[s,o]),"number"!=typeof h||isNaN(h))throw new RangeError("'numberOfPoints' option must be a number");if(h<1)throw new RangeError("the number of points must be at least 1");var l="slot"===a?function(t,e,r,n,i){var o=t.length,s=(n-r)/(i-1),a=s/2,h=t[t.length-1]-t[t.length-2],u=r-a,l=new Array(i),c=u,f=u+s,g=-Number.MAX_VALUE,m=0,d=t[0],p=e[0],v=0,w=!0,y=0,x=0,b=1,M=0;t:for(;;){if(g>=d)throw new Error("x must be an increasing serie");for(;g-f>0;){if(w&&(x++,w=!1),l[M]=x<=0?0:y/x,++M===i)break t;c=f,f+=s,y=0,x=0}g>c&&(y+=m,x++),(g===-Number.MAX_VALUE||v>1)&&x--,g=d,m=p,b=0;){var E=n(0,g-m,y,d);if(M=w+E,u[A++]=(M-b)/a,A===o)break t;f=g,g+=a,b=M}w+=n(m,p,y,x),m=p,d=v,Sr&&(r=n,e=t[s])}return e}},function(t,e,r){"use strict";r.r(e),e.default=function(t){var e=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).algorithm,r=void 0===e?"absolute":e;if(!Array.isArray(t))throw new Error("input must be an array");if(0===t.length)throw new Error("input must not be empty");switch(r.toLowerCase()){case"absolute":var n=function(t){for(var e=0,r=0;r1&&void 0!==arguments[1]?arguments[1]:{};return Math.sqrt(Object(n.default)(t,e))}},function(t,e,r){"use strict";function n(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{window:n=.01}=r;for(var i={x:e.slice(),y:new Array(e.length).fill(0)},o=0,s=0;o=0?{x:r[h],y:n[h]}:0!==(h=~h)&&Math.abs(r[h]-s)>.5||h===r.length?{x:r[h-1],y:n[h-1]}:{x:r[h],y:n[h]}}},function(t,e,r){"use strict";function n(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{x:r,y:n}=t,{groupWidth:i=.001}=e;for(var o={x:[],y:[]},s={x:[],y:[]},a=0,h=0;hi?(s.x.push(r[h]),s.y.push(n[h]),o.x.push(r[h]),o.y.push(n[h]),h++,a++):(n[h]>s.y[a-1]&&(s.x[a-1]=r[h],s.y[a-1]=n[h]),o.x[a-1]=r[h],o.y[a-1]+=n[h],h++);return o.x=s.x.slice(),o}r.r(e),r.d(e,"default",function(){return n})},function(t,e,r){"use strict";r.r(e),r.d(e,"default",function(){return s});var n=r(6),i=r.n(n),o=r(7);function s(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{x:r,y:n}=t;let{from:i={index:0},to:o={index:r.length},reverse:s=!1}=e;void 0!==i.value&&void 0===i.index&&(i.index=a(i.value,r,s)),void 0!==o.value&&void 0===o.index&&(o.index=a(o.value,r,s));for(var h,u=Number.MIN_VALUE,l=i.index;l1&&void 0!==arguments[1]?arguments[1]:{};const{x:r,y:n}=t,{reverse:i=!1}=e;var o;o=i?(t,e)=>e.x-t.x:(t,e)=>t.x-e.x;for(var s=r.map((t,e)=>({x:t,y:n[e]})).sort(o),a={x:r.slice(),y:n.slice()},h=0;h0&&void 0!==arguments[0]?arguments[0]:{};const{x:e,y:r}=t;if(e.length<2)return;if(e.length!==r.length)throw new Error("The X and Y arrays mush have the same length");let n=e[0],i=0;for(let t=1;t1&&void 0!==arguments[1]?arguments[1]:{};const{x:r,y:n}=t,{groupWidth:i=.001}=e;for(var o={x:[],y:[]},s={x:[],y:[]},a=0,h=0;hi?(s.x.push(r[h]*n[h]),s.y.push(n[h]),o.x.push(r[h]),o.y.push(n[h]),h++,a++):(s.x[a-1]+=r[h]*n[h],s.y[a-1]+=n[h],o.x[a-1]=r[h],o.y[a-1]+=n[h],h++);for(var u=0;u2&&void 0!==arguments[2]?arguments[2]:o;const n=r.distanceFunction||o.distanceFunction,i=r.similarityFunction||o.similarityFunction;let s=-1;if("function"==typeof i){let r=Number.MIN_VALUE;for(let n=0;nr&&(r=o,s=n)}}else{if("function"!=typeof n)throw new Error("A similarity or distance function it's required");{let r=Number.MAX_VALUE;for(let i=0;in)return!1;return!0}(s,t,i.distanceFunction,i.tolerance);return new m(r,s,h,o,i.distanceFunction)}function v(t,e,r){if(r=Object.assign({},d,r),e<=0||e>t.length||!Number.isInteger(e))throw new Error("K should be a positive integer smaller than the number of points");var i;if(Array.isArray(r.initialization)){if(r.initialization.length!==e)throw new Error("The initial centers should have the same length as K");i=r.initialization}else switch(r.initialization){case"kmeans++":i=function(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const i=(t=new u.Matrix(t)).length,o=new h.default(r.seed),s=[],a=r.localTrials||2+Math.floor(Math.log(e)),g=o.randInt(i);s.push(t[g].slice());let m=[t.map(t=>n(t,s[0]))],d=[f(m[0])];const p=1/d[0][i-1];let v=u.Matrix.mul(m,p);for(let r=1;r1){for(var s={dist:-1,index:-1},a=0;as.dist&&(s.dist=r[o[0]][a],s.index=a);if(o[1]=s.index,e>2)for(var u=2;ul.dist&&(l=Object.assign({},f))}o[u]=l.index}}return o.map(e=>t[e])}(t,e,function(t,e){for(var r=new Array(t.length),n=0;nr.load(t))}else this.replacement=t.replacement,this.maxFeatures=t.maxFeatures,this.nEstimators=t.nEstimators,this.treeOptions=t.treeOptions,this.isClassifier=t.isClassifier,this.seed=t.seed,this.useSampleBagging=t.useSampleBagging}train(t,e){if(t=i.Matrix.checkMatrix(t),this.maxFeatures=this.maxFeatures||t.columns,(r=this.maxFeatures)>0&&r<=1)this.n=Math.floor(t.columns*this.maxFeatures);else{if(!Number.isInteger(this.maxFeatures))throw new RangeError("Cannot process the maxFeatures parameter ".concat(this.maxFeatures));if(this.maxFeatures>t.columns)throw new RangeError("The maxFeatures parameter should be less than ".concat(t.columns));this.n=this.maxFeatures}var r;if(this.isClassifier)var o=n.DecisionTreeClassifier;else o=n.DecisionTreeRegression;this.estimators=new Array(this.nEstimators),this.indexes=new Array(this.nEstimators);for(var s=0;st.toJSON()),useSampleBagging:this.useSampleBagging}}}const l={maxFeatures:1,replacement:!0,nEstimators:10,seed:42,useSampleBagging:!1};class c extends u{constructor(t,e){!0===t?super(!0,e.baseModel):((t=Object.assign({},l,t)).isClassifier=!0,super(t))}selection(t){return(e=t).sort((t,r)=>e.filter(e=>e===t).length-e.filter(t=>t===r).length).pop();var e}toJSON(){return{baseModel:super.toJSON(),name:"RFClassifier"}}static load(t){if("RFClassifier"!==t.name)throw new RangeError("Invalid model: ".concat(t.name));return new c(!0,t)}}var f=r(5),g=r(18);const m={mean:f.default,median:g.default},d={maxFeatures:1,replacement:!1,nEstimators:10,treeOptions:{},selectionMethod:"mean",seed:42,useSampleBagging:!1};class p extends u{constructor(t,e){if(!0===t)super(!0,e.baseModel),this.selectionMethod=e.selectionMethod;else{if("mean"!==(t=Object.assign({},d,t)).selectionMethod&&"median"!==t.selectionMethod)throw new RangeError("Unsupported selection method ".concat(t.selectionMethod));t.isClassifier=!1,super(t),this.selectionMethod=t.selectionMethod}}selection(t){return m[this.selectionMethod](t)}toJSON(){return{baseModel:super.toJSON(),selectionMethod:this.selectionMethod,name:"RFRegression"}}static load(t){if("RFRegression"!==t.name)throw new RangeError("Invalid model: ".concat(t.name));return new p(!0,t)}}r.d(e,"RandomForestClassifier",function(){return c}),r.d(e,"RandomForestRegression",function(){return p})},function(t,e,r){"use strict";r.r(e);var n=r(20);function i(t,e,r,n){return.5*r*e*e+n*e-(.5*r*t*t+n*t)}function o(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{x:r,y:n}=t,i=r.length,o=!1;r.length>1&&r[0]>r[1]&&(r=r.slice().reverse(),n=n.slice().reverse(),o=!0);let{from:a=r[0],to:h=r[i-1],variant:u="smooth",numberOfPoints:l=100,exclusions:c=[]}=e;if(i!==n.length)throw new RangeError("the x and y vector doesn't have the same size.");if("number"!=typeof a||isNaN(a))throw new RangeError("'from' option must be a number");if("number"!=typeof h||isNaN(h))throw new RangeError("'to' option must be a number");if("number"!=typeof l||isNaN(l))throw new RangeError("'numberOfPoints' option must be a number");let f=function(t,e,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];t>e&&([t,e]=[e,t]),n=n.filter(t=>void 0!==t.from&&void 0!==t.to),(n=JSON.parse(JSON.stringify(n))).forEach(t=>{t.from>t.to&&([t.to,t.from]=[t.from,t.to])}),n.sort((t,e)=>t.from-e.from),n.forEach(r=>{r.frome&&(r.to=e)});for(let t=0;tn[t+1].from&&(n[t].to=n[t+1].from);if(!(n=n.filter(t=>t.fromt+=e.to-e.from,0),o=(e-t-i)/r,s=[],a=t,h=0;for(let t of n){let e=Math.round((t.from-a)/o);h+=e,e>0&&s.push({from:a,to:t.from,numberOfPoints:e}),a=t.to}return r-h>0&&s.push({from:a,to:e,numberOfPoints:r-h}),s}(a,h,l,c),g=[],m=[];for(let t of f){let e=s(r,n,t.from,t.to,t.numberOfPoints,u);g.push(...e.x),m.push(...e.y)}return o?a=d)throw new Error("x must be an increasing serie");for(;g-f>0;){if(w&&(x++,w=!1),l[M]=x<=0?0:y/x,++M===i)break t;c=f,f+=s,y=0,x=0}g>c&&(y+=m,x++),(g===-Number.MAX_VALUE||v>1)&&x--,g=d,m=p,b=0;){var E=i(0,g-m,y,d);if(M=w+E,u[A++]=(M-b)/a,A===o)break t;f=g,g+=a,b=M}w+=i(m,p,y,x),m=p,d=v,Sn&&(n=s,i=o)}return i}function u(t,e,r,n){return t-=e,Math.log(r*Math.exp(t*t/n))}class l{constructor(t){t&&(this.conditionalProbability=n.default.checkMatrix(t.conditionalProbability),this.priorProbability=n.default.checkMatrix(t.priorProbability))}train(t,e){if((t=n.default.checkMatrix(t)).rows!==e.length)throw new RangeError("the size of the training set and the training labels must be the same.");var r=s(t,e);this.priorProbability=new n.default(r.length,1);for(var i=0;if&&xf;){var O=b.mmul(R);O.div(s(O)),k=E,E=t.mmul(O);var C=M.mmul(E);C.div(s(C)),R=e.mmul(C)}k=E;var N=b.mmul(k),T=k.transpose().mmul(k)[0][0],P=N.div(T),_=s(P);P.div(_),k.mul(_),O.mul(_),N=R.transpose().mmul(k),T=k.transpose().mmul(k)[0][0];var z=N.div(T)[0][0];t.sub(k.mmul(P.transpose())),e.sub(k.clone().mul(z).mmul(C.transpose())),m.setColumn(x,k),d.setColumn(x,P),p.setColumn(x,R),v.setColumn(x,C),y.setColumn(x,O),w[x][x]=z,x++}x--,m=m.subMatrix(0,m.rows-1,0,x),d=d.subMatrix(0,d.rows-1,0,x),p=p.subMatrix(0,p.rows-1,0,x),v=v.subMatrix(0,v.rows-1,0,x),y=y.subMatrix(0,y.rows-1,0,x),w=w.subMatrix(0,x,0,x),this.ssqYcal=c,this.E=t,this.F=e,this.T=m,this.P=d,this.U=p,this.Q=v,this.W=y,this.B=w,this.PBQ=d.mmul(w).mmul(v.transpose()),this.R2X=k.transpose().mmul(k).mmul(P.transpose().mmul(P)).div(u)[0][0]}predict(t){var e=n.default.checkMatrix(t);this.scale&&(e=e.subRowVector(this.meanX).divRowVector(this.stdDevX));var r=e.mmul(this.PBQ);return r=r.mulRowVector(this.stdDevY).addRowVector(this.meanY)}getExplainedVariance(){return this.R2X}toJSON(){return{name:"PLS",R2X:this.R2X,meanX:this.meanX,stdDevX:this.stdDevX,meanY:this.meanY,stdDevY:this.stdDevY,PBQ:this.PBQ,tolerance:this.tolerance,scale:this.scale}}static load(t){if("PLS"!==t.name)throw new RangeError("Invalid model: "+t.name);return new u(!0,t)}}function l(t){return t.sum("column").maxIndex()[0]}class c{constructor(t,e){if(!0===t)this.trainingSet=new n.Matrix(e.trainingSet),this.YLoadingMat=new n.Matrix(e.YLoadingMat),this.SigmaPow=new n.Matrix(e.SigmaPow),this.YScoreMat=new n.Matrix(e.YScoreMat),this.predScoreMat=h(e.predScoreMat,!1),this.YOrthLoadingVec=h(e.YOrthLoadingVec,!1),this.YOrthEigen=e.YOrthEigen,this.YOrthScoreMat=h(e.YOrthScoreMat,!1),this.toNorm=h(e.toNorm,!1),this.TURegressionCoeff=h(e.TURegressionCoeff,!1),this.kernelX=h(e.kernelX,!0),this.kernel=e.kernel,this.orthogonalComp=e.orthogonalComp,this.predictiveComp=e.predictiveComp;else{if(void 0===t.predictiveComponents)throw new RangeError("no predictive components found!");if(void 0===t.orthogonalComponents)throw new RangeError("no orthogonal components found!");if(void 0===t.kernel)throw new RangeError("no kernel found!");this.orthogonalComp=t.orthogonalComponents,this.predictiveComp=t.predictiveComponents,this.kernel=t.kernel}}train(t,e){t=n.Matrix.checkMatrix(t),e=n.Matrix.checkMatrix(e),this.trainingSet=t.clone();var r=this.kernel.compute(t),i=n.Matrix.eye(r.rows,r.rows,1),o=r;(r=new n.Matrix(this.orthogonalComp+1,this.orthogonalComp+1))[0][0]=o;var s=new n.SingularValueDecomposition(e.transpose().mmul(r[0][0]).mmul(e),{computeLeftSingularVectors:!0,computeRightSingularVectors:!1}),a=s.leftSingularVectors,h=s.diagonalMatrix;a=a.subMatrix(0,a.rows-1,0,this.predictiveComp-1),h=h.subMatrix(0,this.predictiveComp-1,0,this.predictiveComp-1);var u=e.mmul(a),l=new Array(this.orthogonalComp+1),c=new Array(this.orthogonalComp+1),f=new Array(this.orthogonalComp),g=new Array(this.orthogonalComp),m=new Array(this.orthogonalComp),d=new Array(this.orthogonalComp),p=n.Matrix.pow(h,-.5);p.apply(function(t,e){this[t][e]===1/0&&(this[t][e]=0)});for(var v=0;vh(t)),l=function(t,e,r,n,o){const s=r.length,a=t.x.length;for(var h=new Array(s),u=0;u2&&void 0!==arguments[2]?arguments[2]:{},{maxIterations:i=100,gradientDifference:s=.1,damping:a=0,errorTolerance:h=.01,minValues:u,maxValues:l,initialValues:c}=r;if(a<=0)throw new Error("The damping option must be a positive number");if(!t.x||!t.y)throw new Error("The data parameter must have x and y elements");if(!Array.isArray(t.x)||t.x.length<2||!Array.isArray(t.y)||t.y.length<2)throw new Error("The data parameter elements must be an array with more than 2 points");if(t.x.length!==t.y.length)throw new Error("The data parameter elements must have the same size");var f=c||new Array(e.length).fill(1);let g=f.length;if(l=l||new Array(g).fill(Number.MAX_SAFE_INTEGER),u=u||new Array(g).fill(Number.MIN_SAFE_INTEGER),l.length!==u.length)throw new Error("minValues and maxValues must be the same size");if(!Array.isArray(f))throw new Error("initialValues must be an array");for(var m=n(t,f,e),d=m<=h,p=0;p1&&void 0!==arguments[1]?arguments[1]:{};const{x:r,y:n}=t,{from:i=r[0],to:o=r[r.length-1],exclusions:s=[]}=e;let a=function(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];t>e&&([t,e]=[e,t]),r=r.filter(t=>void 0!==t.from&&void 0!==t.to),(r=JSON.parse(JSON.stringify(r))).forEach(t=>{t.from>t.to&&([t.to,t.from]=[t.from,t.to])}),r.sort((t,e)=>t.from-e.from),r.forEach(r=>{r.frome&&(r.to=e)});for(let t=0;tr[t+1].from&&(r[t].to=r[t+1].from);if(!(r=r.filter(t=>t.from=a[h].from)u.push(r[c]),l.push(n[c]);else if(r[c]>a[h].to&&!a[++h])break;c++}return{x:u,y:l}}r.r(e),r.d(e,"default",function(){return n})},function(t,e,r){"use strict"; /* * Original code from: * @@ -11,5 +11,5 @@ * @author Ubilabs http://ubilabs.net, 2012 * @license MIT License */ -function n(t,e,r){this.obj=t,this.left=null,this.right=null,this.parent=r,this.dimension=e}r.r(e);class i{constructor(t,e){if(Array.isArray(t)){this.dimensions=new Array(t[0].length);for(var r=0;rt[o[s]]-e[o[s]]);const a=Math.floor(e.length/2);const h=new n(e[a],s,i);h.left=t(e.slice(0,a),r+1,h,o);h.right=t(e.slice(a+1),r+1,h,o);return h}(t,0,null,this.dimensions)}else this.dimensions=t.dimensions,this.root=t,function t(e){e.left&&(e.left.parent=e,t(e.left));e.right&&(e.right.parent=e,t(e.right))}(this.root);this.metric=e}toJSON(){const t=function t(e){const r=new n(e.obj,e.dimension,null);e.left&&(r.left=t(e.left));e.right&&(r.right=t(e.right));return r}(this.root);return t.dimensions=this.dimensions,t}nearest(t,e,r){const n=this.metric,i=this.dimensions;var s;const a=new o(function(t){return-t[1]});if(r)for(s=0;se&&a.pop()}for(g=0;g0&&(this.content[0]=e,this.sinkDown(0)),t}peek(){return this.content[0]}size(){return this.content.length}bubbleUp(t){for(var e=this.content[t];t>0;){const r=Math.floor((t+1)/2)-1,n=this.content[r];if(!(this.scoreFunction(e)2&&void 0!==arguments[2]?arguments[2]:{};if(!0===t){const t=e;return this.kdTree=new i(t.kdTree,r),this.k=t.k,this.classes=new Set(t.classes),void(this.isEuclidean=t.isEuclidean)}const n=new Set(e),o=r.distance,s=void 0===o?a.a:o,h=r.k,u=void 0===h?n.size+1:h,l=new Array(t.length);for(var c=0;c1&&void 0!==arguments[1]?arguments[1]:a.a;if("KNN"!==t.name)throw new Error("invalid model: "+t.name);if(!t.isEuclidean&&e===a.a)throw new Error("a custom distance function was used to create the model. Please provide it again");if(t.isEuclidean&&e!==a.a)throw new Error("the model was created with the default distance function. Do not load it with another one");return new h(!0,t,e)}toJSON(){return{name:"KNN",kdTree:this.kdTree,k:this.k,classes:Array.from(this.classes),isEuclidean:this.isEuclidean}}predict(t){if(Array.isArray(t)){if("number"==typeof t[0])return u(this,t);if(Array.isArray(t[0])&&"number"==typeof t[0][0]){const r=new Array(t.length);for(var e=0;eo&&(i=u,o=l)}return i}}])}); +function n(t,e,r){this.obj=t,this.left=null,this.right=null,this.parent=r,this.dimension=e}r.r(e);class i{constructor(t,e){if(Array.isArray(t)){this.dimensions=new Array(t[0].length);for(var r=0;rt[o[s]]-e[o[s]]);const a=Math.floor(e.length/2);const h=new n(e[a],s,i);h.left=t(e.slice(0,a),r+1,h,o);h.right=t(e.slice(a+1),r+1,h,o);return h}(t,0,null,this.dimensions)}else this.dimensions=t.dimensions,this.root=t,function t(e){e.left&&(e.left.parent=e,t(e.left));e.right&&(e.right.parent=e,t(e.right))}(this.root);this.metric=e}toJSON(){const t=function t(e){const r=new n(e.obj,e.dimension,null);e.left&&(r.left=t(e.left));e.right&&(r.right=t(e.right));return r}(this.root);return t.dimensions=this.dimensions,t}nearest(t,e,r){const n=this.metric,i=this.dimensions;var s;const a=new o(function(t){return-t[1]});if(r)for(s=0;se&&a.pop()}for(g=0;g0&&(this.content[0]=e,this.sinkDown(0)),t}peek(){return this.content[0]}size(){return this.content.length}bubbleUp(t){for(var e=this.content[t];t>0;){const r=Math.floor((t+1)/2)-1,n=this.content[r];if(!(this.scoreFunction(e)2&&void 0!==arguments[2]?arguments[2]:{};if(!0===t){const t=e;return this.kdTree=new i(t.kdTree,r),this.k=t.k,this.classes=new Set(t.classes),void(this.isEuclidean=t.isEuclidean)}const n=new Set(e),{distance:o=a.a,k:s=n.size+1}=r,h=new Array(t.length);for(var u=0;u1&&void 0!==arguments[1]?arguments[1]:a.a;if("KNN"!==t.name)throw new Error("invalid model: "+t.name);if(!t.isEuclidean&&e===a.a)throw new Error("a custom distance function was used to create the model. Please provide it again");if(t.isEuclidean&&e!==a.a)throw new Error("the model was created with the default distance function. Do not load it with another one");return new h(!0,t,e)}toJSON(){return{name:"KNN",kdTree:this.kdTree,k:this.k,classes:Array.from(this.classes),isEuclidean:this.isEuclidean}}predict(t){if(Array.isArray(t)){if("number"==typeof t[0])return u(this,t);if(Array.isArray(t[0])&&"number"==typeof t[0][0]){const r=new Array(t.length);for(var e=0;eo&&(i=u,o=l)}return i}}])}); //# sourceMappingURL=ml.min.js.map \ No newline at end of file diff --git a/dist/ml.min.js.map b/dist/ml.min.js.map index cba73e9..5bb2f6d 100644 --- a/dist/ml.min.js.map +++ b/dist/ml.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack://ML/webpack/universalModuleDefinition","webpack://ML/webpack/bootstrap","webpack://ML/./node_modules/ml-matrix/src/dc/lu.js","webpack://ML/./node_modules/ml-matrix/src/dc/util.js","webpack://ML/./node_modules/ml-matrix/src/dc/svd.js","webpack://ML/./node_modules/ml-matrix/src/util.js","webpack://ML/./node_modules/ml-matrix/src/views/base.js","webpack://ML/./node_modules/ml-matrix/src/views/transpose.js","webpack://ML/./node_modules/ml-matrix/src/views/row.js","webpack://ML/./node_modules/ml-matrix/src/views/sub.js","webpack://ML/./node_modules/ml-matrix/src/views/selection.js","webpack://ML/./node_modules/ml-matrix/src/views/rowSelection.js","webpack://ML/./node_modules/ml-matrix/src/views/columnSelection.js","webpack://ML/./node_modules/ml-matrix/src/views/column.js","webpack://ML/./node_modules/ml-matrix/src/views/flipRow.js","webpack://ML/./node_modules/ml-matrix/src/views/flipColumn.js","webpack://ML/./node_modules/ml-matrix/src/abstractMatrix.js","webpack://ML/./node_modules/ml-matrix/src/matrix.js","webpack://ML/./node_modules/ml-matrix/src/wrap/WrapperMatrix1D.js","webpack://ML/./node_modules/ml-matrix/src/wrap/WrapperMatrix2D.js","webpack://ML/./node_modules/ml-matrix/src/wrap/wrap.js","webpack://ML/./node_modules/ml-matrix/src/dc/qr.js","webpack://ML/./node_modules/ml-matrix/src/decompositions.js","webpack://ML/./node_modules/ml-matrix/src/linearDependencies.js","webpack://ML/./node_modules/ml-matrix/src/dc/evd.js","webpack://ML/./node_modules/ml-matrix/src/dc/cholesky.js","webpack://ML/./node_modules/ml-matrix/src/index.js","webpack://ML/./node_modules/is-any-array/src/index.js","webpack://ML/./node_modules/ml-distance-euclidean/euclidean.js","webpack://ML/./node_modules/ml-stat/index.js","webpack://ML/./node_modules/ml-stat/matrix.js","webpack://ML/./node_modules/ml-array-mean/lib-es6/index.js","webpack://ML/./node_modules/binary-search/index.js","webpack://ML/./node_modules/num-sort/index.js","webpack://ML/./node_modules/ml-cart/src/utils.js","webpack://ML/./node_modules/ml-cart/src/TreeNode.js","webpack://ML/./node_modules/ml-cart/src/DecisionTreeClassifier.js","webpack://ML/./node_modules/ml-cart/src/DecisionTreeRegression.js","webpack://ML/./node_modules/ml-cart/src/index.js","webpack://ML/./node_modules/ml-array-max/lib-es6/index.js","webpack://ML/./node_modules/ml-kernel/src/kernel.js","webpack://ML/./node_modules/ml-random/lib-es6/choice.js","webpack://ML/./node_modules/ml-random/lib-es6/index.js","webpack://ML/./node_modules/random-js/lib/random.js","webpack://ML/./node_modules/ml-array-rescale/lib-es6/index.js","webpack://ML/./node_modules/ml-hash-table/src/HashTable.js","webpack://ML/./node_modules/ml-hclust/src/Cluster.js","webpack://ML/./node_modules/extend/index.js","webpack://ML/./node_modules/ml-array-min/lib-es6/index.js","webpack://ML/./node_modules/ml-array-median/lib-es6/index.js","webpack://ML/./node_modules/ml-xsadd/lib-es6/xsadd.js","webpack://ML/./node_modules/ml-array-variance/lib-es6/index.js","webpack://ML/./node_modules/ml-stat/array.js","webpack://ML/./node_modules/ml-hclust/src/ClusterLeaf.js","webpack://ML/./node_modules/ml-distance-matrix/src/index.js","webpack://ML/./node_modules/ml-confusion-matrix/src/index.js","webpack://ML/./node_modules/ml-fnn/src/Layer.js","webpack://ML/./node_modules/ml-fnn/src/utils.js","webpack://ML/./node_modules/ml-fnn/src/activationFunctions.js","webpack://ML/./node_modules/ml-som/src/node-square.js","webpack://ML/./node_modules/ml-distance/src/index.js","webpack://ML/./node_modules/ml-distance/src/similarities/czekanowski.js","webpack://ML/./node_modules/ml-distance/src/distances/dice.js","webpack://ML/./node_modules/ml-distance/src/distances/intersection.js","webpack://ML/./node_modules/ml-distance/src/distances/jaccard.js","webpack://ML/./node_modules/ml-distance/src/distances/kulczynski.js","webpack://ML/./node_modules/ml-distance/src/distances/motyka.js","webpack://ML/./node_modules/ml-distance/src/distances/squaredChord.js","webpack://ML/./node_modules/ml-distance/src/similarities/tanimoto.js","webpack://ML/./node_modules/ml-distance/src/similarities/cosine.js","webpack://ML/./node_modules/ml-pad-array/src/index.js","webpack://ML/./node_modules/ml-regression-base/src/maybeToPrecision.js","webpack://ML/./node_modules/ml-regression-base/src/checkArrayLength.js","webpack://ML/./node_modules/ml-regression-base/src/index.js","webpack://ML/./node_modules/ml-regression-simple-linear/src/index.js","webpack://ML/./node_modules/ml-regression-polynomial/src/index.js","webpack://ML/./node_modules/ml-regression-exponential/src/index.js","webpack://ML/./node_modules/ml-regression-power/src/index.js","webpack://ML/./node_modules/ml-regression-multivariate-linear/src/index.js","webpack://ML/./node_modules/ml-regression/src/regression/potential-regression.js","webpack://ML/./node_modules/ml-regression/src/regression/kernel-ridge-regression.js","webpack://ML/./node_modules/ml-regression/src/regression/poly-fit-regression2d.js","webpack://ML/./node_modules/ml-regression-theil-sen/src/index.js","webpack://ML/./node_modules/ml-regression-robust-polynomial/src/index.js","webpack://ML/./node_modules/ml-regression/src/index.js","webpack://ML/./node_modules/median-quickselect/lib/median-quickselect.min.js","webpack://ML/./src/index.js","webpack://ML/./node_modules/ml-pca/src/pca.js","webpack://ML/./node_modules/ml-hclust/src/index.js","webpack://ML/./node_modules/ml-hclust/src/agnes.js","webpack://ML/./node_modules/heap/index.js","webpack://ML/./node_modules/heap/lib/heap.js","webpack://ML/./node_modules/util/util.js","webpack://ML/./node_modules/process/browser.js","webpack://ML/./node_modules/util/support/isBufferBrowser.js","webpack://ML/./node_modules/inherits/inherits_browser.js","webpack://ML/./node_modules/ml-hclust/src/diana.js","webpack://ML/./node_modules/ml-svm/src/svm.js","webpack://ML/./node_modules/ml-kernel-gaussian/gaussian-kernel.js","webpack://ML/./node_modules/ml-kernel-polynomial/polynomial-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/anova-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/cauchy-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/exponential-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/histogram-intersection-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/laplacian-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/multiquadratic-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/rational-quadratic-kernel.js","webpack://ML/./node_modules/ml-kernel-sigmoid/sigmoid-kernel.js","webpack://ML/./node_modules/ml-cross-validation/src/index.js","webpack://ML/./node_modules/ml-combinations/lib/index.js","webpack://ML/./node_modules/ml-fnn/src/FeedForwardNeuralNetwork.js","webpack://ML/./node_modules/ml-fnn/src/OutputLayer.js","webpack://ML/./node_modules/ml-som/src/index.js","webpack://ML/./node_modules/ml-som/src/node-hexagonal.js","webpack://ML/./node_modules/ml-levenberg-marquardt/lib/index.js","webpack://ML/./node_modules/ml-sparse-matrix/src/index.js","webpack://ML/./node_modules/new-array/index.js","webpack://ML/./node_modules/ml-hash-table/src/primeFinder.js","webpack://ML/./node_modules/number-is-nan/index.js","webpack://ML/./node_modules/ml-distance/src/distances.js","webpack://ML/./node_modules/ml-distance/src/distances/additiveSymmetric.js","webpack://ML/./node_modules/ml-distance/src/distances/avg.js","webpack://ML/./node_modules/ml-distance/src/distances/bhattacharyya.js","webpack://ML/./node_modules/ml-distance/src/distances/canberra.js","webpack://ML/./node_modules/ml-distance/src/distances/chebyshev.js","webpack://ML/./node_modules/ml-distance/src/distances/clark.js","webpack://ML/./node_modules/ml-distance/src/distances/czekanowski.js","webpack://ML/./node_modules/ml-distance/src/distances/divergence.js","webpack://ML/./node_modules/ml-distance/src/distances/fidelity.js","webpack://ML/./node_modules/ml-distance/src/distances/gower.js","webpack://ML/./node_modules/ml-distance/src/distances/harmonicMean.js","webpack://ML/./node_modules/ml-distance/src/distances/hellinger.js","webpack://ML/./node_modules/ml-distance/src/distances/innerProduct.js","webpack://ML/./node_modules/ml-distance/src/distances/jeffreys.js","webpack://ML/./node_modules/ml-distance/src/distances/jensenDifference.js","webpack://ML/./node_modules/ml-distance/src/distances/jensenShannon.js","webpack://ML/./node_modules/ml-distance/src/distances/kdivergence.js","webpack://ML/./node_modules/ml-distance/src/distances/kullbackLeibler.js","webpack://ML/./node_modules/ml-distance/src/distances/kumarHassebrook.js","webpack://ML/./node_modules/ml-distance/src/distances/kumarJohnson.js","webpack://ML/./node_modules/ml-distance/src/distances/lorentzian.js","webpack://ML/./node_modules/ml-distance/src/distances/manhattan.js","webpack://ML/./node_modules/ml-distance/src/distances/matusita.js","webpack://ML/./node_modules/ml-distance/src/distances/minkowski.js","webpack://ML/./node_modules/ml-distance/src/distances/neyman.js","webpack://ML/./node_modules/ml-distance/src/distances/pearson.js","webpack://ML/./node_modules/ml-distance/src/distances/probabilisticSymmetric.js","webpack://ML/./node_modules/ml-distance/src/distances/ruzicka.js","webpack://ML/./node_modules/ml-distance/src/distances/soergel.js","webpack://ML/./node_modules/ml-distance/src/distances/sorensen.js","webpack://ML/./node_modules/ml-distance/src/distances/squared.js","webpack://ML/./node_modules/ml-distance/src/distances/taneja.js","webpack://ML/./node_modules/ml-distance/src/distances/tanimoto.js","webpack://ML/./node_modules/ml-distance/src/distances/topsoe.js","webpack://ML/./node_modules/ml-tree-similarity/src/index.js","webpack://ML/./node_modules/ml-distance/src/distances/waveHedges.js","webpack://ML/./node_modules/ml-distance/src/similarities.js","webpack://ML/./node_modules/ml-distance/src/similarities/dice.js","webpack://ML/./node_modules/ml-distance/src/similarities/intersection.js","webpack://ML/./node_modules/ml-distance/src/similarities/jaccard.js","webpack://ML/./node_modules/ml-distance/src/similarities/kulczynski.js","webpack://ML/./node_modules/ml-distance/src/similarities/motyka.js","webpack://ML/./node_modules/ml-distance/src/similarities/pearson.js","webpack://ML/./node_modules/ml-distance/src/similarities/squaredChord.js","webpack://ML/./node_modules/ml-performance/src/index.js","webpack://ML/./node_modules/ml-performance/src/measures.js","webpack://ML/./node_modules/ml-savitzky-golay/src/index.js","webpack://ML/./node_modules/ml-savitzky-golay-generalized/src/index.js","webpack://ML/./node_modules/ml-bit-array/src/index.js","webpack://ML/./node_modules/ml-bit-array/src/creator.js","webpack://ML/./node_modules/ml-array-utils/src/index.js","webpack://ML/./node_modules/ml-array-utils/src/ArrayUtils.js","webpack://ML/./node_modules/ml-array-utils/src/getEquallySpaced.js","webpack://ML/./node_modules/ml-array-utils/src/snv.js","webpack://ML/./node_modules/ml-array-mode/lib-es6/index.js","webpack://ML/./node_modules/ml-array-normed/lib-es6/index.js","webpack://ML/./node_modules/ml-array-sequential-fill/lib-es6/index.js","webpack://ML/./node_modules/ml-array-standard-deviation/lib-es6/index.js","webpack://ML/./node_modules/ml-array-xy-centroids-merge/src/index.js","webpack://ML/./node_modules/ml-arrayxy-closestx/src/index.js","webpack://ML/./node_modules/ml-array-xy-max-merge/src/index.js","webpack://ML/./node_modules/ml-array-xy-max-y/src/index.js","webpack://ML/./node_modules/ml-array-xy-sort-x/src/index.js","webpack://ML/./node_modules/ml-arrayxy-uniquex/src/index.js","webpack://ML/./node_modules/ml-array-xy-weighted-merge/src/index.js","webpack://ML/./node_modules/ml-kmeans/node_modules/ml-distance-euclidean/lib-es6/euclidean.js","webpack://ML/./node_modules/ml-nearest-vector/node_modules/ml-distance-euclidean/lib-es6/euclidean.js","webpack://ML/./node_modules/ml-nearest-vector/lib-es6/index.js","webpack://ML/./node_modules/ml-kmeans/src/utils.js","webpack://ML/./node_modules/ml-kmeans/src/initialization.js","webpack://ML/./node_modules/ml-kmeans/src/KMeansResult.js","webpack://ML/./node_modules/ml-kmeans/src/kmeans.js","webpack://ML/./node_modules/ml-random-forest/src/utils.js","webpack://ML/./node_modules/ml-random-forest/src/RandomForestBase.js","webpack://ML/./node_modules/ml-random-forest/src/RandomForestClassifier.js","webpack://ML/./node_modules/ml-random-forest/src/RandomForestRegression.js","webpack://ML/./node_modules/ml-random-forest/src/index.js","webpack://ML/./node_modules/ml-pls/src/utils.js","webpack://ML/./node_modules/ml-pls/src/pls.js","webpack://ML/./node_modules/ml-pls/src/kopls.js","webpack://ML/./node_modules/ml-pls/src/index.js","webpack://ML/./node_modules/ml-naivebayes/src/utils.js","webpack://ML/./node_modules/ml-naivebayes/src/GaussianNB.js","webpack://ML/./node_modules/ml-naivebayes/src/MultinomialNB.js","webpack://ML/./node_modules/ml-naivebayes/src/index.js","webpack://ML/./node_modules/ml-knn/src/KDTree.js","webpack://ML/./node_modules/ml-knn/src/index.js"],"names":["root","factory","exports","module","define","amd","self","this","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","LuDecomposition","constructor","matrix","j","k","v","LUcolj","kmax","lu","WrapperMatrix2D","checkMatrix","clone","rows","columns","pivotVector","Array","pivotSign","Math","min","set","abs","LU","isSingular","data","col","solve","Matrix","Error","count","X","subMatrixRow","determinant","isSquare","lowerTriangularMatrix","upperTriangularMatrix","pivotPermutationVector","slice","hypotenuse","a","b","sqrt","getFilled2DArray","array","SingularValueDecomposition","options","arguments","length","undefined","_options$computeLeftS","computeLeftSingularVectors","_options$computeRight","computeRightSingularVectors","_options$autoTranspos","autoTranspose","wantu","Boolean","wantv","swapped","transpose","aux","console","warn","nu","ni","U","V","e","work","si","nct","nrt","max","mrc","pp","eps","Number","EPSILON","kase","alpha","MIN_VALUE","isNaN","ks","f","cs","sn","scale","sp","spm1","epm1","sk","ek","shift","g","tmp","Y","threshold","scols","Ls","zeros","rightSingularVectors","VL","mmul","vrows","urows","VLU","sum","solveForDiagonal","diag","inverse","vcols","ucols","condition","norm2","rank","tol","ii","diagonal","leftSingularVectors","isMatrix","diagonalMatrix","checkRowIndex","index","outer","RangeError","checkColumnIndex","checkRowVector","vector","to1DArray","checkColumnVector","checkIndices","rowIndices","columnIndices","row","checkRowIndices","column","checkColumnIndices","TypeError","some","isArray","from","checkRange","startRow","endRow","startColumn","endColumn","checkNumber","concat","BaseView","AbstractMatrix","super","static","species","MatrixTransposeView","rowIndex","columnIndex","MatrixRowView","MatrixSubView","MatrixSelectionView","indices","MatrixRowSelectionView","MatrixColumnSelectionView","MatrixColumnView","MatrixFlipRowView","MatrixFlipColumnView","superCtor","[object Object]","newRows","newColumns","newData","newMatrix","empty","fill","rng","random","maxValue","floor","matrix1","matrix2","result","klass","size","apply","callback","jj","to2DArray","copy","isRowVector","isColumnVector","isVector","isSymmetric","isEchelonForm","previousColumn","checked","isReducedEchelonForm","repeat","rowRep","colRep","setSubMatrix","neg","mulS","getRow","getRowVector","rowVector","setRow","swapRows","row1","row2","temp","getColumn","getColumnVector","columnVector","setColumn","swapColumns","column1","column2","addRowVector","subRowVector","mulRowVector","divRowVector","addColumnVector","subColumnVector","mulColumnVector","divColumnVector","mulRow","mulColumn","maxIndex","idx","minIndex","maxRow","maxRowIndex","minRow","minRowIndex","maxColumn","maxColumnIndex","minColumn","minColumnIndex","by","sumByRow","sumByColumn","sumAll","mean","prod","norm","type","cumulativeSum","dot","vector2","vector1","other","Bcolj","strassen2x2","a11","b11","a12","b12","a21","b21","a22","b22","m1","m2","m3","m4","m5","c00","c01","c10","c11","strassen3x3","a00","a01","a02","a10","a20","b00","b01","b02","b10","b20","m6","m7","m8","m9","m12","m13","m14","m15","m16","m17","m18","c02","c12","c20","c21","c22","mmulStrassen","y","x","r1","c1","r2","c2","embed","mat","cols","resultat","blockMult","halfRows","parseInt","halfCols","subMatrix","add","sub","scaleRows","scaled","rescale","scaleColumns","kroneckerProduct","q","sortRows","compareFunction","compareNumbers","sort","sortColumns","subMatrixColumn","selection","trace","transposeView","rowView","columnView","flipRowView","flipColumnView","subMatrixView","selectionView","rowSelectionView","columnSelectionView","det","subMatrix0","subMatrix1","subMatrix2","pseudoInverse","svdSolution","SvDecomposition","rand","identity","eye","negate","tensorProduct","staticMethodWithArgs","eval2","eval","operator","inplaceOp","fillTemplateFunction","op","inplaceOpS","inplaceOpM","staticOp","methods","method","forEach","mathMethod","push","inplaceMeth","staticMeth","methodWithArg","args","inplaceMethWithArgs","staticMethWithArgs","tmplVar","inplaceMethod2","inplaceMethodS","inplaceMethodM","staticMethod2","template","values","replace","RegExp","nRows","nColumns","isInteger","removeRow","splice","addRow","removeColumn","addColumn","WrapperMatrix1D","_options$rows","_calculateIndex","wrap","QrDecomposition","qr","rdiag","nrm","QR","Rdiag","isFullRank","orthogonalMatrix","useSVD","leftHandSide","rightHandSide","xrange","exception","range","dependenciesOneRow","error","thresholdValue","returnArray","linearDependencies","_options$thresholdVal","_options$thresholdErr","thresholdError","results","Abis","EigenvalueDecomposition","_options$assumeSymmet","assumeSymmetric","h","hh","tred2","dl1","c3","el1","s2","tst1","tql2","H","ort","high","low","orthes","nn","w","ra","sa","vr","vi","notlast","cdivres","exshift","z","iter","cdiv","hqr2","realEigenvalues","imaginaryEigenvalues","eigenvectorMatrix","xr","xi","yr","yi","CholeskyDecomposition","dimension","positiveDefinite","Lrowj","Lrowk","L","B","__webpack_exports__","matrix_Matrix","WrapperMatrix2D_WrapperMatrix2D","WrapperMatrix1D_WrapperMatrix1D","svd_SingularValueDecomposition","evd_EigenvalueDecomposition","cholesky_CholeskyDecomposition","lu_LuDecomposition","qr_QrDecomposition","toString","endsWith","squaredEuclidean","euclidean","squared","require","arrayStat","Infinity","minMax","entropy","l1","l2","log","theMean","N","theSum","product","theProduct","standardDeviation","means","unbiased","vari","variance","sum1","sum2","median","medians","modes","itemCount","itemArray","indexOf","skewness","skew","s3","dev","pow","kurtosis","kurt","s4","standardError","samples","standardDeviations","standardErrors","sqrtN","covariance","scatter","divisor","cov","correlation","scores","zScores","cor","standardize","center","inPlace","resultRow","sourceRow","weightedVariance","weights","weightedMean","weightSum","weightedCovariance","s1","factor","weightedScatter","is_any_array__WEBPACK_IMPORTED_MODULE_0__","is_any_array__WEBPACK_IMPORTED_MODULE_0___default","input","haystack","needle","comparator","mid","cmp","numberIsNan","assertNum","asc","desc","toDiscreteDistribution","numberOfClasses","counts","giniImpurity","probabilities","getNumberOfClasses","filter","val","arr","squaredError","meanArray","currentElement","gainFunctions","gini","splitted","splitsImpurity","splits","currentSplit","regression","splitFunctions","TreeNode","kind","gainFunction","splitFunction","minNumSamples","maxDepth","bestSplit","XTranspose","bestGain","check","currentFeature","splitValues","featureSplit","currentSplitVal","split","gain","maxGain","splitValue","lesser","greater","ret","Utils","calculatePrediction","distribution","train","currentDepth","parentGain","splitColumn","splittedMatrix","lesserX","greaterX","lesserY","greaterY","left","right","classify","setNodeParameters","node","defaultOptions","DecisionTreeClassifier","model","Tree","assign","trainingSet","trainingLabels","predict","toPredict","predictions","toJSON","DecisionTreeRegression","trainingValues","DecisionTreeClassifier_DecisionTreeClassifier","DecisionTreeRegression_DecisionTreeRegression","GaussianKernel","PolynomialKernel","ANOVAKernel","CauchyKernel","ExponentialKernel","HistogramKernel","LaplacianKernel","MultiquadraticKernel","RationalKernel","SigmoidKernel","kernelType","gaussian","rbf","polynomial","poly","anova","cauchy","exponential","histogram","laplacian","multiquadratic","rational","sigmoid","mlp","toLowerCase","KernelConstructor","kernelFunction","compute","inputs","landmarks","kernelMatrix","PROB_TOLERANCE","randomIndex","cumSum","randomChoice","_options$size","_options$replace","valuesArr","getArray","lib_es6_Random","Random","seedOrRandom","xsadd","XSAdd","randomGenerator","choice","randInt","randomSample","__WEBPACK_AMD_DEFINE_RESULT__","imul","al","bl","stringRepeat","String","pattern","engine","engines","nativeMath","proto","returnValue","generate","addend","toInteger","number","ceil","convertSliceArgument","returnUndefined","mt19937","Int32Array","refreshData","uses","next","temper","getUseCount","discard","seed","initial","previous","seedWithArray","source","sourceLength","autoSeed","generateEntropyArray","browserCrypto","crypto","getRandomValues","Date","getTime","int32","uint32","uint53","uint53Full","int53","int53Full","integer","isPowerOfTwoMinusOne","downscaleToRange","masking","extendedRange","maximum","downscaleToLoopCheckedRange","upscaleWithinU53","highRange","upscaleToLoopCheckedRange","upscaleWithinI53AndLoopCheck","isFinite","realZeroToOneInclusive","realZeroToOneExclusive","real","inclusive","multiplier","bool","isLeastBitTrue","lessThan","numerator","denominator","percentage","round","probability","pick","begin","end","start","finish","lowerHex","upperHex","picker","shuffle","downTo","sample","population","sampleSize","tailLength","die","sideCount","dice","dieCount","uuid4","zeroPad","string","zeroCount","pool","charAt","hex","toUpperCase","upper","date","ml_array_max__WEBPACK_IMPORTED_MODULE_0__","ml_array_min__WEBPACK_IMPORTED_MODULE_1__","is_any_array__WEBPACK_IMPORTED_MODULE_2__","is_any_array__WEBPACK_IMPORTED_MODULE_2___default","output","currentMin","currentMax","_options$min","minValue","autoMinMax","_options$max","newArray","primeFinder","nextPrime","largestPrime","FREE","FULL","REMOVED","defaultInitialCapacity","defaultMinLoadFactor","defaultMaxLoadFactor","HashTable","table","state","minLoadFactor","maxLoadFactor","distinct","freeEntries","lowWaterMark","highWaterMark","initialCapacity","capacity","chooseHighWaterMark","indexOfKey","indexOfInsertion","newCapacity","chooseGrowCapacity","rehash","remove","noRehash","maybeShrinkCapacity","delete","minLoad","maxLoad","containsKey","hash","decrement","containsValue","indexOfValue","ensureCapacity","minCapacity","oldCapacity","oldTable","oldValues","oldState","newTable","newValues","newState","element","forEachKey","forEachValue","forEachPair","Heap","Cluster","children","distance","cut","list","ans","group","minGroups","heap","first","pop","child","toArray","traverse","cb","visit","hasOwn","toStr","gOPD","getOwnPropertyDescriptor","isPlainObject","obj","hasOwnConstructor","hasIsPrototypeOf","setProperty","target","configurable","newValue","writable","getProperty","extend","src","copyIsArray","deep","median_quickselect__WEBPACK_IMPORTED_MODULE_0__","median_quickselect__WEBPACK_IMPORTED_MODULE_0___default","is_any_array__WEBPACK_IMPORTED_MODULE_1__","is_any_array__WEBPACK_IMPORTED_MODULE_1___default","quickSelectMedian","XSadd","LOOP","FLOAT_MUL","sh1","sh2","sh3","multiply_uint32","nlo","now","Uint32Array","init","getFloat","getUint32","nextState","periodCertification","ml_array_mean__WEBPACK_IMPORTED_MODULE_0__","_options$unbiased","_options$mean","arrayMean","sqrError","arithmeticMean","geometricMean","mul","logMean","lnsum","grandMean","truncatedMean","percent","alreadySorted","harmonicMean","contraHarmonicMean","half","theVariance","robustMeanAndStdev","averageDeviations","stdev","quartiles","quart","q1","q2","q3","pooledStandardDeviation","pooledVariance","mean1","mean2","weightedStandardDeviation","standardDev","ClusterLeaf","inherits","distanceFn","map","ConfusionMatrix","labels","actual","predicted","distinctLabels","Set","actualIdx","predictedIdx","getMatrix","getLabels","getTotalCount","getTrueCount","getFalseCount","getTruePositiveCount","label","getIndex","getTrueNegativeCount","getFalsePositiveCount","getFalseNegativeCount","getPositiveCount","getNegativeCount","getTruePositiveRate","getTrueNegativeRate","getPositivePredictiveValue","TP","getNegativePredictiveValue","TN","getFalseNegativeRate","getFalsePositiveRate","getFalseDiscoveryRate","FP","getFalseOmissionRate","FN","getF1Score","getMatthewsCorrelationCoefficient","getInformedness","getMarkedness","getConfusionTable","getAccuracy","correct","incorrect","getCount","actualIndex","predictedIndex","accuracy","total","ACTIVATION_FUNCTIONS","Layer","inputSize","outputSize","regularization","epsilon","activation","activationParam","selectedFunction","params","actFunction","derFunction","derivate","activationFunction","W","forward","backpropagation","delta","dW","db","sumCol","aCopy","update","dictOutputs","outputs","sumRow","logistic","exp","expELU","param","tanh","arctan","atan","softsign","relu","softplus","bent","sinusoid","sin","cos","sinc","parametric-relu","exponential-elu","soft-exponential","NodeSquare","som","neighbors","adjustWeights","learningRate","influence","getDistance","otherNode","getDistanceTorus","distX","distY","gridDim","getNeighbors","xy","torus","nodes","getPos","bestNeighbor","direction","simA","simB","getPosition","similarity","up","down","p1","p2","bitvector","inter","union","matrixCase","len","cond","arrayCase","maybeToPrecision","digits","toPrecision","checkArraySize","BaseRegression","_predict","toLaTeX","score","y2","xSum","ySum","chi2","rmsd","xSquared","ySquared","xY","SimpleLinearRegression","slope","intercept","coefficients","checkArrayLength","slr","regress","computeX","precision","xFactor","absIntercept","json","PolynomialRegression","degree","powers","pr","F","FT","A","_toFormula","isLaTeX","sup","closeSup","times","fn","str","ExponentialRegression","er","yl","linear","PowerRegression","xl","newInputs","MultivariateLinearRegression","_options$intercept","_options$statistics","statistics","beta","SVD","fittedValues","addM","ri","reduce","stdError","stdErrorMatrix","stdErrors","tStats","summary","regressionStatistics","observations","variables","tStat","PotentialRegression","M","lambda","kernelOptions","computeCoefficient","KernelRidgeRegression","kernel","Kernel","K","order","PolynomialFitRegression2D","examples","x1","x2","scaleX1","scaleX2","scaleY","limit","powColVector","svd","qqs","qqs1","power","TheilSenRegression","slopes","medianSlope","cuts","theilSen","RobustPolynomialRegression","tuples","pos","counter","getRandomTuples","tuple","calcCoefficients","residuals","residual","residualsMedian","robustPolynomial","NLR","src_SimpleLinearRegression","src_PolynomialRegression","src_ExponentialRegression","src_PowerRegression","src_MultivariateLinearRegression","kernel_ridge_regression_KernelRidgeRegression","poly_fit_regression2d_PolynomialFitRegression2D","src_TheilSenRegression","src_RobustPolynomialRegression","_ref","window","mlCart","mlRandomForest","ML","PCA","HClust","KMeans","SVM","NaiveBayes","KNN","PLS","CrossValidation","RandomForestClassifier","FNN","SOM","Regression","RandomForestRegression","levenbergMarquardt","EVD","SparseMatrix","Distance","Similarity","distanceMatrix","default","Performance","savitzkyGolay","savitzkyGolayGeneralized","BitArray","padArray","binarySearch","numSort","ArrayUtils","MatrixUtil","ArrayStat","MatrixStat","normed","sequentialFill","ArrayXY","centroidsMerge","closestX","maxMerge","maxY","sortX","uniqueX","weightedMerge","matrixLib","Stat","isCovarianceMatrix","dataset","stdevs","S","_computeFromCovarianceMatrix","useCovarianceMatrix","covarianceMatrix","_adjust","div","singularValues","eigenvalues","_options$nComponents","nComponents","getExplainedVariance","getCumulativeVariance","explained","getEigenvectors","getEigenvalues","getStandardDeviations","getLoadings","evd","reverse","agnes","diana","simpleLink","cluster1","cluster2","disFun","completeLink","averageLink","centroidLink","dist","wardLink","disFunc","isDistanceMatrix","dis","fdistance","sdistance","toFixed","dmin","clustered","diff","indCount","__WEBPACK_AMD_DEFINE_FACTORY__","__WEBPACK_AMD_DEFINE_ARRAY__","defaultCmp","heapify","heappop","heappush","heappushpop","heapreplace","insort","nlargest","nsmallest","updateItem","_siftdown","_siftup","lo","hi","item","lastelt","returnitem","_i","_len","_ref1","_results","_results1","_j","elem","los","startpos","newitem","parent","parentpos","childpos","endpos","rightpos","pushpop","peek","contains","clear","insert","top","front","has","process","getOwnPropertyDescriptors","keys","descriptors","formatRegExp","format","isString","objects","inspect","join","JSON","stringify","_","isNull","isObject","deprecate","msg","noDeprecation","warned","throwDeprecation","traceDeprecation","debugEnviron","debugs","opts","ctx","seen","stylize","stylizeNoColor","depth","colors","isBoolean","showHidden","_extend","isUndefined","customInspect","stylizeWithColor","formatValue","styleType","style","styles","recurseTimes","isFunction","primitive","simple","isNumber","formatPrimitive","visibleKeys","arrayToHash","getOwnPropertyNames","isError","formatError","isRegExp","isDate","base","braces","toUTCString","formatProperty","match","formatArray","prev","cur","numLinesEst","reduceToSingleString","line","substr","ar","arg","re","objectToString","pad","debuglog","env","NODE_DEBUG","test","pid","bold","italic","underline","white","grey","black","blue","cyan","green","magenta","red","yellow","special","boolean","null","regexp","isNullOrUndefined","isSymbol","isPrimitive","isBuffer","months","prop","time","getHours","getMinutes","getSeconds","getDate","getMonth","origin","kCustomPromisifiedSymbol","callbackifyOnRejected","reason","newReason","promisify","original","promiseResolve","promiseReject","promise","Promise","resolve","reject","err","setPrototypeOf","getPrototypeOf","defineProperties","custom","callbackify","callbackified","maybeCb","then","nextTick","rej","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","setTimeout","clearTimeout","currentQueue","queue","draining","queueIndex","cleanUpNextTick","drainQueue","timeout","run","marker","runClearTimeout","Item","noop","title","browser","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","readUInt8","ctor","super_","TempCtor","y1","splitting","Ci","ndist","Cj","intrDist","clId","rebel","tree","ind","C","sG","spl","fData","sData","stat","maxPasses","maxIterations","alphaTol","whitening","features","_trained","_loaded","D","alphas","b1","b2","passes","Ei","Ej","ai","aj","eta","numChange","_marginOnePrecomputed","newaj","iterations","nX","nY","nAlphas","_supportVectorIdx","predictOne","marginOne","noWhitening","_applyWhitening","margin","supportVectors","load","svm","whitened","sigma","constant","E","CV","combinations","initMatrix","getDistinct","validate","Classifier","classifierOptions","testIdx","trainIdx","confusionMatrix","_getTrainTest","getTrainTest","testFeatures","trainFeatures","testLabels","trainLabels","classifier","updateConfusionMatrix","validateWithCallback","_getTrainTest2","predictedLabels","leaveOneOut","leavePOut","gen","allIdx","kFold","current","folds","randi","runtime","createCommonjsModule","global","Op","$Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","regeneratorRuntime","GenStateSuspendedStart","GenStateSuspendedYield","GenStateExecuting","GenStateCompleted","ContinueSentinel","IteratorPrototype","getProto","NativeIteratorPrototype","Gp","GeneratorFunctionPrototype","Generator","GeneratorFunction","displayName","isGeneratorFunction","genFun","mark","__proto__","awrap","__await","defineIteratorMethods","AsyncIterator","async","innerFn","outerFn","tryLocsList","done","Context","reset","skipTempReset","sent","_sent","delegate","tryEntries","resetTryEntry","stop","rootEntry","rootRecord","completion","rval","dispatchException","context","handle","loc","caught","record","entry","tryLoc","hasCatch","hasFinally","catchLoc","finallyLoc","abrupt","finallyEntry","complete","afterLoc","catch","thrown","delegateYield","iterable","resultName","nextLoc","protoGenerator","generator","_invoke","doneResult","delegateResult","maybeInvokeDelegate","tryCatch","makeInvokeMethod","previousPromise","callInvokeWithMethodAndArg","invoke","unwrapped","return","info","pushTryEntry","locs","iteratorMethod","Function","hadRuntime","oldRuntime","runtimeModule","regenerator","_callee","twiddle","_context","OutputLayer","FeedForwardNeuralNetworks","hiddenLayers","dicts","layers","buildNetwork","propagate","NodeHexagonal","fields","randomizer","squareEuclidean","gridType","reload","numWeights","converters","getConverters","extractor","creator","nodeType","hx","distanceMethod","maxDistance","getMaxDistance","findBMU","adjust","iterationCount","startLearningRate","mapRadius","algorithmMethod","_initNodes","normalizers","denormalizers","getNormalizer","getDenormalizer","getRandomValue","zero","one","loadModel","export","includeDistance","initNodes","setTraining","convertedSet","numIterations","timeConstant","trainOne","neighbourhoodRadius","trainingValue","trainingSetFactor","bmu","_findBestMatchingUnit","now2","radiusLimit","xMin","xMax","yMin","yMax","theX","theY","getConvertedNodes","candidate","lowest","computePosition","getQuantizationError","fit","getFit","hX","distZ","mlMatrix","errorCalculation","parameters","parameterizedFunction","func","step","damping","gradientDifference","evaluatedData","gradientFunc","paramFunction","auxParams","funcParam","point","gradientFunction","matrixFunc","matrixFunction","inverseMatrix","_options$maxIteration","_options$gradientDiff","_options$damping","_options$errorToleran","errorTolerance","initialValues","converged","iteration","parameterValues","parameterError","ml_hash_table__WEBPACK_IMPORTED_MODULE_0__","ml_hash_table__WEBPACK_IMPORTED_MODULE_0___default","_init","elements","symmetric","forEachNonZero","bandWidth","isBanded","width","cardinality","v1","v2","getNonZeros","setThreshold","newThreshold","trans","inplaceOperator","inplaceOperatorScalar","inplaceOperatorMatrix","staticOperator","inplaceMethod","staticMethod","operators","sortAsc","primeNumbers","additiveSymmetric","avg","bhattacharyya","canberra","chebyshev","clark","czekanowski","divergence","fidelity","gower","hellinger","innerProduct","intersection","jaccard","jeffreys","jensenDifference","jensenShannon","kdivergence","kulczynski","kullbackLeibler","kumarHassebrook","kumarJohnson","lorentzian","manhattan","matusita","minkowski","motyka","neyman","pearson","probabilisticSymmetric","ruzicka","soergel","sorensen","squaredChord","taneja","tanimoto","topsoe","waveHedges","czekanowskiSimilarity","tanimotoS","createTree","to","minWindow","gamma","calc","cosine","diceD","intersectionD","jaccardD","kulczynskiD","motykaD","avgA","avgB","newA","newB","squaredChordD","measures","prediction","isDistance","predP","all","pred","targ","cutoffs","MAX_VALUE","fp","tp","nPos","nNeg","currentPred","nTp","nFp","tn","nPosPred","nNegPred","nSamples","getMeasure","measure","getAURC","auc","getAUDC","getDistribution","cutLength","cutLow","cutHigh","interval","xLabels","interValues","intraValues","interCumPercent","intraCumPercent","nTP","currentTP","nFP","currentFP","thisTP","thisFP","names","acc","fpr","tpr","fnr","tnr","ppv","npv","pcfall","pcmiss","lift","rpp","rnp","windowSize","derivative","padValue","J","ones","inic","Jtranspose","getHs","hs","GramPoly","GenFact","gf","Weight","np","fullWeights","constantH","wg1","wg2","d1","d2","wg","eightBits","toBinaryString","and","arr1","arr2","or","xor","not","getBit","mask","setBit","parseBinaryString","toHexString","parseHexString","toDebug","binary","num","getEquallySpacedData","SNV","resultMatrix","coordArrayToPoints","dimensions","pointsArr","coordArrayToCoordMatrix","coordinatesArray","points","currentPoint","coordMatrixToCoordArray","coordMatrix","coodinatesArray","coordMatrixToPoints","pointsToCoordArray","pointsToCoordMatrix","applyDotProduct","firstVector","secondVector","largestVector","smallestVector","difference","dotProductApplied","integral","x0","xLength","_options$from","_options$to","_options$variant","variant","_options$numberOfPoin","numberOfPoints","halfStep","lastStep","previousX","previousY","nextX","nextY","frontOutsideSpectra","backOutsideSpectra","currentValue","currentPoints","main","getEquallySpacedSlot","initialOriginalStep","lastOriginalStep","sumAtMin","sumAtMax","getEquallySpacedSmooth","std","maxCount","_options$algorithm","algorithm","absoluteSum","_typeof","_options","ml_array_variance__WEBPACK_IMPORTED_MODULE_0__","mergeByCentroids","originalPoints","centroids","_options$window","mergedPoints","originalIndex","mergedIndex","binary_search__WEBPACK_IMPORTED_MODULE_0__","binary_search__WEBPACK_IMPORTED_MODULE_0___default","num_sort__WEBPACK_IMPORTED_MODULE_1__","_options$target","_options$reverse","_options$groupWidth","groupWidth","merged","maxAbscissa","calculateIndex","currentIndex","sortFunc","grouped","response","weightedAbscissa","distanceFunction","nearestVector","listVectors","similarityFunction","vectorIndex","maxSim","sim","minDist","updateClusterID","centers","clusterID","euclidianDistances","distanceSymbol","KMeansResult","clusters","nearest","centroid","computeInformation","enrichedCentroids","kmeans","tolerance","withIterations","initialization","newCenters","prevCenters","nDim","centersLen","dim","id","updateCenters","oldCenters","hasConverged","localTrials","firstCenterIdx","closestDistSquared","cumSumClosestDistSquared","candidateIdx","distanceToCandidates","bestCandidate","bestPot","bestDistSquared","newDistSquared","newPot","kmeanspp","maxDist","minDistCent","mostDistant","calculateDistanceMatrix","stepResult","stepNumber","kmeansGenerator","examplesBaggingWithReplacement","Xr","featureBagging","replacement","toRet","usedIndex","RandomForestBase","maxFeatures","nEstimators","treeOptions","isClassifier","indexes","useSampleBagging","Estimator","DTClassifier","DTRegression","estimators","est","res","predictionValues","baseModel","selectionMethods","arrayMedian","selectionMethod","RandomForestClassifier_RandomForestClassifier","RandomForestRegression_RandomForestRegression","pow2array","initializeMatrices","meanX","stdDevX","meanY","stdDevY","PBQ","R2X","scaleMethod","_options$tolerance","_options$scale","latentVectors","rx","cx","ry","cy","ssqXcal","sumOfSquaresY","T","P","Q","transposeX","transposeY","tIndex","maxSumColIndex","mulM","uIndex","t1","u","den","pnorm","ssqYcal","KOPLS","YLoadingMat","SigmaPow","YScoreMat","predScoreMat","YOrthLoadingVec","YOrthEigen","YOrthScoreMat","toNorm","TURegressionCoeff","kernelX","orthogonalComp","predictiveComp","predictiveComponents","orthogonalComponents","Identity","Sigma","YOrthScoreNorm","TpiPrime","CoTemp","SoTemp","toiPrime","ITo","lastScoreMat","lastTpPrime","KTestTrain","YOrthScoreVector","scoreMatPrime","p3","predYOrthVectors","pls_PLS","kopls_KOPLS","separateClasses","classes","totalPerClasses","separatedClasses","GaussianNB","calculateProbabilities","C1","PI","logPriorProbability","currentStd","getCurrentClass","modelName","currentCase","maxProbability","predictedClass","currentProbability","calculateLogProbability","C2","MultinomialNB","conditionalProbability","priorProbability","separateClass","classValues","matrixLog","GaussianNB_GaussianNB","MultinomialNB_MultinomialNB","Node","KDTree","metric","buildTree","restoreParent","toJSONImpl","dest","maxNodes","bestNodes","BinaryHeap","nearestSearch","ownDistance","linearPoint","bestChild","linearDistance","otherChild","saveNode","content","scoreFunction","bubbleUp","sinkDown","parentN","elemScore","child2N","child1N","swap","child1","child1Score","child2","src_KNN","kdTree","isEuclidean","_options$distance","euclideanDistance","_options$k","getSinglePrediction","knn","nearestPoints","pointsPerClass","maxPoints","lastElement","currentClass"],"mappings":"CAAA,SAAAA,EAAAC,GACA,iBA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tL,QAAQ0I,EAAakD,EAAI5oE,GACpD8oE,EAAiB,GACjBlD,GAAkB,EAClBmD,GAAa,EACbC,EAAcH,EAAc,GAAG,GAAGnmE,OAAS,EAE/C,IAAK,IAAIwwB,KAAW01C,EAAI7D,QACpB+D,EAAe51C,GAAW,EAG9B,IAAK,IAAIt1B,EAAI,EAAGA,EAAIirE,EAAcnmE,SAAU9E,EAAG,CAC3C,IAAIqrE,EAAeJ,EAAcjrE,GAAG,GAAGorE,GACnCrP,IAAkBmP,EAAeG,GACjCtP,EAAgBoP,IAChBnD,EAAiBqD,EACjBF,EAAYpP,GAIpB,OAAOiM","file":"ml.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"ML\"] = factory();\n\telse\n\t\troot[\"ML\"] = factory();\n})(typeof self !== 'undefined' ? self : this, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 42);\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\n/**\r\n * @class LuDecomposition\r\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs\r\n * @param {Matrix} matrix\r\n */\r\nexport default class LuDecomposition {\r\n constructor(matrix) {\r\n matrix = WrapperMatrix2D.checkMatrix(matrix);\r\n\r\n var lu = matrix.clone();\r\n var rows = lu.rows;\r\n var columns = lu.columns;\r\n var pivotVector = new Array(rows);\r\n var pivotSign = 1;\r\n var i, j, k, p, s, t, v;\r\n var LUcolj, kmax;\r\n\r\n for (i = 0; i < rows; i++) {\r\n pivotVector[i] = i;\r\n }\r\n\r\n LUcolj = new Array(rows);\r\n\r\n for (j = 0; j < columns; j++) {\r\n for (i = 0; i < rows; i++) {\r\n LUcolj[i] = lu.get(i, j);\r\n }\r\n\r\n for (i = 0; i < rows; i++) {\r\n kmax = Math.min(i, j);\r\n s = 0;\r\n for (k = 0; k < kmax; k++) {\r\n s += lu.get(i, k) * LUcolj[k];\r\n }\r\n LUcolj[i] -= s;\r\n lu.set(i, j, LUcolj[i]);\r\n }\r\n\r\n p = j;\r\n for (i = j + 1; i < rows; i++) {\r\n if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) {\r\n p = i;\r\n }\r\n }\r\n\r\n if (p !== j) {\r\n for (k = 0; k < columns; k++) {\r\n t = lu.get(p, k);\r\n lu.set(p, k, lu.get(j, k));\r\n lu.set(j, k, t);\r\n }\r\n\r\n v = pivotVector[p];\r\n pivotVector[p] = pivotVector[j];\r\n pivotVector[j] = v;\r\n\r\n pivotSign = -pivotSign;\r\n }\r\n\r\n if (j < rows && lu.get(j, j) !== 0) {\r\n for (i = j + 1; i < rows; i++) {\r\n lu.set(i, j, lu.get(i, j) / lu.get(j, j));\r\n }\r\n }\r\n }\r\n\r\n this.LU = lu;\r\n this.pivotVector = pivotVector;\r\n this.pivotSign = pivotSign;\r\n }\r\n\r\n /**\r\n *\r\n * @return {boolean}\r\n */\r\n isSingular() {\r\n var data = this.LU;\r\n var col = data.columns;\r\n for (var j = 0; j < col; j++) {\r\n if (data[j][j] === 0) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n *\r\n * @param {Matrix} value\r\n * @return {Matrix}\r\n */\r\n solve(value) {\r\n value = Matrix.checkMatrix(value);\r\n\r\n var lu = this.LU;\r\n var rows = lu.rows;\r\n\r\n if (rows !== value.rows) {\r\n throw new Error('Invalid matrix dimensions');\r\n }\r\n if (this.isSingular()) {\r\n throw new Error('LU matrix is singular');\r\n }\r\n\r\n var count = value.columns;\r\n var X = value.subMatrixRow(this.pivotVector, 0, count - 1);\r\n var columns = lu.columns;\r\n var i, j, k;\r\n\r\n for (k = 0; k < columns; k++) {\r\n for (i = k + 1; i < columns; i++) {\r\n for (j = 0; j < count; j++) {\r\n X[i][j] -= X[k][j] * lu[i][k];\r\n }\r\n }\r\n }\r\n for (k = columns - 1; k >= 0; k--) {\r\n for (j = 0; j < count; j++) {\r\n X[k][j] /= lu[k][k];\r\n }\r\n for (i = 0; i < k; i++) {\r\n for (j = 0; j < count; j++) {\r\n X[i][j] -= X[k][j] * lu[i][k];\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get determinant() {\r\n var data = this.LU;\r\n if (!data.isSquare()) {\r\n throw new Error('Matrix must be square');\r\n }\r\n var determinant = this.pivotSign;\r\n var col = data.columns;\r\n for (var j = 0; j < col; j++) {\r\n determinant *= data[j][j];\r\n }\r\n return determinant;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get lowerTriangularMatrix() {\r\n var data = this.LU;\r\n var rows = data.rows;\r\n var columns = data.columns;\r\n var X = new Matrix(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n if (i > j) {\r\n X[i][j] = data[i][j];\r\n } else if (i === j) {\r\n X[i][j] = 1;\r\n } else {\r\n X[i][j] = 0;\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get upperTriangularMatrix() {\r\n var data = this.LU;\r\n var rows = data.rows;\r\n var columns = data.columns;\r\n var X = new Matrix(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n if (i <= j) {\r\n X[i][j] = data[i][j];\r\n } else {\r\n X[i][j] = 0;\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Array}\r\n */\r\n get pivotPermutationVector() {\r\n return this.pivotVector.slice();\r\n }\r\n}\r\n","export function hypotenuse(a, b) {\r\n var r = 0;\r\n if (Math.abs(a) > Math.abs(b)) {\r\n r = b / a;\r\n return Math.abs(a) * Math.sqrt(1 + r * r);\r\n }\r\n if (b !== 0) {\r\n r = a / b;\r\n return Math.abs(b) * Math.sqrt(1 + r * r);\r\n }\r\n return 0;\r\n}\r\n\r\nexport function getFilled2DArray(rows, columns, value) {\r\n var array = new Array(rows);\r\n for (var i = 0; i < rows; i++) {\r\n array[i] = new Array(columns);\r\n for (var j = 0; j < columns; j++) {\r\n array[i][j] = value;\r\n }\r\n }\r\n return array;\r\n}\r\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\nimport { hypotenuse, getFilled2DArray } from './util';\r\n\r\n/**\r\n * @class SingularValueDecomposition\r\n * @see https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs\r\n * @param {Matrix} value\r\n * @param {object} [options]\r\n * @param {boolean} [options.computeLeftSingularVectors=true]\r\n * @param {boolean} [options.computeRightSingularVectors=true]\r\n * @param {boolean} [options.autoTranspose=false]\r\n */\r\nexport default class SingularValueDecomposition {\r\n constructor(value, options = {}) {\r\n value = WrapperMatrix2D.checkMatrix(value);\r\n\r\n var m = value.rows;\r\n var n = value.columns;\r\n\r\n const {\r\n computeLeftSingularVectors = true,\r\n computeRightSingularVectors = true,\r\n autoTranspose = false\r\n } = options;\r\n\r\n var wantu = Boolean(computeLeftSingularVectors);\r\n var wantv = Boolean(computeRightSingularVectors);\r\n\r\n var swapped = false;\r\n var a;\r\n if (m < n) {\r\n if (!autoTranspose) {\r\n a = value.clone();\r\n // eslint-disable-next-line no-console\r\n console.warn(\r\n 'Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose'\r\n );\r\n } else {\r\n a = value.transpose();\r\n m = a.rows;\r\n n = a.columns;\r\n swapped = true;\r\n var aux = wantu;\r\n wantu = wantv;\r\n wantv = aux;\r\n }\r\n } else {\r\n a = value.clone();\r\n }\r\n\r\n var nu = Math.min(m, n);\r\n var ni = Math.min(m + 1, n);\r\n var s = new Array(ni);\r\n var U = getFilled2DArray(m, nu, 0);\r\n var V = getFilled2DArray(n, n, 0);\r\n\r\n var e = new Array(n);\r\n var work = new Array(m);\r\n\r\n var si = new Array(ni);\r\n for (let i = 0; i < ni; i++) si[i] = i;\r\n\r\n var nct = Math.min(m - 1, n);\r\n var nrt = Math.max(0, Math.min(n - 2, m));\r\n var mrc = Math.max(nct, nrt);\r\n\r\n for (let k = 0; k < mrc; k++) {\r\n if (k < nct) {\r\n s[k] = 0;\r\n for (let i = k; i < m; i++) {\r\n s[k] = hypotenuse(s[k], a[i][k]);\r\n }\r\n if (s[k] !== 0) {\r\n if (a[k][k] < 0) {\r\n s[k] = -s[k];\r\n }\r\n for (let i = k; i < m; i++) {\r\n a[i][k] /= s[k];\r\n }\r\n a[k][k] += 1;\r\n }\r\n s[k] = -s[k];\r\n }\r\n\r\n for (let j = k + 1; j < n; j++) {\r\n if (k < nct && s[k] !== 0) {\r\n let t = 0;\r\n for (let i = k; i < m; i++) {\r\n t += a[i][k] * a[i][j];\r\n }\r\n t = -t / a[k][k];\r\n for (let i = k; i < m; i++) {\r\n a[i][j] += t * a[i][k];\r\n }\r\n }\r\n e[j] = a[k][j];\r\n }\r\n\r\n if (wantu && k < nct) {\r\n for (let i = k; i < m; i++) {\r\n U[i][k] = a[i][k];\r\n }\r\n }\r\n\r\n if (k < nrt) {\r\n e[k] = 0;\r\n for (let i = k + 1; i < n; i++) {\r\n e[k] = hypotenuse(e[k], e[i]);\r\n }\r\n if (e[k] !== 0) {\r\n if (e[k + 1] < 0) {\r\n e[k] = 0 - e[k];\r\n }\r\n for (let i = k + 1; i < n; i++) {\r\n e[i] /= e[k];\r\n }\r\n e[k + 1] += 1;\r\n }\r\n e[k] = -e[k];\r\n if (k + 1 < m && e[k] !== 0) {\r\n for (let i = k + 1; i < m; i++) {\r\n work[i] = 0;\r\n }\r\n for (let i = k + 1; i < m; i++) {\r\n for (let j = k + 1; j < n; j++) {\r\n work[i] += e[j] * a[i][j];\r\n }\r\n }\r\n for (let j = k + 1; j < n; j++) {\r\n let t = -e[j] / e[k + 1];\r\n for (let i = k + 1; i < m; i++) {\r\n a[i][j] += t * work[i];\r\n }\r\n }\r\n }\r\n if (wantv) {\r\n for (let i = k + 1; i < n; i++) {\r\n V[i][k] = e[i];\r\n }\r\n }\r\n }\r\n }\r\n\r\n let p = Math.min(n, m + 1);\r\n if (nct < n) {\r\n s[nct] = a[nct][nct];\r\n }\r\n if (m < p) {\r\n s[p - 1] = 0;\r\n }\r\n if (nrt + 1 < p) {\r\n e[nrt] = a[nrt][p - 1];\r\n }\r\n e[p - 1] = 0;\r\n\r\n if (wantu) {\r\n for (let j = nct; j < nu; j++) {\r\n for (let i = 0; i < m; i++) {\r\n U[i][j] = 0;\r\n }\r\n U[j][j] = 1;\r\n }\r\n for (let k = nct - 1; k >= 0; k--) {\r\n if (s[k] !== 0) {\r\n for (let j = k + 1; j < nu; j++) {\r\n let t = 0;\r\n for (let i = k; i < m; i++) {\r\n t += U[i][k] * U[i][j];\r\n }\r\n t = -t / U[k][k];\r\n for (let i = k; i < m; i++) {\r\n U[i][j] += t * U[i][k];\r\n }\r\n }\r\n for (let i = k; i < m; i++) {\r\n U[i][k] = -U[i][k];\r\n }\r\n U[k][k] = 1 + U[k][k];\r\n for (let i = 0; i < k - 1; i++) {\r\n U[i][k] = 0;\r\n }\r\n } else {\r\n for (let i = 0; i < m; i++) {\r\n U[i][k] = 0;\r\n }\r\n U[k][k] = 1;\r\n }\r\n }\r\n }\r\n\r\n if (wantv) {\r\n for (let k = n - 1; k >= 0; k--) {\r\n if (k < nrt && e[k] !== 0) {\r\n for (let j = k + 1; j < n; j++) {\r\n let t = 0;\r\n for (let i = k + 1; i < n; i++) {\r\n t += V[i][k] * V[i][j];\r\n }\r\n t = -t / V[k + 1][k];\r\n for (let i = k + 1; i < n; i++) {\r\n V[i][j] += t * V[i][k];\r\n }\r\n }\r\n }\r\n for (let i = 0; i < n; i++) {\r\n V[i][k] = 0;\r\n }\r\n V[k][k] = 1;\r\n }\r\n }\r\n\r\n var pp = p - 1;\r\n var iter = 0;\r\n var eps = Number.EPSILON;\r\n while (p > 0) {\r\n let k, kase;\r\n for (k = p - 2; k >= -1; k--) {\r\n if (k === -1) {\r\n break;\r\n }\r\n const alpha =\r\n Number.MIN_VALUE + eps * Math.abs(s[k] + Math.abs(s[k + 1]));\r\n if (Math.abs(e[k]) <= alpha || Number.isNaN(e[k])) {\r\n e[k] = 0;\r\n break;\r\n }\r\n }\r\n if (k === p - 2) {\r\n kase = 4;\r\n } else {\r\n let ks;\r\n for (ks = p - 1; ks >= k; ks--) {\r\n if (ks === k) {\r\n break;\r\n }\r\n let t =\r\n (ks !== p ? Math.abs(e[ks]) : 0) +\r\n (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0);\r\n if (Math.abs(s[ks]) <= eps * t) {\r\n s[ks] = 0;\r\n break;\r\n }\r\n }\r\n if (ks === k) {\r\n kase = 3;\r\n } else if (ks === p - 1) {\r\n kase = 1;\r\n } else {\r\n kase = 2;\r\n k = ks;\r\n }\r\n }\r\n\r\n k++;\r\n\r\n switch (kase) {\r\n case 1: {\r\n let f = e[p - 2];\r\n e[p - 2] = 0;\r\n for (let j = p - 2; j >= k; j--) {\r\n let t = hypotenuse(s[j], f);\r\n let cs = s[j] / t;\r\n let sn = f / t;\r\n s[j] = t;\r\n if (j !== k) {\r\n f = -sn * e[j - 1];\r\n e[j - 1] = cs * e[j - 1];\r\n }\r\n if (wantv) {\r\n for (let i = 0; i < n; i++) {\r\n t = cs * V[i][j] + sn * V[i][p - 1];\r\n V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1];\r\n V[i][j] = t;\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n case 2: {\r\n let f = e[k - 1];\r\n e[k - 1] = 0;\r\n for (let j = k; j < p; j++) {\r\n let t = hypotenuse(s[j], f);\r\n let cs = s[j] / t;\r\n let sn = f / t;\r\n s[j] = t;\r\n f = -sn * e[j];\r\n e[j] = cs * e[j];\r\n if (wantu) {\r\n for (let i = 0; i < m; i++) {\r\n t = cs * U[i][j] + sn * U[i][k - 1];\r\n U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1];\r\n U[i][j] = t;\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n case 3: {\r\n const scale = Math.max(\r\n Math.abs(s[p - 1]),\r\n Math.abs(s[p - 2]),\r\n Math.abs(e[p - 2]),\r\n Math.abs(s[k]),\r\n Math.abs(e[k])\r\n );\r\n const sp = s[p - 1] / scale;\r\n const spm1 = s[p - 2] / scale;\r\n const epm1 = e[p - 2] / scale;\r\n const sk = s[k] / scale;\r\n const ek = e[k] / scale;\r\n const b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;\r\n const c = sp * epm1 * (sp * epm1);\r\n let shift = 0;\r\n if (b !== 0 || c !== 0) {\r\n if (b < 0) {\r\n shift = 0 - Math.sqrt(b * b + c);\r\n } else {\r\n shift = Math.sqrt(b * b + c);\r\n }\r\n shift = c / (b + shift);\r\n }\r\n let f = (sk + sp) * (sk - sp) + shift;\r\n let g = sk * ek;\r\n for (let j = k; j < p - 1; j++) {\r\n let t = hypotenuse(f, g);\r\n if (t === 0) t = Number.MIN_VALUE;\r\n let cs = f / t;\r\n let sn = g / t;\r\n if (j !== k) {\r\n e[j - 1] = t;\r\n }\r\n f = cs * s[j] + sn * e[j];\r\n e[j] = cs * e[j] - sn * s[j];\r\n g = sn * s[j + 1];\r\n s[j + 1] = cs * s[j + 1];\r\n if (wantv) {\r\n for (let i = 0; i < n; i++) {\r\n t = cs * V[i][j] + sn * V[i][j + 1];\r\n V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1];\r\n V[i][j] = t;\r\n }\r\n }\r\n t = hypotenuse(f, g);\r\n if (t === 0) t = Number.MIN_VALUE;\r\n cs = f / t;\r\n sn = g / t;\r\n s[j] = t;\r\n f = cs * e[j] + sn * s[j + 1];\r\n s[j + 1] = -sn * e[j] + cs * s[j + 1];\r\n g = sn * e[j + 1];\r\n e[j + 1] = cs * e[j + 1];\r\n if (wantu && j < m - 1) {\r\n for (let i = 0; i < m; i++) {\r\n t = cs * U[i][j] + sn * U[i][j + 1];\r\n U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1];\r\n U[i][j] = t;\r\n }\r\n }\r\n }\r\n e[p - 2] = f;\r\n iter = iter + 1;\r\n break;\r\n }\r\n case 4: {\r\n if (s[k] <= 0) {\r\n s[k] = s[k] < 0 ? -s[k] : 0;\r\n if (wantv) {\r\n for (let i = 0; i <= pp; i++) {\r\n V[i][k] = -V[i][k];\r\n }\r\n }\r\n }\r\n while (k < pp) {\r\n if (s[k] >= s[k + 1]) {\r\n break;\r\n }\r\n let t = s[k];\r\n s[k] = s[k + 1];\r\n s[k + 1] = t;\r\n if (wantv && k < n - 1) {\r\n for (let i = 0; i < n; i++) {\r\n t = V[i][k + 1];\r\n V[i][k + 1] = V[i][k];\r\n V[i][k] = t;\r\n }\r\n }\r\n if (wantu && k < m - 1) {\r\n for (let i = 0; i < m; i++) {\r\n t = U[i][k + 1];\r\n U[i][k + 1] = U[i][k];\r\n U[i][k] = t;\r\n }\r\n }\r\n k++;\r\n }\r\n iter = 0;\r\n p--;\r\n break;\r\n }\r\n // no default\r\n }\r\n }\r\n\r\n if (swapped) {\r\n var tmp = V;\r\n V = U;\r\n U = tmp;\r\n }\r\n\r\n this.m = m;\r\n this.n = n;\r\n this.s = s;\r\n this.U = U;\r\n this.V = V;\r\n }\r\n\r\n /**\r\n * Solve a problem of least square (Ax=b) by using the SVD. Useful when A is singular. When A is not singular, it would be better to use qr.solve(value).\r\n * Example : We search to approximate x, with A matrix shape m*n, x vector size n, b vector size m (m > n). We will use :\r\n * var svd = SingularValueDecomposition(A);\r\n * var x = svd.solve(b);\r\n * @param {Matrix} value - Matrix 1D which is the vector b (in the equation Ax = b)\r\n * @return {Matrix} - The vector x\r\n */\r\n solve(value) {\r\n var Y = value;\r\n var e = this.threshold;\r\n var scols = this.s.length;\r\n var Ls = Matrix.zeros(scols, scols);\r\n\r\n for (let i = 0; i < scols; i++) {\r\n if (Math.abs(this.s[i]) <= e) {\r\n Ls[i][i] = 0;\r\n } else {\r\n Ls[i][i] = 1 / this.s[i];\r\n }\r\n }\r\n\r\n var U = this.U;\r\n var V = this.rightSingularVectors;\r\n\r\n var VL = V.mmul(Ls);\r\n var vrows = V.rows;\r\n var urows = U.length;\r\n var VLU = Matrix.zeros(vrows, urows);\r\n\r\n for (let i = 0; i < vrows; i++) {\r\n for (let j = 0; j < urows; j++) {\r\n let sum = 0;\r\n for (let k = 0; k < scols; k++) {\r\n sum += VL[i][k] * U[j][k];\r\n }\r\n VLU[i][j] = sum;\r\n }\r\n }\r\n\r\n return VLU.mmul(Y);\r\n }\r\n\r\n /**\r\n *\r\n * @param {Array} value\r\n * @return {Matrix}\r\n */\r\n solveForDiagonal(value) {\r\n return this.solve(Matrix.diag(value));\r\n }\r\n\r\n /**\r\n * Get the inverse of the matrix. We compute the inverse of a matrix using SVD when this matrix is singular or ill-conditioned. Example :\r\n * var svd = SingularValueDecomposition(A);\r\n * var inverseA = svd.inverse();\r\n * @return {Matrix} - The approximation of the inverse of the matrix\r\n */\r\n inverse() {\r\n var V = this.V;\r\n var e = this.threshold;\r\n var vrows = V.length;\r\n var vcols = V[0].length;\r\n var X = new Matrix(vrows, this.s.length);\r\n\r\n for (let i = 0; i < vrows; i++) {\r\n for (let j = 0; j < vcols; j++) {\r\n if (Math.abs(this.s[j]) > e) {\r\n X[i][j] = V[i][j] / this.s[j];\r\n } else {\r\n X[i][j] = 0;\r\n }\r\n }\r\n }\r\n\r\n var U = this.U;\r\n\r\n var urows = U.length;\r\n var ucols = U[0].length;\r\n var Y = new Matrix(vrows, urows);\r\n\r\n for (let i = 0; i < vrows; i++) {\r\n for (let j = 0; j < urows; j++) {\r\n let sum = 0;\r\n for (let k = 0; k < ucols; k++) {\r\n sum += X[i][k] * U[j][k];\r\n }\r\n Y[i][j] = sum;\r\n }\r\n }\r\n\r\n return Y;\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get condition() {\r\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get norm2() {\r\n return this.s[0];\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get rank() {\r\n var tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON;\r\n var r = 0;\r\n var s = this.s;\r\n for (var i = 0, ii = s.length; i < ii; i++) {\r\n if (s[i] > tol) {\r\n r++;\r\n }\r\n }\r\n return r;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Array}\r\n */\r\n get diagonal() {\r\n return this.s;\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get threshold() {\r\n return Number.EPSILON / 2 * Math.max(this.m, this.n) * this.s[0];\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get leftSingularVectors() {\r\n if (!Matrix.isMatrix(this.U)) {\r\n this.U = new Matrix(this.U);\r\n }\r\n return this.U;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get rightSingularVectors() {\r\n if (!Matrix.isMatrix(this.V)) {\r\n this.V = new Matrix(this.V);\r\n }\r\n return this.V;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get diagonalMatrix() {\r\n return Matrix.diag(this.s);\r\n }\r\n}\r\n","import Matrix from './matrix';\r\n\r\n/**\r\n * @private\r\n * Check that a row index is not out of bounds\r\n * @param {Matrix} matrix\r\n * @param {number} index\r\n * @param {boolean} [outer]\r\n */\r\nexport function checkRowIndex(matrix, index, outer) {\r\n var max = outer ? matrix.rows : matrix.rows - 1;\r\n if (index < 0 || index > max) {\r\n throw new RangeError('Row index out of range');\r\n }\r\n}\r\n\r\n/**\r\n * @private\r\n * Check that a column index is not out of bounds\r\n * @param {Matrix} matrix\r\n * @param {number} index\r\n * @param {boolean} [outer]\r\n */\r\nexport function checkColumnIndex(matrix, index, outer) {\r\n var max = outer ? matrix.columns : matrix.columns - 1;\r\n if (index < 0 || index > max) {\r\n throw new RangeError('Column index out of range');\r\n }\r\n}\r\n\r\n/**\r\n * @private\r\n * Check that the provided vector is an array with the right length\r\n * @param {Matrix} matrix\r\n * @param {Array|Matrix} vector\r\n * @return {Array}\r\n * @throws {RangeError}\r\n */\r\nexport function checkRowVector(matrix, vector) {\r\n if (vector.to1DArray) {\r\n vector = vector.to1DArray();\r\n }\r\n if (vector.length !== matrix.columns) {\r\n throw new RangeError(\r\n 'vector size must be the same as the number of columns'\r\n );\r\n }\r\n return vector;\r\n}\r\n\r\n/**\r\n * @private\r\n * Check that the provided vector is an array with the right length\r\n * @param {Matrix} matrix\r\n * @param {Array|Matrix} vector\r\n * @return {Array}\r\n * @throws {RangeError}\r\n */\r\nexport function checkColumnVector(matrix, vector) {\r\n if (vector.to1DArray) {\r\n vector = vector.to1DArray();\r\n }\r\n if (vector.length !== matrix.rows) {\r\n throw new RangeError('vector size must be the same as the number of rows');\r\n }\r\n return vector;\r\n}\r\n\r\nexport function checkIndices(matrix, rowIndices, columnIndices) {\r\n return {\r\n row: checkRowIndices(matrix, rowIndices),\r\n column: checkColumnIndices(matrix, columnIndices)\r\n };\r\n}\r\n\r\nexport function checkRowIndices(matrix, rowIndices) {\r\n if (typeof rowIndices !== 'object') {\r\n throw new TypeError('unexpected type for row indices');\r\n }\r\n\r\n var rowOut = rowIndices.some((r) => {\r\n return r < 0 || r >= matrix.rows;\r\n });\r\n\r\n if (rowOut) {\r\n throw new RangeError('row indices are out of range');\r\n }\r\n\r\n if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices);\r\n\r\n return rowIndices;\r\n}\r\n\r\nexport function checkColumnIndices(matrix, columnIndices) {\r\n if (typeof columnIndices !== 'object') {\r\n throw new TypeError('unexpected type for column indices');\r\n }\r\n\r\n var columnOut = columnIndices.some((c) => {\r\n return c < 0 || c >= matrix.columns;\r\n });\r\n\r\n if (columnOut) {\r\n throw new RangeError('column indices are out of range');\r\n }\r\n if (!Array.isArray(columnIndices)) columnIndices = Array.from(columnIndices);\r\n\r\n return columnIndices;\r\n}\r\n\r\nexport function checkRange(matrix, startRow, endRow, startColumn, endColumn) {\r\n if (arguments.length !== 5) {\r\n throw new RangeError('expected 4 arguments');\r\n }\r\n checkNumber('startRow', startRow);\r\n checkNumber('endRow', endRow);\r\n checkNumber('startColumn', startColumn);\r\n checkNumber('endColumn', endColumn);\r\n if (\r\n startRow > endRow ||\r\n startColumn > endColumn ||\r\n startRow < 0 ||\r\n startRow >= matrix.rows ||\r\n endRow < 0 ||\r\n endRow >= matrix.rows ||\r\n startColumn < 0 ||\r\n startColumn >= matrix.columns ||\r\n endColumn < 0 ||\r\n endColumn >= matrix.columns\r\n ) {\r\n throw new RangeError('Submatrix indices are out of range');\r\n }\r\n}\r\n\r\nexport function getRange(from, to) {\r\n var arr = new Array(to - from + 1);\r\n for (var i = 0; i < arr.length; i++) {\r\n arr[i] = from + i;\r\n }\r\n return arr;\r\n}\r\n\r\nexport function sumByRow(matrix) {\r\n var sum = Matrix.zeros(matrix.rows, 1);\r\n for (var i = 0; i < matrix.rows; ++i) {\r\n for (var j = 0; j < matrix.columns; ++j) {\r\n sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j));\r\n }\r\n }\r\n return sum;\r\n}\r\n\r\nexport function sumByColumn(matrix) {\r\n var sum = Matrix.zeros(1, matrix.columns);\r\n for (var i = 0; i < matrix.rows; ++i) {\r\n for (var j = 0; j < matrix.columns; ++j) {\r\n sum.set(0, j, sum.get(0, j) + matrix.get(i, j));\r\n }\r\n }\r\n return sum;\r\n}\r\n\r\nexport function sumAll(matrix) {\r\n var v = 0;\r\n for (var i = 0; i < matrix.rows; i++) {\r\n for (var j = 0; j < matrix.columns; j++) {\r\n v += matrix.get(i, j);\r\n }\r\n }\r\n return v;\r\n}\r\n\r\nfunction checkNumber(name, value) {\r\n if (typeof value !== 'number') {\r\n throw new TypeError(`${name} must be a number`);\r\n }\r\n}\r\n","import AbstractMatrix from '../abstractMatrix';\r\nimport Matrix from '../matrix';\r\n\r\nexport default class BaseView extends AbstractMatrix() {\r\n constructor(matrix, rows, columns) {\r\n super();\r\n this.matrix = matrix;\r\n this.rows = rows;\r\n this.columns = columns;\r\n }\r\n\r\n static get [Symbol.species]() {\r\n return Matrix;\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixTransposeView extends BaseView {\r\n constructor(matrix) {\r\n super(matrix, matrix.columns, matrix.rows);\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(columnIndex, rowIndex, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(columnIndex, rowIndex);\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixRowView extends BaseView {\r\n constructor(matrix, row) {\r\n super(matrix, 1, matrix.columns);\r\n this.row = row;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(this.row, columnIndex, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(this.row, columnIndex);\r\n }\r\n}\r\n","import { checkRange } from '../util';\r\n\r\nimport BaseView from './base';\r\n\r\nexport default class MatrixSubView extends BaseView {\r\n constructor(matrix, startRow, endRow, startColumn, endColumn) {\r\n checkRange(matrix, startRow, endRow, startColumn, endColumn);\r\n super(matrix, endRow - startRow + 1, endColumn - startColumn + 1);\r\n this.startRow = startRow;\r\n this.startColumn = startColumn;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(\r\n this.startRow + rowIndex,\r\n this.startColumn + columnIndex,\r\n value\r\n );\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(\r\n this.startRow + rowIndex,\r\n this.startColumn + columnIndex\r\n );\r\n }\r\n}\r\n","import { checkIndices } from '../util';\r\n\r\nimport BaseView from './base';\r\n\r\nexport default class MatrixSelectionView extends BaseView {\r\n constructor(matrix, rowIndices, columnIndices) {\r\n var indices = checkIndices(matrix, rowIndices, columnIndices);\r\n super(matrix, indices.row.length, indices.column.length);\r\n this.rowIndices = indices.row;\r\n this.columnIndices = indices.column;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(\r\n this.rowIndices[rowIndex],\r\n this.columnIndices[columnIndex],\r\n value\r\n );\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(\r\n this.rowIndices[rowIndex],\r\n this.columnIndices[columnIndex]\r\n );\r\n }\r\n}\r\n","import { checkRowIndices } from '../util';\r\n\r\nimport BaseView from './base';\r\n\r\nexport default class MatrixRowSelectionView extends BaseView {\r\n constructor(matrix, rowIndices) {\r\n rowIndices = checkRowIndices(matrix, rowIndices);\r\n super(matrix, rowIndices.length, matrix.columns);\r\n this.rowIndices = rowIndices;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(this.rowIndices[rowIndex], columnIndex, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(this.rowIndices[rowIndex], columnIndex);\r\n }\r\n}\r\n","import { checkColumnIndices } from '../util';\r\n\r\nimport BaseView from './base';\r\n\r\nexport default class MatrixColumnSelectionView extends BaseView {\r\n constructor(matrix, columnIndices) {\r\n columnIndices = checkColumnIndices(matrix, columnIndices);\r\n super(matrix, matrix.rows, columnIndices.length);\r\n this.columnIndices = columnIndices;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(rowIndex, this.columnIndices[columnIndex], value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(rowIndex, this.columnIndices[columnIndex]);\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixColumnView extends BaseView {\r\n constructor(matrix, column) {\r\n super(matrix, matrix.rows, 1);\r\n this.column = column;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(rowIndex, this.column, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex) {\r\n return this.matrix.get(rowIndex, this.column);\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixFlipRowView extends BaseView {\r\n constructor(matrix) {\r\n super(matrix, matrix.rows, matrix.columns);\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(this.rows - rowIndex - 1, columnIndex, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(this.rows - rowIndex - 1, columnIndex);\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixFlipColumnView extends BaseView {\r\n constructor(matrix) {\r\n super(matrix, matrix.rows, matrix.columns);\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(rowIndex, this.columns - columnIndex - 1, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(rowIndex, this.columns - columnIndex - 1);\r\n }\r\n}\r\n","import rescale from 'ml-array-rescale';\r\n\r\nimport LuDecomposition from './dc/lu';\r\nimport SvDecomposition from './dc/svd';\r\nimport {\r\n checkRowVector, checkRowIndex, checkColumnIndex, checkColumnVector,\r\n checkRange, checkIndices,\r\n sumByRow, sumByColumn, sumAll\r\n} from './util';\r\nimport MatrixTransposeView from './views/transpose';\r\nimport MatrixRowView from './views/row';\r\nimport MatrixSubView from './views/sub';\r\nimport MatrixSelectionView from './views/selection';\r\nimport MatrixRowSelectionView from './views/rowSelection';\r\nimport MatrixColumnSelectionView from './views/columnSelection';\r\nimport MatrixColumnView from './views/column';\r\nimport MatrixFlipRowView from './views/flipRow';\r\nimport MatrixFlipColumnView from './views/flipColumn';\r\n\r\nexport default function AbstractMatrix(superCtor) {\r\n if (superCtor === undefined) superCtor = Object;\r\n\r\n /**\r\n * Real matrix\r\n * @class Matrix\r\n * @param {number|Array|Matrix} nRows - Number of rows of the new matrix,\r\n * 2D array containing the data or Matrix instance to clone\r\n * @param {number} [nColumns] - Number of columns of the new matrix\r\n */\r\n class Matrix extends superCtor {\r\n static get [Symbol.species]() {\r\n return this;\r\n }\r\n\r\n /**\r\n * Constructs a Matrix with the chosen dimensions from a 1D array\r\n * @param {number} newRows - Number of rows\r\n * @param {number} newColumns - Number of columns\r\n * @param {Array} newData - A 1D array containing data for the matrix\r\n * @return {Matrix} - The new matrix\r\n */\r\n static from1DArray(newRows, newColumns, newData) {\r\n var length = newRows * newColumns;\r\n if (length !== newData.length) {\r\n throw new RangeError('Data length does not match given dimensions');\r\n }\r\n var newMatrix = new this(newRows, newColumns);\r\n for (var row = 0; row < newRows; row++) {\r\n for (var column = 0; column < newColumns; column++) {\r\n newMatrix.set(row, column, newData[row * newColumns + column]);\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Creates a row vector, a matrix with only one row.\r\n * @param {Array} newData - A 1D array containing data for the vector\r\n * @return {Matrix} - The new matrix\r\n */\r\n static rowVector(newData) {\r\n var vector = new this(1, newData.length);\r\n for (var i = 0; i < newData.length; i++) {\r\n vector.set(0, i, newData[i]);\r\n }\r\n return vector;\r\n }\r\n\r\n /**\r\n * Creates a column vector, a matrix with only one column.\r\n * @param {Array} newData - A 1D array containing data for the vector\r\n * @return {Matrix} - The new matrix\r\n */\r\n static columnVector(newData) {\r\n var vector = new this(newData.length, 1);\r\n for (var i = 0; i < newData.length; i++) {\r\n vector.set(i, 0, newData[i]);\r\n }\r\n return vector;\r\n }\r\n\r\n /**\r\n * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns).\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @return {Matrix} - The new matrix\r\n */\r\n static empty(rows, columns) {\r\n return new this(rows, columns);\r\n }\r\n\r\n /**\r\n * Creates a matrix with the given dimensions. Values will be set to zero.\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @return {Matrix} - The new matrix\r\n */\r\n static zeros(rows, columns) {\r\n return this.empty(rows, columns).fill(0);\r\n }\r\n\r\n /**\r\n * Creates a matrix with the given dimensions. Values will be set to one.\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @return {Matrix} - The new matrix\r\n */\r\n static ones(rows, columns) {\r\n return this.empty(rows, columns).fill(1);\r\n }\r\n\r\n /**\r\n * Creates a matrix with the given dimensions. Values will be randomly set.\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @param {function} [rng=Math.random] - Random number generator\r\n * @return {Matrix} The new matrix\r\n */\r\n static rand(rows, columns, rng) {\r\n if (rng === undefined) rng = Math.random;\r\n var matrix = this.empty(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n matrix.set(i, j, rng());\r\n }\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Creates a matrix with the given dimensions. Values will be random integers.\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @param {number} [maxValue=1000] - Maximum value\r\n * @param {function} [rng=Math.random] - Random number generator\r\n * @return {Matrix} The new matrix\r\n */\r\n static randInt(rows, columns, maxValue, rng) {\r\n if (maxValue === undefined) maxValue = 1000;\r\n if (rng === undefined) rng = Math.random;\r\n var matrix = this.empty(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n var value = Math.floor(rng() * maxValue);\r\n matrix.set(i, j, value);\r\n }\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0.\r\n * @param {number} rows - Number of rows\r\n * @param {number} [columns=rows] - Number of columns\r\n * @param {number} [value=1] - Value to fill the diagonal with\r\n * @return {Matrix} - The new identity matrix\r\n */\r\n static eye(rows, columns, value) {\r\n if (columns === undefined) columns = rows;\r\n if (value === undefined) value = 1;\r\n var min = Math.min(rows, columns);\r\n var matrix = this.zeros(rows, columns);\r\n for (var i = 0; i < min; i++) {\r\n matrix.set(i, i, value);\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Creates a diagonal matrix based on the given array.\r\n * @param {Array} data - Array containing the data for the diagonal\r\n * @param {number} [rows] - Number of rows (Default: data.length)\r\n * @param {number} [columns] - Number of columns (Default: rows)\r\n * @return {Matrix} - The new diagonal matrix\r\n */\r\n static diag(data, rows, columns) {\r\n var l = data.length;\r\n if (rows === undefined) rows = l;\r\n if (columns === undefined) columns = rows;\r\n var min = Math.min(l, rows, columns);\r\n var matrix = this.zeros(rows, columns);\r\n for (var i = 0; i < min; i++) {\r\n matrix.set(i, i, data[i]);\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Returns a matrix whose elements are the minimum between matrix1 and matrix2\r\n * @param {Matrix} matrix1\r\n * @param {Matrix} matrix2\r\n * @return {Matrix}\r\n */\r\n static min(matrix1, matrix2) {\r\n matrix1 = this.checkMatrix(matrix1);\r\n matrix2 = this.checkMatrix(matrix2);\r\n var rows = matrix1.rows;\r\n var columns = matrix1.columns;\r\n var result = new this(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a matrix whose elements are the maximum between matrix1 and matrix2\r\n * @param {Matrix} matrix1\r\n * @param {Matrix} matrix2\r\n * @return {Matrix}\r\n */\r\n static max(matrix1, matrix2) {\r\n matrix1 = this.checkMatrix(matrix1);\r\n matrix2 = this.checkMatrix(matrix2);\r\n var rows = matrix1.rows;\r\n var columns = matrix1.columns;\r\n var result = new this(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Check that the provided value is a Matrix and tries to instantiate one if not\r\n * @param {*} value - The value to check\r\n * @return {Matrix}\r\n */\r\n static checkMatrix(value) {\r\n return Matrix.isMatrix(value) ? value : new this(value);\r\n }\r\n\r\n /**\r\n * Returns true if the argument is a Matrix, false otherwise\r\n * @param {*} value - The value to check\r\n * @return {boolean}\r\n */\r\n static isMatrix(value) {\r\n return (value != null) && (value.klass === 'Matrix');\r\n }\r\n\r\n /**\r\n * @prop {number} size - The number of elements in the matrix.\r\n */\r\n get size() {\r\n return this.rows * this.columns;\r\n }\r\n\r\n /**\r\n * Applies a callback for each element of the matrix. The function is called in the matrix (this) context.\r\n * @param {function} callback - Function that will be called with two parameters : i (row) and j (column)\r\n * @return {Matrix} this\r\n */\r\n apply(callback) {\r\n if (typeof callback !== 'function') {\r\n throw new TypeError('callback must be a function');\r\n }\r\n var ii = this.rows;\r\n var jj = this.columns;\r\n for (var i = 0; i < ii; i++) {\r\n for (var j = 0; j < jj; j++) {\r\n callback.call(this, i, j);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns a new 1D array filled row by row with the matrix values\r\n * @return {Array}\r\n */\r\n to1DArray() {\r\n var array = new Array(this.size);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n array[i * this.columns + j] = this.get(i, j);\r\n }\r\n }\r\n return array;\r\n }\r\n\r\n /**\r\n * Returns a 2D array containing a copy of the data\r\n * @return {Array}\r\n */\r\n to2DArray() {\r\n var copy = new Array(this.rows);\r\n for (var i = 0; i < this.rows; i++) {\r\n copy[i] = new Array(this.columns);\r\n for (var j = 0; j < this.columns; j++) {\r\n copy[i][j] = this.get(i, j);\r\n }\r\n }\r\n return copy;\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix has one row\r\n */\r\n isRowVector() {\r\n return this.rows === 1;\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix has one column\r\n */\r\n isColumnVector() {\r\n return this.columns === 1;\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix has one row or one column\r\n */\r\n isVector() {\r\n return (this.rows === 1) || (this.columns === 1);\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix has the same number of rows and columns\r\n */\r\n isSquare() {\r\n return this.rows === this.columns;\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal\r\n */\r\n isSymmetric() {\r\n if (this.isSquare()) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j <= i; j++) {\r\n if (this.get(i, j) !== this.get(j, i)) {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * @return true if the matrix is in echelon form\r\n */\r\n isEchelonForm() {\r\n let i = 0;\r\n let j = 0;\r\n let previousColumn = -1;\r\n let isEchelonForm = true;\r\n let checked = false;\r\n while ((i < this.rows) && (isEchelonForm)) {\r\n j = 0;\r\n checked = false;\r\n while ((j < this.columns) && (checked === false)) {\r\n if (this.get(i, j) === 0) {\r\n j++;\r\n } else if ((this.get(i, j) === 1) && (j > previousColumn)) {\r\n checked = true;\r\n previousColumn = j;\r\n } else {\r\n isEchelonForm = false;\r\n checked = true;\r\n }\r\n }\r\n i++;\r\n }\r\n return isEchelonForm;\r\n }\r\n\r\n /**\r\n * @return true if the matrix is in reduced echelon form\r\n */\r\n isReducedEchelonForm() {\r\n let i = 0;\r\n let j = 0;\r\n let previousColumn = -1;\r\n let isReducedEchelonForm = true;\r\n let checked = false;\r\n while ((i < this.rows) && (isReducedEchelonForm)) {\r\n j = 0;\r\n checked = false;\r\n while ((j < this.columns) && (checked === false)) {\r\n if (this.get(i, j) === 0) {\r\n j++;\r\n } else if ((this.get(i, j) === 1) && (j > previousColumn)) {\r\n checked = true;\r\n previousColumn = j;\r\n } else {\r\n isReducedEchelonForm = false;\r\n checked = true;\r\n }\r\n }\r\n for (let k = j + 1; k < this.rows; k++) {\r\n if (this.get(i, k) !== 0) {\r\n isReducedEchelonForm = false;\r\n }\r\n }\r\n i++;\r\n }\r\n return isReducedEchelonForm;\r\n }\r\n\r\n /**\r\n * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1\r\n * @abstract\r\n * @param {number} rowIndex - Index of the row\r\n * @param {number} columnIndex - Index of the column\r\n * @param {number} value - The new value for the element\r\n * @return {Matrix} this\r\n */\r\n set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars\r\n throw new Error('set method is unimplemented');\r\n }\r\n\r\n /**\r\n * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4]\r\n * @abstract\r\n * @param {number} rowIndex - Index of the row\r\n * @param {number} columnIndex - Index of the column\r\n * @return {number}\r\n */\r\n get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars\r\n throw new Error('get method is unimplemented');\r\n }\r\n\r\n /**\r\n * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of\r\n * rows of the matrix, and colRep times the number of columns of the matrix\r\n * @param {number} rowRep - Number of times the rows should be repeated\r\n * @param {number} colRep - Number of times the columns should be re\r\n * @return {Matrix}\r\n * @example\r\n * var matrix = new Matrix([[1,2]]);\r\n * matrix.repeat(2); // [[1,2],[1,2]]\r\n */\r\n repeat(rowRep, colRep) {\r\n rowRep = rowRep || 1;\r\n colRep = colRep || 1;\r\n var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep);\r\n for (var i = 0; i < rowRep; i++) {\r\n for (var j = 0; j < colRep; j++) {\r\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\r\n }\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Fills the matrix with a given value. All elements will be set to this value.\r\n * @param {number} value - New value\r\n * @return {Matrix} this\r\n */\r\n fill(value) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, value);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Negates the matrix. All elements will be multiplied by (-1)\r\n * @return {Matrix} this\r\n */\r\n neg() {\r\n return this.mulS(-1);\r\n }\r\n\r\n /**\r\n * Returns a new array from the given row index\r\n * @param {number} index - Row index\r\n * @return {Array}\r\n */\r\n getRow(index) {\r\n checkRowIndex(this, index);\r\n var row = new Array(this.columns);\r\n for (var i = 0; i < this.columns; i++) {\r\n row[i] = this.get(index, i);\r\n }\r\n return row;\r\n }\r\n\r\n /**\r\n * Returns a new row vector from the given row index\r\n * @param {number} index - Row index\r\n * @return {Matrix}\r\n */\r\n getRowVector(index) {\r\n return this.constructor.rowVector(this.getRow(index));\r\n }\r\n\r\n /**\r\n * Sets a row at the given index\r\n * @param {number} index - Row index\r\n * @param {Array|Matrix} array - Array or vector\r\n * @return {Matrix} this\r\n */\r\n setRow(index, array) {\r\n checkRowIndex(this, index);\r\n array = checkRowVector(this, array);\r\n for (var i = 0; i < this.columns; i++) {\r\n this.set(index, i, array[i]);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Swaps two rows\r\n * @param {number} row1 - First row index\r\n * @param {number} row2 - Second row index\r\n * @return {Matrix} this\r\n */\r\n swapRows(row1, row2) {\r\n checkRowIndex(this, row1);\r\n checkRowIndex(this, row2);\r\n for (var i = 0; i < this.columns; i++) {\r\n var temp = this.get(row1, i);\r\n this.set(row1, i, this.get(row2, i));\r\n this.set(row2, i, temp);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns a new array from the given column index\r\n * @param {number} index - Column index\r\n * @return {Array}\r\n */\r\n getColumn(index) {\r\n checkColumnIndex(this, index);\r\n var column = new Array(this.rows);\r\n for (var i = 0; i < this.rows; i++) {\r\n column[i] = this.get(i, index);\r\n }\r\n return column;\r\n }\r\n\r\n /**\r\n * Returns a new column vector from the given column index\r\n * @param {number} index - Column index\r\n * @return {Matrix}\r\n */\r\n getColumnVector(index) {\r\n return this.constructor.columnVector(this.getColumn(index));\r\n }\r\n\r\n /**\r\n * Sets a column at the given index\r\n * @param {number} index - Column index\r\n * @param {Array|Matrix} array - Array or vector\r\n * @return {Matrix} this\r\n */\r\n setColumn(index, array) {\r\n checkColumnIndex(this, index);\r\n array = checkColumnVector(this, array);\r\n for (var i = 0; i < this.rows; i++) {\r\n this.set(i, index, array[i]);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Swaps two columns\r\n * @param {number} column1 - First column index\r\n * @param {number} column2 - Second column index\r\n * @return {Matrix} this\r\n */\r\n swapColumns(column1, column2) {\r\n checkColumnIndex(this, column1);\r\n checkColumnIndex(this, column2);\r\n for (var i = 0; i < this.rows; i++) {\r\n var temp = this.get(i, column1);\r\n this.set(i, column1, this.get(i, column2));\r\n this.set(i, column2, temp);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Adds the values of a vector to each row\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n addRowVector(vector) {\r\n vector = checkRowVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) + vector[j]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Subtracts the values of a vector from each row\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n subRowVector(vector) {\r\n vector = checkRowVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) - vector[j]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Multiplies the values of a vector with each row\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n mulRowVector(vector) {\r\n vector = checkRowVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) * vector[j]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Divides the values of each row by those of a vector\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n divRowVector(vector) {\r\n vector = checkRowVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) / vector[j]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Adds the values of a vector to each column\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n addColumnVector(vector) {\r\n vector = checkColumnVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) + vector[i]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Subtracts the values of a vector from each column\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n subColumnVector(vector) {\r\n vector = checkColumnVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) - vector[i]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Multiplies the values of a vector with each column\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n mulColumnVector(vector) {\r\n vector = checkColumnVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) * vector[i]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Divides the values of each column by those of a vector\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n divColumnVector(vector) {\r\n vector = checkColumnVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) / vector[i]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Multiplies the values of a row with a scalar\r\n * @param {number} index - Row index\r\n * @param {number} value\r\n * @return {Matrix} this\r\n */\r\n mulRow(index, value) {\r\n checkRowIndex(this, index);\r\n for (var i = 0; i < this.columns; i++) {\r\n this.set(index, i, this.get(index, i) * value);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Multiplies the values of a column with a scalar\r\n * @param {number} index - Column index\r\n * @param {number} value\r\n * @return {Matrix} this\r\n */\r\n mulColumn(index, value) {\r\n checkColumnIndex(this, index);\r\n for (var i = 0; i < this.rows; i++) {\r\n this.set(i, index, this.get(i, index) * value);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns the maximum value of the matrix\r\n * @return {number}\r\n */\r\n max() {\r\n var v = this.get(0, 0);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n if (this.get(i, j) > v) {\r\n v = this.get(i, j);\r\n }\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the maximum value\r\n * @return {Array}\r\n */\r\n maxIndex() {\r\n var v = this.get(0, 0);\r\n var idx = [0, 0];\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n if (this.get(i, j) > v) {\r\n v = this.get(i, j);\r\n idx[0] = i;\r\n idx[1] = j;\r\n }\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the minimum value of the matrix\r\n * @return {number}\r\n */\r\n min() {\r\n var v = this.get(0, 0);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n if (this.get(i, j) < v) {\r\n v = this.get(i, j);\r\n }\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the minimum value\r\n * @return {Array}\r\n */\r\n minIndex() {\r\n var v = this.get(0, 0);\r\n var idx = [0, 0];\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n if (this.get(i, j) < v) {\r\n v = this.get(i, j);\r\n idx[0] = i;\r\n idx[1] = j;\r\n }\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the maximum value of one row\r\n * @param {number} row - Row index\r\n * @return {number}\r\n */\r\n maxRow(row) {\r\n checkRowIndex(this, row);\r\n var v = this.get(row, 0);\r\n for (var i = 1; i < this.columns; i++) {\r\n if (this.get(row, i) > v) {\r\n v = this.get(row, i);\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the maximum value of one row\r\n * @param {number} row - Row index\r\n * @return {Array}\r\n */\r\n maxRowIndex(row) {\r\n checkRowIndex(this, row);\r\n var v = this.get(row, 0);\r\n var idx = [row, 0];\r\n for (var i = 1; i < this.columns; i++) {\r\n if (this.get(row, i) > v) {\r\n v = this.get(row, i);\r\n idx[1] = i;\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the minimum value of one row\r\n * @param {number} row - Row index\r\n * @return {number}\r\n */\r\n minRow(row) {\r\n checkRowIndex(this, row);\r\n var v = this.get(row, 0);\r\n for (var i = 1; i < this.columns; i++) {\r\n if (this.get(row, i) < v) {\r\n v = this.get(row, i);\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the maximum value of one row\r\n * @param {number} row - Row index\r\n * @return {Array}\r\n */\r\n minRowIndex(row) {\r\n checkRowIndex(this, row);\r\n var v = this.get(row, 0);\r\n var idx = [row, 0];\r\n for (var i = 1; i < this.columns; i++) {\r\n if (this.get(row, i) < v) {\r\n v = this.get(row, i);\r\n idx[1] = i;\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the maximum value of one column\r\n * @param {number} column - Column index\r\n * @return {number}\r\n */\r\n maxColumn(column) {\r\n checkColumnIndex(this, column);\r\n var v = this.get(0, column);\r\n for (var i = 1; i < this.rows; i++) {\r\n if (this.get(i, column) > v) {\r\n v = this.get(i, column);\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the maximum value of one column\r\n * @param {number} column - Column index\r\n * @return {Array}\r\n */\r\n maxColumnIndex(column) {\r\n checkColumnIndex(this, column);\r\n var v = this.get(0, column);\r\n var idx = [0, column];\r\n for (var i = 1; i < this.rows; i++) {\r\n if (this.get(i, column) > v) {\r\n v = this.get(i, column);\r\n idx[0] = i;\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the minimum value of one column\r\n * @param {number} column - Column index\r\n * @return {number}\r\n */\r\n minColumn(column) {\r\n checkColumnIndex(this, column);\r\n var v = this.get(0, column);\r\n for (var i = 1; i < this.rows; i++) {\r\n if (this.get(i, column) < v) {\r\n v = this.get(i, column);\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the minimum value of one column\r\n * @param {number} column - Column index\r\n * @return {Array}\r\n */\r\n minColumnIndex(column) {\r\n checkColumnIndex(this, column);\r\n var v = this.get(0, column);\r\n var idx = [0, column];\r\n for (var i = 1; i < this.rows; i++) {\r\n if (this.get(i, column) < v) {\r\n v = this.get(i, column);\r\n idx[0] = i;\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns an array containing the diagonal values of the matrix\r\n * @return {Array}\r\n */\r\n diag() {\r\n var min = Math.min(this.rows, this.columns);\r\n var diag = new Array(min);\r\n for (var i = 0; i < min; i++) {\r\n diag[i] = this.get(i, i);\r\n }\r\n return diag;\r\n }\r\n\r\n /**\r\n * Returns the sum by the argument given, if no argument given,\r\n * it returns the sum of all elements of the matrix.\r\n * @param {string} by - sum by 'row' or 'column'.\r\n * @return {Matrix|number}\r\n */\r\n sum(by) {\r\n switch (by) {\r\n case 'row':\r\n return sumByRow(this);\r\n case 'column':\r\n return sumByColumn(this);\r\n default:\r\n return sumAll(this);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the mean of all elements of the matrix\r\n * @return {number}\r\n */\r\n mean() {\r\n return this.sum() / this.size;\r\n }\r\n\r\n /**\r\n * Returns the product of all elements of the matrix\r\n * @return {number}\r\n */\r\n prod() {\r\n var prod = 1;\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n prod *= this.get(i, j);\r\n }\r\n }\r\n return prod;\r\n }\r\n\r\n /**\r\n * Returns the norm of a matrix.\r\n * @param {string} type - \"frobenius\" (default) or \"max\" return resp. the Frobenius norm and the max norm.\r\n * @return {number}\r\n */\r\n norm(type = 'frobenius') {\r\n var result = 0;\r\n if (type === 'max') {\r\n return this.max();\r\n } else if (type === 'frobenius') {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n result = result + this.get(i, j) * this.get(i, j);\r\n }\r\n }\r\n return Math.sqrt(result);\r\n } else {\r\n throw new RangeError(`unknown norm type: ${type}`);\r\n }\r\n }\r\n\r\n /**\r\n * Computes the cumulative sum of the matrix elements (in place, row by row)\r\n * @return {Matrix} this\r\n */\r\n cumulativeSum() {\r\n var sum = 0;\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n sum += this.get(i, j);\r\n this.set(i, j, sum);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Computes the dot (scalar) product between the matrix and another\r\n * @param {Matrix} vector2 vector\r\n * @return {number}\r\n */\r\n dot(vector2) {\r\n if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\r\n var vector1 = this.to1DArray();\r\n if (vector1.length !== vector2.length) {\r\n throw new RangeError('vectors do not have the same size');\r\n }\r\n var dot = 0;\r\n for (var i = 0; i < vector1.length; i++) {\r\n dot += vector1[i] * vector2[i];\r\n }\r\n return dot;\r\n }\r\n\r\n /**\r\n * Returns the matrix product between this and other\r\n * @param {Matrix} other\r\n * @return {Matrix}\r\n */\r\n mmul(other) {\r\n other = this.constructor.checkMatrix(other);\r\n if (this.columns !== other.rows) {\r\n // eslint-disable-next-line no-console\r\n console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\r\n }\r\n\r\n var m = this.rows;\r\n var n = this.columns;\r\n var p = other.columns;\r\n\r\n var result = new this.constructor[Symbol.species](m, p);\r\n\r\n var Bcolj = new Array(n);\r\n for (var j = 0; j < p; j++) {\r\n for (var k = 0; k < n; k++) {\r\n Bcolj[k] = other.get(k, j);\r\n }\r\n\r\n for (var i = 0; i < m; i++) {\r\n var s = 0;\r\n for (k = 0; k < n; k++) {\r\n s += this.get(i, k) * Bcolj[k];\r\n }\r\n\r\n result.set(i, j, s);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n strassen2x2(other) {\r\n var result = new this.constructor[Symbol.species](2, 2);\r\n const a11 = this.get(0, 0);\r\n const b11 = other.get(0, 0);\r\n const a12 = this.get(0, 1);\r\n const b12 = other.get(0, 1);\r\n const a21 = this.get(1, 0);\r\n const b21 = other.get(1, 0);\r\n const a22 = this.get(1, 1);\r\n const b22 = other.get(1, 1);\r\n\r\n // Compute intermediate values.\r\n const m1 = (a11 + a22) * (b11 + b22);\r\n const m2 = (a21 + a22) * b11;\r\n const m3 = a11 * (b12 - b22);\r\n const m4 = a22 * (b21 - b11);\r\n const m5 = (a11 + a12) * b22;\r\n const m6 = (a21 - a11) * (b11 + b12);\r\n const m7 = (a12 - a22) * (b21 + b22);\r\n\r\n // Combine intermediate values into the output.\r\n const c00 = m1 + m4 - m5 + m7;\r\n const c01 = m3 + m5;\r\n const c10 = m2 + m4;\r\n const c11 = m1 - m2 + m3 + m6;\r\n\r\n result.set(0, 0, c00);\r\n result.set(0, 1, c01);\r\n result.set(1, 0, c10);\r\n result.set(1, 1, c11);\r\n return result;\r\n }\r\n\r\n strassen3x3(other) {\r\n var result = new this.constructor[Symbol.species](3, 3);\r\n\r\n const a00 = this.get(0, 0);\r\n const a01 = this.get(0, 1);\r\n const a02 = this.get(0, 2);\r\n const a10 = this.get(1, 0);\r\n const a11 = this.get(1, 1);\r\n const a12 = this.get(1, 2);\r\n const a20 = this.get(2, 0);\r\n const a21 = this.get(2, 1);\r\n const a22 = this.get(2, 2);\r\n\r\n const b00 = other.get(0, 0);\r\n const b01 = other.get(0, 1);\r\n const b02 = other.get(0, 2);\r\n const b10 = other.get(1, 0);\r\n const b11 = other.get(1, 1);\r\n const b12 = other.get(1, 2);\r\n const b20 = other.get(2, 0);\r\n const b21 = other.get(2, 1);\r\n const b22 = other.get(2, 2);\r\n\r\n const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;\r\n const m2 = (a00 - a10) * (-b01 + b11);\r\n const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);\r\n const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);\r\n const m5 = (a10 + a11) * (-b00 + b01);\r\n const m6 = a00 * b00;\r\n const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);\r\n const m8 = (-a00 + a20) * (b02 - b12);\r\n const m9 = (a20 + a21) * (-b00 + b02);\r\n const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;\r\n const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);\r\n const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);\r\n const m13 = (a02 - a22) * (b11 - b21);\r\n const m14 = a02 * b20;\r\n const m15 = (a21 + a22) * (-b20 + b21);\r\n const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);\r\n const m17 = (a02 - a12) * (b12 - b22);\r\n const m18 = (a11 + a12) * (-b20 + b22);\r\n const m19 = a01 * b10;\r\n const m20 = a12 * b21;\r\n const m21 = a10 * b02;\r\n const m22 = a20 * b01;\r\n const m23 = a22 * b22;\r\n\r\n const c00 = m6 + m14 + m19;\r\n const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;\r\n const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;\r\n const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;\r\n const c11 = m2 + m4 + m5 + m6 + m20;\r\n const c12 = m14 + m16 + m17 + m18 + m21;\r\n const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;\r\n const c21 = m12 + m13 + m14 + m15 + m22;\r\n const c22 = m6 + m7 + m8 + m9 + m23;\r\n\r\n result.set(0, 0, c00);\r\n result.set(0, 1, c01);\r\n result.set(0, 2, c02);\r\n result.set(1, 0, c10);\r\n result.set(1, 1, c11);\r\n result.set(1, 2, c12);\r\n result.set(2, 0, c20);\r\n result.set(2, 1, c21);\r\n result.set(2, 2, c22);\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000.\r\n * @param {Matrix} y\r\n * @return {Matrix}\r\n */\r\n mmulStrassen(y) {\r\n var x = this.clone();\r\n var r1 = x.rows;\r\n var c1 = x.columns;\r\n var r2 = y.rows;\r\n var c2 = y.columns;\r\n if (c1 !== r2) {\r\n // eslint-disable-next-line no-console\r\n console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`);\r\n }\r\n\r\n // Put a matrix into the top left of a matrix of zeros.\r\n // `rows` and `cols` are the dimensions of the output matrix.\r\n function embed(mat, rows, cols) {\r\n var r = mat.rows;\r\n var c = mat.columns;\r\n if ((r === rows) && (c === cols)) {\r\n return mat;\r\n } else {\r\n var resultat = Matrix.zeros(rows, cols);\r\n resultat = resultat.setSubMatrix(mat, 0, 0);\r\n return resultat;\r\n }\r\n }\r\n\r\n\r\n // Make sure both matrices are the same size.\r\n // This is exclusively for simplicity:\r\n // this algorithm can be implemented with matrices of different sizes.\r\n\r\n var r = Math.max(r1, r2);\r\n var c = Math.max(c1, c2);\r\n x = embed(x, r, c);\r\n y = embed(y, r, c);\r\n\r\n // Our recursive multiplication function.\r\n function blockMult(a, b, rows, cols) {\r\n // For small matrices, resort to naive multiplication.\r\n if (rows <= 512 || cols <= 512) {\r\n return a.mmul(b); // a is equivalent to this\r\n }\r\n\r\n // Apply dynamic padding.\r\n if ((rows % 2 === 1) && (cols % 2 === 1)) {\r\n a = embed(a, rows + 1, cols + 1);\r\n b = embed(b, rows + 1, cols + 1);\r\n } else if (rows % 2 === 1) {\r\n a = embed(a, rows + 1, cols);\r\n b = embed(b, rows + 1, cols);\r\n } else if (cols % 2 === 1) {\r\n a = embed(a, rows, cols + 1);\r\n b = embed(b, rows, cols + 1);\r\n }\r\n\r\n var halfRows = parseInt(a.rows / 2, 10);\r\n var halfCols = parseInt(a.columns / 2, 10);\r\n // Subdivide input matrices.\r\n var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\r\n var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\r\n\r\n var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\r\n var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\r\n\r\n var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\r\n var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\r\n\r\n var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\r\n var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\r\n\r\n // Compute intermediate values.\r\n var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols);\r\n var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols);\r\n var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols);\r\n var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols);\r\n var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols);\r\n var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols);\r\n var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols);\r\n\r\n // Combine intermediate values into the output.\r\n var c11 = Matrix.add(m1, m4);\r\n c11.sub(m5);\r\n c11.add(m7);\r\n var c12 = Matrix.add(m3, m5);\r\n var c21 = Matrix.add(m2, m4);\r\n var c22 = Matrix.sub(m1, m2);\r\n c22.add(m3);\r\n c22.add(m6);\r\n\r\n // Crop output to the desired size (undo dynamic padding).\r\n var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns);\r\n resultat = resultat.setSubMatrix(c11, 0, 0);\r\n resultat = resultat.setSubMatrix(c12, c11.rows, 0);\r\n resultat = resultat.setSubMatrix(c21, 0, c11.columns);\r\n resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns);\r\n return resultat.subMatrix(0, rows - 1, 0, cols - 1);\r\n }\r\n return blockMult(x, y, r, c);\r\n }\r\n\r\n /**\r\n * Returns a row-by-row scaled matrix\r\n * @param {number} [min=0] - Minimum scaled value\r\n * @param {number} [max=1] - Maximum scaled value\r\n * @return {Matrix} - The scaled matrix\r\n */\r\n scaleRows(min, max) {\r\n min = min === undefined ? 0 : min;\r\n max = max === undefined ? 1 : max;\r\n if (min >= max) {\r\n throw new RangeError('min should be strictly smaller than max');\r\n }\r\n var newMatrix = this.constructor.empty(this.rows, this.columns);\r\n for (var i = 0; i < this.rows; i++) {\r\n var scaled = rescale(this.getRow(i), { min, max });\r\n newMatrix.setRow(i, scaled);\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Returns a new column-by-column scaled matrix\r\n * @param {number} [min=0] - Minimum scaled value\r\n * @param {number} [max=1] - Maximum scaled value\r\n * @return {Matrix} - The new scaled matrix\r\n * @example\r\n * var matrix = new Matrix([[1,2],[-1,0]]);\r\n * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]]\r\n */\r\n scaleColumns(min, max) {\r\n min = min === undefined ? 0 : min;\r\n max = max === undefined ? 1 : max;\r\n if (min >= max) {\r\n throw new RangeError('min should be strictly smaller than max');\r\n }\r\n var newMatrix = this.constructor.empty(this.rows, this.columns);\r\n for (var i = 0; i < this.columns; i++) {\r\n var scaled = rescale(this.getColumn(i), {\r\n min: min,\r\n max: max\r\n });\r\n newMatrix.setColumn(i, scaled);\r\n }\r\n return newMatrix;\r\n }\r\n\r\n\r\n /**\r\n * Returns the Kronecker product (also known as tensor product) between this and other\r\n * See https://en.wikipedia.org/wiki/Kronecker_product\r\n * @param {Matrix} other\r\n * @return {Matrix}\r\n */\r\n kroneckerProduct(other) {\r\n other = this.constructor.checkMatrix(other);\r\n\r\n var m = this.rows;\r\n var n = this.columns;\r\n var p = other.rows;\r\n var q = other.columns;\r\n\r\n var result = new this.constructor[Symbol.species](m * p, n * q);\r\n for (var i = 0; i < m; i++) {\r\n for (var j = 0; j < n; j++) {\r\n for (var k = 0; k < p; k++) {\r\n for (var l = 0; l < q; l++) {\r\n result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l);\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Transposes the matrix and returns a new one containing the result\r\n * @return {Matrix}\r\n */\r\n transpose() {\r\n var result = new this.constructor[Symbol.species](this.columns, this.rows);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n result.set(j, i, this.get(i, j));\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sorts the rows (in place)\r\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\r\n * @return {Matrix} this\r\n */\r\n sortRows(compareFunction) {\r\n if (compareFunction === undefined) compareFunction = compareNumbers;\r\n for (var i = 0; i < this.rows; i++) {\r\n this.setRow(i, this.getRow(i).sort(compareFunction));\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Sorts the columns (in place)\r\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\r\n * @return {Matrix} this\r\n */\r\n sortColumns(compareFunction) {\r\n if (compareFunction === undefined) compareFunction = compareNumbers;\r\n for (var i = 0; i < this.columns; i++) {\r\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns a subset of the matrix\r\n * @param {number} startRow - First row index\r\n * @param {number} endRow - Last row index\r\n * @param {number} startColumn - First column index\r\n * @param {number} endColumn - Last column index\r\n * @return {Matrix}\r\n */\r\n subMatrix(startRow, endRow, startColumn, endColumn) {\r\n checkRange(this, startRow, endRow, startColumn, endColumn);\r\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1);\r\n for (var i = startRow; i <= endRow; i++) {\r\n for (var j = startColumn; j <= endColumn; j++) {\r\n newMatrix[i - startRow][j - startColumn] = this.get(i, j);\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Returns a subset of the matrix based on an array of row indices\r\n * @param {Array} indices - Array containing the row indices\r\n * @param {number} [startColumn = 0] - First column index\r\n * @param {number} [endColumn = this.columns-1] - Last column index\r\n * @return {Matrix}\r\n */\r\n subMatrixRow(indices, startColumn, endColumn) {\r\n if (startColumn === undefined) startColumn = 0;\r\n if (endColumn === undefined) endColumn = this.columns - 1;\r\n if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) {\r\n throw new RangeError('Argument out of range');\r\n }\r\n\r\n var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1);\r\n for (var i = 0; i < indices.length; i++) {\r\n for (var j = startColumn; j <= endColumn; j++) {\r\n if (indices[i] < 0 || indices[i] >= this.rows) {\r\n throw new RangeError(`Row index out of range: ${indices[i]}`);\r\n }\r\n newMatrix.set(i, j - startColumn, this.get(indices[i], j));\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Returns a subset of the matrix based on an array of column indices\r\n * @param {Array} indices - Array containing the column indices\r\n * @param {number} [startRow = 0] - First row index\r\n * @param {number} [endRow = this.rows-1] - Last row index\r\n * @return {Matrix}\r\n */\r\n subMatrixColumn(indices, startRow, endRow) {\r\n if (startRow === undefined) startRow = 0;\r\n if (endRow === undefined) endRow = this.rows - 1;\r\n if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) {\r\n throw new RangeError('Argument out of range');\r\n }\r\n\r\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length);\r\n for (var i = 0; i < indices.length; i++) {\r\n for (var j = startRow; j <= endRow; j++) {\r\n if (indices[i] < 0 || indices[i] >= this.columns) {\r\n throw new RangeError(`Column index out of range: ${indices[i]}`);\r\n }\r\n newMatrix.set(j - startRow, i, this.get(j, indices[i]));\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Set a part of the matrix to the given sub-matrix\r\n * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values.\r\n * @param {number} startRow - The index of the first row to set\r\n * @param {number} startColumn - The index of the first column to set\r\n * @return {Matrix}\r\n */\r\n setSubMatrix(matrix, startRow, startColumn) {\r\n matrix = this.constructor.checkMatrix(matrix);\r\n var endRow = startRow + matrix.rows - 1;\r\n var endColumn = startColumn + matrix.columns - 1;\r\n checkRange(this, startRow, endRow, startColumn, endColumn);\r\n for (var i = 0; i < matrix.rows; i++) {\r\n for (var j = 0; j < matrix.columns; j++) {\r\n this[startRow + i][startColumn + j] = matrix.get(i, j);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Return a new matrix based on a selection of rows and columns\r\n * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once.\r\n * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once.\r\n * @return {Matrix} The new matrix\r\n */\r\n selection(rowIndices, columnIndices) {\r\n var indices = checkIndices(this, rowIndices, columnIndices);\r\n var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length);\r\n for (var i = 0; i < indices.row.length; i++) {\r\n var rowIndex = indices.row[i];\r\n for (var j = 0; j < indices.column.length; j++) {\r\n var columnIndex = indices.column[j];\r\n newMatrix[i][j] = this.get(rowIndex, columnIndex);\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Returns the trace of the matrix (sum of the diagonal elements)\r\n * @return {number}\r\n */\r\n trace() {\r\n var min = Math.min(this.rows, this.columns);\r\n var trace = 0;\r\n for (var i = 0; i < min; i++) {\r\n trace += this.get(i, i);\r\n }\r\n return trace;\r\n }\r\n\r\n /*\r\n Matrix views\r\n */\r\n\r\n /**\r\n * Returns a view of the transposition of the matrix\r\n * @return {MatrixTransposeView}\r\n */\r\n transposeView() {\r\n return new MatrixTransposeView(this);\r\n }\r\n\r\n /**\r\n * Returns a view of the row vector with the given index\r\n * @param {number} row - row index of the vector\r\n * @return {MatrixRowView}\r\n */\r\n rowView(row) {\r\n checkRowIndex(this, row);\r\n return new MatrixRowView(this, row);\r\n }\r\n\r\n /**\r\n * Returns a view of the column vector with the given index\r\n * @param {number} column - column index of the vector\r\n * @return {MatrixColumnView}\r\n */\r\n columnView(column) {\r\n checkColumnIndex(this, column);\r\n return new MatrixColumnView(this, column);\r\n }\r\n\r\n /**\r\n * Returns a view of the matrix flipped in the row axis\r\n * @return {MatrixFlipRowView}\r\n */\r\n flipRowView() {\r\n return new MatrixFlipRowView(this);\r\n }\r\n\r\n /**\r\n * Returns a view of the matrix flipped in the column axis\r\n * @return {MatrixFlipColumnView}\r\n */\r\n flipColumnView() {\r\n return new MatrixFlipColumnView(this);\r\n }\r\n\r\n /**\r\n * Returns a view of a submatrix giving the index boundaries\r\n * @param {number} startRow - first row index of the submatrix\r\n * @param {number} endRow - last row index of the submatrix\r\n * @param {number} startColumn - first column index of the submatrix\r\n * @param {number} endColumn - last column index of the submatrix\r\n * @return {MatrixSubView}\r\n */\r\n subMatrixView(startRow, endRow, startColumn, endColumn) {\r\n return new MatrixSubView(this, startRow, endRow, startColumn, endColumn);\r\n }\r\n\r\n /**\r\n * Returns a view of the cross of the row indices and the column indices\r\n * @example\r\n * // resulting vector is [[2], [2]]\r\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1])\r\n * @param {Array} rowIndices\r\n * @param {Array} columnIndices\r\n * @return {MatrixSelectionView}\r\n */\r\n selectionView(rowIndices, columnIndices) {\r\n return new MatrixSelectionView(this, rowIndices, columnIndices);\r\n }\r\n\r\n /**\r\n * Returns a view of the row indices\r\n * @example\r\n * // resulting vector is [[1,2,3], [1,2,3]]\r\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).rowSelectionView([0, 0])\r\n * @param {Array} rowIndices\r\n * @return {MatrixRowSelectionView}\r\n */\r\n rowSelectionView(rowIndices) {\r\n return new MatrixRowSelectionView(this, rowIndices);\r\n }\r\n\r\n /**\r\n * Returns a view of the column indices\r\n * @example\r\n * // resulting vector is [[2, 2], [5, 5]]\r\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).columnSelectionView([1, 1])\r\n * @param {Array} columnIndices\r\n * @return {MatrixColumnSelectionView}\r\n */\r\n columnSelectionView(columnIndices) {\r\n return new MatrixColumnSelectionView(this, columnIndices);\r\n }\r\n\r\n\r\n /**\r\n * Calculates and returns the determinant of a matrix as a Number\r\n * @example\r\n * new Matrix([[1,2,3], [4,5,6]]).det()\r\n * @return {number}\r\n */\r\n det() {\r\n if (this.isSquare()) {\r\n var a, b, c, d;\r\n if (this.columns === 2) {\r\n // 2 x 2 matrix\r\n a = this.get(0, 0);\r\n b = this.get(0, 1);\r\n c = this.get(1, 0);\r\n d = this.get(1, 1);\r\n\r\n return a * d - (b * c);\r\n } else if (this.columns === 3) {\r\n // 3 x 3 matrix\r\n var subMatrix0, subMatrix1, subMatrix2;\r\n subMatrix0 = this.selectionView([1, 2], [1, 2]);\r\n subMatrix1 = this.selectionView([1, 2], [0, 2]);\r\n subMatrix2 = this.selectionView([1, 2], [0, 1]);\r\n a = this.get(0, 0);\r\n b = this.get(0, 1);\r\n c = this.get(0, 2);\r\n\r\n return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det();\r\n } else {\r\n // general purpose determinant using the LU decomposition\r\n return new LuDecomposition(this).determinant;\r\n }\r\n } else {\r\n throw Error('Determinant can only be calculated for a square matrix.');\r\n }\r\n }\r\n\r\n /**\r\n * Returns inverse of a matrix if it exists or the pseudoinverse\r\n * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15)\r\n * @return {Matrix} the (pseudo)inverted matrix.\r\n */\r\n pseudoInverse(threshold) {\r\n if (threshold === undefined) threshold = Number.EPSILON;\r\n var svdSolution = new SvDecomposition(this, { autoTranspose: true });\r\n\r\n var U = svdSolution.leftSingularVectors;\r\n var V = svdSolution.rightSingularVectors;\r\n var s = svdSolution.diagonal;\r\n\r\n for (var i = 0; i < s.length; i++) {\r\n if (Math.abs(s[i]) > threshold) {\r\n s[i] = 1.0 / s[i];\r\n } else {\r\n s[i] = 0.0;\r\n }\r\n }\r\n\r\n // convert list to diagonal\r\n s = this.constructor[Symbol.species].diag(s);\r\n return V.mmul(s.mmul(U.transposeView()));\r\n }\r\n\r\n /**\r\n * Creates an exact and independent copy of the matrix\r\n * @return {Matrix}\r\n */\r\n clone() {\r\n var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns);\r\n for (var row = 0; row < this.rows; row++) {\r\n for (var column = 0; column < this.columns; column++) {\r\n newMatrix.set(row, column, this.get(row, column));\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n }\r\n\r\n Matrix.prototype.klass = 'Matrix';\r\n\r\n function compareNumbers(a, b) {\r\n return a - b;\r\n }\r\n\r\n /*\r\n Synonyms\r\n */\r\n\r\n Matrix.random = Matrix.rand;\r\n Matrix.diagonal = Matrix.diag;\r\n Matrix.prototype.diagonal = Matrix.prototype.diag;\r\n Matrix.identity = Matrix.eye;\r\n Matrix.prototype.negate = Matrix.prototype.neg;\r\n Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct;\r\n Matrix.prototype.determinant = Matrix.prototype.det;\r\n\r\n /*\r\n Add dynamically instance and static methods for mathematical operations\r\n */\r\n\r\n var inplaceOperator = `\r\n(function %name%(value) {\r\n if (typeof value === 'number') return this.%name%S(value);\r\n return this.%name%M(value);\r\n})\r\n`;\r\n\r\n var inplaceOperatorScalar = `\r\n(function %name%S(value) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) %op% value);\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var inplaceOperatorMatrix = `\r\n(function %name%M(matrix) {\r\n matrix = this.constructor.checkMatrix(matrix);\r\n if (this.rows !== matrix.rows ||\r\n this.columns !== matrix.columns) {\r\n throw new RangeError('Matrices dimensions must be equal');\r\n }\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) %op% matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var staticOperator = `\r\n(function %name%(matrix, value) {\r\n var newMatrix = new this[Symbol.species](matrix);\r\n return newMatrix.%name%(value);\r\n})\r\n`;\r\n\r\n var inplaceMethod = `\r\n(function %name%() {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, %method%(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var staticMethod = `\r\n(function %name%(matrix) {\r\n var newMatrix = new this[Symbol.species](matrix);\r\n return newMatrix.%name%();\r\n})\r\n`;\r\n\r\n var inplaceMethodWithArgs = `\r\n(function %name%(%args%) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, %method%(this.get(i, j), %args%));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var staticMethodWithArgs = `\r\n(function %name%(matrix, %args%) {\r\n var newMatrix = new this[Symbol.species](matrix);\r\n return newMatrix.%name%(%args%);\r\n})\r\n`;\r\n\r\n\r\n var inplaceMethodWithOneArgScalar = `\r\n(function %name%S(value) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, %method%(this.get(i, j), value));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n var inplaceMethodWithOneArgMatrix = `\r\n(function %name%M(matrix) {\r\n matrix = this.constructor.checkMatrix(matrix);\r\n if (this.rows !== matrix.rows ||\r\n this.columns !== matrix.columns) {\r\n throw new RangeError('Matrices dimensions must be equal');\r\n }\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, %method%(this.get(i, j), matrix.get(i, j)));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var inplaceMethodWithOneArg = `\r\n(function %name%(value) {\r\n if (typeof value === 'number') return this.%name%S(value);\r\n return this.%name%M(value);\r\n})\r\n`;\r\n\r\n var staticMethodWithOneArg = staticMethodWithArgs;\r\n\r\n var operators = [\r\n // Arithmetic operators\r\n ['+', 'add'],\r\n ['-', 'sub', 'subtract'],\r\n ['*', 'mul', 'multiply'],\r\n ['/', 'div', 'divide'],\r\n ['%', 'mod', 'modulus'],\r\n // Bitwise operators\r\n ['&', 'and'],\r\n ['|', 'or'],\r\n ['^', 'xor'],\r\n ['<<', 'leftShift'],\r\n ['>>', 'signPropagatingRightShift'],\r\n ['>>>', 'rightShift', 'zeroFillRightShift']\r\n ];\r\n\r\n var i;\r\n var eval2 = eval; // eslint-disable-line no-eval\r\n for (var operator of operators) {\r\n var inplaceOp = eval2(fillTemplateFunction(inplaceOperator, { name: operator[1], op: operator[0] }));\r\n var inplaceOpS = eval2(fillTemplateFunction(inplaceOperatorScalar, { name: `${operator[1]}S`, op: operator[0] }));\r\n var inplaceOpM = eval2(fillTemplateFunction(inplaceOperatorMatrix, { name: `${operator[1]}M`, op: operator[0] }));\r\n var staticOp = eval2(fillTemplateFunction(staticOperator, { name: operator[1] }));\r\n for (i = 1; i < operator.length; i++) {\r\n Matrix.prototype[operator[i]] = inplaceOp;\r\n Matrix.prototype[`${operator[i]}S`] = inplaceOpS;\r\n Matrix.prototype[`${operator[i]}M`] = inplaceOpM;\r\n Matrix[operator[i]] = staticOp;\r\n }\r\n }\r\n\r\n var methods = [['~', 'not']];\r\n\r\n [\r\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\r\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\r\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\r\n ].forEach(function (mathMethod) {\r\n methods.push([`Math.${mathMethod}`, mathMethod]);\r\n });\r\n\r\n for (var method of methods) {\r\n var inplaceMeth = eval2(fillTemplateFunction(inplaceMethod, { name: method[1], method: method[0] }));\r\n var staticMeth = eval2(fillTemplateFunction(staticMethod, { name: method[1] }));\r\n for (i = 1; i < method.length; i++) {\r\n Matrix.prototype[method[i]] = inplaceMeth;\r\n Matrix[method[i]] = staticMeth;\r\n }\r\n }\r\n\r\n var methodsWithArgs = [['Math.pow', 1, 'pow']];\r\n\r\n for (var methodWithArg of methodsWithArgs) {\r\n var args = 'arg0';\r\n for (i = 1; i < methodWithArg[1]; i++) {\r\n args += `, arg${i}`;\r\n }\r\n if (methodWithArg[1] !== 1) {\r\n var inplaceMethWithArgs = eval2(fillTemplateFunction(inplaceMethodWithArgs, {\r\n name: methodWithArg[2],\r\n method: methodWithArg[0],\r\n args: args\r\n }));\r\n var staticMethWithArgs = eval2(fillTemplateFunction(staticMethodWithArgs, { name: methodWithArg[2], args: args }));\r\n for (i = 2; i < methodWithArg.length; i++) {\r\n Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs;\r\n Matrix[methodWithArg[i]] = staticMethWithArgs;\r\n }\r\n } else {\r\n var tmplVar = {\r\n name: methodWithArg[2],\r\n args: args,\r\n method: methodWithArg[0]\r\n };\r\n var inplaceMethod2 = eval2(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar));\r\n var inplaceMethodS = eval2(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar));\r\n var inplaceMethodM = eval2(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar));\r\n var staticMethod2 = eval2(fillTemplateFunction(staticMethodWithOneArg, tmplVar));\r\n for (i = 2; i < methodWithArg.length; i++) {\r\n Matrix.prototype[methodWithArg[i]] = inplaceMethod2;\r\n Matrix.prototype[`${methodWithArg[i]}M`] = inplaceMethodM;\r\n Matrix.prototype[`${methodWithArg[i]}S`] = inplaceMethodS;\r\n Matrix[methodWithArg[i]] = staticMethod2;\r\n }\r\n }\r\n }\r\n\r\n function fillTemplateFunction(template, values) {\r\n for (var value in values) {\r\n template = template.replace(new RegExp(`%${value}%`, 'g'), values[value]);\r\n }\r\n return template;\r\n }\r\n\r\n return Matrix;\r\n}\r\n","import AbstractMatrix from './abstractMatrix';\r\nimport {\r\n checkColumnIndex,\r\n checkColumnVector,\r\n checkRowIndex,\r\n checkRowVector\r\n} from './util';\r\n\r\nexport default class Matrix extends AbstractMatrix(Array) {\r\n constructor(nRows, nColumns) {\r\n var i;\r\n if (arguments.length === 1 && typeof nRows === 'number') {\r\n return new Array(nRows);\r\n }\r\n if (Matrix.isMatrix(nRows)) {\r\n return nRows.clone();\r\n } else if (Number.isInteger(nRows) && nRows > 0) {\r\n // Create an empty matrix\r\n super(nRows);\r\n if (Number.isInteger(nColumns) && nColumns > 0) {\r\n for (i = 0; i < nRows; i++) {\r\n this[i] = new Array(nColumns);\r\n }\r\n } else {\r\n throw new TypeError('nColumns must be a positive integer');\r\n }\r\n } else if (Array.isArray(nRows)) {\r\n // Copy the values from the 2D array\r\n const matrix = nRows;\r\n nRows = matrix.length;\r\n nColumns = matrix[0].length;\r\n if (typeof nColumns !== 'number' || nColumns === 0) {\r\n throw new TypeError(\r\n 'Data must be a 2D array with at least one element'\r\n );\r\n }\r\n super(nRows);\r\n for (i = 0; i < nRows; i++) {\r\n if (matrix[i].length !== nColumns) {\r\n throw new RangeError('Inconsistent array dimensions');\r\n }\r\n this[i] = [].concat(matrix[i]);\r\n }\r\n } else {\r\n throw new TypeError(\r\n 'First argument must be a positive number or an array'\r\n );\r\n }\r\n this.rows = nRows;\r\n this.columns = nColumns;\r\n return this;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this[rowIndex][columnIndex] = value;\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this[rowIndex][columnIndex];\r\n }\r\n\r\n /**\r\n * Removes a row from the given index\r\n * @param {number} index - Row index\r\n * @return {Matrix} this\r\n */\r\n removeRow(index) {\r\n checkRowIndex(this, index);\r\n if (this.rows === 1) {\r\n throw new RangeError('A matrix cannot have less than one row');\r\n }\r\n this.splice(index, 1);\r\n this.rows -= 1;\r\n return this;\r\n }\r\n\r\n /**\r\n * Adds a row at the given index\r\n * @param {number} [index = this.rows] - Row index\r\n * @param {Array|Matrix} array - Array or vector\r\n * @return {Matrix} this\r\n */\r\n addRow(index, array) {\r\n if (array === undefined) {\r\n array = index;\r\n index = this.rows;\r\n }\r\n checkRowIndex(this, index, true);\r\n array = checkRowVector(this, array, true);\r\n this.splice(index, 0, array);\r\n this.rows += 1;\r\n return this;\r\n }\r\n\r\n /**\r\n * Removes a column from the given index\r\n * @param {number} index - Column index\r\n * @return {Matrix} this\r\n */\r\n removeColumn(index) {\r\n checkColumnIndex(this, index);\r\n if (this.columns === 1) {\r\n throw new RangeError('A matrix cannot have less than one column');\r\n }\r\n for (var i = 0; i < this.rows; i++) {\r\n this[i].splice(index, 1);\r\n }\r\n this.columns -= 1;\r\n return this;\r\n }\r\n\r\n /**\r\n * Adds a column at the given index\r\n * @param {number} [index = this.columns] - Column index\r\n * @param {Array|Matrix} array - Array or vector\r\n * @return {Matrix} this\r\n */\r\n addColumn(index, array) {\r\n if (typeof array === 'undefined') {\r\n array = index;\r\n index = this.columns;\r\n }\r\n checkColumnIndex(this, index, true);\r\n array = checkColumnVector(this, array);\r\n for (var i = 0; i < this.rows; i++) {\r\n this[i].splice(index, 0, array[i]);\r\n }\r\n this.columns += 1;\r\n return this;\r\n }\r\n}\r\n","import AbstractMatrix from '../abstractMatrix';\r\nimport Matrix from '../matrix';\r\n\r\nexport default class WrapperMatrix1D extends AbstractMatrix() {\r\n /**\r\n * @class WrapperMatrix1D\r\n * @param {Array} data\r\n * @param {object} [options]\r\n * @param {object} [options.rows = 1]\r\n */\r\n constructor(data, options = {}) {\r\n const { rows = 1 } = options;\r\n\r\n if (data.length % rows !== 0) {\r\n throw new Error('the data length is not divisible by the number of rows');\r\n }\r\n super();\r\n this.rows = rows;\r\n this.columns = data.length / rows;\r\n this.data = data;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n var index = this._calculateIndex(rowIndex, columnIndex);\r\n this.data[index] = value;\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n var index = this._calculateIndex(rowIndex, columnIndex);\r\n return this.data[index];\r\n }\r\n\r\n _calculateIndex(row, column) {\r\n return row * this.columns + column;\r\n }\r\n\r\n static get [Symbol.species]() {\r\n return Matrix;\r\n }\r\n}\r\n","import AbstractMatrix from '../abstractMatrix';\r\nimport Matrix from '../matrix';\r\n\r\nexport default class WrapperMatrix2D extends AbstractMatrix() {\r\n /**\r\n * @class WrapperMatrix2D\r\n * @param {Array>} data\r\n */\r\n constructor(data) {\r\n super();\r\n this.data = data;\r\n this.rows = data.length;\r\n this.columns = data[0].length;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.data[rowIndex][columnIndex] = value;\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.data[rowIndex][columnIndex];\r\n }\r\n\r\n static get [Symbol.species]() {\r\n return Matrix;\r\n }\r\n}\r\n","import WrapperMatrix1D from './WrapperMatrix1D';\r\nimport WrapperMatrix2D from './WrapperMatrix2D';\r\n\r\n/**\r\n * @param {Array>|Array} array\r\n * @param {object} [options]\r\n * @param {object} [options.rows = 1]\r\n * @return {WrapperMatrix1D|WrapperMatrix2D}\r\n */\r\nexport function wrap(array, options) {\r\n if (Array.isArray(array)) {\r\n if (array[0] && Array.isArray(array[0])) {\r\n return new WrapperMatrix2D(array);\r\n } else {\r\n return new WrapperMatrix1D(array, options);\r\n }\r\n } else {\r\n throw new Error('the argument is not an array');\r\n }\r\n}\r\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\nimport { hypotenuse } from './util';\r\n\r\n/**\r\n * @class QrDecomposition\r\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs\r\n * @param {Matrix} value\r\n */\r\nexport default class QrDecomposition {\r\n constructor(value) {\r\n value = WrapperMatrix2D.checkMatrix(value);\r\n\r\n var qr = value.clone();\r\n var m = value.rows;\r\n var n = value.columns;\r\n var rdiag = new Array(n);\r\n var i, j, k, s;\r\n\r\n for (k = 0; k < n; k++) {\r\n var nrm = 0;\r\n for (i = k; i < m; i++) {\r\n nrm = hypotenuse(nrm, qr.get(i, k));\r\n }\r\n if (nrm !== 0) {\r\n if (qr.get(k, k) < 0) {\r\n nrm = -nrm;\r\n }\r\n for (i = k; i < m; i++) {\r\n qr.set(i, k, qr.get(i, k) / nrm);\r\n }\r\n qr.set(k, k, qr.get(k, k) + 1);\r\n for (j = k + 1; j < n; j++) {\r\n s = 0;\r\n for (i = k; i < m; i++) {\r\n s += qr.get(i, k) * qr.get(i, j);\r\n }\r\n s = -s / qr.get(k, k);\r\n for (i = k; i < m; i++) {\r\n qr.set(i, j, qr.get(i, j) + s * qr.get(i, k));\r\n }\r\n }\r\n }\r\n rdiag[k] = -nrm;\r\n }\r\n\r\n this.QR = qr;\r\n this.Rdiag = rdiag;\r\n }\r\n\r\n /**\r\n * Solve a problem of least square (Ax=b) by using the QR decomposition. Useful when A is rectangular, but not working when A is singular.\r\n * Example : We search to approximate x, with A matrix shape m*n, x vector size n, b vector size m (m > n). We will use :\r\n * var qr = QrDecomposition(A);\r\n * var x = qr.solve(b);\r\n * @param {Matrix} value - Matrix 1D which is the vector b (in the equation Ax = b)\r\n * @return {Matrix} - The vector x\r\n */\r\n solve(value) {\r\n value = Matrix.checkMatrix(value);\r\n\r\n var qr = this.QR;\r\n var m = qr.rows;\r\n\r\n if (value.rows !== m) {\r\n throw new Error('Matrix row dimensions must agree');\r\n }\r\n if (!this.isFullRank()) {\r\n throw new Error('Matrix is rank deficient');\r\n }\r\n\r\n var count = value.columns;\r\n var X = value.clone();\r\n var n = qr.columns;\r\n var i, j, k, s;\r\n\r\n for (k = 0; k < n; k++) {\r\n for (j = 0; j < count; j++) {\r\n s = 0;\r\n for (i = k; i < m; i++) {\r\n s += qr[i][k] * X[i][j];\r\n }\r\n s = -s / qr[k][k];\r\n for (i = k; i < m; i++) {\r\n X[i][j] += s * qr[i][k];\r\n }\r\n }\r\n }\r\n for (k = n - 1; k >= 0; k--) {\r\n for (j = 0; j < count; j++) {\r\n X[k][j] /= this.Rdiag[k];\r\n }\r\n for (i = 0; i < k; i++) {\r\n for (j = 0; j < count; j++) {\r\n X[i][j] -= X[k][j] * qr[i][k];\r\n }\r\n }\r\n }\r\n\r\n return X.subMatrix(0, n - 1, 0, count - 1);\r\n }\r\n\r\n /**\r\n *\r\n * @return {boolean}\r\n */\r\n isFullRank() {\r\n var columns = this.QR.columns;\r\n for (var i = 0; i < columns; i++) {\r\n if (this.Rdiag[i] === 0) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get upperTriangularMatrix() {\r\n var qr = this.QR;\r\n var n = qr.columns;\r\n var X = new Matrix(n, n);\r\n var i, j;\r\n for (i = 0; i < n; i++) {\r\n for (j = 0; j < n; j++) {\r\n if (i < j) {\r\n X[i][j] = qr[i][j];\r\n } else if (i === j) {\r\n X[i][j] = this.Rdiag[i];\r\n } else {\r\n X[i][j] = 0;\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get orthogonalMatrix() {\r\n var qr = this.QR;\r\n var rows = qr.rows;\r\n var columns = qr.columns;\r\n var X = new Matrix(rows, columns);\r\n var i, j, k, s;\r\n\r\n for (k = columns - 1; k >= 0; k--) {\r\n for (i = 0; i < rows; i++) {\r\n X[i][k] = 0;\r\n }\r\n X[k][k] = 1;\r\n for (j = k; j < columns; j++) {\r\n if (qr[k][k] !== 0) {\r\n s = 0;\r\n for (i = k; i < rows; i++) {\r\n s += qr[i][k] * X[i][j];\r\n }\r\n\r\n s = -s / qr[k][k];\r\n\r\n for (i = k; i < rows; i++) {\r\n X[i][j] += s * qr[i][k];\r\n }\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n}\r\n","import LuDecomposition from './dc/lu';\r\nimport QrDecomposition from './dc/qr';\r\nimport SingularValueDecomposition from './dc/svd';\r\n\r\nimport { Matrix, WrapperMatrix2D } from './index';\r\n\r\n/**\r\n * Computes the inverse of a Matrix\r\n * @param {Matrix} matrix\r\n * @param {boolean} [useSVD=false]\r\n * @return {Matrix}\r\n */\r\nexport function inverse(matrix, useSVD = false) {\r\n matrix = WrapperMatrix2D.checkMatrix(matrix);\r\n if (useSVD) {\r\n return new SingularValueDecomposition(matrix).inverse();\r\n } else {\r\n return solve(matrix, Matrix.eye(matrix.rows));\r\n }\r\n}\r\n\r\n/**\r\n *\r\n * @param {Matrix} leftHandSide\r\n * @param {Matrix} rightHandSide\r\n * @param {boolean} [useSVD = false]\r\n * @return {Matrix}\r\n */\r\nexport function solve(leftHandSide, rightHandSide, useSVD = false) {\r\n leftHandSide = WrapperMatrix2D.checkMatrix(leftHandSide);\r\n rightHandSide = WrapperMatrix2D.checkMatrix(rightHandSide);\r\n if (useSVD) {\r\n return new SingularValueDecomposition(leftHandSide).solve(rightHandSide);\r\n } else {\r\n return leftHandSide.isSquare()\r\n ? new LuDecomposition(leftHandSide).solve(rightHandSide)\r\n : new QrDecomposition(leftHandSide).solve(rightHandSide);\r\n }\r\n}\r\n","import max from 'ml-array-max';\r\n\r\nimport Matrix from './matrix';\r\nimport SingularValueDecomposition from './dc/svd';\r\n\r\n// function used by rowsDependencies\r\nfunction xrange(n, exception) {\r\n var range = [];\r\n for (var i = 0; i < n; i++) {\r\n if (i !== exception) {\r\n range.push(i);\r\n }\r\n }\r\n return range;\r\n}\r\n\r\n// function used by rowsDependencies\r\nfunction dependenciesOneRow(\r\n error,\r\n matrix,\r\n index,\r\n thresholdValue = 10e-10,\r\n thresholdError = 10e-10\r\n) {\r\n if (error > thresholdError) {\r\n return new Array(matrix.rows + 1).fill(0);\r\n } else {\r\n var returnArray = matrix.addRow(index, [0]);\r\n for (var i = 0; i < returnArray.rows; i++) {\r\n if (Math.abs(returnArray.get(i, 0)) < thresholdValue) {\r\n returnArray.set(i, 0, 0);\r\n }\r\n }\r\n return returnArray.to1DArray();\r\n }\r\n}\r\n\r\n/**\r\n * Creates a matrix which represents the dependencies between rows.\r\n * If a row is a linear combination of others rows, the result will be a row with the coefficients of this combination.\r\n * For example : for A = [[2, 0, 0, 1], [0, 1, 6, 0], [0, 3, 0, 1], [0, 0, 1, 0], [0, 1, 2, 0]], the result will be [[0, 0, 0, 0, 0], [0, 0, 0, 4, 1], [0, 0, 0, 0, 0], [0, 0.25, 0, 0, -0.25], [0, 1, 0, -4, 0]]\r\n * @param {Matrix} matrix\r\n * @param {Object} [options] includes thresholdValue and thresholdError.\r\n * @param {number} [options.thresholdValue = 10e-10] If an absolute value is inferior to this threshold, it will equals zero.\r\n * @param {number} [options.thresholdError = 10e-10] If the error is inferior to that threshold, the linear combination found is accepted and the row is dependent from other rows.\r\n * @return {Matrix} the matrix which represents the dependencies between rows.\r\n */\r\n\r\nexport function linearDependencies(matrix, options = {}) {\r\n const { thresholdValue = 10e-10, thresholdError = 10e-10 } = options;\r\n\r\n var n = matrix.rows;\r\n var results = new Matrix(n, n);\r\n\r\n for (var i = 0; i < n; i++) {\r\n var b = Matrix.columnVector(matrix.getRow(i));\r\n var Abis = matrix.subMatrixRow(xrange(n, i)).transposeView();\r\n var svd = new SingularValueDecomposition(Abis);\r\n var x = svd.solve(b);\r\n var error = max(\r\n Matrix.sub(b, Abis.mmul(x))\r\n .abs()\r\n .to1DArray()\r\n );\r\n results.setRow(\r\n i,\r\n dependenciesOneRow(error, x, i, thresholdValue, thresholdError)\r\n );\r\n }\r\n return results;\r\n}\r\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\nimport { hypotenuse, getFilled2DArray } from './util';\r\n\r\n/**\r\n * @class EigenvalueDecomposition\r\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs\r\n * @param {Matrix} matrix\r\n * @param {object} [options]\r\n * @param {boolean} [options.assumeSymmetric=false]\r\n */\r\nexport default class EigenvalueDecomposition {\r\n constructor(matrix, options = {}) {\r\n const { assumeSymmetric = false } = options;\r\n\r\n matrix = WrapperMatrix2D.checkMatrix(matrix);\r\n if (!matrix.isSquare()) {\r\n throw new Error('Matrix is not a square matrix');\r\n }\r\n\r\n var n = matrix.columns;\r\n var V = getFilled2DArray(n, n, 0);\r\n var d = new Array(n);\r\n var e = new Array(n);\r\n var value = matrix;\r\n var i, j;\r\n\r\n var isSymmetric = false;\r\n if (assumeSymmetric) {\r\n isSymmetric = true;\r\n } else {\r\n isSymmetric = matrix.isSymmetric();\r\n }\r\n\r\n if (isSymmetric) {\r\n for (i = 0; i < n; i++) {\r\n for (j = 0; j < n; j++) {\r\n V[i][j] = value.get(i, j);\r\n }\r\n }\r\n tred2(n, e, d, V);\r\n tql2(n, e, d, V);\r\n } else {\r\n var H = getFilled2DArray(n, n, 0);\r\n var ort = new Array(n);\r\n for (j = 0; j < n; j++) {\r\n for (i = 0; i < n; i++) {\r\n H[i][j] = value.get(i, j);\r\n }\r\n }\r\n orthes(n, H, ort, V);\r\n hqr2(n, e, d, V, H);\r\n }\r\n\r\n this.n = n;\r\n this.e = e;\r\n this.d = d;\r\n this.V = V;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Array}\r\n */\r\n get realEigenvalues() {\r\n return this.d;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Array}\r\n */\r\n get imaginaryEigenvalues() {\r\n return this.e;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get eigenvectorMatrix() {\r\n if (!Matrix.isMatrix(this.V)) {\r\n this.V = new Matrix(this.V);\r\n }\r\n return this.V;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get diagonalMatrix() {\r\n var n = this.n;\r\n var e = this.e;\r\n var d = this.d;\r\n var X = new Matrix(n, n);\r\n var i, j;\r\n for (i = 0; i < n; i++) {\r\n for (j = 0; j < n; j++) {\r\n X[i][j] = 0;\r\n }\r\n X[i][i] = d[i];\r\n if (e[i] > 0) {\r\n X[i][i + 1] = e[i];\r\n } else if (e[i] < 0) {\r\n X[i][i - 1] = e[i];\r\n }\r\n }\r\n return X;\r\n }\r\n}\r\n\r\nfunction tred2(n, e, d, V) {\r\n var f, g, h, i, j, k, hh, scale;\r\n\r\n for (j = 0; j < n; j++) {\r\n d[j] = V[n - 1][j];\r\n }\r\n\r\n for (i = n - 1; i > 0; i--) {\r\n scale = 0;\r\n h = 0;\r\n for (k = 0; k < i; k++) {\r\n scale = scale + Math.abs(d[k]);\r\n }\r\n\r\n if (scale === 0) {\r\n e[i] = d[i - 1];\r\n for (j = 0; j < i; j++) {\r\n d[j] = V[i - 1][j];\r\n V[i][j] = 0;\r\n V[j][i] = 0;\r\n }\r\n } else {\r\n for (k = 0; k < i; k++) {\r\n d[k] /= scale;\r\n h += d[k] * d[k];\r\n }\r\n\r\n f = d[i - 1];\r\n g = Math.sqrt(h);\r\n if (f > 0) {\r\n g = -g;\r\n }\r\n\r\n e[i] = scale * g;\r\n h = h - f * g;\r\n d[i - 1] = f - g;\r\n for (j = 0; j < i; j++) {\r\n e[j] = 0;\r\n }\r\n\r\n for (j = 0; j < i; j++) {\r\n f = d[j];\r\n V[j][i] = f;\r\n g = e[j] + V[j][j] * f;\r\n for (k = j + 1; k <= i - 1; k++) {\r\n g += V[k][j] * d[k];\r\n e[k] += V[k][j] * f;\r\n }\r\n e[j] = g;\r\n }\r\n\r\n f = 0;\r\n for (j = 0; j < i; j++) {\r\n e[j] /= h;\r\n f += e[j] * d[j];\r\n }\r\n\r\n hh = f / (h + h);\r\n for (j = 0; j < i; j++) {\r\n e[j] -= hh * d[j];\r\n }\r\n\r\n for (j = 0; j < i; j++) {\r\n f = d[j];\r\n g = e[j];\r\n for (k = j; k <= i - 1; k++) {\r\n V[k][j] -= f * e[k] + g * d[k];\r\n }\r\n d[j] = V[i - 1][j];\r\n V[i][j] = 0;\r\n }\r\n }\r\n d[i] = h;\r\n }\r\n\r\n for (i = 0; i < n - 1; i++) {\r\n V[n - 1][i] = V[i][i];\r\n V[i][i] = 1;\r\n h = d[i + 1];\r\n if (h !== 0) {\r\n for (k = 0; k <= i; k++) {\r\n d[k] = V[k][i + 1] / h;\r\n }\r\n\r\n for (j = 0; j <= i; j++) {\r\n g = 0;\r\n for (k = 0; k <= i; k++) {\r\n g += V[k][i + 1] * V[k][j];\r\n }\r\n for (k = 0; k <= i; k++) {\r\n V[k][j] -= g * d[k];\r\n }\r\n }\r\n }\r\n\r\n for (k = 0; k <= i; k++) {\r\n V[k][i + 1] = 0;\r\n }\r\n }\r\n\r\n for (j = 0; j < n; j++) {\r\n d[j] = V[n - 1][j];\r\n V[n - 1][j] = 0;\r\n }\r\n\r\n V[n - 1][n - 1] = 1;\r\n e[0] = 0;\r\n}\r\n\r\nfunction tql2(n, e, d, V) {\r\n var g, h, i, j, k, l, m, p, r, dl1, c, c2, c3, el1, s, s2, iter;\r\n\r\n for (i = 1; i < n; i++) {\r\n e[i - 1] = e[i];\r\n }\r\n\r\n e[n - 1] = 0;\r\n\r\n var f = 0;\r\n var tst1 = 0;\r\n var eps = Number.EPSILON;\r\n\r\n for (l = 0; l < n; l++) {\r\n tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));\r\n m = l;\r\n while (m < n) {\r\n if (Math.abs(e[m]) <= eps * tst1) {\r\n break;\r\n }\r\n m++;\r\n }\r\n\r\n if (m > l) {\r\n iter = 0;\r\n do {\r\n iter = iter + 1;\r\n\r\n g = d[l];\r\n p = (d[l + 1] - g) / (2 * e[l]);\r\n r = hypotenuse(p, 1);\r\n if (p < 0) {\r\n r = -r;\r\n }\r\n\r\n d[l] = e[l] / (p + r);\r\n d[l + 1] = e[l] * (p + r);\r\n dl1 = d[l + 1];\r\n h = g - d[l];\r\n for (i = l + 2; i < n; i++) {\r\n d[i] -= h;\r\n }\r\n\r\n f = f + h;\r\n\r\n p = d[m];\r\n c = 1;\r\n c2 = c;\r\n c3 = c;\r\n el1 = e[l + 1];\r\n s = 0;\r\n s2 = 0;\r\n for (i = m - 1; i >= l; i--) {\r\n c3 = c2;\r\n c2 = c;\r\n s2 = s;\r\n g = c * e[i];\r\n h = c * p;\r\n r = hypotenuse(p, e[i]);\r\n e[i + 1] = s * r;\r\n s = e[i] / r;\r\n c = p / r;\r\n p = c * d[i] - s * g;\r\n d[i + 1] = h + s * (c * g + s * d[i]);\r\n\r\n for (k = 0; k < n; k++) {\r\n h = V[k][i + 1];\r\n V[k][i + 1] = s * V[k][i] + c * h;\r\n V[k][i] = c * V[k][i] - s * h;\r\n }\r\n }\r\n\r\n p = -s * s2 * c3 * el1 * e[l] / dl1;\r\n e[l] = s * p;\r\n d[l] = c * p;\r\n } while (Math.abs(e[l]) > eps * tst1);\r\n }\r\n d[l] = d[l] + f;\r\n e[l] = 0;\r\n }\r\n\r\n for (i = 0; i < n - 1; i++) {\r\n k = i;\r\n p = d[i];\r\n for (j = i + 1; j < n; j++) {\r\n if (d[j] < p) {\r\n k = j;\r\n p = d[j];\r\n }\r\n }\r\n\r\n if (k !== i) {\r\n d[k] = d[i];\r\n d[i] = p;\r\n for (j = 0; j < n; j++) {\r\n p = V[j][i];\r\n V[j][i] = V[j][k];\r\n V[j][k] = p;\r\n }\r\n }\r\n }\r\n}\r\n\r\nfunction orthes(n, H, ort, V) {\r\n var low = 0;\r\n var high = n - 1;\r\n var f, g, h, i, j, m;\r\n var scale;\r\n\r\n for (m = low + 1; m <= high - 1; m++) {\r\n scale = 0;\r\n for (i = m; i <= high; i++) {\r\n scale = scale + Math.abs(H[i][m - 1]);\r\n }\r\n\r\n if (scale !== 0) {\r\n h = 0;\r\n for (i = high; i >= m; i--) {\r\n ort[i] = H[i][m - 1] / scale;\r\n h += ort[i] * ort[i];\r\n }\r\n\r\n g = Math.sqrt(h);\r\n if (ort[m] > 0) {\r\n g = -g;\r\n }\r\n\r\n h = h - ort[m] * g;\r\n ort[m] = ort[m] - g;\r\n\r\n for (j = m; j < n; j++) {\r\n f = 0;\r\n for (i = high; i >= m; i--) {\r\n f += ort[i] * H[i][j];\r\n }\r\n\r\n f = f / h;\r\n for (i = m; i <= high; i++) {\r\n H[i][j] -= f * ort[i];\r\n }\r\n }\r\n\r\n for (i = 0; i <= high; i++) {\r\n f = 0;\r\n for (j = high; j >= m; j--) {\r\n f += ort[j] * H[i][j];\r\n }\r\n\r\n f = f / h;\r\n for (j = m; j <= high; j++) {\r\n H[i][j] -= f * ort[j];\r\n }\r\n }\r\n\r\n ort[m] = scale * ort[m];\r\n H[m][m - 1] = scale * g;\r\n }\r\n }\r\n\r\n for (i = 0; i < n; i++) {\r\n for (j = 0; j < n; j++) {\r\n V[i][j] = i === j ? 1 : 0;\r\n }\r\n }\r\n\r\n for (m = high - 1; m >= low + 1; m--) {\r\n if (H[m][m - 1] !== 0) {\r\n for (i = m + 1; i <= high; i++) {\r\n ort[i] = H[i][m - 1];\r\n }\r\n\r\n for (j = m; j <= high; j++) {\r\n g = 0;\r\n for (i = m; i <= high; i++) {\r\n g += ort[i] * V[i][j];\r\n }\r\n\r\n g = g / ort[m] / H[m][m - 1];\r\n for (i = m; i <= high; i++) {\r\n V[i][j] += g * ort[i];\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nfunction hqr2(nn, e, d, V, H) {\r\n var n = nn - 1;\r\n var low = 0;\r\n var high = nn - 1;\r\n var eps = Number.EPSILON;\r\n var exshift = 0;\r\n var norm = 0;\r\n var p = 0;\r\n var q = 0;\r\n var r = 0;\r\n var s = 0;\r\n var z = 0;\r\n var iter = 0;\r\n var i, j, k, l, m, t, w, x, y;\r\n var ra, sa, vr, vi;\r\n var notlast, cdivres;\r\n\r\n for (i = 0; i < nn; i++) {\r\n if (i < low || i > high) {\r\n d[i] = H[i][i];\r\n e[i] = 0;\r\n }\r\n\r\n for (j = Math.max(i - 1, 0); j < nn; j++) {\r\n norm = norm + Math.abs(H[i][j]);\r\n }\r\n }\r\n\r\n while (n >= low) {\r\n l = n;\r\n while (l > low) {\r\n s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]);\r\n if (s === 0) {\r\n s = norm;\r\n }\r\n if (Math.abs(H[l][l - 1]) < eps * s) {\r\n break;\r\n }\r\n l--;\r\n }\r\n\r\n if (l === n) {\r\n H[n][n] = H[n][n] + exshift;\r\n d[n] = H[n][n];\r\n e[n] = 0;\r\n n--;\r\n iter = 0;\r\n } else if (l === n - 1) {\r\n w = H[n][n - 1] * H[n - 1][n];\r\n p = (H[n - 1][n - 1] - H[n][n]) / 2;\r\n q = p * p + w;\r\n z = Math.sqrt(Math.abs(q));\r\n H[n][n] = H[n][n] + exshift;\r\n H[n - 1][n - 1] = H[n - 1][n - 1] + exshift;\r\n x = H[n][n];\r\n\r\n if (q >= 0) {\r\n z = p >= 0 ? p + z : p - z;\r\n d[n - 1] = x + z;\r\n d[n] = d[n - 1];\r\n if (z !== 0) {\r\n d[n] = x - w / z;\r\n }\r\n e[n - 1] = 0;\r\n e[n] = 0;\r\n x = H[n][n - 1];\r\n s = Math.abs(x) + Math.abs(z);\r\n p = x / s;\r\n q = z / s;\r\n r = Math.sqrt(p * p + q * q);\r\n p = p / r;\r\n q = q / r;\r\n\r\n for (j = n - 1; j < nn; j++) {\r\n z = H[n - 1][j];\r\n H[n - 1][j] = q * z + p * H[n][j];\r\n H[n][j] = q * H[n][j] - p * z;\r\n }\r\n\r\n for (i = 0; i <= n; i++) {\r\n z = H[i][n - 1];\r\n H[i][n - 1] = q * z + p * H[i][n];\r\n H[i][n] = q * H[i][n] - p * z;\r\n }\r\n\r\n for (i = low; i <= high; i++) {\r\n z = V[i][n - 1];\r\n V[i][n - 1] = q * z + p * V[i][n];\r\n V[i][n] = q * V[i][n] - p * z;\r\n }\r\n } else {\r\n d[n - 1] = x + p;\r\n d[n] = x + p;\r\n e[n - 1] = z;\r\n e[n] = -z;\r\n }\r\n\r\n n = n - 2;\r\n iter = 0;\r\n } else {\r\n x = H[n][n];\r\n y = 0;\r\n w = 0;\r\n if (l < n) {\r\n y = H[n - 1][n - 1];\r\n w = H[n][n - 1] * H[n - 1][n];\r\n }\r\n\r\n if (iter === 10) {\r\n exshift += x;\r\n for (i = low; i <= n; i++) {\r\n H[i][i] -= x;\r\n }\r\n s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]);\r\n x = y = 0.75 * s;\r\n w = -0.4375 * s * s;\r\n }\r\n\r\n if (iter === 30) {\r\n s = (y - x) / 2;\r\n s = s * s + w;\r\n if (s > 0) {\r\n s = Math.sqrt(s);\r\n if (y < x) {\r\n s = -s;\r\n }\r\n s = x - w / ((y - x) / 2 + s);\r\n for (i = low; i <= n; i++) {\r\n H[i][i] -= s;\r\n }\r\n exshift += s;\r\n x = y = w = 0.964;\r\n }\r\n }\r\n\r\n iter = iter + 1;\r\n\r\n m = n - 2;\r\n while (m >= l) {\r\n z = H[m][m];\r\n r = x - z;\r\n s = y - z;\r\n p = (r * s - w) / H[m + 1][m] + H[m][m + 1];\r\n q = H[m + 1][m + 1] - z - r - s;\r\n r = H[m + 2][m + 1];\r\n s = Math.abs(p) + Math.abs(q) + Math.abs(r);\r\n p = p / s;\r\n q = q / s;\r\n r = r / s;\r\n if (m === l) {\r\n break;\r\n }\r\n if (\r\n Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) <\r\n eps *\r\n (Math.abs(p) *\r\n (Math.abs(H[m - 1][m - 1]) +\r\n Math.abs(z) +\r\n Math.abs(H[m + 1][m + 1])))\r\n ) {\r\n break;\r\n }\r\n m--;\r\n }\r\n\r\n for (i = m + 2; i <= n; i++) {\r\n H[i][i - 2] = 0;\r\n if (i > m + 2) {\r\n H[i][i - 3] = 0;\r\n }\r\n }\r\n\r\n for (k = m; k <= n - 1; k++) {\r\n notlast = k !== n - 1;\r\n if (k !== m) {\r\n p = H[k][k - 1];\r\n q = H[k + 1][k - 1];\r\n r = notlast ? H[k + 2][k - 1] : 0;\r\n x = Math.abs(p) + Math.abs(q) + Math.abs(r);\r\n if (x !== 0) {\r\n p = p / x;\r\n q = q / x;\r\n r = r / x;\r\n }\r\n }\r\n\r\n if (x === 0) {\r\n break;\r\n }\r\n\r\n s = Math.sqrt(p * p + q * q + r * r);\r\n if (p < 0) {\r\n s = -s;\r\n }\r\n\r\n if (s !== 0) {\r\n if (k !== m) {\r\n H[k][k - 1] = -s * x;\r\n } else if (l !== m) {\r\n H[k][k - 1] = -H[k][k - 1];\r\n }\r\n\r\n p = p + s;\r\n x = p / s;\r\n y = q / s;\r\n z = r / s;\r\n q = q / p;\r\n r = r / p;\r\n\r\n for (j = k; j < nn; j++) {\r\n p = H[k][j] + q * H[k + 1][j];\r\n if (notlast) {\r\n p = p + r * H[k + 2][j];\r\n H[k + 2][j] = H[k + 2][j] - p * z;\r\n }\r\n\r\n H[k][j] = H[k][j] - p * x;\r\n H[k + 1][j] = H[k + 1][j] - p * y;\r\n }\r\n\r\n for (i = 0; i <= Math.min(n, k + 3); i++) {\r\n p = x * H[i][k] + y * H[i][k + 1];\r\n if (notlast) {\r\n p = p + z * H[i][k + 2];\r\n H[i][k + 2] = H[i][k + 2] - p * r;\r\n }\r\n\r\n H[i][k] = H[i][k] - p;\r\n H[i][k + 1] = H[i][k + 1] - p * q;\r\n }\r\n\r\n for (i = low; i <= high; i++) {\r\n p = x * V[i][k] + y * V[i][k + 1];\r\n if (notlast) {\r\n p = p + z * V[i][k + 2];\r\n V[i][k + 2] = V[i][k + 2] - p * r;\r\n }\r\n\r\n V[i][k] = V[i][k] - p;\r\n V[i][k + 1] = V[i][k + 1] - p * q;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (norm === 0) {\r\n return;\r\n }\r\n\r\n for (n = nn - 1; n >= 0; n--) {\r\n p = d[n];\r\n q = e[n];\r\n\r\n if (q === 0) {\r\n l = n;\r\n H[n][n] = 1;\r\n for (i = n - 1; i >= 0; i--) {\r\n w = H[i][i] - p;\r\n r = 0;\r\n for (j = l; j <= n; j++) {\r\n r = r + H[i][j] * H[j][n];\r\n }\r\n\r\n if (e[i] < 0) {\r\n z = w;\r\n s = r;\r\n } else {\r\n l = i;\r\n if (e[i] === 0) {\r\n H[i][n] = w !== 0 ? -r / w : -r / (eps * norm);\r\n } else {\r\n x = H[i][i + 1];\r\n y = H[i + 1][i];\r\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\r\n t = (x * s - z * r) / q;\r\n H[i][n] = t;\r\n H[i + 1][n] =\r\n Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z;\r\n }\r\n\r\n t = Math.abs(H[i][n]);\r\n if (eps * t * t > 1) {\r\n for (j = i; j <= n; j++) {\r\n H[j][n] = H[j][n] / t;\r\n }\r\n }\r\n }\r\n }\r\n } else if (q < 0) {\r\n l = n - 1;\r\n\r\n if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) {\r\n H[n - 1][n - 1] = q / H[n][n - 1];\r\n H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1];\r\n } else {\r\n cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q);\r\n H[n - 1][n - 1] = cdivres[0];\r\n H[n - 1][n] = cdivres[1];\r\n }\r\n\r\n H[n][n - 1] = 0;\r\n H[n][n] = 1;\r\n for (i = n - 2; i >= 0; i--) {\r\n ra = 0;\r\n sa = 0;\r\n for (j = l; j <= n; j++) {\r\n ra = ra + H[i][j] * H[j][n - 1];\r\n sa = sa + H[i][j] * H[j][n];\r\n }\r\n\r\n w = H[i][i] - p;\r\n\r\n if (e[i] < 0) {\r\n z = w;\r\n r = ra;\r\n s = sa;\r\n } else {\r\n l = i;\r\n if (e[i] === 0) {\r\n cdivres = cdiv(-ra, -sa, w, q);\r\n H[i][n - 1] = cdivres[0];\r\n H[i][n] = cdivres[1];\r\n } else {\r\n x = H[i][i + 1];\r\n y = H[i + 1][i];\r\n vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;\r\n vi = (d[i] - p) * 2 * q;\r\n if (vr === 0 && vi === 0) {\r\n vr =\r\n eps *\r\n norm *\r\n (Math.abs(w) +\r\n Math.abs(q) +\r\n Math.abs(x) +\r\n Math.abs(y) +\r\n Math.abs(z));\r\n }\r\n cdivres = cdiv(\r\n x * r - z * ra + q * sa,\r\n x * s - z * sa - q * ra,\r\n vr,\r\n vi\r\n );\r\n H[i][n - 1] = cdivres[0];\r\n H[i][n] = cdivres[1];\r\n if (Math.abs(x) > Math.abs(z) + Math.abs(q)) {\r\n H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x;\r\n H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x;\r\n } else {\r\n cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q);\r\n H[i + 1][n - 1] = cdivres[0];\r\n H[i + 1][n] = cdivres[1];\r\n }\r\n }\r\n\r\n t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n]));\r\n if (eps * t * t > 1) {\r\n for (j = i; j <= n; j++) {\r\n H[j][n - 1] = H[j][n - 1] / t;\r\n H[j][n] = H[j][n] / t;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n for (i = 0; i < nn; i++) {\r\n if (i < low || i > high) {\r\n for (j = i; j < nn; j++) {\r\n V[i][j] = H[i][j];\r\n }\r\n }\r\n }\r\n\r\n for (j = nn - 1; j >= low; j--) {\r\n for (i = low; i <= high; i++) {\r\n z = 0;\r\n for (k = low; k <= Math.min(j, high); k++) {\r\n z = z + V[i][k] * H[k][j];\r\n }\r\n V[i][j] = z;\r\n }\r\n }\r\n}\r\n\r\nfunction cdiv(xr, xi, yr, yi) {\r\n var r, d;\r\n if (Math.abs(yr) > Math.abs(yi)) {\r\n r = yi / yr;\r\n d = yr + r * yi;\r\n return [(xr + r * xi) / d, (xi - r * xr) / d];\r\n } else {\r\n r = yr / yi;\r\n d = yi + r * yr;\r\n return [(r * xr + xi) / d, (r * xi - xr) / d];\r\n }\r\n}\r\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\n/**\r\n * @class CholeskyDecomposition\r\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs\r\n * @param {Matrix} value\r\n */\r\nexport default class CholeskyDecomposition {\r\n constructor(value) {\r\n value = WrapperMatrix2D.checkMatrix(value);\r\n if (!value.isSymmetric()) {\r\n throw new Error('Matrix is not symmetric');\r\n }\r\n\r\n var a = value;\r\n var dimension = a.rows;\r\n var l = new Matrix(dimension, dimension);\r\n var positiveDefinite = true;\r\n var i, j, k;\r\n\r\n for (j = 0; j < dimension; j++) {\r\n var Lrowj = l[j];\r\n var d = 0;\r\n for (k = 0; k < j; k++) {\r\n var Lrowk = l[k];\r\n var s = 0;\r\n for (i = 0; i < k; i++) {\r\n s += Lrowk[i] * Lrowj[i];\r\n }\r\n Lrowj[k] = s = (a.get(j, k) - s) / l[k][k];\r\n d = d + s * s;\r\n }\r\n\r\n d = a.get(j, j) - d;\r\n\r\n positiveDefinite &= d > 0;\r\n l[j][j] = Math.sqrt(Math.max(d, 0));\r\n for (k = j + 1; k < dimension; k++) {\r\n l[j][k] = 0;\r\n }\r\n }\r\n\r\n if (!positiveDefinite) {\r\n throw new Error('Matrix is not positive definite');\r\n }\r\n\r\n this.L = l;\r\n }\r\n\r\n /**\r\n *\r\n * @param {Matrix} value\r\n * @return {Matrix}\r\n */\r\n solve(value) {\r\n value = WrapperMatrix2D.checkMatrix(value);\r\n\r\n var l = this.L;\r\n var dimension = l.rows;\r\n\r\n if (value.rows !== dimension) {\r\n throw new Error('Matrix dimensions do not match');\r\n }\r\n\r\n var count = value.columns;\r\n var B = value.clone();\r\n var i, j, k;\r\n\r\n for (k = 0; k < dimension; k++) {\r\n for (j = 0; j < count; j++) {\r\n for (i = 0; i < k; i++) {\r\n B[k][j] -= B[i][j] * l[k][i];\r\n }\r\n B[k][j] /= l[k][k];\r\n }\r\n }\r\n\r\n for (k = dimension - 1; k >= 0; k--) {\r\n for (j = 0; j < count; j++) {\r\n for (i = k + 1; i < dimension; i++) {\r\n B[k][j] -= B[i][j] * l[i][k];\r\n }\r\n B[k][j] /= l[k][k];\r\n }\r\n }\r\n\r\n return B;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get lowerTriangularMatrix() {\r\n return this.L;\r\n }\r\n}\r\n","export { default, default as Matrix } from './matrix';\r\nexport { default as abstractMatrix } from './abstractMatrix';\r\n\r\nexport { wrap } from './wrap/wrap';\r\nexport { default as WrapperMatrix2D } from './wrap/WrapperMatrix2D';\r\nexport { default as WrapperMatrix1D } from './wrap/WrapperMatrix1D';\r\n\r\nexport { solve, inverse } from './decompositions';\r\nexport { linearDependencies } from './linearDependencies';\r\nexport {\r\n default as SingularValueDecomposition,\r\n default as SVD\r\n} from './dc/svd.js';\r\nexport {\r\n default as EigenvalueDecomposition,\r\n default as EVD\r\n} from './dc/evd.js';\r\nexport {\r\n default as CholeskyDecomposition,\r\n default as CHO\r\n} from './dc/cholesky.js';\r\nexport { default as LuDecomposition, default as LU } from './dc/lu.js';\r\nexport { default as QrDecomposition, default as QR } from './dc/qr.js';\r\n","'use strict';\n\nconst toString = Object.prototype.toString;\n\nfunction isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n\nmodule.exports = isAnyArray;\n","'use strict';\n\nfunction squaredEuclidean(p, q) {\n var d = 0;\n for (var i = 0; i < p.length; i++) {\n d += (p[i] - q[i]) * (p[i] - q[i]);\n }\n return d;\n}\n\nfunction euclidean(p, q) {\n return Math.sqrt(squaredEuclidean(p, q));\n}\n\nmodule.exports = euclidean;\neuclidean.squared = squaredEuclidean;\n","'use strict';\n\nexports.array = require('./array');\nexports.matrix = require('./matrix');\n","'use strict';\n\nvar arrayStat = require('./array');\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nexports.max = function max(matrix) {\n var max = -Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] > max) max = matrix[i][j];\n }\n }\n return max;\n};\n\nexports.min = function min(matrix) {\n var min = Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] < min) min = matrix[i][j];\n }\n }\n return min;\n};\n\nexports.minMax = function minMax(matrix) {\n var min = Infinity;\n var max = -Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] < min) min = matrix[i][j];\n if (matrix[i][j] > max) max = matrix[i][j];\n }\n }\n return {\n min:min,\n max:max\n };\n};\n\nexports.entropy = function entropy(matrix, eps) {\n if (typeof (eps) === 'undefined') {\n eps = 0;\n }\n var sum = 0,\n l1 = matrix.length,\n l2 = matrix[0].length;\n for (var i = 0; i < l1; i++) {\n for (var j = 0; j < l2; j++) {\n sum += matrix[i][j] * Math.log(matrix[i][j] + eps);\n }\n }\n return -sum;\n};\n\nexports.mean = function mean(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theMean, N, i, j;\n\n if (dimension === -1) {\n theMean = [0];\n N = rows * cols;\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theMean[0] += matrix[i][j];\n }\n }\n theMean[0] /= N;\n } else if (dimension === 0) {\n theMean = new Array(cols);\n N = rows;\n for (j = 0; j < cols; j++) {\n theMean[j] = 0;\n for (i = 0; i < rows; i++) {\n theMean[j] += matrix[i][j];\n }\n theMean[j] /= N;\n }\n } else if (dimension === 1) {\n theMean = new Array(rows);\n N = cols;\n for (j = 0; j < rows; j++) {\n theMean[j] = 0;\n for (i = 0; i < cols; i++) {\n theMean[j] += matrix[j][i];\n }\n theMean[j] /= N;\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theMean;\n};\n\nexports.sum = function sum(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theSum, i, j;\n\n if (dimension === -1) {\n theSum = [0];\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theSum[0] += matrix[i][j];\n }\n }\n } else if (dimension === 0) {\n theSum = new Array(cols);\n for (j = 0; j < cols; j++) {\n theSum[j] = 0;\n for (i = 0; i < rows; i++) {\n theSum[j] += matrix[i][j];\n }\n }\n } else if (dimension === 1) {\n theSum = new Array(rows);\n for (j = 0; j < rows; j++) {\n theSum[j] = 0;\n for (i = 0; i < cols; i++) {\n theSum[j] += matrix[j][i];\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theSum;\n};\n\nexports.product = function product(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theProduct, i, j;\n\n if (dimension === -1) {\n theProduct = [1];\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theProduct[0] *= matrix[i][j];\n }\n }\n } else if (dimension === 0) {\n theProduct = new Array(cols);\n for (j = 0; j < cols; j++) {\n theProduct[j] = 1;\n for (i = 0; i < rows; i++) {\n theProduct[j] *= matrix[i][j];\n }\n }\n } else if (dimension === 1) {\n theProduct = new Array(rows);\n for (j = 0; j < rows; j++) {\n theProduct[j] = 1;\n for (i = 0; i < cols; i++) {\n theProduct[j] *= matrix[j][i];\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theProduct;\n};\n\nexports.standardDeviation = function standardDeviation(matrix, means, unbiased) {\n var vari = exports.variance(matrix, means, unbiased), l = vari.length;\n for (var i = 0; i < l; i++) {\n vari[i] = Math.sqrt(vari[i]);\n }\n return vari;\n};\n\nexports.variance = function variance(matrix, means, unbiased) {\n if (typeof (unbiased) === 'undefined') {\n unbiased = true;\n }\n means = means || exports.mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum1 = 0, sum2 = 0, x = 0;\n for (var i = 0; i < rows; i++) {\n x = matrix[i][j] - means[j];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / (rows - 1);\n } else {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / rows;\n }\n }\n return vari;\n};\n\nexports.median = function median(matrix) {\n var rows = matrix.length, cols = matrix[0].length;\n var medians = new Array(cols);\n\n for (var i = 0; i < cols; i++) {\n var data = new Array(rows);\n for (var j = 0; j < rows; j++) {\n data[j] = matrix[j][i];\n }\n data.sort(compareNumbers);\n var N = data.length;\n if (N % 2 === 0) {\n medians[i] = (data[N / 2] + data[(N / 2) - 1]) * 0.5;\n } else {\n medians[i] = data[Math.floor(N / 2)];\n }\n }\n return medians;\n};\n\nexports.mode = function mode(matrix) {\n var rows = matrix.length,\n cols = matrix[0].length,\n modes = new Array(cols),\n i, j;\n for (i = 0; i < cols; i++) {\n var itemCount = new Array(rows);\n for (var k = 0; k < rows; k++) {\n itemCount[k] = 0;\n }\n var itemArray = new Array(rows);\n var count = 0;\n\n for (j = 0; j < rows; j++) {\n var index = itemArray.indexOf(matrix[j][i]);\n if (index >= 0) {\n itemCount[index]++;\n } else {\n itemArray[count] = matrix[j][i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (j = 0; j < count; j++) {\n if (itemCount[j] > maxValue) {\n maxValue = itemCount[j];\n maxIndex = j;\n }\n }\n\n modes[i] = itemArray[maxIndex];\n }\n return modes;\n};\n\nexports.skewness = function skewness(matrix, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var means = exports.mean(matrix);\n var n = matrix.length, l = means.length;\n var skew = new Array(l);\n\n for (var j = 0; j < l; j++) {\n var s2 = 0, s3 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n\n var m2 = s2 / n;\n var m3 = s3 / n;\n var g = m3 / Math.pow(m2, 3 / 2);\n\n if (unbiased) {\n var a = Math.sqrt(n * (n - 1));\n var b = n - 2;\n skew[j] = (a / b) * g;\n } else {\n skew[j] = g;\n }\n }\n return skew;\n};\n\nexports.kurtosis = function kurtosis(matrix, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var means = exports.mean(matrix);\n var n = matrix.length, m = matrix[0].length;\n var kurt = new Array(m);\n\n for (var j = 0; j < m; j++) {\n var s2 = 0, s4 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n kurt[j] = a * b - 3 * c;\n } else {\n kurt[j] = m4 / (m2 * m2) - 3;\n }\n }\n return kurt;\n};\n\nexports.standardError = function standardError(matrix) {\n var samples = matrix.length;\n var standardDeviations = exports.standardDeviation(matrix);\n var l = standardDeviations.length;\n var standardErrors = new Array(l);\n var sqrtN = Math.sqrt(samples);\n\n for (var i = 0; i < l; i++) {\n standardErrors[i] = standardDeviations[i] / sqrtN;\n }\n return standardErrors;\n};\n\nexports.covariance = function covariance(matrix, dimension) {\n return exports.scatter(matrix, undefined, dimension);\n};\n\nexports.scatter = function scatter(matrix, divisor, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n if (typeof (divisor) === 'undefined') {\n if (dimension === 0) {\n divisor = matrix.length - 1;\n } else if (dimension === 1) {\n divisor = matrix[0].length - 1;\n }\n }\n var means = exports.mean(matrix, dimension);\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, s, k;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n};\n\nexports.correlation = function correlation(matrix) {\n var means = exports.mean(matrix),\n standardDeviations = exports.standardDeviation(matrix, true, means),\n scores = exports.zScores(matrix, means, standardDeviations),\n rows = matrix.length,\n cols = matrix[0].length,\n i, j;\n\n var cor = new Array(cols);\n for (i = 0; i < cols; i++) {\n cor[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n var c = 0;\n for (var k = 0, l = scores.length; k < l; k++) {\n c += scores[k][j] * scores[k][i];\n }\n c /= rows - 1;\n cor[i][j] = c;\n cor[j][i] = c;\n }\n }\n return cor;\n};\n\nexports.zScores = function zScores(matrix, means, standardDeviations) {\n means = means || exports.mean(matrix);\n if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix, true, means);\n return exports.standardize(exports.center(matrix, means, false), standardDeviations, true);\n};\n\nexports.center = function center(matrix, means, inPlace) {\n means = means || exports.mean(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var row = result[i];\n for (j = 0, jj = row.length; j < jj; j++) {\n row[j] = matrix[i][j] - means[j];\n }\n }\n return result;\n};\n\nexports.standardize = function standardize(matrix, standardDeviations, inPlace) {\n if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var resultRow = result[i];\n var sourceRow = matrix[i];\n for (j = 0, jj = resultRow.length; j < jj; j++) {\n if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) {\n resultRow[j] = sourceRow[j] / standardDeviations[j];\n }\n }\n }\n return result;\n};\n\nexports.weightedVariance = function weightedVariance(matrix, weights) {\n var means = exports.mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum = 0;\n var a = 0, b = 0;\n\n for (var i = 0; i < rows; i++) {\n var z = matrix[i][j] - means[j];\n var w = weights[i];\n\n sum += w * (z * z);\n b += w;\n a += w * w;\n }\n\n vari[j] = sum * (b / (b * b - a));\n }\n\n return vari;\n};\n\nexports.weightedMean = function weightedMean(matrix, weights, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length,\n means, i, ii, j, w, row;\n\n if (dimension === 0) {\n means = new Array(cols);\n for (i = 0; i < cols; i++) {\n means[i] = 0;\n }\n for (i = 0; i < rows; i++) {\n row = matrix[i];\n w = weights[i];\n for (j = 0; j < cols; j++) {\n means[j] += row[j] * w;\n }\n }\n } else if (dimension === 1) {\n means = new Array(rows);\n for (i = 0; i < rows; i++) {\n means[i] = 0;\n }\n for (j = 0; j < rows; j++) {\n row = matrix[j];\n w = weights[j];\n for (i = 0; i < cols; i++) {\n means[j] += row[i] * w;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n var weightSum = arrayStat.sum(weights);\n if (weightSum !== 0) {\n for (i = 0, ii = means.length; i < ii; i++) {\n means[i] /= weightSum;\n }\n }\n return means;\n};\n\nexports.weightedCovariance = function weightedCovariance(matrix, weights, means, dimension) {\n dimension = dimension || 0;\n means = means || exports.weightedMean(matrix, weights, dimension);\n var s1 = 0, s2 = 0;\n for (var i = 0, ii = weights.length; i < ii; i++) {\n s1 += weights[i];\n s2 += weights[i] * weights[i];\n }\n var factor = s1 / (s1 * s1 - s2);\n return exports.weightedScatter(matrix, weights, means, factor, dimension);\n};\n\nexports.weightedScatter = function weightedScatter(matrix, weights, means, factor, dimension) {\n dimension = dimension || 0;\n means = means || exports.weightedMean(matrix, weights, dimension);\n if (typeof (factor) === 'undefined') {\n factor = 1;\n }\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, k, s;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n};\n","import isArray from 'is-any-array';\n\n/**\n * Computes the mean of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction mean(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var sum = 0;\n\n for (var i = 0; i < input.length; i++) {\n sum += input[i];\n }\n\n return sum / input.length;\n}\n\nexport default mean;\n","module.exports = function(haystack, needle, comparator, low, high) {\n var mid, cmp;\n\n if(low === undefined)\n low = 0;\n\n else {\n low = low|0;\n if(low < 0 || low >= haystack.length)\n throw new RangeError(\"invalid lower bound\");\n }\n\n if(high === undefined)\n high = haystack.length - 1;\n\n else {\n high = high|0;\n if(high < low || high >= haystack.length)\n throw new RangeError(\"invalid upper bound\");\n }\n\n while(low <= high) {\n /* Note that \"(low + high) >>> 1\" may overflow, and results in a typecast\n * to double (which gives the wrong results). */\n mid = low + (high - low >> 1);\n cmp = +comparator(haystack[mid], needle, mid, haystack);\n\n /* Too low. */\n if(cmp < 0.0)\n low = mid + 1;\n\n /* Too high. */\n else if(cmp > 0.0)\n high = mid - 1;\n\n /* Key found. */\n else\n return mid;\n }\n\n /* Key not found. */\n return ~low;\n}\n","'use strict';\nvar numberIsNan = require('number-is-nan');\n\nfunction assertNum(x) {\n\tif (typeof x !== 'number' || numberIsNan(x)) {\n\t\tthrow new TypeError('Expected a number');\n\t}\n}\n\nexports.asc = function (a, b) {\n\tassertNum(a);\n\tassertNum(b);\n\treturn a - b;\n};\n\nexports.desc = function (a, b) {\n\tassertNum(a);\n\tassertNum(b);\n\treturn b - a;\n};\n","import Matrix from 'ml-matrix';\nimport meanArray from 'ml-array-mean';\n\n/**\n * @private\n * return an array of probabilities of each class\n * @param {Array} array - contains the classes\n * @param {number} numberOfClasses\n * @return {Matrix} - rowVector of probabilities.\n */\nexport function toDiscreteDistribution(array, numberOfClasses) {\n var counts = new Array(numberOfClasses).fill(0);\n for (var i = 0; i < array.length; ++i) {\n counts[array[i]] += 1 / array.length;\n }\n\n return Matrix.rowVector(counts);\n}\n\n/**\n * @private\n * Retrieves the impurity of array of predictions\n * @param {Array} array - predictions.\n * @return {number} Gini impurity\n */\nexport function giniImpurity(array) {\n if (array.length === 0) {\n return 0;\n }\n\n var probabilities = toDiscreteDistribution(array, getNumberOfClasses(array))[0];\n\n var sum = 0.0;\n for (var i = 0; i < probabilities.length; ++i) {\n sum += probabilities[i] * probabilities[i];\n }\n\n return 1 - sum;\n}\n\n/**\n * @private\n * Return the number of classes given the array of predictions.\n * @param {Array} array - predictions.\n * @return {number} Number of classes.\n */\nexport function getNumberOfClasses(array) {\n return array.filter(function (val, i, arr) {\n return arr.indexOf(val) === i;\n }).length;\n}\n\n/**\n * @private\n * Calculates the Gini Gain of an array of predictions and those predictions splitted by a feature.\n * @para {Array} array - Predictions\n * @param {object} splitted - Object with elements \"greater\" and \"lesser\" that contains an array of predictions splitted.\n * @return {number} - Gini Gain.\n */\n\nexport function giniGain(array, splitted) {\n var splitsImpurity = 0.0;\n var splits = ['greater', 'lesser'];\n\n for (var i = 0; i < splits.length; ++i) {\n var currentSplit = splitted[splits[i]];\n splitsImpurity += giniImpurity(currentSplit) * currentSplit.length / array.length;\n }\n\n return giniImpurity(array) - splitsImpurity;\n}\n\n/**\n * @private\n * Calculates the squared error of a predictions values.\n * @param {Array} array - predictions values\n * @return {number} squared error.\n */\nexport function squaredError(array) {\n var l = array.length;\n\n var m = meanArray(array);\n var squaredError = 0.0;\n\n for (var i = 0; i < l; ++i) {\n var currentElement = array[i];\n squaredError += (currentElement - m) * (currentElement - m);\n }\n\n return squaredError;\n}\n\n/**\n * @private\n * Calculates the sum of squared error of the two arrays that contains the splitted values.\n * @param {Array} array - this argument is no necessary but is used to fit with the main interface.\n * @param {object} splitted - Object with elements \"greater\" and \"lesser\" that contains an array of predictions splitted.\n * @return {number} - sum of squared errors.\n */\nexport function regressionError(array, splitted) {\n var error = 0.0;\n var splits = ['greater', 'lesser'];\n\n for (var i = 0; i < splits.length; ++i) {\n var currentSplit = splitted[splits[i]];\n error += squaredError(currentSplit);\n }\n return error;\n}\n\n/**\n * @private\n * Split the training set and values from a given column of the training set if is less than a value\n * @param {Matrix} X - Training set.\n * @param {Array} y - Training values.\n * @param {number} column - Column to split.\n * @param {number} value - value to split the Training set and values.\n * @return {object} - Object that contains the splitted values.\n */\nexport function matrixSplitter(X, y, column, value) {\n var lesserX = [];\n var greaterX = [];\n var lesserY = [];\n var greaterY = [];\n\n for (var i = 0; i < X.rows; ++i) {\n if (X[i][column] < value) {\n lesserX.push(X[i]);\n lesserY.push(y[i]);\n } else {\n greaterX.push(X[i]);\n greaterY.push(y[i]);\n }\n }\n\n return {\n greaterX: greaterX,\n greaterY: greaterY,\n lesserX: lesserX,\n lesserY: lesserY\n };\n}\n\n/**\n * @private\n * Calculates the mean between two values\n * @param {number} a\n * @param {number} b\n * @return {number}\n */\nexport function mean(a, b) {\n return (a + b) / 2;\n}\n\n/**\n * @private\n * Returns a list of tuples that contains the i-th element of each array.\n * @param {Array} a\n * @param {Array} b\n * @return {Array} list of tuples.\n */\nexport function zip(a, b) {\n if (a.length !== b.length) {\n throw new TypeError('Error on zip: the size of a: ' + a.length + ' is different from b: ' + b.length);\n }\n\n var ret = new Array(a.length);\n for (var i = 0; i < a.length; ++i) {\n ret[i] = [a[i], b[i]];\n }\n\n return ret;\n}\n","import Matrix from 'ml-matrix';\nimport * as Utils from './utils';\nimport mean from 'ml-array-mean';\n\nconst gainFunctions = {\n gini: Utils.giniGain,\n regression: Utils.regressionError\n};\n\nconst splitFunctions = {\n mean: Utils.mean\n};\n\nexport default class TreeNode {\n\n /**\n * @private\n * Constructor for a tree node given the options received on the main classes (DecisionTreeClassifier, DecisionTreeRegression)\n * @param {object|TreeNode} options for loading\n * @constructor\n */\n constructor(options) {\n // options parameters\n this.kind = options.kind;\n this.gainFunction = options.gainFunction;\n this.splitFunction = options.splitFunction;\n this.minNumSamples = options.minNumSamples;\n this.maxDepth = options.maxDepth;\n }\n\n /**\n * @private\n * Function that retrieve the best feature to make the split.\n * @param {Matrix} XTranspose - Training set transposed\n * @param {Array} y - labels or values (depending of the decision tree)\n * @return {object} - return tree values, the best gain, column and the split value.\n */\n bestSplit(XTranspose, y) {\n\n // Depending in the node tree class, we set the variables to check information gain (to classify)\n // or error (for regression)\n\n var bestGain = this.kind === 'classifier' ? -Infinity : Infinity;\n var check = this.kind === 'classifier' ? (a, b) => a > b : (a, b) => a < b;\n\n\n var maxColumn;\n var maxValue;\n\n for (var i = 0; i < XTranspose.rows; ++i) {\n var currentFeature = XTranspose[i];\n var splitValues = this.featureSplit(currentFeature, y);\n for (var j = 0; j < splitValues.length; ++j) {\n var currentSplitVal = splitValues[j];\n var splitted = this.split(currentFeature, y, currentSplitVal);\n\n var gain = gainFunctions[this.gainFunction](y, splitted);\n if (check(gain, bestGain)) {\n maxColumn = i;\n maxValue = currentSplitVal;\n bestGain = gain;\n }\n }\n }\n\n return {\n maxGain: bestGain,\n maxColumn: maxColumn,\n maxValue: maxValue\n };\n }\n\n /**\n * @private\n * Makes the split of the training labels or values from the training set feature given a split value.\n * @param {Array} x - Training set feature\n * @param {Array} y - Training set value or label\n * @param {number} splitValue\n * @return {object}\n */\n\n split(x, y, splitValue) {\n var lesser = [];\n var greater = [];\n\n for (var i = 0; i < x.length; ++i) {\n if (x[i] < splitValue) {\n lesser.push(y[i]);\n } else {\n greater.push(y[i]);\n }\n }\n\n return {\n greater: greater,\n lesser: lesser\n };\n }\n\n /**\n * @private\n * Calculates the possible points to split over the tree given a training set feature and corresponding labels or values.\n * @param {Array} x - Training set feature\n * @param {Array} y - Training set value or label\n * @return {Array} possible split values.\n */\n featureSplit(x, y) {\n var splitValues = [];\n var arr = Utils.zip(x, y);\n arr.sort(function (a, b) {\n return a[0] - b[0];\n });\n\n for (var i = 1; i < arr.length; ++i) {\n if (arr[i - 1][1] !== arr[i][1]) {\n splitValues.push(splitFunctions[this.splitFunction](arr[i - 1][0], arr[i][0]));\n }\n }\n\n return splitValues;\n }\n\n /**\n * @private\n * Calculate the predictions of a leaf tree node given the training labels or values\n * @param {Array} y\n */\n calculatePrediction(y) {\n if (this.kind === 'classifier') {\n this.distribution = Utils.toDiscreteDistribution(y, Utils.getNumberOfClasses(y));\n if (this.distribution.columns === 0) {\n throw new TypeError('Error on calculate the prediction');\n }\n } else {\n this.distribution = mean(y);\n }\n }\n\n /**\n * @private\n * Train a node given the training set and labels, because it trains recursively, it also receive\n * the current depth of the node, parent gain to avoid infinite recursion and boolean value to check if\n * the training set is transposed.\n * @param {Matrix} X - Training set (could be transposed or not given transposed).\n * @param {Array} y - Training labels or values.\n * @param {number} currentDepth - Current depth of the node.\n * @param {number} parentGain - parent node gain or error.\n */\n train(X, y, currentDepth, parentGain) {\n if (X.rows <= this.minNumSamples) {\n this.calculatePrediction(y);\n return;\n }\n if (parentGain === undefined) parentGain = 0.0;\n\n var XTranspose = X.transpose();\n var split = this.bestSplit(XTranspose, y);\n\n this.splitValue = split.maxValue;\n this.splitColumn = split.maxColumn;\n this.gain = split.maxGain;\n\n var splittedMatrix = Utils.matrixSplitter(X, y, this.splitColumn, this.splitValue);\n\n if (currentDepth < this.maxDepth &&\n (this.gain > 0.01 && this.gain !== parentGain) &&\n (splittedMatrix.lesserX.length > 0 && splittedMatrix.greaterX.length > 0)) {\n this.left = new TreeNode(this);\n this.right = new TreeNode(this);\n\n var lesserX = new Matrix(splittedMatrix.lesserX);\n var greaterX = new Matrix(splittedMatrix.greaterX);\n\n this.left.train(lesserX, splittedMatrix.lesserY, currentDepth + 1, this.gain);\n this.right.train(greaterX, splittedMatrix.greaterY, currentDepth + 1, this.gain);\n } else {\n this.calculatePrediction(y);\n }\n }\n\n /**\n * @private\n * Calculates the prediction of a given element.\n * @param {Array} row\n * @return {number|Array} prediction\n * * if a node is a classifier returns an array of probabilities of each class.\n * * if a node is for regression returns a number with the prediction.\n */\n classify(row) {\n if (this.right && this.left) {\n if (row[this.splitColumn] < this.splitValue) {\n return this.left.classify(row);\n } else {\n return this.right.classify(row);\n }\n }\n\n return this.distribution;\n }\n\n /**\n * @private\n * Set the parameter of the current node and their children.\n * @param {object} node - parameters of the current node and the children.\n */\n setNodeParameters(node) {\n if (node.distribution !== undefined) {\n this.distribution = node.distribution.constructor === Array ? new Matrix(node.distribution) :\n node.distribution;\n } else {\n this.distribution = undefined;\n this.splitValue = node.splitValue;\n this.splitColumn = node.splitColumn;\n this.gain = node.gain;\n\n this.left = new TreeNode(this);\n this.right = new TreeNode(this);\n\n if (node.left !== {}) {\n this.left.setNodeParameters(node.left);\n }\n if (node.right !== {}) {\n this.right.setNodeParameters(node.right);\n }\n }\n }\n}\n","import Matrix from 'ml-matrix';\nimport Tree from './TreeNode';\n\nconst defaultOptions = {\n gainFunction: 'gini',\n splitFunction: 'mean',\n minNumSamples: 3,\n maxDepth: Infinity\n};\n\nexport class DecisionTreeClassifier {\n\n /**\n * Create new Decision Tree Classifier with CART implementation with the given options\n * @param {object} options\n * @param {string} [options.gainFunction=\"gini\"] - gain function to get the best split, \"gini\" the only one supported.\n * @param {string} [options.splitFunction=\"mean\"] - given two integers from a split feature, get the value to split, \"mean\" the only one supported.\n * @param {number} [options.minNumSamples=3] - minimum number of samples to create a leaf node to decide a class.\n * @param {number} [options.maxDepth=Infinity] - Max depth of the tree.\n * @param {object} model - for load purposes.\n * @constructor\n */\n constructor(options, model) {\n if (options === true) {\n this.options = model.options;\n this.root = new Tree(model.options);\n this.root.setNodeParameters(model.root);\n } else {\n this.options = Object.assign({}, defaultOptions, options);\n this.options.kind = 'classifier';\n }\n }\n\n /**\n * Train the decision tree with the given training set and labels.\n * @param {Matrix|MatrixTransposeView|Array} trainingSet\n * @param {Array} trainingLabels\n */\n train(trainingSet, trainingLabels) {\n this.root = new Tree(this.options);\n trainingSet = Matrix.checkMatrix(trainingSet);\n this.root.train(trainingSet, trainingLabels, 0, null);\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Matrix|MatrixTransposeView|Array} toPredict\n * @return {Array} predictions\n */\n predict(toPredict) {\n toPredict = Matrix.checkMatrix(toPredict);\n var predictions = new Array(toPredict.rows);\n\n for (var i = 0; i < toPredict.rows; ++i) {\n predictions[i] = this.root.classify(toPredict.getRow(i)).maxRowIndex(0)[1];\n }\n\n return predictions;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n options: this.options,\n root: this.root,\n name: 'DTClassifier'\n };\n }\n\n /**\n * Load a Decision tree classifier with the given model.\n * @param {object} model\n * @return {DecisionTreeClassifier}\n */\n static load(model) {\n if (model.name !== 'DTClassifier') {\n throw new RangeError('Invalid model: ' + model.name);\n }\n\n return new DecisionTreeClassifier(true, model);\n }\n}\n","import Matrix from 'ml-matrix';\nimport Tree from './TreeNode';\n\nconst defaultOptions = {\n gainFunction: 'regression',\n splitFunction: 'mean',\n minNumSamples: 3,\n maxDepth: Infinity\n};\n\nexport class DecisionTreeRegression {\n\n /**\n * Create new Decision Tree Regression with CART implementation with the given options.\n * @param {object} options\n * @param {string} [options.gainFunction=\"regression\"] - gain function to get the best split, \"regression\" the only one supported.\n * @param {string} [options.splitFunction=\"mean\"] - given two integers from a split feature, get the value to split, \"mean\" the only one supported.\n * @param {number} [options.minNumSamples=3] - minimum number of samples to create a leaf node to decide a class.\n * @param {number} [options.maxDepth=Infinity] - Max depth of the tree.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.options = model.options;\n this.root = new Tree(model.options);\n this.root.setNodeParameters(model.root);\n } else {\n this.options = Object.assign({}, defaultOptions, options);\n this.options.kind = 'regression';\n }\n }\n\n /**\n * Train the decision tree with the given training set and values.\n * @param {Matrix|MatrixTransposeView|Array} trainingSet\n * @param {Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n this.root = new Tree(this.options);\n\n if (trainingSet[0].length === undefined) trainingSet = Matrix.columnVector(trainingSet);\n trainingSet = Matrix.checkMatrix(trainingSet);\n this.root.train(trainingSet, trainingValues, 0);\n }\n\n /**\n * Predicts the values given the matrix to predict.\n * @param {Matrix|MatrixTransposeView|Array} toPredict\n * @return {Array} predictions\n */\n predict(toPredict) {\n if (toPredict[0] !== undefined && toPredict[0].length === undefined) toPredict = Matrix.columnVector(toPredict);\n toPredict = Matrix.checkMatrix(toPredict);\n\n var predictions = new Array(toPredict.rows);\n for (var i = 0; i < toPredict.rows; ++i) {\n predictions[i] = this.root.classify(toPredict.getRow(i));\n }\n\n return predictions;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n options: this.options,\n root: this.root,\n name: 'DTRegression'\n };\n }\n\n /**\n * Load a Decision tree regression with the given model.\n * @param {object} model\n * @return {DecisionTreeRegression}\n */\n static load(model) {\n if (model.name !== 'DTRegression') {\n throw new RangeError('Invalid model:' + model.name);\n }\n\n return new DecisionTreeRegression(true, model);\n }\n}\n","export {DecisionTreeClassifier} from './DecisionTreeClassifier';\nexport {DecisionTreeRegression} from './DecisionTreeRegression';\n","import isArray from 'is-any-array';\n\n/**\n * Computes the maximum of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction max(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var max = input[0];\n\n for (var i = 1; i < input.length; i++) {\n if (input[i] > max) max = input[i];\n }\n\n return max;\n}\n\nexport default max;\n","'use strict';\n\nconst Matrix = require('ml-matrix').Matrix;\n\nconst GaussianKernel = require('ml-kernel-gaussian');\nconst PolynomialKernel = require('ml-kernel-polynomial');\nconst ANOVAKernel = require('./kernels/anova-kernel');\nconst CauchyKernel = require('./kernels/cauchy-kernel');\nconst ExponentialKernel = require('./kernels/exponential-kernel');\nconst HistogramKernel = require('./kernels/histogram-intersection-kernel');\nconst LaplacianKernel = require('./kernels/laplacian-kernel');\nconst MultiquadraticKernel = require('./kernels/multiquadratic-kernel');\nconst RationalKernel = require('./kernels/rational-quadratic-kernel');\nconst SigmoidKernel = require('ml-kernel-sigmoid');\n\nconst kernelType = {\n gaussian: GaussianKernel,\n rbf: GaussianKernel,\n polynomial: PolynomialKernel,\n poly: PolynomialKernel,\n anova: ANOVAKernel,\n cauchy: CauchyKernel,\n exponential: ExponentialKernel,\n histogram: HistogramKernel,\n min: HistogramKernel,\n laplacian: LaplacianKernel,\n multiquadratic: MultiquadraticKernel,\n rational: RationalKernel,\n sigmoid: SigmoidKernel,\n mlp: SigmoidKernel\n};\n\nclass Kernel {\n constructor(type, options) {\n this.kernelType = type;\n if (type === 'linear') return;\n\n if (typeof type === 'string') {\n type = type.toLowerCase();\n\n var KernelConstructor = kernelType[type];\n if (KernelConstructor) {\n this.kernelFunction = new KernelConstructor(options);\n } else {\n throw new Error('unsupported kernel type: ' + type);\n }\n } else if (typeof type === 'object' && typeof type.compute === 'function') {\n this.kernelFunction = type;\n } else {\n throw new TypeError('first argument must be a valid kernel type or instance');\n }\n }\n\n compute(inputs, landmarks) {\n if (landmarks === undefined) {\n landmarks = inputs;\n }\n\n if (this.kernelType === 'linear') {\n var matrix = new Matrix(inputs);\n return matrix.mmul(new Matrix(landmarks).transposeView());\n }\n\n const kernelMatrix = new Matrix(inputs.length, landmarks.length);\n var i, j;\n if (inputs === landmarks) { // fast path, matrix is symmetric\n for (i = 0; i < inputs.length; i++) {\n for (j = i; j < inputs.length; j++) {\n kernelMatrix[i][j] = kernelMatrix[j][i] = this.kernelFunction.compute(inputs[i], inputs[j]);\n }\n }\n } else {\n for (i = 0; i < inputs.length; i++) {\n for (j = 0; j < landmarks.length; j++) {\n kernelMatrix[i][j] = this.kernelFunction.compute(inputs[i], landmarks[j]);\n }\n }\n }\n return kernelMatrix;\n }\n}\n\nmodule.exports = Kernel;\n","const PROB_TOLERANCE = 0.00000001;\nfunction randomChoice(values, options = {}, random = Math.random) {\n const { size = 1, replace = false, probabilities } = options;\n let valuesArr;\n let cumSum;\n if (typeof values === 'number') {\n valuesArr = getArray(values);\n }\n else {\n valuesArr = values.slice();\n }\n if (probabilities) {\n if (!replace) {\n throw new Error('choice with probabilities and no replacement is not implemented');\n }\n // check input is sane\n if (probabilities.length !== valuesArr.length) {\n throw new Error('the length of probabilities option should be equal to the number of choices');\n }\n cumSum = [probabilities[0]];\n for (let i = 1; i < probabilities.length; i++) {\n cumSum[i] = cumSum[i - 1] + probabilities[i];\n }\n if (Math.abs(1 - cumSum[cumSum.length - 1]) > PROB_TOLERANCE) {\n throw new Error(`probabilities should sum to 1, but instead sums to ${cumSum[cumSum.length - 1]}`);\n }\n }\n if (replace === false && size > valuesArr.length) {\n throw new Error('size option is too large');\n }\n const result = [];\n for (let i = 0; i < size; i++) {\n const index = randomIndex(valuesArr.length, random, cumSum);\n result.push(valuesArr[index]);\n if (!replace) {\n valuesArr.splice(index, 1);\n }\n }\n return result;\n}\nfunction getArray(n) {\n const arr = [];\n for (let i = 0; i < n; i++) {\n arr.push(i);\n }\n return arr;\n}\nfunction randomIndex(n, random, cumSum) {\n const rand = random();\n if (!cumSum) {\n return Math.floor(rand * n);\n }\n else {\n let idx = 0;\n while (rand > cumSum[idx]) {\n idx++;\n }\n return idx;\n }\n}\nexport default randomChoice;\n","// tslint:disable-next-line\nimport XSAdd from 'ml-xsadd';\nimport choice from './choice';\n/**\n * @classdesc Random class\n */\nexport default class Random {\n /**\n * @param [seedOrRandom=Math.random] - Control the random number generator used by the Random class instance. Pass a random number generator function with a uniform distribution over the half-open interval [0, 1[. If seed will pass it to ml-xsadd to create a seeded random number generator. If undefined will use Math.random.\n */\n constructor(seedOrRandom = Math.random) {\n if (typeof seedOrRandom === 'number') {\n const xsadd = new XSAdd(seedOrRandom);\n this.randomGenerator = xsadd.random;\n }\n else {\n this.randomGenerator = seedOrRandom;\n }\n }\n choice(values, options) {\n if (typeof values === 'number') {\n return choice(values, options, this.randomGenerator);\n }\n return choice(values, options, this.randomGenerator);\n }\n /**\n * Draw a random number from a uniform distribution on [0,1)\n * @return The random number\n */\n random() {\n return this.randomGenerator();\n }\n /**\n * Draw a random integer from a uniform distribution on [low, high). If only low is specified, the number is drawn on [0, low)\n * @param low - The lower bound of the uniform distribution interval.\n * @param high - The higher bound of the uniform distribution interval.\n */\n randInt(low, high) {\n if (high === undefined) {\n high = low;\n low = 0;\n }\n return low + Math.floor(this.randomGenerator() * (high - low));\n }\n /**\n * Draw several random number from a uniform distribution on [0, 1)\n * @param size - The number of number to draw\n * @return - The list of drawn numbers.\n */\n randomSample(size) {\n const result = [];\n for (let i = 0; i < size; i++) {\n result.push(this.random());\n }\n return result;\n }\n}\n","/*jshint eqnull:true*/\n(function (root) {\n \"use strict\";\n\n var GLOBAL_KEY = \"Random\";\n\n var imul = (typeof Math.imul !== \"function\" || Math.imul(0xffffffff, 5) !== -5 ?\n function (a, b) {\n var ah = (a >>> 16) & 0xffff;\n var al = a & 0xffff;\n var bh = (b >>> 16) & 0xffff;\n var bl = b & 0xffff;\n // the shift by 0 fixes the sign on the high part\n // the final |0 converts the unsigned value into a signed value\n return (al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0;\n } :\n Math.imul);\n\n var stringRepeat = (typeof String.prototype.repeat === \"function\" && \"x\".repeat(3) === \"xxx\" ?\n function (x, y) {\n return x.repeat(y);\n } : function (pattern, count) {\n var result = \"\";\n while (count > 0) {\n if (count & 1) {\n result += pattern;\n }\n count >>= 1;\n pattern += pattern;\n }\n return result;\n });\n\n function Random(engine) {\n if (!(this instanceof Random)) {\n return new Random(engine);\n }\n\n if (engine == null) {\n engine = Random.engines.nativeMath;\n } else if (typeof engine !== \"function\") {\n throw new TypeError(\"Expected engine to be a function, got \" + typeof engine);\n }\n this.engine = engine;\n }\n var proto = Random.prototype;\n\n Random.engines = {\n nativeMath: function () {\n return (Math.random() * 0x100000000) | 0;\n },\n mt19937: (function (Int32Array) {\n // http://en.wikipedia.org/wiki/Mersenne_twister\n function refreshData(data) {\n var k = 0;\n var tmp = 0;\n for (;\n (k | 0) < 227; k = (k + 1) | 0) {\n tmp = (data[k] & 0x80000000) | (data[(k + 1) | 0] & 0x7fffffff);\n data[k] = data[(k + 397) | 0] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);\n }\n\n for (;\n (k | 0) < 623; k = (k + 1) | 0) {\n tmp = (data[k] & 0x80000000) | (data[(k + 1) | 0] & 0x7fffffff);\n data[k] = data[(k - 227) | 0] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);\n }\n\n tmp = (data[623] & 0x80000000) | (data[0] & 0x7fffffff);\n data[623] = data[396] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);\n }\n\n function temper(value) {\n value ^= value >>> 11;\n value ^= (value << 7) & 0x9d2c5680;\n value ^= (value << 15) & 0xefc60000;\n return value ^ (value >>> 18);\n }\n\n function seedWithArray(data, source) {\n var i = 1;\n var j = 0;\n var sourceLength = source.length;\n var k = Math.max(sourceLength, 624) | 0;\n var previous = data[0] | 0;\n for (;\n (k | 0) > 0; --k) {\n data[i] = previous = ((data[i] ^ imul((previous ^ (previous >>> 30)), 0x0019660d)) + (source[j] | 0) + (j | 0)) | 0;\n i = (i + 1) | 0;\n ++j;\n if ((i | 0) > 623) {\n data[0] = data[623];\n i = 1;\n }\n if (j >= sourceLength) {\n j = 0;\n }\n }\n for (k = 623;\n (k | 0) > 0; --k) {\n data[i] = previous = ((data[i] ^ imul((previous ^ (previous >>> 30)), 0x5d588b65)) - i) | 0;\n i = (i + 1) | 0;\n if ((i | 0) > 623) {\n data[0] = data[623];\n i = 1;\n }\n }\n data[0] = 0x80000000;\n }\n\n function mt19937() {\n var data = new Int32Array(624);\n var index = 0;\n var uses = 0;\n\n function next() {\n if ((index | 0) >= 624) {\n refreshData(data);\n index = 0;\n }\n\n var value = data[index];\n index = (index + 1) | 0;\n uses += 1;\n return temper(value) | 0;\n }\n next.getUseCount = function() {\n return uses;\n };\n next.discard = function (count) {\n uses += count;\n if ((index | 0) >= 624) {\n refreshData(data);\n index = 0;\n }\n while ((count - index) > 624) {\n count -= 624 - index;\n refreshData(data);\n index = 0;\n }\n index = (index + count) | 0;\n return next;\n };\n next.seed = function (initial) {\n var previous = 0;\n data[0] = previous = initial | 0;\n\n for (var i = 1; i < 624; i = (i + 1) | 0) {\n data[i] = previous = (imul((previous ^ (previous >>> 30)), 0x6c078965) + i) | 0;\n }\n index = 624;\n uses = 0;\n return next;\n };\n next.seedWithArray = function (source) {\n next.seed(0x012bd6aa);\n seedWithArray(data, source);\n return next;\n };\n next.autoSeed = function () {\n return next.seedWithArray(Random.generateEntropyArray());\n };\n return next;\n }\n\n return mt19937;\n }(typeof Int32Array === \"function\" ? Int32Array : Array)),\n browserCrypto: (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\" && typeof Int32Array === \"function\") ? (function () {\n var data = null;\n var index = 128;\n\n return function () {\n if (index >= 128) {\n if (data === null) {\n data = new Int32Array(128);\n }\n crypto.getRandomValues(data);\n index = 0;\n }\n\n return data[index++] | 0;\n };\n }()) : null\n };\n\n Random.generateEntropyArray = function () {\n var array = [];\n var engine = Random.engines.nativeMath;\n for (var i = 0; i < 16; ++i) {\n array[i] = engine() | 0;\n }\n array.push(new Date().getTime() | 0);\n return array;\n };\n\n function returnValue(value) {\n return function () {\n return value;\n };\n }\n\n // [-0x80000000, 0x7fffffff]\n Random.int32 = function (engine) {\n return engine() | 0;\n };\n proto.int32 = function () {\n return Random.int32(this.engine);\n };\n\n // [0, 0xffffffff]\n Random.uint32 = function (engine) {\n return engine() >>> 0;\n };\n proto.uint32 = function () {\n return Random.uint32(this.engine);\n };\n\n // [0, 0x1fffffffffffff]\n Random.uint53 = function (engine) {\n var high = engine() & 0x1fffff;\n var low = engine() >>> 0;\n return (high * 0x100000000) + low;\n };\n proto.uint53 = function () {\n return Random.uint53(this.engine);\n };\n\n // [0, 0x20000000000000]\n Random.uint53Full = function (engine) {\n while (true) {\n var high = engine() | 0;\n if (high & 0x200000) {\n if ((high & 0x3fffff) === 0x200000 && (engine() | 0) === 0) {\n return 0x20000000000000;\n }\n } else {\n var low = engine() >>> 0;\n return ((high & 0x1fffff) * 0x100000000) + low;\n }\n }\n };\n proto.uint53Full = function () {\n return Random.uint53Full(this.engine);\n };\n\n // [-0x20000000000000, 0x1fffffffffffff]\n Random.int53 = function (engine) {\n var high = engine() | 0;\n var low = engine() >>> 0;\n return ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);\n };\n proto.int53 = function () {\n return Random.int53(this.engine);\n };\n\n // [-0x20000000000000, 0x20000000000000]\n Random.int53Full = function (engine) {\n while (true) {\n var high = engine() | 0;\n if (high & 0x400000) {\n if ((high & 0x7fffff) === 0x400000 && (engine() | 0) === 0) {\n return 0x20000000000000;\n }\n } else {\n var low = engine() >>> 0;\n return ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);\n }\n }\n };\n proto.int53Full = function () {\n return Random.int53Full(this.engine);\n };\n\n function add(generate, addend) {\n if (addend === 0) {\n return generate;\n } else {\n return function (engine) {\n return generate(engine) + addend;\n };\n }\n }\n\n Random.integer = (function () {\n function isPowerOfTwoMinusOne(value) {\n return ((value + 1) & value) === 0;\n }\n\n function bitmask(masking) {\n return function (engine) {\n return engine() & masking;\n };\n }\n\n function downscaleToLoopCheckedRange(range) {\n var extendedRange = range + 1;\n var maximum = extendedRange * Math.floor(0x100000000 / extendedRange);\n return function (engine) {\n var value = 0;\n do {\n value = engine() >>> 0;\n } while (value >= maximum);\n return value % extendedRange;\n };\n }\n\n function downscaleToRange(range) {\n if (isPowerOfTwoMinusOne(range)) {\n return bitmask(range);\n } else {\n return downscaleToLoopCheckedRange(range);\n }\n }\n\n function isEvenlyDivisibleByMaxInt32(value) {\n return (value | 0) === 0;\n }\n\n function upscaleWithHighMasking(masking) {\n return function (engine) {\n var high = engine() & masking;\n var low = engine() >>> 0;\n return (high * 0x100000000) + low;\n };\n }\n\n function upscaleToLoopCheckedRange(extendedRange) {\n var maximum = extendedRange * Math.floor(0x20000000000000 / extendedRange);\n return function (engine) {\n var ret = 0;\n do {\n var high = engine() & 0x1fffff;\n var low = engine() >>> 0;\n ret = (high * 0x100000000) + low;\n } while (ret >= maximum);\n return ret % extendedRange;\n };\n }\n\n function upscaleWithinU53(range) {\n var extendedRange = range + 1;\n if (isEvenlyDivisibleByMaxInt32(extendedRange)) {\n var highRange = ((extendedRange / 0x100000000) | 0) - 1;\n if (isPowerOfTwoMinusOne(highRange)) {\n return upscaleWithHighMasking(highRange);\n }\n }\n return upscaleToLoopCheckedRange(extendedRange);\n }\n\n function upscaleWithinI53AndLoopCheck(min, max) {\n return function (engine) {\n var ret = 0;\n do {\n var high = engine() | 0;\n var low = engine() >>> 0;\n ret = ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);\n } while (ret < min || ret > max);\n return ret;\n };\n }\n\n return function (min, max) {\n min = Math.floor(min);\n max = Math.floor(max);\n if (min < -0x20000000000000 || !isFinite(min)) {\n throw new RangeError(\"Expected min to be at least \" + (-0x20000000000000));\n } else if (max > 0x20000000000000 || !isFinite(max)) {\n throw new RangeError(\"Expected max to be at most \" + 0x20000000000000);\n }\n\n var range = max - min;\n if (range <= 0 || !isFinite(range)) {\n return returnValue(min);\n } else if (range === 0xffffffff) {\n if (min === 0) {\n return Random.uint32;\n } else {\n return add(Random.int32, min + 0x80000000);\n }\n } else if (range < 0xffffffff) {\n return add(downscaleToRange(range), min);\n } else if (range === 0x1fffffffffffff) {\n return add(Random.uint53, min);\n } else if (range < 0x1fffffffffffff) {\n return add(upscaleWithinU53(range), min);\n } else if (max - 1 - min === 0x1fffffffffffff) {\n return add(Random.uint53Full, min);\n } else if (min === -0x20000000000000 && max === 0x20000000000000) {\n return Random.int53Full;\n } else if (min === -0x20000000000000 && max === 0x1fffffffffffff) {\n return Random.int53;\n } else if (min === -0x1fffffffffffff && max === 0x20000000000000) {\n return add(Random.int53, 1);\n } else if (max === 0x20000000000000) {\n return add(upscaleWithinI53AndLoopCheck(min - 1, max - 1), 1);\n } else {\n return upscaleWithinI53AndLoopCheck(min, max);\n }\n };\n }());\n proto.integer = function (min, max) {\n return Random.integer(min, max)(this.engine);\n };\n\n // [0, 1] (floating point)\n Random.realZeroToOneInclusive = function (engine) {\n return Random.uint53Full(engine) / 0x20000000000000;\n };\n proto.realZeroToOneInclusive = function () {\n return Random.realZeroToOneInclusive(this.engine);\n };\n\n // [0, 1) (floating point)\n Random.realZeroToOneExclusive = function (engine) {\n return Random.uint53(engine) / 0x20000000000000;\n };\n proto.realZeroToOneExclusive = function () {\n return Random.realZeroToOneExclusive(this.engine);\n };\n\n Random.real = (function () {\n function multiply(generate, multiplier) {\n if (multiplier === 1) {\n return generate;\n } else if (multiplier === 0) {\n return function () {\n return 0;\n };\n } else {\n return function (engine) {\n return generate(engine) * multiplier;\n };\n }\n }\n\n return function (left, right, inclusive) {\n if (!isFinite(left)) {\n throw new RangeError(\"Expected left to be a finite number\");\n } else if (!isFinite(right)) {\n throw new RangeError(\"Expected right to be a finite number\");\n }\n return add(\n multiply(\n inclusive ? Random.realZeroToOneInclusive : Random.realZeroToOneExclusive,\n right - left),\n left);\n };\n }());\n proto.real = function (min, max, inclusive) {\n return Random.real(min, max, inclusive)(this.engine);\n };\n\n Random.bool = (function () {\n function isLeastBitTrue(engine) {\n return (engine() & 1) === 1;\n }\n\n function lessThan(generate, value) {\n return function (engine) {\n return generate(engine) < value;\n };\n }\n\n function probability(percentage) {\n if (percentage <= 0) {\n return returnValue(false);\n } else if (percentage >= 1) {\n return returnValue(true);\n } else {\n var scaled = percentage * 0x100000000;\n if (scaled % 1 === 0) {\n return lessThan(Random.int32, (scaled - 0x80000000) | 0);\n } else {\n return lessThan(Random.uint53, Math.round(percentage * 0x20000000000000));\n }\n }\n }\n\n return function (numerator, denominator) {\n if (denominator == null) {\n if (numerator == null) {\n return isLeastBitTrue;\n }\n return probability(numerator);\n } else {\n if (numerator <= 0) {\n return returnValue(false);\n } else if (numerator >= denominator) {\n return returnValue(true);\n }\n return lessThan(Random.integer(0, denominator - 1), numerator);\n }\n };\n }());\n proto.bool = function (numerator, denominator) {\n return Random.bool(numerator, denominator)(this.engine);\n };\n\n function toInteger(value) {\n var number = +value;\n if (number < 0) {\n return Math.ceil(number);\n } else {\n return Math.floor(number);\n }\n }\n\n function convertSliceArgument(value, length) {\n if (value < 0) {\n return Math.max(value + length, 0);\n } else {\n return Math.min(value, length);\n }\n }\n Random.pick = function (engine, array, begin, end) {\n var length = array.length;\n var start = begin == null ? 0 : convertSliceArgument(toInteger(begin), length);\n var finish = end === void 0 ? length : convertSliceArgument(toInteger(end), length);\n if (start >= finish) {\n return void 0;\n }\n var distribution = Random.integer(start, finish - 1);\n return array[distribution(engine)];\n };\n proto.pick = function (array, begin, end) {\n return Random.pick(this.engine, array, begin, end);\n };\n\n function returnUndefined() {\n return void 0;\n }\n var slice = Array.prototype.slice;\n Random.picker = function (array, begin, end) {\n var clone = slice.call(array, begin, end);\n if (!clone.length) {\n return returnUndefined;\n }\n var distribution = Random.integer(0, clone.length - 1);\n return function (engine) {\n return clone[distribution(engine)];\n };\n };\n\n Random.shuffle = function (engine, array, downTo) {\n var length = array.length;\n if (length) {\n if (downTo == null) {\n downTo = 0;\n }\n for (var i = (length - 1) >>> 0; i > downTo; --i) {\n var distribution = Random.integer(0, i);\n var j = distribution(engine);\n if (i !== j) {\n var tmp = array[i];\n array[i] = array[j];\n array[j] = tmp;\n }\n }\n }\n return array;\n };\n proto.shuffle = function (array) {\n return Random.shuffle(this.engine, array);\n };\n\n Random.sample = function (engine, population, sampleSize) {\n if (sampleSize < 0 || sampleSize > population.length || !isFinite(sampleSize)) {\n throw new RangeError(\"Expected sampleSize to be within 0 and the length of the population\");\n }\n\n if (sampleSize === 0) {\n return [];\n }\n\n var clone = slice.call(population);\n var length = clone.length;\n if (length === sampleSize) {\n return Random.shuffle(engine, clone, 0);\n }\n var tailLength = length - sampleSize;\n return Random.shuffle(engine, clone, tailLength - 1).slice(tailLength);\n };\n proto.sample = function (population, sampleSize) {\n return Random.sample(this.engine, population, sampleSize);\n };\n\n Random.die = function (sideCount) {\n return Random.integer(1, sideCount);\n };\n proto.die = function (sideCount) {\n return Random.die(sideCount)(this.engine);\n };\n\n Random.dice = function (sideCount, dieCount) {\n var distribution = Random.die(sideCount);\n return function (engine) {\n var result = [];\n result.length = dieCount;\n for (var i = 0; i < dieCount; ++i) {\n result[i] = distribution(engine);\n }\n return result;\n };\n };\n proto.dice = function (sideCount, dieCount) {\n return Random.dice(sideCount, dieCount)(this.engine);\n };\n\n // http://en.wikipedia.org/wiki/Universally_unique_identifier\n Random.uuid4 = (function () {\n function zeroPad(string, zeroCount) {\n return stringRepeat(\"0\", zeroCount - string.length) + string;\n }\n\n return function (engine) {\n var a = engine() >>> 0;\n var b = engine() | 0;\n var c = engine() | 0;\n var d = engine() >>> 0;\n\n return (\n zeroPad(a.toString(16), 8) +\n \"-\" +\n zeroPad((b & 0xffff).toString(16), 4) +\n \"-\" +\n zeroPad((((b >> 4) & 0x0fff) | 0x4000).toString(16), 4) +\n \"-\" +\n zeroPad(((c & 0x3fff) | 0x8000).toString(16), 4) +\n \"-\" +\n zeroPad(((c >> 4) & 0xffff).toString(16), 4) +\n zeroPad(d.toString(16), 8));\n };\n }());\n proto.uuid4 = function () {\n return Random.uuid4(this.engine);\n };\n\n Random.string = (function () {\n // has 2**x chars, for faster uniform distribution\n var DEFAULT_STRING_POOL = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-\";\n\n return function (pool) {\n if (pool == null) {\n pool = DEFAULT_STRING_POOL;\n }\n\n var length = pool.length;\n if (!length) {\n throw new Error(\"Expected pool not to be an empty string\");\n }\n\n var distribution = Random.integer(0, length - 1);\n return function (engine, length) {\n var result = \"\";\n for (var i = 0; i < length; ++i) {\n var j = distribution(engine);\n result += pool.charAt(j);\n }\n return result;\n };\n };\n }());\n proto.string = function (length, pool) {\n return Random.string(pool)(this.engine, length);\n };\n\n Random.hex = (function () {\n var LOWER_HEX_POOL = \"0123456789abcdef\";\n var lowerHex = Random.string(LOWER_HEX_POOL);\n var upperHex = Random.string(LOWER_HEX_POOL.toUpperCase());\n\n return function (upper) {\n if (upper) {\n return upperHex;\n } else {\n return lowerHex;\n }\n };\n }());\n proto.hex = function (length, upper) {\n return Random.hex(upper)(this.engine, length);\n };\n\n Random.date = function (start, end) {\n if (!(start instanceof Date)) {\n throw new TypeError(\"Expected start to be a Date, got \" + typeof start);\n } else if (!(end instanceof Date)) {\n throw new TypeError(\"Expected end to be a Date, got \" + typeof end);\n }\n var distribution = Random.integer(start.getTime(), end.getTime());\n return function (engine) {\n return new Date(distribution(engine));\n };\n };\n proto.date = function (start, end) {\n return Random.date(start, end)(this.engine);\n };\n\n if (typeof define === \"function\" && define.amd) {\n define(function () {\n return Random;\n });\n } else if (typeof module !== \"undefined\" && typeof require === \"function\") {\n module.exports = Random;\n } else {\n (function () {\n var oldGlobal = root[GLOBAL_KEY];\n Random.noConflict = function () {\n root[GLOBAL_KEY] = oldGlobal;\n return this;\n };\n }());\n root[GLOBAL_KEY] = Random;\n }\n}(this));","import max from 'ml-array-max';\nimport min from 'ml-array-min';\nimport isArray from 'is-any-array';\n\nfunction rescale(input) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n } else if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var output;\n\n if (options.output !== undefined) {\n if (!isArray(options.output)) {\n throw new TypeError('output option must be an array if specified');\n }\n\n output = options.output;\n } else {\n output = new Array(input.length);\n }\n\n var currentMin = min(input);\n var currentMax = max(input);\n\n if (currentMin === currentMax) {\n throw new RangeError('minimum and maximum input values are equal. Cannot rescale a constant array');\n }\n\n var _options$min = options.min,\n minValue = _options$min === void 0 ? options.autoMinMax ? currentMin : 0 : _options$min,\n _options$max = options.max,\n maxValue = _options$max === void 0 ? options.autoMinMax ? currentMax : 1 : _options$max;\n\n if (minValue >= maxValue) {\n throw new RangeError('min option must be smaller than max option');\n }\n\n var factor = (maxValue - minValue) / (currentMax - currentMin);\n\n for (var i = 0; i < input.length; i++) {\n output[i] = (input[i] - currentMin) * factor + minValue;\n }\n\n return output;\n}\n\nexport default rescale;\n","'use strict';\n\nconst newArray = require('new-array');\n\nconst primeFinder = require('./primeFinder');\nconst nextPrime = primeFinder.nextPrime;\nconst largestPrime = primeFinder.largestPrime;\n\nconst FREE = 0;\nconst FULL = 1;\nconst REMOVED = 2;\n\nconst defaultInitialCapacity = 150;\nconst defaultMinLoadFactor = 1 / 6;\nconst defaultMaxLoadFactor = 2 / 3;\n\nclass HashTable {\n constructor(options = {}) {\n if (options instanceof HashTable) {\n this.table = options.table.slice();\n this.values = options.values.slice();\n this.state = options.state.slice();\n this.minLoadFactor = options.minLoadFactor;\n this.maxLoadFactor = options.maxLoadFactor;\n this.distinct = options.distinct;\n this.freeEntries = options.freeEntries;\n this.lowWaterMark = options.lowWaterMark;\n this.highWaterMark = options.maxLoadFactor;\n return;\n }\n\n const initialCapacity = options.initialCapacity === undefined ? defaultInitialCapacity : options.initialCapacity;\n if (initialCapacity < 0) {\n throw new RangeError(`initial capacity must not be less than zero: ${initialCapacity}`);\n }\n\n const minLoadFactor = options.minLoadFactor === undefined ? defaultMinLoadFactor : options.minLoadFactor;\n const maxLoadFactor = options.maxLoadFactor === undefined ? defaultMaxLoadFactor : options.maxLoadFactor;\n if (minLoadFactor < 0 || minLoadFactor >= 1) {\n throw new RangeError(`invalid minLoadFactor: ${minLoadFactor}`);\n }\n if (maxLoadFactor <= 0 || maxLoadFactor >= 1) {\n throw new RangeError(`invalid maxLoadFactor: ${maxLoadFactor}`);\n }\n if (minLoadFactor >= maxLoadFactor) {\n throw new RangeError(`minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`);\n }\n\n let capacity = initialCapacity;\n // User wants to put at least capacity elements. We need to choose the size based on the maxLoadFactor to\n // avoid the need to rehash before this capacity is reached.\n // actualCapacity * maxLoadFactor >= capacity\n capacity = (capacity / maxLoadFactor) | 0;\n capacity = nextPrime(capacity);\n if (capacity === 0) capacity = 1;\n\n this.table = newArray(capacity, 0);\n this.values = newArray(capacity, 0);\n this.state = newArray(capacity, 0);\n\n this.minLoadFactor = minLoadFactor;\n if (capacity === largestPrime) {\n this.maxLoadFactor = 1;\n } else {\n this.maxLoadFactor = maxLoadFactor;\n }\n\n this.distinct = 0;\n this.freeEntries = capacity;\n\n this.lowWaterMark = 0;\n this.highWaterMark = chooseHighWaterMark(capacity, this.maxLoadFactor);\n }\n\n clone() {\n return new HashTable(this);\n }\n\n get size() {\n return this.distinct;\n }\n\n get(key) {\n const i = this.indexOfKey(key);\n if (i < 0) return 0;\n return this.values[i];\n }\n\n set(key, value) {\n let i = this.indexOfInsertion(key);\n if (i < 0) {\n i = -i - 1;\n this.values[i] = value;\n return false;\n }\n\n if (this.distinct > this.highWaterMark) {\n const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n return this.set(key, value);\n }\n\n this.table[i] = key;\n this.values[i] = value;\n if (this.state[i] === FREE) this.freeEntries--;\n this.state[i] = FULL;\n this.distinct++;\n\n if (this.freeEntries < 1) {\n const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n }\n\n return true;\n }\n \n remove(key, noRehash) {\n const i = this.indexOfKey(key);\n if (i < 0) return false;\n\n this.state[i] = REMOVED;\n this.distinct--;\n\n if (!noRehash) this.maybeShrinkCapacity();\n\n return true;\n }\n\n delete(key, noRehash) {\n const i = this.indexOfKey(key);\n if (i < 0) return false;\n\n this.state[i] = FREE;\n this.distinct--;\n\n if (!noRehash) this.maybeShrinkCapacity();\n\n return true;\n }\n\n maybeShrinkCapacity() {\n if (this.distinct < this.lowWaterMark) {\n const newCapacity = chooseShrinkCapacity(this.distinct, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n }\n }\n\n containsKey(key) {\n return this.indexOfKey(key) >= 0;\n }\n\n indexOfKey(key) {\n const table = this.table;\n const state = this.state;\n const length = this.table.length;\n\n const hash = key & 0x7fffffff;\n let i = hash % length;\n let decrement = hash % (length - 2);\n if (decrement === 0) decrement = 1;\n\n while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) {\n i -= decrement;\n if (i < 0) i += length;\n }\n\n if (state[i] === FREE) return -1;\n return i;\n }\n\n containsValue(value) {\n return this.indexOfValue(value) >= 0;\n }\n\n indexOfValue(value) {\n const values = this.values;\n const state = this.state;\n\n for (var i = 0; i < state.length; i++) {\n if (state[i] === FULL && values[i] === value) {\n return i;\n }\n }\n\n return -1;\n }\n\n indexOfInsertion(key) {\n const table = this.table;\n const state = this.state;\n const length = table.length;\n\n\n const hash = key & 0x7fffffff;\n let i = hash % length;\n let decrement = hash % (length - 2);\n if (decrement === 0) decrement = 1;\n\n while (state[i] === FULL && table[i] !== key) {\n i -= decrement;\n if (i < 0) i += length;\n }\n\n if (state[i] === REMOVED) {\n const j = i;\n while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) {\n i -= decrement;\n if (i < 0) i += length;\n }\n if (state[i] === FREE) i = j;\n }\n\n if (state[i] === FULL) {\n return -i - 1;\n }\n\n return i;\n }\n\n ensureCapacity(minCapacity) {\n if (this.table.length < minCapacity) {\n const newCapacity = nextPrime(minCapacity);\n this.rehash(newCapacity);\n }\n }\n\n rehash(newCapacity) {\n const oldCapacity = this.table.length;\n\n if (newCapacity <= this.distinct) throw new Error('Unexpected');\n\n const oldTable = this.table;\n const oldValues = this.values;\n const oldState = this.state;\n\n const newTable = newArray(newCapacity, 0);\n const newValues = newArray(newCapacity, 0);\n const newState = newArray(newCapacity, 0);\n\n this.lowWaterMark = chooseLowWaterMark(newCapacity, this.minLoadFactor);\n this.highWaterMark = chooseHighWaterMark(newCapacity, this.maxLoadFactor);\n\n this.table = newTable;\n this.values = newValues;\n this.state = newState;\n this.freeEntries = newCapacity - this.distinct;\n\n for (var i = 0; i < oldCapacity; i++) {\n if (oldState[i] === FULL) {\n var element = oldTable[i];\n var index = this.indexOfInsertion(element);\n newTable[index] = element;\n newValues[index] = oldValues[i];\n newState[index] = FULL;\n }\n }\n }\n\n forEachKey(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.table[i])) return false;\n }\n }\n return true;\n }\n\n forEachValue(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.values[i])) return false;\n }\n }\n return true;\n }\n\n forEachPair(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.table[i], this.values[i])) return false;\n }\n }\n return true;\n }\n}\n\nmodule.exports = HashTable;\n\nfunction chooseLowWaterMark(capacity, minLoad) {\n return (capacity * minLoad) | 0;\n}\n\nfunction chooseHighWaterMark(capacity, maxLoad) {\n return Math.min(capacity - 2, (capacity * maxLoad) | 0);\n}\n\nfunction chooseGrowCapacity(size, minLoad, maxLoad) {\n return nextPrime(Math.max(size + 1, (4 * size / (3 * minLoad + maxLoad)) | 0));\n}\n\nfunction chooseShrinkCapacity(size, minLoad, maxLoad) {\n return nextPrime(Math.max(size + 1, (4 * size / (minLoad + 3 * maxLoad)) | 0));\n}\n","'use strict';\n\nconst Heap = require('heap');\n\nfunction Cluster() {\n this.children = [];\n this.distance = -1;\n this.index = [];\n}\n\n/**\n * Creates an array of values where maximum distance smaller than the threshold\n * @param {number} threshold\n * @return {Array }\n */\nCluster.prototype.cut = function (threshold) {\n if (threshold < 0) throw new RangeError('Threshold too small');\n var root = new Cluster();\n root.children = this.children;\n root.distance = this.distance;\n root.index = this.index;\n var list = [root];\n var ans = [];\n while (list.length > 0) {\n var aux = list.shift();\n if (threshold >= aux.distance) {\n ans.push(aux);\n } else {\n list = list.concat(aux.children);\n }\n }\n return ans;\n};\n\n/**\n * Merge the leaves in the minimum way to have 'minGroups' number of clusters\n * @param {number} minGroups - Them minimum number of children the first level of the tree should have\n * @return {Cluster}\n */\nCluster.prototype.group = function (minGroups) {\n if (!Number.isInteger(minGroups) || minGroups < 1) throw new RangeError('Number of groups must be a positive integer');\n\n const heap = new Heap(function (a, b) {\n return b.distance - a.distance;\n });\n\n heap.push(this);\n\n while (heap.size() < minGroups) {\n var first = heap.pop();\n if (first.children.length === 0) {\n break;\n }\n first.children.forEach(child => heap.push(child));\n }\n\n var root = new Cluster();\n root.children = heap.toArray();\n root.distance = this.distance;\n\n return root;\n};\n\n/**\n * Traverses the tree depth-first and provide callback to be called on each individual node\n * @param {function} cb - The callback to be called on each node encounter\n * @type {Cluster}\n */\nCluster.prototype.traverse = function (cb) {\n function visit(root, callback) {\n callback(root);\n if (root.children) {\n for (var i = root.children.length - 1; i >= 0; i--) {\n visit(root.children[i], callback);\n }\n }\n }\n visit(this, cb);\n};\n\nmodule.exports = Cluster;\n","'use strict';\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toStr = Object.prototype.toString;\nvar defineProperty = Object.defineProperty;\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nvar isArray = function isArray(arr) {\n\tif (typeof Array.isArray === 'function') {\n\t\treturn Array.isArray(arr);\n\t}\n\n\treturn toStr.call(arr) === '[object Array]';\n};\n\nvar isPlainObject = function isPlainObject(obj) {\n\tif (!obj || toStr.call(obj) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tvar hasOwnConstructor = hasOwn.call(obj, 'constructor');\n\tvar hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n\t\treturn false;\n\t}\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor (key in obj) { /**/ }\n\n\treturn typeof key === 'undefined' || hasOwn.call(obj, key);\n};\n\n// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target\nvar setProperty = function setProperty(target, options) {\n\tif (defineProperty && options.name === '__proto__') {\n\t\tdefineProperty(target, options.name, {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\tvalue: options.newValue,\n\t\t\twritable: true\n\t\t});\n\t} else {\n\t\ttarget[options.name] = options.newValue;\n\t}\n};\n\n// Return undefined instead of __proto__ if '__proto__' is not an own property\nvar getProperty = function getProperty(obj, name) {\n\tif (name === '__proto__') {\n\t\tif (!hasOwn.call(obj, name)) {\n\t\t\treturn void 0;\n\t\t} else if (gOPD) {\n\t\t\t// In early versions of node, obj['__proto__'] is buggy when obj has\n\t\t\t// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.\n\t\t\treturn gOPD(obj, name).value;\n\t\t}\n\t}\n\n\treturn obj[name];\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone;\n\tvar target = arguments[0];\n\tvar i = 1;\n\tvar length = arguments.length;\n\tvar deep = false;\n\n\t// Handle a deep copy situation\n\tif (typeof target === 'boolean') {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t}\n\tif (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n\t\ttarget = {};\n\t}\n\n\tfor (; i < length; ++i) {\n\t\toptions = arguments[i];\n\t\t// Only deal with non-null/undefined values\n\t\tif (options != null) {\n\t\t\t// Extend the base object\n\t\t\tfor (name in options) {\n\t\t\t\tsrc = getProperty(target, name);\n\t\t\t\tcopy = getProperty(options, name);\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif (target !== copy) {\n\t\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\t\tif (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {\n\t\t\t\t\t\tif (copyIsArray) {\n\t\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\t\tclone = src && isArray(src) ? src : [];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: extend(deep, clone, copy) });\n\n\t\t\t\t\t// Don't bring in undefined values\n\t\t\t\t\t} else if (typeof copy !== 'undefined') {\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: copy });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n","import isArray from 'is-any-array';\n\n/**\n * Computes the minimum of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction min(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var min = input[0];\n\n for (var i = 1; i < input.length; i++) {\n if (input[i] < min) min = input[i];\n }\n\n return min;\n}\n\nexport default min;\n","import quickSelectMedian from 'median-quickselect';\nimport isArray from 'is-any-array';\n\n/**\n * Computes the median of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction median(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n return quickSelectMedian(input.slice());\n}\n\nexport default median;\n","const LOOP = 8;\nconst FLOAT_MUL = 1 / 16777216;\nconst sh1 = 15;\nconst sh2 = 18;\nconst sh3 = 11;\nfunction multiply_uint32(n, m) {\n n >>>= 0;\n m >>>= 0;\n const nlo = n & 0xffff;\n const nhi = n - nlo;\n return (((nhi * m) >>> 0) + nlo * m) >>> 0;\n}\nexport default class XSadd {\n constructor(seed = Date.now()) {\n this.state = new Uint32Array(4);\n this.init(seed);\n this.random = this.getFloat.bind(this);\n }\n /**\n * Returns a 32-bit integer r (0 <= r < 2^32)\n */\n getUint32() {\n this.nextState();\n return (this.state[3] + this.state[2]) >>> 0;\n }\n /**\n * Returns a floating point number r (0.0 <= r < 1.0)\n */\n getFloat() {\n return (this.getUint32() >>> 8) * FLOAT_MUL;\n }\n init(seed) {\n if (!Number.isInteger(seed)) {\n throw new TypeError('seed must be an integer');\n }\n this.state[0] = seed;\n this.state[1] = 0;\n this.state[2] = 0;\n this.state[3] = 0;\n for (let i = 1; i < LOOP; i++) {\n this.state[i & 3] ^=\n (i +\n multiply_uint32(1812433253, this.state[(i - 1) & 3] ^ ((this.state[(i - 1) & 3] >>> 30) >>> 0))) >>>\n 0;\n }\n this.periodCertification();\n for (let i = 0; i < LOOP; i++) {\n this.nextState();\n }\n }\n periodCertification() {\n if (this.state[0] === 0 &&\n this.state[1] === 0 &&\n this.state[2] === 0 &&\n this.state[3] === 0) {\n this.state[0] = 88; // X\n this.state[1] = 83; // S\n this.state[2] = 65; // A\n this.state[3] = 68; // D\n }\n }\n nextState() {\n let t = this.state[0];\n t ^= t << sh1;\n t ^= t >>> sh2;\n t ^= this.state[3] << sh3;\n this.state[0] = this.state[1];\n this.state[1] = this.state[2];\n this.state[2] = this.state[3];\n this.state[3] = t;\n }\n}\n","import arrayMean from 'ml-array-mean';\nimport isArray from 'is-any-array';\n\n/**\n * Computes the variance of the given values\n * @param {Array} values\n * @param {object} [options]\n * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n.\n * @param {number} [options.mean = arrayMean] - precalculated mean, if any.\n * @return {number}\n */\n\nfunction variance(values) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n if (!isArray(values)) {\n throw new TypeError('input must be an array');\n }\n\n var _options$unbiased = options.unbiased,\n unbiased = _options$unbiased === void 0 ? true : _options$unbiased,\n _options$mean = options.mean,\n mean = _options$mean === void 0 ? arrayMean(values) : _options$mean;\n var sqrError = 0;\n\n for (var i = 0; i < values.length; i++) {\n var x = values[i] - mean;\n sqrError += x * x;\n }\n\n if (unbiased) {\n return sqrError / (values.length - 1);\n } else {\n return sqrError / values.length;\n }\n}\n\nexport default variance;\n","'use strict';\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\n/**\n * Computes the sum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.sum = function sum(values) {\n var sum = 0;\n for (var i = 0; i < values.length; i++) {\n sum += values[i];\n }\n return sum;\n};\n\n/**\n * Computes the maximum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.max = function max(values) {\n var max = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] > max) max = values[i];\n }\n return max;\n};\n\n/**\n * Computes the minimum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.min = function min(values) {\n var min = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] < min) min = values[i];\n }\n return min;\n};\n\n/**\n * Computes the min and max of the given values\n * @param {Array} values\n * @returns {{min: number, max: number}}\n */\nexports.minMax = function minMax(values) {\n var min = values[0];\n var max = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] < min) min = values[i];\n if (values[i] > max) max = values[i];\n }\n return {\n min: min,\n max: max\n };\n};\n\n/**\n * Computes the arithmetic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.arithmeticMean = function arithmeticMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n sum += values[i];\n }\n return sum / l;\n};\n\n/**\n * {@link arithmeticMean}\n */\nexports.mean = exports.arithmeticMean;\n\n/**\n * Computes the geometric mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.geometricMean = function geometricMean(values) {\n var mul = 1;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n mul *= values[i];\n }\n return Math.pow(mul, 1 / l);\n};\n\n/**\n * Computes the mean of the log of the given values\n * If the return value is exponentiated, it gives the same result as the\n * geometric mean.\n * @param {Array} values\n * @returns {number}\n */\nexports.logMean = function logMean(values) {\n var lnsum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n lnsum += Math.log(values[i]);\n }\n return lnsum / l;\n};\n\n/**\n * Computes the weighted grand mean for a list of means and sample sizes\n * @param {Array} means - Mean values for each set of samples\n * @param {Array} samples - Number of original values for each set of samples\n * @returns {number}\n */\nexports.grandMean = function grandMean(means, samples) {\n var sum = 0;\n var n = 0;\n var l = means.length;\n for (var i = 0; i < l; i++) {\n sum += samples[i] * means[i];\n n += samples[i];\n }\n return sum / n;\n};\n\n/**\n * Computes the truncated mean of the given values using a given percentage\n * @param {Array} values\n * @param {number} percent - The percentage of values to keep (range: [0,1])\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.truncatedMean = function truncatedMean(values, percent, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var k = Math.floor(l * percent);\n var sum = 0;\n for (var i = k; i < (l - k); i++) {\n sum += values[i];\n }\n return sum / (l - 2 * k);\n};\n\n/**\n * Computes the harmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.harmonicMean = function harmonicMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (values[i] === 0) {\n throw new RangeError('value at index ' + i + 'is zero');\n }\n sum += 1 / values[i];\n }\n return l / sum;\n};\n\n/**\n * Computes the contraharmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.contraHarmonicMean = function contraHarmonicMean(values) {\n var r1 = 0;\n var r2 = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n r1 += values[i] * values[i];\n r2 += values[i];\n }\n if (r2 < 0) {\n throw new RangeError('sum of values is negative');\n }\n return r1 / r2;\n};\n\n/**\n * Computes the median of the given values\n * @param {Array} values\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.median = function median(values, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return (values[half - 1] + values[half]) * 0.5;\n } else {\n return values[half];\n }\n};\n\n/**\n * Computes the variance of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.variance = function variance(values, unbiased) {\n if (unbiased === undefined) unbiased = true;\n var theMean = exports.mean(values);\n var theVariance = 0;\n var l = values.length;\n\n for (var i = 0; i < l; i++) {\n var x = values[i] - theMean;\n theVariance += x * x;\n }\n\n if (unbiased) {\n return theVariance / (l - 1);\n } else {\n return theVariance / l;\n }\n};\n\n/**\n * Computes the standard deviation of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.standardDeviation = function standardDeviation(values, unbiased) {\n return Math.sqrt(exports.variance(values, unbiased));\n};\n\nexports.standardError = function standardError(values) {\n return exports.standardDeviation(values) / Math.sqrt(values.length);\n};\n\n/**\n * IEEE Transactions on biomedical engineering, vol. 52, no. 1, january 2005, p. 76-\n * Calculate the standard deviation via the Median of the absolute deviation\n * The formula for the standard deviation only holds for Gaussian random variables.\n * @returns {{mean: number, stdev: number}}\n */\nexports.robustMeanAndStdev = function robustMeanAndStdev(y) {\n var mean = 0, stdev = 0;\n var length = y.length, i = 0;\n for (i = 0; i < length; i++) {\n mean += y[i];\n }\n mean /= length;\n var averageDeviations = new Array(length);\n for (i = 0; i < length; i++)\n averageDeviations[i] = Math.abs(y[i] - mean);\n averageDeviations.sort(compareNumbers);\n if (length % 2 === 1) {\n stdev = averageDeviations[(length - 1) / 2] / 0.6745;\n } else {\n stdev = 0.5 * (averageDeviations[length / 2] + averageDeviations[length / 2 - 1]) / 0.6745;\n }\n\n return {\n mean: mean,\n stdev: stdev\n };\n};\n\nexports.quartiles = function quartiles(values, alreadySorted) {\n if (typeof (alreadySorted) === 'undefined') alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n\n var quart = values.length / 4;\n var q1 = values[Math.ceil(quart) - 1];\n var q2 = exports.median(values, true);\n var q3 = values[Math.ceil(quart * 3) - 1];\n\n return {q1: q1, q2: q2, q3: q3};\n};\n\nexports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) {\n return Math.sqrt(exports.pooledVariance(samples, unbiased));\n};\n\nexports.pooledVariance = function pooledVariance(samples, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var sum = 0;\n var length = 0, l = samples.length;\n for (var i = 0; i < l; i++) {\n var values = samples[i];\n var vari = exports.variance(values);\n\n sum += (values.length - 1) * vari;\n\n if (unbiased)\n length += values.length - 1;\n else\n length += values.length;\n }\n return sum / length;\n};\n\nexports.mode = function mode(values) {\n var l = values.length,\n itemCount = new Array(l),\n i;\n for (i = 0; i < l; i++) {\n itemCount[i] = 0;\n }\n var itemArray = new Array(l);\n var count = 0;\n\n for (i = 0; i < l; i++) {\n var index = itemArray.indexOf(values[i]);\n if (index >= 0)\n itemCount[index]++;\n else {\n itemArray[count] = values[i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (i = 0; i < count; i++) {\n if (itemCount[i] > maxValue) {\n maxValue = itemCount[i];\n maxIndex = i;\n }\n }\n\n return itemArray[maxIndex];\n};\n\nexports.covariance = function covariance(vector1, vector2, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var mean1 = exports.mean(vector1);\n var mean2 = exports.mean(vector2);\n\n if (vector1.length !== vector2.length)\n throw 'Vectors do not have the same dimensions';\n\n var cov = 0, l = vector1.length;\n for (var i = 0; i < l; i++) {\n var x = vector1[i] - mean1;\n var y = vector2[i] - mean2;\n cov += x * y;\n }\n\n if (unbiased)\n return cov / (l - 1);\n else\n return cov / l;\n};\n\nexports.skewness = function skewness(values, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n\n var s2 = 0, s3 = 0, l = values.length;\n for (var i = 0; i < l; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n var m2 = s2 / l;\n var m3 = s3 / l;\n\n var g = m3 / (Math.pow(m2, 3 / 2.0));\n if (unbiased) {\n var a = Math.sqrt(l * (l - 1));\n var b = l - 2;\n return (a / b) * g;\n } else {\n return g;\n }\n};\n\nexports.kurtosis = function kurtosis(values, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n var n = values.length, s2 = 0, s4 = 0;\n\n for (var i = 0; i < n; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n\n return a * b - 3 * c;\n } else {\n return m4 / (m2 * m2) - 3;\n }\n};\n\nexports.entropy = function entropy(values, eps) {\n if (typeof (eps) === 'undefined') eps = 0;\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * Math.log(values[i] + eps);\n return -sum;\n};\n\nexports.weightedMean = function weightedMean(values, weights) {\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * weights[i];\n return sum;\n};\n\nexports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) {\n return Math.sqrt(exports.weightedVariance(values, weights));\n};\n\nexports.weightedVariance = function weightedVariance(values, weights) {\n var theMean = exports.weightedMean(values, weights);\n var vari = 0, l = values.length;\n var a = 0, b = 0;\n\n for (var i = 0; i < l; i++) {\n var z = values[i] - theMean;\n var w = weights[i];\n\n vari += w * (z * z);\n b += w;\n a += w * w;\n }\n\n return vari * (b / (b * b - a));\n};\n\nexports.center = function center(values, inPlace) {\n if (typeof (inPlace) === 'undefined') inPlace = false;\n\n var result = values;\n if (!inPlace)\n result = [].concat(values);\n\n var theMean = exports.mean(result), l = result.length;\n for (var i = 0; i < l; i++)\n result[i] -= theMean;\n};\n\nexports.standardize = function standardize(values, standardDev, inPlace) {\n if (typeof (standardDev) === 'undefined') standardDev = exports.standardDeviation(values);\n if (typeof (inPlace) === 'undefined') inPlace = false;\n var l = values.length;\n var result = inPlace ? values : new Array(l);\n for (var i = 0; i < l; i++)\n result[i] = values[i] / standardDev;\n return result;\n};\n\nexports.cumulativeSum = function cumulativeSum(array) {\n var l = array.length;\n var result = new Array(l);\n result[0] = array[0];\n for (var i = 1; i < l; i++)\n result[i] = result[i - 1] + array[i];\n return result;\n};\n","'use strict';\n\nconst Cluster = require('./Cluster');\nconst util = require('util');\n\nfunction ClusterLeaf(index) {\n Cluster.call(this);\n this.index = index;\n this.distance = 0;\n this.children = [];\n}\n\nutil.inherits(ClusterLeaf, Cluster);\n\nmodule.exports = ClusterLeaf;\n","'use strict';\n\n\n/**\n * Computes a distance/similarity matrix given an array of data and a distance/similarity function.\n * @param {Array} data An array of data\n * @param {function} distanceFn A function that accepts two arguments and computes a distance/similarity between them\n * @return {Array} The similarity matrix. The similarity matrix is square and has a size equal to the length of\n * the data array\n */\nfunction distanceMatrix(data, distanceFn) {\n const length = data.length;\n let result = Array.from({length}).map(() => Array.from({length}));\n\n // Compute upper distance matrix\n for (let i = 0; i < length; i++) {\n for (let j = 0; j <= i; j++) {\n result[i][j] = distanceFn(data[i], data[j]);\n }\n }\n\n // Copy to lower distance matrix\n for (let i = 0; i < length; i++) {\n for (let j = i + 1; j < length; j++) {\n result[i][j] = result[j][i];\n }\n }\n\n return result;\n}\n\nmodule.exports = distanceMatrix;\n","/**\n * Constructs a confusion matrix\n * @class ConfusionMatrix\n * @example\n * const CM = new ConfusionMatrix([[13, 2], [10, 5]], ['cat', 'dog'])\n * @param {Array>} matrix - The confusion matrix, a 2D Array. Rows represent the actual label and columns\n * the predicted label.\n * @param {Array} labels - Labels of the confusion matrix, a 1D Array\n */\nclass ConfusionMatrix {\n constructor(matrix, labels) {\n if (matrix.length !== matrix[0].length) {\n throw new Error('Confusion matrix must be square');\n }\n if (labels.length !== matrix.length) {\n throw new Error('Confusion matrix and labels should have the same length');\n }\n this.labels = labels;\n this.matrix = matrix;\n }\n\n\n /**\n * Construct confusion matrix from the predicted and actual labels (classes). Be sure to provide the arguments in\n * the correct order!\n * @param {Array} actual - The predicted labels of the classification\n * @param {Array} predicted - The actual labels of the classification. Has to be of same length as\n * predicted.\n * @param {object} [options] - Additional options\n * @param {Array} [options.labels] - The list of labels that should be used. If not provided the distinct set\n * of labels present in predicted and actual is used. Labels are compared using the strict equality operator\n * '==='\n * @return {ConfusionMatrix} - Confusion matrix\n */\n static fromLabels(actual, predicted, options = {}) {\n if (predicted.length !== actual.length) {\n throw new Error('predicted and actual must have the same length');\n }\n let distinctLabels;\n if (options.labels) {\n distinctLabels = new Set(options.labels);\n } else {\n distinctLabels = new Set([...actual, ...predicted]);\n }\n distinctLabels = Array.from(distinctLabels);\n if (options.sort) {\n distinctLabels.sort(options.sort);\n }\n\n // Create confusion matrix and fill with 0's\n const matrix = Array.from({length: distinctLabels.length});\n for (let i = 0; i < matrix.length; i++) {\n matrix[i] = new Array(matrix.length);\n matrix[i].fill(0);\n }\n\n for (let i = 0; i < predicted.length; i++) {\n const actualIdx = distinctLabels.indexOf(actual[i]);\n const predictedIdx = distinctLabels.indexOf(predicted[i]);\n if (actualIdx >= 0 && predictedIdx >= 0) {\n matrix[actualIdx][predictedIdx]++;\n }\n }\n\n return new ConfusionMatrix(matrix, distinctLabels);\n }\n\n /**\n * Get the confusion matrix\n * @return {Array >}\n */\n getMatrix() {\n return this.matrix;\n }\n\n getLabels() {\n return this.labels;\n }\n\n /**\n * Get the total number of samples\n * @return {number}\n */\n getTotalCount() {\n let predicted = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n for (var j = 0; j < this.matrix.length; j++) {\n predicted += this.matrix[i][j];\n }\n }\n return predicted;\n }\n\n /**\n * Get the total number of true predictions\n * @return {number}\n */\n getTrueCount() {\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n count += this.matrix[i][i];\n }\n return count;\n }\n\n /**\n * Get the total number of false predictions.\n * @return {number}\n */\n getFalseCount() {\n return this.getTotalCount() - this.getTrueCount();\n }\n\n /**\n * Get the number of true positive predictions.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getTruePositiveCount(label) {\n const index = this.getIndex(label);\n return this.matrix[index][index];\n }\n\n /**\n * Get the number of true negative predictions\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getTrueNegativeCount(label) {\n const index = this.getIndex(label);\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n for (var j = 0; j < this.matrix.length; j++) {\n if (i !== index && j !== index) {\n count += this.matrix[i][j];\n }\n }\n }\n return count;\n }\n\n /**\n * Get the number of false positive predictions.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalsePositiveCount(label) {\n const index = this.getIndex(label);\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n if (i !== index) {\n count += this.matrix[i][index];\n }\n }\n return count;\n }\n\n /**\n * Get the number of false negative predictions.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseNegativeCount(label) {\n const index = this.getIndex(label);\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n if (i !== index) {\n count += this.matrix[index][i];\n }\n }\n return count;\n }\n\n /**\n * Get the number of real positive samples.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getPositiveCount(label) {\n return this.getTruePositiveCount(label) + this.getFalseNegativeCount(label);\n }\n\n /**\n * Get the number of real negative samples.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getNegativeCount(label) {\n return this.getTrueNegativeCount(label) + this.getFalsePositiveCount(label);\n }\n\n /**\n * Get the index in the confusion matrix that corresponds to the given label\n * @param {any} label - The label to search for\n * @throws if the label is not found\n * @return {number}\n */\n getIndex(label) {\n const index = this.labels.indexOf(label);\n if (index === -1) throw new Error('The label does not exist');\n return index;\n }\n\n /**\n * Get the true positive rate a.k.a. sensitivity. Computes the ratio between the number of true positive predictions and the total number of positive samples.\n * {@link https://en.wikipedia.org/wiki/Sensitivity_and_specificity}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number} - The true positive rate [0-1]\n */\n getTruePositiveRate(label) {\n return this.getTruePositiveCount(label) / this.getPositiveCount(label);\n }\n\n /**\n * Get the true negative rate a.k.a. specificity. Computes the ration between the number of true negative predictions and the total number of negative samples.\n * {@link https://en.wikipedia.org/wiki/Sensitivity_and_specificity}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getTrueNegativeRate(label) {\n return this.getTrueNegativeCount(label) / this.getNegativeCount(label);\n }\n\n /**\n * Get the positive predictive value a.k.a. precision. Computes TP / (TP + FP)\n * {@link https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getPositivePredictiveValue(label) {\n const TP = this.getTruePositiveCount(label);\n return TP / (TP + this.getFalsePositiveCount(label));\n }\n\n /**\n * Negative predictive value\n * {@link https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getNegativePredictiveValue(label) {\n const TN = this.getTrueNegativeCount(label);\n return TN / (TN + this.getFalseNegativeCount(label));\n }\n\n /**\n * False negative rate a.k.a. miss rate.\n * {@link https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#False_positive_and_false_negative_rates}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseNegativeRate(label) {\n return 1 - this.getTruePositiveRate(label);\n }\n\n /**\n * False positive rate a.k.a. fall-out rate.\n * {@link https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#False_positive_and_false_negative_rates}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalsePositiveRate(label) {\n return 1 - this.getTrueNegativeRate(label);\n }\n\n /**\n * False discovery rate (FDR)\n * {@link https://en.wikipedia.org/wiki/False_discovery_rate}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseDiscoveryRate(label) {\n const FP = this.getFalsePositiveCount(label);\n return FP / (FP + this.getTruePositiveCount(label));\n }\n\n /**\n * False omission rate (FOR)\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseOmissionRate(label) {\n const FN = this.getFalseNegativeCount(label);\n return FN / (FN + this.getTruePositiveCount(label));\n }\n\n /**\n * F1 score\n * {@link https://en.wikipedia.org/wiki/F1_score}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getF1Score(label) {\n const TP = this.getTruePositiveCount(label);\n return 2 * TP / (2 * TP + this.getFalsePositiveCount(label) + this.getFalseNegativeCount(label));\n }\n\n /**\n * Matthews correlation coefficient (MCC)\n * {@link https://en.wikipedia.org/wiki/Matthews_correlation_coefficient}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getMatthewsCorrelationCoefficient(label) {\n const TP = this.getTruePositiveCount(label);\n const TN = this.getTrueNegativeCount(label);\n const FP = this.getFalsePositiveCount(label);\n const FN = this.getFalseNegativeCount(label);\n return (TP * TN - FP * FN) / Math.sqrt((TP + FP) * (TP + FN) * (TN + FP) * (TN + FN));\n }\n\n /**\n * Informedness\n * {@link https://en.wikipedia.org/wiki/Youden%27s_J_statistic}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getInformedness(label) {\n return this.getTruePositiveRate(label) + this.getTrueNegativeRate(label) - 1;\n }\n\n /**\n * Markedness\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getMarkedness(label) {\n return this.getPositivePredictiveValue(label) + this.getNegativePredictiveValue(label) - 1;\n }\n\n /**\n * Get the confusion table.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {Array >} - The 2x2 confusion table. [[TP, FN], [FP, TN]]\n */\n getConfusionTable(label) {\n return [\n [\n this.getTruePositiveCount(label),\n this.getFalseNegativeCount(label)\n ],\n [\n this.getFalsePositiveCount(label),\n this.getTrueNegativeCount(label)\n ]\n ];\n }\n\n /**\n * Get total accuracy.\n * @return {number} - The ratio between the number of true predictions and total number of classifications ([0-1])\n */\n getAccuracy() {\n let correct = 0;\n let incorrect = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n for (var j = 0; j < this.matrix.length; j++) {\n if (i === j) correct += this.matrix[i][j];\n else incorrect += this.matrix[i][j];\n }\n }\n return correct / (correct + incorrect);\n }\n\n\n /**\n * Returns the element in the confusion matrix that corresponds to the given actual and predicted labels.\n * @param {any} actual - The true label\n * @param {any} predicted - The predicted label\n * @return {number} - The element in the confusion matrix\n */\n getCount(actual, predicted) {\n const actualIndex = this.getIndex(actual);\n const predictedIndex = this.getIndex(predicted);\n return this.matrix[actualIndex][predictedIndex];\n }\n\n /**\n * Compute the general prediction accuracy\n * @deprecated Use getAccuracy\n * @return {number} - The prediction accuracy ([0-1]\n */\n get accuracy() {\n return this.getAccuracy();\n }\n\n /**\n * Compute the number of predicted observations\n * @deprecated Use getTotalCount\n * @return {number}\n */\n get total() {\n return this.getTotalCount();\n }\n}\n\nmodule.exports = ConfusionMatrix;\n","'use strict';\n\nvar Matrix = require('ml-matrix').Matrix;\n\nvar Utils = require('./utils');\nconst ACTIVATION_FUNCTIONS = require('./activationFunctions');\n\nclass Layer {\n /**\n * @private\n * Create a new layer with the given options\n * @param {object} options\n * @param {number} [options.inputSize] - Number of conections that enter the neurons.\n * @param {number} [options.outputSize] - Number of conections that leave the neurons.\n * @param {number} [options.regularization] - Regularization parameter.\n * @param {number} [options.epsilon] - Learning rate parameter.\n * @param {string} [options.activation] - Activation function parameter from the FeedForwardNeuralNetwork class.\n * @param {number} [options.activationParam] - Activation parameter if needed.\n */\n constructor(options) {\n this.inputSize = options.inputSize;\n this.outputSize = options.outputSize;\n this.regularization = options.regularization;\n this.epsilon = options.epsilon;\n this.activation = options.activation;\n this.activationParam = options.activationParam;\n\n var selectedFunction = ACTIVATION_FUNCTIONS[options.activation];\n var params = selectedFunction.activation.length;\n\n var actFunction = params > 1 ? val => selectedFunction.activation(val, options.activationParam) : selectedFunction.activation;\n var derFunction = params > 1 ? val => selectedFunction.derivate(val, options.activationParam) : selectedFunction.derivate;\n\n this.activationFunction = function (i, j) {\n this[i][j] = actFunction(this[i][j]);\n };\n this.derivate = function (i, j) {\n this[i][j] = derFunction(this[i][j]);\n };\n\n if (options.model) {\n // load model\n this.W = Matrix.checkMatrix(options.W);\n this.b = Matrix.checkMatrix(options.b);\n\n } else {\n // default constructor\n\n this.W = Matrix.rand(this.inputSize, this.outputSize);\n this.b = Matrix.zeros(1, this.outputSize);\n\n this.W.apply(function (i, j) {\n this[i][j] /= Math.sqrt(options.inputSize);\n });\n }\n }\n\n /**\n * @private\n * propagate the given input through the current layer.\n * @param {Matrix} X - input.\n * @return {Matrix} output at the current layer.\n */\n forward(X) {\n var z = X.mmul(this.W).addRowVector(this.b);\n z.apply(this.activationFunction);\n this.a = z.clone();\n return z;\n }\n\n /**\n * @private\n * apply backpropagation algorithm at the current layer\n * @param {Matrix} delta - delta values estimated at the following layer.\n * @param {Matrix} a - 'a' values from the following layer.\n * @return {Matrix} the new delta values for the next layer.\n */\n backpropagation(delta, a) {\n this.dW = a.transposeView().mmul(delta);\n this.db = Utils.sumCol(delta);\n\n var aCopy = a.clone();\n return delta.mmul(this.W.transposeView()).mul(aCopy.apply(this.derivate));\n }\n\n /**\n * @private\n * Function that updates the weights at the current layer with the derivatives.\n */\n update() {\n this.dW.add(this.W.clone().mul(this.regularization));\n this.W.add(this.dW.mul(-this.epsilon));\n this.b.add(this.db.mul(-this.epsilon));\n }\n\n /**\n * @private\n * Export the current layer to JSON.\n * @return {object} model\n */\n toJSON() {\n return {\n model: 'Layer',\n inputSize: this.inputSize,\n outputSize: this.outputSize,\n regularization: this.regularization,\n epsilon: this.epsilon,\n activation: this.activation,\n W: this.W,\n b: this.b\n };\n }\n\n /**\n * @private\n * Creates a new Layer with the given model.\n * @param {object} model\n * @return {Layer}\n */\n static load(model) {\n if (model.model !== 'Layer') {\n throw new RangeError('the current model is not a Layer model');\n }\n return new Layer(model);\n }\n\n}\n\nmodule.exports = Layer;\n","'use strict';\n\nvar Matrix = require('ml-matrix').Matrix;\n\n/**\n * @private\n * Retrieves the sum at each row of the given matrix.\n * @param {Matrix} matrix\n * @return {Matrix}\n */\nfunction sumRow(matrix) {\n var sum = Matrix.zeros(matrix.rows, 1);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum[i][0] += matrix[i][j];\n }\n }\n return sum;\n}\n\n/**\n * @private\n * Retrieves the sum at each column of the given matrix.\n * @param {Matrix} matrix\n * @return {Matrix}\n */\nfunction sumCol(matrix) {\n var sum = Matrix.zeros(1, matrix.columns);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum[0][j] += matrix[i][j];\n }\n }\n return sum;\n}\n\n/**\n * @private\n * Method that given an array of labels(predictions), returns two dictionaries, one to transform from labels to\n * numbers and other in the reverse way\n * @param {Array} array\n * @return {object}\n */\nfunction dictOutputs(array) {\n var inputs = {};\n var outputs = {};\n var index = 0;\n for (var i = 0; i < array.length; i += 1) {\n if (inputs[array[i]] === undefined) {\n inputs[array[i]] = index;\n outputs[index] = array[i];\n index++;\n }\n }\n\n return {\n inputs: inputs,\n outputs: outputs\n };\n}\n\nmodule.exports = {\n dictOutputs: dictOutputs,\n sumCol: sumCol,\n sumRow: sumRow\n};\n","'use strict';\n\nfunction logistic(val) {\n return 1 / (1 + Math.exp(-val));\n}\n\nfunction expELU(val, param) {\n return val < 0 ? param * (Math.exp(val) - 1) : val;\n}\n\nfunction softExponential(val, param) {\n if (param < 0) {\n return -Math.log(1 - param * (val + param)) / param;\n }\n if (param > 0) {\n return ((Math.exp(param * val) - 1) / param) + param;\n }\n return val;\n}\n\nfunction softExponentialPrime(val, param) {\n if (param < 0) {\n return 1 / (1 - param * (param + val));\n } else {\n return Math.exp(param * val);\n }\n}\n\nconst ACTIVATION_FUNCTIONS = {\n tanh: {\n activation: Math.tanh,\n derivate: val => 1 - (val * val)\n },\n identity: {\n activation: val => val,\n derivate: () => 1\n },\n logistic: {\n activation: logistic,\n derivate: val => logistic(val) * (1 - logistic(val))\n },\n arctan: {\n activation: Math.atan,\n derivate: val => 1 / (val * val + 1)\n },\n softsign: {\n activation: val => val / (1 + Math.abs(val)),\n derivate: val => 1 / ((1 + Math.abs(val)) * (1 + Math.abs(val)))\n },\n relu: {\n activation: val => val < 0 ? 0 : val,\n derivate: val => val < 0 ? 0 : 1\n },\n softplus: {\n activation: val => Math.log(1 + Math.exp(val)),\n derivate: val => 1 / (1 + Math.exp(-val))\n },\n bent: {\n activation: val => ((Math.sqrt(val * val + 1) - 1) / 2) + val,\n derivate: val => (val / (2 * Math.sqrt(val * val + 1))) + 1\n },\n sinusoid: {\n activation: Math.sin,\n derivate: Math.cos\n },\n sinc: {\n activation: val => val === 0 ? 1 : Math.sin(val) / val,\n derivate: val => val === 0 ? 0 : (Math.cos(val) / val) - (Math.sin(val) / (val * val))\n },\n gaussian: {\n activation: val => Math.exp(-(val * val)),\n derivate: val => -2 * val * Math.exp(-(val * val))\n },\n 'parametric-relu': {\n activation: (val, param) => val < 0 ? param * val : val,\n derivate: (val, param) => val < 0 ? param : 1\n },\n 'exponential-elu': {\n activation: expELU,\n derivate: (val, param) => val < 0 ? expELU(val, param) + param : 1\n },\n 'soft-exponential': {\n activation: softExponential,\n derivate: softExponentialPrime\n }\n};\n\nmodule.exports = ACTIVATION_FUNCTIONS;\n","function NodeSquare(x, y, weights, som) {\n this.x = x;\n this.y = y;\n this.weights = weights;\n this.som = som;\n this.neighbors = {};\n}\n\nNodeSquare.prototype.adjustWeights = function adjustWeights(target, learningRate, influence) {\n for (var i = 0, ii = this.weights.length; i < ii; i++) {\n this.weights[i] += learningRate * influence * (target[i] - this.weights[i]);\n }\n};\n\nNodeSquare.prototype.getDistance = function getDistance(otherNode) {\n return Math.max(Math.abs(this.x - otherNode.x), Math.abs(this.y - otherNode.y));\n};\n\nNodeSquare.prototype.getDistanceTorus = function getDistanceTorus(otherNode) {\n var distX = Math.abs(this.x - otherNode.x),\n distY = Math.abs(this.y - otherNode.y);\n return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY));\n};\n\nNodeSquare.prototype.getNeighbors = function getNeighbors(xy) {\n if (!this.neighbors[xy]) {\n this.neighbors[xy] = new Array(2);\n\n // left or bottom neighbor\n var v;\n if (this[xy] > 0) {\n v = this[xy] - 1;\n } else if (this.som.torus) {\n v = this.som.gridDim[xy] - 1\n }\n if (typeof v !== 'undefined') {\n var x, y;\n if (xy === 'x') {\n x = v;\n y = this.y;\n } else {\n x = this.x;\n y = v;\n }\n this.neighbors[xy][0] = this.som.nodes[x][y];\n }\n\n // top or right neighbor\n var w;\n if (this[xy] < (this.som.gridDim[xy] - 1)) {\n w = this[xy] + 1;\n } else if (this.som.torus) {\n w = 0;\n }\n if (typeof w !== 'undefined') {\n if (xy === 'x') {\n x = w;\n y = this.y;\n } else {\n x = this.x;\n y = w;\n }\n this.neighbors[xy][1] = this.som.nodes[x][y];\n }\n }\n return this.neighbors[xy];\n};\n\nNodeSquare.prototype.getPos = function getPos(xy, element) {\n var neighbors = this.getNeighbors(xy),\n distance = this.som.distance,\n bestNeighbor,\n direction;\n if(neighbors[0]) {\n if (neighbors[1]) {\n var dist1 = distance(element, neighbors[0].weights),\n dist2 = distance(element, neighbors[1].weights);\n if(dist1 < dist2) {\n bestNeighbor = neighbors[0];\n direction = -1;\n } else {\n bestNeighbor = neighbors[1];\n direction = 1;\n }\n } else {\n bestNeighbor = neighbors[0];\n direction = -1;\n }\n } else {\n bestNeighbor = neighbors[1];\n direction = 1;\n }\n var simA = 1 - distance(element, this.weights),\n simB = 1 - distance(element, bestNeighbor.weights);\n var factor = ((simA - simB) / (2 - simA - simB));\n return 0.5 + 0.5 * factor * direction;\n};\n\nNodeSquare.prototype.getPosition = function getPosition(element) {\n return [\n this.getPos('x', element),\n this.getPos('y', element)\n ];\n};\n\nmodule.exports = NodeSquare;","'use strict';\n\nexports.distance = require('./distances');\nexports.similarity = require('./similarities');","'use strict';\n\nmodule.exports = function czekanowskiSimilarity(a, b) {\n var up = 0;\n var down = 0;\n for (var i = 0; i < a.length; i++) {\n up += Math.min(a[i], b[i]);\n down += a[i] + b[i];\n }\n return 2 * up / down;\n};\n","module.exports = function dice(a, b) {\n var ii = a.length,\n p = 0,\n q1 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * a[i];\n q1 += b[i] * b[i];\n q2 += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return q2 / (p + q1);\n};\n","module.exports = function intersection(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.min(a[i], b[i]);\n }\n return 1 - ans;\n};\n","module.exports = function jaccard(a, b) {\n var ii = a.length,\n p1 = 0,\n p2 = 0,\n q1 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p1 += a[i] * b[i];\n p2 += a[i] * a[i];\n q1 += b[i] * b[i];\n q2 += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return q2 / (p2 + q1 - p1);\n};\n","module.exports = function kulczynski(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += Math.min(a[i],b[i]);\n }\n return up / down;\n};\n","module.exports = function motyka(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.min(a[i], b[i]);\n down += a[i] + b[i];\n }\n return 1 - (up / down);\n};\n","module.exports = function squaredChord(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i]));\n }\n return ans;\n};\n","module.exports = function tanimoto(a, b, bitvector) {\n if (bitvector) {\n var inter = 0,\n union = 0;\n for (var j = 0; j < a.length; j++) {\n inter += a[j] && b[j];\n union += a[j] || b[j];\n }\n if (union === 0)\n return 1;\n return inter / union;\n }\n else {\n var ii = a.length,\n p = 0,\n q = 0,\n m = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i];\n q += b[i];\n m += Math.min(a[i],b[i]);\n }\n return 1 - (p + q - 2 * m) / (p + q - m);\n }\n};\n","module.exports = function cosine(a, b) {\n var ii = a.length,\n p = 0,\n p2 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * b[i];\n p2 += a[i] * a[i];\n q2 += b[i] * b[i];\n }\n return p / (Math.sqrt(p2) * Math.sqrt(q2));\n};\n","'use strict';\n\nvar extend = require('extend');\n\nvar defaultOptions = {\n size: 1,\n value: 0\n};\n\n/**\n * Case when the entry is an array\n * @param data\n * @param options\n * @returns {Array}\n */\nfunction arrayCase(data, options) {\n var len = data.length;\n if (typeof options.size === 'number')\n options.size = [options.size, options.size];\n\n var cond = len + options.size[0] + options.size[1];\n\n var output;\n if (options.output) {\n if (options.output.length !== cond)\n throw new RangeError('Wrong output size');\n output = options.output;\n }\n else\n output = new Array(cond);\n\n var i;\n\n // circular option\n if (options.value === 'circular') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[((len - (options.size[0] % len)) + i) % len];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[(i - options.size[0]) % len];\n }\n }\n\n // replicate option\n else if (options.value === 'replicate') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[0];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[len - 1];\n }\n }\n\n // symmetric option\n else if (options.value === 'symmetric') {\n if ((options.size[0] > len) || (options.size[1] > len))\n throw new RangeError('expanded value should not be bigger than the data length');\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[options.size[0] - 1 - i];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[2*len + options.size[0] - i - 1];\n }\n }\n\n // default option\n else {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = options.value;\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = options.value;\n }\n }\n\n return output;\n}\n\n/**\n * Case when the entry is a matrix\n * @param data\n * @param options\n * @returns {Array}\n */\nfunction matrixCase(data, options) {\n var row = data.length;\n var col = data[0].length;\n if (options.size[0] === undefined)\n options.size = [options.size, options.size, options.size, options.size];\n throw new Error('matrix not supported yet, sorry');\n}\n\n/**\n * Pads and array\n * @param {Array } data\n * @param {object} options\n */\nfunction padArray (data, options) {\n options = extend({}, defaultOptions, options);\n\n if (Array.isArray(data)) {\n if (Array.isArray(data[0]))\n return matrixCase(data, options);\n else\n return arrayCase(data, options);\n }\n else\n throw new TypeError('data should be an array');\n}\n\nmodule.exports = padArray;\n","export default function maybeToPrecision(value, digits) {\n if (value < 0) {\n value = 0 - value;\n if (typeof digits === 'number') {\n return '- ' + value.toPrecision(digits);\n } else {\n return '- ' + value.toString();\n }\n } else {\n if (typeof digits === 'number') {\n return value.toPrecision(digits);\n } else {\n return value.toString();\n }\n }\n}\n","export default function checkArraySize(x, y) {\n if (!Array.isArray(x) || !Array.isArray(y)) {\n throw new TypeError('x and y must be arrays');\n }\n if (x.length !== y.length) {\n throw new RangeError('x and y arrays must have the same length');\n }\n}\n","export {default as maybeToPrecision} from './maybeToPrecision';\nexport {default as checkArrayLength} from './checkArrayLength';\n\nexport default class BaseRegression {\n constructor() {\n if (new.target === BaseRegression) {\n throw new Error('BaseRegression must be subclassed');\n }\n }\n\n predict(x) {\n if (typeof x === 'number') {\n return this._predict(x);\n } else if (Array.isArray(x)) {\n const y = new Array(x.length);\n for (let i = 0; i < x.length; i++) {\n y[i] = this._predict(x[i]);\n }\n return y;\n } else {\n throw new TypeError('x must be a number or array');\n }\n }\n\n _predict() {\n throw new Error('_predict must be implemented');\n }\n\n train() {\n //Do nothing for this package\n }\n\n toString() {\n return '';\n }\n\n toLaTeX() {\n return '';\n }\n\n /**\n * Return the correlation coefficient of determination (r) and chi-square.\n * @param {Array} x\n * @param {Array} y\n * @return {object}\n */\n score(x, y) {\n if (!Array.isArray(x) || !Array.isArray(y) || x.length !== y.length) {\n throw new Error('x and y must be arrays of the same length');\n }\n\n const n = x.length;\n const y2 = new Array(n);\n for (let i = 0; i < n; i++) {\n y2[i] = this._predict(x[i]);\n }\n\n let xSum = 0;\n let ySum = 0;\n let chi2 = 0;\n let rmsd = 0;\n let xSquared = 0;\n let ySquared = 0;\n let xY = 0;\n for (let i = 0; i < n; i++) {\n xSum += y2[i];\n ySum += y[i];\n xSquared += y2[i] * y2[i];\n ySquared += y[i] * y[i];\n xY += y2[i] * y[i];\n if (y[i] !== 0) {\n chi2 += (y[i] - y2[i]) * (y[i] - y2[i]) / y[i];\n }\n rmsd = (y[i] - y2[i]) * (y[i] - y2[i]);\n }\n\n const r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum));\n\n return {\n r: r,\n r2: r * r,\n chi2: chi2,\n rmsd: rmsd * rmsd / n\n };\n }\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\n\nexport default class SimpleLinearRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) {\n this.slope = y.slope;\n this.intercept = y.intercept;\n this.coefficients = [y.intercept, y.slope];\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n toJSON() {\n return {\n name: 'simpleLinearRegression',\n slope: this.slope,\n intercept: this.intercept\n };\n }\n\n _predict(x) {\n return this.slope * x + this.intercept;\n }\n\n computeX(y) {\n return (y - this.intercept) / this.slope;\n }\n\n toString(precision) {\n let result = 'f(x) = ';\n if (this.slope !== 0) {\n const xFactor = maybeToPrecision(this.slope, precision);\n result += (xFactor === '1' ? '' : xFactor + ' * ') + 'x';\n if (this.intercept) {\n const absIntercept = Math.abs(this.intercept);\n const operator = absIntercept === this.intercept ? '+' : '-';\n result += ` ${operator} ${maybeToPrecision(absIntercept, precision)}`;\n }\n } else {\n result += maybeToPrecision(this.intercept, precision);\n }\n return result;\n }\n\n toLaTeX(precision) {\n return this.toString(precision);\n }\n\n static load(json) {\n if (json.name !== 'simpleLinearRegression') {\n throw new TypeError('not a SLR model');\n }\n return new SimpleLinearRegression(true, json);\n }\n}\n\nfunction regress(slr, x, y) {\n const n = x.length;\n let xSum = 0;\n let ySum = 0;\n\n let xSquared = 0;\n let xY = 0;\n\n for (let i = 0; i < n; i++) {\n xSum += x[i];\n ySum += y[i];\n xSquared += x[i] * x[i];\n xY += x[i] * y[i];\n }\n\n const numerator = (n * xY - xSum * ySum);\n slr.slope = numerator / (n * xSquared - xSum * xSum);\n slr.intercept = (1 / n) * ySum - slr.slope * (1 / n) * xSum;\n slr.coefficients = [slr.intercept, slr.slope];\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport Matrix, {solve} from 'ml-matrix';\n\nexport default class PolynomialRegression extends BaseRegression {\n constructor(x, y, degree) {\n super();\n if (x === true) {\n this.degree = y.degree;\n this.powers = y.powers;\n this.coefficients = y.coefficients;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y, degree);\n }\n }\n\n _predict(x) {\n let y = 0;\n for (let k = 0; k < this.powers.length; k++) {\n y += this.coefficients[k] * Math.pow(x, this.powers[k]);\n }\n return y;\n }\n\n toJSON() {\n return {\n name: 'polynomialRegression',\n degree: this.degree,\n powers: this.powers,\n coefficients: this.coefficients\n };\n }\n\n toString(precision) {\n return this._toFormula(precision, false);\n }\n\n toLaTeX(precision) {\n return this._toFormula(precision, true);\n }\n\n _toFormula(precision, isLaTeX) {\n let sup = '^';\n let closeSup = '';\n let times = ' * ';\n if (isLaTeX) {\n sup = '^{';\n closeSup = '}';\n times = '';\n }\n\n let fn = '';\n let str = '';\n for (let k = 0; k < this.coefficients.length; k++) {\n str = '';\n if (this.coefficients[k] !== 0) {\n if (this.powers[k] === 0) {\n str = maybeToPrecision(this.coefficients[k], precision);\n } else {\n if (this.powers[k] === 1) {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x';\n } else {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup;\n }\n }\n\n if (this.coefficients[k] > 0 && k !== (this.coefficients.length - 1)) {\n str = ' + ' + str;\n } else if (k !== (this.coefficients.length - 1)) {\n str = ' ' + str;\n }\n }\n fn = str + fn;\n }\n if (fn.charAt(0) === '+') {\n fn = fn.slice(1);\n }\n\n return 'f(x) = ' + fn;\n }\n\n static load(json) {\n if (json.name !== 'polynomialRegression') {\n throw new TypeError('not a polynomial regression model');\n }\n return new PolynomialRegression(true, json);\n }\n}\n\nfunction regress(pr, x, y, degree) {\n const n = x.length;\n let powers;\n if (Array.isArray(degree)) {\n powers = degree;\n degree = powers.length;\n } else {\n degree++;\n powers = new Array(degree);\n for (let k = 0; k < degree; k++) {\n powers[k] = k;\n }\n }\n const F = new Matrix(n, degree);\n const Y = new Matrix([y]);\n for (let k = 0; k < degree; k++) {\n for (let i = 0; i < n; i++) {\n if (powers[k] === 0) {\n F[i][k] = 1;\n } else {\n F[i][k] = Math.pow(x[i], powers[k]);\n }\n }\n }\n\n const FT = F.transposeView();\n const A = FT.mmul(F);\n const B = FT.mmul(Y.transposeView());\n\n pr.degree = degree - 1;\n pr.powers = powers;\n pr.coefficients = solve(A, B).to1DArray();\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport SimpleLinearRegression from 'ml-regression-simple-linear';\n\nexport default class ExponentialRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) {\n this.A = y.A;\n this.B = y.B;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n _predict(input) {\n return this.B * Math.exp(input * this.A);\n }\n\n toJSON() {\n return {\n name: 'exponentialRegression',\n A: this.A,\n B: this.B\n };\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.B, precision) + ' * e^(' + maybeToPrecision(this.A, precision) + ' * x)';\n }\n\n toLaTeX(precision) {\n if (this.A >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.B, precision) + 'e^{' + maybeToPrecision(this.A, precision) + 'x}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.B, precision) + '}{e^{' + maybeToPrecision(-this.A, precision) + 'x}}';\n }\n\n }\n\n static load(json) {\n if (json.name !== 'exponentialRegression') {\n throw new TypeError('not a exponential regression model');\n }\n return new ExponentialRegression(true, json);\n }\n}\n\nfunction regress(er, x, y) {\n const n = x.length;\n const yl = new Array(n);\n for (let i = 0; i < n; i++) {\n yl[i] = Math.log(y[i]);\n }\n\n const linear = new SimpleLinearRegression(x, yl);\n er.A = linear.slope;\n er.B = Math.exp(linear.intercept);\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport SimpleLinearRegression from 'ml-regression-simple-linear';\n\nexport default class PowerRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) { // reloading model\n this.A = y.A;\n this.B = y.B;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n _predict(newInputs) {\n return this.A * Math.pow(newInputs, this.B);\n }\n\n toJSON() {\n return {\n name: 'powerRegression',\n A: this.A,\n B: this.B\n };\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + maybeToPrecision(this.B, precision);\n }\n\n toLaTeX(precision) {\n if (this.B >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + maybeToPrecision(this.B, precision) + '}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + maybeToPrecision(-this.B, precision) + '}}';\n }\n }\n\n static load(json) {\n if (json.name !== 'powerRegression') {\n throw new TypeError('not a power regression model');\n }\n return new PowerRegression(true, json);\n }\n}\n\nfunction regress(pr, x, y) {\n const n = x.length;\n const xl = new Array(n);\n const yl = new Array(n);\n for (let i = 0; i < n; i++) {\n xl[i] = Math.log(x[i]);\n yl[i] = Math.log(y[i]);\n }\n\n const linear = new SimpleLinearRegression(xl, yl);\n pr.A = Math.exp(linear.intercept);\n pr.B = linear.slope;\n}\n","import Matrix, { SVD } from 'ml-matrix';\nimport BaseRegression from 'ml-regression-base';\n\nexport default class MultivariateLinearRegression extends BaseRegression {\n constructor(x, y, options = {}) {\n const { intercept = true, statistics = true } = options;\n super();\n this.statistics = statistics;\n if (x === true) {\n this.weights = y.weights;\n this.inputs = y.inputs;\n this.outputs = y.outputs;\n this.intercept = y.intercept;\n } else {\n x = new Matrix(x);\n if (intercept) {\n x.addColumn(new Array(x.length).fill(1));\n }\n const beta = new SVD(x, { autoTranspose: true }).solve(y);\n this.weights = beta.to2DArray();\n this.inputs = x[0].length;\n this.outputs = y[0].length;\n if (intercept) this.inputs--;\n this.intercept = intercept;\n if (statistics) {\n /*\n * Let's add some basic statistics about the beta's to be able to interpret them.\n * source: http://dept.stat.lsa.umich.edu/~kshedden/Courses/Stat401/Notes/401-multreg.pdf\n * validated against Excel Regression AddIn\n * test: \"datamining statistics test\"\n */\n const fittedValues = x.mmul(beta);\n const residuals = new Matrix(y).addM(fittedValues.neg());\n const variance =\n residuals\n .to2DArray()\n .map((ri) => Math.pow(ri[0], 2))\n .reduce((a, b) => a + b) /\n (y.length - x.columns);\n this.stdError = Math.sqrt(variance);\n this.stdErrorMatrix = x\n .transposeView()\n .mmul(x)\n .pseudoInverse()\n .mul(variance);\n this.stdErrors = this.stdErrorMatrix.diagonal().map((d) => Math.sqrt(d));\n this.tStats = this.weights.map(\n (d, i) => (this.stdErrors[i] === 0 ? 0 : d[0] / this.stdErrors[i])\n );\n }\n }\n }\n\n predict(x) {\n if (Array.isArray(x)) {\n if (typeof x[0] === 'number') {\n return this._predict(x);\n } else if (Array.isArray(x[0])) {\n const y = new Array(x.length);\n for (let i = 0; i < x.length; i++) {\n y[i] = this._predict(x[i]);\n }\n return y;\n }\n }\n throw new TypeError('x must be a matrix or array of numbers');\n }\n\n _predict(x) {\n const result = new Array(this.outputs);\n if (this.intercept) {\n for (let i = 0; i < this.outputs; i++) {\n result[i] = this.weights[this.inputs][i];\n }\n } else {\n result.fill(0);\n }\n for (let i = 0; i < this.inputs; i++) {\n for (let j = 0; j < this.outputs; j++) {\n result[j] += this.weights[i][j] * x[i];\n }\n }\n return result;\n }\n\n score() {\n throw new Error('score method is not implemented yet');\n }\n\n toJSON() {\n return {\n name: 'multivariateLinearRegression',\n weights: this.weights,\n inputs: this.inputs,\n outputs: this.outputs,\n intercept: this.intercept,\n summary: (this.statistics)\n ? {\n regressionStatistics: {\n standardError: this.stdError,\n observations: this.outputs\n },\n variables: this.weights.map((d, i) => {\n return {\n label:\n i === this.weights.length - 1\n ? 'Intercept'\n : `X Variable ${i + 1}`,\n coefficients: d,\n standardError: this.stdErrors[i],\n tStat: this.tStats[i]\n };\n })\n }\n : undefined,\n };\n }\n\n static load(model) {\n if (model.name !== 'multivariateLinearRegression') {\n throw new Error('not a MLR model');\n }\n return new MultivariateLinearRegression(true, model);\n }\n}\n","import {maybeToPrecision} from 'ml-regression-base';\nimport PolynomialRegression from 'ml-regression-polynomial';\nimport BaseRegression from 'ml-regression-base';\n\n/*\n * Function that calculate the potential fit in the form f(x) = A*x^M\n * with a given M and return de A coefficient.\n *\n * @param {Vector} X - Vector of the x positions of the points.\n * @param {Vector} Y - Vector of the x positions of the points.\n * @param {Number} M - The exponent of the potential fit.\n * @return {Number} A - The A coefficient of the potential fit.\n */\nexport default class PotentialRegression extends BaseRegression {\n /**\n * @constructor\n * @param x: Independent variable\n * @param y: Dependent variable\n * @param M\n */\n constructor(x, y, M) {\n super();\n if (x === true) { // reloading model\n this.A = y.A;\n this.M = y.M;\n } else {\n var n = x.length;\n if (n !== y.length) {\n throw new RangeError('input and output array have a different length');\n }\n\n var linear = new PolynomialRegression(x, y, [M]);\n this.A = linear.coefficients[0];\n this.M = M;\n }\n }\n\n _predict(x) {\n return this.A * Math.pow(x, this.M);\n }\n\n toJSON() {\n return {\n name: 'potentialRegression',\n A: this.A,\n M: this.M\n };\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + this.M;\n }\n\n toLaTeX(precision) {\n if (this.M >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + this.M + '}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + (-this.M) + '}}';\n }\n }\n\n static load(json) {\n if (json.name !== 'potentialRegression') {\n throw new TypeError('not a potential regression model');\n }\n return new PotentialRegression(true, json);\n }\n}\n","import {Matrix, solve} from 'ml-matrix';\nimport Kernel from 'ml-kernel';\n\nimport BaseRegression from 'ml-regression-base';\n\nconst defaultOptions = {\n lambda: 0.1,\n kernelType: 'gaussian',\n kernelOptions: {},\n computeCoefficient: false\n};\n\n// Implements the Kernel ridge regression algorithm.\n// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf\nexport default class KernelRidgeRegression extends BaseRegression {\n constructor(inputs, outputs, options) {\n super();\n if (inputs === true) { // reloading model\n this.alpha = outputs.alpha;\n this.inputs = outputs.inputs;\n this.kernelType = outputs.kernelType;\n this.kernelOptions = outputs.kernelOptions;\n this.kernel = new Kernel(outputs.kernelType, outputs.kernelOptions);\n } else {\n options = Object.assign({}, defaultOptions, options);\n\n const kernelFunction = new Kernel(options.kernelType, options.kernelOptions);\n const K = kernelFunction.compute(inputs);\n const n = inputs.length;\n K.add(Matrix.eye(n, n).mul(options.lambda));\n\n this.alpha = solve(K, outputs);\n this.inputs = inputs;\n this.kernelType = options.kernelType;\n this.kernelOptions = options.kernelOptions;\n this.kernel = kernelFunction;\n }\n }\n\n _predict(newInputs) {\n return this.kernel.compute([newInputs], this.inputs).mmul(this.alpha)[0];\n }\n\n toJSON() {\n return {\n name: 'kernelRidgeRegression',\n alpha: this.alpha,\n inputs: this.inputs,\n kernelType: this.kernelType,\n kernelOptions: this.kernelOptions\n };\n }\n\n static load(json) {\n if (json.name !== 'kernelRidgeRegression') {\n throw new TypeError('not a KRR model');\n }\n return new KernelRidgeRegression(true, json);\n }\n}\n","import {Matrix, SVD} from 'ml-matrix';\nimport BaseRegression from 'ml-regression-base';\n\nconst defaultOptions = {\n order: 2\n};\n// Implements the Kernel ridge regression algorithm.\n// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf\nexport default class PolynomialFitRegression2D extends BaseRegression {\n /**\n * Constructor for the 2D polynomial fitting\n *\n * @param inputs\n * @param outputs\n * @param options\n * @constructor\n */\n constructor(inputs, outputs, options) {\n super();\n if (inputs === true) { // reloading model\n this.coefficients = Matrix.columnVector(outputs.coefficients);\n this.order = outputs.order;\n if (outputs.r) {\n this.r = outputs.r;\n this.r2 = outputs.r2;\n }\n if (outputs.chi2) {\n this.chi2 = outputs.chi2;\n }\n } else {\n options = Object.assign({}, defaultOptions, options);\n this.order = options.order;\n this.coefficients = [];\n this.X = inputs;\n this.y = outputs;\n\n this.train(this.X, this.y, options);\n }\n }\n\n /**\n * Function that fits the model given the data(X) and predictions(y).\n * The third argument is an object with the following options:\n * * order: order of the polynomial to fit.\n *\n * @param {Matrix} X - A matrix with n rows and 2 columns.\n * @param {Matrix} y - A vector of the prediction values.\n */\n train(X, y) {\n if (!Matrix.isMatrix(X)) X = new Matrix(X);\n if (!Matrix.isMatrix(y)) y = Matrix.columnVector(y);\n\n if (y.rows !== X.rows) {\n y = y.transpose();\n }\n\n if (X.columns !== 2) {\n throw new RangeError('You give X with ' + X.columns + ' columns and it must be 2');\n }\n if (X.rows !== y.rows) {\n throw new RangeError('X and y must have the same rows');\n }\n\n var examples = X.rows;\n var coefficients = ((this.order + 2) * (this.order + 1)) / 2;\n this.coefficients = new Array(coefficients);\n\n var x1 = X.getColumnVector(0);\n var x2 = X.getColumnVector(1);\n\n var scaleX1 = 1.0 / x1.clone().apply(abs).max();\n var scaleX2 = 1.0 / x2.clone().apply(abs).max();\n var scaleY = 1.0 / y.clone().apply(abs).max();\n\n x1.mulColumn(0, scaleX1);\n x2.mulColumn(0, scaleX2);\n y.mulColumn(0, scaleY);\n\n var A = new Matrix(examples, coefficients);\n var col = 0;\n\n for (var i = 0; i <= this.order; ++i) {\n var limit = this.order - i;\n for (var j = 0; j <= limit; ++j) {\n var result = powColVector(x1, i).mulColumnVector(powColVector(x2, j));\n A.setColumn(col, result);\n col++;\n }\n }\n\n var svd = new SVD(A.transpose(), {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: true,\n autoTranspose: false\n });\n\n var qqs = Matrix.rowVector(svd.diagonal);\n qqs = qqs.apply(function (i, j) {\n if (this[i][j] >= 1e-15) this[i][j] = 1 / this[i][j];\n else this[i][j] = 0;\n });\n\n var qqs1 = Matrix.zeros(examples, coefficients);\n for (i = 0; i < coefficients; ++i) {\n qqs1[i][i] = qqs[0][i];\n }\n\n qqs = qqs1;\n\n var U = svd.rightSingularVectors;\n var V = svd.leftSingularVectors;\n\n this.coefficients = V.mmul(qqs.transpose()).mmul(U.transpose()).mmul(y);\n\n col = 0;\n\n for (i = 0; i <= coefficients; ++i) {\n limit = this.order - i;\n for (j = 0; j <= limit; ++j) {\n this.coefficients[col][0] = (this.coefficients[col][0] * Math.pow(scaleX1, i) * Math.pow(scaleX2, j)) / scaleY;\n col++;\n }\n }\n }\n\n _predict(newInputs) {\n var x1 = newInputs[0];\n var x2 = newInputs[1];\n\n var y = 0;\n var column = 0;\n\n for (var i = 0; i <= this.order; i++) {\n for (var j = 0; j <= this.order - i; j++) {\n y += Math.pow(x1, i) * (Math.pow(x2, j)) * this.coefficients[column][0];\n column++;\n }\n }\n\n return y;\n }\n\n toJSON() {\n return {\n name: 'polyfit2D',\n order: this.order,\n coefficients: this.coefficients\n };\n }\n\n static load(json) {\n if (json.name !== 'polyfit2D') {\n throw new TypeError('not a polyfit2D model');\n }\n return new PolynomialFitRegression2D(true, json);\n }\n}\n\n/**\n * Function that given a column vector return this: vector^power\n *\n * @param x - Column vector.\n * @param power - Pow number.\n * @return {Suite|Matrix}\n */\nfunction powColVector(x, power) {\n var result = x.clone();\n for (var i = 0; i < x.rows; ++i) {\n result[i][0] = Math.pow(result[i][0], power);\n }\n return result;\n}\n\n/**\n * Function to use in the apply method to get the absolute value\n * of each element of the matrix\n *\n * @param i - current row.\n * @param j - current column.\n */\nfunction abs(i, j) {\n this[i][j] = Math.abs(this[i][j]);\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport {array} from 'ml-stat';\nconst median = array.median;\n\nexport default class TheilSenRegression extends BaseRegression {\n\n /**\n * Theil–Sen estimator\n * https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator\n * @param {Array|boolean} x\n * @param {Array|object} y\n * @constructor\n */\n constructor(x, y) {\n super();\n if (x === true) {\n // loads the model\n this.slope = y.slope;\n this.intercept = y.intercept;\n this.coefficients = y.coefficients;\n } else {\n // creates the model\n checkArrayLength(x, y);\n theilSen(this, x, y);\n }\n\n }\n\n toJSON() {\n return {\n name: 'TheilSenRegression',\n slope: this.slope,\n intercept: this.intercept\n };\n }\n\n _predict(input) {\n return this.slope * input + this.intercept;\n }\n\n computeX(input) {\n return (input - this.intercept) / this.slope;\n }\n\n toString(precision) {\n var result = 'f(x) = ';\n if (this.slope) {\n var xFactor = maybeToPrecision(this.slope, precision);\n result += (Math.abs(xFactor - 1) < 1e-5 ? '' : xFactor + ' * ') + 'x';\n if (this.intercept) {\n var absIntercept = Math.abs(this.intercept);\n var operator = absIntercept === this.intercept ? '+' : '-';\n result += ' ' + operator + ' ' + maybeToPrecision(absIntercept, precision);\n }\n } else {\n result += maybeToPrecision(this.intercept, precision);\n }\n return result;\n }\n\n toLaTeX(precision) {\n return this.toString(precision);\n }\n\n static load(json) {\n if (json.name !== 'TheilSenRegression') {\n throw new TypeError('not a Theil-Sen model');\n }\n return new TheilSenRegression(true, json);\n }\n}\n\nfunction theilSen(regression, x, y) {\n let len = x.length;\n let slopes = new Array(len * len);\n let count = 0;\n for (let i = 0; i < len; ++i) {\n for (let j = i + 1; j < len; ++j) {\n if (x[i] !== x[j]) {\n slopes[count++] = (y[j] - y[i]) / (x[j] - x[i]);\n }\n }\n }\n slopes.length = count;\n let medianSlope = median(slopes);\n\n let cuts = new Array(len);\n for (let i = 0; i < len; ++i) {\n cuts[i] = y[i] - medianSlope * x[i];\n }\n\n regression.slope = medianSlope;\n regression.intercept = median(cuts);\n regression.coefficients = [regression.intercept, regression.slope];\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport {solve} from 'ml-matrix';\n\nexport default class RobustPolynomialRegression extends BaseRegression {\n constructor(x, y, degree) {\n super();\n if (x === true) {\n this.degree = y.degree;\n this.powers = y.powers;\n this.coefficients = y.coefficients;\n } else {\n checkArrayLength(x, y);\n robustPolynomial(this, x, y, degree);\n }\n }\n\n toJSON() {\n return {\n name: 'robustPolynomialRegression',\n degree: this.degree,\n powers: this.powers,\n coefficients: this.coefficients\n };\n }\n\n _predict(x) {\n return predict(x, this.powers, this.coefficients);\n }\n\n toString(precision) {\n return this._toFormula(precision, false);\n }\n\n toLaTeX(precision) {\n return this._toFormula(precision, true);\n }\n\n _toFormula(precision, isLaTeX) {\n let sup = '^';\n let closeSup = '';\n let times = ' * ';\n if (isLaTeX) {\n sup = '^{';\n closeSup = '}';\n times = '';\n }\n\n let fn = '';\n let str = '';\n for (let k = 0; k < this.coefficients.length; k++) {\n str = '';\n if (this.coefficients[k] !== 0) {\n if (this.powers[k] === 0) {\n str = maybeToPrecision(this.coefficients[k], precision);\n } else {\n if (this.powers[k] === 1) {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x';\n } else {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup;\n }\n }\n\n if (this.coefficients[k] > 0 && k !== (this.coefficients.length - 1)) {\n str = ' + ' + str;\n } else if (k !== (this.coefficients.length - 1)) {\n str = ' ' + str;\n }\n }\n fn = str + fn;\n }\n if (fn.charAt(0) === '+') {\n fn = fn.slice(1);\n }\n\n return 'f(x) = ' + fn;\n }\n\n static load(json) {\n if (json.name !== 'robustPolynomialRegression') {\n throw new TypeError('not a RobustPolynomialRegression model');\n }\n return new RobustPolynomialRegression(true, json);\n }\n}\n\nfunction robustPolynomial(regression, x, y, degree) {\n let powers = new Array(degree);\n for (let k = 0; k < degree; k++) {\n powers[k] = k;\n }\n\n const tuples = getRandomTuples(x, y, degree);\n var min;\n\n for (var i = 0; i < tuples.length; i++) {\n var tuple = tuples[i];\n var coefficients = calcCoefficients(tuple, powers);\n\n var residuals = x.slice();\n for (var j = 0; j < x.length; j++) {\n residuals[j] = y[j] - predict(x[j], powers, coefficients);\n residuals[j] = {\n residual: residuals[j] * residuals[j],\n coefficients\n };\n }\n\n var median = residualsMedian(residuals);\n if (!min || median.residual < min.residual) {\n min = median;\n }\n }\n\n regression.degree = degree;\n regression.powers = powers;\n regression.coefficients = min.coefficients;\n}\n\n/**\n * @ignore\n * @param {Array} x\n * @param {Array} y\n * @param {number} degree\n * @return {Array<{x:number,y:number}>}\n */\nfunction getRandomTuples(x, y, degree) {\n var len = Math.floor(x.length / degree);\n var tuples = new Array(len);\n\n for (var i = 0; i < x.length; i++) {\n var pos = Math.floor(Math.random() * len);\n\n var counter = 0;\n while (counter < x.length) {\n if (!tuples[pos]) {\n tuples[pos] = [{\n x: x[i],\n y: y[i]\n }];\n break;\n } else if (tuples[pos].length < degree) {\n tuples[pos].push({\n x: x[i],\n y: y[i]\n });\n break;\n } else {\n counter++;\n pos = (pos + 1) % len;\n }\n }\n\n if (counter === x.length) {\n return tuples;\n }\n }\n return tuples;\n}\n\n/**\n * @ignore\n * @param {{x:number,y:number}} tuple\n * @param {Array} powers\n * @return {Array}\n */\nfunction calcCoefficients(tuple, powers) {\n var X = tuple.slice();\n var Y = tuple.slice();\n for (var i = 0; i < X.length; i++) {\n Y[i] = [tuple[i].y];\n X[i] = new Array(powers.length);\n for (var j = 0; j < powers.length; j++) {\n X[i][j] = Math.pow(tuple[i].x, powers[j]);\n }\n }\n\n return solve(X, Y).to1DArray();\n}\n\nfunction predict(x, powers, coefficients) {\n let y = 0;\n for (let k = 0; k < powers.length; k++) {\n y += coefficients[k] * Math.pow(x, powers[k]);\n }\n return y;\n}\n\nfunction residualsMedian(residuals) {\n residuals.sort((a, b) => a.residual - b.residual);\n\n var l = residuals.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return residuals[half - 1];\n } else {\n return residuals[half];\n }\n}\n","export {default as SimpleLinearRegression, default as SLR} from 'ml-regression-simple-linear';\nexport {default as PolynomialRegression} from 'ml-regression-polynomial';\nexport {default as ExponentialRegression} from 'ml-regression-exponential';\nexport {default as PowerRegression} from 'ml-regression-power';\nexport {default as MultivariateLinearRegression} from 'ml-regression-multivariate-linear';\n\nimport PotentialRegression from './regression/potential-regression';\nconst NLR = {\n PotentialRegression\n};\nexport {NLR, NLR as NonLinearRegression};\n\nexport {default as KernelRidgeRegression, default as KRR} from './regression/kernel-ridge-regression';\nexport {default as PolinomialFitting2D} from './regression/poly-fit-regression2d';\n\n// robust regressions\nexport {default as TheilSenRegression} from 'ml-regression-theil-sen';\nexport {default as RobustPolynomialRegression} from 'ml-regression-robust-polynomial';\n","(function(){function a(d){for(var e=0,f=d.length-1,g=void 0,h=void 0,i=void 0,j=c(e,f);!0;){if(f<=e)return d[j];if(f==e+1)return d[e]>d[f]&&b(d,e,f),d[j];for(g=c(e,f),d[g]>d[f]&&b(d,g,f),d[e]>d[f]&&b(d,e,f),d[g]>d[e]&&b(d,g,e),b(d,g,e+1),h=e+1,i=f;!0;){do h++;while(d[e]>d[h]);do i--;while(d[i]>d[e]);if(i=j&&(f=i-1)}}var b=function b(d,e,f){var _ref;return _ref=[d[f],d[e]],d[e]=_ref[0],d[f]=_ref[1],_ref},c=function c(d,e){return~~((d+e)/2)};'undefined'!=typeof module&&module.exports?module.exports=a:window.median=a})();\n","'use strict';\n\nconst mlCart = require('ml-cart');\nconst mlRandomForest = require('ml-random-forest');\n\nconst ML = exports;\n\n// Try to keep this list in the same structure as the README.\n\n// Unsupervised learning\nML.PCA = require('ml-pca');\nML.HClust = require('ml-hclust');\nML.KMeans = require('ml-kmeans');\n\n// Supervised learning\nML.SVM = require('ml-svm');\nML.NaiveBayes = require('ml-naivebayes');\nML.KNN = require('ml-knn');\nML.PLS = require('ml-pls');\nML.CrossValidation = require('ml-cross-validation');\nML.ConfusionMatrix = require('ml-confusion-matrix');\nML.DecisionTreeClassifier = mlCart.DecisionTreeClassifier;\nML.RandomForestClassifier = mlRandomForest.RandomForestClassifier;\n\n// Artificial neural networks\nML.FNN = require('ml-fnn');\nML.SOM = require('ml-som');\n\n// Regression\nconst Regression = require('ml-regression');\nML.SimpleLinearRegression = Regression.SimpleLinearRegression;\nML.PolynomialRegression = Regression.PolynomialRegression;\nML.MultivariateLinearRegression = Regression.MultivariateLinearRegression;\nML.PowerRegression = Regression.PowerRegression;\nML.ExponentialRegression = Regression.ExponentialRegression;\nML.TheilSenRegression = Regression.TheilSenRegression;\nML.RobustPolynomialRegression = Regression.RobustPolynomialRegression;\nML.DecisionTreeRegression = mlCart.DecisionTreeRegression;\nML.RandomForestRegression = mlRandomForest.RandomForestRegression;\n\n// Optimization\nML.levenbergMarquardt = require('ml-levenberg-marquardt');\n\n// Math\nconst Matrix = require('ml-matrix');\nML.Matrix = Matrix.Matrix;\nML.SVD = Matrix.SVD;\nML.EVD = Matrix.EVD;\nML.CholeskyDecomposition = Matrix.CholeskyDecomposition;\nML.LuDecomposition = Matrix.LuDecomposition;\nML.QrDecomposition = Matrix.QrDecomposition;\n\nML.SparseMatrix = require('ml-sparse-matrix');\nML.Kernel = require('ml-kernel');\nML.Distance = require('ml-distance').distance;\nML.Similarity = require('ml-distance').similarity;\nML.distanceMatrix = require('ml-distance-matrix');\nML.XSadd = require('ml-xsadd').default;\n\n// Statistics\nML.Performance = require('ml-performance');\n\n// Data preprocessing\nML.savitzkyGolay = require('ml-savitzky-golay');\nML.savitzkyGolayGeneralized = require('ml-savitzky-golay-generalized');\n\n// Utility\nML.BitArray = require('ml-bit-array');\nML.HashTable = require('ml-hash-table');\nML.padArray = require('ml-pad-array');\nML.binarySearch = require('binary-search');\nML.numSort = require('num-sort');\nML.Random = require('ml-random').default;\n\n// Undocumented/deprecated packages\nML.ArrayUtils = require('ml-array-utils');\nML.Regression = require('ml-regression');\nML.MatrixUtil = require('ml-matrix');\nML.ArrayStat = require('ml-stat').array;\nML.MatrixStat = require('ml-stat').matrix;\n\nML.Array = {\n min: require('ml-array-min').default,\n max: require('ml-array-max').default,\n median: require('ml-array-median').default,\n mean: require('ml-array-mean').default,\n mode: require('ml-array-mode').default,\n normed: require('ml-array-normed').default,\n rescale: require('ml-array-rescale').default,\n sequentialFill: require('ml-array-sequential-fill').default,\n standardDeviation: require('ml-array-standard-deviation').default,\n variance: require('ml-array-variance').default\n};\n\nML.ArrayXY = {\n centroidsMerge: require('ml-array-xy-centroids-merge').default,\n closestX: require('ml-arrayxy-closestx').default,\n maxMerge: require('ml-array-xy-max-merge').default,\n maxY: require('ml-array-xy-max-y').default,\n sortX: require('ml-array-xy-sort-x').default,\n uniqueX: require('ml-arrayxy-uniquex').default,\n weightedMerge: require('ml-array-xy-weighted-merge').default\n};\n","'use strict';\n\nconst matrixLib = require('ml-matrix');\nconst Matrix = matrixLib.Matrix;\nconst EVD = matrixLib.EVD;\nconst SVD = matrixLib.SVD;\nconst Stat = require('ml-stat/matrix');\nconst mean = Stat.mean;\nconst stdev = Stat.standardDeviation;\n\nconst defaultOptions = {\n isCovarianceMatrix: false,\n center: true,\n scale: false\n};\n\n/**\n * Creates new PCA (Principal Component Analysis) from the dataset\n * @param {Matrix} dataset - dataset or covariance matrix\n * @param {Object} options\n * @param {boolean} [options.isCovarianceMatrix=false] - true if the dataset is a covariance matrix\n * @param {boolean} [options.center=true] - should the data be centered (subtract the mean)\n * @param {boolean} [options.scale=false] - should the data be scaled (divide by the standard deviation)\n * */\nclass PCA {\n constructor(dataset, options) {\n if (dataset === true) {\n const model = options;\n this.center = model.center;\n this.scale = model.scale;\n this.means = model.means;\n this.stdevs = model.stdevs;\n this.U = Matrix.checkMatrix(model.U);\n this.S = model.S;\n return;\n }\n\n options = Object.assign({}, defaultOptions, options);\n\n this.center = false;\n this.scale = false;\n this.means = null;\n this.stdevs = null;\n\n if (options.isCovarianceMatrix) { // user provided a covariance matrix instead of dataset\n this._computeFromCovarianceMatrix(dataset);\n return;\n }\n\n var useCovarianceMatrix;\n if (typeof options.useCovarianceMatrix === 'boolean') {\n useCovarianceMatrix = options.useCovarianceMatrix;\n } else {\n useCovarianceMatrix = dataset.length > dataset[0].length;\n }\n\n if (useCovarianceMatrix) { // user provided a dataset but wants us to compute and use the covariance matrix\n dataset = this._adjust(dataset, options);\n const covarianceMatrix = dataset.transposeView().mmul(dataset).div(dataset.rows - 1);\n this._computeFromCovarianceMatrix(covarianceMatrix);\n } else {\n dataset = this._adjust(dataset, options);\n var svd = new SVD(dataset, {\n computeLeftSingularVectors: false,\n computeRightSingularVectors: true,\n autoTranspose: true\n });\n\n this.U = svd.rightSingularVectors;\n\n const singularValues = svd.diagonal;\n const eigenvalues = new Array(singularValues.length);\n for (var i = 0; i < singularValues.length; i++) {\n eigenvalues[i] = singularValues[i] * singularValues[i] / (dataset.length - 1);\n }\n this.S = eigenvalues;\n }\n }\n\n /**\n * Load a PCA model from JSON\n * @param {Object} model\n * @return {PCA}\n */\n static load(model) {\n if (model.name !== 'PCA')\n throw new RangeError('Invalid model: ' + model.name);\n return new PCA(true, model);\n }\n\n\n /**\n * Project the dataset into the PCA space\n * @param {Matrix} dataset\n * @param {Object} options\n * @return {Matrix} dataset projected in the PCA space\n */\n predict(dataset, options = {}) {\n const {\n nComponents = this.U.columns\n } = options;\n\n dataset = new Matrix(dataset);\n if (this.center) {\n dataset.subRowVector(this.means);\n if (this.scale) {\n dataset.divRowVector(this.stdevs);\n }\n }\n\n var predictions = dataset.mmul(this.U);\n return predictions.subMatrix(0, predictions.rows - 1, 0, nComponents - 1);\n }\n\n /**\n * Returns the proportion of variance for each component\n * @return {[number]}\n */\n getExplainedVariance() {\n var sum = 0;\n for (var i = 0; i < this.S.length; i++) {\n sum += this.S[i];\n }\n return this.S.map(value => value / sum);\n }\n\n /**\n * Returns the cumulative proportion of variance\n * @return {[number]}\n */\n getCumulativeVariance() {\n var explained = this.getExplainedVariance();\n for (var i = 1; i < explained.length; i++) {\n explained[i] += explained[i - 1];\n }\n return explained;\n }\n\n /**\n * Returns the Eigenvectors of the covariance matrix\n * @returns {Matrix}\n */\n getEigenvectors() {\n return this.U;\n }\n\n /**\n * Returns the Eigenvalues (on the diagonal)\n * @returns {[number]}\n */\n getEigenvalues() {\n return this.S;\n }\n\n /**\n * Returns the standard deviations of the principal components\n * @returns {[number]}\n */\n getStandardDeviations() {\n return this.S.map(x => Math.sqrt(x));\n }\n\n /**\n * Returns the loadings matrix\n * @return {Matrix}\n */\n getLoadings() {\n return this.U.transpose();\n }\n\n /**\n * Export the current model to a JSON object\n * @return {Object} model\n */\n toJSON() {\n return {\n name: 'PCA',\n center: this.center,\n scale: this.scale,\n means: this.means,\n stdevs: this.stdevs,\n U: this.U,\n S: this.S,\n };\n }\n\n _adjust(dataset, options) {\n this.center = !!options.center;\n this.scale = !!options.scale;\n\n dataset = new Matrix(dataset);\n\n if (this.center) {\n const means = mean(dataset);\n const stdevs = this.scale ? stdev(dataset, means, true) : null;\n this.means = means;\n dataset.subRowVector(means);\n if (this.scale) {\n for (var i = 0; i < stdevs.length; i++) {\n if (stdevs[i] === 0) {\n throw new RangeError('Cannot scale the dataset (standard deviation is zero at index ' + i);\n }\n }\n this.stdevs = stdevs;\n dataset.divRowVector(stdevs);\n }\n }\n\n return dataset;\n }\n\n _computeFromCovarianceMatrix(dataset) {\n const evd = new EVD(dataset, {assumeSymmetric: true});\n this.U = evd.eigenvectorMatrix;\n for (var i = 0; i < this.U.length; i++) {\n this.U[i].reverse();\n }\n this.S = evd.realEigenvalues.reverse();\n }\n}\n\nmodule.exports = PCA;\n","'use strict';\n\nexports.agnes = require('./agnes');\nexports.diana = require('./diana');\n//exports.birch = require('./birch');\n//exports.cure = require('./cure');\n//exports.chameleon = require('./chameleon');\n","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\nconst ClusterLeaf = require('./ClusterLeaf');\nconst Cluster = require('./Cluster');\nconst distanceMatrix = require('ml-distance-matrix');\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction simpleLink(cluster1, cluster2, disFun) {\n var m = 10e100;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n var d = disFun[cluster1[i]][ cluster2[j]];\n m = Math.min(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction completeLink(cluster1, cluster2, disFun) {\n var m = -1;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n var d = disFun[cluster1[i]][ cluster2[j]];\n m = Math.max(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction averageLink(cluster1, cluster2, disFun) {\n var m = 0;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n m += disFun[cluster1[i]][ cluster2[j]];\n }\n }\n return m / (cluster1.length * cluster2.length);\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {*}\n */\nfunction centroidLink(cluster1, cluster2, disFun) {\n var dist = new Array(cluster1.length * cluster2.length);\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n dist[i * cluster2.length + j] = (disFun[cluster1[i]][ cluster2[j]]);\n }\n }\n return median(dist);\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction wardLink(cluster1, cluster2, disFun) {\n return centroidLink(cluster1, cluster2, disFun)\n * cluster1.length * cluster2.length / (cluster1.length + cluster2.length);\n}\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nfunction median(values, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return (values[half - 1] + values[half]) * 0.5;\n } else {\n return values[half];\n }\n}\n\nvar defaultOptions = {\n disFunc: euclidean,\n kind: 'single',\n isDistanceMatrix: false\n\n};\n\n/**\n * Continuously merge nodes that have the least dissimilarity\n * @param {Array >} distance - Array of points to be clustered\n * @param {json} options\n * @option isDistanceMatrix: Is the input a distance matrix?\n * @constructor\n */\nfunction agnes(data, options) {\n options = Object.assign({}, defaultOptions, options);\n var len = data.length;\n var distance = data;//If source\n if (!options.isDistanceMatrix) {\n distance = distanceMatrix(data, options.disFunc);\n }\n\n\n // allows to use a string or a given function\n if (typeof options.kind === 'string') {\n switch (options.kind) {\n case 'single':\n options.kind = simpleLink;\n break;\n case 'complete':\n options.kind = completeLink;\n break;\n case 'average':\n options.kind = averageLink;\n break;\n case 'centroid':\n options.kind = centroidLink;\n break;\n case 'ward':\n options.kind = wardLink;\n break;\n default:\n throw new RangeError('Unknown kind of similarity');\n }\n } else if (typeof options.kind !== 'function') {\n throw new TypeError('Undefined kind of similarity');\n }\n\n var list = new Array(len);\n for (var i = 0; i < distance.length; i++) {\n list[i] = new ClusterLeaf(i);\n }\n var min = 10e5,\n d = {},\n dis = 0;\n\n while (list.length > 1) {\n // calculates the minimum distance\n d = {};\n min = 10e5;\n for (var j = 0; j < list.length; j++) {\n for (var k = j + 1; k < list.length; k++) {\n var fdistance, sdistance;\n if (list[j] instanceof ClusterLeaf) {\n fdistance = [list[j].index];\n } else {\n fdistance = new Array(list[j].index.length);\n for (var e = 0; e < fdistance.length; e++) {\n fdistance[e] = list[j].index[e].index;\n }\n }\n if (list[k] instanceof ClusterLeaf) {\n sdistance = [list[k].index];\n } else {\n sdistance = new Array(list[k].index.length);\n for (var f = 0; f < sdistance.length; f++) {\n sdistance[f] = list[k].index[f].index;\n }\n }\n dis = options.kind(fdistance, sdistance, distance).toFixed(4);\n if (dis in d) {\n d[dis].push([list[j], list[k]]);\n } else {\n d[dis] = [[list[j], list[k]]];\n }\n min = Math.min(dis, min);\n }\n }\n // cluster dots\n var dmin = d[min.toFixed(4)];\n var clustered = new Array(dmin.length);\n var aux,\n count = 0;\n while (dmin.length > 0) {\n aux = dmin.shift();\n for (var q = 0; q < dmin.length; q++) {\n var int = dmin[q].filter(function (n) {\n //noinspection JSReferencingMutableVariableFromClosure\n return aux.indexOf(n) !== -1;\n });\n if (int.length > 0) {\n var diff = dmin[q].filter(function (n) {\n //noinspection JSReferencingMutableVariableFromClosure\n return aux.indexOf(n) === -1;\n });\n aux = aux.concat(diff);\n dmin.splice(q--, 1);\n }\n }\n clustered[count++] = aux;\n }\n clustered.length = count;\n\n for (var ii = 0; ii < clustered.length; ii++) {\n var obj = new Cluster();\n obj.children = clustered[ii].concat();\n obj.distance = min;\n obj.index = new Array(len);\n var indCount = 0;\n for (var jj = 0; jj < clustered[ii].length; jj++) {\n if (clustered[ii][jj] instanceof ClusterLeaf) {\n obj.index[indCount++] = clustered[ii][jj];\n } else {\n indCount += clustered[ii][jj].index.length;\n obj.index = clustered[ii][jj].index.concat(obj.index);\n }\n list.splice((list.indexOf(clustered[ii][jj])), 1);\n }\n obj.index.length = indCount;\n list.push(obj);\n }\n }\n return list[0];\n}\n\nmodule.exports = agnes;\n","module.exports = require('./lib/heap');\n","// Generated by CoffeeScript 1.8.0\n(function() {\n var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;\n\n floor = Math.floor, min = Math.min;\n\n\n /*\n Default comparison function to be used\n */\n\n defaultCmp = function(x, y) {\n if (x < y) {\n return -1;\n }\n if (x > y) {\n return 1;\n }\n return 0;\n };\n\n\n /*\n Insert item x in list a, and keep it sorted assuming a is sorted.\n \n If x is already in a, insert it to the right of the rightmost x.\n \n Optional args lo (default 0) and hi (default a.length) bound the slice\n of a to be searched.\n */\n\n insort = function(a, x, lo, hi, cmp) {\n var mid;\n if (lo == null) {\n lo = 0;\n }\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (lo < 0) {\n throw new Error('lo must be non-negative');\n }\n if (hi == null) {\n hi = a.length;\n }\n while (lo < hi) {\n mid = floor((lo + hi) / 2);\n if (cmp(x, a[mid]) < 0) {\n hi = mid;\n } else {\n lo = mid + 1;\n }\n }\n return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);\n };\n\n\n /*\n Push item onto heap, maintaining the heap invariant.\n */\n\n heappush = function(array, item, cmp) {\n if (cmp == null) {\n cmp = defaultCmp;\n }\n array.push(item);\n return _siftdown(array, 0, array.length - 1, cmp);\n };\n\n\n /*\n Pop the smallest item off the heap, maintaining the heap invariant.\n */\n\n heappop = function(array, cmp) {\n var lastelt, returnitem;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n lastelt = array.pop();\n if (array.length) {\n returnitem = array[0];\n array[0] = lastelt;\n _siftup(array, 0, cmp);\n } else {\n returnitem = lastelt;\n }\n return returnitem;\n };\n\n\n /*\n Pop and return the current smallest value, and add the new item.\n \n This is more efficient than heappop() followed by heappush(), and can be\n more appropriate when using a fixed size heap. Note that the value\n returned may be larger than item! That constrains reasonable use of\n this routine unless written as part of a conditional replacement:\n if item > array[0]\n item = heapreplace(array, item)\n */\n\n heapreplace = function(array, item, cmp) {\n var returnitem;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n returnitem = array[0];\n array[0] = item;\n _siftup(array, 0, cmp);\n return returnitem;\n };\n\n\n /*\n Fast version of a heappush followed by a heappop.\n */\n\n heappushpop = function(array, item, cmp) {\n var _ref;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (array.length && cmp(array[0], item) < 0) {\n _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];\n _siftup(array, 0, cmp);\n }\n return item;\n };\n\n\n /*\n Transform list into a heap, in-place, in O(array.length) time.\n */\n\n heapify = function(array, cmp) {\n var i, _i, _j, _len, _ref, _ref1, _results, _results1;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n _ref1 = (function() {\n _results1 = [];\n for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }\n return _results1;\n }).apply(this).reverse();\n _results = [];\n for (_i = 0, _len = _ref1.length; _i < _len; _i++) {\n i = _ref1[_i];\n _results.push(_siftup(array, i, cmp));\n }\n return _results;\n };\n\n\n /*\n Update the position of the given item in the heap.\n This function should be called every time the item is being modified.\n */\n\n updateItem = function(array, item, cmp) {\n var pos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n pos = array.indexOf(item);\n if (pos === -1) {\n return;\n }\n _siftdown(array, 0, pos, cmp);\n return _siftup(array, pos, cmp);\n };\n\n\n /*\n Find the n largest elements in a dataset.\n */\n\n nlargest = function(array, n, cmp) {\n var elem, result, _i, _len, _ref;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n result = array.slice(0, n);\n if (!result.length) {\n return result;\n }\n heapify(result, cmp);\n _ref = array.slice(n);\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n heappushpop(result, elem, cmp);\n }\n return result.sort(cmp).reverse();\n };\n\n\n /*\n Find the n smallest elements in a dataset.\n */\n\n nsmallest = function(array, n, cmp) {\n var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (n * 10 <= array.length) {\n result = array.slice(0, n).sort(cmp);\n if (!result.length) {\n return result;\n }\n los = result[result.length - 1];\n _ref = array.slice(n);\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n if (cmp(elem, los) < 0) {\n insort(result, elem, 0, null, cmp);\n result.pop();\n los = result[result.length - 1];\n }\n }\n return result;\n }\n heapify(array, cmp);\n _results = [];\n for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) {\n _results.push(heappop(array, cmp));\n }\n return _results;\n };\n\n _siftdown = function(array, startpos, pos, cmp) {\n var newitem, parent, parentpos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n newitem = array[pos];\n while (pos > startpos) {\n parentpos = (pos - 1) >> 1;\n parent = array[parentpos];\n if (cmp(newitem, parent) < 0) {\n array[pos] = parent;\n pos = parentpos;\n continue;\n }\n break;\n }\n return array[pos] = newitem;\n };\n\n _siftup = function(array, pos, cmp) {\n var childpos, endpos, newitem, rightpos, startpos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n endpos = array.length;\n startpos = pos;\n newitem = array[pos];\n childpos = 2 * pos + 1;\n while (childpos < endpos) {\n rightpos = childpos + 1;\n if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {\n childpos = rightpos;\n }\n array[pos] = array[childpos];\n pos = childpos;\n childpos = 2 * pos + 1;\n }\n array[pos] = newitem;\n return _siftdown(array, startpos, pos, cmp);\n };\n\n Heap = (function() {\n Heap.push = heappush;\n\n Heap.pop = heappop;\n\n Heap.replace = heapreplace;\n\n Heap.pushpop = heappushpop;\n\n Heap.heapify = heapify;\n\n Heap.updateItem = updateItem;\n\n Heap.nlargest = nlargest;\n\n Heap.nsmallest = nsmallest;\n\n function Heap(cmp) {\n this.cmp = cmp != null ? cmp : defaultCmp;\n this.nodes = [];\n }\n\n Heap.prototype.push = function(x) {\n return heappush(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.pop = function() {\n return heappop(this.nodes, this.cmp);\n };\n\n Heap.prototype.peek = function() {\n return this.nodes[0];\n };\n\n Heap.prototype.contains = function(x) {\n return this.nodes.indexOf(x) !== -1;\n };\n\n Heap.prototype.replace = function(x) {\n return heapreplace(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.pushpop = function(x) {\n return heappushpop(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.heapify = function() {\n return heapify(this.nodes, this.cmp);\n };\n\n Heap.prototype.updateItem = function(x) {\n return updateItem(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.clear = function() {\n return this.nodes = [];\n };\n\n Heap.prototype.empty = function() {\n return this.nodes.length === 0;\n };\n\n Heap.prototype.size = function() {\n return this.nodes.length;\n };\n\n Heap.prototype.clone = function() {\n var heap;\n heap = new Heap();\n heap.nodes = this.nodes.slice(0);\n return heap;\n };\n\n Heap.prototype.toArray = function() {\n return this.nodes.slice(0);\n };\n\n Heap.prototype.insert = Heap.prototype.push;\n\n Heap.prototype.top = Heap.prototype.peek;\n\n Heap.prototype.front = Heap.prototype.peek;\n\n Heap.prototype.has = Heap.prototype.contains;\n\n Heap.prototype.copy = Heap.prototype.clone;\n\n return Heap;\n\n })();\n\n (function(root, factory) {\n if (typeof define === 'function' && define.amd) {\n return define([], factory);\n } else if (typeof exports === 'object') {\n return module.exports = factory();\n } else {\n return root.Heap = factory();\n }\n })(this, function() {\n return Heap;\n });\n\n}).call(this);\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||\n function getOwnPropertyDescriptors(obj) {\n var keys = Object.keys(obj);\n var descriptors = {};\n for (var i = 0; i < keys.length; i++) {\n descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);\n }\n return descriptors;\n };\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n if (!isString(f)) {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j':\n try {\n return JSON.stringify(args[i++]);\n } catch (_) {\n return '[Circular]';\n }\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (isNull(x) || !isObject(x)) {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexports.deprecate = function(fn, msg) {\n if (typeof process !== 'undefined' && process.noDeprecation === true) {\n return fn;\n }\n\n // Allow for deprecating things in the process of starting up.\n if (typeof process === 'undefined') {\n return function() {\n return exports.deprecate(fn, msg).apply(this, arguments);\n };\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnviron;\nexports.debuglog = function(set) {\n if (isUndefined(debugEnviron))\n debugEnviron = process.env.NODE_DEBUG || '';\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (new RegExp('\\\\b' + set + '\\\\b', 'i').test(debugEnviron)) {\n var pid = process.pid;\n debugs[set] = function() {\n var msg = exports.format.apply(exports, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nfunction inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (isBoolean(opts)) {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n exports._extend(ctx, opts);\n }\n // set default options\n if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n if (isUndefined(ctx.depth)) ctx.depth = 2;\n if (isUndefined(ctx.colors)) ctx.colors = false;\n if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\nexports.inspect = inspect;\n\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect &&\n value &&\n isFunction(value.inspect) &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== exports.inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n var ret = value.inspect(recurseTimes, ctx);\n if (!isString(ret)) {\n ret = formatValue(ctx, ret, recurseTimes);\n }\n return ret;\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // IE doesn't make error fields non-enumerable\n // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n if (isError(value)\n && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n return formatError(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (isFunction(value)) {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (isFunction(value)) {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n if (isUndefined(value))\n return ctx.stylize('undefined', 'undefined');\n if (isString(value)) {\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n }\n if (isNumber(value))\n return ctx.stylize('' + value, 'number');\n if (isBoolean(value))\n return ctx.stylize('' + value, 'boolean');\n // For some reason typeof null is \"object\", so special case here.\n if (isNull(value))\n return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (isNull(recurseTimes)) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (isUndefined(name)) {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nfunction isArray(ar) {\n return Array.isArray(ar);\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return isObject(re) && objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return isObject(d) && objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return isObject(e) &&\n (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('./support/isBuffer');\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexports.log = function() {\n console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexports.inherits = require('inherits');\n\nexports._extend = function(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || !isObject(add)) return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nvar kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;\n\nexports.promisify = function promisify(original) {\n if (typeof original !== 'function')\n throw new TypeError('The \"original\" argument must be of type Function');\n\n if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {\n var fn = original[kCustomPromisifiedSymbol];\n if (typeof fn !== 'function') {\n throw new TypeError('The \"util.promisify.custom\" argument must be of type Function');\n }\n Object.defineProperty(fn, kCustomPromisifiedSymbol, {\n value: fn, enumerable: false, writable: false, configurable: true\n });\n return fn;\n }\n\n function fn() {\n var promiseResolve, promiseReject;\n var promise = new Promise(function (resolve, reject) {\n promiseResolve = resolve;\n promiseReject = reject;\n });\n\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n args.push(function (err, value) {\n if (err) {\n promiseReject(err);\n } else {\n promiseResolve(value);\n }\n });\n\n try {\n original.apply(this, args);\n } catch (err) {\n promiseReject(err);\n }\n\n return promise;\n }\n\n Object.setPrototypeOf(fn, Object.getPrototypeOf(original));\n\n if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {\n value: fn, enumerable: false, writable: false, configurable: true\n });\n return Object.defineProperties(\n fn,\n getOwnPropertyDescriptors(original)\n );\n}\n\nexports.promisify.custom = kCustomPromisifiedSymbol\n\nfunction callbackifyOnRejected(reason, cb) {\n // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).\n // Because `null` is a special error value in callbacks which means \"no error\n // occurred\", we error-wrap so the callback consumer can distinguish between\n // \"the promise rejected with null\" or \"the promise fulfilled with undefined\".\n if (!reason) {\n var newReason = new Error('Promise was rejected with a falsy value');\n newReason.reason = reason;\n reason = newReason;\n }\n return cb(reason);\n}\n\nfunction callbackify(original) {\n if (typeof original !== 'function') {\n throw new TypeError('The \"original\" argument must be of type Function');\n }\n\n // We DO NOT return the promise as it gives the user a false sense that\n // the promise is actually somehow related to the callback's execution\n // and that the callback throwing will reject the promise.\n function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }\n\n Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));\n Object.defineProperties(callbackified,\n getOwnPropertyDescriptors(original));\n return callbackified;\n}\nexports.callbackify = callbackify;\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","module.exports = function isBuffer(arg) {\n return arg && typeof arg === 'object'\n && typeof arg.copy === 'function'\n && typeof arg.fill === 'function'\n && typeof arg.readUInt8 === 'function';\n}","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\nconst ClusterLeaf = require('./ClusterLeaf');\nconst Cluster = require('./Cluster');\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction simpleLink(cluster1, cluster2, disFun) {\n var m = 10e100;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = i; j < cluster2.length; j++) {\n var d = disFun(cluster1[i], cluster2[j]);\n m = Math.min(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction completeLink(cluster1, cluster2, disFun) {\n var m = -1;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = i; j < cluster2.length; j++) {\n var d = disFun(cluster1[i], cluster2[j]);\n m = Math.max(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction averageLink(cluster1, cluster2, disFun) {\n var m = 0;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n m += disFun(cluster1[i], cluster2[j]);\n }\n }\n return m / (cluster1.length * cluster2.length);\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction centroidLink(cluster1, cluster2, disFun) {\n var x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0;\n for (var i = 0; i < cluster1.length; i++) {\n x1 += cluster1[i][0];\n y1 += cluster1[i][1];\n }\n for (var j = 0; j < cluster2.length; j++) {\n x2 += cluster2[j][0];\n y2 += cluster2[j][1];\n }\n x1 /= cluster1.length;\n y1 /= cluster1.length;\n x2 /= cluster2.length;\n y2 /= cluster2.length;\n return disFun([x1, y1], [x2, y2]);\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction wardLink(cluster1, cluster2, disFun) {\n var x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0;\n for (var i = 0; i < cluster1.length; i++) {\n x1 += cluster1[i][0];\n y1 += cluster1[i][1];\n }\n for (var j = 0; j < cluster2.length; j++) {\n x2 += cluster2[j][0];\n y2 += cluster2[j][1];\n }\n x1 /= cluster1.length;\n y1 /= cluster1.length;\n x2 /= cluster2.length;\n y2 /= cluster2.length;\n return disFun([x1, y1], [x2, y2]) * cluster1.length * cluster2.length / (cluster1.length + cluster2.length);\n}\n\n/**\n * @private\n * Returns the most distant point and his distance\n * @param {Array >} splitting - Clusters to split\n * @param {Array >} data - Original data\n * @param {function} disFun - Distance function\n * @returns {{d: number, p: number}} - d: maximum difference between points, p: the point more distant\n */\nfunction diff(splitting, data, disFun) {\n var ans = {\n d: 0,\n p: 0\n };\n\n var Ci = new Array(splitting[0].length);\n for (var e = 0; e < splitting[0].length; e++) {\n Ci[e] = data[splitting[0][e]];\n }\n var Cj = new Array(splitting[1].length);\n for (var f = 0; f < splitting[1].length; f++) {\n Cj[f] = data[splitting[1][f]];\n }\n\n var dist, ndist;\n for (var i = 0; i < Ci.length; i++) {\n dist = 0;\n for (var j = 0; j < Ci.length; j++) {\n if (i !== j) {\n dist += disFun(Ci[i], Ci[j]);\n }\n }\n dist /= (Ci.length - 1);\n ndist = 0;\n for (var k = 0; k < Cj.length; k++) {\n ndist += disFun(Ci[i], Cj[k]);\n }\n ndist /= Cj.length;\n if ((dist - ndist) > ans.d) {\n ans.d = (dist - ndist);\n ans.p = i;\n }\n }\n return ans;\n}\n\nvar defaultOptions = {\n dist: euclidean,\n kind: 'single'\n};\n\n/**\n * @private\n * Intra-cluster distance\n * @param {Array} index\n * @param {Array} data\n * @param {function} disFun\n * @returns {number}\n */\nfunction intrDist(index, data, disFun) {\n var dist = 0,\n count = 0;\n for (var i = 0; i < index.length; i++) {\n for (var j = i; j < index.length; j++) {\n dist += disFun(data[index[i].index], data[index[j].index]);\n count++;\n }\n }\n return dist / count;\n}\n\n/**\n * Splits the higher level clusters\n * @param {Array >} data - Array of points to be clustered\n * @param {json} options\n * @constructor\n */\nfunction diana(data, options) {\n options = Object.assign({}, defaultOptions, options);\n if (typeof options.kind === 'string') {\n switch (options.kind) {\n case 'single':\n options.kind = simpleLink;\n break;\n case 'complete':\n options.kind = completeLink;\n break;\n case 'average':\n options.kind = averageLink;\n break;\n case 'centroid':\n options.kind = centroidLink;\n break;\n case 'ward':\n options.kind = wardLink;\n break;\n default:\n throw new RangeError('Unknown kind of similarity');\n }\n } else if (typeof options.kind !== 'function') {\n throw new TypeError('Undefined kind of similarity');\n }\n var tree = new Cluster();\n tree.children = new Array(data.length);\n tree.index = new Array(data.length);\n for (var ind = 0; ind < data.length; ind++) {\n tree.children[ind] = new ClusterLeaf(ind);\n tree.index[ind] = new ClusterLeaf(ind);\n }\n\n tree.distance = intrDist(tree.index, data, options.dist);\n var m, M, clId,\n dist, rebel;\n var list = [tree];\n while (list.length > 0) {\n M = 0;\n clId = 0;\n for (var i = 0; i < list.length; i++) {\n m = 0;\n for (var j = 0; j < list[i].length; j++) {\n for (var l = (j + 1); l < list[i].length; l++) {\n m = Math.max(options.dist(data[list[i].index[j].index], data[list[i].index[l].index]), m);\n }\n }\n if (m > M) {\n M = m;\n clId = i;\n }\n }\n M = 0;\n if (list[clId].index.length === 2) {\n list[clId].children = [list[clId].index[0], list[clId].index[1]];\n list[clId].distance = options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]);\n } else if (list[clId].index.length === 3) {\n list[clId].children = [list[clId].index[0], list[clId].index[1], list[clId].index[2]];\n var d = [\n options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]),\n options.dist(data[list[clId].index[1].index], data[list[clId].index[2].index])\n ];\n list[clId].distance = (d[0] + d[1]) / 2;\n } else {\n var C = new Cluster();\n var sG = new Cluster();\n var splitting = [new Array(list[clId].index.length), []];\n for (var spl = 0; spl < splitting[0].length; spl++) {\n splitting[0][spl] = spl;\n }\n for (var ii = 0; ii < splitting[0].length; ii++) {\n dist = 0;\n for (var jj = 0; jj < splitting[0].length; jj++) {\n if (ii !== jj) {\n dist += options.dist(data[list[clId].index[splitting[0][jj]].index], data[list[clId].index[splitting[0][ii]].index]);\n }\n }\n dist /= (splitting[0].length - 1);\n if (dist > M) {\n M = dist;\n rebel = ii;\n }\n }\n splitting[1] = [rebel];\n splitting[0].splice(rebel, 1);\n dist = diff(splitting, data, options.dist);\n while (dist.d > 0) {\n splitting[1].push(splitting[0][dist.p]);\n splitting[0].splice(dist.p, 1);\n dist = diff(splitting, data, options.dist);\n }\n var fData = new Array(splitting[0].length);\n C.index = new Array(splitting[0].length);\n for (var e = 0; e < fData.length; e++) {\n fData[e] = data[list[clId].index[splitting[0][e]].index];\n C.index[e] = list[clId].index[splitting[0][e]];\n C.children[e] = list[clId].index[splitting[0][e]];\n }\n var sData = new Array(splitting[1].length);\n sG.index = new Array(splitting[1].length);\n for (var f = 0; f < sData.length; f++) {\n sData[f] = data[list[clId].index[splitting[1][f]].index];\n sG.index[f] = list[clId].index[splitting[1][f]];\n sG.children[f] = list[clId].index[splitting[1][f]];\n }\n C.distance = intrDist(C.index, data, options.dist);\n sG.distance = intrDist(sG.index, data, options.dist);\n list.push(C);\n list.push(sG);\n list[clId].children = [C, sG];\n }\n list.splice(clId, 1);\n }\n return tree;\n}\n\nmodule.exports = diana;\n","'use strict';\nconst Kernel = require('ml-kernel');\nconst stat = require('ml-stat').array;\n\nvar defaultOptions = {\n C: 1,\n tol: 1e-4,\n maxPasses: 10,\n maxIterations: 10000,\n kernel: 'linear',\n alphaTol: 1e-6,\n random: Math.random,\n whitening: true\n};\n\n/**\n * Simplified version of the Sequential Minimal Optimization algorithm for training\n * support vector machines\n * @param {{Object}} options - SVM options\n * @param {Number} [options.C=1] - regularization parameter\n * @param {Number} [options.tol=1e-4] - numerical tolerance\n * @param {Number} [options.alphaTol=1e-6] - alpha tolerance, threshold to decide support vectors\n * @param {Number} [options.maxPasses=10] - max number of times to iterate over alphas without changing\n * @param {Number} [options.maxIterations=10000] - max number of iterations\n * @param {String} [options.kernel=linear] - the kind of kernel. {@link https://github.com/mljs/kernel/tree/1252de5f9012776e6e0eb06c7b434b8631fb21f0 List of kernels}\n * @param {Function} [options.random=Math.random] - custom random number generator\n * @constructor\n */\nfunction SVM(options) {\n this.options = Object.assign({}, defaultOptions, options);\n\n this.kernel = new Kernel(this.options.kernel, this.options.kernelOptions);\n this.b = 0;\n}\n\n/**\n * Train the SVM model\n * @param {Array >} features - training data features\n * @param {Array } labels - training data labels in the domain {1,-1}\n */\nSVM.prototype.train = function (features, labels) {\n if (features.length !== labels.length) {\n throw new Error('Features and labels should have the same length');\n }\n if (features.length < 2) {\n throw new Error('Cannot train with less than 2 observations');\n }\n this._trained = false;\n this._loaded = false;\n this.N = labels.length;\n this.D = features[0].length;\n if (this.options.whitening) {\n this.X = new Array(this.N);\n for (var i = 0; i < this.N; i++) {\n this.X[i] = new Array(this.D);\n }\n this.minMax = new Array(this.D);\n // Apply normalization and keep normalization parameters\n for (var j = 0; j < this.D; j++) {\n var d = new Array(this.N);\n for (i = 0; i < this.N; i++) {\n d[i] = features[i][j];\n }\n this.minMax[j] = stat.minMax(d);\n for (i = 0; i < this.N; i++) {\n this.X[i][j] = (features[i][j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min);\n }\n }\n } else {\n this.X = features;\n }\n this.Y = labels;\n this.b = 0;\n this.W = undefined;\n\n var kernel = this.kernel.compute(this.X);\n var m = labels.length;\n var alpha = new Array(m).fill(0);\n this.alphas = alpha;\n for (var a = 0; a < m; a++)\n alpha[a] = 0;\n\n var b1 = 0,\n b2 = 0,\n iter = 0,\n passes = 0,\n Ei = 0,\n Ej = 0,\n ai = 0,\n aj = 0,\n L = 0,\n H = 0,\n eta = 0;\n\n while (passes < this.options.maxPasses && iter < this.options.maxIterations) {\n var numChange = 0;\n for (i = 0; i < m; i++) {\n Ei = this._marginOnePrecomputed(i, kernel) - labels[i];\n if (labels[i] * Ei < -this.options.tol && alpha[i] < this.options.C || labels[i] * Ei > this.options.tol && alpha[i] > 0) {\n j = i;\n while (j === i) j = Math.floor(this.options.random() * m);\n Ej = this._marginOnePrecomputed(j, kernel) - labels[j];\n ai = alpha[i];\n aj = alpha[j];\n if (labels[i] === labels[j]) {\n L = Math.max(0, ai + aj - this.options.C);\n H = Math.min(this.options.C, ai + aj);\n } else {\n L = Math.max(0, aj - ai);\n H = Math.min(this.options.C, this.options.C + aj + ai);\n }\n if (Math.abs(L - H) < 1e-4) continue;\n\n eta = 2 * kernel[i][j] - kernel[i][i] - kernel[j][j];\n if (eta >= 0) continue;\n var newaj = alpha[j] - labels[j] * (Ei - Ej) / eta;\n if (newaj > H)\n newaj = H;\n else if (newaj < L)\n newaj = L;\n if (Math.abs(aj - newaj) < 10e-4) continue;\n alpha[j] = newaj;\n alpha[i] = alpha[i] + labels[i] * labels[j] * (aj - newaj);\n b1 = this.b - Ei - labels[i] * (alpha[i] - ai) * kernel[i][i] - labels[j] * (alpha[j] - aj) * kernel[i][j];\n b2 = this.b - Ej - labels[i] * (alpha[i] - ai) * kernel[i][j] - labels[j] * (alpha[j] - aj) * kernel[j][j];\n this.b = (b1 + b2) / 2;\n if (alpha[i] < this.options.C && alpha[i] > 0) this.b = b1;\n if (alpha[j] < this.options.C && alpha[j] > 0) this.b = b2;\n numChange += 1;\n }\n }\n iter++;\n if (numChange === 0)\n passes += 1;\n else\n passes = 0;\n }\n if (iter === this.options.maxIterations) {\n throw new Error('max iterations reached');\n }\n\n this.iterations = iter;\n\n // Compute the weights (useful for fast decision on new test instances when linear SVM)\n if (this.options.kernel === 'linear') {\n this.W = new Array(this.D);\n for (var r = 0; r < this.D; r++) {\n this.W[r] = 0;\n for (var w = 0; w < m; w++)\n this.W[r] += labels[w] * alpha[w] * this.X[w][r];\n }\n }\n\n // Keep only support vectors\n // It will compute decision on new test instances faster\n // We also keep the index of the support vectors\n // in the original data\n var nX = [];\n var nY = [];\n var nAlphas = [];\n this._supportVectorIdx = [];\n for (i = 0; i < this.N; i++) {\n if (this.alphas[i] > this.options.alphaTol) {\n nX.push(this.X[i]);\n nY.push(labels[i]);\n nAlphas.push(this.alphas[i]);\n this._supportVectorIdx.push(i);\n\n }\n }\n this.X = nX;\n this.Y = nY;\n this.N = nX.length;\n this.alphas = nAlphas;\n\n\n // A flag to say this SVM has been trained\n this._trained = true;\n};\n\n/**\n * Get prediction ({-1,1}) given one observation's features.\n * @private\n * @param p The observation's features.\n * @returns {number} Classification result ({-1,1})\n */\nSVM.prototype.predictOne = function (p) {\n var margin = this.marginOne(p);\n return margin > 0 ? 1 : -1;\n};\n\n/**\n * Predict the classification outcome of a trained svm given one or several observations' features.\n * @param {Array} features - The observation(s)' features\n * @returns {Array|Number} An array of {-1, 1} if several observations are given or a number if one observation\n * is given\n */\nSVM.prototype.predict = function (features) {\n if (!this._trained && !this._loaded) throw new Error('Cannot predict, you need to train the SVM first');\n if (Array.isArray(features) && Array.isArray(features[0])) {\n return features.map(this.predictOne.bind(this));\n } else {\n return this.predictOne(features);\n }\n};\n\n/**\n * Get margin given one observation's features\n * @private\n * @param {Array} features - Features\n * @returns {Number} - The computed margin\n */\nSVM.prototype.marginOne = function (features, noWhitening) {\n // Apply normalization\n if (this.options.whitening && !noWhitening) {\n features = this._applyWhitening(features);\n }\n var ans = this.b, i;\n if (this.options.kernel === 'linear' && this.W) {\n // Use weights, it's faster\n for (i = 0; i < this.W.length; i++) {\n ans += this.W[i] * features[i];\n }\n } else {\n for (i = 0; i < this.N; i++) {\n ans += this.alphas[i] * this.Y[i] * this.kernel.compute([features], [this.X[i]])[0][0];\n }\n }\n return ans;\n};\n\n\n/**\n * Get a margin using the precomputed kernel. Much faster than normal margin computation\n * @private\n * @param {Number} index - Train data index\n * @param {Array< Array >} kernel - The precomputed kernel\n * @returns {number} Computed margin\n * @private\n */\nSVM.prototype._marginOnePrecomputed = function (index, kernel) {\n var ans = this.b, i;\n for (i = 0; i < this.N; i++) {\n ans += this.alphas[i] * this.Y[i] * kernel[index][i];\n }\n return ans;\n};\n\n\n/**\n * Returns the margin of one or several observations given its features\n * @param {Array >|Array} features - Features from on or several observations.\n * @returns {Number|Array} The computed margin. Is an Array if several observations' features given, or a Number if\n * only one observation's features given\n */\nSVM.prototype.margin = function (features) {\n if (Array.isArray(features)) {\n return features.map(this.marginOne.bind(this));\n } else {\n return this.marginOne(features);\n }\n};\n\n/**\n * Get support vectors indexes of the trained classifier. WARINNG: this method does not work for svm instances\n * created from {@link #SVM.load load} if linear kernel\n * @returns {Array} The indices in the training vector of the support vectors\n */\nSVM.prototype.supportVectors = function () {\n if (!this._trained && !this._loaded) throw new Error('Cannot get support vectors, you need to train the SVM first');\n if (this._loaded && this.options.kernel === 'linear') throw new Error('Cannot get support vectors from saved linear model, you need to train the SVM to have them');\n return this._supportVectorIdx;\n};\n\n/**\n * Create a SVM instance from a saved model\n * @param {Object} model - Object such as returned by a trained SVM instance with {@link #SVM#toJSON toJSON}\n * @returns {SVM} Instance of svm classifier\n */\nSVM.load = function (model) {\n this._loaded = true;\n this._trained = false;\n var svm = new SVM(model.options);\n if (model.options.kernel === 'linear') {\n svm.W = model.W.slice();\n svm.D = svm.W.length;\n } else {\n svm.X = model.X.slice();\n svm.Y = model.Y.slice();\n svm.alphas = model.alphas.slice();\n svm.N = svm.X.length;\n svm.D = svm.X[0].length;\n }\n svm.minMax = model.minMax;\n svm.b = model.b;\n svm._loaded = true;\n svm._trained = false;\n return svm;\n};\n\n/**\n * Export the minimal object that enables to reload the model\n * @returns {Object} Model object that can be reused with {@link #SVM.load load}\n */\nSVM.prototype.toJSON = function () {\n if (!this._trained && !this._loaded) throw new Error('Cannot export, you need to train the SVM first');\n var model = {};\n model.options = Object.assign({}, this.options);\n model.b = this.b;\n model.minMax = this.minMax;\n if (model.options.kernel === 'linear') {\n model.W = this.W.slice();\n } else {\n // Exporting non-linear models is heavier\n model.X = this.X.slice();\n model.Y = this.Y.slice();\n model.alphas = this.alphas.slice();\n }\n return model;\n};\n\nSVM.prototype._applyWhitening = function (features) {\n if (!this.minMax) throw new Error('Could not apply whitening');\n var whitened = new Array(features.length);\n for (var j = 0; j < features.length; j++) {\n whitened[j] = (features[j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min);\n }\n return whitened;\n};\n\nmodule.exports = SVM;\n","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass GaussianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = GaussianKernel;\n","'use strict';\n\nconst defaultOptions = {\n degree: 1,\n constant: 1,\n scale: 1\n};\n\nclass PolynomialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n\n this.degree = options.degree;\n this.constant = options.constant;\n this.scale = options.scale;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.pow(this.scale * sum + this.constant, this.degree);\n }\n}\n\nmodule.exports = PolynomialKernel;\n","'use strict';\n\nconst defaultOptions = {\n sigma: 1,\n degree: 1\n};\n\nclass ANOVAKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.degree = options.degree;\n }\n\n compute(x, y) {\n var sum = 0;\n var len = Math.min(x.length, y.length);\n for (var i = 1; i <= len; ++i) {\n sum += Math.pow(Math.exp(-this.sigma * Math.pow(Math.pow(x[i - 1], i) -\n Math.pow(y[i - 1], i), 2)), this.degree);\n }\n return sum;\n }\n}\n\nmodule.exports = ANOVAKernel;\n","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass CauchyKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n return 1 / (1 + squaredEuclidean(x, y) / (this.sigma * this.sigma));\n }\n}\n\nmodule.exports = CauchyKernel;\n","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass ExponentialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = ExponentialKernel;\n","'use strict';\n\nclass HistogramIntersectionKernel {\n compute(x, y) {\n var min = Math.min(x.length, y.length);\n var sum = 0;\n for (var i = 0; i < min; ++i) {\n sum += Math.min(x[i], y[i]);\n }\n\n return sum;\n }\n}\n\nmodule.exports = HistogramIntersectionKernel;\n","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass LaplacianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.sigma);\n }\n}\n\nmodule.exports = LaplacianKernel;\n","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass MultiquadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n return Math.sqrt(squaredEuclidean(x, y) + this.constant * this.constant);\n }\n}\n\nmodule.exports = MultiquadraticKernel;\n","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass RationalQuadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return 1 - (distance / (distance + this.constant));\n }\n}\n\nmodule.exports = RationalQuadraticKernel;\n","'use strict';\n\nconst defaultOptions = {\n alpha: 0.01,\n constant: -Math.E\n};\n\nclass SigmoidKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.alpha = options.alpha;\n this.constant = options.constant;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.tanh(this.alpha * sum + this.constant);\n }\n}\n\nmodule.exports = SigmoidKernel;\n","'use strict';\n\nconst ConfusionMatrix = require('ml-confusion-matrix');\n\nconst CV = {};\nconst combinations = require('ml-combinations');\n\n/**\n * Performs a leave-one-out cross-validation (LOO-CV) of the given samples. In LOO-CV, 1 observation is used as the\n * validation set while the rest is used as the training set. This is repeated once for each observation. LOO-CV is a\n * special case of LPO-CV. @see leavePout\n * @param {function} Classifier - The classifier's constructor to use for the cross validation. Expect ml-classifier\n * api.\n * @param {Array} features - The features for all samples of the data-set\n * @param {Array} labels - The classification class of all samples of the data-set\n * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated.\n * @return {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.leaveOneOut = function (Classifier, features, labels, classifierOptions) {\n if (typeof labels === 'function') {\n var callback = labels;\n labels = features;\n features = Classifier;\n return CV.leavePOut(features, labels, 1, callback);\n }\n return CV.leavePOut(Classifier, features, labels, classifierOptions, 1);\n};\n\n\n/**\n * Performs a leave-p-out cross-validation (LPO-CV) of the given samples. In LPO-CV, p observations are used as the\n * validation set while the rest is used as the training set. This is repeated as many times as there are possible\n * ways to combine p observations from the set (unordered without replacement). Be aware that for relatively small\n * data-set size this can require a very large number of training and testing to do!\n * @param {function} Classifier - The classifier's constructor to use for the cross validation. Expect ml-classifier\n * api.\n * @param {Array} features - The features for all samples of the data-set\n * @param {Array} labels - The classification class of all samples of the data-set\n * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated.\n * @param {number} p - The size of the validation sub-samples' set\n * @return {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.leavePOut = function (Classifier, features, labels, classifierOptions, p) {\n if (typeof classifierOptions === 'function') {\n var callback = classifierOptions;\n p = labels;\n labels = features;\n features = Classifier;\n }\n check(features, labels);\n const distinct = getDistinct(labels);\n const confusionMatrix = initMatrix(distinct.length, distinct.length);\n\n var N = features.length;\n var gen = combinations(p, N);\n var allIdx = new Array(N);\n for (let i = 0; i < N; i++) {\n allIdx[i] = i;\n }\n for (const testIdx of gen) {\n var trainIdx = allIdx.slice();\n\n for (let i = testIdx.length - 1; i >= 0; i--) {\n trainIdx.splice(testIdx[i], 1);\n }\n\n if (callback) {\n validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback);\n } else {\n validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct);\n }\n\n }\n\n return new ConfusionMatrix(confusionMatrix, distinct);\n};\n\n/**\n * Performs k-fold cross-validation (KF-CV). KF-CV separates the data-set into k random equally sized partitions, and\n * uses each as a validation set, with all other partitions used in the training set. Observations left over from if k\n * does not divide the number of observations are left out of the cross-validation process.\n * @param {function} Classifier - The classifier's to use for the cross validation. Expect ml-classifier api.\n * @param {Array} features - The features for all samples of the data-set\n * @param {Array} labels - The classification class of all samples of the data-set\n * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated.\n * @param {number} k - The number of partitions to create\n * @return {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.kFold = function (Classifier, features, labels, classifierOptions, k) {\n if (typeof classifierOptions === 'function') {\n var callback = classifierOptions;\n k = labels;\n labels = features;\n features = Classifier;\n }\n check(features, labels);\n const distinct = getDistinct(labels);\n const confusionMatrix = initMatrix(distinct.length, distinct.length);\n var N = features.length;\n var allIdx = new Array(N);\n for (var i = 0; i < N; i++) {\n allIdx[i] = i;\n }\n\n var l = Math.floor(N / k);\n // create random k-folds\n var current = [];\n var folds = [];\n while (allIdx.length) {\n var randi = Math.floor(Math.random() * allIdx.length);\n current.push(allIdx[randi]);\n allIdx.splice(randi, 1);\n if (current.length === l) {\n folds.push(current);\n current = [];\n }\n }\n if (current.length) folds.push(current);\n folds = folds.slice(0, k);\n\n\n for (i = 0; i < folds.length; i++) {\n var testIdx = folds[i];\n var trainIdx = [];\n for (var j = 0; j < folds.length; j++) {\n if (j !== i) trainIdx = trainIdx.concat(folds[j]);\n }\n\n if (callback) {\n validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback);\n } else {\n validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct);\n }\n }\n\n return new ConfusionMatrix(confusionMatrix, distinct);\n};\n\nfunction check(features, labels) {\n if (features.length !== labels.length) {\n throw new Error('features and labels should have the same length');\n }\n}\n\nfunction initMatrix(rows, columns) {\n return new Array(rows).fill(0).map(() => new Array(columns).fill(0));\n}\n\nfunction getDistinct(arr) {\n var s = new Set();\n for (let i = 0; i < arr.length; i++) {\n s.add(arr[i]);\n }\n return Array.from(s);\n}\n\nfunction validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct) {\n const {testFeatures, trainFeatures, testLabels, trainLabels} = getTrainTest(features, labels, testIdx, trainIdx);\n\n var classifier;\n if (Classifier.prototype.train) {\n classifier = new Classifier(classifierOptions);\n classifier.train(trainFeatures, trainLabels);\n } else {\n classifier = new Classifier(trainFeatures, trainLabels, classifierOptions);\n }\n\n var predictedLabels = classifier.predict(testFeatures);\n updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct);\n}\n\nfunction validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback) {\n const {testFeatures, trainFeatures, testLabels, trainLabels} = getTrainTest(features, labels, testIdx, trainIdx);\n const predictedLabels = callback(trainFeatures, trainLabels, testFeatures);\n updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct);\n}\n\nfunction updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct) {\n\n for (var i = 0; i < predictedLabels.length; i++) {\n const actualIdx = distinct.indexOf(testLabels[i]);\n const predictedIdx = distinct.indexOf(predictedLabels[i]);\n if (actualIdx < 0 || predictedIdx < 0) {\n // eslint-disable-next-line no-console\n console.warn(`ignore unknown predicted label ${predictedLabels[i]}`);\n }\n confusionMatrix[actualIdx][predictedIdx]++;\n }\n}\n\n\nfunction getTrainTest(features, labels, testIdx, trainIdx) {\n return {\n testFeatures: testIdx.map(function (index) {\n return features[index];\n }),\n trainFeatures: trainIdx.map(function (index) {\n return features[index];\n }),\n testLabels: testIdx.map(function (index) {\n return labels[index];\n }),\n trainLabels: trainIdx.map(function (index) {\n return labels[index];\n })\n };\n}\n\nmodule.exports = CV;\n","(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? factory() :\n\ttypeof define === 'function' && define.amd ? define(factory) :\n\t(factory());\n}(this, (function () { 'use strict';\n\n\tfunction createCommonjsModule(fn, module) {\n\t\treturn module = { exports: {} }, fn(module, module.exports), module.exports;\n\t}\n\n\tvar runtime = createCommonjsModule(function (module) {\n\t/**\n\t * Copyright (c) 2014-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t */\n\n\t!(function(global) {\n\n\t var Op = Object.prototype;\n\t var hasOwn = Op.hasOwnProperty;\n\t var undefined; // More compressible than void 0.\n\t var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n\t var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n\t var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n\t var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\t var runtime = global.regeneratorRuntime;\n\t if (runtime) {\n\t {\n\t // If regeneratorRuntime is defined globally and we're in a module,\n\t // make the exports object identical to regeneratorRuntime.\n\t module.exports = runtime;\n\t }\n\t // Don't bother evaluating the rest of this file if the runtime was\n\t // already defined globally.\n\t return;\n\t }\n\n\t // Define the runtime globally (as expected by generated code) as either\n\t // module.exports (if we're in a module) or a new, empty object.\n\t runtime = global.regeneratorRuntime = module.exports;\n\n\t function wrap(innerFn, outerFn, self, tryLocsList) {\n\t // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n\t var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n\t var generator = Object.create(protoGenerator.prototype);\n\t var context = new Context(tryLocsList || []);\n\n\t // The ._invoke method unifies the implementations of the .next,\n\t // .throw, and .return methods.\n\t generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n\t return generator;\n\t }\n\t runtime.wrap = wrap;\n\n\t // Try/catch helper to minimize deoptimizations. Returns a completion\n\t // record like context.tryEntries[i].completion. This interface could\n\t // have been (and was previously) designed to take a closure to be\n\t // invoked without arguments, but in all the cases we care about we\n\t // already have an existing method we want to call, so there's no need\n\t // to create a new function object. We can even get away with assuming\n\t // the method takes exactly one argument, since that happens to be true\n\t // in every case, so we don't have to touch the arguments object. The\n\t // only additional allocation required is the completion record, which\n\t // has a stable shape and so hopefully should be cheap to allocate.\n\t function tryCatch(fn, obj, arg) {\n\t try {\n\t return { type: \"normal\", arg: fn.call(obj, arg) };\n\t } catch (err) {\n\t return { type: \"throw\", arg: err };\n\t }\n\t }\n\n\t var GenStateSuspendedStart = \"suspendedStart\";\n\t var GenStateSuspendedYield = \"suspendedYield\";\n\t var GenStateExecuting = \"executing\";\n\t var GenStateCompleted = \"completed\";\n\n\t // Returning this object from the innerFn has the same effect as\n\t // breaking out of the dispatch switch statement.\n\t var ContinueSentinel = {};\n\n\t // Dummy constructor functions that we use as the .constructor and\n\t // .constructor.prototype properties for functions that return Generator\n\t // objects. For full spec compliance, you may wish to configure your\n\t // minifier not to mangle the names of these two functions.\n\t function Generator() {}\n\t function GeneratorFunction() {}\n\t function GeneratorFunctionPrototype() {}\n\n\t // This is a polyfill for %IteratorPrototype% for environments that\n\t // don't natively support it.\n\t var IteratorPrototype = {};\n\t IteratorPrototype[iteratorSymbol] = function () {\n\t return this;\n\t };\n\n\t var getProto = Object.getPrototypeOf;\n\t var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n\t if (NativeIteratorPrototype &&\n\t NativeIteratorPrototype !== Op &&\n\t hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n\t // This environment has a native %IteratorPrototype%; use it instead\n\t // of the polyfill.\n\t IteratorPrototype = NativeIteratorPrototype;\n\t }\n\n\t var Gp = GeneratorFunctionPrototype.prototype =\n\t Generator.prototype = Object.create(IteratorPrototype);\n\t GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n\t GeneratorFunctionPrototype.constructor = GeneratorFunction;\n\t GeneratorFunctionPrototype[toStringTagSymbol] =\n\t GeneratorFunction.displayName = \"GeneratorFunction\";\n\n\t // Helper for defining the .next, .throw, and .return methods of the\n\t // Iterator interface in terms of a single ._invoke method.\n\t function defineIteratorMethods(prototype) {\n\t [\"next\", \"throw\", \"return\"].forEach(function(method) {\n\t prototype[method] = function(arg) {\n\t return this._invoke(method, arg);\n\t };\n\t });\n\t }\n\n\t runtime.isGeneratorFunction = function(genFun) {\n\t var ctor = typeof genFun === \"function\" && genFun.constructor;\n\t return ctor\n\t ? ctor === GeneratorFunction ||\n\t // For the native GeneratorFunction constructor, the best we can\n\t // do is to check its .name property.\n\t (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n\t : false;\n\t };\n\n\t runtime.mark = function(genFun) {\n\t if (Object.setPrototypeOf) {\n\t Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n\t } else {\n\t genFun.__proto__ = GeneratorFunctionPrototype;\n\t if (!(toStringTagSymbol in genFun)) {\n\t genFun[toStringTagSymbol] = \"GeneratorFunction\";\n\t }\n\t }\n\t genFun.prototype = Object.create(Gp);\n\t return genFun;\n\t };\n\n\t // Within the body of any async function, `await x` is transformed to\n\t // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n\t // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n\t // meant to be awaited.\n\t runtime.awrap = function(arg) {\n\t return { __await: arg };\n\t };\n\n\t function AsyncIterator(generator) {\n\t function invoke(method, arg, resolve, reject) {\n\t var record = tryCatch(generator[method], generator, arg);\n\t if (record.type === \"throw\") {\n\t reject(record.arg);\n\t } else {\n\t var result = record.arg;\n\t var value = result.value;\n\t if (value &&\n\t typeof value === \"object\" &&\n\t hasOwn.call(value, \"__await\")) {\n\t return Promise.resolve(value.__await).then(function(value) {\n\t invoke(\"next\", value, resolve, reject);\n\t }, function(err) {\n\t invoke(\"throw\", err, resolve, reject);\n\t });\n\t }\n\n\t return Promise.resolve(value).then(function(unwrapped) {\n\t // When a yielded Promise is resolved, its final value becomes\n\t // the .value of the Promise<{value,done}> result for the\n\t // current iteration. If the Promise is rejected, however, the\n\t // result for this iteration will be rejected with the same\n\t // reason. Note that rejections of yielded Promises are not\n\t // thrown back into the generator function, as is the case\n\t // when an awaited Promise is rejected. This difference in\n\t // behavior between yield and await is important, because it\n\t // allows the consumer to decide what to do with the yielded\n\t // rejection (swallow it and continue, manually .throw it back\n\t // into the generator, abandon iteration, whatever). With\n\t // await, by contrast, there is no opportunity to examine the\n\t // rejection reason outside the generator function, so the\n\t // only option is to throw it from the await expression, and\n\t // let the generator function handle the exception.\n\t result.value = unwrapped;\n\t resolve(result);\n\t }, reject);\n\t }\n\t }\n\n\t var previousPromise;\n\n\t function enqueue(method, arg) {\n\t function callInvokeWithMethodAndArg() {\n\t return new Promise(function(resolve, reject) {\n\t invoke(method, arg, resolve, reject);\n\t });\n\t }\n\n\t return previousPromise =\n\t // If enqueue has been called before, then we want to wait until\n\t // all previous Promises have been resolved before calling invoke,\n\t // so that results are always delivered in the correct order. If\n\t // enqueue has not been called before, then it is important to\n\t // call invoke immediately, without waiting on a callback to fire,\n\t // so that the async generator function has the opportunity to do\n\t // any necessary setup in a predictable way. This predictability\n\t // is why the Promise constructor synchronously invokes its\n\t // executor callback, and why async functions synchronously\n\t // execute code before the first await. Since we implement simple\n\t // async functions in terms of async generators, it is especially\n\t // important to get this right, even though it requires care.\n\t previousPromise ? previousPromise.then(\n\t callInvokeWithMethodAndArg,\n\t // Avoid propagating failures to Promises returned by later\n\t // invocations of the iterator.\n\t callInvokeWithMethodAndArg\n\t ) : callInvokeWithMethodAndArg();\n\t }\n\n\t // Define the unified helper method that is used to implement .next,\n\t // .throw, and .return (see defineIteratorMethods).\n\t this._invoke = enqueue;\n\t }\n\n\t defineIteratorMethods(AsyncIterator.prototype);\n\t AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n\t return this;\n\t };\n\t runtime.AsyncIterator = AsyncIterator;\n\n\t // Note that simple async functions are implemented on top of\n\t // AsyncIterator objects; they just return a Promise for the value of\n\t // the final result produced by the iterator.\n\t runtime.async = function(innerFn, outerFn, self, tryLocsList) {\n\t var iter = new AsyncIterator(\n\t wrap(innerFn, outerFn, self, tryLocsList)\n\t );\n\n\t return runtime.isGeneratorFunction(outerFn)\n\t ? iter // If outerFn is a generator, return the full iterator.\n\t : iter.next().then(function(result) {\n\t return result.done ? result.value : iter.next();\n\t });\n\t };\n\n\t function makeInvokeMethod(innerFn, self, context) {\n\t var state = GenStateSuspendedStart;\n\n\t return function invoke(method, arg) {\n\t if (state === GenStateExecuting) {\n\t throw new Error(\"Generator is already running\");\n\t }\n\n\t if (state === GenStateCompleted) {\n\t if (method === \"throw\") {\n\t throw arg;\n\t }\n\n\t // Be forgiving, per 25.3.3.3.3 of the spec:\n\t // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n\t return doneResult();\n\t }\n\n\t context.method = method;\n\t context.arg = arg;\n\n\t while (true) {\n\t var delegate = context.delegate;\n\t if (delegate) {\n\t var delegateResult = maybeInvokeDelegate(delegate, context);\n\t if (delegateResult) {\n\t if (delegateResult === ContinueSentinel) continue;\n\t return delegateResult;\n\t }\n\t }\n\n\t if (context.method === \"next\") {\n\t // Setting context._sent for legacy support of Babel's\n\t // function.sent implementation.\n\t context.sent = context._sent = context.arg;\n\n\t } else if (context.method === \"throw\") {\n\t if (state === GenStateSuspendedStart) {\n\t state = GenStateCompleted;\n\t throw context.arg;\n\t }\n\n\t context.dispatchException(context.arg);\n\n\t } else if (context.method === \"return\") {\n\t context.abrupt(\"return\", context.arg);\n\t }\n\n\t state = GenStateExecuting;\n\n\t var record = tryCatch(innerFn, self, context);\n\t if (record.type === \"normal\") {\n\t // If an exception is thrown from innerFn, we leave state ===\n\t // GenStateExecuting and loop back for another invocation.\n\t state = context.done\n\t ? GenStateCompleted\n\t : GenStateSuspendedYield;\n\n\t if (record.arg === ContinueSentinel) {\n\t continue;\n\t }\n\n\t return {\n\t value: record.arg,\n\t done: context.done\n\t };\n\n\t } else if (record.type === \"throw\") {\n\t state = GenStateCompleted;\n\t // Dispatch the exception by looping back around to the\n\t // context.dispatchException(context.arg) call above.\n\t context.method = \"throw\";\n\t context.arg = record.arg;\n\t }\n\t }\n\t };\n\t }\n\n\t // Call delegate.iterator[context.method](context.arg) and handle the\n\t // result, either by returning a { value, done } result from the\n\t // delegate iterator, or by modifying context.method and context.arg,\n\t // setting context.delegate to null, and returning the ContinueSentinel.\n\t function maybeInvokeDelegate(delegate, context) {\n\t var method = delegate.iterator[context.method];\n\t if (method === undefined) {\n\t // A .throw or .return when the delegate iterator has no .throw\n\t // method always terminates the yield* loop.\n\t context.delegate = null;\n\n\t if (context.method === \"throw\") {\n\t if (delegate.iterator.return) {\n\t // If the delegate iterator has a return method, give it a\n\t // chance to clean up.\n\t context.method = \"return\";\n\t context.arg = undefined;\n\t maybeInvokeDelegate(delegate, context);\n\n\t if (context.method === \"throw\") {\n\t // If maybeInvokeDelegate(context) changed context.method from\n\t // \"return\" to \"throw\", let that override the TypeError below.\n\t return ContinueSentinel;\n\t }\n\t }\n\n\t context.method = \"throw\";\n\t context.arg = new TypeError(\n\t \"The iterator does not provide a 'throw' method\");\n\t }\n\n\t return ContinueSentinel;\n\t }\n\n\t var record = tryCatch(method, delegate.iterator, context.arg);\n\n\t if (record.type === \"throw\") {\n\t context.method = \"throw\";\n\t context.arg = record.arg;\n\t context.delegate = null;\n\t return ContinueSentinel;\n\t }\n\n\t var info = record.arg;\n\n\t if (! info) {\n\t context.method = \"throw\";\n\t context.arg = new TypeError(\"iterator result is not an object\");\n\t context.delegate = null;\n\t return ContinueSentinel;\n\t }\n\n\t if (info.done) {\n\t // Assign the result of the finished delegate to the temporary\n\t // variable specified by delegate.resultName (see delegateYield).\n\t context[delegate.resultName] = info.value;\n\n\t // Resume execution at the desired location (see delegateYield).\n\t context.next = delegate.nextLoc;\n\n\t // If context.method was \"throw\" but the delegate handled the\n\t // exception, let the outer generator proceed normally. If\n\t // context.method was \"next\", forget context.arg since it has been\n\t // \"consumed\" by the delegate iterator. If context.method was\n\t // \"return\", allow the original .return call to continue in the\n\t // outer generator.\n\t if (context.method !== \"return\") {\n\t context.method = \"next\";\n\t context.arg = undefined;\n\t }\n\n\t } else {\n\t // Re-yield the result returned by the delegate method.\n\t return info;\n\t }\n\n\t // The delegate iterator is finished, so forget it and continue with\n\t // the outer generator.\n\t context.delegate = null;\n\t return ContinueSentinel;\n\t }\n\n\t // Define Generator.prototype.{next,throw,return} in terms of the\n\t // unified ._invoke helper method.\n\t defineIteratorMethods(Gp);\n\n\t Gp[toStringTagSymbol] = \"Generator\";\n\n\t // A Generator should always return itself as the iterator object when the\n\t // @@iterator function is called on it. Some browsers' implementations of the\n\t // iterator prototype chain incorrectly implement this, causing the Generator\n\t // object to not be returned from this call. This ensures that doesn't happen.\n\t // See https://github.com/facebook/regenerator/issues/274 for more details.\n\t Gp[iteratorSymbol] = function() {\n\t return this;\n\t };\n\n\t Gp.toString = function() {\n\t return \"[object Generator]\";\n\t };\n\n\t function pushTryEntry(locs) {\n\t var entry = { tryLoc: locs[0] };\n\n\t if (1 in locs) {\n\t entry.catchLoc = locs[1];\n\t }\n\n\t if (2 in locs) {\n\t entry.finallyLoc = locs[2];\n\t entry.afterLoc = locs[3];\n\t }\n\n\t this.tryEntries.push(entry);\n\t }\n\n\t function resetTryEntry(entry) {\n\t var record = entry.completion || {};\n\t record.type = \"normal\";\n\t delete record.arg;\n\t entry.completion = record;\n\t }\n\n\t function Context(tryLocsList) {\n\t // The root entry object (effectively a try statement without a catch\n\t // or a finally block) gives us a place to store values thrown from\n\t // locations where there is no enclosing try statement.\n\t this.tryEntries = [{ tryLoc: \"root\" }];\n\t tryLocsList.forEach(pushTryEntry, this);\n\t this.reset(true);\n\t }\n\n\t runtime.keys = function(object) {\n\t var keys = [];\n\t for (var key in object) {\n\t keys.push(key);\n\t }\n\t keys.reverse();\n\n\t // Rather than returning an object with a next method, we keep\n\t // things simple and return the next function itself.\n\t return function next() {\n\t while (keys.length) {\n\t var key = keys.pop();\n\t if (key in object) {\n\t next.value = key;\n\t next.done = false;\n\t return next;\n\t }\n\t }\n\n\t // To avoid creating an additional object, we just hang the .value\n\t // and .done properties off the next function object itself. This\n\t // also ensures that the minifier will not anonymize the function.\n\t next.done = true;\n\t return next;\n\t };\n\t };\n\n\t function values(iterable) {\n\t if (iterable) {\n\t var iteratorMethod = iterable[iteratorSymbol];\n\t if (iteratorMethod) {\n\t return iteratorMethod.call(iterable);\n\t }\n\n\t if (typeof iterable.next === \"function\") {\n\t return iterable;\n\t }\n\n\t if (!isNaN(iterable.length)) {\n\t var i = -1, next = function next() {\n\t while (++i < iterable.length) {\n\t if (hasOwn.call(iterable, i)) {\n\t next.value = iterable[i];\n\t next.done = false;\n\t return next;\n\t }\n\t }\n\n\t next.value = undefined;\n\t next.done = true;\n\n\t return next;\n\t };\n\n\t return next.next = next;\n\t }\n\t }\n\n\t // Return an iterator with no values.\n\t return { next: doneResult };\n\t }\n\t runtime.values = values;\n\n\t function doneResult() {\n\t return { value: undefined, done: true };\n\t }\n\n\t Context.prototype = {\n\t constructor: Context,\n\n\t reset: function(skipTempReset) {\n\t this.prev = 0;\n\t this.next = 0;\n\t // Resetting context._sent for legacy support of Babel's\n\t // function.sent implementation.\n\t this.sent = this._sent = undefined;\n\t this.done = false;\n\t this.delegate = null;\n\n\t this.method = \"next\";\n\t this.arg = undefined;\n\n\t this.tryEntries.forEach(resetTryEntry);\n\n\t if (!skipTempReset) {\n\t for (var name in this) {\n\t // Not sure about the optimal order of these conditions:\n\t if (name.charAt(0) === \"t\" &&\n\t hasOwn.call(this, name) &&\n\t !isNaN(+name.slice(1))) {\n\t this[name] = undefined;\n\t }\n\t }\n\t }\n\t },\n\n\t stop: function() {\n\t this.done = true;\n\n\t var rootEntry = this.tryEntries[0];\n\t var rootRecord = rootEntry.completion;\n\t if (rootRecord.type === \"throw\") {\n\t throw rootRecord.arg;\n\t }\n\n\t return this.rval;\n\t },\n\n\t dispatchException: function(exception) {\n\t if (this.done) {\n\t throw exception;\n\t }\n\n\t var context = this;\n\t function handle(loc, caught) {\n\t record.type = \"throw\";\n\t record.arg = exception;\n\t context.next = loc;\n\n\t if (caught) {\n\t // If the dispatched exception was caught by a catch block,\n\t // then let that catch block handle the exception normally.\n\t context.method = \"next\";\n\t context.arg = undefined;\n\t }\n\n\t return !! caught;\n\t }\n\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t var record = entry.completion;\n\n\t if (entry.tryLoc === \"root\") {\n\t // Exception thrown outside of any try block that could handle\n\t // it, so set the completion value of the entire function to\n\t // throw the exception.\n\t return handle(\"end\");\n\t }\n\n\t if (entry.tryLoc <= this.prev) {\n\t var hasCatch = hasOwn.call(entry, \"catchLoc\");\n\t var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n\t if (hasCatch && hasFinally) {\n\t if (this.prev < entry.catchLoc) {\n\t return handle(entry.catchLoc, true);\n\t } else if (this.prev < entry.finallyLoc) {\n\t return handle(entry.finallyLoc);\n\t }\n\n\t } else if (hasCatch) {\n\t if (this.prev < entry.catchLoc) {\n\t return handle(entry.catchLoc, true);\n\t }\n\n\t } else if (hasFinally) {\n\t if (this.prev < entry.finallyLoc) {\n\t return handle(entry.finallyLoc);\n\t }\n\n\t } else {\n\t throw new Error(\"try statement without catch or finally\");\n\t }\n\t }\n\t }\n\t },\n\n\t abrupt: function(type, arg) {\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t if (entry.tryLoc <= this.prev &&\n\t hasOwn.call(entry, \"finallyLoc\") &&\n\t this.prev < entry.finallyLoc) {\n\t var finallyEntry = entry;\n\t break;\n\t }\n\t }\n\n\t if (finallyEntry &&\n\t (type === \"break\" ||\n\t type === \"continue\") &&\n\t finallyEntry.tryLoc <= arg &&\n\t arg <= finallyEntry.finallyLoc) {\n\t // Ignore the finally entry if control is not jumping to a\n\t // location outside the try/catch block.\n\t finallyEntry = null;\n\t }\n\n\t var record = finallyEntry ? finallyEntry.completion : {};\n\t record.type = type;\n\t record.arg = arg;\n\n\t if (finallyEntry) {\n\t this.method = \"next\";\n\t this.next = finallyEntry.finallyLoc;\n\t return ContinueSentinel;\n\t }\n\n\t return this.complete(record);\n\t },\n\n\t complete: function(record, afterLoc) {\n\t if (record.type === \"throw\") {\n\t throw record.arg;\n\t }\n\n\t if (record.type === \"break\" ||\n\t record.type === \"continue\") {\n\t this.next = record.arg;\n\t } else if (record.type === \"return\") {\n\t this.rval = this.arg = record.arg;\n\t this.method = \"return\";\n\t this.next = \"end\";\n\t } else if (record.type === \"normal\" && afterLoc) {\n\t this.next = afterLoc;\n\t }\n\n\t return ContinueSentinel;\n\t },\n\n\t finish: function(finallyLoc) {\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t if (entry.finallyLoc === finallyLoc) {\n\t this.complete(entry.completion, entry.afterLoc);\n\t resetTryEntry(entry);\n\t return ContinueSentinel;\n\t }\n\t }\n\t },\n\n\t \"catch\": function(tryLoc) {\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t if (entry.tryLoc === tryLoc) {\n\t var record = entry.completion;\n\t if (record.type === \"throw\") {\n\t var thrown = record.arg;\n\t resetTryEntry(entry);\n\t }\n\t return thrown;\n\t }\n\t }\n\n\t // The context.catch method must only be called with a location\n\t // argument that corresponds to a known catch block.\n\t throw new Error(\"illegal catch attempt\");\n\t },\n\n\t delegateYield: function(iterable, resultName, nextLoc) {\n\t this.delegate = {\n\t iterator: values(iterable),\n\t resultName: resultName,\n\t nextLoc: nextLoc\n\t };\n\n\t if (this.method === \"next\") {\n\t // Deliberately forget the last sent value so that we don't\n\t // accidentally pass it on to the delegate.\n\t this.arg = undefined;\n\t }\n\n\t return ContinueSentinel;\n\t }\n\t };\n\t})(\n\t // In sloppy mode, unbound `this` refers to the global object, fallback to\n\t // Function constructor if we're in global strict mode. That is sadly a form\n\t // of indirect eval which violates Content Security Policy.\n\t (function() { return this })() || Function(\"return this\")()\n\t);\n\t});\n\n\t/**\n\t * Copyright (c) 2014-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t */\n\n\t// This method of obtaining a reference to the global object needs to be\n\t// kept identical to the way it is obtained in runtime.js\n\tvar g = (function() { return this })() || Function(\"return this\")();\n\n\t// Use `getOwnPropertyNames` because not all browsers support calling\n\t// `hasOwnProperty` on the global `self` object in a worker. See #183.\n\tvar hadRuntime = g.regeneratorRuntime &&\n\t Object.getOwnPropertyNames(g).indexOf(\"regeneratorRuntime\") >= 0;\n\n\t// Save the old regeneratorRuntime in case it needs to be restored later.\n\tvar oldRuntime = hadRuntime && g.regeneratorRuntime;\n\n\t// Force reevalutation of runtime.js.\n\tg.regeneratorRuntime = undefined;\n\n\tvar runtimeModule = runtime;\n\n\tif (hadRuntime) {\n\t // Restore the original runtime.\n\t g.regeneratorRuntime = oldRuntime;\n\t} else {\n\t // Remove the global property added by runtime.js.\n\t try {\n\t delete g.regeneratorRuntime;\n\t } catch(e) {\n\t g.regeneratorRuntime = undefined;\n\t }\n\t}\n\n\tvar regenerator = runtimeModule;\n\n\tvar defaultOptions = {\n\t mode: 'index'\n\t};\n\n\tmodule.exports = /*#__PURE__*/regenerator.mark(function _callee(M, N, options) {\n\t var a, c, b, p, x, y, z, i, twiddle;\n\t return regenerator.wrap(function _callee$(_context) {\n\t while (1) {\n\t switch (_context.prev = _context.next) {\n\t case 0:\n\t twiddle = function twiddle() {\n\t var i, j, k;\n\t j = 1;\n\t while (p[j] <= 0) {\n\t j++;\n\t }\n\t if (p[j - 1] === 0) {\n\t for (i = j - 1; i !== 1; i--) {\n\t p[i] = -1;\n\t }\n\t p[j] = 0;\n\t x = z = 0;\n\t p[1] = 1;\n\t y = j - 1;\n\t } else {\n\t if (j > 1) {\n\t p[j - 1] = 0;\n\t }\n\t do {\n\t j++;\n\t } while (p[j] > 0);\n\t k = j - 1;\n\t i = j;\n\t while (p[i] === 0) {\n\t p[i++] = -1;\n\t }\n\t if (p[i] === -1) {\n\t p[i] = p[k];\n\t z = p[k] - 1;\n\t x = i - 1;\n\t y = k - 1;\n\t p[k] = -1;\n\t } else {\n\t if (i === p[0]) {\n\t return 0;\n\t } else {\n\t p[j] = p[i];\n\t z = p[i] - 1;\n\t p[i] = 0;\n\t x = j - 1;\n\t y = i - 1;\n\t }\n\t }\n\t }\n\t return 1;\n\t };\n\n\t options = Object.assign({}, defaultOptions, options);\n\t a = new Array(N);\n\t c = new Array(M);\n\t b = new Array(N);\n\t p = new Array(N + 2);\n\n\n\t // init a and b\n\t for (i = 0; i < N; i++) {\n\t a[i] = i;\n\t if (i < N - M) b[i] = 0;else b[i] = 1;\n\t }\n\n\t // init c\n\t for (i = 0; i < M; i++) {\n\t c[i] = N - M + i;\n\t }\n\n\t // init p\n\t for (i = 0; i < p.length; i++) {\n\t if (i === 0) p[i] = N + 1;else if (i <= N - M) p[i] = 0;else if (i <= N) p[i] = i - N + M;else p[i] = -2;\n\t }\n\n\t if (!(options.mode === 'index')) {\n\t _context.next = 20;\n\t break;\n\t }\n\n\t _context.next = 12;\n\t return c.slice();\n\n\t case 12:\n\t if (!twiddle()) {\n\t _context.next = 18;\n\t break;\n\t }\n\n\t c[z] = a[x];\n\t _context.next = 16;\n\t return c.slice();\n\n\t case 16:\n\t _context.next = 12;\n\t break;\n\n\t case 18:\n\t _context.next = 33;\n\t break;\n\n\t case 20:\n\t if (!(options.mode === 'mask')) {\n\t _context.next = 32;\n\t break;\n\t }\n\n\t _context.next = 23;\n\t return b.slice();\n\n\t case 23:\n\t if (!twiddle()) {\n\t _context.next = 30;\n\t break;\n\t }\n\n\t b[x] = 1;\n\t b[y] = 0;\n\t _context.next = 28;\n\t return b.slice();\n\n\t case 28:\n\t _context.next = 23;\n\t break;\n\n\t case 30:\n\t _context.next = 33;\n\t break;\n\n\t case 32:\n\t throw new Error('Invalid mode');\n\n\t case 33:\n\t case 'end':\n\t return _context.stop();\n\t }\n\t }\n\t }, _callee, this);\n\t});\n\n})));\n","'use strict';\n\nconst Matrix = require('ml-matrix').Matrix;\n\nconst Layer = require('./Layer');\nconst OutputLayer = require('./OutputLayer');\nconst Utils = require('./utils');\nconst ACTIVATION_FUNCTIONS = require('./activationFunctions');\n\nclass FeedForwardNeuralNetworks {\n\n /**\n * Create a new Feedforword neural network model.\n * @class FeedForwardNeuralNetworks\n * @param {object} [options]\n * @param {Array} [options.hiddenLayers=[10]] - Array that contains the sizes of the hidden layers.\n * @param {number} [options.iterations=50] - Number of iterations at the training step.\n * @param {number} [options.learningRate=0.01] - Learning rate of the neural net (also known as epsilon).\n * @param {number} [options.regularization=0.01] - Regularization parameter af the neural net.\n * @param {string} [options.activation='tanh'] - activation function to be used. (options: 'tanh'(default),\n * 'identity', 'logistic', 'arctan', 'softsign', 'relu', 'softplus', 'bent', 'sinusoid', 'sinc', 'gaussian').\n * (single-parametric options: 'parametric-relu', 'exponential-relu', 'soft-exponential').\n * @param {number} [options.activationParam=1] - if the selected activation function needs a parameter.\n */\n constructor(options) {\n options = options || {};\n if (options.model) {\n // load network\n this.hiddenLayers = options.hiddenLayers;\n this.iterations = options.iterations;\n this.learningRate = options.learningRate;\n this.regularization = options.regularization;\n this.dicts = options.dicts;\n this.activation = options.activation;\n this.activationParam = options.activationParam;\n this.model = new Array(options.layers.length);\n\n for (var i = 0; i < this.model.length - 1; ++i) {\n this.model[i] = Layer.load(options.layers[i]);\n }\n this.model[this.model.length - 1] = OutputLayer.load(options.layers[this.model.length - 1]);\n } else {\n // default constructor\n this.hiddenLayers = options.hiddenLayers || [10];\n this.iterations = options.iterations || 50;\n\n this.learningRate = options.learningRate || 0.01;\n this.regularization = options.regularization || 0.01;\n\n this.activation = options.activation || 'tanh';\n this.activationParam = options.activationParam || 1;\n if (!(this.activation in Object.keys(ACTIVATION_FUNCTIONS))) {\n this.activation = 'tanh';\n }\n }\n }\n\n /**\n * @private\n * Function that build and initialize the neural net.\n * @param {number} inputSize - total of features to fit.\n * @param {number} outputSize - total of labels of the prediction set.\n */\n buildNetwork(inputSize, outputSize) {\n var size = 2 + (this.hiddenLayers.length - 1);\n this.model = new Array(size);\n\n // input layer\n this.model[0] = new Layer({\n inputSize: inputSize,\n outputSize: this.hiddenLayers[0],\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n\n // hidden layers\n for (var i = 1; i < this.hiddenLayers.length; ++i) {\n this.model[i] = new Layer({\n inputSize: this.hiddenLayers[i - 1],\n outputSize: this.hiddenLayers[i],\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n }\n\n // output layer\n this.model[size - 1] = new OutputLayer({\n inputSize: this.hiddenLayers[this.hiddenLayers.length - 1],\n outputSize: outputSize,\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n }\n\n /**\n * Train the neural net with the given features and labels.\n * @param {Matrix|Array} features\n * @param {Matrix|Array} labels\n */\n train(features, labels) {\n features = Matrix.checkMatrix(features);\n this.dicts = Utils.dictOutputs(labels);\n\n var inputSize = features.columns;\n var outputSize = Object.keys(this.dicts.inputs).length;\n\n this.buildNetwork(inputSize, outputSize);\n\n for (var i = 0; i < this.iterations; ++i) {\n var probabilities = this.propagate(features);\n this.backpropagation(features, labels, probabilities);\n }\n }\n\n /**\n * @private\n * Propagate the input(training set) and retrives the probabilities of each class.\n * @param {Matrix} X\n * @return {Matrix} probabilities of each class.\n */\n propagate(X) {\n var input = X;\n for (var i = 0; i < this.model.length; ++i) {\n //console.log(i);\n input = this.model[i].forward(input);\n }\n\n // get probabilities\n return input.divColumnVector(Utils.sumRow(input));\n }\n\n /**\n * @private\n * Function that applies the backpropagation algorithm on each layer of the network\n * in order to fit the features and labels.\n * @param {Matrix} features\n * @param {Array} labels\n * @param {Matrix} probabilities - probabilities of each class of the feature set.\n */\n backpropagation(features, labels, probabilities) {\n for (var i = 0; i < probabilities.length; ++i) {\n probabilities[i][this.dicts.inputs[labels[i]]] -= 1;\n }\n\n // remember, the last delta doesn't matter\n var delta = probabilities;\n for (i = this.model.length - 1; i >= 0; --i) {\n var a = i > 0 ? this.model[i - 1].a : features;\n delta = this.model[i].backpropagation(delta, a);\n }\n\n for (i = 0; i < this.model.length; ++i) {\n this.model[i].update();\n }\n }\n\n /**\n * Predict the output given the feature set.\n * @param {Array|Matrix} features\n * @return {Array}\n */\n predict(features) {\n features = Matrix.checkMatrix(features);\n var outputs = new Array(features.rows);\n var probabilities = this.propagate(features);\n for (var i = 0; i < features.rows; ++i) {\n outputs[i] = this.dicts.outputs[probabilities.maxRowIndex(i)[1]];\n }\n\n return outputs;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} model\n */\n toJSON() {\n var model = {\n model: 'FNN',\n hiddenLayers: this.hiddenLayers,\n iterations: this.iterations,\n learningRate: this.learningRate,\n regularization: this.regularization,\n activation: this.activation,\n activationParam: this.activationParam,\n dicts: this.dicts,\n layers: new Array(this.model.length)\n };\n\n for (var i = 0; i < this.model.length; ++i) {\n model.layers[i] = this.model[i].toJSON();\n }\n\n return model;\n }\n\n /**\n * Load a Feedforward Neural Network with the current model.\n * @param {object} model\n * @return {FeedForwardNeuralNetworks}\n */\n static load(model) {\n if (model.model !== 'FNN') {\n throw new RangeError('the current model is not a feed forward network');\n }\n\n return new FeedForwardNeuralNetworks(model);\n }\n}\n\nmodule.exports = FeedForwardNeuralNetworks;\n","'use strict';\n\nvar Layer = require('./Layer');\n\nclass OutputLayer extends Layer {\n constructor(options) {\n super(options);\n\n this.activationFunction = function (i, j) {\n this[i][j] = Math.exp(this[i][j]);\n };\n }\n\n static load(model) {\n if (model.model !== 'Layer') {\n throw new RangeError('the current model is not a Layer model');\n }\n\n return new OutputLayer(model);\n }\n}\n\nmodule.exports = OutputLayer;\n","'use strict';\n\nvar NodeSquare = require('./node-square'),\n NodeHexagonal = require('./node-hexagonal');\n\nvar defaultOptions = {\n fields: 3,\n randomizer: Math.random,\n distance: squareEuclidean,\n iterations: 10,\n learningRate: 0.1,\n gridType: 'rect',\n torus: true,\n method: 'random'\n};\n\nfunction SOM(x, y, options, reload) {\n\n this.x = x;\n this.y = y;\n\n options = options || {};\n this.options = {};\n for (var i in defaultOptions) {\n if (options.hasOwnProperty(i)) {\n this.options[i] = options[i];\n } else {\n this.options[i] = defaultOptions[i];\n }\n }\n\n if (typeof this.options.fields === 'number') {\n this.numWeights = this.options.fields;\n } else if (Array.isArray(this.options.fields)) {\n this.numWeights = this.options.fields.length;\n var converters = getConverters(this.options.fields);\n this.extractor = converters.extractor;\n this.creator = converters.creator;\n } else {\n throw new Error('Invalid fields definition');\n }\n\n if (this.options.gridType === 'rect') {\n this.nodeType = NodeSquare;\n this.gridDim = {\n x: x,\n y: y\n };\n } else {\n this.nodeType = NodeHexagonal;\n var hx = this.x - Math.floor(this.y / 2);\n this.gridDim = {\n x: hx,\n y: this.y,\n z: -(0 - hx - this.y)\n };\n }\n\n this.torus = this.options.torus;\n this.distanceMethod = this.torus ? 'getDistanceTorus' : 'getDistance';\n\n this.distance = this.options.distance;\n\n this.maxDistance = getMaxDistance(this.distance, this.numWeights);\n\n if (reload === true) { // For model loading\n this.done = true;\n return;\n }\n if (!(x > 0 && y > 0)) {\n throw new Error('x and y must be positive');\n }\n\n this.times = {\n findBMU: 0,\n adjust: 0\n };\n\n this.randomizer = this.options.randomizer;\n\n this.iterationCount = 0;\n this.iterations = this.options.iterations;\n\n this.startLearningRate = this.learningRate = this.options.learningRate;\n\n this.mapRadius = Math.floor(Math.max(x, y) / 2);\n\n this.algorithmMethod = this.options.method;\n\n this._initNodes();\n\n this.done = false;\n}\n\nSOM.load = function loadModel(model, distance) {\n if (model.name === 'SOM') {\n var x = model.data.length,\n y = model.data[0].length;\n if (distance) {\n model.options.distance = distance;\n } else if (model.options.distance) {\n model.options.distance = eval('(' + model.options.distance + ')');\n }\n var som = new SOM(x, y, model.options, true);\n som.nodes = new Array(x);\n for (var i = 0; i < x; i++) {\n som.nodes[i] = new Array(y);\n for (var j = 0; j < y; j++) {\n som.nodes[i][j] = new som.nodeType(i, j, model.data[i][j], som);\n }\n }\n return som;\n } else {\n throw new Error('expecting a SOM model');\n }\n};\n\nSOM.prototype.export = function exportModel(includeDistance) {\n if (!this.done) {\n throw new Error('model is not ready yet');\n }\n var model = {\n name: 'SOM'\n };\n model.options = {\n fields: this.options.fields,\n gridType: this.options.gridType,\n torus: this.options.torus\n };\n model.data = new Array(this.x);\n for (var i = 0; i < this.x; i++) {\n model.data[i] = new Array(this.y);\n for (var j = 0; j < this.y; j++) {\n model.data[i][j] = this.nodes[i][j].weights;\n }\n }\n if (includeDistance) {\n model.options.distance = this.distance.toString();\n }\n return model;\n};\n\nSOM.prototype._initNodes = function initNodes() {\n var now = Date.now(),\n i, j, k;\n this.nodes = new Array(this.x);\n for (i = 0; i < this.x; i++) {\n this.nodes[i] = new Array(this.y);\n for (j = 0; j < this.y; j++) {\n var weights = new Array(this.numWeights);\n for (k = 0; k < this.numWeights; k++) {\n weights[k] = this.randomizer();\n }\n this.nodes[i][j] = new this.nodeType(i, j, weights, this);\n }\n }\n this.times.initNodes = Date.now() - now;\n};\n\nSOM.prototype.setTraining = function setTraining(trainingSet) {\n if (this.trainingSet) {\n throw new Error('training set has already been set');\n }\n var now = Date.now();\n var convertedSet = trainingSet;\n var i, l = trainingSet.length;\n if (this.extractor) {\n convertedSet = new Array(l);\n for (i = 0; i < l; i++) {\n convertedSet[i] = this.extractor(trainingSet[i]);\n }\n }\n this.numIterations = this.iterations * l;\n\n if (this.algorithmMethod === 'random') {\n this.timeConstant = this.numIterations / Math.log(this.mapRadius);\n } else {\n this.timeConstant = l / Math.log(this.mapRadius);\n }\n this.trainingSet = convertedSet;\n this.times.setTraining = Date.now() - now;\n};\n\nSOM.prototype.trainOne = function trainOne() {\n if (this.done) {\n\n return false;\n\n } else if (this.numIterations-- > 0) {\n\n var neighbourhoodRadius,\n trainingValue,\n trainingSetFactor;\n\n if (this.algorithmMethod === 'random') { // Pick a random value of the training set at each step\n neighbourhoodRadius = this.mapRadius * Math.exp(-this.iterationCount / this.timeConstant);\n trainingValue = getRandomValue(this.trainingSet, this.randomizer);\n this._adjust(trainingValue, neighbourhoodRadius);\n this.learningRate = this.startLearningRate * Math.exp(-this.iterationCount / this.numIterations);\n } else { // Get next input vector\n trainingSetFactor = -Math.floor(this.iterationCount / this.trainingSet.length);\n neighbourhoodRadius = this.mapRadius * Math.exp(trainingSetFactor / this.timeConstant);\n trainingValue = this.trainingSet[this.iterationCount % this.trainingSet.length];\n this._adjust(trainingValue, neighbourhoodRadius);\n if (((this.iterationCount + 1) % this.trainingSet.length) === 0) {\n this.learningRate = this.startLearningRate * Math.exp(trainingSetFactor / Math.floor(this.numIterations / this.trainingSet.length));\n }\n }\n\n this.iterationCount++;\n\n return true;\n\n } else {\n\n this.done = true;\n return false;\n\n }\n};\n\nSOM.prototype._adjust = function adjust(trainingValue, neighbourhoodRadius) {\n var now = Date.now(),\n x, y, dist, influence;\n\n var bmu = this._findBestMatchingUnit(trainingValue);\n\n var now2 = Date.now();\n this.times.findBMU += now2 - now;\n\n var radiusLimit = Math.floor(neighbourhoodRadius);\n var xMin = bmu.x - radiusLimit,\n xMax = bmu.x + radiusLimit,\n yMin = bmu.y - radiusLimit,\n yMax = bmu.y + radiusLimit;\n\n for (x = xMin; x <= xMax; x++) {\n var theX = x;\n if (x < 0) {\n theX += this.x;\n } else if (x >= this.x) {\n theX -= this.x;\n }\n for (y = yMin; y <= yMax; y++) {\n var theY = y;\n if (y < 0) {\n theY += this.y;\n } else if (y >= this.y) {\n theY -= this.y;\n }\n\n dist = bmu[this.distanceMethod](this.nodes[theX][theY]);\n\n if (dist < neighbourhoodRadius) {\n influence = Math.exp(-dist / (2 * neighbourhoodRadius));\n this.nodes[theX][theY].adjustWeights(trainingValue, this.learningRate, influence);\n }\n\n }\n }\n\n this.times.adjust += (Date.now() - now2);\n\n};\n\nSOM.prototype.train = function train(trainingSet) {\n if (!this.done) {\n this.setTraining(trainingSet);\n while (this.trainOne()) {\n }\n }\n};\n\nSOM.prototype.getConvertedNodes = function getConvertedNodes() {\n var result = new Array(this.x);\n for (var i = 0; i < this.x; i++) {\n result[i] = new Array(this.y);\n for (var j = 0; j < this.y; j++) {\n var node = this.nodes[i][j];\n result[i][j] = this.creator ? this.creator(node.weights) : node.weights;\n }\n }\n return result;\n};\n\nSOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) {\n\n var bmu,\n lowest = Infinity,\n dist;\n\n for (var i = 0; i < this.x; i++) {\n for (var j = 0; j < this.y; j++) {\n dist = this.distance(this.nodes[i][j].weights, candidate);\n if (dist < lowest) {\n lowest = dist;\n bmu = this.nodes[i][j];\n }\n }\n }\n\n return bmu;\n\n};\n\nSOM.prototype.predict = function predict(data, computePosition) {\n if (typeof data === 'boolean') {\n computePosition = data;\n data = null;\n }\n if (!data) {\n data = this.trainingSet;\n }\n if (Array.isArray(data) && (Array.isArray(data[0]) || (typeof data[0] === 'object'))) { // predict a dataset\n var self = this;\n return data.map(function (element) {\n return self._predict(element, computePosition);\n });\n } else { // predict a single element\n return this._predict(data, computePosition);\n }\n};\n\nSOM.prototype._predict = function _predict(element, computePosition) {\n if (!Array.isArray(element)) {\n element = this.extractor(element);\n }\n var bmu = this._findBestMatchingUnit(element);\n var result = [bmu.x, bmu.y];\n if (computePosition) {\n result[2] = bmu.getPosition(element);\n }\n return result;\n};\n\n// As seen in http://www.scholarpedia.org/article/Kohonen_network\nSOM.prototype.getQuantizationError = function getQuantizationError() {\n var fit = this.getFit(),\n l = fit.length,\n sum = 0;\n for (var i = 0; i < l; i++) {\n sum += fit[i];\n }\n return sum / l;\n};\n\nSOM.prototype.getFit = function getFit(dataset) {\n if (!dataset) {\n dataset = this.trainingSet;\n }\n var l = dataset.length,\n bmu,\n result = new Array(l);\n for (var i = 0; i < l; i++) {\n bmu = this._findBestMatchingUnit(dataset[i]);\n result[i] = Math.sqrt(this.distance(dataset[i], bmu.weights));\n }\n return result;\n};\n\nfunction getConverters(fields) {\n var l = fields.length,\n normalizers = new Array(l),\n denormalizers = new Array(l);\n for (var i = 0; i < l; i++) {\n normalizers[i] = getNormalizer(fields[i].range);\n denormalizers[i] = getDenormalizer(fields[i].range);\n }\n return {\n extractor: function extractor(value) {\n var result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = normalizers[i](value[fields[i].name]);\n }\n return result;\n },\n creator: function creator(value) {\n var result = {};\n for (var i = 0; i < l; i++) {\n result[fields[i].name] = denormalizers[i](value[i]);\n }\n return result;\n }\n };\n}\n\nfunction getNormalizer(minMax) {\n return function normalizer(value) {\n return (value - minMax[0]) / (minMax[1] - minMax[0]);\n };\n}\n\nfunction getDenormalizer(minMax) {\n return function denormalizer(value) {\n return (minMax[0] + value * (minMax[1] - minMax[0]));\n };\n}\n\nfunction squareEuclidean(a, b) {\n var d = 0;\n for (var i = 0, ii = a.length; i < ii; i++) {\n d += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return d;\n}\n\nfunction getRandomValue(arr, randomizer) {\n return arr[Math.floor(randomizer() * arr.length)];\n}\n\nfunction getMaxDistance(distance, numWeights) {\n var zero = new Array(numWeights),\n one = new Array(numWeights);\n for (var i = 0; i < numWeights; i++) {\n zero[i] = 0;\n one[i] = 1;\n }\n return distance(zero, one);\n}\n\nmodule.exports = SOM;","var NodeSquare = require('./node-square');\n\nfunction NodeHexagonal(x, y, weights, som) {\n\n NodeSquare.call(this, x, y, weights, som);\n\n this.hX = x - Math.floor(y / 2);\n this.z = 0 - this.hX - y;\n\n}\n\nNodeHexagonal.prototype = new NodeSquare;\nNodeHexagonal.prototype.constructor = NodeHexagonal;\n\nNodeHexagonal.prototype.getDistance = function getDistanceHexagonal(otherNode) {\n return Math.max(Math.abs(this.hX - otherNode.hX), Math.abs(this.y - otherNode.y), Math.abs(this.z - otherNode.z));\n};\n\nNodeHexagonal.prototype.getDistanceTorus = function getDistanceTorus(otherNode) {\n var distX = Math.abs(this.hX - otherNode.hX),\n distY = Math.abs(this.y - otherNode.y),\n distZ = Math.abs(this.z - otherNode.z);\n return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY), Math.min(distZ, this.som.gridDim.z - distZ));\n};\n\nNodeHexagonal.prototype.getPosition = function getPosition() {\n throw new Error('Unimplemented : cannot get position of the points for hexagonal grid');\n};\n\nmodule.exports = NodeHexagonal;","'use strict';\n\nvar mlMatrix = require('ml-matrix');\n\n/**\n * Calculate current error\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} parameters - Array of current parameter values\n * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @return {number}\n */\nfunction errorCalculation(\n data,\n parameters,\n parameterizedFunction\n) {\n var error = 0;\n const func = parameterizedFunction(parameters);\n\n for (var i = 0; i < data.x.length; i++) {\n error += Math.abs(data.y[i] - func(data.x[i]));\n }\n\n return error;\n}\n\n/**\n * Difference of the matrix function over the parameters\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} evaluatedData - Array of previous evaluated function values\n * @param {Array} params - Array of previous parameter values\n * @param {number} gradientDifference - Adjustment for decrease the damping parameter\n * @param {function} paramFunction - The parameters and returns a function with the independent variable as a parameter\n * @return {Matrix}\n */\nfunction gradientFunction(\n data,\n evaluatedData,\n params,\n gradientDifference,\n paramFunction\n) {\n const n = params.length;\n const m = data.x.length;\n\n var ans = new Array(n);\n\n for (var param = 0; param < n; param++) {\n ans[param] = new Array(m);\n var auxParams = params.concat();\n auxParams[param] += gradientDifference;\n var funcParam = paramFunction(auxParams);\n\n for (var point = 0; point < m; point++) {\n ans[param][point] = evaluatedData[point] - funcParam(data.x[point]);\n }\n }\n return new mlMatrix.Matrix(ans);\n}\n\n/**\n * Matrix function over the samples\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} evaluatedData - Array of previous evaluated function values\n * @return {Matrix}\n */\nfunction matrixFunction(data, evaluatedData) {\n const m = data.x.length;\n\n var ans = new Array(m);\n\n for (var point = 0; point < m; point++) {\n ans[point] = data.y[point] - evaluatedData[point];\n }\n\n return new mlMatrix.Matrix([ans]);\n}\n\n/**\n * Iteration for Levenberg-Marquardt\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} params - Array of previous parameter values\n * @param {number} damping - Levenberg-Marquardt parameter\n * @param {number} gradientDifference - Adjustment for decrease the damping parameter\n * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @return {Array}\n */\nfunction step(\n data,\n params,\n damping,\n gradientDifference,\n parameterizedFunction\n) {\n var identity = mlMatrix.Matrix.eye(params.length).mul(\n damping * gradientDifference * gradientDifference\n );\n\n var l = data.x.length;\n var evaluatedData = new Array(l);\n const func = parameterizedFunction(params);\n for (var i = 0; i < l; i++) {\n evaluatedData[i] = func(data.x[i]);\n }\n var gradientFunc = gradientFunction(\n data,\n evaluatedData,\n params,\n gradientDifference,\n parameterizedFunction\n );\n var matrixFunc = matrixFunction(data, evaluatedData).transposeView();\n var inverseMatrix = mlMatrix.inverse(\n identity.add(gradientFunc.mmul(gradientFunc.transposeView()))\n );\n params = new mlMatrix.Matrix([params]);\n params = params.sub(\n inverseMatrix\n .mmul(gradientFunc)\n .mmul(matrixFunc)\n .mul(gradientDifference)\n .transposeView()\n );\n\n return params.to1DArray();\n}\n\n/**\n * Curve fitting algorithm\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @param {object} [options] - Options object\n * @param {number} [options.damping] - Levenberg-Marquardt parameter\n * @param {number} [options.gradientDifference = 10e-2] - Adjustment for decrease the damping parameter\n * @param {Array} [options.initialValues] - Array of initial parameter values\n * @param {number} [options.maxIterations = 100] - Maximum of allowed iterations\n * @param {number} [options.errorTolerance = 10e-3] - Minimum uncertainty allowed for each point\n * @return {{parameterValues: Array, parameterError: number, iterations: number}}\n */\nfunction levenbergMarquardt(\n data,\n parameterizedFunction,\n options = {}\n) {\n let {\n maxIterations = 100,\n gradientDifference = 10e-2,\n damping = 0,\n errorTolerance = 10e-3,\n initialValues\n } = options;\n\n if (damping <= 0) {\n throw new Error('The damping option must be a positive number');\n } else if (!data.x || !data.y) {\n throw new Error('The data parameter must have x and y elements');\n } else if (\n !Array.isArray(data.x) ||\n data.x.length < 2 ||\n !Array.isArray(data.y) ||\n data.y.length < 2\n ) {\n throw new Error(\n 'The data parameter elements must be an array with more than 2 points'\n );\n } else {\n let dataLen = data.x.length;\n if (dataLen !== data.y.length) {\n throw new Error('The data parameter elements must have the same size');\n }\n }\n\n var parameters =\n initialValues || new Array(parameterizedFunction.length).fill(1);\n\n if (!Array.isArray(parameters)) {\n throw new Error('initialValues must be an array');\n }\n\n var error = errorCalculation(data, parameters, parameterizedFunction);\n\n var converged = error <= errorTolerance;\n\n for (\n var iteration = 0;\n iteration < maxIterations && !converged;\n iteration++\n ) {\n parameters = step(\n data,\n parameters,\n damping,\n gradientDifference,\n parameterizedFunction\n );\n error = errorCalculation(data, parameters, parameterizedFunction);\n converged = error <= errorTolerance;\n }\n\n return {\n parameterValues: parameters,\n parameterError: error,\n iterations: iteration\n };\n}\n\nmodule.exports = levenbergMarquardt;\n","import HashTable from 'ml-hash-table';\n\nexport class SparseMatrix {\n constructor(rows, columns, options = {}) {\n if (rows instanceof SparseMatrix) { // clone\n const other = rows;\n this._init(other.rows, other.columns, other.elements.clone(), other.threshold);\n return;\n }\n\n if (Array.isArray(rows)) {\n const matrix = rows;\n rows = matrix.length;\n options = columns || {};\n columns = matrix[0].length;\n this._init(rows, columns, new HashTable(options), options.threshold);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n var value = matrix[i][j];\n if (this.threshold && Math.abs(value) < this.threshold) value = 0;\n if (value !== 0) {\n this.elements.set(i * columns + j, matrix[i][j]);\n }\n }\n }\n } else {\n this._init(rows, columns, new HashTable(options), options.threshold);\n }\n }\n\n _init(rows, columns, elements, threshold) {\n this.rows = rows;\n this.columns = columns;\n this.elements = elements;\n this.threshold = threshold || 0;\n }\n\n static eye(rows = 1, columns = rows) {\n const min = Math.min(rows, columns);\n const matrix = new SparseMatrix(rows, columns, {initialCapacity: min});\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, 1);\n }\n return matrix;\n }\n\n clone() {\n return new SparseMatrix(this);\n }\n\n to2DArray() {\n const copy = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n copy[i] = new Array(this.columns);\n for (var j = 0; j < this.columns; j++) {\n copy[i][j] = this.get(i, j);\n }\n }\n return copy;\n }\n\n isSquare() {\n return this.rows === this.columns;\n }\n\n isSymmetric() {\n if (!this.isSquare()) return false;\n\n var symmetric = true;\n this.forEachNonZero((i, j, v) => {\n if (this.get(j, i) !== v) {\n symmetric = false;\n return false;\n }\n return v;\n });\n return symmetric;\n }\n\n /**\n * Search for the wither band in the main diagonals\n * @return {number}\n */\n bandWidth() {\n let min = this.columns;\n let max = -1;\n this.forEachNonZero((i, j, v) => {\n let diff = i - j;\n min = Math.min(min, diff);\n max = Math.max(max, diff);\n return v;\n });\n return max - min;\n }\n\n /**\n * Test if a matrix is consider banded using a threshold\n * @param {number} width\n * @return {boolean}\n */\n isBanded(width) {\n let bandWidth = this.bandWidth();\n return bandWidth <= width;\n }\n\n get cardinality() {\n return this.elements.size;\n }\n\n get size() {\n return this.rows * this.columns;\n }\n\n get(row, column) {\n return this.elements.get(row * this.columns + column);\n }\n\n set(row, column, value) {\n if (this.threshold && Math.abs(value) < this.threshold) value = 0;\n if (value === 0) {\n this.elements.remove(row * this.columns + column);\n } else {\n this.elements.set(row * this.columns + column, value);\n }\n return this;\n }\n\n mmul(other) {\n if (this.columns !== other.rows) {\n // eslint-disable-next-line no-console\n console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\n }\n\n const m = this.rows;\n const p = other.columns;\n\n const result = new SparseMatrix(m, p);\n this.forEachNonZero((i, j, v1) => {\n other.forEachNonZero((k, l, v2) => {\n if (j === k) {\n result.set(i, l, result.get(i, l) + v1 * v2);\n }\n return v2;\n });\n return v1;\n });\n return result;\n }\n\n kroneckerProduct(other) {\n const m = this.rows;\n const n = this.columns;\n const p = other.rows;\n const q = other.columns;\n\n const result = new SparseMatrix(m * p, n * q, {\n initialCapacity: this.cardinality * other.cardinality\n });\n this.forEachNonZero((i, j, v1) => {\n other.forEachNonZero((k, l, v2) => {\n result.set(p * i + k, q * j + l, v1 * v2);\n return v2;\n });\n return v1;\n });\n return result;\n }\n\n forEachNonZero(callback) {\n this.elements.forEachPair((key, value) => {\n const i = (key / this.columns) | 0;\n const j = key % this.columns;\n let r = callback(i, j, value);\n if (r === false) return false; // stop iteration\n if (this.threshold && Math.abs(r) < this.threshold) r = 0;\n if (r !== value) {\n if (r === 0) {\n this.elements.remove(key, true);\n } else {\n this.elements.set(key, r);\n }\n }\n return true;\n });\n this.elements.maybeShrinkCapacity();\n return this;\n }\n\n getNonZeros() {\n const cardinality = this.cardinality;\n const rows = new Array(cardinality);\n const columns = new Array(cardinality);\n const values = new Array(cardinality);\n var idx = 0;\n this.forEachNonZero((i, j, value) => {\n rows[idx] = i;\n columns[idx] = j;\n values[idx] = value;\n idx++;\n return value;\n });\n return {rows, columns, values};\n }\n\n setThreshold(newThreshold) {\n if (newThreshold !== 0 && newThreshold !== this.threshold) {\n this.threshold = newThreshold;\n this.forEachNonZero((i, j, v) => v);\n }\n return this;\n }\n\n /**\n * @return {SparseMatrix} - New transposed sparse matrix\n */\n transpose() {\n let trans = new SparseMatrix(this.columns, this.rows, {initialCapacity: this.cardinality});\n this.forEachNonZero((i, j, value) => {\n trans.set(j, i, value);\n return value;\n });\n return trans;\n }\n}\n\nSparseMatrix.prototype.klass = 'Matrix';\n\nSparseMatrix.identity = SparseMatrix.eye;\nSparseMatrix.prototype.tensorProduct = SparseMatrix.prototype.kroneckerProduct;\n\n/*\n Add dynamically instance and static methods for mathematical operations\n */\n\nvar inplaceOperator = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\nvar inplaceOperatorScalar = `\n(function %name%S(value) {\n this.forEachNonZero((i, j, v) => v %op% value);\n return this;\n})\n`;\n\nvar inplaceOperatorMatrix = `\n(function %name%M(matrix) {\n matrix.forEachNonZero((i, j, v) => {\n this.set(i, j, this.get(i, j) %op% v);\n return v;\n });\n return this;\n})\n`;\n\nvar staticOperator = `\n(function %name%(matrix, value) {\n var newMatrix = new SparseMatrix(matrix);\n return newMatrix.%name%(value);\n})\n`;\n\nvar inplaceMethod = `\n(function %name%() {\n this.forEachNonZero((i, j, v) => %method%(v));\n return this;\n})\n`;\n\nvar staticMethod = `\n(function %name%(matrix) {\n var newMatrix = new SparseMatrix(matrix);\n return newMatrix.%name%();\n})\n`;\n\nconst operators = [\n // Arithmetic operators\n ['+', 'add'],\n ['-', 'sub', 'subtract'],\n ['*', 'mul', 'multiply'],\n ['/', 'div', 'divide'],\n ['%', 'mod', 'modulus'],\n // Bitwise operators\n ['&', 'and'],\n ['|', 'or'],\n ['^', 'xor'],\n ['<<', 'leftShift'],\n ['>>', 'signPropagatingRightShift'],\n ['>>>', 'rightShift', 'zeroFillRightShift']\n];\n\nfor (const operator of operators) {\n for (let i = 1; i < operator.length; i++) {\n SparseMatrix.prototype[operator[i]] = eval(fillTemplateFunction(inplaceOperator, {name: operator[i], op: operator[0]}));\n SparseMatrix.prototype[operator[i] + 'S'] = eval(fillTemplateFunction(inplaceOperatorScalar, {name: operator[i] + 'S', op: operator[0]}));\n SparseMatrix.prototype[operator[i] + 'M'] = eval(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[i] + 'M', op: operator[0]}));\n\n SparseMatrix[operator[i]] = eval(fillTemplateFunction(staticOperator, {name: operator[i]}));\n }\n}\n\nvar methods = [\n ['~', 'not']\n];\n\n[\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\n].forEach(function (mathMethod) {\n methods.push(['Math.' + mathMethod, mathMethod]);\n});\n\nfor (const method of methods) {\n for (let i = 1; i < method.length; i++) {\n SparseMatrix.prototype[method[i]] = eval(fillTemplateFunction(inplaceMethod, {name: method[i], method: method[0]}));\n SparseMatrix[method[i]] = eval(fillTemplateFunction(staticMethod, {name: method[i]}));\n }\n}\n\nfunction fillTemplateFunction(template, values) {\n for (const i in values) {\n template = template.replace(new RegExp('%' + i + '%', 'g'), values[i]);\n }\n return template;\n}\n","module.exports = newArray\n\nfunction newArray (n, value) {\n n = n || 0\n var array = new Array(n)\n for (var i = 0; i < n; i++) {\n array[i] = value\n }\n return array\n}\n","const binarySearch = require('binary-search');\nconst sortAsc = require('num-sort').asc;\n\nconst largestPrime = 0x7fffffff;\n\nconst primeNumbers = [\n //chunk #0\n largestPrime, // 2^31-1\n\n //chunk #1\n 5, 11, 23, 47, 97, 197, 397, 797, 1597, 3203, 6421, 12853, 25717, 51437, 102877, 205759,\n 411527, 823117, 1646237, 3292489, 6584983, 13169977, 26339969, 52679969, 105359939,\n 210719881, 421439783, 842879579, 1685759167,\n\n //chunk #2\n 433, 877, 1759, 3527, 7057, 14143, 28289, 56591, 113189, 226379, 452759, 905551, 1811107,\n 3622219, 7244441, 14488931, 28977863, 57955739, 115911563, 231823147, 463646329, 927292699,\n 1854585413,\n\n //chunk #3\n 953, 1907, 3821, 7643, 15287, 30577, 61169, 122347, 244703, 489407, 978821, 1957651, 3915341,\n 7830701, 15661423, 31322867, 62645741, 125291483, 250582987, 501165979, 1002331963,\n 2004663929,\n\n //chunk #4\n 1039, 2081, 4177, 8363, 16729, 33461, 66923, 133853, 267713, 535481, 1070981, 2141977, 4283963,\n 8567929, 17135863, 34271747, 68543509, 137087021, 274174111, 548348231, 1096696463,\n\n //chunk #5\n 31, 67, 137, 277, 557, 1117, 2237, 4481, 8963, 17929, 35863, 71741, 143483, 286973, 573953,\n 1147921, 2295859, 4591721, 9183457, 18366923, 36733847, 73467739, 146935499, 293871013,\n 587742049, 1175484103,\n\n //chunk #6\n 599, 1201, 2411, 4831, 9677, 19373, 38747, 77509, 155027, 310081, 620171, 1240361, 2480729,\n 4961459, 9922933, 19845871, 39691759, 79383533, 158767069, 317534141, 635068283, 1270136683,\n\n //chunk #7\n 311, 631, 1277, 2557, 5119, 10243, 20507, 41017, 82037, 164089, 328213, 656429, 1312867,\n 2625761, 5251529, 10503061, 21006137, 42012281, 84024581, 168049163, 336098327, 672196673,\n 1344393353,\n\n //chunk #8\n 3, 7, 17, 37, 79, 163, 331, 673, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899,\n 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557,\n 359339171, 718678369, 1437356741,\n\n //chunk #9\n 43, 89, 179, 359, 719, 1439, 2879, 5779, 11579, 23159, 46327, 92657, 185323, 370661, 741337,\n 1482707, 2965421, 5930887, 11861791, 23723597, 47447201, 94894427, 189788857, 379577741,\n 759155483, 1518310967,\n\n //chunk #10\n 379, 761, 1523, 3049, 6101, 12203, 24407, 48817, 97649, 195311, 390647, 781301, 1562611,\n 3125257, 6250537, 12501169, 25002389, 50004791, 100009607, 200019221, 400038451, 800076929,\n 1600153859,\n\n //chunk #11\n 13, 29, 59, 127, 257, 521, 1049, 2099, 4201, 8419, 16843, 33703, 67409, 134837, 269683,\n 539389, 1078787, 2157587, 4315183, 8630387, 17260781, 34521589, 69043189, 138086407,\n 276172823, 552345671, 1104691373,\n\n //chunk #12\n 19, 41, 83, 167, 337, 677,\n 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899,\n 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557,\n 359339171, 718678369, 1437356741,\n\n //chunk #13\n 53, 107, 223, 449, 907, 1823, 3659, 7321, 14653, 29311, 58631, 117269,\n 234539, 469099, 938207, 1876417, 3752839, 7505681, 15011389, 30022781,\n 60045577, 120091177, 240182359, 480364727, 960729461, 1921458943\n];\n\nprimeNumbers.sort(sortAsc);\n\nfunction nextPrime(value) {\n let index = binarySearch(primeNumbers, value, sortAsc);\n if (index < 0) {\n index = ~index;\n }\n return primeNumbers[index];\n}\n\nexports.nextPrime = nextPrime;\nexports.largestPrime = largestPrime;\n","'use strict';\nmodule.exports = Number.isNaN || function (x) {\n\treturn x !== x;\n};\n","\"use strict\";\n\nexports.additiveSymmetric = require('./distances/additiveSymmetric');\nexports.avg = require('./distances/avg');\nexports.bhattacharyya = require('./distances/bhattacharyya');\nexports.canberra = require('./distances/canberra');\nexports.chebyshev = require('./distances/chebyshev');\nexports.clark = require('./distances/clark');\nexports.czekanowski = require('./distances/czekanowski');\nexports.dice = require('./distances/dice');\nexports.divergence = require('./distances/divergence');\nexports.euclidean = require('ml-distance-euclidean');\nexports.fidelity = require('./distances/fidelity');\nexports.gower = require('./distances/gower');\nexports.harmonicMean = require('./distances/harmonicMean');\nexports.hellinger = require('./distances/hellinger');\nexports.innerProduct = require('./distances/innerProduct');\nexports.intersection = require('./distances/intersection');\nexports.jaccard = require('./distances/jaccard');\nexports.jeffreys = require('./distances/jeffreys');\nexports.jensenDifference = require('./distances/jensenDifference');\nexports.jensenShannon = require('./distances/jensenShannon');\nexports.kdivergence = require('./distances/kdivergence');\nexports.kulczynski = require('./distances/kulczynski');\nexports.kullbackLeibler = require('./distances/kullbackLeibler');\nexports.kumarHassebrook = require('./distances/kumarHassebrook');\nexports.kumarJohnson = require('./distances/kumarJohnson');\nexports.lorentzian = require('./distances/lorentzian');\nexports.manhattan = require('./distances/manhattan');\nexports.matusita = require('./distances/matusita');\nexports.minkowski = require('./distances/minkowski');\nexports.motyka = require('./distances/motyka');\nexports.neyman = require('./distances/neyman');\nexports.pearson = require('./distances/pearson');\nexports.probabilisticSymmetric = require('./distances/probabilisticSymmetric');\nexports.ruzicka = require('./distances/ruzicka');\nexports.soergel = require('./distances/soergel');\nexports.sorensen = require('./distances/sorensen');\nexports.squared = require('./distances/squared');\nexports.squaredChord = require('./distances/squaredChord');\nexports.squaredEuclidean = require('ml-distance-euclidean').squared;\nexports.taneja = require('./distances/taneja');\nexports.tanimoto = require('./distances/tanimoto');\nexports.topsoe = require('./distances/topsoe');\nexports.tree = require('ml-tree-similarity');\nexports.waveHedges = require('./distances/waveHedges');\n","module.exports = function additiveSymmetric(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i]) * (a[i] + b[i])) / (a[i] * b[i]);\n }\n return 2 * d;\n};\n","module.exports = function avg(a, b) {\n var ii = a.length,\n max = 0,\n ans = 0,\n aux = 0;\n for (var i = 0; i < ii ; i++) {\n aux = Math.abs(a[i] - b[i]);\n ans += aux;\n if (max < aux) {\n max = aux;\n }\n }\n return (max + ans) / 2;\n};\n","module.exports = function bhattacharyya(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return - Math.log(ans);\n};\n","module.exports = function canberra(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.abs(a[i] - b[i]) / (a[i] + b[i]);\n }\n return ans;\n};\n","module.exports = function chebyshev(a, b) {\n var ii = a.length,\n max = 0,\n aux = 0;\n for (var i = 0; i < ii ; i++) {\n aux = Math.abs(a[i] - b[i]);\n if (max < aux) {\n max = aux;\n }\n }\n return max;\n};\n","module.exports = function clark(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.sqrt(((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i])));\n }\n return 2 * d;\n};\n","'use strict';\n\nconst czekanowskiSimilarity = require('../similarities/czekanowski');\n\nmodule.exports = function czekanowskiDistance(a, b) {\n return 1 - czekanowskiSimilarity(a, b);\n};\n","module.exports = function divergence(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i]));\n }\n return 2 * d;\n};\n","module.exports = function fidelity(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return ans;\n};\n","module.exports = function gower(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.abs(a[i] - b[i]);\n }\n return ans / ii;\n};\n","module.exports = function harmonicMean(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] * b[i]) / (a[i] + b[i]);\n }\n return 2 * ans;\n};\n","module.exports = function hellinger(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return 2 * Math.sqrt(1 - ans);\n};\n","module.exports = function innerProduct(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * b[i];\n }\n return ans;\n};\n","module.exports = function jeffreys(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] - b[i]) * Math.log(a[i] / b[i]);\n }\n return ans;\n};\n","module.exports = function jensenDifference(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += ((a[i] * Math.log(a[i]) + b[i] * Math.log(b[i])) / 2) - ((a[i] + b[i]) / 2) * Math.log((a[i] + b[i]) / 2);\n }\n return ans;\n};\n","module.exports = function jensenShannon(a, b) {\n var ii = a.length,\n p = 0,\n q = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * Math.log(2 * a[i] / (a[i] + b[i]));\n q += b[i] * Math.log(2 * b[i] / (a[i] + b[i]));\n }\n return (p + q) / 2;\n};\n","module.exports = function kdivergence(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i]));\n }\n return ans;\n};\n","module.exports = function kullbackLeibler(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(a[i] / b[i]);\n }\n return ans;\n};\n","module.exports = function kumarHassebrook(a, b) {\n var ii = a.length,\n p = 0,\n p2 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * b[i];\n p2 += a[i] * a[i];\n q2 += b[i] * b[i];\n }\n return p / (p2 + q2 - p);\n};\n","module.exports = function kumarJohnson(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.pow(a[i] * a[i] - b[i] * b[i],2) / (2 * Math.pow(a[i] * b[i],1.5));\n }\n return ans;\n};\n","module.exports = function lorentzian(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.log(Math.abs(a[i] - b[i]) + 1);\n }\n return ans;\n};\n","module.exports = function manhattan(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.abs(a[i] - b[i]);\n }\n return d;\n};\n","module.exports = function matusita(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return Math.sqrt(2 - 2 * ans);\n};\n","module.exports = function minkowski(a, b, p) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.pow(Math.abs(a[i] - b[i]),p);\n }\n return Math.pow(d,(1/p));\n};\n","module.exports = function neyman(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / a[i];\n }\n return d;\n};\n","module.exports = function pearson(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / b[i];\n }\n return d;\n};\n","module.exports = function probabilisticSymmetric(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]);\n }\n return 2 * d;\n};\n","module.exports = function ruzicka(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.min(a[i],b[i]);\n down += Math.max(a[i],b[i]);\n }\n return up / down;\n};\n","module.exports = function soergel(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += Math.max(a[i],b[i]);\n }\n return up / down;\n};\n","module.exports = function sorensen(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += a[i] + b[i];\n }\n return up / down;\n};\n","module.exports = function squared(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]);\n }\n return d;\n};\n","module.exports = function taneja(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] + b[i]) / 2 * Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i])));\n }\n return ans;\n};\n","var tanimotoS = require('./../similarities/tanimoto');\n\nmodule.exports = function tanimoto(a, b, bitvector) {\n if (bitvector)\n return 1 - tanimotoS(a, b, bitvector);\n else {\n var ii = a.length,\n p = 0,\n q = 0,\n m = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i];\n q += b[i];\n m += Math.min(a[i],b[i]);\n }\n return (p + q - 2 * m) / (p + q - m);\n }\n};\n","module.exports = function topsoe(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])) + b[i] * Math.log(2 * b[i] / (a[i] + b[i]));\n }\n return ans;\n};\n","\"use strict\";\n\n/**\n * Function that creates the tree\n * @param {Array } X - chemical shifts of the signal\n * @param {Array } Y - intensity of the signal\n * @param {number} from - the low limit of x\n * @param {number} to - the top limit of x\n * @param {number} minWindow - smallest range to accept in x\n * @param {number} threshold - smallest range to accept in y\n * @returns {{sum: number, center: number, left: {json}, right: {json}}}\n * left and right have the same structure than the parent, or have a\n * undefined value if are leafs\n */\nfunction createTree (X, Y, from, to, minWindow, threshold) {\n minWindow = minWindow || 0.16;\n threshold = threshold || 0.01;\n if ((to - from) < minWindow)\n return undefined;\n var sum = 0;\n for (var i = 0; X[i] < to; i++) {\n if (X[i] > from)\n sum += Y[i];\n }\n if (sum < threshold) {\n return undefined;\n }\n var center = 0;\n for (var j = 0; X[j] < to; j++) {\n if (X[i] > from)\n center += X[j] * Y[j];\n }\n center = center / sum;\n if (((center - from) < 10e-6) || ((to - center) < 10e-6)) return undefined;\n if ((center - from) < (minWindow /4)) {\n return createTree(X, Y, center, to, minWindow, threshold);\n }\n else {\n if ((to - center) < (minWindow / 4)) {\n return createTree(X, Y, from, center, minWindow, threshold);\n }\n else {\n return {\n 'sum': sum,\n 'center': center,\n 'left': createTree(X, Y, from, center, minWindow, threshold),\n 'right': createTree(X, Y, center, to, minWindow, threshold)\n };\n }\n }\n}\n\n/**\n * Similarity between two nodes\n * @param {{sum: number, center: number, left: {json}, right: {json}}} a - tree A node\n * @param {{sum: number, center: number, left: {json}, right: {json}}} b - tree B node\n * @param {number} alpha - weights the relative importance of intensity vs. shift match\n * @param {number} beta - weights the relative importance of node matching and children matching\n * @param {number} gamma - controls the attenuation of the effect of chemical shift differences\n * @returns {number} similarity measure between tree nodes\n */\nfunction S(a, b, alpha, beta, gamma) {\n if (a === undefined || b === undefined) {\n return 0;\n }\n else {\n var C = (alpha*Math.min(a.sum, b.sum)/Math.max(a.sum, b.sum)+ (1-alpha)*Math.exp(-gamma*Math.abs(a.center - b.center)));\n }\n return beta*C + (1-beta)*(S(a.left, b.left, alpha, beta, gamma)+S(a.right, b.right, alpha, beta, gamma));\n}\n\n/**\n * @type {number} alpha - weights the relative importance of intensity vs. shift match\n * @type {number} beta - weights the relative importance of node matching and children matching\n * @type {number} gamma - controls the attenuation of the effect of chemical shift differences\n * @type {number} minWindow - smallest range to accept in x\n * @type {number} threshold - smallest range to accept in y\n */\nvar defaultOptions = {\n minWindow: 0.16,\n threshold : 0.01,\n alpha: 0.1,\n beta: 0.33,\n gamma: 0.001\n};\n\n/**\n * Builds a tree based in the spectra and compares this trees\n * @param {{x: Array, y: Array}} A - first spectra to be compared\n * @param {{x: Array, y: Array}} B - second spectra to be compared\n * @param {number} from - the low limit of x\n * @param {number} to - the top limit of x\n * @param {{minWindow: number, threshold: number, alpha: number, beta: number, gamma: number}} options\n * @returns {number} similarity measure between the spectra\n */\nfunction tree(A, B, from, to, options) {\n options = options || {};\n for (var o in defaultOptions)\n if (!options.hasOwnProperty(o)) {\n options[o] = defaultOptions[o];\n }\n var Atree, Btree;\n if (A.sum)\n Atree = A;\n else\n Atree = createTree(A.x, A.y, from, to, options.minWindow, options.threshold);\n if (B.sum)\n Btree = B;\n else\n Btree = createTree(B.x, B.y, from, to, options.minWindow, options.threshold);\n return S(Atree, Btree, options.alpha, options.beta, options.gamma);\n}\n\nmodule.exports = {\n calc: tree,\n createTree: createTree\n};","module.exports = function waveHedges(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += 1 - (Math.min(a[i], b[i]) / Math.max(a[i], b[i]));\n }\n return ans;\n};\n","\"use strict\";\n\nexports.cosine = require('./similarities/cosine');\nexports.czekanowski = require('./similarities/czekanowski');\nexports.dice = require('./similarities/dice');\nexports.intersection = require('./similarities/intersection');\nexports.jaccard = require('./similarities/jaccard');\nexports.kulczynski = require('./similarities/kulczynski');\nexports.motyka = require('./similarities/motyka');\nexports.pearson = require('./similarities/pearson');\nexports.squaredChord = require('./similarities/squaredChord');\nexports.tanimoto = require('./similarities/tanimoto');\n","var diceD = require('./../distances/dice');\n\nmodule.exports = function dice(a, b) {\n return 1 - diceD(a,b);\n};\n","var intersectionD = require('./../distances/intersection');\n\nmodule.exports = function intersection(a, b) {\n return 1 - intersectionD(a,b);\n};\n","var jaccardD = require('./../distances/jaccard');\n\nmodule.exports = function jaccard(a, b) {\n return 1 - jaccardD(a, b);\n};\n","var kulczynskiD = require('./../distances/kulczynski');\n\nmodule.exports = function kulczynski(a, b) {\n return 1 / kulczynskiD(a, b);\n};\n","var motykaD = require('./../distances/motyka');\n\nmodule.exports = function motyka(a, b) {\n return 1 - motykaD(a,b);\n};\n","'use strict';\n\nvar stat=require('ml-stat').array;\nvar cosine=require('./cosine');\n\nmodule.exports = function pearson(a, b) {\n var avgA=stat.mean(a);\n var avgB=stat.mean(b);\n\n var newA=new Array(a.length);\n var newB=new Array(b.length);\n for (var i=0; i a.pred - b.pred);\n } else {\n predP.sort((a, b) => b.pred - a.pred);\n }\n \n const cutoffs = this.cutoffs = [isDistance ? Number.MIN_VALUE : Number.MAX_VALUE];\n const fp = this.fp = [0];\n const tp = this.tp = [0];\n\n var nPos = 0;\n var nNeg = 0;\n\n var currentPred = predP[0].pred;\n var nTp = 0;\n var nFp = 0;\n for (var i = 0; i < predP.length; i++) {\n if (predP[i].pred !== currentPred) {\n cutoffs.push(currentPred);\n fp.push(nFp);\n tp.push(nTp);\n currentPred = predP[i].pred;\n }\n if (predP[i].targ) {\n nPos++;\n nTp++;\n } else {\n nNeg++;\n nFp++;\n }\n }\n cutoffs.push(currentPred);\n fp.push(nFp);\n tp.push(nTp);\n\n const l = cutoffs.length;\n const fn = this.fn = new Array(l);\n const tn = this.tn = new Array(l);\n const nPosPred = this.nPosPred = new Array(l);\n const nNegPred = this.nNegPred = new Array(l);\n\n for (var i = 0; i < l; i++) {\n fn[i] = nPos - tp[i];\n tn[i] = nNeg - fp[i];\n\n nPosPred[i] = tp[i] + fp[i];\n nNegPred[i] = tn[i] + fn[i];\n }\n\n this.nPos = nPos;\n this.nNeg = nNeg;\n this.nSamples = nPos + nNeg;\n }\n\n /**\n * Computes a measure from the prediction object.\n *\n * Many measures are available and can be combined :\n * To create a ROC curve, you need fpr and tpr\n * To create a DET curve, you need fnr and fpr\n * To create a Lift chart, you need rpp and lift\n *\n * Possible measures are : threshold (Threshold), acc (Accuracy), err (Error rate),\n * fpr (False positive rate), tpr (True positive rate), fnr (False negative rate), tnr (True negative rate), ppv (Positive predictive value),\n * npv (Negative predictive value), pcfall (Prediction-conditioned fallout), pcmiss (Prediction-conditioned miss), lift (Lift value), rpp (Rate of positive predictions), rnp (Rate of negative predictions)\n *\n * @param measure - The short name of the measure\n *\n * @return [number]\n */\n getMeasure(measure) {\n if (typeof measure !== 'string') {\n throw new Error('No measure specified');\n }\n if (!measures[measure]) {\n throw new Error(`The specified measure (${measure}) does not exist`);\n }\n return measures[measure](this);\n }\n\n /**\n * Returns the area under the ROC curve\n */\n getAURC() {\n const l = this.cutoffs.length;\n const x = new Array(l);\n const y = new Array(l);\n for (var i = 0; i < l; i++) {\n x[i] = this.fp[i] / this.nNeg;\n y[i] = this.tp[i] / this.nPos;\n }\n var auc = 0;\n for (i = 1; i < l; i++) {\n auc += 0.5 * (x[i] - x[i - 1]) * (y[i] + y[i - 1]);\n }\n return auc;\n }\n\n /**\n * Returns the area under the DET curve\n */\n getAUDC() {\n const l = this.cutoffs.length;\n const x = new Array(l);\n const y = new Array(l);\n for (var i = 0; i < l; i++) {\n x[i] = this.fn[i] / this.nPos;\n y[i] = this.fp[i] / this.nNeg;\n }\n var auc = 0;\n for (i = 1; i < l; i++) {\n auc += 0.5 * (x[i] + x[i - 1]) * (y[i] - y[i - 1]);\n }\n return auc;\n }\n\n getDistribution(options) {\n options = options || {};\n var cutLength = this.cutoffs.length;\n var cutLow = options.xMin || Math.floor(this.cutoffs[cutLength - 1] * 100) / 100;\n var cutHigh = options.xMax || Math.ceil(this.cutoffs[1] * 100) / 100;\n var interval = options.interval || Math.floor(((cutHigh - cutLow) / 20 * 10000000) - 1) / 10000000; // Trick to avoid the precision problem of float numbers\n\n var xLabels = [];\n var interValues = [];\n var intraValues = [];\n var interCumPercent = [];\n var intraCumPercent = [];\n\n var nTP = this.tp[cutLength - 1], currentTP = 0;\n var nFP = this.fp[cutLength - 1], currentFP = 0;\n\n for (var i = cutLow, j = (cutLength - 1); i <= cutHigh; i += interval) {\n while (this.cutoffs[j] < i)\n j--;\n\n xLabels.push(i);\n\n var thisTP = nTP - currentTP - this.tp[j];\n var thisFP = nFP - currentFP - this.fp[j];\n\n currentTP += thisTP;\n currentFP += thisFP;\n\n interValues.push(thisFP);\n intraValues.push(thisTP);\n\n interCumPercent.push(100 - (nFP - this.fp[j]) / nFP * 100);\n intraCumPercent.push(100 - (nTP - this.tp[j]) / nTP * 100);\n }\n\n return {\n xLabels: xLabels,\n interValues: interValues,\n intraValues: intraValues,\n interCumPercent: interCumPercent,\n intraCumPercent: intraCumPercent\n };\n }\n}\n\nPerformance.names = {\n acc: 'Accuracy',\n err: 'Error rate',\n fpr: 'False positive rate',\n tpr: 'True positive rate',\n fnr: 'False negative rate',\n tnr: 'True negative rate',\n ppv: 'Positive predictive value',\n npv: 'Negative predictive value',\n pcfall: 'Prediction-conditioned fallout',\n pcmiss: 'Prediction-conditioned miss',\n lift: 'Lift value',\n rpp: 'Rate of positive predictions',\n rnp: 'Rate of negative predictions',\n threshold: 'Threshold'\n};\n\nmodule.exports = Performance;\n","'use strict';\n\n// Accuracy\nexports.acc = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.tn[i] + pred.tp[i]) / (l - 1);\n }\n return result;\n};\n\n// Error rate\nexports.err = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.fp[i] / (l - 1));\n }\n return result;\n};\n\n// False positive rate\nexports.fpr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.fp[i] / pred.nNeg;\n }\n return result;\n};\n\n// True positive rate\nexports.tpr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.tp[i] / pred.nPos;\n }\n return result;\n};\n\n// False negative rate\nexports.fnr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.fn[i] / pred.nPos;\n }\n return result;\n};\n\n// True negative rate\nexports.tnr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.tn[i] / pred.nNeg;\n }\n return result;\n};\n\n// Positive predictive value\nexports.ppv = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 0;\n }\n return result;\n};\n\n// Negative predictive value\nexports.npv = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 0;\n }\n return result;\n};\n\n// Prediction conditioned fallout\nexports.pcfall = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? 1 - (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 1;\n }\n return result;\n};\n\n// Prediction conditioned miss\nexports.pcmiss = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? 1 - (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 1;\n }\n return result;\n};\n\n// Lift value\nexports.lift = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.nPosPred[i] !== 0) ? ((pred.tp[i] / pred.nPos) / (pred.nPosPred[i] / pred.nSamples)) : 0;\n }\n return result;\n};\n\n// Rate of positive predictions\nexports.rpp = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.nPosPred[i] / pred.nSamples;\n }\n return result;\n};\n\n// Rate of negative predictions\nexports.rnp = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.nNegPred[i] / pred.nSamples;\n }\n return result;\n};\n\n// Threshold\nexports.threshold = pred => {\n const clone = pred.cutoffs.slice();\n clone[0] = clone[1]; // Remove the infinite value\n return clone;\n};\n","'use strict';\n\nvar matrixLib = require('ml-matrix');\nvar Matrix = matrixLib.Matrix;\nvar inverse = matrixLib.inverse;\nvar padArray = require('ml-pad-array');\nvar extend = require('extend');\n\nvar defaultOptions = {\n windowSize: 5,\n derivative: 1,\n polynomial: 2,\n pad: 'none',\n padValue: 'replicate'\n};\n\n/**\n * Savitzky-Golay filter\n * @param {Array } data\n * @param {number} h\n * @param {Object} options\n * @returns {Array}\n */\nfunction SavitzkyGolay (data, h, options) {\n options = extend({}, defaultOptions, options);\n if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize)))\n throw new RangeError('Invalid window size (should be odd and at least 5 integer number)');\n if ((options.derivative < 0) || !(Number.isInteger(options.derivative)))\n throw new RangeError('Derivative should be a positive integer');\n if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial)))\n throw new RangeError('Polynomial should be a positive integer');\n\n var C, norm;\n var step = Math.floor(options.windowSize / 2);\n\n if (options.pad === 'pre') {\n data = padArray(data, {size: step, value: options.padValue});\n }\n\n var ans = new Array(data.length - 2*step);\n\n if ((options.windowSize === 5) && (options.polynomial === 2) && ((options.derivative === 1) || (options.derivative === 2))) {\n if (options.derivative === 1) {\n C = [-2,-1,0,1,2];\n norm = 10;\n }\n else {\n C = [2, -1, -2, -1, 2];\n norm = 7;\n }\n }\n else {\n var J = Matrix.ones(options.windowSize, options.polynomial + 1);\n var inic = -(options.windowSize - 1) / 2;\n for (var i = 0; i < J.length; i++) {\n for (var j = 0; j < J[i].length; j++) {\n if ((inic + 1 !== 0) || (j !== 0))\n J[i][j] = Math.pow((inic + i), j);\n }\n }\n var Jtranspose = J.transposeView();\n var Jinv = inverse(Jtranspose.mmul(J));\n C = Jinv.mmul(Jtranspose);\n C = C[options.derivative];\n norm = 1;\n }\n var det = norm * Math.pow(h, options.derivative);\n for (var k = step; k < (data.length - step); k++) {\n var d = 0;\n for (var l = 0; l < C.length; l++)\n d += C[l] * data[l + k - step] / det;\n ans[k - step] = d;\n }\n\n if (options.pad === 'post') {\n ans = padArray(ans, {size: step, value: options.padValue});\n }\n\n return ans;\n}\n\nmodule.exports = SavitzkyGolay;\n","//Code translate from Pascal source in http://pubs.acs.org/doi/pdf/10.1021/ac00205a007\nvar extend = require('extend');\nvar stat = require('ml-stat');\n\nvar defaultOptions = {\n windowSize: 9,\n derivative: 0,\n polynomial: 3,\n};\n\n\nfunction SavitzkyGolay(data, h, options) {\n options = extend({}, defaultOptions, options);\n\n if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize)))\n throw new RangeError('Invalid window size (should be odd and at least 5 integer number)')\n\n\n if (options.windowSize>data.length)\n throw new RangeError('Window size is higher than the data length '+options.windowSize+\">\"+data.length);\n if ((options.derivative < 0) || !(Number.isInteger(options.derivative)))\n throw new RangeError('Derivative should be a positive integer');\n if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial)))\n throw new RangeError('Polynomial should be a positive integer');\n if (options.polynomial >= 6)\n console.warn('You should not use polynomial grade higher than 5 if you are' +\n ' not sure that your data arises from such a model. Possible polynomial oscillation problems');\n\n var windowSize = options.windowSize;\n\n var half = Math.floor(windowSize/2);\n var np = data.length;\n var ans = new Array(np);\n var weights = fullWeights(windowSize,options.polynomial,options.derivative);\n var hs = 0;\n var constantH = true;\n if( Object.prototype.toString.call( h ) === '[object Array]' ) {\n constantH = false;\n }\n else{\n hs = Math.pow(h, options.derivative);\n }\n //console.log(\"Constant h: \"+constantH);\n //For the borders\n for(var i=0;i=0 && i < h.length-1){\n hs+= (h[i+1]-h[i]);\n count++;\n }\n }\n return Math.pow(hs/count,derivative);\n}\n\nfunction GramPoly(i,m,k,s){\n var Grampoly = 0;\n if(k>0){\n Grampoly = (4*k-2)/(k*(2*m-k+1))*(i*GramPoly(i,m,k-1,s) +\n s*GramPoly(i,m,k-1,s-1)) - ((k-1)*(2*m+k))/(k*(2*m-k+1))*GramPoly(i,m,k-2,s);\n }\n else{\n if(k==0&&s==0){\n Grampoly=1;\n }\n else{\n Grampoly=0;\n }\n }\n //console.log(Grampoly);\n return Grampoly;\n}\n\nfunction GenFact(a,b){\n var gf=1;\n if(a>=b){\n for(var j=a-b+1;j<=a;j++){\n gf*=j;\n }\n }\n return gf;\n}\n\nfunction Weight(i,t,m,n,s){\n var sum=0;\n for(var k=0;k<=n;k++){\n //console.log(k);\n sum+=(2*k+1)*(GenFact(2*m,k)/GenFact(2*m+k+1,k+1))*GramPoly(i,m,k,0)*GramPoly(t,m,k,s)\n }\n return sum;\n}\n\n/**\n *\n * @param m Number of points\n * @param n Polynomial grade\n * @param s Derivative\n */\nfunction fullWeights(m,n,s){\n var weights = new Array(m);\n var np = Math.floor(m/2);\n for(var t=-np;t<=np;t++){\n weights[t+np] = new Array(m);\n for(var j=-np;j<=np;j++){\n weights[t+np][j+np]=Weight(j,t,np,n,s);\n }\n }\n return weights;\n}\n\n/*function entropy(data,h,options){\n var trend = SavitzkyGolay(data,h,trendOptions);\n var copy = new Array(data.length);\n var sum = 0;\n var max = 0;\n for(var i=0;i> 8) & 0xff] + eightBits[(arr[i] >> 16) & 0xff] + eightBits[(arr[i] >> 24) & 0xff];\n }\n return c;\n}\n\n/**\n * Logical AND operation\n * @param {Array} arr1\n * @param {Array} arr2\n * @return {Array}\n */\nfunction and(arr1, arr2) {\n var ans = new Array(arr1.length);\n for (var i = 0; i < arr1.length; i++)\n ans[i] = arr1[i] & arr2[i];\n return ans;\n}\n\n/**\n * Logical OR operation\n * @param {Array} arr1\n * @param {Array} arr2\n * @return {Array}\n */\nfunction or(arr1, arr2) {\n var ans = new Array(arr1.length);\n for (var i = 0; i < arr1.length; i++)\n ans[i] = arr1[i] | arr2[i];\n return ans;\n}\n\n/**\n * Logical XOR operation\n * @param {Array} arr1\n * @param {Array} arr2\n * @return {Array}\n */\nfunction xor(arr1, arr2) {\n var ans = new Array(arr1.length);\n for (var i = 0; i < arr1.length; i++)\n ans[i] = arr1[i] ^ arr2[i];\n return ans;\n}\n\n/**\n * Logical NOT operation\n * @param {Array} arr\n * @return {Array}\n */\nfunction not(arr) {\n var ans = new Array(arr.length);\n for (var i = 0; i < ans.length; i++)\n ans[i] = ~arr[i];\n return ans;\n}\n\n/**\n * Gets the n value of array arr\n * @param {Array} arr\n * @param {number} n\n * @return {boolean}\n */\nfunction getBit(arr, n) {\n var index = n >> 5; // Same as Math.floor(n/32)\n var mask = 1 << (31 - n % 32);\n return Boolean(arr[index] & mask);\n}\n\n/**\n * Sets the n value of array arr to the value val\n * @param {Array} arr\n * @param {number} n\n * @param {boolean} val\n * @return {Array}\n */\nfunction setBit(arr, n, val) {\n var index = n >> 5; // Same as Math.floor(n/32)\n var mask = 1 << (31 - n % 32);\n if (val)\n arr[index] = mask | arr[index];\n else\n arr[index] = ~mask & arr[index];\n return arr;\n}\n\n/**\n * Translates an array of numbers to a string of bits\n * @param {Array} arr\n * @returns {string}\n */\nfunction toBinaryString(arr) {\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n var obj = (arr[i] >>> 0).toString(2);\n str += '00000000000000000000000000000000'.substr(obj.length) + obj;\n }\n return str;\n}\n\n/**\n * Creates an array of numbers based on a string of bits\n * @param {string} str\n * @returns {Array}\n */\nfunction parseBinaryString(str) {\n var len = str.length / 32;\n var ans = new Array(len);\n for (var i = 0; i < len; i++) {\n ans[i] = parseInt(str.substr(i*32, 32), 2) | 0;\n }\n return ans;\n}\n\n/**\n * Translates an array of numbers to a hex string\n * @param {Array} arr\n * @returns {string}\n */\nfunction toHexString(arr) {\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n var obj = (arr[i] >>> 0).toString(16);\n str += '00000000'.substr(obj.length) + obj;\n }\n return str;\n}\n\n/**\n * Creates an array of numbers based on a hex string\n * @param {string} str\n * @returns {Array}\n */\nfunction parseHexString(str) {\n var len = str.length / 8;\n var ans = new Array(len);\n for (var i = 0; i < len; i++) {\n ans[i] = parseInt(str.substr(i*8, 8), 16) | 0;\n }\n return ans;\n}\n\n/**\n * Creates a human readable string of the array\n * @param {Array} arr\n * @returns {string}\n */\nfunction toDebug(arr) {\n var binary = toBinaryString(arr);\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n str += '0000'.substr((i * 32).toString(16).length) + (i * 32).toString(16) + ':';\n for (var j = 0; j < 32; j += 4) {\n str += ' ' + binary.substr(i * 32 + j, 4);\n }\n if (i < arr.length - 1) str += '\\n';\n }\n return str\n}\n\nmodule.exports = {\n count: count,\n and: and,\n or: or,\n xor: xor,\n not: not,\n getBit: getBit,\n setBit: setBit,\n toBinaryString: toBinaryString,\n parseBinaryString: parseBinaryString,\n toHexString: toHexString,\n parseHexString: parseHexString,\n toDebug: toDebug\n};\n","// auxiliary file to create the 256 look at table elements\n\nvar ans = new Array(256);\nfor (var i = 0; i < 256; i++) {\n var num = i;\n var c = 0;\n while (num) {\n num = num & (num - 1);\n c++;\n }\n ans[i] = c;\n}\n\nmodule.exports = ans;","'use strict';\n\nmodule.exports = exports = require('./ArrayUtils');\n\nexports.getEquallySpacedData = require('./getEquallySpaced').getEquallySpacedData;\nexports.SNV = require('./snv').SNV;\n","'use strict';\n\nconst Stat = require('ml-stat').array;\n/**\n * Function that returns an array of points given 1D array as follows:\n *\n * [x1, y1, .. , x2, y2, ..]\n *\n * And receive the number of dimensions of each point.\n * @param array\n * @param dimensions\n * @returns {Array} - Array of points.\n */\nfunction coordArrayToPoints(array, dimensions) {\n if (array.length % dimensions !== 0) {\n throw new RangeError('Dimensions number must be accordance with the size of the array.');\n }\n\n var length = array.length / dimensions;\n var pointsArr = new Array(length);\n\n var k = 0;\n for (var i = 0; i < array.length; i += dimensions) {\n var point = new Array(dimensions);\n for (var j = 0; j < dimensions; ++j) {\n point[j] = array[i + j];\n }\n\n pointsArr[k] = point;\n k++;\n }\n\n return pointsArr;\n}\n\n\n/**\n * Function that given an array as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * Returns an array as follows:\n * [[x1, x2, ..], [y1, y2, ..], [ .. ]]\n *\n * And receives the number of dimensions of each coordinate.\n * @param array\n * @param dimensions\n * @returns {Array} - Matrix of coordinates\n */\nfunction coordArrayToCoordMatrix(array, dimensions) {\n if (array.length % dimensions !== 0) {\n throw new RangeError('Dimensions number must be accordance with the size of the array.');\n }\n\n var coordinatesArray = new Array(dimensions);\n var points = array.length / dimensions;\n for (var i = 0; i < coordinatesArray.length; i++) {\n coordinatesArray[i] = new Array(points);\n }\n\n for (i = 0; i < array.length; i += dimensions) {\n for (var j = 0; j < dimensions; ++j) {\n var currentPoint = Math.floor(i / dimensions);\n coordinatesArray[j][currentPoint] = array[i + j];\n }\n }\n\n return coordinatesArray;\n}\n\n/**\n * Function that receives a coordinate matrix as follows:\n * [[x1, x2, ..], [y1, y2, ..], [ .. ]]\n *\n * Returns an array of coordinates as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * @param coordMatrix\n * @returns {Array}\n */\nfunction coordMatrixToCoordArray(coordMatrix) {\n var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length);\n var k = 0;\n for (var i = 0; i < coordMatrix[0].length; ++i) {\n for (var j = 0; j < coordMatrix.length; ++j) {\n coodinatesArray[k] = coordMatrix[j][i];\n ++k;\n }\n }\n\n return coodinatesArray;\n}\n\n/**\n * Tranpose a matrix, this method is for coordMatrixToPoints and\n * pointsToCoordMatrix, that because only transposing the matrix\n * you can change your representation.\n *\n * @param matrix\n * @returns {Array}\n */\nfunction transpose(matrix) {\n var resultMatrix = new Array(matrix[0].length);\n for (var i = 0; i < resultMatrix.length; ++i) {\n resultMatrix[i] = new Array(matrix.length);\n }\n\n for (i = 0; i < matrix.length; ++i) {\n for (var j = 0; j < matrix[0].length; ++j) {\n resultMatrix[j][i] = matrix[i][j];\n }\n }\n\n return resultMatrix;\n}\n\n/**\n * Function that transform an array of points into a coordinates array\n * as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * @param points\n * @returns {Array}\n */\nfunction pointsToCoordArray(points) {\n var coodinatesArray = new Array(points.length * points[0].length);\n var k = 0;\n for (var i = 0; i < points.length; ++i) {\n for (var j = 0; j < points[0].length; ++j) {\n coodinatesArray[k] = points[i][j];\n ++k;\n }\n }\n\n return coodinatesArray;\n}\n\n/**\n * Apply the dot product between the smaller vector and a subsets of the\n * largest one.\n *\n * @param firstVector\n * @param secondVector\n * @returns {Array} each dot product of size of the difference between the\n * larger and the smallest one.\n */\nfunction applyDotProduct(firstVector, secondVector) {\n var largestVector, smallestVector;\n if (firstVector.length <= secondVector.length) {\n smallestVector = firstVector;\n largestVector = secondVector;\n } else {\n smallestVector = secondVector;\n largestVector = firstVector;\n }\n\n var difference = largestVector.length - smallestVector.length + 1;\n var dotProductApplied = new Array(difference);\n\n for (var i = 0; i < difference; ++i) {\n var sum = 0;\n for (var j = 0; j < smallestVector.length; ++j) {\n sum += smallestVector[j] * largestVector[i + j];\n }\n dotProductApplied[i] = sum;\n }\n\n return dotProductApplied;\n}\n/**\n * To scale the input array between the specified min and max values. The operation is performed inplace\n * if the options.inplace is specified. If only one of the min or max parameters is specified, then the scaling\n * will multiply the input array by min/min(input) or max/max(input)\n * @param input\n * @param options\n * @returns {*}\n */\nfunction scale(input, options = {}) {\n const {\n min,\n max\n } = options;\n\n var y = options.inPlace ? input : (new Array(input.length));\n var minMax = Stat.minMax(input);\n\n if (typeof max === 'number') {\n if (typeof min === 'number') {\n let factor = (max - min) / (minMax.max - minMax.min);\n for (let i = 0; i < y.length; i++) {\n y[i] = (input[i] - minMax.min) * factor + min;\n }\n } else if (minMax.max !== 0) {\n let factor = max / minMax.max;\n for (let i = 0; i < y.length; i++) {\n y[i] = input[i] * factor;\n }\n } else {\n options.min = minMax.min;\n y = scale(input, options);\n }\n } else if (typeof min === 'number') {\n if (minMax.min !== 0) {\n let factor = min / minMax.min;\n for (let i = 0; i < y.length; i++) {\n y[i] = input[i] * factor;\n }\n\n } else {\n options.max = minMax.max;\n y = scale(input, options);\n }\n }\n return y;\n}\n\nmodule.exports = {\n coordArrayToPoints: coordArrayToPoints,\n coordArrayToCoordMatrix: coordArrayToCoordMatrix,\n coordMatrixToCoordArray: coordMatrixToCoordArray,\n coordMatrixToPoints: transpose,\n pointsToCoordArray: pointsToCoordArray,\n pointsToCoordMatrix: transpose,\n applyDotProduct: applyDotProduct,\n scale: scale\n};\n\n","'use strict';\n\n/**\n *\n * Function that returns a Number array of equally spaced numberOfPoints\n * containing a representation of intensities of the spectra arguments x\n * and y.\n *\n * The options parameter contains an object in the following form:\n * from: starting point\n * to: last point\n * numberOfPoints: number of points between from and to\n * variant: \"slot\" or \"smooth\" - smooth is the default option\n *\n * The slot variant consist that each point in the new array is calculated\n * averaging the existing points between the slot that belongs to the current\n * value. The smooth variant is the same but takes the integral of the range\n * of the slot and divide by the step size between two points in the new array.\n *\n * @param x - sorted increasing x values\n * @param y\n * @param options\n * @returns {Array} new array with the equally spaced data.\n *\n */\nfunction getEquallySpacedData(x, y, options = {}) {\n var xLength = x.length;\n if (x.length > 1 && x[0] > x[1]) {\n x = x.slice().reverse();\n y = y.slice().reverse();\n }\n\n var {\n from = x[0],\n to = x[xLength - 1],\n variant = 'smooth',\n numberOfPoints = 100\n } = options;\n\n if (xLength !== y.length) {\n throw new RangeError(\"the x and y vector doesn't have the same size.\");\n }\n\n if (typeof from !== 'number' || isNaN(from)) {\n throw new RangeError(\"'from' option must be a number\");\n }\n\n if (typeof to !== 'number' || isNaN(to)) {\n throw new RangeError(\"'to' option must be a number\");\n }\n\n var reverse = from > to;\n if (reverse) {\n [from, to] = [to, from];\n }\n\n if (typeof numberOfPoints !== 'number' || isNaN(numberOfPoints)) {\n throw new RangeError(\"'numberOfPoints' option must be a number\");\n }\n if (numberOfPoints < 1) {\n throw new RangeError('the number of points must be at least 1');\n }\n\n var output = variant === 'slot' ? getEquallySpacedSlot(x, y, from, to, numberOfPoints) : getEquallySpacedSmooth(x, y, from, to, numberOfPoints);\n\n return reverse ? output.reverse() : output;\n}\n\n/**\n * function that retrieves the getEquallySpacedData with the variant \"smooth\"\n *\n * @param x\n * @param y\n * @param from - Initial point\n * @param to - Final point\n * @param numberOfPoints\n * @returns {Array} - Array of y's equally spaced with the variant \"smooth\"\n */\nfunction getEquallySpacedSmooth(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n\n var output = new Array(numberOfPoints);\n\n var initialOriginalStep = x[1] - x[0];\n var lastOriginalStep = x[xLength - 1] - x[xLength - 2];\n\n // Init main variables\n var min = from - halfStep;\n var max = from + halfStep;\n\n var previousX = Number.MIN_VALUE;\n var previousY = 0;\n var nextX = x[0] - initialOriginalStep;\n var nextY = 0;\n\n var currentValue = 0;\n var slope = 0;\n var intercept = 0;\n var sumAtMin = 0;\n var sumAtMax = 0;\n\n var i = 0; // index of input\n var j = 0; // index of output\n\n function getSlope(x0, y0, x1, y1) {\n return (y1 - y0) / (x1 - x0);\n }\n\n main: while (true) {\n\n if (previousX <= min && min <= nextX) {\n add = integral(0, min - previousX, slope, previousY);\n sumAtMin = currentValue + add;\n }\n\n while (nextX - max >= 0) {\n // no overlap with original point, just consume current value\n var add = integral(0, max - previousX, slope, previousY);\n sumAtMax = currentValue + add;\n\n output[j++] = (sumAtMax - sumAtMin) / step;\n\n if (j === numberOfPoints) {\n break main;\n }\n\n min = max;\n max += step;\n sumAtMin = sumAtMax;\n }\n\n currentValue += integral(previousX, nextX, slope, intercept);\n\n previousX = nextX;\n previousY = nextY;\n\n if (i < xLength) {\n nextX = x[i];\n nextY = y[i];\n i++;\n } else if (i === xLength) {\n nextX += lastOriginalStep;\n nextY = 0;\n }\n\n slope = getSlope(previousX, previousY, nextX, nextY);\n intercept = -slope * previousX + previousY;\n }\n\n return output;\n}\n\n/**\n * function that retrieves the getEquallySpacedData with the variant \"slot\"\n *\n * @param x\n * @param y\n * @param from - Initial point\n * @param to - Final point\n * @param numberOfPoints\n * @returns {Array} - Array of y's equally spaced with the variant \"slot\"\n */\nfunction getEquallySpacedSlot(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n var lastStep = x[x.length - 1] - x[x.length - 2];\n\n var start = from - halfStep;\n var output = new Array(numberOfPoints);\n\n // Init main variables\n var min = start;\n var max = start + step;\n\n var previousX = -Number.MAX_VALUE;\n var previousY = 0;\n var nextX = x[0];\n var nextY = y[0];\n var frontOutsideSpectra = 0;\n var backOutsideSpectra = true;\n\n var currentValue = 0;\n\n // for slot algorithm\n var currentPoints = 0;\n\n var i = 1; // index of input\n var j = 0; // index of output\n\n main: while (true) {\n if (previousX >= nextX) throw (new Error('x must be an increasing serie'));\n while (previousX - max > 0) {\n // no overlap with original point, just consume current value\n if (backOutsideSpectra) {\n currentPoints++;\n backOutsideSpectra = false;\n }\n\n output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints;\n j++;\n\n if (j === numberOfPoints) {\n break main;\n }\n\n min = max;\n max += step;\n currentValue = 0;\n currentPoints = 0;\n }\n\n if (previousX > min) {\n currentValue += previousY;\n currentPoints++;\n }\n\n if (previousX === -Number.MAX_VALUE || frontOutsideSpectra > 1) {\n currentPoints--;\n }\n\n previousX = nextX;\n previousY = nextY;\n\n if (i < xLength) {\n nextX = x[i];\n nextY = y[i];\n i++;\n } else {\n nextX += lastStep;\n nextY = 0;\n frontOutsideSpectra++;\n }\n }\n\n return output;\n}\n/**\n * Function that calculates the integral of the line between two\n * x-coordinates, given the slope and intercept of the line.\n * @param x0\n * @param x1\n * @param slope\n * @param intercept\n * @returns {number} integral value.\n */\nfunction integral(x0, x1, slope, intercept) {\n return (0.5 * slope * x1 * x1 + intercept * x1) - (0.5 * slope * x0 * x0 + intercept * x0);\n}\n\nexports.getEquallySpacedData = getEquallySpacedData;\nexports.integral = integral;\n","'use strict';\n\nexports.SNV = SNV;\nvar Stat = require('ml-stat').array;\n\n/**\n * Function that applies the standard normal variate (SNV) to an array of values.\n *\n * @param data - Array of values.\n * @returns {Array} - applied the SNV.\n */\nfunction SNV(data) {\n var mean = Stat.mean(data);\n var std = Stat.standardDeviation(data);\n var result = data.slice();\n for (var i = 0; i < data.length; i++) {\n result[i] = (result[i] - mean) / std;\n }\n return result;\n}\n","import isArray from 'is-any-array';\n\n/**\n * Computes the mode of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction mode(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var maxValue = 0;\n var maxCount = 0;\n var count = 0;\n var counts = {};\n\n for (var i = 0; i < input.length; ++i) {\n var element = input[i];\n count = counts[element];\n\n if (count) {\n counts[element]++;\n count++;\n } else {\n counts[element] = count = 1;\n }\n\n if (count > maxCount) {\n maxCount = count;\n maxValue = input[i];\n }\n }\n\n return maxValue;\n}\n\nexport default mode;\n","/**\n * Computes the norm of the given values\n * @param {Array} input\n * @param {object} [options={}]\n * @param {string} [algorithm='absolute']\n * @return {number}\n */\nfunction norm(input) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var _options$algorithm = options.algorithm,\n algorithm = _options$algorithm === void 0 ? 'absolute' : _options$algorithm;\n\n if (!Array.isArray(input)) {\n throw new Error('input must be an array');\n }\n\n if (input.length === 0) {\n throw new Error('input must not be empty');\n }\n\n switch (algorithm.toLowerCase()) {\n case 'absolute':\n var sum = absoluteSum(input);\n if (sum === 0) return input.slice(0);\n return input.map(function (element) {\n return element / sum;\n });\n\n default:\n throw new Error(\"norm: unknown algorithm: \".concat(algorithm));\n }\n}\n\nfunction absoluteSum(input) {\n var sum = 0;\n\n for (var i = 0; i < input.length; i++) {\n sum += Math.abs(input[i]);\n }\n\n return sum;\n}\n\nexport default norm;\n","import isArray from 'is-any-array';\n\nfunction _typeof(obj) {\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function (obj) {\n return typeof obj;\n };\n } else {\n _typeof = function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n}\n\n/**\n * Fill an array with sequential numbers\n * @param {Array} [input] - optional destination array (if not provided a new array will be created)\n * @param {object} [options={}]\n * @param {number} [options.from=0] - first value in the array\n * @param {number} [options.to=10] - last value in the array\n * @param {number} [options.size=input.length] - size of the array (if not provided calculated from step)\n * @param {number} [options.step] - if not provided calculated from size\n * @return {Array}\n */\n\nfunction sequentialFill() {\n var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n if (_typeof(input) === 'object' && !isArray(input)) {\n options = input;\n input = [];\n }\n\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n var _options = options,\n _options$from = _options.from,\n from = _options$from === void 0 ? 0 : _options$from,\n _options$to = _options.to,\n to = _options$to === void 0 ? 10 : _options$to,\n _options$size = _options.size,\n size = _options$size === void 0 ? input.length : _options$size,\n step = _options.step;\n\n if (size && step) {\n throw new Error('step is defined by the array size');\n }\n\n if (!size) {\n if (step) {\n size = Math.floor((to - from) / step) + 1;\n } else {\n size = to - from + 1;\n }\n }\n\n if (!step && size) {\n step = (to - from) / (size - 1);\n }\n\n if (Array.isArray(input)) {\n input.length = 0; // only works with normal array\n\n for (var i = 0; i < size; i++) {\n input.push(from);\n from += step;\n }\n } else {\n if (input.length !== size) {\n throw new Error('sequentialFill typed array must have the correct length');\n }\n\n for (var _i = 0; _i < size; _i++) {\n input[_i] = from;\n from += step;\n }\n }\n\n return input;\n}\n\nexport default sequentialFill;\n","import variance from 'ml-array-variance';\n\n/**\n * Computes the standard deviation of the given values\n * @param {Array} values\n * @param {object} [options]\n * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n.\n * @param {number} [options.mean = arrayMean] - precalculated mean, if any.\n * @return {number}\n */\n\nfunction standardDeviation(values) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return Math.sqrt(variance(values, options));\n}\n\nexport default standardDeviation;\n","/**\n * Merge abscissa values if the ordinate value is in a list of centroids\n * @param {object} originalPoints\n * @param {Array} originalPoints.x\n * @param {Array} originalPoints.y\n * @param {Array} centroids\n * @param {object} [options]\n * @param {number} [options.window = 0.01] - has to be a positive number\n * @return {{x: Array, y: Array}}\n */\nexport default function mergeByCentroids(\n originalPoints,\n centroids,\n options = {}\n) {\n const { window = 0.01 } = options;\n\n var mergedPoints = {\n x: centroids.slice(),\n y: new Array(centroids.length).fill(0)\n };\n\n var originalIndex = 0;\n var mergedIndex = 0;\n while (\n originalIndex < originalPoints.x.length &&\n mergedIndex < centroids.length\n ) {\n var diff = originalPoints.x[originalIndex] - centroids[mergedIndex];\n if (Math.abs(diff) < window) {\n mergedPoints.y[mergedIndex] += originalPoints.y[originalIndex++];\n } else if (diff < 0) {\n originalIndex++;\n } else {\n mergedIndex++;\n }\n }\n\n return mergedPoints;\n}\n","import binarySearch from 'binary-search';\nimport { asc, desc } from 'num-sort';\n\n/**\n *\n * @param {object} points\n * @param {Array} originalPoints.x\n * @param {Array} originalPoints.y\n * @param {*} options\n * @return {{x: Array, y: Array}}\n */\nexport default function closestX(points, options) {\n const { x, y } = points;\n const { target = x[0], reverse = false } = options;\n\n let index;\n if (reverse) {\n index = binarySearch(x, target, desc);\n } else {\n index = binarySearch(x, target, asc);\n }\n\n if (index >= 0) {\n return {\n x: x[index],\n y: y[index]\n };\n } else {\n index = ~index;\n if (\n (index !== 0 && Math.abs(x[index] - target) > 0.5) ||\n index === x.length\n ) {\n return {\n x: x[index - 1],\n y: y[index - 1]\n };\n } else {\n return {\n x: x[index],\n y: y[index]\n };\n }\n }\n}\n","/**\n * Merge abscissas values on similar ordinates and weight the group of abscissas\n * @param {object} points\n * @param {Array} points.x - sorted abscissas values\n * @param {Array} points.y - ordinates values\n * @param {object} [options]\n * @param {number} [options.groupWidth = 0.001] - window for abscissas to merge\n * @return {{x: Array, y: Array}}\n */\nexport default function maxMerge(points, options = {}) {\n const { x, y } = points;\n const { groupWidth = 0.001 } = options;\n\n var merged = { x: [], y: [] };\n var maxAbscissa = { x: [], y: [] };\n var size = 0;\n var index = 0;\n\n while (index < x.length) {\n if (size === 0 || x[index] - merged.x[size - 1] > groupWidth) {\n maxAbscissa.x.push(x[index]);\n maxAbscissa.y.push(y[index]);\n merged.x.push(x[index]);\n merged.y.push(y[index]);\n index++;\n size++;\n } else {\n if (y[index] > maxAbscissa.y[size - 1]) {\n maxAbscissa.x[size - 1] = x[index];\n maxAbscissa.y[size - 1] = y[index];\n }\n merged.x[size - 1] = x[index];\n merged.y[size - 1] += y[index];\n index++;\n }\n }\n\n merged.x = maxAbscissa.x.slice();\n\n return merged;\n}\n","import binarySearch from 'binary-search';\nimport { asc, desc } from 'num-sort';\n\n/**\n * @param {object} points\n * @param {Array} points.x - sorted abscissas values\n * @param {Array} points.y - ordinates values\n * @param {object} [options]\n * @param {object} [options.from = {index: 0}]\n * @param {object} [options.to = {index: x.length-1}]\n * @param {boolean} [options.reverse = false]\n * @return {{index: number, value: number}}\n */\nexport default function maxY(points, options = {}) {\n const { x, y } = points;\n let {\n from = { index: 0 },\n to = { index: x.length },\n reverse = false\n } = options;\n\n if (from.value !== undefined && from.index === undefined) {\n from.index = calculateIndex(from.value, x, reverse);\n }\n\n if (to.value !== undefined && to.index === undefined) {\n to.index = calculateIndex(to.value, x, reverse);\n }\n\n var currentMax = Number.MIN_VALUE;\n var currentIndex;\n for (var i = from.index; i < to.index; i++) {\n if (currentMax < y[i]) {\n currentMax = y[i];\n currentIndex = i;\n }\n }\n\n return {\n index: currentIndex,\n value: currentMax\n };\n}\n\n/**\n * @param {number} value\n * @param {Array} x\n * @param {boolean} reverse\n * @return {number} index of the value in the array\n */\nfunction calculateIndex(value, x, reverse) {\n let index;\n if (reverse) {\n index = binarySearch(x, value, desc);\n } else {\n index = binarySearch(x, value, asc);\n }\n\n if (index < 0) {\n throw new Error(`the value ${value} doesn't belongs to the abscissa value`);\n }\n\n return index;\n}\n","export default function sortX(points, options = {}) {\n const { x, y } = points;\n const { reverse = false } = options;\n\n var sortFunc;\n if (!reverse) {\n sortFunc = (a, b) => a.x - b.x;\n } else {\n sortFunc = (a, b) => b.x - a.x;\n }\n\n var grouped = x\n .map((val, index) => ({\n x: val,\n y: y[index]\n }))\n .sort(sortFunc);\n\n var response = { x: x.slice(), y: y.slice() };\n for (var i = 0; i < x.length; i++) {\n response.x[i] = grouped[i].x;\n response.y[i] = grouped[i].y;\n }\n\n return response;\n}\n","\n/**\n * In place modification of the 2 arrays to make X unique and sum the Y if X has the same value\n * @param {object} [points={}] : Object of points contains property x (an array) and y (an array)\n * @return points\n */\n\nexport default function uniqueX(points = {}) {\n const { x, y } = points;\n if (x.length < 2) return;\n if (x.length !== y.length) {\n throw new Error('The X and Y arrays mush have the same length');\n }\n\n let current = x[0];\n let counter = 0;\n\n for (let i = 1; i < x.length; i++) {\n if (current !== x[i]) {\n counter++;\n current = x[i];\n x[counter] = x[i];\n if (i !== counter) {\n y[counter] = 0;\n }\n }\n if (i !== counter) {\n y[counter] += y[i];\n }\n }\n\n x.length = counter + 1;\n y.length = counter + 1;\n}\n","/**\n * Merge abscissas values on similar ordinates and weight the group of abscissas\n * @param {object} points\n * @param {Array} points.x - sorted abscissas values\n * @param {Array} points.y - ordinates values\n * @param {object} [options]\n * @param {number} [options.groupWidth = 0.001] - window for abscissas to merge\n * @return {{x: Array, y: Array}}\n */\nexport default function weightedMerge(points, options = {}) {\n const { x, y } = points;\n const { groupWidth = 0.001 } = options;\n\n var merged = { x: [], y: [] };\n var weightedAbscissa = { x: [], y: [] };\n var size = 0;\n var index = 0;\n\n while (index < x.length) {\n if (size === 0 || x[index] - merged.x[size - 1] > groupWidth) {\n weightedAbscissa.x.push(x[index] * y[index]);\n weightedAbscissa.y.push(y[index]);\n merged.x.push(x[index]);\n merged.y.push(y[index]);\n index++;\n size++;\n } else {\n weightedAbscissa.x[size - 1] += x[index] * y[index];\n weightedAbscissa.y[size - 1] += y[index];\n merged.x[size - 1] = x[index];\n merged.y[size - 1] += y[index];\n index++;\n }\n }\n\n for (var i = 0; i < merged.x.length; i++) {\n merged.x[i] = weightedAbscissa.x[i] / weightedAbscissa.y[i];\n }\n\n return merged;\n}\n","export function squaredEuclidean(p, q) {\r\n let d = 0;\r\n for (let i = 0; i < p.length; i++) {\r\n d += (p[i] - q[i]) * (p[i] - q[i]);\r\n }\r\n return d;\r\n}\r\nexport function euclidean(p, q) {\r\n return Math.sqrt(squaredEuclidean(p, q));\r\n}\r\n","export function squaredEuclidean(p, q) {\r\n let d = 0;\r\n for (let i = 0; i < p.length; i++) {\r\n d += (p[i] - q[i]) * (p[i] - q[i]);\r\n }\r\n return d;\r\n}\r\nexport function euclidean(p, q) {\r\n return Math.sqrt(squaredEuclidean(p, q));\r\n}\r\n","'use strict';\nimport { squaredEuclidean } from 'ml-distance-euclidean';\nconst defaultOptions = {\n distanceFunction: squaredEuclidean\n};\nexport default function nearestVector(listVectors, vector, options = defaultOptions) {\n const distanceFunction = options.distanceFunction || defaultOptions.distanceFunction;\n const similarityFunction = options.similarityFunction || defaultOptions.similarityFunction;\n let vectorIndex = -1;\n if (typeof similarityFunction === 'function') {\n // maximum similarity\n let maxSim = Number.MIN_VALUE;\n for (let j = 0; j < listVectors.length; j++) {\n const sim = similarityFunction(vector, listVectors[j]);\n if (sim > maxSim) {\n maxSim = sim;\n vectorIndex = j;\n }\n }\n }\n else if (typeof distanceFunction === 'function') {\n // minimum distance\n let minDist = Number.MAX_VALUE;\n for (let i = 0; i < listVectors.length; i++) {\n const dist = distanceFunction(vector, listVectors[i]);\n if (dist < minDist) {\n minDist = dist;\n vectorIndex = i;\n }\n }\n }\n else {\n throw new Error(\"A similarity or distance function it's required\");\n }\n return vectorIndex;\n}\nexport function findNearestVector(vectorList, vector, options = defaultOptions) {\n const index = nearestVector(vectorList, vector, options);\n return vectorList[index];\n}\n","import nearestVector from 'ml-nearest-vector';\n\n/**\n * Calculates the distance matrix for a given array of points\n * @ignore\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @param {function} distance - Distance function to use between the points\n * @return {Array>} - matrix with the distance values\n */\nexport function calculateDistanceMatrix(data, distance) {\n var distanceMatrix = new Array(data.length);\n for (var i = 0; i < data.length; ++i) {\n for (var j = i; j < data.length; ++j) {\n if (!distanceMatrix[i]) {\n distanceMatrix[i] = new Array(data.length);\n }\n if (!distanceMatrix[j]) {\n distanceMatrix[j] = new Array(data.length);\n }\n const dist = distance(data[i], data[j]);\n distanceMatrix[i][j] = dist;\n distanceMatrix[j][i] = dist;\n }\n }\n return distanceMatrix;\n}\n\n/**\n * Updates the cluster identifier based in the new data\n * @ignore\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @param {Array>} centers - the K centers in format [x,y,z,...]\n * @param {Array } clusterID - the cluster identifier for each data dot\n * @param {function} distance - Distance function to use between the points\n * @return {Array} the cluster identifier for each data dot\n */\nexport function updateClusterID(data, centers, clusterID, distance) {\n for (var i = 0; i < data.length; i++) {\n clusterID[i] = nearestVector(centers, data[i], {\n distanceFunction: distance\n });\n }\n return clusterID;\n}\n\n/**\n * Update the center values based in the new configurations of the clusters\n * @ignore\n * @param {Array>} prevCenters - Centroids from the previous iteration\n * @param {Array >} data - the [x,y,z,...] points to cluster\n * @param {Array } clusterID - the cluster identifier for each data dot\n * @param {number} K - Number of clusters\n * @return {Array} he K centers in format [x,y,z,...]\n */\nexport function updateCenters(prevCenters, data, clusterID, K) {\n const nDim = data[0].length;\n\n // copy previous centers\n var centers = new Array(K);\n var centersLen = new Array(K);\n for (var i = 0; i < K; i++) {\n centers[i] = new Array(nDim);\n centersLen[i] = 0;\n for (var j = 0; j < nDim; j++) {\n centers[i][j] = 0;\n }\n }\n\n // add the value for all dimensions of the point\n for (var l = 0; l < data.length; l++) {\n centersLen[clusterID[l]]++;\n for (var dim = 0; dim < nDim; dim++) {\n centers[clusterID[l]][dim] += data[l][dim];\n }\n }\n\n // divides by length\n for (var id = 0; id < K; id++) {\n for (var d = 0; d < nDim; d++) {\n if (centersLen[id]) {\n centers[id][d] /= centersLen[id];\n } else {\n centers[id][d] = prevCenters[id][d];\n }\n }\n }\n return centers;\n}\n\n/**\n * The centers have moved more than the tolerance value?\n * @ignore\n * @param {Array>} centers - the K centers in format [x,y,z,...]\n * @param {Array>} oldCenters - the K old centers in format [x,y,z,...]\n * @param {function} distanceFunction - Distance function to use between the points\n * @param {number} tolerance - Allowed distance for the centroids to move\n * @return {boolean}\n */\nexport function hasConverged(centers, oldCenters, distanceFunction, tolerance) {\n for (var i = 0; i < centers.length; i++) {\n if (distanceFunction(centers[i], oldCenters[i]) > tolerance) {\n return false;\n }\n }\n return true;\n}\n","import Random from 'ml-random';\nimport { squaredEuclidean } from 'ml-distance-euclidean';\nimport { Matrix } from 'ml-matrix';\n\n/**\n * Choose K different random points from the original data\n * @ignore\n * @param {Array>} data - Points in the format to cluster [x,y,z,...]\n * @param {number} K - number of clusters\n * @param {number} seed - seed for random number generation\n * @return {Array>} - Initial random points\n */\nexport function random(data, K, seed) {\n const random = new Random(seed);\n return random.choice(data, { size: K });\n}\n\n/**\n * Chooses the most distant points to a first random pick\n * @ignore\n * @param {Array>} data - Points in the format to cluster [x,y,z,...]\n * @param {number} K - number of clusters\n * @param {Array>} distanceMatrix - matrix with the distance values\n * @param {number} seed - seed for random number generation\n * @return {Array>} - Initial random points\n */\nexport function mostDistant(data, K, distanceMatrix, seed) {\n const random = new Random(seed);\n var ans = new Array(K);\n // chooses a random point as initial cluster\n ans[0] = Math.floor(random.random() * data.length);\n\n if (K > 1) {\n // chooses the more distant point\n var maxDist = { dist: -1, index: -1 };\n for (var l = 0; l < data.length; ++l) {\n if (distanceMatrix[ans[0]][l] > maxDist.dist) {\n maxDist.dist = distanceMatrix[ans[0]][l];\n maxDist.index = l;\n }\n }\n ans[1] = maxDist.index;\n\n if (K > 2) {\n // chooses the set of points that maximises the min distance\n for (var k = 2; k < K; ++k) {\n var center = { dist: -1, index: -1 };\n for (var m = 0; m < data.length; ++m) {\n // minimum distance to centers\n var minDistCent = { dist: Number.MAX_VALUE, index: -1 };\n for (var n = 0; n < k; ++n) {\n if (\n distanceMatrix[n][m] < minDistCent.dist &&\n ans.indexOf(m) === -1\n ) {\n minDistCent = {\n dist: distanceMatrix[n][m],\n index: m\n };\n }\n }\n\n if (\n minDistCent.dist !== Number.MAX_VALUE &&\n minDistCent.dist > center.dist\n ) {\n center = Object.assign({}, minDistCent);\n }\n }\n\n ans[k] = center.index;\n }\n }\n }\n\n return ans.map((index) => data[index]);\n}\n\n// Implementation inspired from scikit\nexport function kmeanspp(X, K, options = {}) {\n X = new Matrix(X);\n const nSamples = X.length;\n const random = new Random(options.seed);\n // Set the number of trials\n const centers = [];\n const localTrials = options.localTrials || 2 + Math.floor(Math.log(K));\n\n // Pick the first center at random from the dataset\n const firstCenterIdx = random.randInt(nSamples);\n centers.push(X[firstCenterIdx].slice());\n\n // Init closest distances\n let closestDistSquared = [X.map((x) => squaredEuclidean(x, centers[0]))];\n let cumSumClosestDistSquared = [cumSum(closestDistSquared[0])];\n const factor = 1 / cumSumClosestDistSquared[0][nSamples - 1];\n let probabilities = Matrix.mul(closestDistSquared, factor);\n\n // Iterate over the remaining centers\n for (let i = 1; i < K; i++) {\n const candidateIdx = random.choice(nSamples, {\n replace: true,\n size: localTrials,\n probabilities: probabilities[0]\n });\n\n const candidates = X.selection(candidateIdx, range(X[0].length));\n const distanceToCandidates = euclidianDistances(candidates, X);\n\n let bestCandidate;\n let bestPot;\n let bestDistSquared;\n\n for (let j = 0; j < localTrials; j++) {\n const newDistSquared = Matrix.min(closestDistSquared, [distanceToCandidates[j]]);\n const newPot = newDistSquared.sum();\n if (bestCandidate === undefined || newPot < bestPot) {\n bestCandidate = candidateIdx[j];\n bestPot = newPot;\n bestDistSquared = newDistSquared;\n }\n }\n centers[i] = X[bestCandidate].slice();\n closestDistSquared = bestDistSquared;\n cumSumClosestDistSquared = [cumSum(closestDistSquared[0])];\n probabilities = Matrix.mul(\n closestDistSquared,\n 1 / cumSumClosestDistSquared[0][nSamples - 1]\n );\n }\n return centers;\n}\n\nfunction euclidianDistances(A, B) {\n const result = new Matrix(A.length, B.length);\n for (let i = 0; i < A.length; i++) {\n for (let j = 0; j < B.length; j++) {\n result.set(i, j, squaredEuclidean(A.getRow(i), B.getRow(j)));\n }\n }\n return result;\n}\n\nfunction range(l) {\n let r = [];\n for (let i = 0; i < l; i++) {\n r.push(i);\n }\n return r;\n}\n\nfunction cumSum(arr) {\n let cumSum = [arr[0]];\n for (let i = 1; i < arr.length; i++) {\n cumSum[i] = cumSum[i - 1] + arr[i];\n }\n return cumSum;\n}\n","import { updateClusterID } from './utils';\n\nconst distanceSymbol = Symbol('distance');\n\nexport default class KMeansResult {\n /**\n * Result of the kmeans algorithm\n * @param {Array} clusters - the cluster identifier for each data dot\n * @param {Array>} centroids - the K centers in format [x,y,z,...], the error and size of the cluster\n * @param {boolean} converged - Converge criteria satisfied\n * @param {number} iterations - Current number of iterations\n * @param {function} distance - (*Private*) Distance function to use between the points\n * @constructor\n */\n constructor(clusters, centroids, converged, iterations, distance) {\n this.clusters = clusters;\n this.centroids = centroids;\n this.converged = converged;\n this.iterations = iterations;\n this[distanceSymbol] = distance;\n }\n\n /**\n * Allows to compute for a new array of points their cluster id\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @return {Array} - cluster id for each point\n */\n nearest(data) {\n const clusterID = new Array(data.length);\n const centroids = this.centroids.map(function (centroid) {\n return centroid.centroid;\n });\n return updateClusterID(data, centroids, clusterID, this[distanceSymbol]);\n }\n\n /**\n * Returns a KMeansResult with the error and size of the cluster\n * @ignore\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @return {KMeansResult}\n */\n computeInformation(data) {\n var enrichedCentroids = this.centroids.map(function (centroid) {\n return {\n centroid: centroid,\n error: 0,\n size: 0\n };\n });\n\n for (var i = 0; i < data.length; i++) {\n enrichedCentroids[this.clusters[i]].error += this[distanceSymbol](\n data[i],\n this.centroids[this.clusters[i]]\n );\n enrichedCentroids[this.clusters[i]].size++;\n }\n\n for (var j = 0; j < this.centroids.length; j++) {\n if (enrichedCentroids[j].size) {\n enrichedCentroids[j].error /= enrichedCentroids[j].size;\n } else {\n enrichedCentroids[j].error = null;\n }\n }\n\n return new KMeansResult(\n this.clusters,\n enrichedCentroids,\n this.converged,\n this.iterations,\n this[distanceSymbol]\n );\n }\n}\n","import { squaredEuclidean } from 'ml-distance-euclidean';\n\nimport {\n updateClusterID,\n updateCenters,\n hasConverged,\n calculateDistanceMatrix\n} from './utils';\nimport { mostDistant, random, kmeanspp } from './initialization';\nimport KMeansResult from './KMeansResult';\n\nconst defaultOptions = {\n maxIterations: 100,\n tolerance: 1e-6,\n withIterations: false,\n initialization: 'kmeans++',\n distanceFunction: squaredEuclidean\n};\n\n/**\n * Each step operation for kmeans\n * @ignore\n * @param {Array>} centers - K centers in format [x,y,z,...]\n * @param {Array>} data - Points [x,y,z,...] to cluster\n * @param {Array} clusterID - Cluster identifier for each data dot\n * @param {number} K - Number of clusters\n * @param {object} [options] - Option object\n * @param {number} iterations - Current number of iterations\n * @return {KMeansResult}\n */\nfunction step(centers, data, clusterID, K, options, iterations) {\n clusterID = updateClusterID(\n data,\n centers,\n clusterID,\n options.distanceFunction\n );\n var newCenters = updateCenters(centers, data, clusterID, K);\n var converged = hasConverged(\n newCenters,\n centers,\n options.distanceFunction,\n options.tolerance\n );\n return new KMeansResult(\n clusterID,\n newCenters,\n converged,\n iterations,\n options.distanceFunction\n );\n}\n\n/**\n * Generator version for the algorithm\n * @ignore\n * @param {Array>} centers - K centers in format [x,y,z,...]\n * @param {Array>} data - Points [x,y,z,...] to cluster\n * @param {Array} clusterID - Cluster identifier for each data dot\n * @param {number} K - Number of clusters\n * @param {object} [options] - Option object\n */\nfunction* kmeansGenerator(centers, data, clusterID, K, options) {\n var converged = false;\n var stepNumber = 0;\n var stepResult;\n while (!converged && stepNumber < options.maxIterations) {\n stepResult = step(centers, data, clusterID, K, options, ++stepNumber);\n yield stepResult.computeInformation(data);\n converged = stepResult.converged;\n centers = stepResult.centroids;\n }\n}\n\n/**\n * K-means algorithm\n * @param {Array>} data - Points in the format to cluster [x,y,z,...]\n * @param {number} K - Number of clusters\n * @param {object} [options] - Option object\n * @param {number} [options.maxIterations = 100] - Maximum of iterations allowed\n * @param {number} [options.tolerance = 1e-6] - Error tolerance\n * @param {boolean} [options.withIterations = false] - Store clusters and centroids for each iteration\n * @param {function} [options.distanceFunction = squaredDistance] - Distance function to use between the points\n * @param {number} [options.seed] - Seed for random initialization.\n * @param {string|Array>} [options.initialization = 'kmeans++'] - K centers in format [x,y,z,...] or a method for initialize the data:\n * * You can either specify your custom start centroids, or select one of the following initialization method:\n * * `'kmeans++'` will use the kmeans++ method as described by http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf\n * * `'random'` will choose K random different values.\n * * `'mostDistant'` will choose the more distant points to a first random pick\n * @return {KMeansResult} - Cluster identifier for each data dot and centroids with the following fields:\n * * `'clusters'`: Array of indexes for the clusters.\n * * `'centroids'`: Array with the resulting centroids.\n * * `'iterations'`: Number of iterations that took to converge\n */\nexport default function kmeans(data, K, options) {\n options = Object.assign({}, defaultOptions, options);\n\n if (K <= 0 || K > data.length || !Number.isInteger(K)) {\n throw new Error(\n 'K should be a positive integer smaller than the number of points'\n );\n }\n\n var centers;\n if (Array.isArray(options.initialization)) {\n if (options.initialization.length !== K) {\n throw new Error('The initial centers should have the same length as K');\n } else {\n centers = options.initialization;\n }\n } else {\n switch (options.initialization) {\n case 'kmeans++':\n centers = kmeanspp(data, K, options);\n break;\n case 'random':\n centers = random(data, K, options.seed);\n break;\n case 'mostDistant':\n centers = mostDistant(\n data,\n K,\n calculateDistanceMatrix(data, options.distanceFunction),\n options.seed\n );\n break;\n default:\n throw new Error(\n `Unknown initialization method: \"${options.initialization}\"`\n );\n }\n }\n\n // infinite loop until convergence\n if (options.maxIterations === 0) {\n options.maxIterations = Number.MAX_VALUE;\n }\n\n var clusterID = new Array(data.length);\n if (options.withIterations) {\n return kmeansGenerator(centers, data, clusterID, K, options);\n } else {\n var converged = false;\n var stepNumber = 0;\n var stepResult;\n while (!converged && stepNumber < options.maxIterations) {\n stepResult = step(centers, data, clusterID, K, options, ++stepNumber);\n converged = stepResult.converged;\n centers = stepResult.centroids;\n }\n return stepResult.computeInformation(data);\n }\n}\n","import Random from 'random-js';\nimport Matrix from 'ml-matrix';\n\nexport function checkFloat(n) {\n return n > 0.0 && n <= 1.0;\n}\n\n/**\n * Select n with replacement elements on the training set and values, where n is the size of the training set.\n * @ignore\n * @param {Matrix} trainingSet\n * @param {Array} trainingValue\n * @param {number} seed - seed for the random selection, must be a 32-bit integer.\n * @return {object} with new X and y.\n */\nexport function examplesBaggingWithReplacement(trainingSet, trainingValue, seed) {\n var engine = Random.engines.mt19937();\n var distribution = Random.integer(0, trainingSet.rows - 1);\n if (seed === undefined) {\n engine = engine.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = engine.seed(seed);\n } else {\n throw new RangeError(`Expected seed must be undefined or integer not ${seed}`);\n }\n\n var Xr = new Array(trainingSet.rows);\n var yr = new Array(trainingSet.rows);\n\n for (var i = 0; i < trainingSet.rows; ++i) {\n var index = distribution(engine);\n Xr[i] = trainingSet[index];\n yr[i] = trainingValue[index];\n }\n\n return {\n X: new Matrix(Xr),\n y: yr\n };\n}\n\n/**\n * selects n features from the training set with or without replacement, returns the new training set and the indexes used.\n * @ignore\n * @param {Matrix} trainingSet\n * @param {number} n - features.\n * @param {boolean} replacement\n * @param {number} seed - seed for the random selection, must be a 32-bit integer.\n * @return {object}\n */\nexport function featureBagging(trainingSet, n, replacement, seed) {\n if (trainingSet.columns < n) {\n throw new RangeError('N should be less or equal to the number of columns of X');\n }\n\n var distribution = Random.integer(0, trainingSet.columns - 1);\n var engine = Random.engines.mt19937();\n if (seed === undefined) {\n engine = engine.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = engine.seed(seed);\n } else {\n throw new RangeError(`Expected seed must be undefined or integer not ${seed}`);\n }\n\n var toRet = new Matrix(trainingSet.rows, n);\n\n if (replacement) {\n var usedIndex = new Array(n);\n for (var i = 0; i < n; ++i) {\n var index = distribution(engine);\n usedIndex[i] = index;\n toRet.setColumn(i, trainingSet.getColumn(index));\n }\n } else {\n usedIndex = new Set();\n index = distribution(engine);\n for (i = 0; i < n; ++i) {\n while (usedIndex.has(index)) {\n index = distribution(engine);\n }\n toRet.setColumn(i, trainingSet.getColumn(index));\n usedIndex.add(index);\n }\n usedIndex = Array.from(usedIndex);\n }\n\n return {\n X: toRet,\n usedIndex: usedIndex\n };\n}\n","import {\n DecisionTreeClassifier as DTClassifier,\n DecisionTreeRegression as DTRegression\n} from 'ml-cart';\nimport { Matrix, WrapperMatrix2D } from 'ml-matrix';\n\nimport * as Utils from './utils';\n\n/**\n * @class RandomForestBase\n */\nexport class RandomForestBase {\n /**\n * Create a new base random forest for a classifier or regression model.\n * @constructor\n * @param {object} options\n * @param {number|String} [options.maxFeatures] - the number of features used on each estimator.\n * * if is an integer it selects maxFeatures elements over the sample features.\n * * if is a float between (0, 1), it takes the percentage of features.\n * @param {boolean} [options.replacement] - use replacement over the sample features.\n * @param {number} [options.seed] - seed for feature and samples selection, must be a 32-bit integer.\n * @param {number} [options.nEstimators] - number of estimator to use.\n * @param {object} [options.treeOptions] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/}\n * @param {boolean} [options.isClassifier] - boolean to check if is a classifier or regression model (used by subclasses).\n * @param {boolean} [options.useSampleBagging] - use bagging over training samples.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.replacement = model.replacement;\n this.maxFeatures = model.maxFeatures;\n this.nEstimators = model.nEstimators;\n this.treeOptions = model.treeOptions;\n this.isClassifier = model.isClassifier;\n this.seed = model.seed;\n this.n = model.n;\n this.indexes = model.indexes;\n this.useSampleBagging = model.useSampleBagging;\n\n var Estimator = this.isClassifier ? DTClassifier : DTRegression;\n this.estimators = model.estimators.map((est) => Estimator.load(est));\n } else {\n this.replacement = options.replacement;\n this.maxFeatures = options.maxFeatures;\n this.nEstimators = options.nEstimators;\n this.treeOptions = options.treeOptions;\n this.isClassifier = options.isClassifier;\n this.seed = options.seed;\n this.useSampleBagging = options.useSampleBagging;\n }\n }\n\n /**\n * Train the decision tree with the given training set and labels.\n * @param {Matrix|Array} trainingSet\n * @param {Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n\n this.maxFeatures = this.maxFeatures || trainingSet.columns;\n\n if (Utils.checkFloat(this.maxFeatures)) {\n this.n = Math.floor(trainingSet.columns * this.maxFeatures);\n } else if (Number.isInteger(this.maxFeatures)) {\n if (this.maxFeatures > trainingSet.columns) {\n throw new RangeError(`The maxFeatures parameter should be less than ${trainingSet.columns}`);\n } else {\n this.n = this.maxFeatures;\n }\n } else {\n throw new RangeError(`Cannot process the maxFeatures parameter ${this.maxFeatures}`);\n }\n\n\n if (this.isClassifier) {\n var Estimator = DTClassifier;\n } else {\n Estimator = DTRegression;\n }\n\n this.estimators = new Array(this.nEstimators);\n this.indexes = new Array(this.nEstimators);\n\n for (var i = 0; i < this.nEstimators; ++i) {\n var res = this.useSampleBagging ? Utils.examplesBaggingWithReplacement(trainingSet, trainingValues, this.seed) : { X: trainingSet, y: trainingValues };\n var X = res.X;\n var y = res.y;\n\n res = Utils.featureBagging(X, this.n, this.replacement, this.seed);\n X = res.X;\n\n this.indexes[i] = res.usedIndex;\n this.estimators[i] = new Estimator(this.treeOptions);\n this.estimators[i].train(X, y);\n }\n }\n\n /**\n * Method that returns the way the algorithm generates the predictions, for example, in classification\n * you can return the mode of all predictions retrieved by the trees, or in case of regression you can\n * use the mean or the median.\n * @abstract\n * @param {Array} values - predictions of the estimators.\n * @return {number} prediction.\n */\n // eslint-disable-next-line no-unused-vars\n selection(values) {\n throw new Error('Abstract method \\'selection\\' not implemented!');\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Matrix|Array} toPredict\n * @return {Array} predictions\n */\n predict(toPredict) {\n var predictionValues = new Array(this.nEstimators);\n toPredict = Matrix.checkMatrix(toPredict);\n for (var i = 0; i < this.nEstimators; ++i) {\n var X = toPredict.columnSelectionView(this.indexes[i]); // get features for estimator\n predictionValues[i] = this.estimators[i].predict(X);\n }\n\n predictionValues = new WrapperMatrix2D(predictionValues).transposeView();\n var predictions = new Array(predictionValues.rows);\n for (i = 0; i < predictionValues.rows; ++i) {\n predictions[i] = this.selection(predictionValues.getRow(i));\n }\n\n return predictions;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n indexes: this.indexes,\n n: this.n,\n replacement: this.replacement,\n maxFeatures: this.maxFeatures,\n nEstimators: this.nEstimators,\n treeOptions: this.treeOptions,\n isClassifier: this.isClassifier,\n seed: this.seed,\n estimators: this.estimators.map((est) => est.toJSON()),\n useSampleBagging: this.useSampleBagging\n };\n }\n}\n","import { RandomForestBase } from './RandomForestBase';\n\nconst defaultOptions = {\n maxFeatures: 1.0,\n replacement: true,\n nEstimators: 10,\n seed: 42,\n useSampleBagging: false\n};\n\n/**\n * @class RandomForestClassifier\n * @augments RandomForestBase\n */\nexport class RandomForestClassifier extends RandomForestBase {\n /**\n * Create a new base random forest for a classifier or regression model.\n * @constructor\n * @param {object} options\n * @param {number} [options.maxFeatures=1.0] - the number of features used on each estimator.\n * * if is an integer it selects maxFeatures elements over the sample features.\n * * if is a float between (0, 1), it takes the percentage of features.\n * @param {boolean} [options.replacement=true] - use replacement over the sample features.\n * @param {number} [options.seed=42] - seed for feature and samples selection, must be a 32-bit integer.\n * @param {number} [options.nEstimators=10] - number of estimator to use.\n * @param {object} [options.treeOptions={}] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/}\n * @param {boolean} [options.useSampleBagging=false] - use bagging over training samples.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n super(true, model.baseModel);\n } else {\n options = Object.assign({}, defaultOptions, options);\n options.isClassifier = true;\n super(options);\n }\n }\n\n /**\n * retrieve the prediction given the selection method.\n * @param {Array} values - predictions of the estimators.\n * @return {number} prediction\n */\n selection(values) {\n return mode(values);\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n var baseModel = super.toJSON();\n return {\n baseModel: baseModel,\n name: 'RFClassifier'\n };\n }\n\n /**\n * Load a Decision tree classifier with the given model.\n * @param {object} model\n * @return {RandomForestClassifier}\n */\n static load(model) {\n if (model.name !== 'RFClassifier') {\n throw new RangeError(`Invalid model: ${model.name}`);\n }\n\n return new RandomForestClassifier(true, model);\n }\n}\n\n/**\n * Return the most repeated element on the array.\n * @param {Array} arr\n * @return {number} mode\n */\nfunction mode(arr) {\n return arr.sort((a, b) =>\n arr.filter((v) => v === a).length\n - arr.filter((v) => v === b).length\n ).pop();\n}\n","import arrayMean from 'ml-array-mean';\nimport arrayMedian from 'ml-array-median';\n\nimport { RandomForestBase } from './RandomForestBase';\n\nconst selectionMethods = {\n mean: arrayMean,\n median: arrayMedian\n};\n\nconst defaultOptions = {\n maxFeatures: 1.0,\n replacement: false,\n nEstimators: 10,\n treeOptions: {},\n selectionMethod: 'mean',\n seed: 42,\n useSampleBagging: false\n};\n\n/**\n * @class RandomForestRegression\n * @augments RandomForestBase\n */\nexport class RandomForestRegression extends RandomForestBase {\n /**\n * Create a new base random forest for a classifier or regression model.\n * @constructor\n * @param {object} options\n * @param {number} [options.maxFeatures=1.0] - the number of features used on each estimator.\n * * if is an integer it selects maxFeatures elements over the sample features.\n * * if is a float between (0, 1), it takes the percentage of features.\n * @param {boolean} [options.replacement=true] - use replacement over the sample features.\n * @param {number} [options.seed=42] - seed for feature and samples selection, must be a 32-bit integer.\n * @param {number} [options.nEstimators=10] - number of estimator to use.\n * @param {object} [options.treeOptions={}] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/}\n * @param {string} [options.selectionMethod=\"mean\"] - the way to calculate the prediction from estimators, \"mean\" and \"median\" are supported.\n * @param {boolean} [options.useSampleBagging=false] - use bagging over training samples.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n super(true, model.baseModel);\n this.selectionMethod = model.selectionMethod;\n } else {\n options = Object.assign({}, defaultOptions, options);\n\n if (!(options.selectionMethod === 'mean' || options.selectionMethod === 'median')) {\n throw new RangeError(`Unsupported selection method ${options.selectionMethod}`);\n }\n\n options.isClassifier = false;\n\n super(options);\n this.selectionMethod = options.selectionMethod;\n }\n }\n\n /**\n * retrieve the prediction given the selection method.\n * @param {Array} values - predictions of the estimators.\n * @return {number} prediction\n */\n selection(values) {\n return selectionMethods[this.selectionMethod](values);\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n var baseModel = super.toJSON();\n return {\n baseModel: baseModel,\n selectionMethod: this.selectionMethod,\n name: 'RFRegression'\n };\n }\n\n /**\n * Load a Decision tree classifier with the given model.\n * @param {object} model\n * @return {RandomForestRegression}\n */\n static load(model) {\n if (model.name !== 'RFRegression') {\n throw new RangeError(`Invalid model: ${model.name}`);\n }\n\n return new RandomForestRegression(true, model);\n }\n}\n","export { RandomForestClassifier } from './RandomForestClassifier';\nexport { RandomForestRegression } from './RandomForestRegression';\n","import Matrix from 'ml-matrix';\nimport Stat from 'ml-stat/matrix';\n\n/**\n * @private\n * Function that given vector, returns his norm\n * @param {Vector} X\n * @return {number} Norm of the vector\n */\nexport function norm(X) {\n return Math.sqrt(X.clone().apply(pow2array).sum());\n}\n\n/**\n * @private\n * Function that pow 2 each element of a Matrix or a Vector,\n * used in the apply method of the Matrix object\n * @param {number} i - index i.\n * @param {number} j - index j.\n * @return {Matrix} The Matrix object modified at the index i, j.\n * */\nexport function pow2array(i, j) {\n this[i][j] = this[i][j] * this[i][j];\n return this;\n}\n\n/**\n * @private\n * Function that normalize the dataset and return the means and\n * standard deviation of each feature.\n * @param {Matrix} dataset\n * @return {object} dataset normalized, means and standard deviations\n */\nexport function featureNormalize(dataset) {\n var means = Stat.mean(dataset);\n var std = Stat.standardDeviation(dataset, means, true);\n var result = Matrix.checkMatrix(dataset).subRowVector(means);\n return {result: result.divRowVector(std), means: means, std: std};\n}\n\n/**\n * @private\n * Function that initialize an array of matrices.\n * @param {Array} array\n * @param {boolean} isMatrix\n * @return {Array} array with the matrices initialized.\n */\nexport function initializeMatrices(array, isMatrix) {\n if (isMatrix) {\n for (var i = 0; i < array.length; ++i) {\n for (var j = 0; j < array[i].length; ++j) {\n var elem = array[i][j];\n array[i][j] = elem !== null ? new Matrix(array[i][j]) : undefined;\n }\n }\n } else {\n for (i = 0; i < array.length; ++i) {\n array[i] = new Matrix(array[i]);\n }\n }\n\n return array;\n}\n","import Matrix from 'ml-matrix';\nimport Stat from 'ml-stat/matrix';\nimport * as Utils from './utils';\n\n/**\n * @class PLS\n */\nexport class PLS {\n\n /**\n * Constructor for Partial Least Squares (PLS)\n * @param {object} options\n * @param {number} [options.latentVectors] - Number of latent vector to get (if the algorithm doesn't find a good model below the tolerance)\n * @param {number} [options.tolerance=1e-5]\n * @param {boolean} [options.scale=true] - rescale dataset using mean.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.meanX = model.meanX;\n this.stdDevX = model.stdDevX;\n this.meanY = model.meanY;\n this.stdDevY = model.stdDevY;\n this.PBQ = Matrix.checkMatrix(model.PBQ);\n this.R2X = model.R2X;\n this.scale = model.scale;\n this.scaleMethod = model.scaleMethod;\n this.tolerance = model.tolerance;\n } else {\n var {\n tolerance = 1e-5,\n scale = true,\n } = options;\n this.tolerance = tolerance;\n this.scale = scale;\n this.latentVectors = options.latentVectors;\n }\n }\n\n /**\n * Fits the model with the given data and predictions, in this function is calculated the\n * following outputs:\n *\n * T - Score matrix of X\n * P - Loading matrix of X\n * U - Score matrix of Y\n * Q - Loading matrix of Y\n * B - Matrix of regression coefficient\n * W - Weight matrix of X\n *\n * @param {Matrix|Array} trainingSet\n * @param {Matrix|Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n trainingValues = Matrix.checkMatrix(trainingValues);\n\n if (trainingSet.length !== trainingValues.length) {\n throw new RangeError('The number of X rows must be equal to the number of Y rows');\n }\n\n this.meanX = Stat.mean(trainingSet);\n this.stdDevX = Stat.standardDeviation(trainingSet, this.meanX, true);\n this.meanY = Stat.mean(trainingValues);\n this.stdDevY = Stat.standardDeviation(trainingValues, this.meanY, true);\n\n if (this.scale) { // here should be the ml-preprocess project\n trainingSet = trainingSet.clone().subRowVector(this.meanX).divRowVector(this.stdDevX);\n trainingValues = trainingValues.clone().subRowVector(this.meanY).divRowVector(this.stdDevY);\n }\n\n if (this.latentVectors === undefined) {\n this.latentVectors = Math.min(trainingSet.length - 1, trainingSet[0].length);\n }\n\n var rx = trainingSet.rows;\n var cx = trainingSet.columns;\n var ry = trainingValues.rows;\n var cy = trainingValues.columns;\n\n var ssqXcal = trainingSet.clone().mul(trainingSet).sum(); // for the r²\n var sumOfSquaresY = trainingValues.clone().mul(trainingValues).sum();\n\n var tolerance = this.tolerance;\n var n = this.latentVectors;\n var T = Matrix.zeros(rx, n);\n var P = Matrix.zeros(cx, n);\n var U = Matrix.zeros(ry, n);\n var Q = Matrix.zeros(cy, n);\n var B = Matrix.zeros(n, n);\n var W = P.clone();\n var k = 0;\n\n while (Utils.norm(trainingValues) > tolerance && k < n) {\n var transposeX = trainingSet.transpose();\n var transposeY = trainingValues.transpose();\n\n var tIndex = maxSumColIndex(trainingSet.clone().mulM(trainingSet));\n var uIndex = maxSumColIndex(trainingValues.clone().mulM(trainingValues));\n\n var t1 = trainingSet.getColumnVector(tIndex);\n var u = trainingValues.getColumnVector(uIndex);\n var t = Matrix.zeros(rx, 1);\n\n while (Utils.norm(t1.clone().sub(t)) > tolerance) {\n var w = transposeX.mmul(u);\n w.div(Utils.norm(w));\n t = t1;\n t1 = trainingSet.mmul(w);\n var q = transposeY.mmul(t1);\n q.div(Utils.norm(q));\n u = trainingValues.mmul(q);\n }\n\n t = t1;\n var num = transposeX.mmul(t);\n var den = (t.transpose().mmul(t))[0][0];\n var p = num.div(den);\n var pnorm = Utils.norm(p);\n p.div(pnorm);\n t.mul(pnorm);\n w.mul(pnorm);\n\n num = u.transpose().mmul(t);\n den = (t.transpose().mmul(t))[0][0];\n var b = (num.div(den))[0][0];\n trainingSet.sub(t.mmul(p.transpose()));\n trainingValues.sub(t.clone().mul(b).mmul(q.transpose()));\n\n T.setColumn(k, t);\n P.setColumn(k, p);\n U.setColumn(k, u);\n Q.setColumn(k, q);\n W.setColumn(k, w);\n\n B[k][k] = b;\n k++;\n }\n\n k--;\n T = T.subMatrix(0, T.rows - 1, 0, k);\n P = P.subMatrix(0, P.rows - 1, 0, k);\n U = U.subMatrix(0, U.rows - 1, 0, k);\n Q = Q.subMatrix(0, Q.rows - 1, 0, k);\n W = W.subMatrix(0, W.rows - 1, 0, k);\n B = B.subMatrix(0, k, 0, k);\n\n // TODO: review of R2Y\n //this.R2Y = t.transpose().mmul(t).mul(q[k][0]*q[k][0]).divS(ssqYcal)[0][0];\n //\n this.ssqYcal = sumOfSquaresY;\n this.E = trainingSet;\n this.F = trainingValues;\n this.T = T;\n this.P = P;\n this.U = U;\n this.Q = Q;\n this.W = W;\n this.B = B;\n this.PBQ = P.mmul(B).mmul(Q.transpose());\n this.R2X = t.transpose().mmul(t).mmul(p.transpose().mmul(p)).div(ssqXcal)[0][0];\n }\n\n /**\n * Predicts the behavior of the given dataset.\n * @param {Matrix|Array} dataset - data to be predicted.\n * @return {Matrix} - predictions of each element of the dataset.\n */\n predict(dataset) {\n var X = Matrix.checkMatrix(dataset);\n if (this.scale) {\n X = X.subRowVector(this.meanX).divRowVector(this.stdDevX);\n }\n var Y = X.mmul(this.PBQ);\n Y = Y.mulRowVector(this.stdDevY).addRowVector(this.meanY);\n return Y;\n }\n\n /**\n * Returns the explained variance on training of the PLS model\n * @return {number}\n */\n getExplainedVariance() {\n return this.R2X;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n name: 'PLS',\n R2X: this.R2X,\n meanX: this.meanX,\n stdDevX: this.stdDevX,\n meanY: this.meanY,\n stdDevY: this.stdDevY,\n PBQ: this.PBQ,\n tolerance: this.tolerance,\n scale: this.scale,\n };\n }\n\n /**\n * Load a PLS model from a JSON Object\n * @param {object} model\n * @return {PLS} - PLS object from the given model\n */\n static load(model) {\n if (model.name !== 'PLS') {\n throw new RangeError('Invalid model: ' + model.name);\n }\n return new PLS(true, model);\n }\n}\n\n/**\n * @private\n * Function that returns the index where the sum of each\n * column vector is maximum.\n * @param {Matrix} data\n * @return {number} index of the maximum\n */\nfunction maxSumColIndex(data) {\n return data.sum('column').maxIndex()[0];\n}\n","import {Matrix, SingularValueDecomposition, inverse} from 'ml-matrix';\nimport {initializeMatrices} from './utils';\n\n/**\n * @class KOPLS\n */\nexport class KOPLS {\n\n /**\n * Constructor for Kernel-based Orthogonal Projections to Latent Structures (K-OPLS)\n * @param {object} options\n * @param {number} [options.predictiveComponents] - Number of predictive components to use.\n * @param {number} [options.orthogonalComponents] - Number of Y-Orthogonal components.\n * @param {Kernel} [options.kernel] - Kernel object to apply, see [ml-kernel](https://github.com/mljs/kernel).\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.trainingSet = new Matrix(model.trainingSet);\n this.YLoadingMat = new Matrix(model.YLoadingMat);\n this.SigmaPow = new Matrix(model.SigmaPow);\n this.YScoreMat = new Matrix(model.YScoreMat);\n this.predScoreMat = initializeMatrices(model.predScoreMat, false);\n this.YOrthLoadingVec = initializeMatrices(model.YOrthLoadingVec, false);\n this.YOrthEigen = model.YOrthEigen;\n this.YOrthScoreMat = initializeMatrices(model.YOrthScoreMat, false);\n this.toNorm = initializeMatrices(model.toNorm, false);\n this.TURegressionCoeff = initializeMatrices(model.TURegressionCoeff, false);\n this.kernelX = initializeMatrices(model.kernelX, true);\n this.kernel = model.kernel;\n this.orthogonalComp = model.orthogonalComp;\n this.predictiveComp = model.predictiveComp;\n } else {\n if (options.predictiveComponents === undefined) {\n throw new RangeError('no predictive components found!');\n }\n if (options.orthogonalComponents === undefined) {\n throw new RangeError('no orthogonal components found!');\n }\n if (options.kernel === undefined) {\n throw new RangeError('no kernel found!');\n }\n\n this.orthogonalComp = options.orthogonalComponents;\n this.predictiveComp = options.predictiveComponents;\n this.kernel = options.kernel;\n }\n }\n\n /**\n * Train the K-OPLS model with the given training set and labels.\n * @param {Matrix|Array} trainingSet\n * @param {Matrix|Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n trainingValues = Matrix.checkMatrix(trainingValues);\n\n // to save and compute kernel with the prediction dataset.\n this.trainingSet = trainingSet.clone();\n\n var kernelX = this.kernel.compute(trainingSet);\n\n var Identity = Matrix.eye(kernelX.rows, kernelX.rows, 1);\n var temp = kernelX;\n kernelX = new Matrix(this.orthogonalComp + 1, this.orthogonalComp + 1);\n kernelX[0][0] = temp;\n\n var result = new SingularValueDecomposition(trainingValues.transpose().mmul(kernelX[0][0]).mmul(trainingValues), {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: false\n });\n var YLoadingMat = result.leftSingularVectors;\n var Sigma = result.diagonalMatrix;\n\n YLoadingMat = YLoadingMat.subMatrix(0, YLoadingMat.rows - 1, 0, this.predictiveComp - 1);\n Sigma = Sigma.subMatrix(0, this.predictiveComp - 1, 0, this.predictiveComp - 1);\n\n var YScoreMat = trainingValues.mmul(YLoadingMat);\n\n var predScoreMat = new Array(this.orthogonalComp + 1);\n var TURegressionCoeff = new Array(this.orthogonalComp + 1);\n var YOrthScoreMat = new Array(this.orthogonalComp);\n var YOrthLoadingVec = new Array(this.orthogonalComp);\n var YOrthEigen = new Array(this.orthogonalComp);\n var YOrthScoreNorm = new Array(this.orthogonalComp);\n\n var SigmaPow = Matrix.pow(Sigma, -0.5);\n // to avoid errors, check infinity\n SigmaPow.apply(function (i, j) {\n if (this[i][j] === Infinity) {\n this[i][j] = 0.0;\n }\n });\n\n for (var i = 0; i < this.orthogonalComp; ++i) {\n predScoreMat[i] = kernelX[0][i].transpose().mmul(YScoreMat).mmul(SigmaPow);\n\n var TpiPrime = predScoreMat[i].transpose();\n TURegressionCoeff[i] = inverse(TpiPrime.mmul(predScoreMat[i])).mmul(TpiPrime).mmul(YScoreMat);\n\n result = new SingularValueDecomposition(TpiPrime.mmul(Matrix.sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime))).mmul(predScoreMat[i]), {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: false\n });\n var CoTemp = result.leftSingularVectors;\n var SoTemp = result.diagonalMatrix;\n\n YOrthLoadingVec[i] = CoTemp.subMatrix(0, CoTemp.rows - 1, 0, 0);\n YOrthEigen[i] = SoTemp[0][0];\n\n YOrthScoreMat[i] = Matrix.sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime)).mmul(predScoreMat[i]).mmul(YOrthLoadingVec[i]).mul(Math.pow(YOrthEigen[i], -0.5));\n\n var toiPrime = YOrthScoreMat[i].transpose();\n YOrthScoreNorm[i] = Matrix.sqrt(toiPrime.mmul(YOrthScoreMat[i]));\n\n YOrthScoreMat[i] = YOrthScoreMat[i].divRowVector(YOrthScoreNorm[i]);\n\n var ITo = Matrix.sub(Identity, YOrthScoreMat[i].mmul(YOrthScoreMat[i].transpose()));\n\n kernelX[0][i + 1] = kernelX[0][i].mmul(ITo);\n kernelX[i + 1][i + 1] = ITo.mmul(kernelX[i][i]).mmul(ITo);\n }\n\n var lastScoreMat = predScoreMat[this.orthogonalComp] = kernelX[0][this.orthogonalComp].transpose().mmul(YScoreMat).mmul(SigmaPow);\n\n var lastTpPrime = lastScoreMat.transpose();\n TURegressionCoeff[this.orthogonalComp] = inverse(lastTpPrime.mmul(lastScoreMat)).mmul(lastTpPrime).mmul(YScoreMat);\n\n this.YLoadingMat = YLoadingMat;\n this.SigmaPow = SigmaPow;\n this.YScoreMat = YScoreMat;\n this.predScoreMat = predScoreMat;\n this.YOrthLoadingVec = YOrthLoadingVec;\n this.YOrthEigen = YOrthEigen;\n this.YOrthScoreMat = YOrthScoreMat;\n this.toNorm = YOrthScoreNorm;\n this.TURegressionCoeff = TURegressionCoeff;\n this.kernelX = kernelX;\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Matrix|Array} toPredict\n * @return {{y: Matrix, predScoreMat: Array, predYOrthVectors: Array}} predictions\n */\n predict(toPredict) {\n\n var KTestTrain = this.kernel.compute(toPredict, this.trainingSet);\n\n var temp = KTestTrain;\n KTestTrain = new Matrix(this.orthogonalComp + 1, this.orthogonalComp + 1);\n KTestTrain[0][0] = temp;\n\n var YOrthScoreVector = new Array(this.orthogonalComp);\n var predScoreMat = new Array(this.orthogonalComp);\n\n var i;\n for (i = 0; i < this.orthogonalComp; ++i) {\n predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow);\n\n YOrthScoreVector[i] = Matrix.sub(KTestTrain[i][i], predScoreMat[i].mmul(this.predScoreMat[i].transpose())).mmul(this.predScoreMat[i]).mmul(this.YOrthLoadingVec[i]).mul(Math.pow(this.YOrthEigen[i], -0.5));\n\n YOrthScoreVector[i] = YOrthScoreVector[i].divRowVector(this.toNorm[i]);\n\n var scoreMatPrime = this.YOrthScoreMat[i].transpose();\n KTestTrain[i + 1][0] = Matrix.sub(KTestTrain[i][0], YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[0][i].transpose()));\n\n var p1 = Matrix.sub(KTestTrain[i][0], KTestTrain[i][i].mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime));\n var p2 = YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[i][i]);\n var p3 = p2.mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime);\n\n KTestTrain[i + 1][i + 1] = p1.sub(p2).add(p3);\n }\n\n predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow);\n var prediction = predScoreMat[i].mmul(this.TURegressionCoeff[i]).mmul(this.YLoadingMat.transpose());\n\n return {\n prediction: prediction,\n predScoreMat: predScoreMat,\n predYOrthVectors: YOrthScoreVector\n };\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n name: 'K-OPLS',\n YLoadingMat: this.YLoadingMat,\n SigmaPow: this.SigmaPow,\n YScoreMat: this.YScoreMat,\n predScoreMat: this.predScoreMat,\n YOrthLoadingVec: this.YOrthLoadingVec,\n YOrthEigen: this.YOrthEigen,\n YOrthScoreMat: this.YOrthScoreMat,\n toNorm: this.toNorm,\n TURegressionCoeff: this.TURegressionCoeff,\n kernelX: this.kernelX,\n trainingSet: this.trainingSet,\n orthogonalComp: this.orthogonalComp,\n predictiveComp: this.predictiveComp\n };\n }\n\n /**\n * Load a K-OPLS with the given model.\n * @param {object} model\n * @param {Kernel} kernel - kernel used on the model, see [ml-kernel](https://github.com/mljs/kernel).\n * @return {KOPLS}\n */\n static load(model, kernel) {\n if (model.name !== 'K-OPLS') {\n throw new RangeError('Invalid model: ' + model.name);\n }\n\n if (!kernel) {\n throw new RangeError('You must provide a kernel for the model!');\n }\n\n model.kernel = kernel;\n return new KOPLS(true, model);\n }\n}\n","export {PLS} from './pls';\nexport {KOPLS} from './kopls';\n","import Matrix from 'ml-matrix';\n\n/**\n * @private\n * Function that retuns an array of matrices of the cases that belong to each class.\n * @param {Matrix} X - dataset\n * @param {Array} y - predictions\n * @return {Array}\n */\nexport function separateClasses(X, y) {\n var features = X.columns;\n\n var classes = 0;\n var totalPerClasses = new Array(10000); // max upperbound of classes\n for (var i = 0; i < y.length; i++) {\n if (totalPerClasses[y[i]] === undefined) {\n totalPerClasses[y[i]] = 0;\n classes++;\n }\n totalPerClasses[y[i]]++;\n }\n var separatedClasses = new Array(classes);\n var currentIndex = new Array(classes);\n for (i = 0; i < classes; ++i) {\n separatedClasses[i] = new Matrix(totalPerClasses[i], features);\n currentIndex[i] = 0;\n }\n for (i = 0; i < X.rows; ++i) {\n separatedClasses[y[i]].setRow(currentIndex[y[i]], X.getRow(i));\n currentIndex[y[i]]++;\n }\n return separatedClasses;\n}\n","import Matrix from 'ml-matrix';\nimport Stat from 'ml-stat';\nimport {separateClasses} from './utils';\n\n/**\n * @class GaussianNB\n */\nexport class GaussianNB {\n\n /**\n * @constructor\n * Constructor for the Gaussian Naive Bayes classifier, the parameters here is just for loading purposes.\n *\n * @param {boolean} reload\n * @param {object} model\n */\n constructor(reload, model) {\n if (reload) {\n this.means = model.means;\n this.calculateProbabilities = model.calculateProbabilities;\n }\n }\n\n /**\n * Function that trains the classifier with a matrix that represents the training set and an array that\n * represents the label of each row in the training set. the labels must be numbers between 0 to n-1 where\n * n represents the number of classes.\n *\n * WARNING: in the case that one class, all the cases in one or more features have the same value, the\n * Naive Bayes classifier will not work well.\n * @param {Matrix|Array} trainingSet\n * @param {Matrix|Array} trainingLabels\n */\n train(trainingSet, trainingLabels) {\n var C1 = Math.sqrt(2 * Math.PI); // constant to precalculate the squared root\n trainingSet = Matrix.checkMatrix(trainingSet);//if (!Matrix.isMatrix(trainingSet)) trainingSet = new Matrix(trainingSet);\n\n if (trainingSet.rows !== trainingLabels.length) {\n throw new RangeError('the size of the training set and the training labels must be the same.');\n }\n\n var separatedClasses = separateClasses(trainingSet, trainingLabels);\n var calculateProbabilities = new Array(separatedClasses.length);\n this.means = new Array(separatedClasses.length);\n for (var i = 0; i < separatedClasses.length; ++i) {\n var means = Stat.matrix.mean(separatedClasses[i]);\n var std = Stat.matrix.standardDeviation(separatedClasses[i], means);\n\n var logPriorProbability = Math.log(separatedClasses[i].rows / trainingSet.rows);\n calculateProbabilities[i] = new Array(means.length + 1);\n\n calculateProbabilities[i][0] = logPriorProbability;\n for (var j = 1; j < means.length + 1; ++j) {\n var currentStd = std[j - 1];\n calculateProbabilities[i][j] = [(1 / (C1 * currentStd)), -2 * currentStd * currentStd];\n }\n\n this.means[i] = means;\n }\n\n this.calculateProbabilities = calculateProbabilities;\n }\n\n /**\n * function that predicts each row of the dataset (must be a matrix).\n *\n * @param {Matrix|Array} dataset\n * @return {Array}\n */\n predict(dataset) {\n if (dataset[0].length === this.calculateProbabilities[0].length) {\n throw new RangeError('the dataset must have the same features as the training set');\n }\n\n var predictions = new Array(dataset.length);\n\n for (var i = 0; i < predictions.length; ++i) {\n predictions[i] = getCurrentClass(dataset[i], this.means, this.calculateProbabilities);\n }\n\n return predictions;\n }\n\n /**\n * Function that export the NaiveBayes model.\n * @return {object}\n */\n toJSON() {\n return {\n modelName: 'NaiveBayes',\n means: this.means,\n calculateProbabilities: this.calculateProbabilities\n };\n }\n\n /**\n * Function that create a GaussianNB classifier with the given model.\n * @param {object} model\n * @return {GaussianNB}\n */\n static load(model) {\n if (model.modelName !== 'NaiveBayes') {\n throw new RangeError('The current model is not a Multinomial Naive Bayes, current model:', model.name);\n }\n\n return new GaussianNB(true, model);\n }\n}\n\n/**\n * @private\n * Function the retrieves a prediction with one case.\n *\n * @param {Array} currentCase\n * @param {Array} mean - Precalculated means of each class trained\n * @param {Array} classes - Precalculated value of each class (Prior probability and probability function of each feature)\n * @return {number}\n */\nfunction getCurrentClass(currentCase, mean, classes) {\n var maxProbability = 0;\n var predictedClass = -1;\n\n // going through all precalculated values for the classes\n for (var i = 0; i < classes.length; ++i) {\n var currentProbability = classes[i][0]; // initialize with the prior probability\n for (var j = 1; j < classes[0][1].length + 1; ++j) {\n currentProbability += calculateLogProbability(currentCase[j - 1], mean[i][j - 1], classes[i][j][0], classes[i][j][1]);\n }\n\n currentProbability = Math.exp(currentProbability);\n if (currentProbability > maxProbability) {\n maxProbability = currentProbability;\n predictedClass = i;\n }\n }\n\n return predictedClass;\n}\n\n/**\n * @private\n * function that retrieves the probability of the feature given the class.\n * @param {number} value - value of the feature.\n * @param {number} mean - mean of the feature for the given class.\n * @param {number} C1 - precalculated value of (1 / (sqrt(2*pi) * std)).\n * @param {number} C2 - precalculated value of (2 * std^2) for the denominator of the exponential.\n * @return {number}\n */\nfunction calculateLogProbability(value, mean, C1, C2) {\n value = value - mean;\n return Math.log(C1 * Math.exp((value * value) / C2));\n}\n","import Matrix from 'ml-matrix';\nimport {separateClasses} from './utils';\n\n/**\n * @class MultinomialNB\n */\nexport class MultinomialNB {\n\n /**\n * @constructor\n * Constructor for Multinomial Naive Bayes, the model parameter is for load purposes.\n *\n * @param {object} model - for load purposes.\n */\n constructor(model) {\n if (model) {\n this.conditionalProbability = Matrix.checkMatrix(model.conditionalProbability);\n this.priorProbability = Matrix.checkMatrix(model.priorProbability);\n }\n }\n\n /**\n * Train the classifier with the current training set and labels, the labels must be numbers between 0 and n.\n * @param {Matrix|Array} trainingSet\n * @param {Array} trainingLabels\n */\n train(trainingSet, trainingLabels) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n\n if (trainingSet.rows !== trainingLabels.length) {\n throw new RangeError('the size of the training set and the training labels must be the same.');\n }\n\n var separateClass = separateClasses(trainingSet, trainingLabels);\n this.priorProbability = new Matrix(separateClass.length, 1);\n\n for (var i = 0; i < separateClass.length; ++i) {\n this.priorProbability[i][0] = Math.log(separateClass[i].length / trainingSet.rows);\n }\n\n var features = trainingSet.columns;\n this.conditionalProbability = new Matrix(separateClass.length, features);\n for (i = 0; i < separateClass.length; ++i) {\n var classValues = Matrix.checkMatrix(separateClass[i]);\n var total = classValues.sum();\n var divisor = total + features;\n this.conditionalProbability.setRow(i, classValues.sum('column').add(1).div(divisor).apply(matrixLog));\n }\n }\n\n /**\n * Retrieves the predictions for the dataset with the current model.\n * @param {Matrix|Array} dataset\n * @return {Array} - predictions from the dataset.\n */\n predict(dataset) {\n dataset = Matrix.checkMatrix(dataset);\n var predictions = new Array(dataset.rows);\n for (var i = 0; i < dataset.rows; ++i) {\n var currentElement = dataset.getRowVector(i);\n predictions[i] = this.conditionalProbability.clone().mulRowVector(currentElement).sum('row')\n .add(this.priorProbability).maxIndex()[0];\n }\n\n return predictions;\n }\n\n /**\n * Function that saves the current model.\n * @return {object} - model in JSON format.\n */\n toJSON() {\n return {\n name: 'MultinomialNB',\n priorProbability: this.priorProbability,\n conditionalProbability: this.conditionalProbability\n };\n }\n\n /**\n * Creates a new MultinomialNB from the given model\n * @param {object} model\n * @return {MultinomialNB}\n */\n static load(model) {\n if (model.name !== 'MultinomialNB') {\n throw new RangeError(`${model.name} is not a Multinomial Naive Bayes`);\n }\n\n return new MultinomialNB(model);\n }\n}\n\nfunction matrixLog(i, j) {\n this[i][j] = Math.log(this[i][j]);\n}\n","export {GaussianNB} from './GaussianNB';\nexport {MultinomialNB} from './MultinomialNB';\n","/*\n * Original code from:\n *\n * k-d Tree JavaScript - V 1.01\n *\n * https://github.com/ubilabs/kd-tree-javascript\n *\n * @author Mircea Pricop , 2012\n * @author Martin Kleppe , 2012\n * @author Ubilabs http://ubilabs.net, 2012\n * @license MIT License \n */\n\nfunction Node(obj, dimension, parent) {\n this.obj = obj;\n this.left = null;\n this.right = null;\n this.parent = parent;\n this.dimension = dimension;\n}\n\nexport default class KDTree {\n constructor(points, metric) {\n // If points is not an array, assume we're loading a pre-built tree\n if (!Array.isArray(points)) {\n this.dimensions = points.dimensions;\n this.root = points;\n restoreParent(this.root);\n } else {\n this.dimensions = new Array(points[0].length);\n for (var i = 0; i < this.dimensions.length; i++) {\n this.dimensions[i] = i;\n }\n this.root = buildTree(points, 0, null, this.dimensions);\n }\n this.metric = metric;\n }\n\n // Convert to a JSON serializable structure; this just requires removing\n // the `parent` property\n toJSON() {\n const result = toJSONImpl(this.root, true);\n result.dimensions = this.dimensions;\n return result;\n }\n\n nearest(point, maxNodes, maxDistance) {\n const metric = this.metric;\n const dimensions = this.dimensions;\n var i;\n\n const bestNodes = new BinaryHeap(\n function (e) {\n return -e[1];\n }\n );\n\n function nearestSearch(node) {\n const dimension = dimensions[node.dimension];\n const ownDistance = metric(point, node.obj);\n const linearPoint = {};\n var bestChild,\n linearDistance,\n otherChild,\n i;\n\n function saveNode(node, distance) {\n bestNodes.push([node, distance]);\n if (bestNodes.size() > maxNodes) {\n bestNodes.pop();\n }\n }\n\n for (i = 0; i < dimensions.length; i += 1) {\n if (i === node.dimension) {\n linearPoint[dimensions[i]] = point[dimensions[i]];\n } else {\n linearPoint[dimensions[i]] = node.obj[dimensions[i]];\n }\n }\n\n linearDistance = metric(linearPoint, node.obj);\n\n if (node.right === null && node.left === null) {\n if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {\n saveNode(node, ownDistance);\n }\n return;\n }\n\n if (node.right === null) {\n bestChild = node.left;\n } else if (node.left === null) {\n bestChild = node.right;\n } else {\n if (point[dimension] < node.obj[dimension]) {\n bestChild = node.left;\n } else {\n bestChild = node.right;\n }\n }\n\n nearestSearch(bestChild);\n\n if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {\n saveNode(node, ownDistance);\n }\n\n if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) {\n if (bestChild === node.left) {\n otherChild = node.right;\n } else {\n otherChild = node.left;\n }\n if (otherChild !== null) {\n nearestSearch(otherChild);\n }\n }\n }\n\n if (maxDistance) {\n for (i = 0; i < maxNodes; i += 1) {\n bestNodes.push([null, maxDistance]);\n }\n }\n\n if (this.root) {\n nearestSearch(this.root);\n }\n\n const result = [];\n for (i = 0; i < Math.min(maxNodes, bestNodes.content.length); i += 1) {\n if (bestNodes.content[i][0]) {\n result.push([bestNodes.content[i][0].obj, bestNodes.content[i][1]]);\n }\n }\n return result;\n }\n}\n\nfunction toJSONImpl(src) {\n const dest = new Node(src.obj, src.dimension, null);\n if (src.left) dest.left = toJSONImpl(src.left);\n if (src.right) dest.right = toJSONImpl(src.right);\n return dest;\n}\n\nfunction buildTree(points, depth, parent, dimensions) {\n const dim = depth % dimensions.length;\n\n if (points.length === 0) {\n return null;\n }\n if (points.length === 1) {\n return new Node(points[0], dim, parent);\n }\n\n points.sort((a, b) => a[dimensions[dim]] - b[dimensions[dim]]);\n\n const median = Math.floor(points.length / 2);\n const node = new Node(points[median], dim, parent);\n node.left = buildTree(points.slice(0, median), depth + 1, node, dimensions);\n node.right = buildTree(points.slice(median + 1), depth + 1, node, dimensions);\n\n return node;\n}\n\nfunction restoreParent(root) {\n if (root.left) {\n root.left.parent = root;\n restoreParent(root.left);\n }\n\n if (root.right) {\n root.right.parent = root;\n restoreParent(root.right);\n }\n}\n\n// Binary heap implementation from:\n// http://eloquentjavascript.net/appendix2.html\nclass BinaryHeap {\n constructor(scoreFunction) {\n this.content = [];\n this.scoreFunction = scoreFunction;\n }\n\n push(element) {\n // Add the new element to the end of the array.\n this.content.push(element);\n // Allow it to bubble up.\n this.bubbleUp(this.content.length - 1);\n }\n\n pop() {\n // Store the first element so we can return it later.\n var result = this.content[0];\n // Get the element at the end of the array.\n var end = this.content.pop();\n // If there are any elements left, put the end element at the\n // start, and let it sink down.\n if (this.content.length > 0) {\n this.content[0] = end;\n this.sinkDown(0);\n }\n return result;\n }\n\n peek() {\n return this.content[0];\n }\n\n size() {\n return this.content.length;\n }\n\n bubbleUp(n) {\n // Fetch the element that has to be moved.\n var element = this.content[n];\n // When at 0, an element can not go up any further.\n while (n > 0) {\n // Compute the parent element's index, and fetch it.\n const parentN = Math.floor((n + 1) / 2) - 1;\n const parent = this.content[parentN];\n // Swap the elements if the parent is greater.\n if (this.scoreFunction(element) < this.scoreFunction(parent)) {\n this.content[parentN] = element;\n this.content[n] = parent;\n // Update 'n' to continue at the new position.\n n = parentN;\n } else { // Found a parent that is less, no need to move it further.\n break;\n }\n }\n }\n\n sinkDown(n) {\n // Look up the target element and its score.\n var length = this.content.length;\n var element = this.content[n];\n var elemScore = this.scoreFunction(element);\n\n while (true) {\n // Compute the indices of the child elements.\n var child2N = (n + 1) * 2;\n var child1N = child2N - 1;\n // This is used to store the new position of the element,\n // if any.\n var swap = null;\n // If the first child exists (is inside the array)...\n if (child1N < length) {\n // Look it up and compute its score.\n var child1 = this.content[child1N];\n var child1Score = this.scoreFunction(child1);\n // If the score is less than our element's, we need to swap.\n if (child1Score < elemScore) {\n swap = child1N;\n }\n }\n // Do the same checks for the other child.\n if (child2N < length) {\n var child2 = this.content[child2N];\n var child2Score = this.scoreFunction(child2);\n if (child2Score < (swap === null ? elemScore : child1Score)) {\n swap = child2N;\n }\n }\n\n // If the element needs to be moved, swap it, and continue.\n if (swap !== null) {\n this.content[n] = this.content[swap];\n this.content[swap] = element;\n n = swap;\n } else {\n // Otherwise, we are done.\n break;\n }\n }\n }\n}\n","import KDTree from './KDTree';\nimport euclideanDistance from 'ml-distance-euclidean';\n\nexport default class KNN {\n\n /**\n * @param {Array} dataset\n * @param {Array} labels\n * @param {object} options\n * @param {number} [options.k=numberOfClasses + 1] - Number of neighbors to classify.\n * @param {function} [options.distance=euclideanDistance] - Distance function that takes two parameters.\n */\n constructor(dataset, labels, options = {}) {\n if (dataset === true) {\n const model = labels;\n this.kdTree = new KDTree(model.kdTree, options);\n this.k = model.k;\n this.classes = new Set(model.classes);\n this.isEuclidean = model.isEuclidean;\n return;\n }\n\n const classes = new Set(labels);\n\n const {\n distance = euclideanDistance,\n k = classes.size + 1\n } = options;\n\n const points = new Array(dataset.length);\n for (var i = 0; i < points.length; ++i) {\n points[i] = dataset[i].slice();\n }\n\n for (i = 0; i < labels.length; ++i) {\n points[i].push(labels[i]);\n }\n\n this.kdTree = new KDTree(points, distance);\n this.k = k;\n this.classes = classes;\n this.isEuclidean = distance === euclideanDistance;\n }\n\n /**\n * Create a new KNN instance with the given model.\n * @param {object} model\n * @param {function} distance=euclideanDistance - distance function must be provided if the model wasn't trained with euclidean distance.\n * @return {KNN}\n */\n static load(model, distance = euclideanDistance) {\n if (model.name !== 'KNN') {\n throw new Error('invalid model: ' + model.name);\n }\n if (!model.isEuclidean && distance === euclideanDistance) {\n throw new Error('a custom distance function was used to create the model. Please provide it again');\n }\n if (model.isEuclidean && distance !== euclideanDistance) {\n throw new Error('the model was created with the default distance function. Do not load it with another one');\n }\n return new KNN(true, model, distance);\n }\n\n /**\n * Return a JSON containing the kd-tree model.\n * @return {object} JSON KNN model.\n */\n toJSON() {\n return {\n name: 'KNN',\n kdTree: this.kdTree,\n k: this.k,\n classes: Array.from(this.classes),\n isEuclidean: this.isEuclidean\n };\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Array} dataset\n * @return {Array} predictions\n */\n predict(dataset) {\n if (Array.isArray(dataset)) {\n if (typeof dataset[0] === 'number') {\n return getSinglePrediction(this, dataset);\n } else if (Array.isArray(dataset[0]) && typeof dataset[0][0] === 'number') {\n const predictions = new Array(dataset.length);\n for (var i = 0; i < dataset.length; i++) {\n predictions[i] = getSinglePrediction(this, dataset[i]);\n }\n return predictions;\n }\n }\n throw new TypeError('dataset to predict must be an array or a matrix');\n }\n}\n\nfunction getSinglePrediction(knn, currentCase) {\n var nearestPoints = knn.kdTree.nearest(currentCase, knn.k);\n var pointsPerClass = {};\n var predictedClass = -1;\n var maxPoints = -1;\n var lastElement = nearestPoints[0][0].length - 1;\n\n for (var element of knn.classes) {\n pointsPerClass[element] = 0;\n }\n\n for (var i = 0; i < nearestPoints.length; ++i) {\n var currentClass = nearestPoints[i][0][lastElement];\n var currentPoints = ++pointsPerClass[currentClass];\n if (currentPoints > maxPoints) {\n predictedClass = currentClass;\n maxPoints = currentPoints;\n }\n }\n\n return predictedClass;\n}\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://ML/webpack/universalModuleDefinition","webpack://ML/webpack/bootstrap","webpack://ML/./node_modules/ml-matrix/src/dc/lu.js","webpack://ML/./node_modules/ml-matrix/src/dc/util.js","webpack://ML/./node_modules/ml-matrix/src/dc/svd.js","webpack://ML/./node_modules/ml-matrix/src/util.js","webpack://ML/./node_modules/ml-matrix/src/views/base.js","webpack://ML/./node_modules/ml-matrix/src/views/transpose.js","webpack://ML/./node_modules/ml-matrix/src/views/row.js","webpack://ML/./node_modules/ml-matrix/src/views/sub.js","webpack://ML/./node_modules/ml-matrix/src/views/selection.js","webpack://ML/./node_modules/ml-matrix/src/views/rowSelection.js","webpack://ML/./node_modules/ml-matrix/src/views/columnSelection.js","webpack://ML/./node_modules/ml-matrix/src/views/column.js","webpack://ML/./node_modules/ml-matrix/src/views/flipRow.js","webpack://ML/./node_modules/ml-matrix/src/views/flipColumn.js","webpack://ML/./node_modules/ml-matrix/src/abstractMatrix.js","webpack://ML/./node_modules/ml-matrix/src/matrix.js","webpack://ML/./node_modules/ml-matrix/src/wrap/WrapperMatrix1D.js","webpack://ML/./node_modules/ml-matrix/src/wrap/WrapperMatrix2D.js","webpack://ML/./node_modules/ml-matrix/src/wrap/wrap.js","webpack://ML/./node_modules/ml-matrix/src/dc/qr.js","webpack://ML/./node_modules/ml-matrix/src/decompositions.js","webpack://ML/./node_modules/ml-matrix/src/linearDependencies.js","webpack://ML/./node_modules/ml-matrix/src/dc/evd.js","webpack://ML/./node_modules/ml-matrix/src/dc/cholesky.js","webpack://ML/./node_modules/ml-matrix/src/index.js","webpack://ML/./node_modules/is-any-array/src/index.js","webpack://ML/./node_modules/ml-distance-euclidean/euclidean.js","webpack://ML/./node_modules/ml-stat/index.js","webpack://ML/./node_modules/ml-stat/matrix.js","webpack://ML/./node_modules/ml-array-mean/lib-es6/index.js","webpack://ML/./node_modules/binary-search/index.js","webpack://ML/./node_modules/num-sort/index.js","webpack://ML/./node_modules/ml-cart/src/utils.js","webpack://ML/./node_modules/ml-cart/src/TreeNode.js","webpack://ML/./node_modules/ml-cart/src/DecisionTreeClassifier.js","webpack://ML/./node_modules/ml-cart/src/DecisionTreeRegression.js","webpack://ML/./node_modules/ml-cart/src/index.js","webpack://ML/./node_modules/ml-array-max/lib-es6/index.js","webpack://ML/./node_modules/ml-kernel/src/kernel.js","webpack://ML/./node_modules/ml-random/lib-es6/choice.js","webpack://ML/./node_modules/ml-random/lib-es6/index.js","webpack://ML/./node_modules/random-js/lib/random.js","webpack://ML/./node_modules/ml-array-rescale/lib-es6/index.js","webpack://ML/./node_modules/ml-hash-table/src/HashTable.js","webpack://ML/./node_modules/ml-hclust/src/Cluster.js","webpack://ML/./node_modules/extend/index.js","webpack://ML/./node_modules/ml-array-min/lib-es6/index.js","webpack://ML/./node_modules/ml-array-median/lib-es6/index.js","webpack://ML/./node_modules/ml-xsadd/lib-es6/xsadd.js","webpack://ML/./node_modules/ml-array-sequential-fill/lib-es6/index.js","webpack://ML/./node_modules/ml-array-variance/lib-es6/index.js","webpack://ML/./node_modules/ml-stat/array.js","webpack://ML/./node_modules/ml-hclust/src/ClusterLeaf.js","webpack://ML/./node_modules/ml-distance-matrix/src/index.js","webpack://ML/./node_modules/ml-confusion-matrix/src/index.js","webpack://ML/./node_modules/ml-fnn/src/Layer.js","webpack://ML/./node_modules/ml-fnn/src/utils.js","webpack://ML/./node_modules/ml-fnn/src/activationFunctions.js","webpack://ML/./node_modules/ml-som/src/node-square.js","webpack://ML/./node_modules/ml-distance/src/index.js","webpack://ML/./node_modules/ml-distance/src/similarities/czekanowski.js","webpack://ML/./node_modules/ml-distance/src/distances/dice.js","webpack://ML/./node_modules/ml-distance/src/distances/intersection.js","webpack://ML/./node_modules/ml-distance/src/distances/jaccard.js","webpack://ML/./node_modules/ml-distance/src/distances/kulczynski.js","webpack://ML/./node_modules/ml-distance/src/distances/motyka.js","webpack://ML/./node_modules/ml-distance/src/distances/squaredChord.js","webpack://ML/./node_modules/ml-distance/src/similarities/tanimoto.js","webpack://ML/./node_modules/ml-distance/src/similarities/cosine.js","webpack://ML/./node_modules/ml-pad-array/src/index.js","webpack://ML/./node_modules/ml-regression-base/src/maybeToPrecision.js","webpack://ML/./node_modules/ml-regression-base/src/checkArrayLength.js","webpack://ML/./node_modules/ml-regression-base/src/index.js","webpack://ML/./node_modules/ml-regression-simple-linear/src/index.js","webpack://ML/./node_modules/ml-regression-polynomial/src/index.js","webpack://ML/./node_modules/ml-regression-exponential/src/index.js","webpack://ML/./node_modules/ml-regression-power/src/index.js","webpack://ML/./node_modules/ml-regression-multivariate-linear/src/index.js","webpack://ML/./node_modules/ml-regression/src/regression/potential-regression.js","webpack://ML/./node_modules/ml-regression/src/regression/kernel-ridge-regression.js","webpack://ML/./node_modules/ml-regression/src/regression/poly-fit-regression2d.js","webpack://ML/./node_modules/ml-regression-theil-sen/src/index.js","webpack://ML/./node_modules/ml-regression-robust-polynomial/src/index.js","webpack://ML/./node_modules/ml-regression/src/index.js","webpack://ML/./node_modules/median-quickselect/lib/median-quickselect.min.js","webpack://ML/./src/index.js","webpack://ML/./node_modules/ml-pca/src/pca.js","webpack://ML/./node_modules/ml-hclust/src/index.js","webpack://ML/./node_modules/ml-hclust/src/agnes.js","webpack://ML/./node_modules/heap/index.js","webpack://ML/./node_modules/heap/lib/heap.js","webpack://ML/./node_modules/util/util.js","webpack://ML/./node_modules/process/browser.js","webpack://ML/./node_modules/util/support/isBufferBrowser.js","webpack://ML/./node_modules/util/node_modules/inherits/inherits_browser.js","webpack://ML/./node_modules/ml-hclust/src/diana.js","webpack://ML/./node_modules/ml-svm/src/svm.js","webpack://ML/./node_modules/ml-kernel-gaussian/gaussian-kernel.js","webpack://ML/./node_modules/ml-kernel-polynomial/polynomial-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/anova-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/cauchy-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/exponential-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/histogram-intersection-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/laplacian-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/multiquadratic-kernel.js","webpack://ML/./node_modules/ml-kernel/src/kernels/rational-quadratic-kernel.js","webpack://ML/./node_modules/ml-kernel-sigmoid/sigmoid-kernel.js","webpack://ML/./node_modules/ml-cross-validation/src/index.js","webpack://ML/./node_modules/ml-combinations/lib/index.js","webpack://ML/./node_modules/ml-fnn/src/FeedForwardNeuralNetwork.js","webpack://ML/./node_modules/ml-fnn/src/OutputLayer.js","webpack://ML/./node_modules/ml-som/src/index.js","webpack://ML/./node_modules/ml-som/src/node-hexagonal.js","webpack://ML/./node_modules/ml-sparse-matrix/src/index.js","webpack://ML/./node_modules/new-array/index.js","webpack://ML/./node_modules/ml-hash-table/src/primeFinder.js","webpack://ML/./node_modules/number-is-nan/index.js","webpack://ML/./node_modules/ml-distance/src/distances.js","webpack://ML/./node_modules/ml-distance/src/distances/additiveSymmetric.js","webpack://ML/./node_modules/ml-distance/src/distances/avg.js","webpack://ML/./node_modules/ml-distance/src/distances/bhattacharyya.js","webpack://ML/./node_modules/ml-distance/src/distances/canberra.js","webpack://ML/./node_modules/ml-distance/src/distances/chebyshev.js","webpack://ML/./node_modules/ml-distance/src/distances/clark.js","webpack://ML/./node_modules/ml-distance/src/distances/czekanowski.js","webpack://ML/./node_modules/ml-distance/src/distances/divergence.js","webpack://ML/./node_modules/ml-distance/src/distances/fidelity.js","webpack://ML/./node_modules/ml-distance/src/distances/gower.js","webpack://ML/./node_modules/ml-distance/src/distances/harmonicMean.js","webpack://ML/./node_modules/ml-distance/src/distances/hellinger.js","webpack://ML/./node_modules/ml-distance/src/distances/innerProduct.js","webpack://ML/./node_modules/ml-distance/src/distances/jeffreys.js","webpack://ML/./node_modules/ml-distance/src/distances/jensenDifference.js","webpack://ML/./node_modules/ml-distance/src/distances/jensenShannon.js","webpack://ML/./node_modules/ml-distance/src/distances/kdivergence.js","webpack://ML/./node_modules/ml-distance/src/distances/kullbackLeibler.js","webpack://ML/./node_modules/ml-distance/src/distances/kumarHassebrook.js","webpack://ML/./node_modules/ml-distance/src/distances/kumarJohnson.js","webpack://ML/./node_modules/ml-distance/src/distances/lorentzian.js","webpack://ML/./node_modules/ml-distance/src/distances/manhattan.js","webpack://ML/./node_modules/ml-distance/src/distances/matusita.js","webpack://ML/./node_modules/ml-distance/src/distances/minkowski.js","webpack://ML/./node_modules/ml-distance/src/distances/neyman.js","webpack://ML/./node_modules/ml-distance/src/distances/pearson.js","webpack://ML/./node_modules/ml-distance/src/distances/probabilisticSymmetric.js","webpack://ML/./node_modules/ml-distance/src/distances/ruzicka.js","webpack://ML/./node_modules/ml-distance/src/distances/soergel.js","webpack://ML/./node_modules/ml-distance/src/distances/sorensen.js","webpack://ML/./node_modules/ml-distance/src/distances/squared.js","webpack://ML/./node_modules/ml-distance/src/distances/taneja.js","webpack://ML/./node_modules/ml-distance/src/distances/tanimoto.js","webpack://ML/./node_modules/ml-distance/src/distances/topsoe.js","webpack://ML/./node_modules/ml-tree-similarity/src/index.js","webpack://ML/./node_modules/ml-distance/src/distances/waveHedges.js","webpack://ML/./node_modules/ml-distance/src/similarities.js","webpack://ML/./node_modules/ml-distance/src/similarities/dice.js","webpack://ML/./node_modules/ml-distance/src/similarities/intersection.js","webpack://ML/./node_modules/ml-distance/src/similarities/jaccard.js","webpack://ML/./node_modules/ml-distance/src/similarities/kulczynski.js","webpack://ML/./node_modules/ml-distance/src/similarities/motyka.js","webpack://ML/./node_modules/ml-distance/src/similarities/pearson.js","webpack://ML/./node_modules/ml-distance/src/similarities/squaredChord.js","webpack://ML/./node_modules/ml-performance/src/index.js","webpack://ML/./node_modules/ml-performance/src/measures.js","webpack://ML/./node_modules/ml-savitzky-golay/src/index.js","webpack://ML/./node_modules/ml-savitzky-golay-generalized/src/index.js","webpack://ML/./node_modules/ml-bit-array/src/index.js","webpack://ML/./node_modules/ml-bit-array/src/creator.js","webpack://ML/./node_modules/ml-array-utils/src/index.js","webpack://ML/./node_modules/ml-array-utils/src/ArrayUtils.js","webpack://ML/./node_modules/ml-array-utils/src/getEquallySpaced.js","webpack://ML/./node_modules/ml-array-utils/src/snv.js","webpack://ML/./node_modules/ml-array-mode/lib-es6/index.js","webpack://ML/./node_modules/ml-array-normed/lib-es6/index.js","webpack://ML/./node_modules/ml-array-standard-deviation/lib-es6/index.js","webpack://ML/./node_modules/ml-array-xy-centroids-merge/src/index.js","webpack://ML/./node_modules/ml-arrayxy-closestx/src/index.js","webpack://ML/./node_modules/ml-array-xy-max-merge/src/index.js","webpack://ML/./node_modules/ml-array-xy-max-y/src/index.js","webpack://ML/./node_modules/ml-array-xy-sort-x/src/index.js","webpack://ML/./node_modules/ml-arrayxy-uniquex/src/index.js","webpack://ML/./node_modules/ml-array-xy-weighted-merge/src/index.js","webpack://ML/./node_modules/ml-kmeans/node_modules/ml-distance-euclidean/lib-es6/euclidean.js","webpack://ML/./node_modules/ml-nearest-vector/node_modules/ml-distance-euclidean/lib-es6/euclidean.js","webpack://ML/./node_modules/ml-nearest-vector/lib-es6/index.js","webpack://ML/./node_modules/ml-kmeans/src/utils.js","webpack://ML/./node_modules/ml-kmeans/src/initialization.js","webpack://ML/./node_modules/ml-kmeans/src/KMeansResult.js","webpack://ML/./node_modules/ml-kmeans/src/kmeans.js","webpack://ML/./node_modules/ml-random-forest/src/utils.js","webpack://ML/./node_modules/ml-random-forest/src/RandomForestBase.js","webpack://ML/./node_modules/ml-random-forest/src/RandomForestClassifier.js","webpack://ML/./node_modules/ml-random-forest/src/RandomForestRegression.js","webpack://ML/./node_modules/ml-random-forest/src/index.js","webpack://ML/./node_modules/ml-array-xy-equally-spaced/src/integral.js","webpack://ML/./node_modules/ml-array-xy-equally-spaced/src/index.js","webpack://ML/./node_modules/ml-array-xy-equally-spaced/src/getZones.js","webpack://ML/./node_modules/ml-array-xy-equally-spaced/src/equallySpacedSlot.js","webpack://ML/./node_modules/ml-array-xy-equally-spaced/src/equallySpacedSmooth.js","webpack://ML/./node_modules/ml-naivebayes/src/utils.js","webpack://ML/./node_modules/ml-naivebayes/src/GaussianNB.js","webpack://ML/./node_modules/ml-naivebayes/src/MultinomialNB.js","webpack://ML/./node_modules/ml-naivebayes/src/index.js","webpack://ML/./node_modules/ml-pls/src/utils.js","webpack://ML/./node_modules/ml-pls/src/pls.js","webpack://ML/./node_modules/ml-pls/src/kopls.js","webpack://ML/./node_modules/ml-pls/src/index.js","webpack://ML/./node_modules/ml-levenberg-marquardt/src/errorCalculation.js","webpack://ML/./node_modules/ml-levenberg-marquardt/src/step.js","webpack://ML/./node_modules/ml-levenberg-marquardt/src/index.js","webpack://ML/./node_modules/ml-array-xy-filter-x/src/index.js","webpack://ML/./node_modules/ml-array-xy-filter-x/src/getZones.js","webpack://ML/./node_modules/ml-knn/src/KDTree.js","webpack://ML/./node_modules/ml-knn/src/index.js"],"names":["root","factory","exports","module","define","amd","self","this","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","LuDecomposition","constructor","matrix","j","k","v","LUcolj","kmax","lu","WrapperMatrix2D","checkMatrix","clone","rows","columns","pivotVector","Array","pivotSign","Math","min","set","abs","LU","isSingular","data","col","solve","Matrix","Error","count","X","subMatrixRow","determinant","isSquare","lowerTriangularMatrix","upperTriangularMatrix","pivotPermutationVector","slice","hypotenuse","a","b","sqrt","getFilled2DArray","array","SingularValueDecomposition","options","arguments","length","undefined","computeLeftSingularVectors","computeRightSingularVectors","autoTranspose","wantu","Boolean","wantv","swapped","transpose","aux","console","warn","nu","ni","U","V","e","work","si","nct","nrt","max","mrc","pp","eps","Number","EPSILON","kase","alpha","MIN_VALUE","isNaN","ks","f","cs","sn","scale","sp","spm1","epm1","sk","ek","shift","g","tmp","Y","threshold","scols","Ls","zeros","rightSingularVectors","VL","mmul","vrows","urows","VLU","sum","solveForDiagonal","diag","inverse","vcols","ucols","condition","norm2","rank","tol","ii","diagonal","leftSingularVectors","isMatrix","diagonalMatrix","checkRowIndex","index","outer","RangeError","checkColumnIndex","checkRowVector","vector","to1DArray","checkColumnVector","checkIndices","rowIndices","columnIndices","row","checkRowIndices","column","checkColumnIndices","TypeError","some","isArray","from","checkRange","startRow","endRow","startColumn","endColumn","checkNumber","concat","BaseView","AbstractMatrix","super","static","species","MatrixTransposeView","rowIndex","columnIndex","MatrixRowView","MatrixSubView","MatrixSelectionView","indices","MatrixRowSelectionView","MatrixColumnSelectionView","MatrixColumnView","MatrixFlipRowView","MatrixFlipColumnView","superCtor","[object Object]","newRows","newColumns","newData","newMatrix","empty","fill","rng","random","maxValue","floor","matrix1","matrix2","result","klass","size","apply","callback","jj","to2DArray","copy","isRowVector","isColumnVector","isVector","isSymmetric","isEchelonForm","previousColumn","checked","isReducedEchelonForm","repeat","rowRep","colRep","setSubMatrix","neg","mulS","getRow","getRowVector","rowVector","setRow","swapRows","row1","row2","temp","getColumn","getColumnVector","columnVector","setColumn","swapColumns","column1","column2","addRowVector","subRowVector","mulRowVector","divRowVector","addColumnVector","subColumnVector","mulColumnVector","divColumnVector","mulRow","mulColumn","maxIndex","idx","minIndex","maxRow","maxRowIndex","minRow","minRowIndex","maxColumn","maxColumnIndex","minColumn","minColumnIndex","by","sumByRow","sumByColumn","sumAll","mean","prod","norm","type","cumulativeSum","dot","vector2","vector1","other","Bcolj","strassen2x2","a11","b11","a12","b12","a21","b21","a22","b22","m1","m2","m3","m4","m5","c00","c01","c10","c11","strassen3x3","a00","a01","a02","a10","a20","b00","b01","b02","b10","b20","m6","m7","m8","m9","m12","m13","m14","m15","m16","m17","m18","c02","c12","c20","c21","c22","mmulStrassen","y","x","r1","c1","r2","c2","embed","mat","cols","resultat","blockMult","halfRows","parseInt","halfCols","subMatrix","add","sub","scaleRows","scaled","rescale","scaleColumns","kroneckerProduct","q","sortRows","compareFunction","compareNumbers","sort","sortColumns","subMatrixColumn","selection","trace","transposeView","rowView","columnView","flipRowView","flipColumnView","subMatrixView","selectionView","rowSelectionView","columnSelectionView","det","subMatrix0","subMatrix1","subMatrix2","pseudoInverse","svdSolution","SvDecomposition","rand","identity","eye","negate","tensorProduct","staticMethodWithArgs","eval2","eval","operator","inplaceOp","fillTemplateFunction","op","inplaceOpS","inplaceOpM","staticOp","methods","method","forEach","mathMethod","push","inplaceMeth","staticMeth","methodWithArg","args","inplaceMethWithArgs","staticMethWithArgs","tmplVar","inplaceMethod2","inplaceMethodS","inplaceMethodM","staticMethod2","template","values","replace","RegExp","nRows","nColumns","isInteger","removeRow","splice","addRow","removeColumn","addColumn","WrapperMatrix1D","_calculateIndex","wrap","QrDecomposition","qr","rdiag","nrm","QR","Rdiag","isFullRank","orthogonalMatrix","useSVD","leftHandSide","rightHandSide","xrange","exception","range","dependenciesOneRow","error","thresholdValue","returnArray","linearDependencies","thresholdError","results","Abis","EigenvalueDecomposition","assumeSymmetric","h","hh","tred2","dl1","c3","el1","s2","tst1","tql2","H","ort","high","low","orthes","nn","w","ra","sa","vr","vi","notlast","cdivres","exshift","z","iter","cdiv","hqr2","realEigenvalues","imaginaryEigenvalues","eigenvectorMatrix","xr","xi","yr","yi","CholeskyDecomposition","dimension","positiveDefinite","Lrowj","Lrowk","L","B","__webpack_exports__","matrix_Matrix","WrapperMatrix2D_WrapperMatrix2D","WrapperMatrix1D_WrapperMatrix1D","svd_SingularValueDecomposition","evd_EigenvalueDecomposition","cholesky_CholeskyDecomposition","lu_LuDecomposition","qr_QrDecomposition","toString","endsWith","squaredEuclidean","euclidean","squared","require","arrayStat","Infinity","minMax","entropy","l1","l2","log","theMean","N","theSum","product","theProduct","standardDeviation","means","unbiased","vari","variance","sum1","sum2","median","medians","modes","itemCount","itemArray","indexOf","skewness","skew","s3","dev","pow","kurtosis","kurt","s4","standardError","samples","standardDeviations","standardErrors","sqrtN","covariance","scatter","divisor","cov","correlation","scores","zScores","cor","standardize","center","inPlace","resultRow","sourceRow","weightedVariance","weights","weightedMean","weightSum","weightedCovariance","s1","factor","weightedScatter","is_any_array__WEBPACK_IMPORTED_MODULE_0__","is_any_array__WEBPACK_IMPORTED_MODULE_0___default","input","haystack","needle","comparator","mid","cmp","numberIsNan","assertNum","asc","desc","toDiscreteDistribution","numberOfClasses","counts","giniImpurity","probabilities","getNumberOfClasses","filter","val","arr","squaredError","meanArray","currentElement","gainFunctions","gini","splitted","splitsImpurity","splits","currentSplit","regression","splitFunctions","TreeNode","kind","gainFunction","splitFunction","minNumSamples","maxDepth","bestSplit","XTranspose","bestGain","check","currentFeature","splitValues","featureSplit","currentSplitVal","split","gain","maxGain","splitValue","lesser","greater","ret","Utils","calculatePrediction","distribution","train","currentDepth","parentGain","splitColumn","splittedMatrix","lesserX","greaterX","lesserY","greaterY","left","right","classify","setNodeParameters","node","defaultOptions","DecisionTreeClassifier","model","Tree","assign","trainingSet","trainingLabels","predict","toPredict","predictions","toJSON","DecisionTreeRegression","trainingValues","DecisionTreeClassifier_DecisionTreeClassifier","DecisionTreeRegression_DecisionTreeRegression","GaussianKernel","PolynomialKernel","ANOVAKernel","CauchyKernel","ExponentialKernel","HistogramKernel","LaplacianKernel","MultiquadraticKernel","RationalKernel","SigmoidKernel","kernelType","gaussian","rbf","polynomial","poly","anova","cauchy","exponential","histogram","laplacian","multiquadratic","rational","sigmoid","mlp","toLowerCase","KernelConstructor","kernelFunction","compute","inputs","landmarks","kernelMatrix","PROB_TOLERANCE","randomIndex","cumSum","randomChoice","valuesArr","getArray","lib_es6_Random","Random","seedOrRandom","xsadd","XSAdd","randomGenerator","choice","randInt","randomSample","__WEBPACK_AMD_DEFINE_RESULT__","imul","al","bl","stringRepeat","String","pattern","engine","engines","nativeMath","proto","returnValue","generate","addend","toInteger","number","ceil","convertSliceArgument","returnUndefined","mt19937","Int32Array","refreshData","uses","next","temper","getUseCount","discard","seed","initial","previous","seedWithArray","source","sourceLength","autoSeed","generateEntropyArray","browserCrypto","crypto","getRandomValues","Date","getTime","int32","uint32","uint53","uint53Full","int53","int53Full","integer","isPowerOfTwoMinusOne","downscaleToRange","masking","extendedRange","maximum","downscaleToLoopCheckedRange","upscaleWithinU53","highRange","upscaleToLoopCheckedRange","upscaleWithinI53AndLoopCheck","isFinite","realZeroToOneInclusive","realZeroToOneExclusive","real","inclusive","multiplier","bool","isLeastBitTrue","lessThan","numerator","denominator","percentage","round","probability","pick","begin","end","start","finish","lowerHex","upperHex","picker","shuffle","downTo","sample","population","sampleSize","tailLength","die","sideCount","dice","dieCount","uuid4","zeroPad","string","zeroCount","pool","charAt","hex","toUpperCase","upper","date","ml_array_max__WEBPACK_IMPORTED_MODULE_0__","ml_array_min__WEBPACK_IMPORTED_MODULE_1__","is_any_array__WEBPACK_IMPORTED_MODULE_2__","is_any_array__WEBPACK_IMPORTED_MODULE_2___default","output","currentMin","currentMax","_options$min","minValue","autoMinMax","_options$max","newArray","primeFinder","nextPrime","largestPrime","FREE","FULL","REMOVED","defaultInitialCapacity","defaultMinLoadFactor","defaultMaxLoadFactor","HashTable","table","state","minLoadFactor","maxLoadFactor","distinct","freeEntries","lowWaterMark","highWaterMark","initialCapacity","capacity","chooseHighWaterMark","indexOfKey","indexOfInsertion","newCapacity","chooseGrowCapacity","rehash","remove","noRehash","maybeShrinkCapacity","delete","minLoad","maxLoad","containsKey","hash","decrement","containsValue","indexOfValue","ensureCapacity","minCapacity","oldCapacity","oldTable","oldValues","oldState","newTable","newValues","newState","element","forEachKey","forEachValue","forEachPair","Heap","Cluster","children","distance","cut","list","ans","group","minGroups","heap","first","pop","child","toArray","traverse","cb","visit","hasOwn","toStr","gOPD","getOwnPropertyDescriptor","isPlainObject","obj","hasOwnConstructor","hasIsPrototypeOf","setProperty","target","configurable","newValue","writable","getProperty","extend","src","copyIsArray","deep","median_quickselect__WEBPACK_IMPORTED_MODULE_0__","median_quickselect__WEBPACK_IMPORTED_MODULE_0___default","is_any_array__WEBPACK_IMPORTED_MODULE_1__","is_any_array__WEBPACK_IMPORTED_MODULE_1___default","quickSelectMedian","XSadd","LOOP","FLOAT_MUL","sh1","sh2","sh3","multiply_uint32","nlo","now","Uint32Array","init","getFloat","getUint32","nextState","periodCertification","_typeof","iterator","sequentialFill","_options","_options$from","_options$to","to","_options$size","step","_i","ml_array_mean__WEBPACK_IMPORTED_MODULE_0__","_options$unbiased","_options$mean","arrayMean","sqrError","arithmeticMean","geometricMean","mul","logMean","lnsum","grandMean","truncatedMean","percent","alreadySorted","harmonicMean","contraHarmonicMean","half","theVariance","robustMeanAndStdev","averageDeviations","stdev","quartiles","quart","q1","q2","q3","pooledStandardDeviation","pooledVariance","mean1","mean2","weightedStandardDeviation","standardDev","ClusterLeaf","inherits","distanceFn","map","ConfusionMatrix","labels","actual","predicted","distinctLabels","Set","actualIdx","predictedIdx","getMatrix","getLabels","getTotalCount","getTrueCount","getFalseCount","getTruePositiveCount","label","getIndex","getTrueNegativeCount","getFalsePositiveCount","getFalseNegativeCount","getPositiveCount","getNegativeCount","getTruePositiveRate","getTrueNegativeRate","getPositivePredictiveValue","TP","getNegativePredictiveValue","TN","getFalseNegativeRate","getFalsePositiveRate","getFalseDiscoveryRate","FP","getFalseOmissionRate","FN","getF1Score","getMatthewsCorrelationCoefficient","getInformedness","getMarkedness","getConfusionTable","getAccuracy","correct","incorrect","getCount","actualIndex","predictedIndex","accuracy","total","ACTIVATION_FUNCTIONS","Layer","inputSize","outputSize","regularization","epsilon","activation","activationParam","selectedFunction","params","actFunction","derFunction","derivate","activationFunction","W","forward","backpropagation","delta","dW","db","sumCol","aCopy","update","dictOutputs","outputs","sumRow","logistic","exp","expELU","param","tanh","arctan","atan","softsign","relu","softplus","bent","sinusoid","sin","cos","sinc","parametric-relu","exponential-elu","soft-exponential","NodeSquare","som","neighbors","adjustWeights","learningRate","influence","getDistance","otherNode","getDistanceTorus","distX","distY","gridDim","getNeighbors","xy","torus","nodes","getPos","bestNeighbor","direction","simA","simB","getPosition","similarity","up","down","p1","p2","bitvector","inter","union","matrixCase","len","cond","arrayCase","maybeToPrecision","digits","toPrecision","checkArraySize","BaseRegression","_predict","toLaTeX","score","y2","xSum","ySum","chi2","rmsd","xSquared","ySquared","xY","SimpleLinearRegression","slope","intercept","coefficients","checkArrayLength","slr","regress","computeX","precision","xFactor","absIntercept","json","PolynomialRegression","degree","powers","pr","F","FT","A","_toFormula","isLaTeX","sup","closeSup","times","fn","str","ExponentialRegression","er","yl","linear","PowerRegression","xl","newInputs","MultivariateLinearRegression","statistics","beta","SVD","fittedValues","addM","ri","reduce","stdError","stdErrorMatrix","stdErrors","tStats","summary","regressionStatistics","observations","variables","tStat","PotentialRegression","M","lambda","kernelOptions","computeCoefficient","KernelRidgeRegression","kernel","Kernel","K","order","PolynomialFitRegression2D","examples","x1","x2","scaleX1","scaleX2","scaleY","limit","powColVector","svd","qqs","qqs1","power","TheilSenRegression","slopes","medianSlope","cuts","theilSen","RobustPolynomialRegression","tuples","pos","counter","getRandomTuples","tuple","calcCoefficients","residuals","residual","residualsMedian","robustPolynomial","NLR","src_SimpleLinearRegression","src_PolynomialRegression","src_ExponentialRegression","src_PowerRegression","src_MultivariateLinearRegression","kernel_ridge_regression_KernelRidgeRegression","poly_fit_regression2d_PolynomialFitRegression2D","src_TheilSenRegression","src_RobustPolynomialRegression","_ref","window","mlCart","mlRandomForest","ML","PCA","HClust","KMeans","SVM","NaiveBayes","KNN","PLS","CrossValidation","RandomForestClassifier","FNN","SOM","Regression","RandomForestRegression","levenbergMarquardt","EVD","SparseMatrix","Distance","Similarity","distanceMatrix","default","Performance","savitzkyGolay","savitzkyGolayGeneralized","BitArray","padArray","binarySearch","numSort","ArrayUtils","MatrixUtil","ArrayStat","MatrixStat","normed","ArrayXY","centroidsMerge","closestX","maxMerge","maxY","sortX","uniqueX","weightedMerge","equallySpaced","filterX","matrixLib","Stat","isCovarianceMatrix","dataset","stdevs","S","_computeFromCovarianceMatrix","useCovarianceMatrix","covarianceMatrix","_adjust","div","singularValues","eigenvalues","nComponents","getExplainedVariance","getCumulativeVariance","explained","getEigenvectors","getEigenvalues","getStandardDeviations","getLoadings","evd","reverse","agnes","diana","simpleLink","cluster1","cluster2","disFun","completeLink","averageLink","centroidLink","dist","wardLink","disFunc","isDistanceMatrix","dis","fdistance","sdistance","toFixed","dmin","clustered","diff","indCount","__WEBPACK_AMD_DEFINE_FACTORY__","__WEBPACK_AMD_DEFINE_ARRAY__","defaultCmp","heapify","heappop","heappush","heappushpop","heapreplace","insort","nlargest","nsmallest","updateItem","_siftdown","_siftup","lo","hi","item","lastelt","returnitem","_len","_ref1","_results","_results1","_j","elem","los","startpos","newitem","parent","parentpos","childpos","endpos","rightpos","pushpop","peek","contains","clear","insert","top","front","has","process","getOwnPropertyDescriptors","keys","descriptors","formatRegExp","format","isString","objects","inspect","join","JSON","stringify","_","isNull","isObject","deprecate","msg","noDeprecation","warned","throwDeprecation","traceDeprecation","debugEnviron","debugs","opts","ctx","seen","stylize","stylizeNoColor","depth","colors","isBoolean","showHidden","_extend","isUndefined","customInspect","stylizeWithColor","formatValue","styleType","style","styles","recurseTimes","isFunction","primitive","simple","isNumber","formatPrimitive","visibleKeys","arrayToHash","getOwnPropertyNames","isError","formatError","isRegExp","isDate","base","braces","toUTCString","formatProperty","match","formatArray","prev","cur","numLinesEst","reduceToSingleString","line","substr","ar","arg","re","objectToString","pad","debuglog","env","NODE_DEBUG","test","pid","bold","italic","underline","white","grey","black","blue","cyan","green","magenta","red","yellow","special","boolean","null","regexp","isNullOrUndefined","isSymbol","isPrimitive","isBuffer","months","prop","time","getHours","getMinutes","getSeconds","getDate","getMonth","origin","kCustomPromisifiedSymbol","callbackifyOnRejected","reason","newReason","promisify","original","promiseResolve","promiseReject","promise","Promise","resolve","reject","err","setPrototypeOf","getPrototypeOf","defineProperties","custom","callbackify","callbackified","maybeCb","then","nextTick","rej","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","setTimeout","clearTimeout","currentQueue","queue","draining","queueIndex","cleanUpNextTick","drainQueue","timeout","run","marker","runClearTimeout","Item","noop","title","browser","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","readUInt8","ctor","super_","TempCtor","y1","splitting","Ci","ndist","Cj","intrDist","clId","rebel","tree","ind","C","sG","spl","fData","sData","stat","maxPasses","maxIterations","alphaTol","whitening","features","_trained","_loaded","D","alphas","b1","b2","passes","Ei","Ej","ai","aj","eta","numChange","_marginOnePrecomputed","newaj","iterations","nX","nY","nAlphas","_supportVectorIdx","predictOne","marginOne","noWhitening","_applyWhitening","margin","supportVectors","load","svm","whitened","sigma","constant","E","CV","combinations","initMatrix","getDistinct","validate","Classifier","classifierOptions","testIdx","trainIdx","confusionMatrix","testFeatures","trainFeatures","testLabels","trainLabels","getTrainTest","classifier","updateConfusionMatrix","validateWithCallback","predictedLabels","leaveOneOut","leavePOut","gen","allIdx","kFold","current","folds","randi","runtime","createCommonjsModule","global","Op","$Symbol","iteratorSymbol","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","regeneratorRuntime","GenStateSuspendedStart","GenStateSuspendedYield","GenStateExecuting","GenStateCompleted","ContinueSentinel","IteratorPrototype","getProto","NativeIteratorPrototype","Gp","GeneratorFunctionPrototype","Generator","GeneratorFunction","displayName","isGeneratorFunction","genFun","mark","__proto__","awrap","__await","defineIteratorMethods","AsyncIterator","async","innerFn","outerFn","tryLocsList","done","Context","reset","skipTempReset","sent","_sent","delegate","tryEntries","resetTryEntry","stop","rootEntry","rootRecord","completion","rval","dispatchException","context","handle","loc","caught","record","entry","tryLoc","hasCatch","hasFinally","catchLoc","finallyLoc","abrupt","finallyEntry","complete","afterLoc","catch","thrown","delegateYield","iterable","resultName","nextLoc","protoGenerator","generator","_invoke","doneResult","delegateResult","maybeInvokeDelegate","tryCatch","makeInvokeMethod","previousPromise","callInvokeWithMethodAndArg","invoke","unwrapped","return","info","pushTryEntry","locs","iteratorMethod","Function","hadRuntime","oldRuntime","runtimeModule","regenerator","_callee","twiddle","_context","OutputLayer","FeedForwardNeuralNetworks","hiddenLayers","dicts","layers","buildNetwork","propagate","NodeHexagonal","fields","randomizer","squareEuclidean","gridType","reload","numWeights","converters","getConverters","extractor","creator","nodeType","hx","distanceMethod","maxDistance","getMaxDistance","findBMU","adjust","iterationCount","startLearningRate","mapRadius","algorithmMethod","_initNodes","normalizers","denormalizers","getNormalizer","getDenormalizer","getRandomValue","zero","one","loadModel","export","includeDistance","initNodes","setTraining","convertedSet","numIterations","timeConstant","trainOne","neighbourhoodRadius","trainingValue","trainingSetFactor","bmu","_findBestMatchingUnit","now2","radiusLimit","xMin","xMax","yMin","yMax","theX","theY","getConvertedNodes","candidate","lowest","computePosition","getQuantizationError","fit","getFit","hX","distZ","ml_hash_table__WEBPACK_IMPORTED_MODULE_0__","ml_hash_table__WEBPACK_IMPORTED_MODULE_0___default","_init","elements","symmetric","forEachNonZero","bandWidth","isBanded","width","cardinality","v1","v2","getNonZeros","setThreshold","newThreshold","trans","inplaceOperator","inplaceOperatorScalar","inplaceOperatorMatrix","staticOperator","inplaceMethod","staticMethod","operators","sortAsc","primeNumbers","additiveSymmetric","avg","bhattacharyya","canberra","chebyshev","clark","czekanowski","divergence","fidelity","gower","hellinger","innerProduct","intersection","jaccard","jeffreys","jensenDifference","jensenShannon","kdivergence","kulczynski","kullbackLeibler","kumarHassebrook","kumarJohnson","lorentzian","manhattan","matusita","minkowski","motyka","neyman","pearson","probabilisticSymmetric","ruzicka","soergel","sorensen","squaredChord","taneja","tanimoto","topsoe","waveHedges","czekanowskiSimilarity","tanimotoS","createTree","minWindow","gamma","calc","cosine","diceD","intersectionD","jaccardD","kulczynskiD","motykaD","avgA","avgB","newA","newB","squaredChordD","measures","prediction","isDistance","predP","all","pred","targ","cutoffs","MAX_VALUE","fp","tp","nPos","nNeg","currentPred","nTp","nFp","tn","nPosPred","nNegPred","nSamples","getMeasure","measure","getAURC","auc","getAUDC","getDistribution","cutLength","cutLow","cutHigh","interval","xLabels","interValues","intraValues","interCumPercent","intraCumPercent","nTP","currentTP","nFP","currentFP","thisTP","thisFP","names","acc","fpr","tpr","fnr","tnr","ppv","npv","pcfall","pcmiss","lift","rpp","rnp","windowSize","derivative","padValue","J","ones","inic","Jtranspose","getHs","hs","GramPoly","GenFact","gf","Weight","np","fullWeights","constantH","wg1","wg2","d1","d2","wg","eightBits","toBinaryString","and","arr1","arr2","or","xor","not","getBit","mask","setBit","parseBinaryString","toHexString","parseHexString","toDebug","binary","num","getEquallySpacedData","SNV","resultMatrix","coordArrayToPoints","dimensions","pointsArr","point","coordArrayToCoordMatrix","coordinatesArray","points","currentPoint","coordMatrixToCoordArray","coordMatrix","coodinatesArray","coordMatrixToPoints","pointsToCoordArray","pointsToCoordMatrix","applyDotProduct","firstVector","secondVector","largestVector","smallestVector","difference","dotProductApplied","integral","x0","xLength","variant","numberOfPoints","halfStep","lastStep","previousX","previousY","nextX","nextY","frontOutsideSpectra","backOutsideSpectra","currentValue","currentPoints","main","getEquallySpacedSlot","initialOriginalStep","lastOriginalStep","sumAtMin","sumAtMax","getEquallySpacedSmooth","std","maxCount","_options$algorithm","algorithm","absoluteSum","ml_array_variance__WEBPACK_IMPORTED_MODULE_0__","mergeByCentroids","originalPoints","centroids","mergedPoints","originalIndex","mergedIndex","binary_search__WEBPACK_IMPORTED_MODULE_0__","binary_search__WEBPACK_IMPORTED_MODULE_0___default","num_sort__WEBPACK_IMPORTED_MODULE_1__","groupWidth","merged","maxAbscissa","calculateIndex","currentIndex","sortFunc","grouped","response","weightedAbscissa","distanceFunction","nearestVector","listVectors","similarityFunction","vectorIndex","maxSim","sim","minDist","updateClusterID","centers","clusterID","euclidianDistances","distanceSymbol","KMeansResult","clusters","converged","nearest","centroid","computeInformation","enrichedCentroids","kmeans","tolerance","withIterations","initialization","newCenters","prevCenters","nDim","centersLen","dim","id","updateCenters","oldCenters","hasConverged","localTrials","firstCenterIdx","closestDistSquared","cumSumClosestDistSquared","candidateIdx","distanceToCandidates","bestCandidate","bestPot","bestDistSquared","newDistSquared","newPot","kmeanspp","maxDist","minDistCent","mostDistant","calculateDistanceMatrix","stepResult","stepNumber","kmeansGenerator","examplesBaggingWithReplacement","Xr","featureBagging","replacement","toRet","usedIndex","RandomForestBase","maxFeatures","nEstimators","treeOptions","isClassifier","indexes","useSampleBagging","Estimator","DTClassifier","DTRegression","estimators","est","res","predictionValues","baseModel","selectionMethods","arrayMedian","selectionMethod","RandomForestClassifier_RandomForestClassifier","RandomForestRegression_RandomForestRegression","arrayXY","exclusions","zones","exclusion","parse","toRemove","unitsPerPoint","currentFrom","totalPoints","currentNbPoints","getZones","xResult","yResult","zone","zoneResult","processZone","equallySpacedSlot","equallySpacedSmooth","separateClasses","classes","totalPerClasses","separatedClasses","GaussianNB","calculateProbabilities","C1","PI","logPriorProbability","currentStd","getCurrentClass","modelName","currentCase","maxProbability","predictedClass","currentProbability","calculateLogProbability","C2","MultinomialNB","conditionalProbability","priorProbability","separateClass","classValues","matrixLog","GaussianNB_GaussianNB","MultinomialNB_MultinomialNB","pow2array","initializeMatrices","meanX","stdDevX","meanY","stdDevY","PBQ","R2X","scaleMethod","latentVectors","rx","cx","ry","cy","ssqXcal","sumOfSquaresY","T","P","Q","transposeX","transposeY","tIndex","maxSumColIndex","mulM","uIndex","t1","u","den","pnorm","ssqYcal","KOPLS","YLoadingMat","SigmaPow","YScoreMat","predScoreMat","YOrthLoadingVec","YOrthEigen","YOrthScoreMat","toNorm","TURegressionCoeff","kernelX","orthogonalComp","predictiveComp","predictiveComponents","orthogonalComponents","Identity","Sigma","YOrthScoreNorm","TpiPrime","CoTemp","SoTemp","toiPrime","ITo","lastScoreMat","lastTpPrime","KTestTrain","YOrthScoreVector","scoreMatPrime","p3","predYOrthVectors","pls_PLS","kopls_KOPLS","errorCalculation","parameters","parameterizedFunction","func","damping","gradientDifference","evaluatedData","gradientFunc","paramFunction","auxParams","funcParam","gradientFunction","matrixFunc","matrixFunction","inverseMatrix","errorTolerance","minValues","maxValues","initialValues","parLen","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","iteration","parameterValues","parameterError","currentZoneIndex","newX","newY","position","Node","KDTree","metric","buildTree","restoreParent","toJSONImpl","dest","maxNodes","bestNodes","BinaryHeap","nearestSearch","ownDistance","linearPoint","bestChild","linearDistance","otherChild","saveNode","content","scoreFunction","bubbleUp","sinkDown","parentN","elemScore","child2N","child1N","swap","child1","child1Score","child2","src_KNN","kdTree","isEuclidean","euclideanDistance","getSinglePrediction","knn","nearestPoints","pointsPerClass","maxPoints","lastElement","currentClass"],"mappings":"CAAA,SAAAA,EAAAC,GACA,iBAAAC,SAAA,iBAAAC,OACAA,OAAAD,QAAAD,IACA,mBAAAG,eAAAC,IACAD,OAAA,GAAAH,GACA,iBAAAC,QACAA,QAAA,GAAAD,IAEAD,EAAA,GAAAC,IARA,CASC,oBAAAK,UAAAC,KAAA,WACD,mBCTA,IAAAC,EAAA,GAGA,SAAAC,EAAAC,GAGA,GAAAF,EAAAE,GACA,OAAAF,EAAAE,GAAAR,QAGA,IAAAC,EAAAK,EAAAE,GAAA,CACAC,EAAAD,EACAE,GAAA,EACAV,QAAA,IAUA,OANAW,EAAAH,GAAAI,KAAAX,EAAAD,QAAAC,IAAAD,QAAAO,GAGAN,EAAAS,GAAA,EAGAT,EAAAD,QA0DA,OArDAO,EAAAM,EAAAF,EAGAJ,EAAAO,EAAAR,EAGAC,EAAAQ,EAAA,SAAAf,EAAAgB,EAAAC,GACAV,EAAAW,EAAAlB,EAAAgB,IACAG,OAAAC,eAAApB,EAAAgB,EAAA,CAA0CK,YAAA,EAAAC,IAAAL,KAK1CV,EAAAgB,EAAA,SAAAvB,GACA,oBAAAwB,eAAAC,aACAN,OAAAC,eAAApB,EAAAwB,OAAAC,YAAA,CAAwDC,MAAA,WAExDP,OAAAC,eAAApB,EAAA,cAAiD0B,OAAA,KAQjDnB,EAAAoB,EAAA,SAAAD,EAAAE,GAEA,GADA,EAAAA,IAAAF,EAAAnB,EAAAmB,IACA,EAAAE,EAAA,OAAAF,EACA,KAAAE,GAAA,iBAAAF,QAAAG,WAAA,OAAAH,EACA,IAAAI,EAAAX,OAAAY,OAAA,MAGA,GAFAxB,EAAAgB,EAAAO,GACAX,OAAAC,eAAAU,EAAA,WAAyCT,YAAA,EAAAK,UACzC,EAAAE,GAAA,iBA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AAI70B,EAAI,EAAGA,EAAIkrE,EAAcpmE,SAAU9E,EAAG,CAC3C,IAAIsrE,EAAeJ,EAAclrE,GAAG,GAAGqrE,GACnC3R,IAAkByR,EAAeG,GACjC5R,EAAgB0R,IAChB5I,EAAiB8I,EACjBF,EAAY1R,GAIpB,OAAO8I","file":"ml.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"ML\"] = factory();\n\telse\n\t\troot[\"ML\"] = factory();\n})(typeof self !== 'undefined' ? self : this, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 43);\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\n/**\r\n * @class LuDecomposition\r\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs\r\n * @param {Matrix} matrix\r\n */\r\nexport default class LuDecomposition {\r\n constructor(matrix) {\r\n matrix = WrapperMatrix2D.checkMatrix(matrix);\r\n\r\n var lu = matrix.clone();\r\n var rows = lu.rows;\r\n var columns = lu.columns;\r\n var pivotVector = new Array(rows);\r\n var pivotSign = 1;\r\n var i, j, k, p, s, t, v;\r\n var LUcolj, kmax;\r\n\r\n for (i = 0; i < rows; i++) {\r\n pivotVector[i] = i;\r\n }\r\n\r\n LUcolj = new Array(rows);\r\n\r\n for (j = 0; j < columns; j++) {\r\n for (i = 0; i < rows; i++) {\r\n LUcolj[i] = lu.get(i, j);\r\n }\r\n\r\n for (i = 0; i < rows; i++) {\r\n kmax = Math.min(i, j);\r\n s = 0;\r\n for (k = 0; k < kmax; k++) {\r\n s += lu.get(i, k) * LUcolj[k];\r\n }\r\n LUcolj[i] -= s;\r\n lu.set(i, j, LUcolj[i]);\r\n }\r\n\r\n p = j;\r\n for (i = j + 1; i < rows; i++) {\r\n if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) {\r\n p = i;\r\n }\r\n }\r\n\r\n if (p !== j) {\r\n for (k = 0; k < columns; k++) {\r\n t = lu.get(p, k);\r\n lu.set(p, k, lu.get(j, k));\r\n lu.set(j, k, t);\r\n }\r\n\r\n v = pivotVector[p];\r\n pivotVector[p] = pivotVector[j];\r\n pivotVector[j] = v;\r\n\r\n pivotSign = -pivotSign;\r\n }\r\n\r\n if (j < rows && lu.get(j, j) !== 0) {\r\n for (i = j + 1; i < rows; i++) {\r\n lu.set(i, j, lu.get(i, j) / lu.get(j, j));\r\n }\r\n }\r\n }\r\n\r\n this.LU = lu;\r\n this.pivotVector = pivotVector;\r\n this.pivotSign = pivotSign;\r\n }\r\n\r\n /**\r\n *\r\n * @return {boolean}\r\n */\r\n isSingular() {\r\n var data = this.LU;\r\n var col = data.columns;\r\n for (var j = 0; j < col; j++) {\r\n if (data[j][j] === 0) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n *\r\n * @param {Matrix} value\r\n * @return {Matrix}\r\n */\r\n solve(value) {\r\n value = Matrix.checkMatrix(value);\r\n\r\n var lu = this.LU;\r\n var rows = lu.rows;\r\n\r\n if (rows !== value.rows) {\r\n throw new Error('Invalid matrix dimensions');\r\n }\r\n if (this.isSingular()) {\r\n throw new Error('LU matrix is singular');\r\n }\r\n\r\n var count = value.columns;\r\n var X = value.subMatrixRow(this.pivotVector, 0, count - 1);\r\n var columns = lu.columns;\r\n var i, j, k;\r\n\r\n for (k = 0; k < columns; k++) {\r\n for (i = k + 1; i < columns; i++) {\r\n for (j = 0; j < count; j++) {\r\n X[i][j] -= X[k][j] * lu[i][k];\r\n }\r\n }\r\n }\r\n for (k = columns - 1; k >= 0; k--) {\r\n for (j = 0; j < count; j++) {\r\n X[k][j] /= lu[k][k];\r\n }\r\n for (i = 0; i < k; i++) {\r\n for (j = 0; j < count; j++) {\r\n X[i][j] -= X[k][j] * lu[i][k];\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get determinant() {\r\n var data = this.LU;\r\n if (!data.isSquare()) {\r\n throw new Error('Matrix must be square');\r\n }\r\n var determinant = this.pivotSign;\r\n var col = data.columns;\r\n for (var j = 0; j < col; j++) {\r\n determinant *= data[j][j];\r\n }\r\n return determinant;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get lowerTriangularMatrix() {\r\n var data = this.LU;\r\n var rows = data.rows;\r\n var columns = data.columns;\r\n var X = new Matrix(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n if (i > j) {\r\n X[i][j] = data[i][j];\r\n } else if (i === j) {\r\n X[i][j] = 1;\r\n } else {\r\n X[i][j] = 0;\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get upperTriangularMatrix() {\r\n var data = this.LU;\r\n var rows = data.rows;\r\n var columns = data.columns;\r\n var X = new Matrix(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n if (i <= j) {\r\n X[i][j] = data[i][j];\r\n } else {\r\n X[i][j] = 0;\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Array}\r\n */\r\n get pivotPermutationVector() {\r\n return this.pivotVector.slice();\r\n }\r\n}\r\n","export function hypotenuse(a, b) {\r\n var r = 0;\r\n if (Math.abs(a) > Math.abs(b)) {\r\n r = b / a;\r\n return Math.abs(a) * Math.sqrt(1 + r * r);\r\n }\r\n if (b !== 0) {\r\n r = a / b;\r\n return Math.abs(b) * Math.sqrt(1 + r * r);\r\n }\r\n return 0;\r\n}\r\n\r\nexport function getFilled2DArray(rows, columns, value) {\r\n var array = new Array(rows);\r\n for (var i = 0; i < rows; i++) {\r\n array[i] = new Array(columns);\r\n for (var j = 0; j < columns; j++) {\r\n array[i][j] = value;\r\n }\r\n }\r\n return array;\r\n}\r\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\nimport { hypotenuse, getFilled2DArray } from './util';\r\n\r\n/**\r\n * @class SingularValueDecomposition\r\n * @see https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs\r\n * @param {Matrix} value\r\n * @param {object} [options]\r\n * @param {boolean} [options.computeLeftSingularVectors=true]\r\n * @param {boolean} [options.computeRightSingularVectors=true]\r\n * @param {boolean} [options.autoTranspose=false]\r\n */\r\nexport default class SingularValueDecomposition {\r\n constructor(value, options = {}) {\r\n value = WrapperMatrix2D.checkMatrix(value);\r\n\r\n var m = value.rows;\r\n var n = value.columns;\r\n\r\n const {\r\n computeLeftSingularVectors = true,\r\n computeRightSingularVectors = true,\r\n autoTranspose = false\r\n } = options;\r\n\r\n var wantu = Boolean(computeLeftSingularVectors);\r\n var wantv = Boolean(computeRightSingularVectors);\r\n\r\n var swapped = false;\r\n var a;\r\n if (m < n) {\r\n if (!autoTranspose) {\r\n a = value.clone();\r\n // eslint-disable-next-line no-console\r\n console.warn(\r\n 'Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose'\r\n );\r\n } else {\r\n a = value.transpose();\r\n m = a.rows;\r\n n = a.columns;\r\n swapped = true;\r\n var aux = wantu;\r\n wantu = wantv;\r\n wantv = aux;\r\n }\r\n } else {\r\n a = value.clone();\r\n }\r\n\r\n var nu = Math.min(m, n);\r\n var ni = Math.min(m + 1, n);\r\n var s = new Array(ni);\r\n var U = getFilled2DArray(m, nu, 0);\r\n var V = getFilled2DArray(n, n, 0);\r\n\r\n var e = new Array(n);\r\n var work = new Array(m);\r\n\r\n var si = new Array(ni);\r\n for (let i = 0; i < ni; i++) si[i] = i;\r\n\r\n var nct = Math.min(m - 1, n);\r\n var nrt = Math.max(0, Math.min(n - 2, m));\r\n var mrc = Math.max(nct, nrt);\r\n\r\n for (let k = 0; k < mrc; k++) {\r\n if (k < nct) {\r\n s[k] = 0;\r\n for (let i = k; i < m; i++) {\r\n s[k] = hypotenuse(s[k], a[i][k]);\r\n }\r\n if (s[k] !== 0) {\r\n if (a[k][k] < 0) {\r\n s[k] = -s[k];\r\n }\r\n for (let i = k; i < m; i++) {\r\n a[i][k] /= s[k];\r\n }\r\n a[k][k] += 1;\r\n }\r\n s[k] = -s[k];\r\n }\r\n\r\n for (let j = k + 1; j < n; j++) {\r\n if (k < nct && s[k] !== 0) {\r\n let t = 0;\r\n for (let i = k; i < m; i++) {\r\n t += a[i][k] * a[i][j];\r\n }\r\n t = -t / a[k][k];\r\n for (let i = k; i < m; i++) {\r\n a[i][j] += t * a[i][k];\r\n }\r\n }\r\n e[j] = a[k][j];\r\n }\r\n\r\n if (wantu && k < nct) {\r\n for (let i = k; i < m; i++) {\r\n U[i][k] = a[i][k];\r\n }\r\n }\r\n\r\n if (k < nrt) {\r\n e[k] = 0;\r\n for (let i = k + 1; i < n; i++) {\r\n e[k] = hypotenuse(e[k], e[i]);\r\n }\r\n if (e[k] !== 0) {\r\n if (e[k + 1] < 0) {\r\n e[k] = 0 - e[k];\r\n }\r\n for (let i = k + 1; i < n; i++) {\r\n e[i] /= e[k];\r\n }\r\n e[k + 1] += 1;\r\n }\r\n e[k] = -e[k];\r\n if (k + 1 < m && e[k] !== 0) {\r\n for (let i = k + 1; i < m; i++) {\r\n work[i] = 0;\r\n }\r\n for (let i = k + 1; i < m; i++) {\r\n for (let j = k + 1; j < n; j++) {\r\n work[i] += e[j] * a[i][j];\r\n }\r\n }\r\n for (let j = k + 1; j < n; j++) {\r\n let t = -e[j] / e[k + 1];\r\n for (let i = k + 1; i < m; i++) {\r\n a[i][j] += t * work[i];\r\n }\r\n }\r\n }\r\n if (wantv) {\r\n for (let i = k + 1; i < n; i++) {\r\n V[i][k] = e[i];\r\n }\r\n }\r\n }\r\n }\r\n\r\n let p = Math.min(n, m + 1);\r\n if (nct < n) {\r\n s[nct] = a[nct][nct];\r\n }\r\n if (m < p) {\r\n s[p - 1] = 0;\r\n }\r\n if (nrt + 1 < p) {\r\n e[nrt] = a[nrt][p - 1];\r\n }\r\n e[p - 1] = 0;\r\n\r\n if (wantu) {\r\n for (let j = nct; j < nu; j++) {\r\n for (let i = 0; i < m; i++) {\r\n U[i][j] = 0;\r\n }\r\n U[j][j] = 1;\r\n }\r\n for (let k = nct - 1; k >= 0; k--) {\r\n if (s[k] !== 0) {\r\n for (let j = k + 1; j < nu; j++) {\r\n let t = 0;\r\n for (let i = k; i < m; i++) {\r\n t += U[i][k] * U[i][j];\r\n }\r\n t = -t / U[k][k];\r\n for (let i = k; i < m; i++) {\r\n U[i][j] += t * U[i][k];\r\n }\r\n }\r\n for (let i = k; i < m; i++) {\r\n U[i][k] = -U[i][k];\r\n }\r\n U[k][k] = 1 + U[k][k];\r\n for (let i = 0; i < k - 1; i++) {\r\n U[i][k] = 0;\r\n }\r\n } else {\r\n for (let i = 0; i < m; i++) {\r\n U[i][k] = 0;\r\n }\r\n U[k][k] = 1;\r\n }\r\n }\r\n }\r\n\r\n if (wantv) {\r\n for (let k = n - 1; k >= 0; k--) {\r\n if (k < nrt && e[k] !== 0) {\r\n for (let j = k + 1; j < n; j++) {\r\n let t = 0;\r\n for (let i = k + 1; i < n; i++) {\r\n t += V[i][k] * V[i][j];\r\n }\r\n t = -t / V[k + 1][k];\r\n for (let i = k + 1; i < n; i++) {\r\n V[i][j] += t * V[i][k];\r\n }\r\n }\r\n }\r\n for (let i = 0; i < n; i++) {\r\n V[i][k] = 0;\r\n }\r\n V[k][k] = 1;\r\n }\r\n }\r\n\r\n var pp = p - 1;\r\n var iter = 0;\r\n var eps = Number.EPSILON;\r\n while (p > 0) {\r\n let k, kase;\r\n for (k = p - 2; k >= -1; k--) {\r\n if (k === -1) {\r\n break;\r\n }\r\n const alpha =\r\n Number.MIN_VALUE + eps * Math.abs(s[k] + Math.abs(s[k + 1]));\r\n if (Math.abs(e[k]) <= alpha || Number.isNaN(e[k])) {\r\n e[k] = 0;\r\n break;\r\n }\r\n }\r\n if (k === p - 2) {\r\n kase = 4;\r\n } else {\r\n let ks;\r\n for (ks = p - 1; ks >= k; ks--) {\r\n if (ks === k) {\r\n break;\r\n }\r\n let t =\r\n (ks !== p ? Math.abs(e[ks]) : 0) +\r\n (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0);\r\n if (Math.abs(s[ks]) <= eps * t) {\r\n s[ks] = 0;\r\n break;\r\n }\r\n }\r\n if (ks === k) {\r\n kase = 3;\r\n } else if (ks === p - 1) {\r\n kase = 1;\r\n } else {\r\n kase = 2;\r\n k = ks;\r\n }\r\n }\r\n\r\n k++;\r\n\r\n switch (kase) {\r\n case 1: {\r\n let f = e[p - 2];\r\n e[p - 2] = 0;\r\n for (let j = p - 2; j >= k; j--) {\r\n let t = hypotenuse(s[j], f);\r\n let cs = s[j] / t;\r\n let sn = f / t;\r\n s[j] = t;\r\n if (j !== k) {\r\n f = -sn * e[j - 1];\r\n e[j - 1] = cs * e[j - 1];\r\n }\r\n if (wantv) {\r\n for (let i = 0; i < n; i++) {\r\n t = cs * V[i][j] + sn * V[i][p - 1];\r\n V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1];\r\n V[i][j] = t;\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n case 2: {\r\n let f = e[k - 1];\r\n e[k - 1] = 0;\r\n for (let j = k; j < p; j++) {\r\n let t = hypotenuse(s[j], f);\r\n let cs = s[j] / t;\r\n let sn = f / t;\r\n s[j] = t;\r\n f = -sn * e[j];\r\n e[j] = cs * e[j];\r\n if (wantu) {\r\n for (let i = 0; i < m; i++) {\r\n t = cs * U[i][j] + sn * U[i][k - 1];\r\n U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1];\r\n U[i][j] = t;\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n case 3: {\r\n const scale = Math.max(\r\n Math.abs(s[p - 1]),\r\n Math.abs(s[p - 2]),\r\n Math.abs(e[p - 2]),\r\n Math.abs(s[k]),\r\n Math.abs(e[k])\r\n );\r\n const sp = s[p - 1] / scale;\r\n const spm1 = s[p - 2] / scale;\r\n const epm1 = e[p - 2] / scale;\r\n const sk = s[k] / scale;\r\n const ek = e[k] / scale;\r\n const b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;\r\n const c = sp * epm1 * (sp * epm1);\r\n let shift = 0;\r\n if (b !== 0 || c !== 0) {\r\n if (b < 0) {\r\n shift = 0 - Math.sqrt(b * b + c);\r\n } else {\r\n shift = Math.sqrt(b * b + c);\r\n }\r\n shift = c / (b + shift);\r\n }\r\n let f = (sk + sp) * (sk - sp) + shift;\r\n let g = sk * ek;\r\n for (let j = k; j < p - 1; j++) {\r\n let t = hypotenuse(f, g);\r\n if (t === 0) t = Number.MIN_VALUE;\r\n let cs = f / t;\r\n let sn = g / t;\r\n if (j !== k) {\r\n e[j - 1] = t;\r\n }\r\n f = cs * s[j] + sn * e[j];\r\n e[j] = cs * e[j] - sn * s[j];\r\n g = sn * s[j + 1];\r\n s[j + 1] = cs * s[j + 1];\r\n if (wantv) {\r\n for (let i = 0; i < n; i++) {\r\n t = cs * V[i][j] + sn * V[i][j + 1];\r\n V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1];\r\n V[i][j] = t;\r\n }\r\n }\r\n t = hypotenuse(f, g);\r\n if (t === 0) t = Number.MIN_VALUE;\r\n cs = f / t;\r\n sn = g / t;\r\n s[j] = t;\r\n f = cs * e[j] + sn * s[j + 1];\r\n s[j + 1] = -sn * e[j] + cs * s[j + 1];\r\n g = sn * e[j + 1];\r\n e[j + 1] = cs * e[j + 1];\r\n if (wantu && j < m - 1) {\r\n for (let i = 0; i < m; i++) {\r\n t = cs * U[i][j] + sn * U[i][j + 1];\r\n U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1];\r\n U[i][j] = t;\r\n }\r\n }\r\n }\r\n e[p - 2] = f;\r\n iter = iter + 1;\r\n break;\r\n }\r\n case 4: {\r\n if (s[k] <= 0) {\r\n s[k] = s[k] < 0 ? -s[k] : 0;\r\n if (wantv) {\r\n for (let i = 0; i <= pp; i++) {\r\n V[i][k] = -V[i][k];\r\n }\r\n }\r\n }\r\n while (k < pp) {\r\n if (s[k] >= s[k + 1]) {\r\n break;\r\n }\r\n let t = s[k];\r\n s[k] = s[k + 1];\r\n s[k + 1] = t;\r\n if (wantv && k < n - 1) {\r\n for (let i = 0; i < n; i++) {\r\n t = V[i][k + 1];\r\n V[i][k + 1] = V[i][k];\r\n V[i][k] = t;\r\n }\r\n }\r\n if (wantu && k < m - 1) {\r\n for (let i = 0; i < m; i++) {\r\n t = U[i][k + 1];\r\n U[i][k + 1] = U[i][k];\r\n U[i][k] = t;\r\n }\r\n }\r\n k++;\r\n }\r\n iter = 0;\r\n p--;\r\n break;\r\n }\r\n // no default\r\n }\r\n }\r\n\r\n if (swapped) {\r\n var tmp = V;\r\n V = U;\r\n U = tmp;\r\n }\r\n\r\n this.m = m;\r\n this.n = n;\r\n this.s = s;\r\n this.U = U;\r\n this.V = V;\r\n }\r\n\r\n /**\r\n * Solve a problem of least square (Ax=b) by using the SVD. Useful when A is singular. When A is not singular, it would be better to use qr.solve(value).\r\n * Example : We search to approximate x, with A matrix shape m*n, x vector size n, b vector size m (m > n). We will use :\r\n * var svd = SingularValueDecomposition(A);\r\n * var x = svd.solve(b);\r\n * @param {Matrix} value - Matrix 1D which is the vector b (in the equation Ax = b)\r\n * @return {Matrix} - The vector x\r\n */\r\n solve(value) {\r\n var Y = value;\r\n var e = this.threshold;\r\n var scols = this.s.length;\r\n var Ls = Matrix.zeros(scols, scols);\r\n\r\n for (let i = 0; i < scols; i++) {\r\n if (Math.abs(this.s[i]) <= e) {\r\n Ls[i][i] = 0;\r\n } else {\r\n Ls[i][i] = 1 / this.s[i];\r\n }\r\n }\r\n\r\n var U = this.U;\r\n var V = this.rightSingularVectors;\r\n\r\n var VL = V.mmul(Ls);\r\n var vrows = V.rows;\r\n var urows = U.length;\r\n var VLU = Matrix.zeros(vrows, urows);\r\n\r\n for (let i = 0; i < vrows; i++) {\r\n for (let j = 0; j < urows; j++) {\r\n let sum = 0;\r\n for (let k = 0; k < scols; k++) {\r\n sum += VL[i][k] * U[j][k];\r\n }\r\n VLU[i][j] = sum;\r\n }\r\n }\r\n\r\n return VLU.mmul(Y);\r\n }\r\n\r\n /**\r\n *\r\n * @param {Array} value\r\n * @return {Matrix}\r\n */\r\n solveForDiagonal(value) {\r\n return this.solve(Matrix.diag(value));\r\n }\r\n\r\n /**\r\n * Get the inverse of the matrix. We compute the inverse of a matrix using SVD when this matrix is singular or ill-conditioned. Example :\r\n * var svd = SingularValueDecomposition(A);\r\n * var inverseA = svd.inverse();\r\n * @return {Matrix} - The approximation of the inverse of the matrix\r\n */\r\n inverse() {\r\n var V = this.V;\r\n var e = this.threshold;\r\n var vrows = V.length;\r\n var vcols = V[0].length;\r\n var X = new Matrix(vrows, this.s.length);\r\n\r\n for (let i = 0; i < vrows; i++) {\r\n for (let j = 0; j < vcols; j++) {\r\n if (Math.abs(this.s[j]) > e) {\r\n X[i][j] = V[i][j] / this.s[j];\r\n } else {\r\n X[i][j] = 0;\r\n }\r\n }\r\n }\r\n\r\n var U = this.U;\r\n\r\n var urows = U.length;\r\n var ucols = U[0].length;\r\n var Y = new Matrix(vrows, urows);\r\n\r\n for (let i = 0; i < vrows; i++) {\r\n for (let j = 0; j < urows; j++) {\r\n let sum = 0;\r\n for (let k = 0; k < ucols; k++) {\r\n sum += X[i][k] * U[j][k];\r\n }\r\n Y[i][j] = sum;\r\n }\r\n }\r\n\r\n return Y;\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get condition() {\r\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get norm2() {\r\n return this.s[0];\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get rank() {\r\n var tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON;\r\n var r = 0;\r\n var s = this.s;\r\n for (var i = 0, ii = s.length; i < ii; i++) {\r\n if (s[i] > tol) {\r\n r++;\r\n }\r\n }\r\n return r;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Array}\r\n */\r\n get diagonal() {\r\n return this.s;\r\n }\r\n\r\n /**\r\n *\r\n * @return {number}\r\n */\r\n get threshold() {\r\n return Number.EPSILON / 2 * Math.max(this.m, this.n) * this.s[0];\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get leftSingularVectors() {\r\n if (!Matrix.isMatrix(this.U)) {\r\n this.U = new Matrix(this.U);\r\n }\r\n return this.U;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get rightSingularVectors() {\r\n if (!Matrix.isMatrix(this.V)) {\r\n this.V = new Matrix(this.V);\r\n }\r\n return this.V;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get diagonalMatrix() {\r\n return Matrix.diag(this.s);\r\n }\r\n}\r\n","import Matrix from './matrix';\r\n\r\n/**\r\n * @private\r\n * Check that a row index is not out of bounds\r\n * @param {Matrix} matrix\r\n * @param {number} index\r\n * @param {boolean} [outer]\r\n */\r\nexport function checkRowIndex(matrix, index, outer) {\r\n var max = outer ? matrix.rows : matrix.rows - 1;\r\n if (index < 0 || index > max) {\r\n throw new RangeError('Row index out of range');\r\n }\r\n}\r\n\r\n/**\r\n * @private\r\n * Check that a column index is not out of bounds\r\n * @param {Matrix} matrix\r\n * @param {number} index\r\n * @param {boolean} [outer]\r\n */\r\nexport function checkColumnIndex(matrix, index, outer) {\r\n var max = outer ? matrix.columns : matrix.columns - 1;\r\n if (index < 0 || index > max) {\r\n throw new RangeError('Column index out of range');\r\n }\r\n}\r\n\r\n/**\r\n * @private\r\n * Check that the provided vector is an array with the right length\r\n * @param {Matrix} matrix\r\n * @param {Array|Matrix} vector\r\n * @return {Array}\r\n * @throws {RangeError}\r\n */\r\nexport function checkRowVector(matrix, vector) {\r\n if (vector.to1DArray) {\r\n vector = vector.to1DArray();\r\n }\r\n if (vector.length !== matrix.columns) {\r\n throw new RangeError(\r\n 'vector size must be the same as the number of columns'\r\n );\r\n }\r\n return vector;\r\n}\r\n\r\n/**\r\n * @private\r\n * Check that the provided vector is an array with the right length\r\n * @param {Matrix} matrix\r\n * @param {Array|Matrix} vector\r\n * @return {Array}\r\n * @throws {RangeError}\r\n */\r\nexport function checkColumnVector(matrix, vector) {\r\n if (vector.to1DArray) {\r\n vector = vector.to1DArray();\r\n }\r\n if (vector.length !== matrix.rows) {\r\n throw new RangeError('vector size must be the same as the number of rows');\r\n }\r\n return vector;\r\n}\r\n\r\nexport function checkIndices(matrix, rowIndices, columnIndices) {\r\n return {\r\n row: checkRowIndices(matrix, rowIndices),\r\n column: checkColumnIndices(matrix, columnIndices)\r\n };\r\n}\r\n\r\nexport function checkRowIndices(matrix, rowIndices) {\r\n if (typeof rowIndices !== 'object') {\r\n throw new TypeError('unexpected type for row indices');\r\n }\r\n\r\n var rowOut = rowIndices.some((r) => {\r\n return r < 0 || r >= matrix.rows;\r\n });\r\n\r\n if (rowOut) {\r\n throw new RangeError('row indices are out of range');\r\n }\r\n\r\n if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices);\r\n\r\n return rowIndices;\r\n}\r\n\r\nexport function checkColumnIndices(matrix, columnIndices) {\r\n if (typeof columnIndices !== 'object') {\r\n throw new TypeError('unexpected type for column indices');\r\n }\r\n\r\n var columnOut = columnIndices.some((c) => {\r\n return c < 0 || c >= matrix.columns;\r\n });\r\n\r\n if (columnOut) {\r\n throw new RangeError('column indices are out of range');\r\n }\r\n if (!Array.isArray(columnIndices)) columnIndices = Array.from(columnIndices);\r\n\r\n return columnIndices;\r\n}\r\n\r\nexport function checkRange(matrix, startRow, endRow, startColumn, endColumn) {\r\n if (arguments.length !== 5) {\r\n throw new RangeError('expected 4 arguments');\r\n }\r\n checkNumber('startRow', startRow);\r\n checkNumber('endRow', endRow);\r\n checkNumber('startColumn', startColumn);\r\n checkNumber('endColumn', endColumn);\r\n if (\r\n startRow > endRow ||\r\n startColumn > endColumn ||\r\n startRow < 0 ||\r\n startRow >= matrix.rows ||\r\n endRow < 0 ||\r\n endRow >= matrix.rows ||\r\n startColumn < 0 ||\r\n startColumn >= matrix.columns ||\r\n endColumn < 0 ||\r\n endColumn >= matrix.columns\r\n ) {\r\n throw new RangeError('Submatrix indices are out of range');\r\n }\r\n}\r\n\r\nexport function getRange(from, to) {\r\n var arr = new Array(to - from + 1);\r\n for (var i = 0; i < arr.length; i++) {\r\n arr[i] = from + i;\r\n }\r\n return arr;\r\n}\r\n\r\nexport function sumByRow(matrix) {\r\n var sum = Matrix.zeros(matrix.rows, 1);\r\n for (var i = 0; i < matrix.rows; ++i) {\r\n for (var j = 0; j < matrix.columns; ++j) {\r\n sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j));\r\n }\r\n }\r\n return sum;\r\n}\r\n\r\nexport function sumByColumn(matrix) {\r\n var sum = Matrix.zeros(1, matrix.columns);\r\n for (var i = 0; i < matrix.rows; ++i) {\r\n for (var j = 0; j < matrix.columns; ++j) {\r\n sum.set(0, j, sum.get(0, j) + matrix.get(i, j));\r\n }\r\n }\r\n return sum;\r\n}\r\n\r\nexport function sumAll(matrix) {\r\n var v = 0;\r\n for (var i = 0; i < matrix.rows; i++) {\r\n for (var j = 0; j < matrix.columns; j++) {\r\n v += matrix.get(i, j);\r\n }\r\n }\r\n return v;\r\n}\r\n\r\nfunction checkNumber(name, value) {\r\n if (typeof value !== 'number') {\r\n throw new TypeError(`${name} must be a number`);\r\n }\r\n}\r\n","import AbstractMatrix from '../abstractMatrix';\r\nimport Matrix from '../matrix';\r\n\r\nexport default class BaseView extends AbstractMatrix() {\r\n constructor(matrix, rows, columns) {\r\n super();\r\n this.matrix = matrix;\r\n this.rows = rows;\r\n this.columns = columns;\r\n }\r\n\r\n static get [Symbol.species]() {\r\n return Matrix;\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixTransposeView extends BaseView {\r\n constructor(matrix) {\r\n super(matrix, matrix.columns, matrix.rows);\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(columnIndex, rowIndex, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(columnIndex, rowIndex);\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixRowView extends BaseView {\r\n constructor(matrix, row) {\r\n super(matrix, 1, matrix.columns);\r\n this.row = row;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(this.row, columnIndex, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(this.row, columnIndex);\r\n }\r\n}\r\n","import { checkRange } from '../util';\r\n\r\nimport BaseView from './base';\r\n\r\nexport default class MatrixSubView extends BaseView {\r\n constructor(matrix, startRow, endRow, startColumn, endColumn) {\r\n checkRange(matrix, startRow, endRow, startColumn, endColumn);\r\n super(matrix, endRow - startRow + 1, endColumn - startColumn + 1);\r\n this.startRow = startRow;\r\n this.startColumn = startColumn;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(\r\n this.startRow + rowIndex,\r\n this.startColumn + columnIndex,\r\n value\r\n );\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(\r\n this.startRow + rowIndex,\r\n this.startColumn + columnIndex\r\n );\r\n }\r\n}\r\n","import { checkIndices } from '../util';\r\n\r\nimport BaseView from './base';\r\n\r\nexport default class MatrixSelectionView extends BaseView {\r\n constructor(matrix, rowIndices, columnIndices) {\r\n var indices = checkIndices(matrix, rowIndices, columnIndices);\r\n super(matrix, indices.row.length, indices.column.length);\r\n this.rowIndices = indices.row;\r\n this.columnIndices = indices.column;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(\r\n this.rowIndices[rowIndex],\r\n this.columnIndices[columnIndex],\r\n value\r\n );\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(\r\n this.rowIndices[rowIndex],\r\n this.columnIndices[columnIndex]\r\n );\r\n }\r\n}\r\n","import { checkRowIndices } from '../util';\r\n\r\nimport BaseView from './base';\r\n\r\nexport default class MatrixRowSelectionView extends BaseView {\r\n constructor(matrix, rowIndices) {\r\n rowIndices = checkRowIndices(matrix, rowIndices);\r\n super(matrix, rowIndices.length, matrix.columns);\r\n this.rowIndices = rowIndices;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(this.rowIndices[rowIndex], columnIndex, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(this.rowIndices[rowIndex], columnIndex);\r\n }\r\n}\r\n","import { checkColumnIndices } from '../util';\r\n\r\nimport BaseView from './base';\r\n\r\nexport default class MatrixColumnSelectionView extends BaseView {\r\n constructor(matrix, columnIndices) {\r\n columnIndices = checkColumnIndices(matrix, columnIndices);\r\n super(matrix, matrix.rows, columnIndices.length);\r\n this.columnIndices = columnIndices;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(rowIndex, this.columnIndices[columnIndex], value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(rowIndex, this.columnIndices[columnIndex]);\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixColumnView extends BaseView {\r\n constructor(matrix, column) {\r\n super(matrix, matrix.rows, 1);\r\n this.column = column;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(rowIndex, this.column, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex) {\r\n return this.matrix.get(rowIndex, this.column);\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixFlipRowView extends BaseView {\r\n constructor(matrix) {\r\n super(matrix, matrix.rows, matrix.columns);\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(this.rows - rowIndex - 1, columnIndex, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(this.rows - rowIndex - 1, columnIndex);\r\n }\r\n}\r\n","import BaseView from './base';\r\n\r\nexport default class MatrixFlipColumnView extends BaseView {\r\n constructor(matrix) {\r\n super(matrix, matrix.rows, matrix.columns);\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.matrix.set(rowIndex, this.columns - columnIndex - 1, value);\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.matrix.get(rowIndex, this.columns - columnIndex - 1);\r\n }\r\n}\r\n","import rescale from 'ml-array-rescale';\r\n\r\nimport LuDecomposition from './dc/lu';\r\nimport SvDecomposition from './dc/svd';\r\nimport {\r\n checkRowVector, checkRowIndex, checkColumnIndex, checkColumnVector,\r\n checkRange, checkIndices,\r\n sumByRow, sumByColumn, sumAll\r\n} from './util';\r\nimport MatrixTransposeView from './views/transpose';\r\nimport MatrixRowView from './views/row';\r\nimport MatrixSubView from './views/sub';\r\nimport MatrixSelectionView from './views/selection';\r\nimport MatrixRowSelectionView from './views/rowSelection';\r\nimport MatrixColumnSelectionView from './views/columnSelection';\r\nimport MatrixColumnView from './views/column';\r\nimport MatrixFlipRowView from './views/flipRow';\r\nimport MatrixFlipColumnView from './views/flipColumn';\r\n\r\nexport default function AbstractMatrix(superCtor) {\r\n if (superCtor === undefined) superCtor = Object;\r\n\r\n /**\r\n * Real matrix\r\n * @class Matrix\r\n * @param {number|Array|Matrix} nRows - Number of rows of the new matrix,\r\n * 2D array containing the data or Matrix instance to clone\r\n * @param {number} [nColumns] - Number of columns of the new matrix\r\n */\r\n class Matrix extends superCtor {\r\n static get [Symbol.species]() {\r\n return this;\r\n }\r\n\r\n /**\r\n * Constructs a Matrix with the chosen dimensions from a 1D array\r\n * @param {number} newRows - Number of rows\r\n * @param {number} newColumns - Number of columns\r\n * @param {Array} newData - A 1D array containing data for the matrix\r\n * @return {Matrix} - The new matrix\r\n */\r\n static from1DArray(newRows, newColumns, newData) {\r\n var length = newRows * newColumns;\r\n if (length !== newData.length) {\r\n throw new RangeError('Data length does not match given dimensions');\r\n }\r\n var newMatrix = new this(newRows, newColumns);\r\n for (var row = 0; row < newRows; row++) {\r\n for (var column = 0; column < newColumns; column++) {\r\n newMatrix.set(row, column, newData[row * newColumns + column]);\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Creates a row vector, a matrix with only one row.\r\n * @param {Array} newData - A 1D array containing data for the vector\r\n * @return {Matrix} - The new matrix\r\n */\r\n static rowVector(newData) {\r\n var vector = new this(1, newData.length);\r\n for (var i = 0; i < newData.length; i++) {\r\n vector.set(0, i, newData[i]);\r\n }\r\n return vector;\r\n }\r\n\r\n /**\r\n * Creates a column vector, a matrix with only one column.\r\n * @param {Array} newData - A 1D array containing data for the vector\r\n * @return {Matrix} - The new matrix\r\n */\r\n static columnVector(newData) {\r\n var vector = new this(newData.length, 1);\r\n for (var i = 0; i < newData.length; i++) {\r\n vector.set(i, 0, newData[i]);\r\n }\r\n return vector;\r\n }\r\n\r\n /**\r\n * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns).\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @return {Matrix} - The new matrix\r\n */\r\n static empty(rows, columns) {\r\n return new this(rows, columns);\r\n }\r\n\r\n /**\r\n * Creates a matrix with the given dimensions. Values will be set to zero.\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @return {Matrix} - The new matrix\r\n */\r\n static zeros(rows, columns) {\r\n return this.empty(rows, columns).fill(0);\r\n }\r\n\r\n /**\r\n * Creates a matrix with the given dimensions. Values will be set to one.\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @return {Matrix} - The new matrix\r\n */\r\n static ones(rows, columns) {\r\n return this.empty(rows, columns).fill(1);\r\n }\r\n\r\n /**\r\n * Creates a matrix with the given dimensions. Values will be randomly set.\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @param {function} [rng=Math.random] - Random number generator\r\n * @return {Matrix} The new matrix\r\n */\r\n static rand(rows, columns, rng) {\r\n if (rng === undefined) rng = Math.random;\r\n var matrix = this.empty(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n matrix.set(i, j, rng());\r\n }\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Creates a matrix with the given dimensions. Values will be random integers.\r\n * @param {number} rows - Number of rows\r\n * @param {number} columns - Number of columns\r\n * @param {number} [maxValue=1000] - Maximum value\r\n * @param {function} [rng=Math.random] - Random number generator\r\n * @return {Matrix} The new matrix\r\n */\r\n static randInt(rows, columns, maxValue, rng) {\r\n if (maxValue === undefined) maxValue = 1000;\r\n if (rng === undefined) rng = Math.random;\r\n var matrix = this.empty(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n var value = Math.floor(rng() * maxValue);\r\n matrix.set(i, j, value);\r\n }\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0.\r\n * @param {number} rows - Number of rows\r\n * @param {number} [columns=rows] - Number of columns\r\n * @param {number} [value=1] - Value to fill the diagonal with\r\n * @return {Matrix} - The new identity matrix\r\n */\r\n static eye(rows, columns, value) {\r\n if (columns === undefined) columns = rows;\r\n if (value === undefined) value = 1;\r\n var min = Math.min(rows, columns);\r\n var matrix = this.zeros(rows, columns);\r\n for (var i = 0; i < min; i++) {\r\n matrix.set(i, i, value);\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Creates a diagonal matrix based on the given array.\r\n * @param {Array} data - Array containing the data for the diagonal\r\n * @param {number} [rows] - Number of rows (Default: data.length)\r\n * @param {number} [columns] - Number of columns (Default: rows)\r\n * @return {Matrix} - The new diagonal matrix\r\n */\r\n static diag(data, rows, columns) {\r\n var l = data.length;\r\n if (rows === undefined) rows = l;\r\n if (columns === undefined) columns = rows;\r\n var min = Math.min(l, rows, columns);\r\n var matrix = this.zeros(rows, columns);\r\n for (var i = 0; i < min; i++) {\r\n matrix.set(i, i, data[i]);\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Returns a matrix whose elements are the minimum between matrix1 and matrix2\r\n * @param {Matrix} matrix1\r\n * @param {Matrix} matrix2\r\n * @return {Matrix}\r\n */\r\n static min(matrix1, matrix2) {\r\n matrix1 = this.checkMatrix(matrix1);\r\n matrix2 = this.checkMatrix(matrix2);\r\n var rows = matrix1.rows;\r\n var columns = matrix1.columns;\r\n var result = new this(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a matrix whose elements are the maximum between matrix1 and matrix2\r\n * @param {Matrix} matrix1\r\n * @param {Matrix} matrix2\r\n * @return {Matrix}\r\n */\r\n static max(matrix1, matrix2) {\r\n matrix1 = this.checkMatrix(matrix1);\r\n matrix2 = this.checkMatrix(matrix2);\r\n var rows = matrix1.rows;\r\n var columns = matrix1.columns;\r\n var result = new this(rows, columns);\r\n for (var i = 0; i < rows; i++) {\r\n for (var j = 0; j < columns; j++) {\r\n result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Check that the provided value is a Matrix and tries to instantiate one if not\r\n * @param {*} value - The value to check\r\n * @return {Matrix}\r\n */\r\n static checkMatrix(value) {\r\n return Matrix.isMatrix(value) ? value : new this(value);\r\n }\r\n\r\n /**\r\n * Returns true if the argument is a Matrix, false otherwise\r\n * @param {*} value - The value to check\r\n * @return {boolean}\r\n */\r\n static isMatrix(value) {\r\n return (value != null) && (value.klass === 'Matrix');\r\n }\r\n\r\n /**\r\n * @prop {number} size - The number of elements in the matrix.\r\n */\r\n get size() {\r\n return this.rows * this.columns;\r\n }\r\n\r\n /**\r\n * Applies a callback for each element of the matrix. The function is called in the matrix (this) context.\r\n * @param {function} callback - Function that will be called with two parameters : i (row) and j (column)\r\n * @return {Matrix} this\r\n */\r\n apply(callback) {\r\n if (typeof callback !== 'function') {\r\n throw new TypeError('callback must be a function');\r\n }\r\n var ii = this.rows;\r\n var jj = this.columns;\r\n for (var i = 0; i < ii; i++) {\r\n for (var j = 0; j < jj; j++) {\r\n callback.call(this, i, j);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns a new 1D array filled row by row with the matrix values\r\n * @return {Array}\r\n */\r\n to1DArray() {\r\n var array = new Array(this.size);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n array[i * this.columns + j] = this.get(i, j);\r\n }\r\n }\r\n return array;\r\n }\r\n\r\n /**\r\n * Returns a 2D array containing a copy of the data\r\n * @return {Array}\r\n */\r\n to2DArray() {\r\n var copy = new Array(this.rows);\r\n for (var i = 0; i < this.rows; i++) {\r\n copy[i] = new Array(this.columns);\r\n for (var j = 0; j < this.columns; j++) {\r\n copy[i][j] = this.get(i, j);\r\n }\r\n }\r\n return copy;\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix has one row\r\n */\r\n isRowVector() {\r\n return this.rows === 1;\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix has one column\r\n */\r\n isColumnVector() {\r\n return this.columns === 1;\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix has one row or one column\r\n */\r\n isVector() {\r\n return (this.rows === 1) || (this.columns === 1);\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix has the same number of rows and columns\r\n */\r\n isSquare() {\r\n return this.rows === this.columns;\r\n }\r\n\r\n /**\r\n * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal\r\n */\r\n isSymmetric() {\r\n if (this.isSquare()) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j <= i; j++) {\r\n if (this.get(i, j) !== this.get(j, i)) {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * @return true if the matrix is in echelon form\r\n */\r\n isEchelonForm() {\r\n let i = 0;\r\n let j = 0;\r\n let previousColumn = -1;\r\n let isEchelonForm = true;\r\n let checked = false;\r\n while ((i < this.rows) && (isEchelonForm)) {\r\n j = 0;\r\n checked = false;\r\n while ((j < this.columns) && (checked === false)) {\r\n if (this.get(i, j) === 0) {\r\n j++;\r\n } else if ((this.get(i, j) === 1) && (j > previousColumn)) {\r\n checked = true;\r\n previousColumn = j;\r\n } else {\r\n isEchelonForm = false;\r\n checked = true;\r\n }\r\n }\r\n i++;\r\n }\r\n return isEchelonForm;\r\n }\r\n\r\n /**\r\n * @return true if the matrix is in reduced echelon form\r\n */\r\n isReducedEchelonForm() {\r\n let i = 0;\r\n let j = 0;\r\n let previousColumn = -1;\r\n let isReducedEchelonForm = true;\r\n let checked = false;\r\n while ((i < this.rows) && (isReducedEchelonForm)) {\r\n j = 0;\r\n checked = false;\r\n while ((j < this.columns) && (checked === false)) {\r\n if (this.get(i, j) === 0) {\r\n j++;\r\n } else if ((this.get(i, j) === 1) && (j > previousColumn)) {\r\n checked = true;\r\n previousColumn = j;\r\n } else {\r\n isReducedEchelonForm = false;\r\n checked = true;\r\n }\r\n }\r\n for (let k = j + 1; k < this.rows; k++) {\r\n if (this.get(i, k) !== 0) {\r\n isReducedEchelonForm = false;\r\n }\r\n }\r\n i++;\r\n }\r\n return isReducedEchelonForm;\r\n }\r\n\r\n /**\r\n * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1\r\n * @abstract\r\n * @param {number} rowIndex - Index of the row\r\n * @param {number} columnIndex - Index of the column\r\n * @param {number} value - The new value for the element\r\n * @return {Matrix} this\r\n */\r\n set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars\r\n throw new Error('set method is unimplemented');\r\n }\r\n\r\n /**\r\n * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4]\r\n * @abstract\r\n * @param {number} rowIndex - Index of the row\r\n * @param {number} columnIndex - Index of the column\r\n * @return {number}\r\n */\r\n get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars\r\n throw new Error('get method is unimplemented');\r\n }\r\n\r\n /**\r\n * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of\r\n * rows of the matrix, and colRep times the number of columns of the matrix\r\n * @param {number} rowRep - Number of times the rows should be repeated\r\n * @param {number} colRep - Number of times the columns should be re\r\n * @return {Matrix}\r\n * @example\r\n * var matrix = new Matrix([[1,2]]);\r\n * matrix.repeat(2); // [[1,2],[1,2]]\r\n */\r\n repeat(rowRep, colRep) {\r\n rowRep = rowRep || 1;\r\n colRep = colRep || 1;\r\n var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep);\r\n for (var i = 0; i < rowRep; i++) {\r\n for (var j = 0; j < colRep; j++) {\r\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\r\n }\r\n }\r\n return matrix;\r\n }\r\n\r\n /**\r\n * Fills the matrix with a given value. All elements will be set to this value.\r\n * @param {number} value - New value\r\n * @return {Matrix} this\r\n */\r\n fill(value) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, value);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Negates the matrix. All elements will be multiplied by (-1)\r\n * @return {Matrix} this\r\n */\r\n neg() {\r\n return this.mulS(-1);\r\n }\r\n\r\n /**\r\n * Returns a new array from the given row index\r\n * @param {number} index - Row index\r\n * @return {Array}\r\n */\r\n getRow(index) {\r\n checkRowIndex(this, index);\r\n var row = new Array(this.columns);\r\n for (var i = 0; i < this.columns; i++) {\r\n row[i] = this.get(index, i);\r\n }\r\n return row;\r\n }\r\n\r\n /**\r\n * Returns a new row vector from the given row index\r\n * @param {number} index - Row index\r\n * @return {Matrix}\r\n */\r\n getRowVector(index) {\r\n return this.constructor.rowVector(this.getRow(index));\r\n }\r\n\r\n /**\r\n * Sets a row at the given index\r\n * @param {number} index - Row index\r\n * @param {Array|Matrix} array - Array or vector\r\n * @return {Matrix} this\r\n */\r\n setRow(index, array) {\r\n checkRowIndex(this, index);\r\n array = checkRowVector(this, array);\r\n for (var i = 0; i < this.columns; i++) {\r\n this.set(index, i, array[i]);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Swaps two rows\r\n * @param {number} row1 - First row index\r\n * @param {number} row2 - Second row index\r\n * @return {Matrix} this\r\n */\r\n swapRows(row1, row2) {\r\n checkRowIndex(this, row1);\r\n checkRowIndex(this, row2);\r\n for (var i = 0; i < this.columns; i++) {\r\n var temp = this.get(row1, i);\r\n this.set(row1, i, this.get(row2, i));\r\n this.set(row2, i, temp);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns a new array from the given column index\r\n * @param {number} index - Column index\r\n * @return {Array}\r\n */\r\n getColumn(index) {\r\n checkColumnIndex(this, index);\r\n var column = new Array(this.rows);\r\n for (var i = 0; i < this.rows; i++) {\r\n column[i] = this.get(i, index);\r\n }\r\n return column;\r\n }\r\n\r\n /**\r\n * Returns a new column vector from the given column index\r\n * @param {number} index - Column index\r\n * @return {Matrix}\r\n */\r\n getColumnVector(index) {\r\n return this.constructor.columnVector(this.getColumn(index));\r\n }\r\n\r\n /**\r\n * Sets a column at the given index\r\n * @param {number} index - Column index\r\n * @param {Array|Matrix} array - Array or vector\r\n * @return {Matrix} this\r\n */\r\n setColumn(index, array) {\r\n checkColumnIndex(this, index);\r\n array = checkColumnVector(this, array);\r\n for (var i = 0; i < this.rows; i++) {\r\n this.set(i, index, array[i]);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Swaps two columns\r\n * @param {number} column1 - First column index\r\n * @param {number} column2 - Second column index\r\n * @return {Matrix} this\r\n */\r\n swapColumns(column1, column2) {\r\n checkColumnIndex(this, column1);\r\n checkColumnIndex(this, column2);\r\n for (var i = 0; i < this.rows; i++) {\r\n var temp = this.get(i, column1);\r\n this.set(i, column1, this.get(i, column2));\r\n this.set(i, column2, temp);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Adds the values of a vector to each row\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n addRowVector(vector) {\r\n vector = checkRowVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) + vector[j]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Subtracts the values of a vector from each row\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n subRowVector(vector) {\r\n vector = checkRowVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) - vector[j]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Multiplies the values of a vector with each row\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n mulRowVector(vector) {\r\n vector = checkRowVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) * vector[j]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Divides the values of each row by those of a vector\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n divRowVector(vector) {\r\n vector = checkRowVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) / vector[j]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Adds the values of a vector to each column\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n addColumnVector(vector) {\r\n vector = checkColumnVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) + vector[i]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Subtracts the values of a vector from each column\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n subColumnVector(vector) {\r\n vector = checkColumnVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) - vector[i]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Multiplies the values of a vector with each column\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n mulColumnVector(vector) {\r\n vector = checkColumnVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) * vector[i]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Divides the values of each column by those of a vector\r\n * @param {Array|Matrix} vector - Array or vector\r\n * @return {Matrix} this\r\n */\r\n divColumnVector(vector) {\r\n vector = checkColumnVector(this, vector);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) / vector[i]);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Multiplies the values of a row with a scalar\r\n * @param {number} index - Row index\r\n * @param {number} value\r\n * @return {Matrix} this\r\n */\r\n mulRow(index, value) {\r\n checkRowIndex(this, index);\r\n for (var i = 0; i < this.columns; i++) {\r\n this.set(index, i, this.get(index, i) * value);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Multiplies the values of a column with a scalar\r\n * @param {number} index - Column index\r\n * @param {number} value\r\n * @return {Matrix} this\r\n */\r\n mulColumn(index, value) {\r\n checkColumnIndex(this, index);\r\n for (var i = 0; i < this.rows; i++) {\r\n this.set(i, index, this.get(i, index) * value);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns the maximum value of the matrix\r\n * @return {number}\r\n */\r\n max() {\r\n var v = this.get(0, 0);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n if (this.get(i, j) > v) {\r\n v = this.get(i, j);\r\n }\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the maximum value\r\n * @return {Array}\r\n */\r\n maxIndex() {\r\n var v = this.get(0, 0);\r\n var idx = [0, 0];\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n if (this.get(i, j) > v) {\r\n v = this.get(i, j);\r\n idx[0] = i;\r\n idx[1] = j;\r\n }\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the minimum value of the matrix\r\n * @return {number}\r\n */\r\n min() {\r\n var v = this.get(0, 0);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n if (this.get(i, j) < v) {\r\n v = this.get(i, j);\r\n }\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the minimum value\r\n * @return {Array}\r\n */\r\n minIndex() {\r\n var v = this.get(0, 0);\r\n var idx = [0, 0];\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n if (this.get(i, j) < v) {\r\n v = this.get(i, j);\r\n idx[0] = i;\r\n idx[1] = j;\r\n }\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the maximum value of one row\r\n * @param {number} row - Row index\r\n * @return {number}\r\n */\r\n maxRow(row) {\r\n checkRowIndex(this, row);\r\n var v = this.get(row, 0);\r\n for (var i = 1; i < this.columns; i++) {\r\n if (this.get(row, i) > v) {\r\n v = this.get(row, i);\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the maximum value of one row\r\n * @param {number} row - Row index\r\n * @return {Array}\r\n */\r\n maxRowIndex(row) {\r\n checkRowIndex(this, row);\r\n var v = this.get(row, 0);\r\n var idx = [row, 0];\r\n for (var i = 1; i < this.columns; i++) {\r\n if (this.get(row, i) > v) {\r\n v = this.get(row, i);\r\n idx[1] = i;\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the minimum value of one row\r\n * @param {number} row - Row index\r\n * @return {number}\r\n */\r\n minRow(row) {\r\n checkRowIndex(this, row);\r\n var v = this.get(row, 0);\r\n for (var i = 1; i < this.columns; i++) {\r\n if (this.get(row, i) < v) {\r\n v = this.get(row, i);\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the maximum value of one row\r\n * @param {number} row - Row index\r\n * @return {Array}\r\n */\r\n minRowIndex(row) {\r\n checkRowIndex(this, row);\r\n var v = this.get(row, 0);\r\n var idx = [row, 0];\r\n for (var i = 1; i < this.columns; i++) {\r\n if (this.get(row, i) < v) {\r\n v = this.get(row, i);\r\n idx[1] = i;\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the maximum value of one column\r\n * @param {number} column - Column index\r\n * @return {number}\r\n */\r\n maxColumn(column) {\r\n checkColumnIndex(this, column);\r\n var v = this.get(0, column);\r\n for (var i = 1; i < this.rows; i++) {\r\n if (this.get(i, column) > v) {\r\n v = this.get(i, column);\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the maximum value of one column\r\n * @param {number} column - Column index\r\n * @return {Array}\r\n */\r\n maxColumnIndex(column) {\r\n checkColumnIndex(this, column);\r\n var v = this.get(0, column);\r\n var idx = [0, column];\r\n for (var i = 1; i < this.rows; i++) {\r\n if (this.get(i, column) > v) {\r\n v = this.get(i, column);\r\n idx[0] = i;\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns the minimum value of one column\r\n * @param {number} column - Column index\r\n * @return {number}\r\n */\r\n minColumn(column) {\r\n checkColumnIndex(this, column);\r\n var v = this.get(0, column);\r\n for (var i = 1; i < this.rows; i++) {\r\n if (this.get(i, column) < v) {\r\n v = this.get(i, column);\r\n }\r\n }\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the index of the minimum value of one column\r\n * @param {number} column - Column index\r\n * @return {Array}\r\n */\r\n minColumnIndex(column) {\r\n checkColumnIndex(this, column);\r\n var v = this.get(0, column);\r\n var idx = [0, column];\r\n for (var i = 1; i < this.rows; i++) {\r\n if (this.get(i, column) < v) {\r\n v = this.get(i, column);\r\n idx[0] = i;\r\n }\r\n }\r\n return idx;\r\n }\r\n\r\n /**\r\n * Returns an array containing the diagonal values of the matrix\r\n * @return {Array}\r\n */\r\n diag() {\r\n var min = Math.min(this.rows, this.columns);\r\n var diag = new Array(min);\r\n for (var i = 0; i < min; i++) {\r\n diag[i] = this.get(i, i);\r\n }\r\n return diag;\r\n }\r\n\r\n /**\r\n * Returns the sum by the argument given, if no argument given,\r\n * it returns the sum of all elements of the matrix.\r\n * @param {string} by - sum by 'row' or 'column'.\r\n * @return {Matrix|number}\r\n */\r\n sum(by) {\r\n switch (by) {\r\n case 'row':\r\n return sumByRow(this);\r\n case 'column':\r\n return sumByColumn(this);\r\n default:\r\n return sumAll(this);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the mean of all elements of the matrix\r\n * @return {number}\r\n */\r\n mean() {\r\n return this.sum() / this.size;\r\n }\r\n\r\n /**\r\n * Returns the product of all elements of the matrix\r\n * @return {number}\r\n */\r\n prod() {\r\n var prod = 1;\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n prod *= this.get(i, j);\r\n }\r\n }\r\n return prod;\r\n }\r\n\r\n /**\r\n * Returns the norm of a matrix.\r\n * @param {string} type - \"frobenius\" (default) or \"max\" return resp. the Frobenius norm and the max norm.\r\n * @return {number}\r\n */\r\n norm(type = 'frobenius') {\r\n var result = 0;\r\n if (type === 'max') {\r\n return this.max();\r\n } else if (type === 'frobenius') {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n result = result + this.get(i, j) * this.get(i, j);\r\n }\r\n }\r\n return Math.sqrt(result);\r\n } else {\r\n throw new RangeError(`unknown norm type: ${type}`);\r\n }\r\n }\r\n\r\n /**\r\n * Computes the cumulative sum of the matrix elements (in place, row by row)\r\n * @return {Matrix} this\r\n */\r\n cumulativeSum() {\r\n var sum = 0;\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n sum += this.get(i, j);\r\n this.set(i, j, sum);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Computes the dot (scalar) product between the matrix and another\r\n * @param {Matrix} vector2 vector\r\n * @return {number}\r\n */\r\n dot(vector2) {\r\n if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\r\n var vector1 = this.to1DArray();\r\n if (vector1.length !== vector2.length) {\r\n throw new RangeError('vectors do not have the same size');\r\n }\r\n var dot = 0;\r\n for (var i = 0; i < vector1.length; i++) {\r\n dot += vector1[i] * vector2[i];\r\n }\r\n return dot;\r\n }\r\n\r\n /**\r\n * Returns the matrix product between this and other\r\n * @param {Matrix} other\r\n * @return {Matrix}\r\n */\r\n mmul(other) {\r\n other = this.constructor.checkMatrix(other);\r\n if (this.columns !== other.rows) {\r\n // eslint-disable-next-line no-console\r\n console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\r\n }\r\n\r\n var m = this.rows;\r\n var n = this.columns;\r\n var p = other.columns;\r\n\r\n var result = new this.constructor[Symbol.species](m, p);\r\n\r\n var Bcolj = new Array(n);\r\n for (var j = 0; j < p; j++) {\r\n for (var k = 0; k < n; k++) {\r\n Bcolj[k] = other.get(k, j);\r\n }\r\n\r\n for (var i = 0; i < m; i++) {\r\n var s = 0;\r\n for (k = 0; k < n; k++) {\r\n s += this.get(i, k) * Bcolj[k];\r\n }\r\n\r\n result.set(i, j, s);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n strassen2x2(other) {\r\n var result = new this.constructor[Symbol.species](2, 2);\r\n const a11 = this.get(0, 0);\r\n const b11 = other.get(0, 0);\r\n const a12 = this.get(0, 1);\r\n const b12 = other.get(0, 1);\r\n const a21 = this.get(1, 0);\r\n const b21 = other.get(1, 0);\r\n const a22 = this.get(1, 1);\r\n const b22 = other.get(1, 1);\r\n\r\n // Compute intermediate values.\r\n const m1 = (a11 + a22) * (b11 + b22);\r\n const m2 = (a21 + a22) * b11;\r\n const m3 = a11 * (b12 - b22);\r\n const m4 = a22 * (b21 - b11);\r\n const m5 = (a11 + a12) * b22;\r\n const m6 = (a21 - a11) * (b11 + b12);\r\n const m7 = (a12 - a22) * (b21 + b22);\r\n\r\n // Combine intermediate values into the output.\r\n const c00 = m1 + m4 - m5 + m7;\r\n const c01 = m3 + m5;\r\n const c10 = m2 + m4;\r\n const c11 = m1 - m2 + m3 + m6;\r\n\r\n result.set(0, 0, c00);\r\n result.set(0, 1, c01);\r\n result.set(1, 0, c10);\r\n result.set(1, 1, c11);\r\n return result;\r\n }\r\n\r\n strassen3x3(other) {\r\n var result = new this.constructor[Symbol.species](3, 3);\r\n\r\n const a00 = this.get(0, 0);\r\n const a01 = this.get(0, 1);\r\n const a02 = this.get(0, 2);\r\n const a10 = this.get(1, 0);\r\n const a11 = this.get(1, 1);\r\n const a12 = this.get(1, 2);\r\n const a20 = this.get(2, 0);\r\n const a21 = this.get(2, 1);\r\n const a22 = this.get(2, 2);\r\n\r\n const b00 = other.get(0, 0);\r\n const b01 = other.get(0, 1);\r\n const b02 = other.get(0, 2);\r\n const b10 = other.get(1, 0);\r\n const b11 = other.get(1, 1);\r\n const b12 = other.get(1, 2);\r\n const b20 = other.get(2, 0);\r\n const b21 = other.get(2, 1);\r\n const b22 = other.get(2, 2);\r\n\r\n const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;\r\n const m2 = (a00 - a10) * (-b01 + b11);\r\n const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);\r\n const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);\r\n const m5 = (a10 + a11) * (-b00 + b01);\r\n const m6 = a00 * b00;\r\n const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);\r\n const m8 = (-a00 + a20) * (b02 - b12);\r\n const m9 = (a20 + a21) * (-b00 + b02);\r\n const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;\r\n const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);\r\n const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);\r\n const m13 = (a02 - a22) * (b11 - b21);\r\n const m14 = a02 * b20;\r\n const m15 = (a21 + a22) * (-b20 + b21);\r\n const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);\r\n const m17 = (a02 - a12) * (b12 - b22);\r\n const m18 = (a11 + a12) * (-b20 + b22);\r\n const m19 = a01 * b10;\r\n const m20 = a12 * b21;\r\n const m21 = a10 * b02;\r\n const m22 = a20 * b01;\r\n const m23 = a22 * b22;\r\n\r\n const c00 = m6 + m14 + m19;\r\n const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;\r\n const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;\r\n const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;\r\n const c11 = m2 + m4 + m5 + m6 + m20;\r\n const c12 = m14 + m16 + m17 + m18 + m21;\r\n const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;\r\n const c21 = m12 + m13 + m14 + m15 + m22;\r\n const c22 = m6 + m7 + m8 + m9 + m23;\r\n\r\n result.set(0, 0, c00);\r\n result.set(0, 1, c01);\r\n result.set(0, 2, c02);\r\n result.set(1, 0, c10);\r\n result.set(1, 1, c11);\r\n result.set(1, 2, c12);\r\n result.set(2, 0, c20);\r\n result.set(2, 1, c21);\r\n result.set(2, 2, c22);\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000.\r\n * @param {Matrix} y\r\n * @return {Matrix}\r\n */\r\n mmulStrassen(y) {\r\n var x = this.clone();\r\n var r1 = x.rows;\r\n var c1 = x.columns;\r\n var r2 = y.rows;\r\n var c2 = y.columns;\r\n if (c1 !== r2) {\r\n // eslint-disable-next-line no-console\r\n console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`);\r\n }\r\n\r\n // Put a matrix into the top left of a matrix of zeros.\r\n // `rows` and `cols` are the dimensions of the output matrix.\r\n function embed(mat, rows, cols) {\r\n var r = mat.rows;\r\n var c = mat.columns;\r\n if ((r === rows) && (c === cols)) {\r\n return mat;\r\n } else {\r\n var resultat = Matrix.zeros(rows, cols);\r\n resultat = resultat.setSubMatrix(mat, 0, 0);\r\n return resultat;\r\n }\r\n }\r\n\r\n\r\n // Make sure both matrices are the same size.\r\n // This is exclusively for simplicity:\r\n // this algorithm can be implemented with matrices of different sizes.\r\n\r\n var r = Math.max(r1, r2);\r\n var c = Math.max(c1, c2);\r\n x = embed(x, r, c);\r\n y = embed(y, r, c);\r\n\r\n // Our recursive multiplication function.\r\n function blockMult(a, b, rows, cols) {\r\n // For small matrices, resort to naive multiplication.\r\n if (rows <= 512 || cols <= 512) {\r\n return a.mmul(b); // a is equivalent to this\r\n }\r\n\r\n // Apply dynamic padding.\r\n if ((rows % 2 === 1) && (cols % 2 === 1)) {\r\n a = embed(a, rows + 1, cols + 1);\r\n b = embed(b, rows + 1, cols + 1);\r\n } else if (rows % 2 === 1) {\r\n a = embed(a, rows + 1, cols);\r\n b = embed(b, rows + 1, cols);\r\n } else if (cols % 2 === 1) {\r\n a = embed(a, rows, cols + 1);\r\n b = embed(b, rows, cols + 1);\r\n }\r\n\r\n var halfRows = parseInt(a.rows / 2, 10);\r\n var halfCols = parseInt(a.columns / 2, 10);\r\n // Subdivide input matrices.\r\n var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\r\n var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\r\n\r\n var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\r\n var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\r\n\r\n var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\r\n var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\r\n\r\n var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\r\n var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\r\n\r\n // Compute intermediate values.\r\n var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols);\r\n var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols);\r\n var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols);\r\n var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols);\r\n var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols);\r\n var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols);\r\n var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols);\r\n\r\n // Combine intermediate values into the output.\r\n var c11 = Matrix.add(m1, m4);\r\n c11.sub(m5);\r\n c11.add(m7);\r\n var c12 = Matrix.add(m3, m5);\r\n var c21 = Matrix.add(m2, m4);\r\n var c22 = Matrix.sub(m1, m2);\r\n c22.add(m3);\r\n c22.add(m6);\r\n\r\n // Crop output to the desired size (undo dynamic padding).\r\n var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns);\r\n resultat = resultat.setSubMatrix(c11, 0, 0);\r\n resultat = resultat.setSubMatrix(c12, c11.rows, 0);\r\n resultat = resultat.setSubMatrix(c21, 0, c11.columns);\r\n resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns);\r\n return resultat.subMatrix(0, rows - 1, 0, cols - 1);\r\n }\r\n return blockMult(x, y, r, c);\r\n }\r\n\r\n /**\r\n * Returns a row-by-row scaled matrix\r\n * @param {number} [min=0] - Minimum scaled value\r\n * @param {number} [max=1] - Maximum scaled value\r\n * @return {Matrix} - The scaled matrix\r\n */\r\n scaleRows(min, max) {\r\n min = min === undefined ? 0 : min;\r\n max = max === undefined ? 1 : max;\r\n if (min >= max) {\r\n throw new RangeError('min should be strictly smaller than max');\r\n }\r\n var newMatrix = this.constructor.empty(this.rows, this.columns);\r\n for (var i = 0; i < this.rows; i++) {\r\n var scaled = rescale(this.getRow(i), { min, max });\r\n newMatrix.setRow(i, scaled);\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Returns a new column-by-column scaled matrix\r\n * @param {number} [min=0] - Minimum scaled value\r\n * @param {number} [max=1] - Maximum scaled value\r\n * @return {Matrix} - The new scaled matrix\r\n * @example\r\n * var matrix = new Matrix([[1,2],[-1,0]]);\r\n * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]]\r\n */\r\n scaleColumns(min, max) {\r\n min = min === undefined ? 0 : min;\r\n max = max === undefined ? 1 : max;\r\n if (min >= max) {\r\n throw new RangeError('min should be strictly smaller than max');\r\n }\r\n var newMatrix = this.constructor.empty(this.rows, this.columns);\r\n for (var i = 0; i < this.columns; i++) {\r\n var scaled = rescale(this.getColumn(i), {\r\n min: min,\r\n max: max\r\n });\r\n newMatrix.setColumn(i, scaled);\r\n }\r\n return newMatrix;\r\n }\r\n\r\n\r\n /**\r\n * Returns the Kronecker product (also known as tensor product) between this and other\r\n * See https://en.wikipedia.org/wiki/Kronecker_product\r\n * @param {Matrix} other\r\n * @return {Matrix}\r\n */\r\n kroneckerProduct(other) {\r\n other = this.constructor.checkMatrix(other);\r\n\r\n var m = this.rows;\r\n var n = this.columns;\r\n var p = other.rows;\r\n var q = other.columns;\r\n\r\n var result = new this.constructor[Symbol.species](m * p, n * q);\r\n for (var i = 0; i < m; i++) {\r\n for (var j = 0; j < n; j++) {\r\n for (var k = 0; k < p; k++) {\r\n for (var l = 0; l < q; l++) {\r\n result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l);\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Transposes the matrix and returns a new one containing the result\r\n * @return {Matrix}\r\n */\r\n transpose() {\r\n var result = new this.constructor[Symbol.species](this.columns, this.rows);\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n result.set(j, i, this.get(i, j));\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Sorts the rows (in place)\r\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\r\n * @return {Matrix} this\r\n */\r\n sortRows(compareFunction) {\r\n if (compareFunction === undefined) compareFunction = compareNumbers;\r\n for (var i = 0; i < this.rows; i++) {\r\n this.setRow(i, this.getRow(i).sort(compareFunction));\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Sorts the columns (in place)\r\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\r\n * @return {Matrix} this\r\n */\r\n sortColumns(compareFunction) {\r\n if (compareFunction === undefined) compareFunction = compareNumbers;\r\n for (var i = 0; i < this.columns; i++) {\r\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns a subset of the matrix\r\n * @param {number} startRow - First row index\r\n * @param {number} endRow - Last row index\r\n * @param {number} startColumn - First column index\r\n * @param {number} endColumn - Last column index\r\n * @return {Matrix}\r\n */\r\n subMatrix(startRow, endRow, startColumn, endColumn) {\r\n checkRange(this, startRow, endRow, startColumn, endColumn);\r\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1);\r\n for (var i = startRow; i <= endRow; i++) {\r\n for (var j = startColumn; j <= endColumn; j++) {\r\n newMatrix[i - startRow][j - startColumn] = this.get(i, j);\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Returns a subset of the matrix based on an array of row indices\r\n * @param {Array} indices - Array containing the row indices\r\n * @param {number} [startColumn = 0] - First column index\r\n * @param {number} [endColumn = this.columns-1] - Last column index\r\n * @return {Matrix}\r\n */\r\n subMatrixRow(indices, startColumn, endColumn) {\r\n if (startColumn === undefined) startColumn = 0;\r\n if (endColumn === undefined) endColumn = this.columns - 1;\r\n if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) {\r\n throw new RangeError('Argument out of range');\r\n }\r\n\r\n var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1);\r\n for (var i = 0; i < indices.length; i++) {\r\n for (var j = startColumn; j <= endColumn; j++) {\r\n if (indices[i] < 0 || indices[i] >= this.rows) {\r\n throw new RangeError(`Row index out of range: ${indices[i]}`);\r\n }\r\n newMatrix.set(i, j - startColumn, this.get(indices[i], j));\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Returns a subset of the matrix based on an array of column indices\r\n * @param {Array} indices - Array containing the column indices\r\n * @param {number} [startRow = 0] - First row index\r\n * @param {number} [endRow = this.rows-1] - Last row index\r\n * @return {Matrix}\r\n */\r\n subMatrixColumn(indices, startRow, endRow) {\r\n if (startRow === undefined) startRow = 0;\r\n if (endRow === undefined) endRow = this.rows - 1;\r\n if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) {\r\n throw new RangeError('Argument out of range');\r\n }\r\n\r\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length);\r\n for (var i = 0; i < indices.length; i++) {\r\n for (var j = startRow; j <= endRow; j++) {\r\n if (indices[i] < 0 || indices[i] >= this.columns) {\r\n throw new RangeError(`Column index out of range: ${indices[i]}`);\r\n }\r\n newMatrix.set(j - startRow, i, this.get(j, indices[i]));\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Set a part of the matrix to the given sub-matrix\r\n * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values.\r\n * @param {number} startRow - The index of the first row to set\r\n * @param {number} startColumn - The index of the first column to set\r\n * @return {Matrix}\r\n */\r\n setSubMatrix(matrix, startRow, startColumn) {\r\n matrix = this.constructor.checkMatrix(matrix);\r\n var endRow = startRow + matrix.rows - 1;\r\n var endColumn = startColumn + matrix.columns - 1;\r\n checkRange(this, startRow, endRow, startColumn, endColumn);\r\n for (var i = 0; i < matrix.rows; i++) {\r\n for (var j = 0; j < matrix.columns; j++) {\r\n this[startRow + i][startColumn + j] = matrix.get(i, j);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Return a new matrix based on a selection of rows and columns\r\n * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once.\r\n * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once.\r\n * @return {Matrix} The new matrix\r\n */\r\n selection(rowIndices, columnIndices) {\r\n var indices = checkIndices(this, rowIndices, columnIndices);\r\n var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length);\r\n for (var i = 0; i < indices.row.length; i++) {\r\n var rowIndex = indices.row[i];\r\n for (var j = 0; j < indices.column.length; j++) {\r\n var columnIndex = indices.column[j];\r\n newMatrix[i][j] = this.get(rowIndex, columnIndex);\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n\r\n /**\r\n * Returns the trace of the matrix (sum of the diagonal elements)\r\n * @return {number}\r\n */\r\n trace() {\r\n var min = Math.min(this.rows, this.columns);\r\n var trace = 0;\r\n for (var i = 0; i < min; i++) {\r\n trace += this.get(i, i);\r\n }\r\n return trace;\r\n }\r\n\r\n /*\r\n Matrix views\r\n */\r\n\r\n /**\r\n * Returns a view of the transposition of the matrix\r\n * @return {MatrixTransposeView}\r\n */\r\n transposeView() {\r\n return new MatrixTransposeView(this);\r\n }\r\n\r\n /**\r\n * Returns a view of the row vector with the given index\r\n * @param {number} row - row index of the vector\r\n * @return {MatrixRowView}\r\n */\r\n rowView(row) {\r\n checkRowIndex(this, row);\r\n return new MatrixRowView(this, row);\r\n }\r\n\r\n /**\r\n * Returns a view of the column vector with the given index\r\n * @param {number} column - column index of the vector\r\n * @return {MatrixColumnView}\r\n */\r\n columnView(column) {\r\n checkColumnIndex(this, column);\r\n return new MatrixColumnView(this, column);\r\n }\r\n\r\n /**\r\n * Returns a view of the matrix flipped in the row axis\r\n * @return {MatrixFlipRowView}\r\n */\r\n flipRowView() {\r\n return new MatrixFlipRowView(this);\r\n }\r\n\r\n /**\r\n * Returns a view of the matrix flipped in the column axis\r\n * @return {MatrixFlipColumnView}\r\n */\r\n flipColumnView() {\r\n return new MatrixFlipColumnView(this);\r\n }\r\n\r\n /**\r\n * Returns a view of a submatrix giving the index boundaries\r\n * @param {number} startRow - first row index of the submatrix\r\n * @param {number} endRow - last row index of the submatrix\r\n * @param {number} startColumn - first column index of the submatrix\r\n * @param {number} endColumn - last column index of the submatrix\r\n * @return {MatrixSubView}\r\n */\r\n subMatrixView(startRow, endRow, startColumn, endColumn) {\r\n return new MatrixSubView(this, startRow, endRow, startColumn, endColumn);\r\n }\r\n\r\n /**\r\n * Returns a view of the cross of the row indices and the column indices\r\n * @example\r\n * // resulting vector is [[2], [2]]\r\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1])\r\n * @param {Array} rowIndices\r\n * @param {Array} columnIndices\r\n * @return {MatrixSelectionView}\r\n */\r\n selectionView(rowIndices, columnIndices) {\r\n return new MatrixSelectionView(this, rowIndices, columnIndices);\r\n }\r\n\r\n /**\r\n * Returns a view of the row indices\r\n * @example\r\n * // resulting vector is [[1,2,3], [1,2,3]]\r\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).rowSelectionView([0, 0])\r\n * @param {Array} rowIndices\r\n * @return {MatrixRowSelectionView}\r\n */\r\n rowSelectionView(rowIndices) {\r\n return new MatrixRowSelectionView(this, rowIndices);\r\n }\r\n\r\n /**\r\n * Returns a view of the column indices\r\n * @example\r\n * // resulting vector is [[2, 2], [5, 5]]\r\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).columnSelectionView([1, 1])\r\n * @param {Array} columnIndices\r\n * @return {MatrixColumnSelectionView}\r\n */\r\n columnSelectionView(columnIndices) {\r\n return new MatrixColumnSelectionView(this, columnIndices);\r\n }\r\n\r\n\r\n /**\r\n * Calculates and returns the determinant of a matrix as a Number\r\n * @example\r\n * new Matrix([[1,2,3], [4,5,6]]).det()\r\n * @return {number}\r\n */\r\n det() {\r\n if (this.isSquare()) {\r\n var a, b, c, d;\r\n if (this.columns === 2) {\r\n // 2 x 2 matrix\r\n a = this.get(0, 0);\r\n b = this.get(0, 1);\r\n c = this.get(1, 0);\r\n d = this.get(1, 1);\r\n\r\n return a * d - (b * c);\r\n } else if (this.columns === 3) {\r\n // 3 x 3 matrix\r\n var subMatrix0, subMatrix1, subMatrix2;\r\n subMatrix0 = this.selectionView([1, 2], [1, 2]);\r\n subMatrix1 = this.selectionView([1, 2], [0, 2]);\r\n subMatrix2 = this.selectionView([1, 2], [0, 1]);\r\n a = this.get(0, 0);\r\n b = this.get(0, 1);\r\n c = this.get(0, 2);\r\n\r\n return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det();\r\n } else {\r\n // general purpose determinant using the LU decomposition\r\n return new LuDecomposition(this).determinant;\r\n }\r\n } else {\r\n throw Error('Determinant can only be calculated for a square matrix.');\r\n }\r\n }\r\n\r\n /**\r\n * Returns inverse of a matrix if it exists or the pseudoinverse\r\n * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15)\r\n * @return {Matrix} the (pseudo)inverted matrix.\r\n */\r\n pseudoInverse(threshold) {\r\n if (threshold === undefined) threshold = Number.EPSILON;\r\n var svdSolution = new SvDecomposition(this, { autoTranspose: true });\r\n\r\n var U = svdSolution.leftSingularVectors;\r\n var V = svdSolution.rightSingularVectors;\r\n var s = svdSolution.diagonal;\r\n\r\n for (var i = 0; i < s.length; i++) {\r\n if (Math.abs(s[i]) > threshold) {\r\n s[i] = 1.0 / s[i];\r\n } else {\r\n s[i] = 0.0;\r\n }\r\n }\r\n\r\n // convert list to diagonal\r\n s = this.constructor[Symbol.species].diag(s);\r\n return V.mmul(s.mmul(U.transposeView()));\r\n }\r\n\r\n /**\r\n * Creates an exact and independent copy of the matrix\r\n * @return {Matrix}\r\n */\r\n clone() {\r\n var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns);\r\n for (var row = 0; row < this.rows; row++) {\r\n for (var column = 0; column < this.columns; column++) {\r\n newMatrix.set(row, column, this.get(row, column));\r\n }\r\n }\r\n return newMatrix;\r\n }\r\n }\r\n\r\n Matrix.prototype.klass = 'Matrix';\r\n\r\n function compareNumbers(a, b) {\r\n return a - b;\r\n }\r\n\r\n /*\r\n Synonyms\r\n */\r\n\r\n Matrix.random = Matrix.rand;\r\n Matrix.diagonal = Matrix.diag;\r\n Matrix.prototype.diagonal = Matrix.prototype.diag;\r\n Matrix.identity = Matrix.eye;\r\n Matrix.prototype.negate = Matrix.prototype.neg;\r\n Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct;\r\n Matrix.prototype.determinant = Matrix.prototype.det;\r\n\r\n /*\r\n Add dynamically instance and static methods for mathematical operations\r\n */\r\n\r\n var inplaceOperator = `\r\n(function %name%(value) {\r\n if (typeof value === 'number') return this.%name%S(value);\r\n return this.%name%M(value);\r\n})\r\n`;\r\n\r\n var inplaceOperatorScalar = `\r\n(function %name%S(value) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) %op% value);\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var inplaceOperatorMatrix = `\r\n(function %name%M(matrix) {\r\n matrix = this.constructor.checkMatrix(matrix);\r\n if (this.rows !== matrix.rows ||\r\n this.columns !== matrix.columns) {\r\n throw new RangeError('Matrices dimensions must be equal');\r\n }\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) %op% matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var staticOperator = `\r\n(function %name%(matrix, value) {\r\n var newMatrix = new this[Symbol.species](matrix);\r\n return newMatrix.%name%(value);\r\n})\r\n`;\r\n\r\n var inplaceMethod = `\r\n(function %name%() {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, %method%(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var staticMethod = `\r\n(function %name%(matrix) {\r\n var newMatrix = new this[Symbol.species](matrix);\r\n return newMatrix.%name%();\r\n})\r\n`;\r\n\r\n var inplaceMethodWithArgs = `\r\n(function %name%(%args%) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, %method%(this.get(i, j), %args%));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var staticMethodWithArgs = `\r\n(function %name%(matrix, %args%) {\r\n var newMatrix = new this[Symbol.species](matrix);\r\n return newMatrix.%name%(%args%);\r\n})\r\n`;\r\n\r\n\r\n var inplaceMethodWithOneArgScalar = `\r\n(function %name%S(value) {\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, %method%(this.get(i, j), value));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n var inplaceMethodWithOneArgMatrix = `\r\n(function %name%M(matrix) {\r\n matrix = this.constructor.checkMatrix(matrix);\r\n if (this.rows !== matrix.rows ||\r\n this.columns !== matrix.columns) {\r\n throw new RangeError('Matrices dimensions must be equal');\r\n }\r\n for (var i = 0; i < this.rows; i++) {\r\n for (var j = 0; j < this.columns; j++) {\r\n this.set(i, j, %method%(this.get(i, j), matrix.get(i, j)));\r\n }\r\n }\r\n return this;\r\n})\r\n`;\r\n\r\n var inplaceMethodWithOneArg = `\r\n(function %name%(value) {\r\n if (typeof value === 'number') return this.%name%S(value);\r\n return this.%name%M(value);\r\n})\r\n`;\r\n\r\n var staticMethodWithOneArg = staticMethodWithArgs;\r\n\r\n var operators = [\r\n // Arithmetic operators\r\n ['+', 'add'],\r\n ['-', 'sub', 'subtract'],\r\n ['*', 'mul', 'multiply'],\r\n ['/', 'div', 'divide'],\r\n ['%', 'mod', 'modulus'],\r\n // Bitwise operators\r\n ['&', 'and'],\r\n ['|', 'or'],\r\n ['^', 'xor'],\r\n ['<<', 'leftShift'],\r\n ['>>', 'signPropagatingRightShift'],\r\n ['>>>', 'rightShift', 'zeroFillRightShift']\r\n ];\r\n\r\n var i;\r\n var eval2 = eval; // eslint-disable-line no-eval\r\n for (var operator of operators) {\r\n var inplaceOp = eval2(fillTemplateFunction(inplaceOperator, { name: operator[1], op: operator[0] }));\r\n var inplaceOpS = eval2(fillTemplateFunction(inplaceOperatorScalar, { name: `${operator[1]}S`, op: operator[0] }));\r\n var inplaceOpM = eval2(fillTemplateFunction(inplaceOperatorMatrix, { name: `${operator[1]}M`, op: operator[0] }));\r\n var staticOp = eval2(fillTemplateFunction(staticOperator, { name: operator[1] }));\r\n for (i = 1; i < operator.length; i++) {\r\n Matrix.prototype[operator[i]] = inplaceOp;\r\n Matrix.prototype[`${operator[i]}S`] = inplaceOpS;\r\n Matrix.prototype[`${operator[i]}M`] = inplaceOpM;\r\n Matrix[operator[i]] = staticOp;\r\n }\r\n }\r\n\r\n var methods = [['~', 'not']];\r\n\r\n [\r\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\r\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\r\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\r\n ].forEach(function (mathMethod) {\r\n methods.push([`Math.${mathMethod}`, mathMethod]);\r\n });\r\n\r\n for (var method of methods) {\r\n var inplaceMeth = eval2(fillTemplateFunction(inplaceMethod, { name: method[1], method: method[0] }));\r\n var staticMeth = eval2(fillTemplateFunction(staticMethod, { name: method[1] }));\r\n for (i = 1; i < method.length; i++) {\r\n Matrix.prototype[method[i]] = inplaceMeth;\r\n Matrix[method[i]] = staticMeth;\r\n }\r\n }\r\n\r\n var methodsWithArgs = [['Math.pow', 1, 'pow']];\r\n\r\n for (var methodWithArg of methodsWithArgs) {\r\n var args = 'arg0';\r\n for (i = 1; i < methodWithArg[1]; i++) {\r\n args += `, arg${i}`;\r\n }\r\n if (methodWithArg[1] !== 1) {\r\n var inplaceMethWithArgs = eval2(fillTemplateFunction(inplaceMethodWithArgs, {\r\n name: methodWithArg[2],\r\n method: methodWithArg[0],\r\n args: args\r\n }));\r\n var staticMethWithArgs = eval2(fillTemplateFunction(staticMethodWithArgs, { name: methodWithArg[2], args: args }));\r\n for (i = 2; i < methodWithArg.length; i++) {\r\n Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs;\r\n Matrix[methodWithArg[i]] = staticMethWithArgs;\r\n }\r\n } else {\r\n var tmplVar = {\r\n name: methodWithArg[2],\r\n args: args,\r\n method: methodWithArg[0]\r\n };\r\n var inplaceMethod2 = eval2(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar));\r\n var inplaceMethodS = eval2(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar));\r\n var inplaceMethodM = eval2(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar));\r\n var staticMethod2 = eval2(fillTemplateFunction(staticMethodWithOneArg, tmplVar));\r\n for (i = 2; i < methodWithArg.length; i++) {\r\n Matrix.prototype[methodWithArg[i]] = inplaceMethod2;\r\n Matrix.prototype[`${methodWithArg[i]}M`] = inplaceMethodM;\r\n Matrix.prototype[`${methodWithArg[i]}S`] = inplaceMethodS;\r\n Matrix[methodWithArg[i]] = staticMethod2;\r\n }\r\n }\r\n }\r\n\r\n function fillTemplateFunction(template, values) {\r\n for (var value in values) {\r\n template = template.replace(new RegExp(`%${value}%`, 'g'), values[value]);\r\n }\r\n return template;\r\n }\r\n\r\n return Matrix;\r\n}\r\n","import AbstractMatrix from './abstractMatrix';\r\nimport {\r\n checkColumnIndex,\r\n checkColumnVector,\r\n checkRowIndex,\r\n checkRowVector\r\n} from './util';\r\n\r\nexport default class Matrix extends AbstractMatrix(Array) {\r\n constructor(nRows, nColumns) {\r\n var i;\r\n if (arguments.length === 1 && typeof nRows === 'number') {\r\n return new Array(nRows);\r\n }\r\n if (Matrix.isMatrix(nRows)) {\r\n return nRows.clone();\r\n } else if (Number.isInteger(nRows) && nRows > 0) {\r\n // Create an empty matrix\r\n super(nRows);\r\n if (Number.isInteger(nColumns) && nColumns > 0) {\r\n for (i = 0; i < nRows; i++) {\r\n this[i] = new Array(nColumns);\r\n }\r\n } else {\r\n throw new TypeError('nColumns must be a positive integer');\r\n }\r\n } else if (Array.isArray(nRows)) {\r\n // Copy the values from the 2D array\r\n const matrix = nRows;\r\n nRows = matrix.length;\r\n nColumns = matrix[0].length;\r\n if (typeof nColumns !== 'number' || nColumns === 0) {\r\n throw new TypeError(\r\n 'Data must be a 2D array with at least one element'\r\n );\r\n }\r\n super(nRows);\r\n for (i = 0; i < nRows; i++) {\r\n if (matrix[i].length !== nColumns) {\r\n throw new RangeError('Inconsistent array dimensions');\r\n }\r\n this[i] = [].concat(matrix[i]);\r\n }\r\n } else {\r\n throw new TypeError(\r\n 'First argument must be a positive number or an array'\r\n );\r\n }\r\n this.rows = nRows;\r\n this.columns = nColumns;\r\n return this;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this[rowIndex][columnIndex] = value;\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this[rowIndex][columnIndex];\r\n }\r\n\r\n /**\r\n * Removes a row from the given index\r\n * @param {number} index - Row index\r\n * @return {Matrix} this\r\n */\r\n removeRow(index) {\r\n checkRowIndex(this, index);\r\n if (this.rows === 1) {\r\n throw new RangeError('A matrix cannot have less than one row');\r\n }\r\n this.splice(index, 1);\r\n this.rows -= 1;\r\n return this;\r\n }\r\n\r\n /**\r\n * Adds a row at the given index\r\n * @param {number} [index = this.rows] - Row index\r\n * @param {Array|Matrix} array - Array or vector\r\n * @return {Matrix} this\r\n */\r\n addRow(index, array) {\r\n if (array === undefined) {\r\n array = index;\r\n index = this.rows;\r\n }\r\n checkRowIndex(this, index, true);\r\n array = checkRowVector(this, array, true);\r\n this.splice(index, 0, array);\r\n this.rows += 1;\r\n return this;\r\n }\r\n\r\n /**\r\n * Removes a column from the given index\r\n * @param {number} index - Column index\r\n * @return {Matrix} this\r\n */\r\n removeColumn(index) {\r\n checkColumnIndex(this, index);\r\n if (this.columns === 1) {\r\n throw new RangeError('A matrix cannot have less than one column');\r\n }\r\n for (var i = 0; i < this.rows; i++) {\r\n this[i].splice(index, 1);\r\n }\r\n this.columns -= 1;\r\n return this;\r\n }\r\n\r\n /**\r\n * Adds a column at the given index\r\n * @param {number} [index = this.columns] - Column index\r\n * @param {Array|Matrix} array - Array or vector\r\n * @return {Matrix} this\r\n */\r\n addColumn(index, array) {\r\n if (typeof array === 'undefined') {\r\n array = index;\r\n index = this.columns;\r\n }\r\n checkColumnIndex(this, index, true);\r\n array = checkColumnVector(this, array);\r\n for (var i = 0; i < this.rows; i++) {\r\n this[i].splice(index, 0, array[i]);\r\n }\r\n this.columns += 1;\r\n return this;\r\n }\r\n}\r\n","import AbstractMatrix from '../abstractMatrix';\r\nimport Matrix from '../matrix';\r\n\r\nexport default class WrapperMatrix1D extends AbstractMatrix() {\r\n /**\r\n * @class WrapperMatrix1D\r\n * @param {Array} data\r\n * @param {object} [options]\r\n * @param {object} [options.rows = 1]\r\n */\r\n constructor(data, options = {}) {\r\n const { rows = 1 } = options;\r\n\r\n if (data.length % rows !== 0) {\r\n throw new Error('the data length is not divisible by the number of rows');\r\n }\r\n super();\r\n this.rows = rows;\r\n this.columns = data.length / rows;\r\n this.data = data;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n var index = this._calculateIndex(rowIndex, columnIndex);\r\n this.data[index] = value;\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n var index = this._calculateIndex(rowIndex, columnIndex);\r\n return this.data[index];\r\n }\r\n\r\n _calculateIndex(row, column) {\r\n return row * this.columns + column;\r\n }\r\n\r\n static get [Symbol.species]() {\r\n return Matrix;\r\n }\r\n}\r\n","import AbstractMatrix from '../abstractMatrix';\r\nimport Matrix from '../matrix';\r\n\r\nexport default class WrapperMatrix2D extends AbstractMatrix() {\r\n /**\r\n * @class WrapperMatrix2D\r\n * @param {Array>} data\r\n */\r\n constructor(data) {\r\n super();\r\n this.data = data;\r\n this.rows = data.length;\r\n this.columns = data[0].length;\r\n }\r\n\r\n set(rowIndex, columnIndex, value) {\r\n this.data[rowIndex][columnIndex] = value;\r\n return this;\r\n }\r\n\r\n get(rowIndex, columnIndex) {\r\n return this.data[rowIndex][columnIndex];\r\n }\r\n\r\n static get [Symbol.species]() {\r\n return Matrix;\r\n }\r\n}\r\n","import WrapperMatrix1D from './WrapperMatrix1D';\r\nimport WrapperMatrix2D from './WrapperMatrix2D';\r\n\r\n/**\r\n * @param {Array>|Array} array\r\n * @param {object} [options]\r\n * @param {object} [options.rows = 1]\r\n * @return {WrapperMatrix1D|WrapperMatrix2D}\r\n */\r\nexport function wrap(array, options) {\r\n if (Array.isArray(array)) {\r\n if (array[0] && Array.isArray(array[0])) {\r\n return new WrapperMatrix2D(array);\r\n } else {\r\n return new WrapperMatrix1D(array, options);\r\n }\r\n } else {\r\n throw new Error('the argument is not an array');\r\n }\r\n}\r\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\nimport { hypotenuse } from './util';\r\n\r\n/**\r\n * @class QrDecomposition\r\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs\r\n * @param {Matrix} value\r\n */\r\nexport default class QrDecomposition {\r\n constructor(value) {\r\n value = WrapperMatrix2D.checkMatrix(value);\r\n\r\n var qr = value.clone();\r\n var m = value.rows;\r\n var n = value.columns;\r\n var rdiag = new Array(n);\r\n var i, j, k, s;\r\n\r\n for (k = 0; k < n; k++) {\r\n var nrm = 0;\r\n for (i = k; i < m; i++) {\r\n nrm = hypotenuse(nrm, qr.get(i, k));\r\n }\r\n if (nrm !== 0) {\r\n if (qr.get(k, k) < 0) {\r\n nrm = -nrm;\r\n }\r\n for (i = k; i < m; i++) {\r\n qr.set(i, k, qr.get(i, k) / nrm);\r\n }\r\n qr.set(k, k, qr.get(k, k) + 1);\r\n for (j = k + 1; j < n; j++) {\r\n s = 0;\r\n for (i = k; i < m; i++) {\r\n s += qr.get(i, k) * qr.get(i, j);\r\n }\r\n s = -s / qr.get(k, k);\r\n for (i = k; i < m; i++) {\r\n qr.set(i, j, qr.get(i, j) + s * qr.get(i, k));\r\n }\r\n }\r\n }\r\n rdiag[k] = -nrm;\r\n }\r\n\r\n this.QR = qr;\r\n this.Rdiag = rdiag;\r\n }\r\n\r\n /**\r\n * Solve a problem of least square (Ax=b) by using the QR decomposition. Useful when A is rectangular, but not working when A is singular.\r\n * Example : We search to approximate x, with A matrix shape m*n, x vector size n, b vector size m (m > n). We will use :\r\n * var qr = QrDecomposition(A);\r\n * var x = qr.solve(b);\r\n * @param {Matrix} value - Matrix 1D which is the vector b (in the equation Ax = b)\r\n * @return {Matrix} - The vector x\r\n */\r\n solve(value) {\r\n value = Matrix.checkMatrix(value);\r\n\r\n var qr = this.QR;\r\n var m = qr.rows;\r\n\r\n if (value.rows !== m) {\r\n throw new Error('Matrix row dimensions must agree');\r\n }\r\n if (!this.isFullRank()) {\r\n throw new Error('Matrix is rank deficient');\r\n }\r\n\r\n var count = value.columns;\r\n var X = value.clone();\r\n var n = qr.columns;\r\n var i, j, k, s;\r\n\r\n for (k = 0; k < n; k++) {\r\n for (j = 0; j < count; j++) {\r\n s = 0;\r\n for (i = k; i < m; i++) {\r\n s += qr[i][k] * X[i][j];\r\n }\r\n s = -s / qr[k][k];\r\n for (i = k; i < m; i++) {\r\n X[i][j] += s * qr[i][k];\r\n }\r\n }\r\n }\r\n for (k = n - 1; k >= 0; k--) {\r\n for (j = 0; j < count; j++) {\r\n X[k][j] /= this.Rdiag[k];\r\n }\r\n for (i = 0; i < k; i++) {\r\n for (j = 0; j < count; j++) {\r\n X[i][j] -= X[k][j] * qr[i][k];\r\n }\r\n }\r\n }\r\n\r\n return X.subMatrix(0, n - 1, 0, count - 1);\r\n }\r\n\r\n /**\r\n *\r\n * @return {boolean}\r\n */\r\n isFullRank() {\r\n var columns = this.QR.columns;\r\n for (var i = 0; i < columns; i++) {\r\n if (this.Rdiag[i] === 0) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get upperTriangularMatrix() {\r\n var qr = this.QR;\r\n var n = qr.columns;\r\n var X = new Matrix(n, n);\r\n var i, j;\r\n for (i = 0; i < n; i++) {\r\n for (j = 0; j < n; j++) {\r\n if (i < j) {\r\n X[i][j] = qr[i][j];\r\n } else if (i === j) {\r\n X[i][j] = this.Rdiag[i];\r\n } else {\r\n X[i][j] = 0;\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get orthogonalMatrix() {\r\n var qr = this.QR;\r\n var rows = qr.rows;\r\n var columns = qr.columns;\r\n var X = new Matrix(rows, columns);\r\n var i, j, k, s;\r\n\r\n for (k = columns - 1; k >= 0; k--) {\r\n for (i = 0; i < rows; i++) {\r\n X[i][k] = 0;\r\n }\r\n X[k][k] = 1;\r\n for (j = k; j < columns; j++) {\r\n if (qr[k][k] !== 0) {\r\n s = 0;\r\n for (i = k; i < rows; i++) {\r\n s += qr[i][k] * X[i][j];\r\n }\r\n\r\n s = -s / qr[k][k];\r\n\r\n for (i = k; i < rows; i++) {\r\n X[i][j] += s * qr[i][k];\r\n }\r\n }\r\n }\r\n }\r\n return X;\r\n }\r\n}\r\n","import LuDecomposition from './dc/lu';\r\nimport QrDecomposition from './dc/qr';\r\nimport SingularValueDecomposition from './dc/svd';\r\n\r\nimport { Matrix, WrapperMatrix2D } from './index';\r\n\r\n/**\r\n * Computes the inverse of a Matrix\r\n * @param {Matrix} matrix\r\n * @param {boolean} [useSVD=false]\r\n * @return {Matrix}\r\n */\r\nexport function inverse(matrix, useSVD = false) {\r\n matrix = WrapperMatrix2D.checkMatrix(matrix);\r\n if (useSVD) {\r\n return new SingularValueDecomposition(matrix).inverse();\r\n } else {\r\n return solve(matrix, Matrix.eye(matrix.rows));\r\n }\r\n}\r\n\r\n/**\r\n *\r\n * @param {Matrix} leftHandSide\r\n * @param {Matrix} rightHandSide\r\n * @param {boolean} [useSVD = false]\r\n * @return {Matrix}\r\n */\r\nexport function solve(leftHandSide, rightHandSide, useSVD = false) {\r\n leftHandSide = WrapperMatrix2D.checkMatrix(leftHandSide);\r\n rightHandSide = WrapperMatrix2D.checkMatrix(rightHandSide);\r\n if (useSVD) {\r\n return new SingularValueDecomposition(leftHandSide).solve(rightHandSide);\r\n } else {\r\n return leftHandSide.isSquare()\r\n ? new LuDecomposition(leftHandSide).solve(rightHandSide)\r\n : new QrDecomposition(leftHandSide).solve(rightHandSide);\r\n }\r\n}\r\n","import max from 'ml-array-max';\r\n\r\nimport Matrix from './matrix';\r\nimport SingularValueDecomposition from './dc/svd';\r\n\r\n// function used by rowsDependencies\r\nfunction xrange(n, exception) {\r\n var range = [];\r\n for (var i = 0; i < n; i++) {\r\n if (i !== exception) {\r\n range.push(i);\r\n }\r\n }\r\n return range;\r\n}\r\n\r\n// function used by rowsDependencies\r\nfunction dependenciesOneRow(\r\n error,\r\n matrix,\r\n index,\r\n thresholdValue = 10e-10,\r\n thresholdError = 10e-10\r\n) {\r\n if (error > thresholdError) {\r\n return new Array(matrix.rows + 1).fill(0);\r\n } else {\r\n var returnArray = matrix.addRow(index, [0]);\r\n for (var i = 0; i < returnArray.rows; i++) {\r\n if (Math.abs(returnArray.get(i, 0)) < thresholdValue) {\r\n returnArray.set(i, 0, 0);\r\n }\r\n }\r\n return returnArray.to1DArray();\r\n }\r\n}\r\n\r\n/**\r\n * Creates a matrix which represents the dependencies between rows.\r\n * If a row is a linear combination of others rows, the result will be a row with the coefficients of this combination.\r\n * For example : for A = [[2, 0, 0, 1], [0, 1, 6, 0], [0, 3, 0, 1], [0, 0, 1, 0], [0, 1, 2, 0]], the result will be [[0, 0, 0, 0, 0], [0, 0, 0, 4, 1], [0, 0, 0, 0, 0], [0, 0.25, 0, 0, -0.25], [0, 1, 0, -4, 0]]\r\n * @param {Matrix} matrix\r\n * @param {Object} [options] includes thresholdValue and thresholdError.\r\n * @param {number} [options.thresholdValue = 10e-10] If an absolute value is inferior to this threshold, it will equals zero.\r\n * @param {number} [options.thresholdError = 10e-10] If the error is inferior to that threshold, the linear combination found is accepted and the row is dependent from other rows.\r\n * @return {Matrix} the matrix which represents the dependencies between rows.\r\n */\r\n\r\nexport function linearDependencies(matrix, options = {}) {\r\n const { thresholdValue = 10e-10, thresholdError = 10e-10 } = options;\r\n\r\n var n = matrix.rows;\r\n var results = new Matrix(n, n);\r\n\r\n for (var i = 0; i < n; i++) {\r\n var b = Matrix.columnVector(matrix.getRow(i));\r\n var Abis = matrix.subMatrixRow(xrange(n, i)).transposeView();\r\n var svd = new SingularValueDecomposition(Abis);\r\n var x = svd.solve(b);\r\n var error = max(\r\n Matrix.sub(b, Abis.mmul(x))\r\n .abs()\r\n .to1DArray()\r\n );\r\n results.setRow(\r\n i,\r\n dependenciesOneRow(error, x, i, thresholdValue, thresholdError)\r\n );\r\n }\r\n return results;\r\n}\r\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\nimport { hypotenuse, getFilled2DArray } from './util';\r\n\r\n/**\r\n * @class EigenvalueDecomposition\r\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs\r\n * @param {Matrix} matrix\r\n * @param {object} [options]\r\n * @param {boolean} [options.assumeSymmetric=false]\r\n */\r\nexport default class EigenvalueDecomposition {\r\n constructor(matrix, options = {}) {\r\n const { assumeSymmetric = false } = options;\r\n\r\n matrix = WrapperMatrix2D.checkMatrix(matrix);\r\n if (!matrix.isSquare()) {\r\n throw new Error('Matrix is not a square matrix');\r\n }\r\n\r\n var n = matrix.columns;\r\n var V = getFilled2DArray(n, n, 0);\r\n var d = new Array(n);\r\n var e = new Array(n);\r\n var value = matrix;\r\n var i, j;\r\n\r\n var isSymmetric = false;\r\n if (assumeSymmetric) {\r\n isSymmetric = true;\r\n } else {\r\n isSymmetric = matrix.isSymmetric();\r\n }\r\n\r\n if (isSymmetric) {\r\n for (i = 0; i < n; i++) {\r\n for (j = 0; j < n; j++) {\r\n V[i][j] = value.get(i, j);\r\n }\r\n }\r\n tred2(n, e, d, V);\r\n tql2(n, e, d, V);\r\n } else {\r\n var H = getFilled2DArray(n, n, 0);\r\n var ort = new Array(n);\r\n for (j = 0; j < n; j++) {\r\n for (i = 0; i < n; i++) {\r\n H[i][j] = value.get(i, j);\r\n }\r\n }\r\n orthes(n, H, ort, V);\r\n hqr2(n, e, d, V, H);\r\n }\r\n\r\n this.n = n;\r\n this.e = e;\r\n this.d = d;\r\n this.V = V;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Array}\r\n */\r\n get realEigenvalues() {\r\n return this.d;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Array}\r\n */\r\n get imaginaryEigenvalues() {\r\n return this.e;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get eigenvectorMatrix() {\r\n if (!Matrix.isMatrix(this.V)) {\r\n this.V = new Matrix(this.V);\r\n }\r\n return this.V;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get diagonalMatrix() {\r\n var n = this.n;\r\n var e = this.e;\r\n var d = this.d;\r\n var X = new Matrix(n, n);\r\n var i, j;\r\n for (i = 0; i < n; i++) {\r\n for (j = 0; j < n; j++) {\r\n X[i][j] = 0;\r\n }\r\n X[i][i] = d[i];\r\n if (e[i] > 0) {\r\n X[i][i + 1] = e[i];\r\n } else if (e[i] < 0) {\r\n X[i][i - 1] = e[i];\r\n }\r\n }\r\n return X;\r\n }\r\n}\r\n\r\nfunction tred2(n, e, d, V) {\r\n var f, g, h, i, j, k, hh, scale;\r\n\r\n for (j = 0; j < n; j++) {\r\n d[j] = V[n - 1][j];\r\n }\r\n\r\n for (i = n - 1; i > 0; i--) {\r\n scale = 0;\r\n h = 0;\r\n for (k = 0; k < i; k++) {\r\n scale = scale + Math.abs(d[k]);\r\n }\r\n\r\n if (scale === 0) {\r\n e[i] = d[i - 1];\r\n for (j = 0; j < i; j++) {\r\n d[j] = V[i - 1][j];\r\n V[i][j] = 0;\r\n V[j][i] = 0;\r\n }\r\n } else {\r\n for (k = 0; k < i; k++) {\r\n d[k] /= scale;\r\n h += d[k] * d[k];\r\n }\r\n\r\n f = d[i - 1];\r\n g = Math.sqrt(h);\r\n if (f > 0) {\r\n g = -g;\r\n }\r\n\r\n e[i] = scale * g;\r\n h = h - f * g;\r\n d[i - 1] = f - g;\r\n for (j = 0; j < i; j++) {\r\n e[j] = 0;\r\n }\r\n\r\n for (j = 0; j < i; j++) {\r\n f = d[j];\r\n V[j][i] = f;\r\n g = e[j] + V[j][j] * f;\r\n for (k = j + 1; k <= i - 1; k++) {\r\n g += V[k][j] * d[k];\r\n e[k] += V[k][j] * f;\r\n }\r\n e[j] = g;\r\n }\r\n\r\n f = 0;\r\n for (j = 0; j < i; j++) {\r\n e[j] /= h;\r\n f += e[j] * d[j];\r\n }\r\n\r\n hh = f / (h + h);\r\n for (j = 0; j < i; j++) {\r\n e[j] -= hh * d[j];\r\n }\r\n\r\n for (j = 0; j < i; j++) {\r\n f = d[j];\r\n g = e[j];\r\n for (k = j; k <= i - 1; k++) {\r\n V[k][j] -= f * e[k] + g * d[k];\r\n }\r\n d[j] = V[i - 1][j];\r\n V[i][j] = 0;\r\n }\r\n }\r\n d[i] = h;\r\n }\r\n\r\n for (i = 0; i < n - 1; i++) {\r\n V[n - 1][i] = V[i][i];\r\n V[i][i] = 1;\r\n h = d[i + 1];\r\n if (h !== 0) {\r\n for (k = 0; k <= i; k++) {\r\n d[k] = V[k][i + 1] / h;\r\n }\r\n\r\n for (j = 0; j <= i; j++) {\r\n g = 0;\r\n for (k = 0; k <= i; k++) {\r\n g += V[k][i + 1] * V[k][j];\r\n }\r\n for (k = 0; k <= i; k++) {\r\n V[k][j] -= g * d[k];\r\n }\r\n }\r\n }\r\n\r\n for (k = 0; k <= i; k++) {\r\n V[k][i + 1] = 0;\r\n }\r\n }\r\n\r\n for (j = 0; j < n; j++) {\r\n d[j] = V[n - 1][j];\r\n V[n - 1][j] = 0;\r\n }\r\n\r\n V[n - 1][n - 1] = 1;\r\n e[0] = 0;\r\n}\r\n\r\nfunction tql2(n, e, d, V) {\r\n var g, h, i, j, k, l, m, p, r, dl1, c, c2, c3, el1, s, s2, iter;\r\n\r\n for (i = 1; i < n; i++) {\r\n e[i - 1] = e[i];\r\n }\r\n\r\n e[n - 1] = 0;\r\n\r\n var f = 0;\r\n var tst1 = 0;\r\n var eps = Number.EPSILON;\r\n\r\n for (l = 0; l < n; l++) {\r\n tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));\r\n m = l;\r\n while (m < n) {\r\n if (Math.abs(e[m]) <= eps * tst1) {\r\n break;\r\n }\r\n m++;\r\n }\r\n\r\n if (m > l) {\r\n iter = 0;\r\n do {\r\n iter = iter + 1;\r\n\r\n g = d[l];\r\n p = (d[l + 1] - g) / (2 * e[l]);\r\n r = hypotenuse(p, 1);\r\n if (p < 0) {\r\n r = -r;\r\n }\r\n\r\n d[l] = e[l] / (p + r);\r\n d[l + 1] = e[l] * (p + r);\r\n dl1 = d[l + 1];\r\n h = g - d[l];\r\n for (i = l + 2; i < n; i++) {\r\n d[i] -= h;\r\n }\r\n\r\n f = f + h;\r\n\r\n p = d[m];\r\n c = 1;\r\n c2 = c;\r\n c3 = c;\r\n el1 = e[l + 1];\r\n s = 0;\r\n s2 = 0;\r\n for (i = m - 1; i >= l; i--) {\r\n c3 = c2;\r\n c2 = c;\r\n s2 = s;\r\n g = c * e[i];\r\n h = c * p;\r\n r = hypotenuse(p, e[i]);\r\n e[i + 1] = s * r;\r\n s = e[i] / r;\r\n c = p / r;\r\n p = c * d[i] - s * g;\r\n d[i + 1] = h + s * (c * g + s * d[i]);\r\n\r\n for (k = 0; k < n; k++) {\r\n h = V[k][i + 1];\r\n V[k][i + 1] = s * V[k][i] + c * h;\r\n V[k][i] = c * V[k][i] - s * h;\r\n }\r\n }\r\n\r\n p = -s * s2 * c3 * el1 * e[l] / dl1;\r\n e[l] = s * p;\r\n d[l] = c * p;\r\n } while (Math.abs(e[l]) > eps * tst1);\r\n }\r\n d[l] = d[l] + f;\r\n e[l] = 0;\r\n }\r\n\r\n for (i = 0; i < n - 1; i++) {\r\n k = i;\r\n p = d[i];\r\n for (j = i + 1; j < n; j++) {\r\n if (d[j] < p) {\r\n k = j;\r\n p = d[j];\r\n }\r\n }\r\n\r\n if (k !== i) {\r\n d[k] = d[i];\r\n d[i] = p;\r\n for (j = 0; j < n; j++) {\r\n p = V[j][i];\r\n V[j][i] = V[j][k];\r\n V[j][k] = p;\r\n }\r\n }\r\n }\r\n}\r\n\r\nfunction orthes(n, H, ort, V) {\r\n var low = 0;\r\n var high = n - 1;\r\n var f, g, h, i, j, m;\r\n var scale;\r\n\r\n for (m = low + 1; m <= high - 1; m++) {\r\n scale = 0;\r\n for (i = m; i <= high; i++) {\r\n scale = scale + Math.abs(H[i][m - 1]);\r\n }\r\n\r\n if (scale !== 0) {\r\n h = 0;\r\n for (i = high; i >= m; i--) {\r\n ort[i] = H[i][m - 1] / scale;\r\n h += ort[i] * ort[i];\r\n }\r\n\r\n g = Math.sqrt(h);\r\n if (ort[m] > 0) {\r\n g = -g;\r\n }\r\n\r\n h = h - ort[m] * g;\r\n ort[m] = ort[m] - g;\r\n\r\n for (j = m; j < n; j++) {\r\n f = 0;\r\n for (i = high; i >= m; i--) {\r\n f += ort[i] * H[i][j];\r\n }\r\n\r\n f = f / h;\r\n for (i = m; i <= high; i++) {\r\n H[i][j] -= f * ort[i];\r\n }\r\n }\r\n\r\n for (i = 0; i <= high; i++) {\r\n f = 0;\r\n for (j = high; j >= m; j--) {\r\n f += ort[j] * H[i][j];\r\n }\r\n\r\n f = f / h;\r\n for (j = m; j <= high; j++) {\r\n H[i][j] -= f * ort[j];\r\n }\r\n }\r\n\r\n ort[m] = scale * ort[m];\r\n H[m][m - 1] = scale * g;\r\n }\r\n }\r\n\r\n for (i = 0; i < n; i++) {\r\n for (j = 0; j < n; j++) {\r\n V[i][j] = i === j ? 1 : 0;\r\n }\r\n }\r\n\r\n for (m = high - 1; m >= low + 1; m--) {\r\n if (H[m][m - 1] !== 0) {\r\n for (i = m + 1; i <= high; i++) {\r\n ort[i] = H[i][m - 1];\r\n }\r\n\r\n for (j = m; j <= high; j++) {\r\n g = 0;\r\n for (i = m; i <= high; i++) {\r\n g += ort[i] * V[i][j];\r\n }\r\n\r\n g = g / ort[m] / H[m][m - 1];\r\n for (i = m; i <= high; i++) {\r\n V[i][j] += g * ort[i];\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nfunction hqr2(nn, e, d, V, H) {\r\n var n = nn - 1;\r\n var low = 0;\r\n var high = nn - 1;\r\n var eps = Number.EPSILON;\r\n var exshift = 0;\r\n var norm = 0;\r\n var p = 0;\r\n var q = 0;\r\n var r = 0;\r\n var s = 0;\r\n var z = 0;\r\n var iter = 0;\r\n var i, j, k, l, m, t, w, x, y;\r\n var ra, sa, vr, vi;\r\n var notlast, cdivres;\r\n\r\n for (i = 0; i < nn; i++) {\r\n if (i < low || i > high) {\r\n d[i] = H[i][i];\r\n e[i] = 0;\r\n }\r\n\r\n for (j = Math.max(i - 1, 0); j < nn; j++) {\r\n norm = norm + Math.abs(H[i][j]);\r\n }\r\n }\r\n\r\n while (n >= low) {\r\n l = n;\r\n while (l > low) {\r\n s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]);\r\n if (s === 0) {\r\n s = norm;\r\n }\r\n if (Math.abs(H[l][l - 1]) < eps * s) {\r\n break;\r\n }\r\n l--;\r\n }\r\n\r\n if (l === n) {\r\n H[n][n] = H[n][n] + exshift;\r\n d[n] = H[n][n];\r\n e[n] = 0;\r\n n--;\r\n iter = 0;\r\n } else if (l === n - 1) {\r\n w = H[n][n - 1] * H[n - 1][n];\r\n p = (H[n - 1][n - 1] - H[n][n]) / 2;\r\n q = p * p + w;\r\n z = Math.sqrt(Math.abs(q));\r\n H[n][n] = H[n][n] + exshift;\r\n H[n - 1][n - 1] = H[n - 1][n - 1] + exshift;\r\n x = H[n][n];\r\n\r\n if (q >= 0) {\r\n z = p >= 0 ? p + z : p - z;\r\n d[n - 1] = x + z;\r\n d[n] = d[n - 1];\r\n if (z !== 0) {\r\n d[n] = x - w / z;\r\n }\r\n e[n - 1] = 0;\r\n e[n] = 0;\r\n x = H[n][n - 1];\r\n s = Math.abs(x) + Math.abs(z);\r\n p = x / s;\r\n q = z / s;\r\n r = Math.sqrt(p * p + q * q);\r\n p = p / r;\r\n q = q / r;\r\n\r\n for (j = n - 1; j < nn; j++) {\r\n z = H[n - 1][j];\r\n H[n - 1][j] = q * z + p * H[n][j];\r\n H[n][j] = q * H[n][j] - p * z;\r\n }\r\n\r\n for (i = 0; i <= n; i++) {\r\n z = H[i][n - 1];\r\n H[i][n - 1] = q * z + p * H[i][n];\r\n H[i][n] = q * H[i][n] - p * z;\r\n }\r\n\r\n for (i = low; i <= high; i++) {\r\n z = V[i][n - 1];\r\n V[i][n - 1] = q * z + p * V[i][n];\r\n V[i][n] = q * V[i][n] - p * z;\r\n }\r\n } else {\r\n d[n - 1] = x + p;\r\n d[n] = x + p;\r\n e[n - 1] = z;\r\n e[n] = -z;\r\n }\r\n\r\n n = n - 2;\r\n iter = 0;\r\n } else {\r\n x = H[n][n];\r\n y = 0;\r\n w = 0;\r\n if (l < n) {\r\n y = H[n - 1][n - 1];\r\n w = H[n][n - 1] * H[n - 1][n];\r\n }\r\n\r\n if (iter === 10) {\r\n exshift += x;\r\n for (i = low; i <= n; i++) {\r\n H[i][i] -= x;\r\n }\r\n s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]);\r\n x = y = 0.75 * s;\r\n w = -0.4375 * s * s;\r\n }\r\n\r\n if (iter === 30) {\r\n s = (y - x) / 2;\r\n s = s * s + w;\r\n if (s > 0) {\r\n s = Math.sqrt(s);\r\n if (y < x) {\r\n s = -s;\r\n }\r\n s = x - w / ((y - x) / 2 + s);\r\n for (i = low; i <= n; i++) {\r\n H[i][i] -= s;\r\n }\r\n exshift += s;\r\n x = y = w = 0.964;\r\n }\r\n }\r\n\r\n iter = iter + 1;\r\n\r\n m = n - 2;\r\n while (m >= l) {\r\n z = H[m][m];\r\n r = x - z;\r\n s = y - z;\r\n p = (r * s - w) / H[m + 1][m] + H[m][m + 1];\r\n q = H[m + 1][m + 1] - z - r - s;\r\n r = H[m + 2][m + 1];\r\n s = Math.abs(p) + Math.abs(q) + Math.abs(r);\r\n p = p / s;\r\n q = q / s;\r\n r = r / s;\r\n if (m === l) {\r\n break;\r\n }\r\n if (\r\n Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) <\r\n eps *\r\n (Math.abs(p) *\r\n (Math.abs(H[m - 1][m - 1]) +\r\n Math.abs(z) +\r\n Math.abs(H[m + 1][m + 1])))\r\n ) {\r\n break;\r\n }\r\n m--;\r\n }\r\n\r\n for (i = m + 2; i <= n; i++) {\r\n H[i][i - 2] = 0;\r\n if (i > m + 2) {\r\n H[i][i - 3] = 0;\r\n }\r\n }\r\n\r\n for (k = m; k <= n - 1; k++) {\r\n notlast = k !== n - 1;\r\n if (k !== m) {\r\n p = H[k][k - 1];\r\n q = H[k + 1][k - 1];\r\n r = notlast ? H[k + 2][k - 1] : 0;\r\n x = Math.abs(p) + Math.abs(q) + Math.abs(r);\r\n if (x !== 0) {\r\n p = p / x;\r\n q = q / x;\r\n r = r / x;\r\n }\r\n }\r\n\r\n if (x === 0) {\r\n break;\r\n }\r\n\r\n s = Math.sqrt(p * p + q * q + r * r);\r\n if (p < 0) {\r\n s = -s;\r\n }\r\n\r\n if (s !== 0) {\r\n if (k !== m) {\r\n H[k][k - 1] = -s * x;\r\n } else if (l !== m) {\r\n H[k][k - 1] = -H[k][k - 1];\r\n }\r\n\r\n p = p + s;\r\n x = p / s;\r\n y = q / s;\r\n z = r / s;\r\n q = q / p;\r\n r = r / p;\r\n\r\n for (j = k; j < nn; j++) {\r\n p = H[k][j] + q * H[k + 1][j];\r\n if (notlast) {\r\n p = p + r * H[k + 2][j];\r\n H[k + 2][j] = H[k + 2][j] - p * z;\r\n }\r\n\r\n H[k][j] = H[k][j] - p * x;\r\n H[k + 1][j] = H[k + 1][j] - p * y;\r\n }\r\n\r\n for (i = 0; i <= Math.min(n, k + 3); i++) {\r\n p = x * H[i][k] + y * H[i][k + 1];\r\n if (notlast) {\r\n p = p + z * H[i][k + 2];\r\n H[i][k + 2] = H[i][k + 2] - p * r;\r\n }\r\n\r\n H[i][k] = H[i][k] - p;\r\n H[i][k + 1] = H[i][k + 1] - p * q;\r\n }\r\n\r\n for (i = low; i <= high; i++) {\r\n p = x * V[i][k] + y * V[i][k + 1];\r\n if (notlast) {\r\n p = p + z * V[i][k + 2];\r\n V[i][k + 2] = V[i][k + 2] - p * r;\r\n }\r\n\r\n V[i][k] = V[i][k] - p;\r\n V[i][k + 1] = V[i][k + 1] - p * q;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (norm === 0) {\r\n return;\r\n }\r\n\r\n for (n = nn - 1; n >= 0; n--) {\r\n p = d[n];\r\n q = e[n];\r\n\r\n if (q === 0) {\r\n l = n;\r\n H[n][n] = 1;\r\n for (i = n - 1; i >= 0; i--) {\r\n w = H[i][i] - p;\r\n r = 0;\r\n for (j = l; j <= n; j++) {\r\n r = r + H[i][j] * H[j][n];\r\n }\r\n\r\n if (e[i] < 0) {\r\n z = w;\r\n s = r;\r\n } else {\r\n l = i;\r\n if (e[i] === 0) {\r\n H[i][n] = w !== 0 ? -r / w : -r / (eps * norm);\r\n } else {\r\n x = H[i][i + 1];\r\n y = H[i + 1][i];\r\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\r\n t = (x * s - z * r) / q;\r\n H[i][n] = t;\r\n H[i + 1][n] =\r\n Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z;\r\n }\r\n\r\n t = Math.abs(H[i][n]);\r\n if (eps * t * t > 1) {\r\n for (j = i; j <= n; j++) {\r\n H[j][n] = H[j][n] / t;\r\n }\r\n }\r\n }\r\n }\r\n } else if (q < 0) {\r\n l = n - 1;\r\n\r\n if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) {\r\n H[n - 1][n - 1] = q / H[n][n - 1];\r\n H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1];\r\n } else {\r\n cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q);\r\n H[n - 1][n - 1] = cdivres[0];\r\n H[n - 1][n] = cdivres[1];\r\n }\r\n\r\n H[n][n - 1] = 0;\r\n H[n][n] = 1;\r\n for (i = n - 2; i >= 0; i--) {\r\n ra = 0;\r\n sa = 0;\r\n for (j = l; j <= n; j++) {\r\n ra = ra + H[i][j] * H[j][n - 1];\r\n sa = sa + H[i][j] * H[j][n];\r\n }\r\n\r\n w = H[i][i] - p;\r\n\r\n if (e[i] < 0) {\r\n z = w;\r\n r = ra;\r\n s = sa;\r\n } else {\r\n l = i;\r\n if (e[i] === 0) {\r\n cdivres = cdiv(-ra, -sa, w, q);\r\n H[i][n - 1] = cdivres[0];\r\n H[i][n] = cdivres[1];\r\n } else {\r\n x = H[i][i + 1];\r\n y = H[i + 1][i];\r\n vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;\r\n vi = (d[i] - p) * 2 * q;\r\n if (vr === 0 && vi === 0) {\r\n vr =\r\n eps *\r\n norm *\r\n (Math.abs(w) +\r\n Math.abs(q) +\r\n Math.abs(x) +\r\n Math.abs(y) +\r\n Math.abs(z));\r\n }\r\n cdivres = cdiv(\r\n x * r - z * ra + q * sa,\r\n x * s - z * sa - q * ra,\r\n vr,\r\n vi\r\n );\r\n H[i][n - 1] = cdivres[0];\r\n H[i][n] = cdivres[1];\r\n if (Math.abs(x) > Math.abs(z) + Math.abs(q)) {\r\n H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x;\r\n H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x;\r\n } else {\r\n cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q);\r\n H[i + 1][n - 1] = cdivres[0];\r\n H[i + 1][n] = cdivres[1];\r\n }\r\n }\r\n\r\n t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n]));\r\n if (eps * t * t > 1) {\r\n for (j = i; j <= n; j++) {\r\n H[j][n - 1] = H[j][n - 1] / t;\r\n H[j][n] = H[j][n] / t;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n for (i = 0; i < nn; i++) {\r\n if (i < low || i > high) {\r\n for (j = i; j < nn; j++) {\r\n V[i][j] = H[i][j];\r\n }\r\n }\r\n }\r\n\r\n for (j = nn - 1; j >= low; j--) {\r\n for (i = low; i <= high; i++) {\r\n z = 0;\r\n for (k = low; k <= Math.min(j, high); k++) {\r\n z = z + V[i][k] * H[k][j];\r\n }\r\n V[i][j] = z;\r\n }\r\n }\r\n}\r\n\r\nfunction cdiv(xr, xi, yr, yi) {\r\n var r, d;\r\n if (Math.abs(yr) > Math.abs(yi)) {\r\n r = yi / yr;\r\n d = yr + r * yi;\r\n return [(xr + r * xi) / d, (xi - r * xr) / d];\r\n } else {\r\n r = yr / yi;\r\n d = yi + r * yr;\r\n return [(r * xr + xi) / d, (r * xi - xr) / d];\r\n }\r\n}\r\n","import { Matrix, WrapperMatrix2D } from '../index';\r\n\r\n/**\r\n * @class CholeskyDecomposition\r\n * @link https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs\r\n * @param {Matrix} value\r\n */\r\nexport default class CholeskyDecomposition {\r\n constructor(value) {\r\n value = WrapperMatrix2D.checkMatrix(value);\r\n if (!value.isSymmetric()) {\r\n throw new Error('Matrix is not symmetric');\r\n }\r\n\r\n var a = value;\r\n var dimension = a.rows;\r\n var l = new Matrix(dimension, dimension);\r\n var positiveDefinite = true;\r\n var i, j, k;\r\n\r\n for (j = 0; j < dimension; j++) {\r\n var Lrowj = l[j];\r\n var d = 0;\r\n for (k = 0; k < j; k++) {\r\n var Lrowk = l[k];\r\n var s = 0;\r\n for (i = 0; i < k; i++) {\r\n s += Lrowk[i] * Lrowj[i];\r\n }\r\n Lrowj[k] = s = (a.get(j, k) - s) / l[k][k];\r\n d = d + s * s;\r\n }\r\n\r\n d = a.get(j, j) - d;\r\n\r\n positiveDefinite &= d > 0;\r\n l[j][j] = Math.sqrt(Math.max(d, 0));\r\n for (k = j + 1; k < dimension; k++) {\r\n l[j][k] = 0;\r\n }\r\n }\r\n\r\n if (!positiveDefinite) {\r\n throw new Error('Matrix is not positive definite');\r\n }\r\n\r\n this.L = l;\r\n }\r\n\r\n /**\r\n *\r\n * @param {Matrix} value\r\n * @return {Matrix}\r\n */\r\n solve(value) {\r\n value = WrapperMatrix2D.checkMatrix(value);\r\n\r\n var l = this.L;\r\n var dimension = l.rows;\r\n\r\n if (value.rows !== dimension) {\r\n throw new Error('Matrix dimensions do not match');\r\n }\r\n\r\n var count = value.columns;\r\n var B = value.clone();\r\n var i, j, k;\r\n\r\n for (k = 0; k < dimension; k++) {\r\n for (j = 0; j < count; j++) {\r\n for (i = 0; i < k; i++) {\r\n B[k][j] -= B[i][j] * l[k][i];\r\n }\r\n B[k][j] /= l[k][k];\r\n }\r\n }\r\n\r\n for (k = dimension - 1; k >= 0; k--) {\r\n for (j = 0; j < count; j++) {\r\n for (i = k + 1; i < dimension; i++) {\r\n B[k][j] -= B[i][j] * l[i][k];\r\n }\r\n B[k][j] /= l[k][k];\r\n }\r\n }\r\n\r\n return B;\r\n }\r\n\r\n /**\r\n *\r\n * @return {Matrix}\r\n */\r\n get lowerTriangularMatrix() {\r\n return this.L;\r\n }\r\n}\r\n","export { default, default as Matrix } from './matrix';\r\nexport { default as abstractMatrix } from './abstractMatrix';\r\n\r\nexport { wrap } from './wrap/wrap';\r\nexport { default as WrapperMatrix2D } from './wrap/WrapperMatrix2D';\r\nexport { default as WrapperMatrix1D } from './wrap/WrapperMatrix1D';\r\n\r\nexport { solve, inverse } from './decompositions';\r\nexport { linearDependencies } from './linearDependencies';\r\nexport {\r\n default as SingularValueDecomposition,\r\n default as SVD\r\n} from './dc/svd.js';\r\nexport {\r\n default as EigenvalueDecomposition,\r\n default as EVD\r\n} from './dc/evd.js';\r\nexport {\r\n default as CholeskyDecomposition,\r\n default as CHO\r\n} from './dc/cholesky.js';\r\nexport { default as LuDecomposition, default as LU } from './dc/lu.js';\r\nexport { default as QrDecomposition, default as QR } from './dc/qr.js';\r\n","'use strict';\n\nconst toString = Object.prototype.toString;\n\nfunction isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n\nmodule.exports = isAnyArray;\n","'use strict';\n\nfunction squaredEuclidean(p, q) {\n var d = 0;\n for (var i = 0; i < p.length; i++) {\n d += (p[i] - q[i]) * (p[i] - q[i]);\n }\n return d;\n}\n\nfunction euclidean(p, q) {\n return Math.sqrt(squaredEuclidean(p, q));\n}\n\nmodule.exports = euclidean;\neuclidean.squared = squaredEuclidean;\n","'use strict';\n\nexports.array = require('./array');\nexports.matrix = require('./matrix');\n","'use strict';\n\nvar arrayStat = require('./array');\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nexports.max = function max(matrix) {\n var max = -Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] > max) max = matrix[i][j];\n }\n }\n return max;\n};\n\nexports.min = function min(matrix) {\n var min = Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] < min) min = matrix[i][j];\n }\n }\n return min;\n};\n\nexports.minMax = function minMax(matrix) {\n var min = Infinity;\n var max = -Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] < min) min = matrix[i][j];\n if (matrix[i][j] > max) max = matrix[i][j];\n }\n }\n return {\n min:min,\n max:max\n };\n};\n\nexports.entropy = function entropy(matrix, eps) {\n if (typeof (eps) === 'undefined') {\n eps = 0;\n }\n var sum = 0,\n l1 = matrix.length,\n l2 = matrix[0].length;\n for (var i = 0; i < l1; i++) {\n for (var j = 0; j < l2; j++) {\n sum += matrix[i][j] * Math.log(matrix[i][j] + eps);\n }\n }\n return -sum;\n};\n\nexports.mean = function mean(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theMean, N, i, j;\n\n if (dimension === -1) {\n theMean = [0];\n N = rows * cols;\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theMean[0] += matrix[i][j];\n }\n }\n theMean[0] /= N;\n } else if (dimension === 0) {\n theMean = new Array(cols);\n N = rows;\n for (j = 0; j < cols; j++) {\n theMean[j] = 0;\n for (i = 0; i < rows; i++) {\n theMean[j] += matrix[i][j];\n }\n theMean[j] /= N;\n }\n } else if (dimension === 1) {\n theMean = new Array(rows);\n N = cols;\n for (j = 0; j < rows; j++) {\n theMean[j] = 0;\n for (i = 0; i < cols; i++) {\n theMean[j] += matrix[j][i];\n }\n theMean[j] /= N;\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theMean;\n};\n\nexports.sum = function sum(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theSum, i, j;\n\n if (dimension === -1) {\n theSum = [0];\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theSum[0] += matrix[i][j];\n }\n }\n } else if (dimension === 0) {\n theSum = new Array(cols);\n for (j = 0; j < cols; j++) {\n theSum[j] = 0;\n for (i = 0; i < rows; i++) {\n theSum[j] += matrix[i][j];\n }\n }\n } else if (dimension === 1) {\n theSum = new Array(rows);\n for (j = 0; j < rows; j++) {\n theSum[j] = 0;\n for (i = 0; i < cols; i++) {\n theSum[j] += matrix[j][i];\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theSum;\n};\n\nexports.product = function product(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theProduct, i, j;\n\n if (dimension === -1) {\n theProduct = [1];\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theProduct[0] *= matrix[i][j];\n }\n }\n } else if (dimension === 0) {\n theProduct = new Array(cols);\n for (j = 0; j < cols; j++) {\n theProduct[j] = 1;\n for (i = 0; i < rows; i++) {\n theProduct[j] *= matrix[i][j];\n }\n }\n } else if (dimension === 1) {\n theProduct = new Array(rows);\n for (j = 0; j < rows; j++) {\n theProduct[j] = 1;\n for (i = 0; i < cols; i++) {\n theProduct[j] *= matrix[j][i];\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theProduct;\n};\n\nexports.standardDeviation = function standardDeviation(matrix, means, unbiased) {\n var vari = exports.variance(matrix, means, unbiased), l = vari.length;\n for (var i = 0; i < l; i++) {\n vari[i] = Math.sqrt(vari[i]);\n }\n return vari;\n};\n\nexports.variance = function variance(matrix, means, unbiased) {\n if (typeof (unbiased) === 'undefined') {\n unbiased = true;\n }\n means = means || exports.mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum1 = 0, sum2 = 0, x = 0;\n for (var i = 0; i < rows; i++) {\n x = matrix[i][j] - means[j];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / (rows - 1);\n } else {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / rows;\n }\n }\n return vari;\n};\n\nexports.median = function median(matrix) {\n var rows = matrix.length, cols = matrix[0].length;\n var medians = new Array(cols);\n\n for (var i = 0; i < cols; i++) {\n var data = new Array(rows);\n for (var j = 0; j < rows; j++) {\n data[j] = matrix[j][i];\n }\n data.sort(compareNumbers);\n var N = data.length;\n if (N % 2 === 0) {\n medians[i] = (data[N / 2] + data[(N / 2) - 1]) * 0.5;\n } else {\n medians[i] = data[Math.floor(N / 2)];\n }\n }\n return medians;\n};\n\nexports.mode = function mode(matrix) {\n var rows = matrix.length,\n cols = matrix[0].length,\n modes = new Array(cols),\n i, j;\n for (i = 0; i < cols; i++) {\n var itemCount = new Array(rows);\n for (var k = 0; k < rows; k++) {\n itemCount[k] = 0;\n }\n var itemArray = new Array(rows);\n var count = 0;\n\n for (j = 0; j < rows; j++) {\n var index = itemArray.indexOf(matrix[j][i]);\n if (index >= 0) {\n itemCount[index]++;\n } else {\n itemArray[count] = matrix[j][i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (j = 0; j < count; j++) {\n if (itemCount[j] > maxValue) {\n maxValue = itemCount[j];\n maxIndex = j;\n }\n }\n\n modes[i] = itemArray[maxIndex];\n }\n return modes;\n};\n\nexports.skewness = function skewness(matrix, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var means = exports.mean(matrix);\n var n = matrix.length, l = means.length;\n var skew = new Array(l);\n\n for (var j = 0; j < l; j++) {\n var s2 = 0, s3 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n\n var m2 = s2 / n;\n var m3 = s3 / n;\n var g = m3 / Math.pow(m2, 3 / 2);\n\n if (unbiased) {\n var a = Math.sqrt(n * (n - 1));\n var b = n - 2;\n skew[j] = (a / b) * g;\n } else {\n skew[j] = g;\n }\n }\n return skew;\n};\n\nexports.kurtosis = function kurtosis(matrix, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var means = exports.mean(matrix);\n var n = matrix.length, m = matrix[0].length;\n var kurt = new Array(m);\n\n for (var j = 0; j < m; j++) {\n var s2 = 0, s4 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n kurt[j] = a * b - 3 * c;\n } else {\n kurt[j] = m4 / (m2 * m2) - 3;\n }\n }\n return kurt;\n};\n\nexports.standardError = function standardError(matrix) {\n var samples = matrix.length;\n var standardDeviations = exports.standardDeviation(matrix);\n var l = standardDeviations.length;\n var standardErrors = new Array(l);\n var sqrtN = Math.sqrt(samples);\n\n for (var i = 0; i < l; i++) {\n standardErrors[i] = standardDeviations[i] / sqrtN;\n }\n return standardErrors;\n};\n\nexports.covariance = function covariance(matrix, dimension) {\n return exports.scatter(matrix, undefined, dimension);\n};\n\nexports.scatter = function scatter(matrix, divisor, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n if (typeof (divisor) === 'undefined') {\n if (dimension === 0) {\n divisor = matrix.length - 1;\n } else if (dimension === 1) {\n divisor = matrix[0].length - 1;\n }\n }\n var means = exports.mean(matrix, dimension);\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, s, k;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n};\n\nexports.correlation = function correlation(matrix) {\n var means = exports.mean(matrix),\n standardDeviations = exports.standardDeviation(matrix, true, means),\n scores = exports.zScores(matrix, means, standardDeviations),\n rows = matrix.length,\n cols = matrix[0].length,\n i, j;\n\n var cor = new Array(cols);\n for (i = 0; i < cols; i++) {\n cor[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n var c = 0;\n for (var k = 0, l = scores.length; k < l; k++) {\n c += scores[k][j] * scores[k][i];\n }\n c /= rows - 1;\n cor[i][j] = c;\n cor[j][i] = c;\n }\n }\n return cor;\n};\n\nexports.zScores = function zScores(matrix, means, standardDeviations) {\n means = means || exports.mean(matrix);\n if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix, true, means);\n return exports.standardize(exports.center(matrix, means, false), standardDeviations, true);\n};\n\nexports.center = function center(matrix, means, inPlace) {\n means = means || exports.mean(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var row = result[i];\n for (j = 0, jj = row.length; j < jj; j++) {\n row[j] = matrix[i][j] - means[j];\n }\n }\n return result;\n};\n\nexports.standardize = function standardize(matrix, standardDeviations, inPlace) {\n if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var resultRow = result[i];\n var sourceRow = matrix[i];\n for (j = 0, jj = resultRow.length; j < jj; j++) {\n if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) {\n resultRow[j] = sourceRow[j] / standardDeviations[j];\n }\n }\n }\n return result;\n};\n\nexports.weightedVariance = function weightedVariance(matrix, weights) {\n var means = exports.mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum = 0;\n var a = 0, b = 0;\n\n for (var i = 0; i < rows; i++) {\n var z = matrix[i][j] - means[j];\n var w = weights[i];\n\n sum += w * (z * z);\n b += w;\n a += w * w;\n }\n\n vari[j] = sum * (b / (b * b - a));\n }\n\n return vari;\n};\n\nexports.weightedMean = function weightedMean(matrix, weights, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length,\n means, i, ii, j, w, row;\n\n if (dimension === 0) {\n means = new Array(cols);\n for (i = 0; i < cols; i++) {\n means[i] = 0;\n }\n for (i = 0; i < rows; i++) {\n row = matrix[i];\n w = weights[i];\n for (j = 0; j < cols; j++) {\n means[j] += row[j] * w;\n }\n }\n } else if (dimension === 1) {\n means = new Array(rows);\n for (i = 0; i < rows; i++) {\n means[i] = 0;\n }\n for (j = 0; j < rows; j++) {\n row = matrix[j];\n w = weights[j];\n for (i = 0; i < cols; i++) {\n means[j] += row[i] * w;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n var weightSum = arrayStat.sum(weights);\n if (weightSum !== 0) {\n for (i = 0, ii = means.length; i < ii; i++) {\n means[i] /= weightSum;\n }\n }\n return means;\n};\n\nexports.weightedCovariance = function weightedCovariance(matrix, weights, means, dimension) {\n dimension = dimension || 0;\n means = means || exports.weightedMean(matrix, weights, dimension);\n var s1 = 0, s2 = 0;\n for (var i = 0, ii = weights.length; i < ii; i++) {\n s1 += weights[i];\n s2 += weights[i] * weights[i];\n }\n var factor = s1 / (s1 * s1 - s2);\n return exports.weightedScatter(matrix, weights, means, factor, dimension);\n};\n\nexports.weightedScatter = function weightedScatter(matrix, weights, means, factor, dimension) {\n dimension = dimension || 0;\n means = means || exports.weightedMean(matrix, weights, dimension);\n if (typeof (factor) === 'undefined') {\n factor = 1;\n }\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, k, s;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n};\n","import isArray from 'is-any-array';\n\n/**\n * Computes the mean of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction mean(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var sum = 0;\n\n for (var i = 0; i < input.length; i++) {\n sum += input[i];\n }\n\n return sum / input.length;\n}\n\nexport default mean;\n","module.exports = function(haystack, needle, comparator, low, high) {\n var mid, cmp;\n\n if(low === undefined)\n low = 0;\n\n else {\n low = low|0;\n if(low < 0 || low >= haystack.length)\n throw new RangeError(\"invalid lower bound\");\n }\n\n if(high === undefined)\n high = haystack.length - 1;\n\n else {\n high = high|0;\n if(high < low || high >= haystack.length)\n throw new RangeError(\"invalid upper bound\");\n }\n\n while(low <= high) {\n /* Note that \"(low + high) >>> 1\" may overflow, and results in a typecast\n * to double (which gives the wrong results). */\n mid = low + (high - low >> 1);\n cmp = +comparator(haystack[mid], needle, mid, haystack);\n\n /* Too low. */\n if(cmp < 0.0)\n low = mid + 1;\n\n /* Too high. */\n else if(cmp > 0.0)\n high = mid - 1;\n\n /* Key found. */\n else\n return mid;\n }\n\n /* Key not found. */\n return ~low;\n}\n","'use strict';\nvar numberIsNan = require('number-is-nan');\n\nfunction assertNum(x) {\n\tif (typeof x !== 'number' || numberIsNan(x)) {\n\t\tthrow new TypeError('Expected a number');\n\t}\n}\n\nexports.asc = function (a, b) {\n\tassertNum(a);\n\tassertNum(b);\n\treturn a - b;\n};\n\nexports.desc = function (a, b) {\n\tassertNum(a);\n\tassertNum(b);\n\treturn b - a;\n};\n","import Matrix from 'ml-matrix';\nimport meanArray from 'ml-array-mean';\n\n/**\n * @private\n * return an array of probabilities of each class\n * @param {Array} array - contains the classes\n * @param {number} numberOfClasses\n * @return {Matrix} - rowVector of probabilities.\n */\nexport function toDiscreteDistribution(array, numberOfClasses) {\n var counts = new Array(numberOfClasses).fill(0);\n for (var i = 0; i < array.length; ++i) {\n counts[array[i]] += 1 / array.length;\n }\n\n return Matrix.rowVector(counts);\n}\n\n/**\n * @private\n * Retrieves the impurity of array of predictions\n * @param {Array} array - predictions.\n * @return {number} Gini impurity\n */\nexport function giniImpurity(array) {\n if (array.length === 0) {\n return 0;\n }\n\n var probabilities = toDiscreteDistribution(array, getNumberOfClasses(array))[0];\n\n var sum = 0.0;\n for (var i = 0; i < probabilities.length; ++i) {\n sum += probabilities[i] * probabilities[i];\n }\n\n return 1 - sum;\n}\n\n/**\n * @private\n * Return the number of classes given the array of predictions.\n * @param {Array} array - predictions.\n * @return {number} Number of classes.\n */\nexport function getNumberOfClasses(array) {\n return array.filter(function (val, i, arr) {\n return arr.indexOf(val) === i;\n }).length;\n}\n\n/**\n * @private\n * Calculates the Gini Gain of an array of predictions and those predictions splitted by a feature.\n * @para {Array} array - Predictions\n * @param {object} splitted - Object with elements \"greater\" and \"lesser\" that contains an array of predictions splitted.\n * @return {number} - Gini Gain.\n */\n\nexport function giniGain(array, splitted) {\n var splitsImpurity = 0.0;\n var splits = ['greater', 'lesser'];\n\n for (var i = 0; i < splits.length; ++i) {\n var currentSplit = splitted[splits[i]];\n splitsImpurity += giniImpurity(currentSplit) * currentSplit.length / array.length;\n }\n\n return giniImpurity(array) - splitsImpurity;\n}\n\n/**\n * @private\n * Calculates the squared error of a predictions values.\n * @param {Array} array - predictions values\n * @return {number} squared error.\n */\nexport function squaredError(array) {\n var l = array.length;\n\n var m = meanArray(array);\n var squaredError = 0.0;\n\n for (var i = 0; i < l; ++i) {\n var currentElement = array[i];\n squaredError += (currentElement - m) * (currentElement - m);\n }\n\n return squaredError;\n}\n\n/**\n * @private\n * Calculates the sum of squared error of the two arrays that contains the splitted values.\n * @param {Array} array - this argument is no necessary but is used to fit with the main interface.\n * @param {object} splitted - Object with elements \"greater\" and \"lesser\" that contains an array of predictions splitted.\n * @return {number} - sum of squared errors.\n */\nexport function regressionError(array, splitted) {\n var error = 0.0;\n var splits = ['greater', 'lesser'];\n\n for (var i = 0; i < splits.length; ++i) {\n var currentSplit = splitted[splits[i]];\n error += squaredError(currentSplit);\n }\n return error;\n}\n\n/**\n * @private\n * Split the training set and values from a given column of the training set if is less than a value\n * @param {Matrix} X - Training set.\n * @param {Array} y - Training values.\n * @param {number} column - Column to split.\n * @param {number} value - value to split the Training set and values.\n * @return {object} - Object that contains the splitted values.\n */\nexport function matrixSplitter(X, y, column, value) {\n var lesserX = [];\n var greaterX = [];\n var lesserY = [];\n var greaterY = [];\n\n for (var i = 0; i < X.rows; ++i) {\n if (X[i][column] < value) {\n lesserX.push(X[i]);\n lesserY.push(y[i]);\n } else {\n greaterX.push(X[i]);\n greaterY.push(y[i]);\n }\n }\n\n return {\n greaterX: greaterX,\n greaterY: greaterY,\n lesserX: lesserX,\n lesserY: lesserY\n };\n}\n\n/**\n * @private\n * Calculates the mean between two values\n * @param {number} a\n * @param {number} b\n * @return {number}\n */\nexport function mean(a, b) {\n return (a + b) / 2;\n}\n\n/**\n * @private\n * Returns a list of tuples that contains the i-th element of each array.\n * @param {Array} a\n * @param {Array} b\n * @return {Array} list of tuples.\n */\nexport function zip(a, b) {\n if (a.length !== b.length) {\n throw new TypeError('Error on zip: the size of a: ' + a.length + ' is different from b: ' + b.length);\n }\n\n var ret = new Array(a.length);\n for (var i = 0; i < a.length; ++i) {\n ret[i] = [a[i], b[i]];\n }\n\n return ret;\n}\n","import Matrix from 'ml-matrix';\nimport * as Utils from './utils';\nimport mean from 'ml-array-mean';\n\nconst gainFunctions = {\n gini: Utils.giniGain,\n regression: Utils.regressionError\n};\n\nconst splitFunctions = {\n mean: Utils.mean\n};\n\nexport default class TreeNode {\n\n /**\n * @private\n * Constructor for a tree node given the options received on the main classes (DecisionTreeClassifier, DecisionTreeRegression)\n * @param {object|TreeNode} options for loading\n * @constructor\n */\n constructor(options) {\n // options parameters\n this.kind = options.kind;\n this.gainFunction = options.gainFunction;\n this.splitFunction = options.splitFunction;\n this.minNumSamples = options.minNumSamples;\n this.maxDepth = options.maxDepth;\n }\n\n /**\n * @private\n * Function that retrieve the best feature to make the split.\n * @param {Matrix} XTranspose - Training set transposed\n * @param {Array} y - labels or values (depending of the decision tree)\n * @return {object} - return tree values, the best gain, column and the split value.\n */\n bestSplit(XTranspose, y) {\n\n // Depending in the node tree class, we set the variables to check information gain (to classify)\n // or error (for regression)\n\n var bestGain = this.kind === 'classifier' ? -Infinity : Infinity;\n var check = this.kind === 'classifier' ? (a, b) => a > b : (a, b) => a < b;\n\n\n var maxColumn;\n var maxValue;\n\n for (var i = 0; i < XTranspose.rows; ++i) {\n var currentFeature = XTranspose[i];\n var splitValues = this.featureSplit(currentFeature, y);\n for (var j = 0; j < splitValues.length; ++j) {\n var currentSplitVal = splitValues[j];\n var splitted = this.split(currentFeature, y, currentSplitVal);\n\n var gain = gainFunctions[this.gainFunction](y, splitted);\n if (check(gain, bestGain)) {\n maxColumn = i;\n maxValue = currentSplitVal;\n bestGain = gain;\n }\n }\n }\n\n return {\n maxGain: bestGain,\n maxColumn: maxColumn,\n maxValue: maxValue\n };\n }\n\n /**\n * @private\n * Makes the split of the training labels or values from the training set feature given a split value.\n * @param {Array} x - Training set feature\n * @param {Array} y - Training set value or label\n * @param {number} splitValue\n * @return {object}\n */\n\n split(x, y, splitValue) {\n var lesser = [];\n var greater = [];\n\n for (var i = 0; i < x.length; ++i) {\n if (x[i] < splitValue) {\n lesser.push(y[i]);\n } else {\n greater.push(y[i]);\n }\n }\n\n return {\n greater: greater,\n lesser: lesser\n };\n }\n\n /**\n * @private\n * Calculates the possible points to split over the tree given a training set feature and corresponding labels or values.\n * @param {Array} x - Training set feature\n * @param {Array} y - Training set value or label\n * @return {Array} possible split values.\n */\n featureSplit(x, y) {\n var splitValues = [];\n var arr = Utils.zip(x, y);\n arr.sort(function (a, b) {\n return a[0] - b[0];\n });\n\n for (var i = 1; i < arr.length; ++i) {\n if (arr[i - 1][1] !== arr[i][1]) {\n splitValues.push(splitFunctions[this.splitFunction](arr[i - 1][0], arr[i][0]));\n }\n }\n\n return splitValues;\n }\n\n /**\n * @private\n * Calculate the predictions of a leaf tree node given the training labels or values\n * @param {Array} y\n */\n calculatePrediction(y) {\n if (this.kind === 'classifier') {\n this.distribution = Utils.toDiscreteDistribution(y, Utils.getNumberOfClasses(y));\n if (this.distribution.columns === 0) {\n throw new TypeError('Error on calculate the prediction');\n }\n } else {\n this.distribution = mean(y);\n }\n }\n\n /**\n * @private\n * Train a node given the training set and labels, because it trains recursively, it also receive\n * the current depth of the node, parent gain to avoid infinite recursion and boolean value to check if\n * the training set is transposed.\n * @param {Matrix} X - Training set (could be transposed or not given transposed).\n * @param {Array} y - Training labels or values.\n * @param {number} currentDepth - Current depth of the node.\n * @param {number} parentGain - parent node gain or error.\n */\n train(X, y, currentDepth, parentGain) {\n if (X.rows <= this.minNumSamples) {\n this.calculatePrediction(y);\n return;\n }\n if (parentGain === undefined) parentGain = 0.0;\n\n var XTranspose = X.transpose();\n var split = this.bestSplit(XTranspose, y);\n\n this.splitValue = split.maxValue;\n this.splitColumn = split.maxColumn;\n this.gain = split.maxGain;\n\n var splittedMatrix = Utils.matrixSplitter(X, y, this.splitColumn, this.splitValue);\n\n if (currentDepth < this.maxDepth &&\n (this.gain > 0.01 && this.gain !== parentGain) &&\n (splittedMatrix.lesserX.length > 0 && splittedMatrix.greaterX.length > 0)) {\n this.left = new TreeNode(this);\n this.right = new TreeNode(this);\n\n var lesserX = new Matrix(splittedMatrix.lesserX);\n var greaterX = new Matrix(splittedMatrix.greaterX);\n\n this.left.train(lesserX, splittedMatrix.lesserY, currentDepth + 1, this.gain);\n this.right.train(greaterX, splittedMatrix.greaterY, currentDepth + 1, this.gain);\n } else {\n this.calculatePrediction(y);\n }\n }\n\n /**\n * @private\n * Calculates the prediction of a given element.\n * @param {Array} row\n * @return {number|Array} prediction\n * * if a node is a classifier returns an array of probabilities of each class.\n * * if a node is for regression returns a number with the prediction.\n */\n classify(row) {\n if (this.right && this.left) {\n if (row[this.splitColumn] < this.splitValue) {\n return this.left.classify(row);\n } else {\n return this.right.classify(row);\n }\n }\n\n return this.distribution;\n }\n\n /**\n * @private\n * Set the parameter of the current node and their children.\n * @param {object} node - parameters of the current node and the children.\n */\n setNodeParameters(node) {\n if (node.distribution !== undefined) {\n this.distribution = node.distribution.constructor === Array ? new Matrix(node.distribution) :\n node.distribution;\n } else {\n this.distribution = undefined;\n this.splitValue = node.splitValue;\n this.splitColumn = node.splitColumn;\n this.gain = node.gain;\n\n this.left = new TreeNode(this);\n this.right = new TreeNode(this);\n\n if (node.left !== {}) {\n this.left.setNodeParameters(node.left);\n }\n if (node.right !== {}) {\n this.right.setNodeParameters(node.right);\n }\n }\n }\n}\n","import Matrix from 'ml-matrix';\nimport Tree from './TreeNode';\n\nconst defaultOptions = {\n gainFunction: 'gini',\n splitFunction: 'mean',\n minNumSamples: 3,\n maxDepth: Infinity\n};\n\nexport class DecisionTreeClassifier {\n\n /**\n * Create new Decision Tree Classifier with CART implementation with the given options\n * @param {object} options\n * @param {string} [options.gainFunction=\"gini\"] - gain function to get the best split, \"gini\" the only one supported.\n * @param {string} [options.splitFunction=\"mean\"] - given two integers from a split feature, get the value to split, \"mean\" the only one supported.\n * @param {number} [options.minNumSamples=3] - minimum number of samples to create a leaf node to decide a class.\n * @param {number} [options.maxDepth=Infinity] - Max depth of the tree.\n * @param {object} model - for load purposes.\n * @constructor\n */\n constructor(options, model) {\n if (options === true) {\n this.options = model.options;\n this.root = new Tree(model.options);\n this.root.setNodeParameters(model.root);\n } else {\n this.options = Object.assign({}, defaultOptions, options);\n this.options.kind = 'classifier';\n }\n }\n\n /**\n * Train the decision tree with the given training set and labels.\n * @param {Matrix|MatrixTransposeView|Array} trainingSet\n * @param {Array} trainingLabels\n */\n train(trainingSet, trainingLabels) {\n this.root = new Tree(this.options);\n trainingSet = Matrix.checkMatrix(trainingSet);\n this.root.train(trainingSet, trainingLabels, 0, null);\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Matrix|MatrixTransposeView|Array} toPredict\n * @return {Array} predictions\n */\n predict(toPredict) {\n toPredict = Matrix.checkMatrix(toPredict);\n var predictions = new Array(toPredict.rows);\n\n for (var i = 0; i < toPredict.rows; ++i) {\n predictions[i] = this.root.classify(toPredict.getRow(i)).maxRowIndex(0)[1];\n }\n\n return predictions;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n options: this.options,\n root: this.root,\n name: 'DTClassifier'\n };\n }\n\n /**\n * Load a Decision tree classifier with the given model.\n * @param {object} model\n * @return {DecisionTreeClassifier}\n */\n static load(model) {\n if (model.name !== 'DTClassifier') {\n throw new RangeError('Invalid model: ' + model.name);\n }\n\n return new DecisionTreeClassifier(true, model);\n }\n}\n","import Matrix from 'ml-matrix';\nimport Tree from './TreeNode';\n\nconst defaultOptions = {\n gainFunction: 'regression',\n splitFunction: 'mean',\n minNumSamples: 3,\n maxDepth: Infinity\n};\n\nexport class DecisionTreeRegression {\n\n /**\n * Create new Decision Tree Regression with CART implementation with the given options.\n * @param {object} options\n * @param {string} [options.gainFunction=\"regression\"] - gain function to get the best split, \"regression\" the only one supported.\n * @param {string} [options.splitFunction=\"mean\"] - given two integers from a split feature, get the value to split, \"mean\" the only one supported.\n * @param {number} [options.minNumSamples=3] - minimum number of samples to create a leaf node to decide a class.\n * @param {number} [options.maxDepth=Infinity] - Max depth of the tree.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.options = model.options;\n this.root = new Tree(model.options);\n this.root.setNodeParameters(model.root);\n } else {\n this.options = Object.assign({}, defaultOptions, options);\n this.options.kind = 'regression';\n }\n }\n\n /**\n * Train the decision tree with the given training set and values.\n * @param {Matrix|MatrixTransposeView|Array} trainingSet\n * @param {Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n this.root = new Tree(this.options);\n\n if (trainingSet[0].length === undefined) trainingSet = Matrix.columnVector(trainingSet);\n trainingSet = Matrix.checkMatrix(trainingSet);\n this.root.train(trainingSet, trainingValues, 0);\n }\n\n /**\n * Predicts the values given the matrix to predict.\n * @param {Matrix|MatrixTransposeView|Array} toPredict\n * @return {Array} predictions\n */\n predict(toPredict) {\n if (toPredict[0] !== undefined && toPredict[0].length === undefined) toPredict = Matrix.columnVector(toPredict);\n toPredict = Matrix.checkMatrix(toPredict);\n\n var predictions = new Array(toPredict.rows);\n for (var i = 0; i < toPredict.rows; ++i) {\n predictions[i] = this.root.classify(toPredict.getRow(i));\n }\n\n return predictions;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n options: this.options,\n root: this.root,\n name: 'DTRegression'\n };\n }\n\n /**\n * Load a Decision tree regression with the given model.\n * @param {object} model\n * @return {DecisionTreeRegression}\n */\n static load(model) {\n if (model.name !== 'DTRegression') {\n throw new RangeError('Invalid model:' + model.name);\n }\n\n return new DecisionTreeRegression(true, model);\n }\n}\n","export {DecisionTreeClassifier} from './DecisionTreeClassifier';\nexport {DecisionTreeRegression} from './DecisionTreeRegression';\n","import isArray from 'is-any-array';\n\n/**\n * Computes the maximum of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction max(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var max = input[0];\n\n for (var i = 1; i < input.length; i++) {\n if (input[i] > max) max = input[i];\n }\n\n return max;\n}\n\nexport default max;\n","'use strict';\n\nconst Matrix = require('ml-matrix').Matrix;\n\nconst GaussianKernel = require('ml-kernel-gaussian');\nconst PolynomialKernel = require('ml-kernel-polynomial');\nconst ANOVAKernel = require('./kernels/anova-kernel');\nconst CauchyKernel = require('./kernels/cauchy-kernel');\nconst ExponentialKernel = require('./kernels/exponential-kernel');\nconst HistogramKernel = require('./kernels/histogram-intersection-kernel');\nconst LaplacianKernel = require('./kernels/laplacian-kernel');\nconst MultiquadraticKernel = require('./kernels/multiquadratic-kernel');\nconst RationalKernel = require('./kernels/rational-quadratic-kernel');\nconst SigmoidKernel = require('ml-kernel-sigmoid');\n\nconst kernelType = {\n gaussian: GaussianKernel,\n rbf: GaussianKernel,\n polynomial: PolynomialKernel,\n poly: PolynomialKernel,\n anova: ANOVAKernel,\n cauchy: CauchyKernel,\n exponential: ExponentialKernel,\n histogram: HistogramKernel,\n min: HistogramKernel,\n laplacian: LaplacianKernel,\n multiquadratic: MultiquadraticKernel,\n rational: RationalKernel,\n sigmoid: SigmoidKernel,\n mlp: SigmoidKernel\n};\n\nclass Kernel {\n constructor(type, options) {\n this.kernelType = type;\n if (type === 'linear') return;\n\n if (typeof type === 'string') {\n type = type.toLowerCase();\n\n var KernelConstructor = kernelType[type];\n if (KernelConstructor) {\n this.kernelFunction = new KernelConstructor(options);\n } else {\n throw new Error('unsupported kernel type: ' + type);\n }\n } else if (typeof type === 'object' && typeof type.compute === 'function') {\n this.kernelFunction = type;\n } else {\n throw new TypeError('first argument must be a valid kernel type or instance');\n }\n }\n\n compute(inputs, landmarks) {\n if (landmarks === undefined) {\n landmarks = inputs;\n }\n\n if (this.kernelType === 'linear') {\n var matrix = new Matrix(inputs);\n return matrix.mmul(new Matrix(landmarks).transposeView());\n }\n\n const kernelMatrix = new Matrix(inputs.length, landmarks.length);\n var i, j;\n if (inputs === landmarks) { // fast path, matrix is symmetric\n for (i = 0; i < inputs.length; i++) {\n for (j = i; j < inputs.length; j++) {\n kernelMatrix[i][j] = kernelMatrix[j][i] = this.kernelFunction.compute(inputs[i], inputs[j]);\n }\n }\n } else {\n for (i = 0; i < inputs.length; i++) {\n for (j = 0; j < landmarks.length; j++) {\n kernelMatrix[i][j] = this.kernelFunction.compute(inputs[i], landmarks[j]);\n }\n }\n }\n return kernelMatrix;\n }\n}\n\nmodule.exports = Kernel;\n","const PROB_TOLERANCE = 0.00000001;\nfunction randomChoice(values, options = {}, random = Math.random) {\n const { size = 1, replace = false, probabilities } = options;\n let valuesArr;\n let cumSum;\n if (typeof values === 'number') {\n valuesArr = getArray(values);\n }\n else {\n valuesArr = values.slice();\n }\n if (probabilities) {\n if (!replace) {\n throw new Error('choice with probabilities and no replacement is not implemented');\n }\n // check input is sane\n if (probabilities.length !== valuesArr.length) {\n throw new Error('the length of probabilities option should be equal to the number of choices');\n }\n cumSum = [probabilities[0]];\n for (let i = 1; i < probabilities.length; i++) {\n cumSum[i] = cumSum[i - 1] + probabilities[i];\n }\n if (Math.abs(1 - cumSum[cumSum.length - 1]) > PROB_TOLERANCE) {\n throw new Error(`probabilities should sum to 1, but instead sums to ${cumSum[cumSum.length - 1]}`);\n }\n }\n if (replace === false && size > valuesArr.length) {\n throw new Error('size option is too large');\n }\n const result = [];\n for (let i = 0; i < size; i++) {\n const index = randomIndex(valuesArr.length, random, cumSum);\n result.push(valuesArr[index]);\n if (!replace) {\n valuesArr.splice(index, 1);\n }\n }\n return result;\n}\nfunction getArray(n) {\n const arr = [];\n for (let i = 0; i < n; i++) {\n arr.push(i);\n }\n return arr;\n}\nfunction randomIndex(n, random, cumSum) {\n const rand = random();\n if (!cumSum) {\n return Math.floor(rand * n);\n }\n else {\n let idx = 0;\n while (rand > cumSum[idx]) {\n idx++;\n }\n return idx;\n }\n}\nexport default randomChoice;\n","// tslint:disable-next-line\nimport XSAdd from 'ml-xsadd';\nimport choice from './choice';\n/**\n * @classdesc Random class\n */\nexport default class Random {\n /**\n * @param [seedOrRandom=Math.random] - Control the random number generator used by the Random class instance. Pass a random number generator function with a uniform distribution over the half-open interval [0, 1[. If seed will pass it to ml-xsadd to create a seeded random number generator. If undefined will use Math.random.\n */\n constructor(seedOrRandom = Math.random) {\n if (typeof seedOrRandom === 'number') {\n const xsadd = new XSAdd(seedOrRandom);\n this.randomGenerator = xsadd.random;\n }\n else {\n this.randomGenerator = seedOrRandom;\n }\n }\n choice(values, options) {\n if (typeof values === 'number') {\n return choice(values, options, this.randomGenerator);\n }\n return choice(values, options, this.randomGenerator);\n }\n /**\n * Draw a random number from a uniform distribution on [0,1)\n * @return The random number\n */\n random() {\n return this.randomGenerator();\n }\n /**\n * Draw a random integer from a uniform distribution on [low, high). If only low is specified, the number is drawn on [0, low)\n * @param low - The lower bound of the uniform distribution interval.\n * @param high - The higher bound of the uniform distribution interval.\n */\n randInt(low, high) {\n if (high === undefined) {\n high = low;\n low = 0;\n }\n return low + Math.floor(this.randomGenerator() * (high - low));\n }\n /**\n * Draw several random number from a uniform distribution on [0, 1)\n * @param size - The number of number to draw\n * @return - The list of drawn numbers.\n */\n randomSample(size) {\n const result = [];\n for (let i = 0; i < size; i++) {\n result.push(this.random());\n }\n return result;\n }\n}\n","/*jshint eqnull:true*/\n(function (root) {\n \"use strict\";\n\n var GLOBAL_KEY = \"Random\";\n\n var imul = (typeof Math.imul !== \"function\" || Math.imul(0xffffffff, 5) !== -5 ?\n function (a, b) {\n var ah = (a >>> 16) & 0xffff;\n var al = a & 0xffff;\n var bh = (b >>> 16) & 0xffff;\n var bl = b & 0xffff;\n // the shift by 0 fixes the sign on the high part\n // the final |0 converts the unsigned value into a signed value\n return (al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0;\n } :\n Math.imul);\n\n var stringRepeat = (typeof String.prototype.repeat === \"function\" && \"x\".repeat(3) === \"xxx\" ?\n function (x, y) {\n return x.repeat(y);\n } : function (pattern, count) {\n var result = \"\";\n while (count > 0) {\n if (count & 1) {\n result += pattern;\n }\n count >>= 1;\n pattern += pattern;\n }\n return result;\n });\n\n function Random(engine) {\n if (!(this instanceof Random)) {\n return new Random(engine);\n }\n\n if (engine == null) {\n engine = Random.engines.nativeMath;\n } else if (typeof engine !== \"function\") {\n throw new TypeError(\"Expected engine to be a function, got \" + typeof engine);\n }\n this.engine = engine;\n }\n var proto = Random.prototype;\n\n Random.engines = {\n nativeMath: function () {\n return (Math.random() * 0x100000000) | 0;\n },\n mt19937: (function (Int32Array) {\n // http://en.wikipedia.org/wiki/Mersenne_twister\n function refreshData(data) {\n var k = 0;\n var tmp = 0;\n for (;\n (k | 0) < 227; k = (k + 1) | 0) {\n tmp = (data[k] & 0x80000000) | (data[(k + 1) | 0] & 0x7fffffff);\n data[k] = data[(k + 397) | 0] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);\n }\n\n for (;\n (k | 0) < 623; k = (k + 1) | 0) {\n tmp = (data[k] & 0x80000000) | (data[(k + 1) | 0] & 0x7fffffff);\n data[k] = data[(k - 227) | 0] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);\n }\n\n tmp = (data[623] & 0x80000000) | (data[0] & 0x7fffffff);\n data[623] = data[396] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);\n }\n\n function temper(value) {\n value ^= value >>> 11;\n value ^= (value << 7) & 0x9d2c5680;\n value ^= (value << 15) & 0xefc60000;\n return value ^ (value >>> 18);\n }\n\n function seedWithArray(data, source) {\n var i = 1;\n var j = 0;\n var sourceLength = source.length;\n var k = Math.max(sourceLength, 624) | 0;\n var previous = data[0] | 0;\n for (;\n (k | 0) > 0; --k) {\n data[i] = previous = ((data[i] ^ imul((previous ^ (previous >>> 30)), 0x0019660d)) + (source[j] | 0) + (j | 0)) | 0;\n i = (i + 1) | 0;\n ++j;\n if ((i | 0) > 623) {\n data[0] = data[623];\n i = 1;\n }\n if (j >= sourceLength) {\n j = 0;\n }\n }\n for (k = 623;\n (k | 0) > 0; --k) {\n data[i] = previous = ((data[i] ^ imul((previous ^ (previous >>> 30)), 0x5d588b65)) - i) | 0;\n i = (i + 1) | 0;\n if ((i | 0) > 623) {\n data[0] = data[623];\n i = 1;\n }\n }\n data[0] = 0x80000000;\n }\n\n function mt19937() {\n var data = new Int32Array(624);\n var index = 0;\n var uses = 0;\n\n function next() {\n if ((index | 0) >= 624) {\n refreshData(data);\n index = 0;\n }\n\n var value = data[index];\n index = (index + 1) | 0;\n uses += 1;\n return temper(value) | 0;\n }\n next.getUseCount = function() {\n return uses;\n };\n next.discard = function (count) {\n uses += count;\n if ((index | 0) >= 624) {\n refreshData(data);\n index = 0;\n }\n while ((count - index) > 624) {\n count -= 624 - index;\n refreshData(data);\n index = 0;\n }\n index = (index + count) | 0;\n return next;\n };\n next.seed = function (initial) {\n var previous = 0;\n data[0] = previous = initial | 0;\n\n for (var i = 1; i < 624; i = (i + 1) | 0) {\n data[i] = previous = (imul((previous ^ (previous >>> 30)), 0x6c078965) + i) | 0;\n }\n index = 624;\n uses = 0;\n return next;\n };\n next.seedWithArray = function (source) {\n next.seed(0x012bd6aa);\n seedWithArray(data, source);\n return next;\n };\n next.autoSeed = function () {\n return next.seedWithArray(Random.generateEntropyArray());\n };\n return next;\n }\n\n return mt19937;\n }(typeof Int32Array === \"function\" ? Int32Array : Array)),\n browserCrypto: (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\" && typeof Int32Array === \"function\") ? (function () {\n var data = null;\n var index = 128;\n\n return function () {\n if (index >= 128) {\n if (data === null) {\n data = new Int32Array(128);\n }\n crypto.getRandomValues(data);\n index = 0;\n }\n\n return data[index++] | 0;\n };\n }()) : null\n };\n\n Random.generateEntropyArray = function () {\n var array = [];\n var engine = Random.engines.nativeMath;\n for (var i = 0; i < 16; ++i) {\n array[i] = engine() | 0;\n }\n array.push(new Date().getTime() | 0);\n return array;\n };\n\n function returnValue(value) {\n return function () {\n return value;\n };\n }\n\n // [-0x80000000, 0x7fffffff]\n Random.int32 = function (engine) {\n return engine() | 0;\n };\n proto.int32 = function () {\n return Random.int32(this.engine);\n };\n\n // [0, 0xffffffff]\n Random.uint32 = function (engine) {\n return engine() >>> 0;\n };\n proto.uint32 = function () {\n return Random.uint32(this.engine);\n };\n\n // [0, 0x1fffffffffffff]\n Random.uint53 = function (engine) {\n var high = engine() & 0x1fffff;\n var low = engine() >>> 0;\n return (high * 0x100000000) + low;\n };\n proto.uint53 = function () {\n return Random.uint53(this.engine);\n };\n\n // [0, 0x20000000000000]\n Random.uint53Full = function (engine) {\n while (true) {\n var high = engine() | 0;\n if (high & 0x200000) {\n if ((high & 0x3fffff) === 0x200000 && (engine() | 0) === 0) {\n return 0x20000000000000;\n }\n } else {\n var low = engine() >>> 0;\n return ((high & 0x1fffff) * 0x100000000) + low;\n }\n }\n };\n proto.uint53Full = function () {\n return Random.uint53Full(this.engine);\n };\n\n // [-0x20000000000000, 0x1fffffffffffff]\n Random.int53 = function (engine) {\n var high = engine() | 0;\n var low = engine() >>> 0;\n return ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);\n };\n proto.int53 = function () {\n return Random.int53(this.engine);\n };\n\n // [-0x20000000000000, 0x20000000000000]\n Random.int53Full = function (engine) {\n while (true) {\n var high = engine() | 0;\n if (high & 0x400000) {\n if ((high & 0x7fffff) === 0x400000 && (engine() | 0) === 0) {\n return 0x20000000000000;\n }\n } else {\n var low = engine() >>> 0;\n return ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);\n }\n }\n };\n proto.int53Full = function () {\n return Random.int53Full(this.engine);\n };\n\n function add(generate, addend) {\n if (addend === 0) {\n return generate;\n } else {\n return function (engine) {\n return generate(engine) + addend;\n };\n }\n }\n\n Random.integer = (function () {\n function isPowerOfTwoMinusOne(value) {\n return ((value + 1) & value) === 0;\n }\n\n function bitmask(masking) {\n return function (engine) {\n return engine() & masking;\n };\n }\n\n function downscaleToLoopCheckedRange(range) {\n var extendedRange = range + 1;\n var maximum = extendedRange * Math.floor(0x100000000 / extendedRange);\n return function (engine) {\n var value = 0;\n do {\n value = engine() >>> 0;\n } while (value >= maximum);\n return value % extendedRange;\n };\n }\n\n function downscaleToRange(range) {\n if (isPowerOfTwoMinusOne(range)) {\n return bitmask(range);\n } else {\n return downscaleToLoopCheckedRange(range);\n }\n }\n\n function isEvenlyDivisibleByMaxInt32(value) {\n return (value | 0) === 0;\n }\n\n function upscaleWithHighMasking(masking) {\n return function (engine) {\n var high = engine() & masking;\n var low = engine() >>> 0;\n return (high * 0x100000000) + low;\n };\n }\n\n function upscaleToLoopCheckedRange(extendedRange) {\n var maximum = extendedRange * Math.floor(0x20000000000000 / extendedRange);\n return function (engine) {\n var ret = 0;\n do {\n var high = engine() & 0x1fffff;\n var low = engine() >>> 0;\n ret = (high * 0x100000000) + low;\n } while (ret >= maximum);\n return ret % extendedRange;\n };\n }\n\n function upscaleWithinU53(range) {\n var extendedRange = range + 1;\n if (isEvenlyDivisibleByMaxInt32(extendedRange)) {\n var highRange = ((extendedRange / 0x100000000) | 0) - 1;\n if (isPowerOfTwoMinusOne(highRange)) {\n return upscaleWithHighMasking(highRange);\n }\n }\n return upscaleToLoopCheckedRange(extendedRange);\n }\n\n function upscaleWithinI53AndLoopCheck(min, max) {\n return function (engine) {\n var ret = 0;\n do {\n var high = engine() | 0;\n var low = engine() >>> 0;\n ret = ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);\n } while (ret < min || ret > max);\n return ret;\n };\n }\n\n return function (min, max) {\n min = Math.floor(min);\n max = Math.floor(max);\n if (min < -0x20000000000000 || !isFinite(min)) {\n throw new RangeError(\"Expected min to be at least \" + (-0x20000000000000));\n } else if (max > 0x20000000000000 || !isFinite(max)) {\n throw new RangeError(\"Expected max to be at most \" + 0x20000000000000);\n }\n\n var range = max - min;\n if (range <= 0 || !isFinite(range)) {\n return returnValue(min);\n } else if (range === 0xffffffff) {\n if (min === 0) {\n return Random.uint32;\n } else {\n return add(Random.int32, min + 0x80000000);\n }\n } else if (range < 0xffffffff) {\n return add(downscaleToRange(range), min);\n } else if (range === 0x1fffffffffffff) {\n return add(Random.uint53, min);\n } else if (range < 0x1fffffffffffff) {\n return add(upscaleWithinU53(range), min);\n } else if (max - 1 - min === 0x1fffffffffffff) {\n return add(Random.uint53Full, min);\n } else if (min === -0x20000000000000 && max === 0x20000000000000) {\n return Random.int53Full;\n } else if (min === -0x20000000000000 && max === 0x1fffffffffffff) {\n return Random.int53;\n } else if (min === -0x1fffffffffffff && max === 0x20000000000000) {\n return add(Random.int53, 1);\n } else if (max === 0x20000000000000) {\n return add(upscaleWithinI53AndLoopCheck(min - 1, max - 1), 1);\n } else {\n return upscaleWithinI53AndLoopCheck(min, max);\n }\n };\n }());\n proto.integer = function (min, max) {\n return Random.integer(min, max)(this.engine);\n };\n\n // [0, 1] (floating point)\n Random.realZeroToOneInclusive = function (engine) {\n return Random.uint53Full(engine) / 0x20000000000000;\n };\n proto.realZeroToOneInclusive = function () {\n return Random.realZeroToOneInclusive(this.engine);\n };\n\n // [0, 1) (floating point)\n Random.realZeroToOneExclusive = function (engine) {\n return Random.uint53(engine) / 0x20000000000000;\n };\n proto.realZeroToOneExclusive = function () {\n return Random.realZeroToOneExclusive(this.engine);\n };\n\n Random.real = (function () {\n function multiply(generate, multiplier) {\n if (multiplier === 1) {\n return generate;\n } else if (multiplier === 0) {\n return function () {\n return 0;\n };\n } else {\n return function (engine) {\n return generate(engine) * multiplier;\n };\n }\n }\n\n return function (left, right, inclusive) {\n if (!isFinite(left)) {\n throw new RangeError(\"Expected left to be a finite number\");\n } else if (!isFinite(right)) {\n throw new RangeError(\"Expected right to be a finite number\");\n }\n return add(\n multiply(\n inclusive ? Random.realZeroToOneInclusive : Random.realZeroToOneExclusive,\n right - left),\n left);\n };\n }());\n proto.real = function (min, max, inclusive) {\n return Random.real(min, max, inclusive)(this.engine);\n };\n\n Random.bool = (function () {\n function isLeastBitTrue(engine) {\n return (engine() & 1) === 1;\n }\n\n function lessThan(generate, value) {\n return function (engine) {\n return generate(engine) < value;\n };\n }\n\n function probability(percentage) {\n if (percentage <= 0) {\n return returnValue(false);\n } else if (percentage >= 1) {\n return returnValue(true);\n } else {\n var scaled = percentage * 0x100000000;\n if (scaled % 1 === 0) {\n return lessThan(Random.int32, (scaled - 0x80000000) | 0);\n } else {\n return lessThan(Random.uint53, Math.round(percentage * 0x20000000000000));\n }\n }\n }\n\n return function (numerator, denominator) {\n if (denominator == null) {\n if (numerator == null) {\n return isLeastBitTrue;\n }\n return probability(numerator);\n } else {\n if (numerator <= 0) {\n return returnValue(false);\n } else if (numerator >= denominator) {\n return returnValue(true);\n }\n return lessThan(Random.integer(0, denominator - 1), numerator);\n }\n };\n }());\n proto.bool = function (numerator, denominator) {\n return Random.bool(numerator, denominator)(this.engine);\n };\n\n function toInteger(value) {\n var number = +value;\n if (number < 0) {\n return Math.ceil(number);\n } else {\n return Math.floor(number);\n }\n }\n\n function convertSliceArgument(value, length) {\n if (value < 0) {\n return Math.max(value + length, 0);\n } else {\n return Math.min(value, length);\n }\n }\n Random.pick = function (engine, array, begin, end) {\n var length = array.length;\n var start = begin == null ? 0 : convertSliceArgument(toInteger(begin), length);\n var finish = end === void 0 ? length : convertSliceArgument(toInteger(end), length);\n if (start >= finish) {\n return void 0;\n }\n var distribution = Random.integer(start, finish - 1);\n return array[distribution(engine)];\n };\n proto.pick = function (array, begin, end) {\n return Random.pick(this.engine, array, begin, end);\n };\n\n function returnUndefined() {\n return void 0;\n }\n var slice = Array.prototype.slice;\n Random.picker = function (array, begin, end) {\n var clone = slice.call(array, begin, end);\n if (!clone.length) {\n return returnUndefined;\n }\n var distribution = Random.integer(0, clone.length - 1);\n return function (engine) {\n return clone[distribution(engine)];\n };\n };\n\n Random.shuffle = function (engine, array, downTo) {\n var length = array.length;\n if (length) {\n if (downTo == null) {\n downTo = 0;\n }\n for (var i = (length - 1) >>> 0; i > downTo; --i) {\n var distribution = Random.integer(0, i);\n var j = distribution(engine);\n if (i !== j) {\n var tmp = array[i];\n array[i] = array[j];\n array[j] = tmp;\n }\n }\n }\n return array;\n };\n proto.shuffle = function (array) {\n return Random.shuffle(this.engine, array);\n };\n\n Random.sample = function (engine, population, sampleSize) {\n if (sampleSize < 0 || sampleSize > population.length || !isFinite(sampleSize)) {\n throw new RangeError(\"Expected sampleSize to be within 0 and the length of the population\");\n }\n\n if (sampleSize === 0) {\n return [];\n }\n\n var clone = slice.call(population);\n var length = clone.length;\n if (length === sampleSize) {\n return Random.shuffle(engine, clone, 0);\n }\n var tailLength = length - sampleSize;\n return Random.shuffle(engine, clone, tailLength - 1).slice(tailLength);\n };\n proto.sample = function (population, sampleSize) {\n return Random.sample(this.engine, population, sampleSize);\n };\n\n Random.die = function (sideCount) {\n return Random.integer(1, sideCount);\n };\n proto.die = function (sideCount) {\n return Random.die(sideCount)(this.engine);\n };\n\n Random.dice = function (sideCount, dieCount) {\n var distribution = Random.die(sideCount);\n return function (engine) {\n var result = [];\n result.length = dieCount;\n for (var i = 0; i < dieCount; ++i) {\n result[i] = distribution(engine);\n }\n return result;\n };\n };\n proto.dice = function (sideCount, dieCount) {\n return Random.dice(sideCount, dieCount)(this.engine);\n };\n\n // http://en.wikipedia.org/wiki/Universally_unique_identifier\n Random.uuid4 = (function () {\n function zeroPad(string, zeroCount) {\n return stringRepeat(\"0\", zeroCount - string.length) + string;\n }\n\n return function (engine) {\n var a = engine() >>> 0;\n var b = engine() | 0;\n var c = engine() | 0;\n var d = engine() >>> 0;\n\n return (\n zeroPad(a.toString(16), 8) +\n \"-\" +\n zeroPad((b & 0xffff).toString(16), 4) +\n \"-\" +\n zeroPad((((b >> 4) & 0x0fff) | 0x4000).toString(16), 4) +\n \"-\" +\n zeroPad(((c & 0x3fff) | 0x8000).toString(16), 4) +\n \"-\" +\n zeroPad(((c >> 4) & 0xffff).toString(16), 4) +\n zeroPad(d.toString(16), 8));\n };\n }());\n proto.uuid4 = function () {\n return Random.uuid4(this.engine);\n };\n\n Random.string = (function () {\n // has 2**x chars, for faster uniform distribution\n var DEFAULT_STRING_POOL = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-\";\n\n return function (pool) {\n if (pool == null) {\n pool = DEFAULT_STRING_POOL;\n }\n\n var length = pool.length;\n if (!length) {\n throw new Error(\"Expected pool not to be an empty string\");\n }\n\n var distribution = Random.integer(0, length - 1);\n return function (engine, length) {\n var result = \"\";\n for (var i = 0; i < length; ++i) {\n var j = distribution(engine);\n result += pool.charAt(j);\n }\n return result;\n };\n };\n }());\n proto.string = function (length, pool) {\n return Random.string(pool)(this.engine, length);\n };\n\n Random.hex = (function () {\n var LOWER_HEX_POOL = \"0123456789abcdef\";\n var lowerHex = Random.string(LOWER_HEX_POOL);\n var upperHex = Random.string(LOWER_HEX_POOL.toUpperCase());\n\n return function (upper) {\n if (upper) {\n return upperHex;\n } else {\n return lowerHex;\n }\n };\n }());\n proto.hex = function (length, upper) {\n return Random.hex(upper)(this.engine, length);\n };\n\n Random.date = function (start, end) {\n if (!(start instanceof Date)) {\n throw new TypeError(\"Expected start to be a Date, got \" + typeof start);\n } else if (!(end instanceof Date)) {\n throw new TypeError(\"Expected end to be a Date, got \" + typeof end);\n }\n var distribution = Random.integer(start.getTime(), end.getTime());\n return function (engine) {\n return new Date(distribution(engine));\n };\n };\n proto.date = function (start, end) {\n return Random.date(start, end)(this.engine);\n };\n\n if (typeof define === \"function\" && define.amd) {\n define(function () {\n return Random;\n });\n } else if (typeof module !== \"undefined\" && typeof require === \"function\") {\n module.exports = Random;\n } else {\n (function () {\n var oldGlobal = root[GLOBAL_KEY];\n Random.noConflict = function () {\n root[GLOBAL_KEY] = oldGlobal;\n return this;\n };\n }());\n root[GLOBAL_KEY] = Random;\n }\n}(this));","import max from 'ml-array-max';\nimport min from 'ml-array-min';\nimport isArray from 'is-any-array';\n\nfunction rescale(input) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n } else if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var output;\n\n if (options.output !== undefined) {\n if (!isArray(options.output)) {\n throw new TypeError('output option must be an array if specified');\n }\n\n output = options.output;\n } else {\n output = new Array(input.length);\n }\n\n var currentMin = min(input);\n var currentMax = max(input);\n\n if (currentMin === currentMax) {\n throw new RangeError('minimum and maximum input values are equal. Cannot rescale a constant array');\n }\n\n var _options$min = options.min,\n minValue = _options$min === void 0 ? options.autoMinMax ? currentMin : 0 : _options$min,\n _options$max = options.max,\n maxValue = _options$max === void 0 ? options.autoMinMax ? currentMax : 1 : _options$max;\n\n if (minValue >= maxValue) {\n throw new RangeError('min option must be smaller than max option');\n }\n\n var factor = (maxValue - minValue) / (currentMax - currentMin);\n\n for (var i = 0; i < input.length; i++) {\n output[i] = (input[i] - currentMin) * factor + minValue;\n }\n\n return output;\n}\n\nexport default rescale;\n","'use strict';\n\nconst newArray = require('new-array');\n\nconst primeFinder = require('./primeFinder');\nconst nextPrime = primeFinder.nextPrime;\nconst largestPrime = primeFinder.largestPrime;\n\nconst FREE = 0;\nconst FULL = 1;\nconst REMOVED = 2;\n\nconst defaultInitialCapacity = 150;\nconst defaultMinLoadFactor = 1 / 6;\nconst defaultMaxLoadFactor = 2 / 3;\n\nclass HashTable {\n constructor(options = {}) {\n if (options instanceof HashTable) {\n this.table = options.table.slice();\n this.values = options.values.slice();\n this.state = options.state.slice();\n this.minLoadFactor = options.minLoadFactor;\n this.maxLoadFactor = options.maxLoadFactor;\n this.distinct = options.distinct;\n this.freeEntries = options.freeEntries;\n this.lowWaterMark = options.lowWaterMark;\n this.highWaterMark = options.maxLoadFactor;\n return;\n }\n\n const initialCapacity = options.initialCapacity === undefined ? defaultInitialCapacity : options.initialCapacity;\n if (initialCapacity < 0) {\n throw new RangeError(`initial capacity must not be less than zero: ${initialCapacity}`);\n }\n\n const minLoadFactor = options.minLoadFactor === undefined ? defaultMinLoadFactor : options.minLoadFactor;\n const maxLoadFactor = options.maxLoadFactor === undefined ? defaultMaxLoadFactor : options.maxLoadFactor;\n if (minLoadFactor < 0 || minLoadFactor >= 1) {\n throw new RangeError(`invalid minLoadFactor: ${minLoadFactor}`);\n }\n if (maxLoadFactor <= 0 || maxLoadFactor >= 1) {\n throw new RangeError(`invalid maxLoadFactor: ${maxLoadFactor}`);\n }\n if (minLoadFactor >= maxLoadFactor) {\n throw new RangeError(`minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`);\n }\n\n let capacity = initialCapacity;\n // User wants to put at least capacity elements. We need to choose the size based on the maxLoadFactor to\n // avoid the need to rehash before this capacity is reached.\n // actualCapacity * maxLoadFactor >= capacity\n capacity = (capacity / maxLoadFactor) | 0;\n capacity = nextPrime(capacity);\n if (capacity === 0) capacity = 1;\n\n this.table = newArray(capacity, 0);\n this.values = newArray(capacity, 0);\n this.state = newArray(capacity, 0);\n\n this.minLoadFactor = minLoadFactor;\n if (capacity === largestPrime) {\n this.maxLoadFactor = 1;\n } else {\n this.maxLoadFactor = maxLoadFactor;\n }\n\n this.distinct = 0;\n this.freeEntries = capacity;\n\n this.lowWaterMark = 0;\n this.highWaterMark = chooseHighWaterMark(capacity, this.maxLoadFactor);\n }\n\n clone() {\n return new HashTable(this);\n }\n\n get size() {\n return this.distinct;\n }\n\n get(key) {\n const i = this.indexOfKey(key);\n if (i < 0) return 0;\n return this.values[i];\n }\n\n set(key, value) {\n let i = this.indexOfInsertion(key);\n if (i < 0) {\n i = -i - 1;\n this.values[i] = value;\n return false;\n }\n\n if (this.distinct > this.highWaterMark) {\n const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n return this.set(key, value);\n }\n\n this.table[i] = key;\n this.values[i] = value;\n if (this.state[i] === FREE) this.freeEntries--;\n this.state[i] = FULL;\n this.distinct++;\n\n if (this.freeEntries < 1) {\n const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n }\n\n return true;\n }\n \n remove(key, noRehash) {\n const i = this.indexOfKey(key);\n if (i < 0) return false;\n\n this.state[i] = REMOVED;\n this.distinct--;\n\n if (!noRehash) this.maybeShrinkCapacity();\n\n return true;\n }\n\n delete(key, noRehash) {\n const i = this.indexOfKey(key);\n if (i < 0) return false;\n\n this.state[i] = FREE;\n this.distinct--;\n\n if (!noRehash) this.maybeShrinkCapacity();\n\n return true;\n }\n\n maybeShrinkCapacity() {\n if (this.distinct < this.lowWaterMark) {\n const newCapacity = chooseShrinkCapacity(this.distinct, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n }\n }\n\n containsKey(key) {\n return this.indexOfKey(key) >= 0;\n }\n\n indexOfKey(key) {\n const table = this.table;\n const state = this.state;\n const length = this.table.length;\n\n const hash = key & 0x7fffffff;\n let i = hash % length;\n let decrement = hash % (length - 2);\n if (decrement === 0) decrement = 1;\n\n while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) {\n i -= decrement;\n if (i < 0) i += length;\n }\n\n if (state[i] === FREE) return -1;\n return i;\n }\n\n containsValue(value) {\n return this.indexOfValue(value) >= 0;\n }\n\n indexOfValue(value) {\n const values = this.values;\n const state = this.state;\n\n for (var i = 0; i < state.length; i++) {\n if (state[i] === FULL && values[i] === value) {\n return i;\n }\n }\n\n return -1;\n }\n\n indexOfInsertion(key) {\n const table = this.table;\n const state = this.state;\n const length = table.length;\n\n\n const hash = key & 0x7fffffff;\n let i = hash % length;\n let decrement = hash % (length - 2);\n if (decrement === 0) decrement = 1;\n\n while (state[i] === FULL && table[i] !== key) {\n i -= decrement;\n if (i < 0) i += length;\n }\n\n if (state[i] === REMOVED) {\n const j = i;\n while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) {\n i -= decrement;\n if (i < 0) i += length;\n }\n if (state[i] === FREE) i = j;\n }\n\n if (state[i] === FULL) {\n return -i - 1;\n }\n\n return i;\n }\n\n ensureCapacity(minCapacity) {\n if (this.table.length < minCapacity) {\n const newCapacity = nextPrime(minCapacity);\n this.rehash(newCapacity);\n }\n }\n\n rehash(newCapacity) {\n const oldCapacity = this.table.length;\n\n if (newCapacity <= this.distinct) throw new Error('Unexpected');\n\n const oldTable = this.table;\n const oldValues = this.values;\n const oldState = this.state;\n\n const newTable = newArray(newCapacity, 0);\n const newValues = newArray(newCapacity, 0);\n const newState = newArray(newCapacity, 0);\n\n this.lowWaterMark = chooseLowWaterMark(newCapacity, this.minLoadFactor);\n this.highWaterMark = chooseHighWaterMark(newCapacity, this.maxLoadFactor);\n\n this.table = newTable;\n this.values = newValues;\n this.state = newState;\n this.freeEntries = newCapacity - this.distinct;\n\n for (var i = 0; i < oldCapacity; i++) {\n if (oldState[i] === FULL) {\n var element = oldTable[i];\n var index = this.indexOfInsertion(element);\n newTable[index] = element;\n newValues[index] = oldValues[i];\n newState[index] = FULL;\n }\n }\n }\n\n forEachKey(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.table[i])) return false;\n }\n }\n return true;\n }\n\n forEachValue(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.values[i])) return false;\n }\n }\n return true;\n }\n\n forEachPair(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.table[i], this.values[i])) return false;\n }\n }\n return true;\n }\n}\n\nmodule.exports = HashTable;\n\nfunction chooseLowWaterMark(capacity, minLoad) {\n return (capacity * minLoad) | 0;\n}\n\nfunction chooseHighWaterMark(capacity, maxLoad) {\n return Math.min(capacity - 2, (capacity * maxLoad) | 0);\n}\n\nfunction chooseGrowCapacity(size, minLoad, maxLoad) {\n return nextPrime(Math.max(size + 1, (4 * size / (3 * minLoad + maxLoad)) | 0));\n}\n\nfunction chooseShrinkCapacity(size, minLoad, maxLoad) {\n return nextPrime(Math.max(size + 1, (4 * size / (minLoad + 3 * maxLoad)) | 0));\n}\n","'use strict';\n\nconst Heap = require('heap');\n\nfunction Cluster() {\n this.children = [];\n this.distance = -1;\n this.index = [];\n}\n\n/**\n * Creates an array of values where maximum distance smaller than the threshold\n * @param {number} threshold\n * @return {Array }\n */\nCluster.prototype.cut = function (threshold) {\n if (threshold < 0) throw new RangeError('Threshold too small');\n var root = new Cluster();\n root.children = this.children;\n root.distance = this.distance;\n root.index = this.index;\n var list = [root];\n var ans = [];\n while (list.length > 0) {\n var aux = list.shift();\n if (threshold >= aux.distance) {\n ans.push(aux);\n } else {\n list = list.concat(aux.children);\n }\n }\n return ans;\n};\n\n/**\n * Merge the leaves in the minimum way to have 'minGroups' number of clusters\n * @param {number} minGroups - Them minimum number of children the first level of the tree should have\n * @return {Cluster}\n */\nCluster.prototype.group = function (minGroups) {\n if (!Number.isInteger(minGroups) || minGroups < 1) throw new RangeError('Number of groups must be a positive integer');\n\n const heap = new Heap(function (a, b) {\n return b.distance - a.distance;\n });\n\n heap.push(this);\n\n while (heap.size() < minGroups) {\n var first = heap.pop();\n if (first.children.length === 0) {\n break;\n }\n first.children.forEach(child => heap.push(child));\n }\n\n var root = new Cluster();\n root.children = heap.toArray();\n root.distance = this.distance;\n\n return root;\n};\n\n/**\n * Traverses the tree depth-first and provide callback to be called on each individual node\n * @param {function} cb - The callback to be called on each node encounter\n * @type {Cluster}\n */\nCluster.prototype.traverse = function (cb) {\n function visit(root, callback) {\n callback(root);\n if (root.children) {\n for (var i = root.children.length - 1; i >= 0; i--) {\n visit(root.children[i], callback);\n }\n }\n }\n visit(this, cb);\n};\n\nmodule.exports = Cluster;\n","'use strict';\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toStr = Object.prototype.toString;\nvar defineProperty = Object.defineProperty;\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nvar isArray = function isArray(arr) {\n\tif (typeof Array.isArray === 'function') {\n\t\treturn Array.isArray(arr);\n\t}\n\n\treturn toStr.call(arr) === '[object Array]';\n};\n\nvar isPlainObject = function isPlainObject(obj) {\n\tif (!obj || toStr.call(obj) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tvar hasOwnConstructor = hasOwn.call(obj, 'constructor');\n\tvar hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n\t\treturn false;\n\t}\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor (key in obj) { /**/ }\n\n\treturn typeof key === 'undefined' || hasOwn.call(obj, key);\n};\n\n// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target\nvar setProperty = function setProperty(target, options) {\n\tif (defineProperty && options.name === '__proto__') {\n\t\tdefineProperty(target, options.name, {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\tvalue: options.newValue,\n\t\t\twritable: true\n\t\t});\n\t} else {\n\t\ttarget[options.name] = options.newValue;\n\t}\n};\n\n// Return undefined instead of __proto__ if '__proto__' is not an own property\nvar getProperty = function getProperty(obj, name) {\n\tif (name === '__proto__') {\n\t\tif (!hasOwn.call(obj, name)) {\n\t\t\treturn void 0;\n\t\t} else if (gOPD) {\n\t\t\t// In early versions of node, obj['__proto__'] is buggy when obj has\n\t\t\t// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.\n\t\t\treturn gOPD(obj, name).value;\n\t\t}\n\t}\n\n\treturn obj[name];\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone;\n\tvar target = arguments[0];\n\tvar i = 1;\n\tvar length = arguments.length;\n\tvar deep = false;\n\n\t// Handle a deep copy situation\n\tif (typeof target === 'boolean') {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t}\n\tif (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n\t\ttarget = {};\n\t}\n\n\tfor (; i < length; ++i) {\n\t\toptions = arguments[i];\n\t\t// Only deal with non-null/undefined values\n\t\tif (options != null) {\n\t\t\t// Extend the base object\n\t\t\tfor (name in options) {\n\t\t\t\tsrc = getProperty(target, name);\n\t\t\t\tcopy = getProperty(options, name);\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif (target !== copy) {\n\t\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\t\tif (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {\n\t\t\t\t\t\tif (copyIsArray) {\n\t\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\t\tclone = src && isArray(src) ? src : [];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: extend(deep, clone, copy) });\n\n\t\t\t\t\t// Don't bring in undefined values\n\t\t\t\t\t} else if (typeof copy !== 'undefined') {\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: copy });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n","import isArray from 'is-any-array';\n\n/**\n * Computes the minimum of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction min(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var min = input[0];\n\n for (var i = 1; i < input.length; i++) {\n if (input[i] < min) min = input[i];\n }\n\n return min;\n}\n\nexport default min;\n","import quickSelectMedian from 'median-quickselect';\nimport isArray from 'is-any-array';\n\n/**\n * Computes the median of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction median(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n return quickSelectMedian(input.slice());\n}\n\nexport default median;\n","const LOOP = 8;\nconst FLOAT_MUL = 1 / 16777216;\nconst sh1 = 15;\nconst sh2 = 18;\nconst sh3 = 11;\nfunction multiply_uint32(n, m) {\n n >>>= 0;\n m >>>= 0;\n const nlo = n & 0xffff;\n const nhi = n - nlo;\n return (((nhi * m) >>> 0) + nlo * m) >>> 0;\n}\nexport default class XSadd {\n constructor(seed = Date.now()) {\n this.state = new Uint32Array(4);\n this.init(seed);\n this.random = this.getFloat.bind(this);\n }\n /**\n * Returns a 32-bit integer r (0 <= r < 2^32)\n */\n getUint32() {\n this.nextState();\n return (this.state[3] + this.state[2]) >>> 0;\n }\n /**\n * Returns a floating point number r (0.0 <= r < 1.0)\n */\n getFloat() {\n return (this.getUint32() >>> 8) * FLOAT_MUL;\n }\n init(seed) {\n if (!Number.isInteger(seed)) {\n throw new TypeError('seed must be an integer');\n }\n this.state[0] = seed;\n this.state[1] = 0;\n this.state[2] = 0;\n this.state[3] = 0;\n for (let i = 1; i < LOOP; i++) {\n this.state[i & 3] ^=\n (i +\n multiply_uint32(1812433253, this.state[(i - 1) & 3] ^ ((this.state[(i - 1) & 3] >>> 30) >>> 0))) >>>\n 0;\n }\n this.periodCertification();\n for (let i = 0; i < LOOP; i++) {\n this.nextState();\n }\n }\n periodCertification() {\n if (this.state[0] === 0 &&\n this.state[1] === 0 &&\n this.state[2] === 0 &&\n this.state[3] === 0) {\n this.state[0] = 88; // X\n this.state[1] = 83; // S\n this.state[2] = 65; // A\n this.state[3] = 68; // D\n }\n }\n nextState() {\n let t = this.state[0];\n t ^= t << sh1;\n t ^= t >>> sh2;\n t ^= this.state[3] << sh3;\n this.state[0] = this.state[1];\n this.state[1] = this.state[2];\n this.state[2] = this.state[3];\n this.state[3] = t;\n }\n}\n","import isArray from 'is-any-array';\n\nfunction _typeof(obj) {\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function (obj) {\n return typeof obj;\n };\n } else {\n _typeof = function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n}\n\n/**\n * Fill an array with sequential numbers\n * @param {Array} [input] - optional destination array (if not provided a new array will be created)\n * @param {object} [options={}]\n * @param {number} [options.from=0] - first value in the array\n * @param {number} [options.to=10] - last value in the array\n * @param {number} [options.size=input.length] - size of the array (if not provided calculated from step)\n * @param {number} [options.step] - if not provided calculated from size\n * @return {Array}\n */\n\nfunction sequentialFill() {\n var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n if (_typeof(input) === 'object' && !isArray(input)) {\n options = input;\n input = [];\n }\n\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n var _options = options,\n _options$from = _options.from,\n from = _options$from === void 0 ? 0 : _options$from,\n _options$to = _options.to,\n to = _options$to === void 0 ? 10 : _options$to,\n _options$size = _options.size,\n size = _options$size === void 0 ? input.length : _options$size,\n step = _options.step;\n\n if (size && step) {\n throw new Error('step is defined by the array size');\n }\n\n if (!size) {\n if (step) {\n size = Math.floor((to - from) / step) + 1;\n } else {\n size = to - from + 1;\n }\n }\n\n if (!step && size) {\n step = (to - from) / (size - 1);\n }\n\n if (Array.isArray(input)) {\n input.length = 0; // only works with normal array\n\n for (var i = 0; i < size; i++) {\n input.push(from);\n from += step;\n }\n } else {\n if (input.length !== size) {\n throw new Error('sequentialFill typed array must have the correct length');\n }\n\n for (var _i = 0; _i < size; _i++) {\n input[_i] = from;\n from += step;\n }\n }\n\n return input;\n}\n\nexport default sequentialFill;\n","import arrayMean from 'ml-array-mean';\nimport isArray from 'is-any-array';\n\n/**\n * Computes the variance of the given values\n * @param {Array} values\n * @param {object} [options]\n * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n.\n * @param {number} [options.mean = arrayMean] - precalculated mean, if any.\n * @return {number}\n */\n\nfunction variance(values) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n if (!isArray(values)) {\n throw new TypeError('input must be an array');\n }\n\n var _options$unbiased = options.unbiased,\n unbiased = _options$unbiased === void 0 ? true : _options$unbiased,\n _options$mean = options.mean,\n mean = _options$mean === void 0 ? arrayMean(values) : _options$mean;\n var sqrError = 0;\n\n for (var i = 0; i < values.length; i++) {\n var x = values[i] - mean;\n sqrError += x * x;\n }\n\n if (unbiased) {\n return sqrError / (values.length - 1);\n } else {\n return sqrError / values.length;\n }\n}\n\nexport default variance;\n","'use strict';\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\n/**\n * Computes the sum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.sum = function sum(values) {\n var sum = 0;\n for (var i = 0; i < values.length; i++) {\n sum += values[i];\n }\n return sum;\n};\n\n/**\n * Computes the maximum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.max = function max(values) {\n var max = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] > max) max = values[i];\n }\n return max;\n};\n\n/**\n * Computes the minimum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.min = function min(values) {\n var min = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] < min) min = values[i];\n }\n return min;\n};\n\n/**\n * Computes the min and max of the given values\n * @param {Array} values\n * @returns {{min: number, max: number}}\n */\nexports.minMax = function minMax(values) {\n var min = values[0];\n var max = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] < min) min = values[i];\n if (values[i] > max) max = values[i];\n }\n return {\n min: min,\n max: max\n };\n};\n\n/**\n * Computes the arithmetic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.arithmeticMean = function arithmeticMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n sum += values[i];\n }\n return sum / l;\n};\n\n/**\n * {@link arithmeticMean}\n */\nexports.mean = exports.arithmeticMean;\n\n/**\n * Computes the geometric mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.geometricMean = function geometricMean(values) {\n var mul = 1;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n mul *= values[i];\n }\n return Math.pow(mul, 1 / l);\n};\n\n/**\n * Computes the mean of the log of the given values\n * If the return value is exponentiated, it gives the same result as the\n * geometric mean.\n * @param {Array} values\n * @returns {number}\n */\nexports.logMean = function logMean(values) {\n var lnsum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n lnsum += Math.log(values[i]);\n }\n return lnsum / l;\n};\n\n/**\n * Computes the weighted grand mean for a list of means and sample sizes\n * @param {Array} means - Mean values for each set of samples\n * @param {Array} samples - Number of original values for each set of samples\n * @returns {number}\n */\nexports.grandMean = function grandMean(means, samples) {\n var sum = 0;\n var n = 0;\n var l = means.length;\n for (var i = 0; i < l; i++) {\n sum += samples[i] * means[i];\n n += samples[i];\n }\n return sum / n;\n};\n\n/**\n * Computes the truncated mean of the given values using a given percentage\n * @param {Array} values\n * @param {number} percent - The percentage of values to keep (range: [0,1])\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.truncatedMean = function truncatedMean(values, percent, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var k = Math.floor(l * percent);\n var sum = 0;\n for (var i = k; i < (l - k); i++) {\n sum += values[i];\n }\n return sum / (l - 2 * k);\n};\n\n/**\n * Computes the harmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.harmonicMean = function harmonicMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (values[i] === 0) {\n throw new RangeError('value at index ' + i + 'is zero');\n }\n sum += 1 / values[i];\n }\n return l / sum;\n};\n\n/**\n * Computes the contraharmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.contraHarmonicMean = function contraHarmonicMean(values) {\n var r1 = 0;\n var r2 = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n r1 += values[i] * values[i];\n r2 += values[i];\n }\n if (r2 < 0) {\n throw new RangeError('sum of values is negative');\n }\n return r1 / r2;\n};\n\n/**\n * Computes the median of the given values\n * @param {Array} values\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.median = function median(values, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return (values[half - 1] + values[half]) * 0.5;\n } else {\n return values[half];\n }\n};\n\n/**\n * Computes the variance of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.variance = function variance(values, unbiased) {\n if (unbiased === undefined) unbiased = true;\n var theMean = exports.mean(values);\n var theVariance = 0;\n var l = values.length;\n\n for (var i = 0; i < l; i++) {\n var x = values[i] - theMean;\n theVariance += x * x;\n }\n\n if (unbiased) {\n return theVariance / (l - 1);\n } else {\n return theVariance / l;\n }\n};\n\n/**\n * Computes the standard deviation of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.standardDeviation = function standardDeviation(values, unbiased) {\n return Math.sqrt(exports.variance(values, unbiased));\n};\n\nexports.standardError = function standardError(values) {\n return exports.standardDeviation(values) / Math.sqrt(values.length);\n};\n\n/**\n * IEEE Transactions on biomedical engineering, vol. 52, no. 1, january 2005, p. 76-\n * Calculate the standard deviation via the Median of the absolute deviation\n * The formula for the standard deviation only holds for Gaussian random variables.\n * @returns {{mean: number, stdev: number}}\n */\nexports.robustMeanAndStdev = function robustMeanAndStdev(y) {\n var mean = 0, stdev = 0;\n var length = y.length, i = 0;\n for (i = 0; i < length; i++) {\n mean += y[i];\n }\n mean /= length;\n var averageDeviations = new Array(length);\n for (i = 0; i < length; i++)\n averageDeviations[i] = Math.abs(y[i] - mean);\n averageDeviations.sort(compareNumbers);\n if (length % 2 === 1) {\n stdev = averageDeviations[(length - 1) / 2] / 0.6745;\n } else {\n stdev = 0.5 * (averageDeviations[length / 2] + averageDeviations[length / 2 - 1]) / 0.6745;\n }\n\n return {\n mean: mean,\n stdev: stdev\n };\n};\n\nexports.quartiles = function quartiles(values, alreadySorted) {\n if (typeof (alreadySorted) === 'undefined') alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n\n var quart = values.length / 4;\n var q1 = values[Math.ceil(quart) - 1];\n var q2 = exports.median(values, true);\n var q3 = values[Math.ceil(quart * 3) - 1];\n\n return {q1: q1, q2: q2, q3: q3};\n};\n\nexports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) {\n return Math.sqrt(exports.pooledVariance(samples, unbiased));\n};\n\nexports.pooledVariance = function pooledVariance(samples, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var sum = 0;\n var length = 0, l = samples.length;\n for (var i = 0; i < l; i++) {\n var values = samples[i];\n var vari = exports.variance(values);\n\n sum += (values.length - 1) * vari;\n\n if (unbiased)\n length += values.length - 1;\n else\n length += values.length;\n }\n return sum / length;\n};\n\nexports.mode = function mode(values) {\n var l = values.length,\n itemCount = new Array(l),\n i;\n for (i = 0; i < l; i++) {\n itemCount[i] = 0;\n }\n var itemArray = new Array(l);\n var count = 0;\n\n for (i = 0; i < l; i++) {\n var index = itemArray.indexOf(values[i]);\n if (index >= 0)\n itemCount[index]++;\n else {\n itemArray[count] = values[i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (i = 0; i < count; i++) {\n if (itemCount[i] > maxValue) {\n maxValue = itemCount[i];\n maxIndex = i;\n }\n }\n\n return itemArray[maxIndex];\n};\n\nexports.covariance = function covariance(vector1, vector2, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var mean1 = exports.mean(vector1);\n var mean2 = exports.mean(vector2);\n\n if (vector1.length !== vector2.length)\n throw 'Vectors do not have the same dimensions';\n\n var cov = 0, l = vector1.length;\n for (var i = 0; i < l; i++) {\n var x = vector1[i] - mean1;\n var y = vector2[i] - mean2;\n cov += x * y;\n }\n\n if (unbiased)\n return cov / (l - 1);\n else\n return cov / l;\n};\n\nexports.skewness = function skewness(values, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n\n var s2 = 0, s3 = 0, l = values.length;\n for (var i = 0; i < l; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n var m2 = s2 / l;\n var m3 = s3 / l;\n\n var g = m3 / (Math.pow(m2, 3 / 2.0));\n if (unbiased) {\n var a = Math.sqrt(l * (l - 1));\n var b = l - 2;\n return (a / b) * g;\n } else {\n return g;\n }\n};\n\nexports.kurtosis = function kurtosis(values, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n var n = values.length, s2 = 0, s4 = 0;\n\n for (var i = 0; i < n; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n\n return a * b - 3 * c;\n } else {\n return m4 / (m2 * m2) - 3;\n }\n};\n\nexports.entropy = function entropy(values, eps) {\n if (typeof (eps) === 'undefined') eps = 0;\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * Math.log(values[i] + eps);\n return -sum;\n};\n\nexports.weightedMean = function weightedMean(values, weights) {\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * weights[i];\n return sum;\n};\n\nexports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) {\n return Math.sqrt(exports.weightedVariance(values, weights));\n};\n\nexports.weightedVariance = function weightedVariance(values, weights) {\n var theMean = exports.weightedMean(values, weights);\n var vari = 0, l = values.length;\n var a = 0, b = 0;\n\n for (var i = 0; i < l; i++) {\n var z = values[i] - theMean;\n var w = weights[i];\n\n vari += w * (z * z);\n b += w;\n a += w * w;\n }\n\n return vari * (b / (b * b - a));\n};\n\nexports.center = function center(values, inPlace) {\n if (typeof (inPlace) === 'undefined') inPlace = false;\n\n var result = values;\n if (!inPlace)\n result = [].concat(values);\n\n var theMean = exports.mean(result), l = result.length;\n for (var i = 0; i < l; i++)\n result[i] -= theMean;\n};\n\nexports.standardize = function standardize(values, standardDev, inPlace) {\n if (typeof (standardDev) === 'undefined') standardDev = exports.standardDeviation(values);\n if (typeof (inPlace) === 'undefined') inPlace = false;\n var l = values.length;\n var result = inPlace ? values : new Array(l);\n for (var i = 0; i < l; i++)\n result[i] = values[i] / standardDev;\n return result;\n};\n\nexports.cumulativeSum = function cumulativeSum(array) {\n var l = array.length;\n var result = new Array(l);\n result[0] = array[0];\n for (var i = 1; i < l; i++)\n result[i] = result[i - 1] + array[i];\n return result;\n};\n","'use strict';\n\nconst Cluster = require('./Cluster');\nconst util = require('util');\n\nfunction ClusterLeaf(index) {\n Cluster.call(this);\n this.index = index;\n this.distance = 0;\n this.children = [];\n}\n\nutil.inherits(ClusterLeaf, Cluster);\n\nmodule.exports = ClusterLeaf;\n","'use strict';\n\n\n/**\n * Computes a distance/similarity matrix given an array of data and a distance/similarity function.\n * @param {Array} data An array of data\n * @param {function} distanceFn A function that accepts two arguments and computes a distance/similarity between them\n * @return {Array} The similarity matrix. The similarity matrix is square and has a size equal to the length of\n * the data array\n */\nfunction distanceMatrix(data, distanceFn) {\n const length = data.length;\n let result = Array.from({length}).map(() => Array.from({length}));\n\n // Compute upper distance matrix\n for (let i = 0; i < length; i++) {\n for (let j = 0; j <= i; j++) {\n result[i][j] = distanceFn(data[i], data[j]);\n }\n }\n\n // Copy to lower distance matrix\n for (let i = 0; i < length; i++) {\n for (let j = i + 1; j < length; j++) {\n result[i][j] = result[j][i];\n }\n }\n\n return result;\n}\n\nmodule.exports = distanceMatrix;\n","/**\n * Constructs a confusion matrix\n * @class ConfusionMatrix\n * @example\n * const CM = new ConfusionMatrix([[13, 2], [10, 5]], ['cat', 'dog'])\n * @param {Array>} matrix - The confusion matrix, a 2D Array. Rows represent the actual label and columns\n * the predicted label.\n * @param {Array} labels - Labels of the confusion matrix, a 1D Array\n */\nclass ConfusionMatrix {\n constructor(matrix, labels) {\n if (matrix.length !== matrix[0].length) {\n throw new Error('Confusion matrix must be square');\n }\n if (labels.length !== matrix.length) {\n throw new Error('Confusion matrix and labels should have the same length');\n }\n this.labels = labels;\n this.matrix = matrix;\n }\n\n\n /**\n * Construct confusion matrix from the predicted and actual labels (classes). Be sure to provide the arguments in\n * the correct order!\n * @param {Array} actual - The predicted labels of the classification\n * @param {Array} predicted - The actual labels of the classification. Has to be of same length as\n * predicted.\n * @param {object} [options] - Additional options\n * @param {Array} [options.labels] - The list of labels that should be used. If not provided the distinct set\n * of labels present in predicted and actual is used. Labels are compared using the strict equality operator\n * '==='\n * @return {ConfusionMatrix} - Confusion matrix\n */\n static fromLabels(actual, predicted, options = {}) {\n if (predicted.length !== actual.length) {\n throw new Error('predicted and actual must have the same length');\n }\n let distinctLabels;\n if (options.labels) {\n distinctLabels = new Set(options.labels);\n } else {\n distinctLabels = new Set([...actual, ...predicted]);\n }\n distinctLabels = Array.from(distinctLabels);\n if (options.sort) {\n distinctLabels.sort(options.sort);\n }\n\n // Create confusion matrix and fill with 0's\n const matrix = Array.from({length: distinctLabels.length});\n for (let i = 0; i < matrix.length; i++) {\n matrix[i] = new Array(matrix.length);\n matrix[i].fill(0);\n }\n\n for (let i = 0; i < predicted.length; i++) {\n const actualIdx = distinctLabels.indexOf(actual[i]);\n const predictedIdx = distinctLabels.indexOf(predicted[i]);\n if (actualIdx >= 0 && predictedIdx >= 0) {\n matrix[actualIdx][predictedIdx]++;\n }\n }\n\n return new ConfusionMatrix(matrix, distinctLabels);\n }\n\n /**\n * Get the confusion matrix\n * @return {Array >}\n */\n getMatrix() {\n return this.matrix;\n }\n\n getLabels() {\n return this.labels;\n }\n\n /**\n * Get the total number of samples\n * @return {number}\n */\n getTotalCount() {\n let predicted = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n for (var j = 0; j < this.matrix.length; j++) {\n predicted += this.matrix[i][j];\n }\n }\n return predicted;\n }\n\n /**\n * Get the total number of true predictions\n * @return {number}\n */\n getTrueCount() {\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n count += this.matrix[i][i];\n }\n return count;\n }\n\n /**\n * Get the total number of false predictions.\n * @return {number}\n */\n getFalseCount() {\n return this.getTotalCount() - this.getTrueCount();\n }\n\n /**\n * Get the number of true positive predictions.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getTruePositiveCount(label) {\n const index = this.getIndex(label);\n return this.matrix[index][index];\n }\n\n /**\n * Get the number of true negative predictions\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getTrueNegativeCount(label) {\n const index = this.getIndex(label);\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n for (var j = 0; j < this.matrix.length; j++) {\n if (i !== index && j !== index) {\n count += this.matrix[i][j];\n }\n }\n }\n return count;\n }\n\n /**\n * Get the number of false positive predictions.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalsePositiveCount(label) {\n const index = this.getIndex(label);\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n if (i !== index) {\n count += this.matrix[i][index];\n }\n }\n return count;\n }\n\n /**\n * Get the number of false negative predictions.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseNegativeCount(label) {\n const index = this.getIndex(label);\n var count = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n if (i !== index) {\n count += this.matrix[index][i];\n }\n }\n return count;\n }\n\n /**\n * Get the number of real positive samples.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getPositiveCount(label) {\n return this.getTruePositiveCount(label) + this.getFalseNegativeCount(label);\n }\n\n /**\n * Get the number of real negative samples.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getNegativeCount(label) {\n return this.getTrueNegativeCount(label) + this.getFalsePositiveCount(label);\n }\n\n /**\n * Get the index in the confusion matrix that corresponds to the given label\n * @param {any} label - The label to search for\n * @throws if the label is not found\n * @return {number}\n */\n getIndex(label) {\n const index = this.labels.indexOf(label);\n if (index === -1) throw new Error('The label does not exist');\n return index;\n }\n\n /**\n * Get the true positive rate a.k.a. sensitivity. Computes the ratio between the number of true positive predictions and the total number of positive samples.\n * {@link https://en.wikipedia.org/wiki/Sensitivity_and_specificity}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number} - The true positive rate [0-1]\n */\n getTruePositiveRate(label) {\n return this.getTruePositiveCount(label) / this.getPositiveCount(label);\n }\n\n /**\n * Get the true negative rate a.k.a. specificity. Computes the ration between the number of true negative predictions and the total number of negative samples.\n * {@link https://en.wikipedia.org/wiki/Sensitivity_and_specificity}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getTrueNegativeRate(label) {\n return this.getTrueNegativeCount(label) / this.getNegativeCount(label);\n }\n\n /**\n * Get the positive predictive value a.k.a. precision. Computes TP / (TP + FP)\n * {@link https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getPositivePredictiveValue(label) {\n const TP = this.getTruePositiveCount(label);\n return TP / (TP + this.getFalsePositiveCount(label));\n }\n\n /**\n * Negative predictive value\n * {@link https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getNegativePredictiveValue(label) {\n const TN = this.getTrueNegativeCount(label);\n return TN / (TN + this.getFalseNegativeCount(label));\n }\n\n /**\n * False negative rate a.k.a. miss rate.\n * {@link https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#False_positive_and_false_negative_rates}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseNegativeRate(label) {\n return 1 - this.getTruePositiveRate(label);\n }\n\n /**\n * False positive rate a.k.a. fall-out rate.\n * {@link https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#False_positive_and_false_negative_rates}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalsePositiveRate(label) {\n return 1 - this.getTrueNegativeRate(label);\n }\n\n /**\n * False discovery rate (FDR)\n * {@link https://en.wikipedia.org/wiki/False_discovery_rate}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseDiscoveryRate(label) {\n const FP = this.getFalsePositiveCount(label);\n return FP / (FP + this.getTruePositiveCount(label));\n }\n\n /**\n * False omission rate (FOR)\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getFalseOmissionRate(label) {\n const FN = this.getFalseNegativeCount(label);\n return FN / (FN + this.getTruePositiveCount(label));\n }\n\n /**\n * F1 score\n * {@link https://en.wikipedia.org/wiki/F1_score}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getF1Score(label) {\n const TP = this.getTruePositiveCount(label);\n return 2 * TP / (2 * TP + this.getFalsePositiveCount(label) + this.getFalseNegativeCount(label));\n }\n\n /**\n * Matthews correlation coefficient (MCC)\n * {@link https://en.wikipedia.org/wiki/Matthews_correlation_coefficient}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getMatthewsCorrelationCoefficient(label) {\n const TP = this.getTruePositiveCount(label);\n const TN = this.getTrueNegativeCount(label);\n const FP = this.getFalsePositiveCount(label);\n const FN = this.getFalseNegativeCount(label);\n return (TP * TN - FP * FN) / Math.sqrt((TP + FP) * (TP + FN) * (TN + FP) * (TN + FN));\n }\n\n /**\n * Informedness\n * {@link https://en.wikipedia.org/wiki/Youden%27s_J_statistic}\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getInformedness(label) {\n return this.getTruePositiveRate(label) + this.getTrueNegativeRate(label) - 1;\n }\n\n /**\n * Markedness\n * @param {any} label - The label that should be considered \"positive\"\n * @return {number}\n */\n getMarkedness(label) {\n return this.getPositivePredictiveValue(label) + this.getNegativePredictiveValue(label) - 1;\n }\n\n /**\n * Get the confusion table.\n * @param {any} label - The label that should be considered \"positive\"\n * @return {Array >} - The 2x2 confusion table. [[TP, FN], [FP, TN]]\n */\n getConfusionTable(label) {\n return [\n [\n this.getTruePositiveCount(label),\n this.getFalseNegativeCount(label)\n ],\n [\n this.getFalsePositiveCount(label),\n this.getTrueNegativeCount(label)\n ]\n ];\n }\n\n /**\n * Get total accuracy.\n * @return {number} - The ratio between the number of true predictions and total number of classifications ([0-1])\n */\n getAccuracy() {\n let correct = 0;\n let incorrect = 0;\n for (var i = 0; i < this.matrix.length; i++) {\n for (var j = 0; j < this.matrix.length; j++) {\n if (i === j) correct += this.matrix[i][j];\n else incorrect += this.matrix[i][j];\n }\n }\n return correct / (correct + incorrect);\n }\n\n\n /**\n * Returns the element in the confusion matrix that corresponds to the given actual and predicted labels.\n * @param {any} actual - The true label\n * @param {any} predicted - The predicted label\n * @return {number} - The element in the confusion matrix\n */\n getCount(actual, predicted) {\n const actualIndex = this.getIndex(actual);\n const predictedIndex = this.getIndex(predicted);\n return this.matrix[actualIndex][predictedIndex];\n }\n\n /**\n * Compute the general prediction accuracy\n * @deprecated Use getAccuracy\n * @return {number} - The prediction accuracy ([0-1]\n */\n get accuracy() {\n return this.getAccuracy();\n }\n\n /**\n * Compute the number of predicted observations\n * @deprecated Use getTotalCount\n * @return {number}\n */\n get total() {\n return this.getTotalCount();\n }\n}\n\nmodule.exports = ConfusionMatrix;\n","'use strict';\n\nvar Matrix = require('ml-matrix').Matrix;\n\nvar Utils = require('./utils');\nconst ACTIVATION_FUNCTIONS = require('./activationFunctions');\n\nclass Layer {\n /**\n * @private\n * Create a new layer with the given options\n * @param {object} options\n * @param {number} [options.inputSize] - Number of conections that enter the neurons.\n * @param {number} [options.outputSize] - Number of conections that leave the neurons.\n * @param {number} [options.regularization] - Regularization parameter.\n * @param {number} [options.epsilon] - Learning rate parameter.\n * @param {string} [options.activation] - Activation function parameter from the FeedForwardNeuralNetwork class.\n * @param {number} [options.activationParam] - Activation parameter if needed.\n */\n constructor(options) {\n this.inputSize = options.inputSize;\n this.outputSize = options.outputSize;\n this.regularization = options.regularization;\n this.epsilon = options.epsilon;\n this.activation = options.activation;\n this.activationParam = options.activationParam;\n\n var selectedFunction = ACTIVATION_FUNCTIONS[options.activation];\n var params = selectedFunction.activation.length;\n\n var actFunction = params > 1 ? val => selectedFunction.activation(val, options.activationParam) : selectedFunction.activation;\n var derFunction = params > 1 ? val => selectedFunction.derivate(val, options.activationParam) : selectedFunction.derivate;\n\n this.activationFunction = function (i, j) {\n this[i][j] = actFunction(this[i][j]);\n };\n this.derivate = function (i, j) {\n this[i][j] = derFunction(this[i][j]);\n };\n\n if (options.model) {\n // load model\n this.W = Matrix.checkMatrix(options.W);\n this.b = Matrix.checkMatrix(options.b);\n\n } else {\n // default constructor\n\n this.W = Matrix.rand(this.inputSize, this.outputSize);\n this.b = Matrix.zeros(1, this.outputSize);\n\n this.W.apply(function (i, j) {\n this[i][j] /= Math.sqrt(options.inputSize);\n });\n }\n }\n\n /**\n * @private\n * propagate the given input through the current layer.\n * @param {Matrix} X - input.\n * @return {Matrix} output at the current layer.\n */\n forward(X) {\n var z = X.mmul(this.W).addRowVector(this.b);\n z.apply(this.activationFunction);\n this.a = z.clone();\n return z;\n }\n\n /**\n * @private\n * apply backpropagation algorithm at the current layer\n * @param {Matrix} delta - delta values estimated at the following layer.\n * @param {Matrix} a - 'a' values from the following layer.\n * @return {Matrix} the new delta values for the next layer.\n */\n backpropagation(delta, a) {\n this.dW = a.transposeView().mmul(delta);\n this.db = Utils.sumCol(delta);\n\n var aCopy = a.clone();\n return delta.mmul(this.W.transposeView()).mul(aCopy.apply(this.derivate));\n }\n\n /**\n * @private\n * Function that updates the weights at the current layer with the derivatives.\n */\n update() {\n this.dW.add(this.W.clone().mul(this.regularization));\n this.W.add(this.dW.mul(-this.epsilon));\n this.b.add(this.db.mul(-this.epsilon));\n }\n\n /**\n * @private\n * Export the current layer to JSON.\n * @return {object} model\n */\n toJSON() {\n return {\n model: 'Layer',\n inputSize: this.inputSize,\n outputSize: this.outputSize,\n regularization: this.regularization,\n epsilon: this.epsilon,\n activation: this.activation,\n W: this.W,\n b: this.b\n };\n }\n\n /**\n * @private\n * Creates a new Layer with the given model.\n * @param {object} model\n * @return {Layer}\n */\n static load(model) {\n if (model.model !== 'Layer') {\n throw new RangeError('the current model is not a Layer model');\n }\n return new Layer(model);\n }\n\n}\n\nmodule.exports = Layer;\n","'use strict';\n\nvar Matrix = require('ml-matrix').Matrix;\n\n/**\n * @private\n * Retrieves the sum at each row of the given matrix.\n * @param {Matrix} matrix\n * @return {Matrix}\n */\nfunction sumRow(matrix) {\n var sum = Matrix.zeros(matrix.rows, 1);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum[i][0] += matrix[i][j];\n }\n }\n return sum;\n}\n\n/**\n * @private\n * Retrieves the sum at each column of the given matrix.\n * @param {Matrix} matrix\n * @return {Matrix}\n */\nfunction sumCol(matrix) {\n var sum = Matrix.zeros(1, matrix.columns);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum[0][j] += matrix[i][j];\n }\n }\n return sum;\n}\n\n/**\n * @private\n * Method that given an array of labels(predictions), returns two dictionaries, one to transform from labels to\n * numbers and other in the reverse way\n * @param {Array} array\n * @return {object}\n */\nfunction dictOutputs(array) {\n var inputs = {};\n var outputs = {};\n var index = 0;\n for (var i = 0; i < array.length; i += 1) {\n if (inputs[array[i]] === undefined) {\n inputs[array[i]] = index;\n outputs[index] = array[i];\n index++;\n }\n }\n\n return {\n inputs: inputs,\n outputs: outputs\n };\n}\n\nmodule.exports = {\n dictOutputs: dictOutputs,\n sumCol: sumCol,\n sumRow: sumRow\n};\n","'use strict';\n\nfunction logistic(val) {\n return 1 / (1 + Math.exp(-val));\n}\n\nfunction expELU(val, param) {\n return val < 0 ? param * (Math.exp(val) - 1) : val;\n}\n\nfunction softExponential(val, param) {\n if (param < 0) {\n return -Math.log(1 - param * (val + param)) / param;\n }\n if (param > 0) {\n return ((Math.exp(param * val) - 1) / param) + param;\n }\n return val;\n}\n\nfunction softExponentialPrime(val, param) {\n if (param < 0) {\n return 1 / (1 - param * (param + val));\n } else {\n return Math.exp(param * val);\n }\n}\n\nconst ACTIVATION_FUNCTIONS = {\n tanh: {\n activation: Math.tanh,\n derivate: val => 1 - (val * val)\n },\n identity: {\n activation: val => val,\n derivate: () => 1\n },\n logistic: {\n activation: logistic,\n derivate: val => logistic(val) * (1 - logistic(val))\n },\n arctan: {\n activation: Math.atan,\n derivate: val => 1 / (val * val + 1)\n },\n softsign: {\n activation: val => val / (1 + Math.abs(val)),\n derivate: val => 1 / ((1 + Math.abs(val)) * (1 + Math.abs(val)))\n },\n relu: {\n activation: val => val < 0 ? 0 : val,\n derivate: val => val < 0 ? 0 : 1\n },\n softplus: {\n activation: val => Math.log(1 + Math.exp(val)),\n derivate: val => 1 / (1 + Math.exp(-val))\n },\n bent: {\n activation: val => ((Math.sqrt(val * val + 1) - 1) / 2) + val,\n derivate: val => (val / (2 * Math.sqrt(val * val + 1))) + 1\n },\n sinusoid: {\n activation: Math.sin,\n derivate: Math.cos\n },\n sinc: {\n activation: val => val === 0 ? 1 : Math.sin(val) / val,\n derivate: val => val === 0 ? 0 : (Math.cos(val) / val) - (Math.sin(val) / (val * val))\n },\n gaussian: {\n activation: val => Math.exp(-(val * val)),\n derivate: val => -2 * val * Math.exp(-(val * val))\n },\n 'parametric-relu': {\n activation: (val, param) => val < 0 ? param * val : val,\n derivate: (val, param) => val < 0 ? param : 1\n },\n 'exponential-elu': {\n activation: expELU,\n derivate: (val, param) => val < 0 ? expELU(val, param) + param : 1\n },\n 'soft-exponential': {\n activation: softExponential,\n derivate: softExponentialPrime\n }\n};\n\nmodule.exports = ACTIVATION_FUNCTIONS;\n","function NodeSquare(x, y, weights, som) {\n this.x = x;\n this.y = y;\n this.weights = weights;\n this.som = som;\n this.neighbors = {};\n}\n\nNodeSquare.prototype.adjustWeights = function adjustWeights(target, learningRate, influence) {\n for (var i = 0, ii = this.weights.length; i < ii; i++) {\n this.weights[i] += learningRate * influence * (target[i] - this.weights[i]);\n }\n};\n\nNodeSquare.prototype.getDistance = function getDistance(otherNode) {\n return Math.max(Math.abs(this.x - otherNode.x), Math.abs(this.y - otherNode.y));\n};\n\nNodeSquare.prototype.getDistanceTorus = function getDistanceTorus(otherNode) {\n var distX = Math.abs(this.x - otherNode.x),\n distY = Math.abs(this.y - otherNode.y);\n return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY));\n};\n\nNodeSquare.prototype.getNeighbors = function getNeighbors(xy) {\n if (!this.neighbors[xy]) {\n this.neighbors[xy] = new Array(2);\n\n // left or bottom neighbor\n var v;\n if (this[xy] > 0) {\n v = this[xy] - 1;\n } else if (this.som.torus) {\n v = this.som.gridDim[xy] - 1\n }\n if (typeof v !== 'undefined') {\n var x, y;\n if (xy === 'x') {\n x = v;\n y = this.y;\n } else {\n x = this.x;\n y = v;\n }\n this.neighbors[xy][0] = this.som.nodes[x][y];\n }\n\n // top or right neighbor\n var w;\n if (this[xy] < (this.som.gridDim[xy] - 1)) {\n w = this[xy] + 1;\n } else if (this.som.torus) {\n w = 0;\n }\n if (typeof w !== 'undefined') {\n if (xy === 'x') {\n x = w;\n y = this.y;\n } else {\n x = this.x;\n y = w;\n }\n this.neighbors[xy][1] = this.som.nodes[x][y];\n }\n }\n return this.neighbors[xy];\n};\n\nNodeSquare.prototype.getPos = function getPos(xy, element) {\n var neighbors = this.getNeighbors(xy),\n distance = this.som.distance,\n bestNeighbor,\n direction;\n if(neighbors[0]) {\n if (neighbors[1]) {\n var dist1 = distance(element, neighbors[0].weights),\n dist2 = distance(element, neighbors[1].weights);\n if(dist1 < dist2) {\n bestNeighbor = neighbors[0];\n direction = -1;\n } else {\n bestNeighbor = neighbors[1];\n direction = 1;\n }\n } else {\n bestNeighbor = neighbors[0];\n direction = -1;\n }\n } else {\n bestNeighbor = neighbors[1];\n direction = 1;\n }\n var simA = 1 - distance(element, this.weights),\n simB = 1 - distance(element, bestNeighbor.weights);\n var factor = ((simA - simB) / (2 - simA - simB));\n return 0.5 + 0.5 * factor * direction;\n};\n\nNodeSquare.prototype.getPosition = function getPosition(element) {\n return [\n this.getPos('x', element),\n this.getPos('y', element)\n ];\n};\n\nmodule.exports = NodeSquare;","'use strict';\n\nexports.distance = require('./distances');\nexports.similarity = require('./similarities');","'use strict';\n\nmodule.exports = function czekanowskiSimilarity(a, b) {\n var up = 0;\n var down = 0;\n for (var i = 0; i < a.length; i++) {\n up += Math.min(a[i], b[i]);\n down += a[i] + b[i];\n }\n return 2 * up / down;\n};\n","module.exports = function dice(a, b) {\n var ii = a.length,\n p = 0,\n q1 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * a[i];\n q1 += b[i] * b[i];\n q2 += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return q2 / (p + q1);\n};\n","module.exports = function intersection(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.min(a[i], b[i]);\n }\n return 1 - ans;\n};\n","module.exports = function jaccard(a, b) {\n var ii = a.length,\n p1 = 0,\n p2 = 0,\n q1 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p1 += a[i] * b[i];\n p2 += a[i] * a[i];\n q1 += b[i] * b[i];\n q2 += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return q2 / (p2 + q1 - p1);\n};\n","module.exports = function kulczynski(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += Math.min(a[i],b[i]);\n }\n return up / down;\n};\n","module.exports = function motyka(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.min(a[i], b[i]);\n down += a[i] + b[i];\n }\n return 1 - (up / down);\n};\n","module.exports = function squaredChord(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i]));\n }\n return ans;\n};\n","module.exports = function tanimoto(a, b, bitvector) {\n if (bitvector) {\n var inter = 0,\n union = 0;\n for (var j = 0; j < a.length; j++) {\n inter += a[j] && b[j];\n union += a[j] || b[j];\n }\n if (union === 0)\n return 1;\n return inter / union;\n }\n else {\n var ii = a.length,\n p = 0,\n q = 0,\n m = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i];\n q += b[i];\n m += Math.min(a[i],b[i]);\n }\n return 1 - (p + q - 2 * m) / (p + q - m);\n }\n};\n","module.exports = function cosine(a, b) {\n var ii = a.length,\n p = 0,\n p2 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * b[i];\n p2 += a[i] * a[i];\n q2 += b[i] * b[i];\n }\n return p / (Math.sqrt(p2) * Math.sqrt(q2));\n};\n","'use strict';\n\nvar extend = require('extend');\n\nvar defaultOptions = {\n size: 1,\n value: 0\n};\n\n/**\n * Case when the entry is an array\n * @param data\n * @param options\n * @returns {Array}\n */\nfunction arrayCase(data, options) {\n var len = data.length;\n if (typeof options.size === 'number')\n options.size = [options.size, options.size];\n\n var cond = len + options.size[0] + options.size[1];\n\n var output;\n if (options.output) {\n if (options.output.length !== cond)\n throw new RangeError('Wrong output size');\n output = options.output;\n }\n else\n output = new Array(cond);\n\n var i;\n\n // circular option\n if (options.value === 'circular') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[((len - (options.size[0] % len)) + i) % len];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[(i - options.size[0]) % len];\n }\n }\n\n // replicate option\n else if (options.value === 'replicate') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[0];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[len - 1];\n }\n }\n\n // symmetric option\n else if (options.value === 'symmetric') {\n if ((options.size[0] > len) || (options.size[1] > len))\n throw new RangeError('expanded value should not be bigger than the data length');\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[options.size[0] - 1 - i];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[2*len + options.size[0] - i - 1];\n }\n }\n\n // default option\n else {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = options.value;\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = options.value;\n }\n }\n\n return output;\n}\n\n/**\n * Case when the entry is a matrix\n * @param data\n * @param options\n * @returns {Array}\n */\nfunction matrixCase(data, options) {\n var row = data.length;\n var col = data[0].length;\n if (options.size[0] === undefined)\n options.size = [options.size, options.size, options.size, options.size];\n throw new Error('matrix not supported yet, sorry');\n}\n\n/**\n * Pads and array\n * @param {Array } data\n * @param {object} options\n */\nfunction padArray (data, options) {\n options = extend({}, defaultOptions, options);\n\n if (Array.isArray(data)) {\n if (Array.isArray(data[0]))\n return matrixCase(data, options);\n else\n return arrayCase(data, options);\n }\n else\n throw new TypeError('data should be an array');\n}\n\nmodule.exports = padArray;\n","export default function maybeToPrecision(value, digits) {\n if (value < 0) {\n value = 0 - value;\n if (typeof digits === 'number') {\n return '- ' + value.toPrecision(digits);\n } else {\n return '- ' + value.toString();\n }\n } else {\n if (typeof digits === 'number') {\n return value.toPrecision(digits);\n } else {\n return value.toString();\n }\n }\n}\n","export default function checkArraySize(x, y) {\n if (!Array.isArray(x) || !Array.isArray(y)) {\n throw new TypeError('x and y must be arrays');\n }\n if (x.length !== y.length) {\n throw new RangeError('x and y arrays must have the same length');\n }\n}\n","export {default as maybeToPrecision} from './maybeToPrecision';\nexport {default as checkArrayLength} from './checkArrayLength';\n\nexport default class BaseRegression {\n constructor() {\n if (new.target === BaseRegression) {\n throw new Error('BaseRegression must be subclassed');\n }\n }\n\n predict(x) {\n if (typeof x === 'number') {\n return this._predict(x);\n } else if (Array.isArray(x)) {\n const y = new Array(x.length);\n for (let i = 0; i < x.length; i++) {\n y[i] = this._predict(x[i]);\n }\n return y;\n } else {\n throw new TypeError('x must be a number or array');\n }\n }\n\n _predict() {\n throw new Error('_predict must be implemented');\n }\n\n train() {\n //Do nothing for this package\n }\n\n toString() {\n return '';\n }\n\n toLaTeX() {\n return '';\n }\n\n /**\n * Return the correlation coefficient of determination (r) and chi-square.\n * @param {Array} x\n * @param {Array} y\n * @return {object}\n */\n score(x, y) {\n if (!Array.isArray(x) || !Array.isArray(y) || x.length !== y.length) {\n throw new Error('x and y must be arrays of the same length');\n }\n\n const n = x.length;\n const y2 = new Array(n);\n for (let i = 0; i < n; i++) {\n y2[i] = this._predict(x[i]);\n }\n\n let xSum = 0;\n let ySum = 0;\n let chi2 = 0;\n let rmsd = 0;\n let xSquared = 0;\n let ySquared = 0;\n let xY = 0;\n for (let i = 0; i < n; i++) {\n xSum += y2[i];\n ySum += y[i];\n xSquared += y2[i] * y2[i];\n ySquared += y[i] * y[i];\n xY += y2[i] * y[i];\n if (y[i] !== 0) {\n chi2 += (y[i] - y2[i]) * (y[i] - y2[i]) / y[i];\n }\n rmsd = (y[i] - y2[i]) * (y[i] - y2[i]);\n }\n\n const r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum));\n\n return {\n r: r,\n r2: r * r,\n chi2: chi2,\n rmsd: rmsd * rmsd / n\n };\n }\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\n\nexport default class SimpleLinearRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) {\n this.slope = y.slope;\n this.intercept = y.intercept;\n this.coefficients = [y.intercept, y.slope];\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n toJSON() {\n return {\n name: 'simpleLinearRegression',\n slope: this.slope,\n intercept: this.intercept\n };\n }\n\n _predict(x) {\n return this.slope * x + this.intercept;\n }\n\n computeX(y) {\n return (y - this.intercept) / this.slope;\n }\n\n toString(precision) {\n let result = 'f(x) = ';\n if (this.slope !== 0) {\n const xFactor = maybeToPrecision(this.slope, precision);\n result += (xFactor === '1' ? '' : xFactor + ' * ') + 'x';\n if (this.intercept) {\n const absIntercept = Math.abs(this.intercept);\n const operator = absIntercept === this.intercept ? '+' : '-';\n result += ` ${operator} ${maybeToPrecision(absIntercept, precision)}`;\n }\n } else {\n result += maybeToPrecision(this.intercept, precision);\n }\n return result;\n }\n\n toLaTeX(precision) {\n return this.toString(precision);\n }\n\n static load(json) {\n if (json.name !== 'simpleLinearRegression') {\n throw new TypeError('not a SLR model');\n }\n return new SimpleLinearRegression(true, json);\n }\n}\n\nfunction regress(slr, x, y) {\n const n = x.length;\n let xSum = 0;\n let ySum = 0;\n\n let xSquared = 0;\n let xY = 0;\n\n for (let i = 0; i < n; i++) {\n xSum += x[i];\n ySum += y[i];\n xSquared += x[i] * x[i];\n xY += x[i] * y[i];\n }\n\n const numerator = (n * xY - xSum * ySum);\n slr.slope = numerator / (n * xSquared - xSum * xSum);\n slr.intercept = (1 / n) * ySum - slr.slope * (1 / n) * xSum;\n slr.coefficients = [slr.intercept, slr.slope];\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport Matrix, {solve} from 'ml-matrix';\n\nexport default class PolynomialRegression extends BaseRegression {\n constructor(x, y, degree) {\n super();\n if (x === true) {\n this.degree = y.degree;\n this.powers = y.powers;\n this.coefficients = y.coefficients;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y, degree);\n }\n }\n\n _predict(x) {\n let y = 0;\n for (let k = 0; k < this.powers.length; k++) {\n y += this.coefficients[k] * Math.pow(x, this.powers[k]);\n }\n return y;\n }\n\n toJSON() {\n return {\n name: 'polynomialRegression',\n degree: this.degree,\n powers: this.powers,\n coefficients: this.coefficients\n };\n }\n\n toString(precision) {\n return this._toFormula(precision, false);\n }\n\n toLaTeX(precision) {\n return this._toFormula(precision, true);\n }\n\n _toFormula(precision, isLaTeX) {\n let sup = '^';\n let closeSup = '';\n let times = ' * ';\n if (isLaTeX) {\n sup = '^{';\n closeSup = '}';\n times = '';\n }\n\n let fn = '';\n let str = '';\n for (let k = 0; k < this.coefficients.length; k++) {\n str = '';\n if (this.coefficients[k] !== 0) {\n if (this.powers[k] === 0) {\n str = maybeToPrecision(this.coefficients[k], precision);\n } else {\n if (this.powers[k] === 1) {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x';\n } else {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup;\n }\n }\n\n if (this.coefficients[k] > 0 && k !== (this.coefficients.length - 1)) {\n str = ' + ' + str;\n } else if (k !== (this.coefficients.length - 1)) {\n str = ' ' + str;\n }\n }\n fn = str + fn;\n }\n if (fn.charAt(0) === '+') {\n fn = fn.slice(1);\n }\n\n return 'f(x) = ' + fn;\n }\n\n static load(json) {\n if (json.name !== 'polynomialRegression') {\n throw new TypeError('not a polynomial regression model');\n }\n return new PolynomialRegression(true, json);\n }\n}\n\nfunction regress(pr, x, y, degree) {\n const n = x.length;\n let powers;\n if (Array.isArray(degree)) {\n powers = degree;\n degree = powers.length;\n } else {\n degree++;\n powers = new Array(degree);\n for (let k = 0; k < degree; k++) {\n powers[k] = k;\n }\n }\n const F = new Matrix(n, degree);\n const Y = new Matrix([y]);\n for (let k = 0; k < degree; k++) {\n for (let i = 0; i < n; i++) {\n if (powers[k] === 0) {\n F[i][k] = 1;\n } else {\n F[i][k] = Math.pow(x[i], powers[k]);\n }\n }\n }\n\n const FT = F.transposeView();\n const A = FT.mmul(F);\n const B = FT.mmul(Y.transposeView());\n\n pr.degree = degree - 1;\n pr.powers = powers;\n pr.coefficients = solve(A, B).to1DArray();\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport SimpleLinearRegression from 'ml-regression-simple-linear';\n\nexport default class ExponentialRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) {\n this.A = y.A;\n this.B = y.B;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n _predict(input) {\n return this.B * Math.exp(input * this.A);\n }\n\n toJSON() {\n return {\n name: 'exponentialRegression',\n A: this.A,\n B: this.B\n };\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.B, precision) + ' * e^(' + maybeToPrecision(this.A, precision) + ' * x)';\n }\n\n toLaTeX(precision) {\n if (this.A >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.B, precision) + 'e^{' + maybeToPrecision(this.A, precision) + 'x}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.B, precision) + '}{e^{' + maybeToPrecision(-this.A, precision) + 'x}}';\n }\n\n }\n\n static load(json) {\n if (json.name !== 'exponentialRegression') {\n throw new TypeError('not a exponential regression model');\n }\n return new ExponentialRegression(true, json);\n }\n}\n\nfunction regress(er, x, y) {\n const n = x.length;\n const yl = new Array(n);\n for (let i = 0; i < n; i++) {\n yl[i] = Math.log(y[i]);\n }\n\n const linear = new SimpleLinearRegression(x, yl);\n er.A = linear.slope;\n er.B = Math.exp(linear.intercept);\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport SimpleLinearRegression from 'ml-regression-simple-linear';\n\nexport default class PowerRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) { // reloading model\n this.A = y.A;\n this.B = y.B;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n _predict(newInputs) {\n return this.A * Math.pow(newInputs, this.B);\n }\n\n toJSON() {\n return {\n name: 'powerRegression',\n A: this.A,\n B: this.B\n };\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + maybeToPrecision(this.B, precision);\n }\n\n toLaTeX(precision) {\n if (this.B >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + maybeToPrecision(this.B, precision) + '}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + maybeToPrecision(-this.B, precision) + '}}';\n }\n }\n\n static load(json) {\n if (json.name !== 'powerRegression') {\n throw new TypeError('not a power regression model');\n }\n return new PowerRegression(true, json);\n }\n}\n\nfunction regress(pr, x, y) {\n const n = x.length;\n const xl = new Array(n);\n const yl = new Array(n);\n for (let i = 0; i < n; i++) {\n xl[i] = Math.log(x[i]);\n yl[i] = Math.log(y[i]);\n }\n\n const linear = new SimpleLinearRegression(xl, yl);\n pr.A = Math.exp(linear.intercept);\n pr.B = linear.slope;\n}\n","import Matrix, { SVD } from 'ml-matrix';\nimport BaseRegression from 'ml-regression-base';\n\nexport default class MultivariateLinearRegression extends BaseRegression {\n constructor(x, y, options = {}) {\n const { intercept = true, statistics = true } = options;\n super();\n this.statistics = statistics;\n if (x === true) {\n this.weights = y.weights;\n this.inputs = y.inputs;\n this.outputs = y.outputs;\n this.intercept = y.intercept;\n } else {\n x = new Matrix(x);\n if (intercept) {\n x.addColumn(new Array(x.length).fill(1));\n }\n const beta = new SVD(x, { autoTranspose: true }).solve(y);\n this.weights = beta.to2DArray();\n this.inputs = x[0].length;\n this.outputs = y[0].length;\n if (intercept) this.inputs--;\n this.intercept = intercept;\n if (statistics) {\n /*\n * Let's add some basic statistics about the beta's to be able to interpret them.\n * source: http://dept.stat.lsa.umich.edu/~kshedden/Courses/Stat401/Notes/401-multreg.pdf\n * validated against Excel Regression AddIn\n * test: \"datamining statistics test\"\n */\n const fittedValues = x.mmul(beta);\n const residuals = new Matrix(y).addM(fittedValues.neg());\n const variance =\n residuals\n .to2DArray()\n .map((ri) => Math.pow(ri[0], 2))\n .reduce((a, b) => a + b) /\n (y.length - x.columns);\n this.stdError = Math.sqrt(variance);\n this.stdErrorMatrix = x\n .transposeView()\n .mmul(x)\n .pseudoInverse()\n .mul(variance);\n this.stdErrors = this.stdErrorMatrix.diagonal().map((d) => Math.sqrt(d));\n this.tStats = this.weights.map(\n (d, i) => (this.stdErrors[i] === 0 ? 0 : d[0] / this.stdErrors[i])\n );\n }\n }\n }\n\n predict(x) {\n if (Array.isArray(x)) {\n if (typeof x[0] === 'number') {\n return this._predict(x);\n } else if (Array.isArray(x[0])) {\n const y = new Array(x.length);\n for (let i = 0; i < x.length; i++) {\n y[i] = this._predict(x[i]);\n }\n return y;\n }\n }\n throw new TypeError('x must be a matrix or array of numbers');\n }\n\n _predict(x) {\n const result = new Array(this.outputs);\n if (this.intercept) {\n for (let i = 0; i < this.outputs; i++) {\n result[i] = this.weights[this.inputs][i];\n }\n } else {\n result.fill(0);\n }\n for (let i = 0; i < this.inputs; i++) {\n for (let j = 0; j < this.outputs; j++) {\n result[j] += this.weights[i][j] * x[i];\n }\n }\n return result;\n }\n\n score() {\n throw new Error('score method is not implemented yet');\n }\n\n toJSON() {\n return {\n name: 'multivariateLinearRegression',\n weights: this.weights,\n inputs: this.inputs,\n outputs: this.outputs,\n intercept: this.intercept,\n summary: (this.statistics)\n ? {\n regressionStatistics: {\n standardError: this.stdError,\n observations: this.outputs\n },\n variables: this.weights.map((d, i) => {\n return {\n label:\n i === this.weights.length - 1\n ? 'Intercept'\n : `X Variable ${i + 1}`,\n coefficients: d,\n standardError: this.stdErrors[i],\n tStat: this.tStats[i]\n };\n })\n }\n : undefined,\n };\n }\n\n static load(model) {\n if (model.name !== 'multivariateLinearRegression') {\n throw new Error('not a MLR model');\n }\n return new MultivariateLinearRegression(true, model);\n }\n}\n","import {maybeToPrecision} from 'ml-regression-base';\nimport PolynomialRegression from 'ml-regression-polynomial';\nimport BaseRegression from 'ml-regression-base';\n\n/*\n * Function that calculate the potential fit in the form f(x) = A*x^M\n * with a given M and return de A coefficient.\n *\n * @param {Vector} X - Vector of the x positions of the points.\n * @param {Vector} Y - Vector of the x positions of the points.\n * @param {Number} M - The exponent of the potential fit.\n * @return {Number} A - The A coefficient of the potential fit.\n */\nexport default class PotentialRegression extends BaseRegression {\n /**\n * @constructor\n * @param x: Independent variable\n * @param y: Dependent variable\n * @param M\n */\n constructor(x, y, M) {\n super();\n if (x === true) { // reloading model\n this.A = y.A;\n this.M = y.M;\n } else {\n var n = x.length;\n if (n !== y.length) {\n throw new RangeError('input and output array have a different length');\n }\n\n var linear = new PolynomialRegression(x, y, [M]);\n this.A = linear.coefficients[0];\n this.M = M;\n }\n }\n\n _predict(x) {\n return this.A * Math.pow(x, this.M);\n }\n\n toJSON() {\n return {\n name: 'potentialRegression',\n A: this.A,\n M: this.M\n };\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + this.M;\n }\n\n toLaTeX(precision) {\n if (this.M >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + this.M + '}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + (-this.M) + '}}';\n }\n }\n\n static load(json) {\n if (json.name !== 'potentialRegression') {\n throw new TypeError('not a potential regression model');\n }\n return new PotentialRegression(true, json);\n }\n}\n","import {Matrix, solve} from 'ml-matrix';\nimport Kernel from 'ml-kernel';\n\nimport BaseRegression from 'ml-regression-base';\n\nconst defaultOptions = {\n lambda: 0.1,\n kernelType: 'gaussian',\n kernelOptions: {},\n computeCoefficient: false\n};\n\n// Implements the Kernel ridge regression algorithm.\n// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf\nexport default class KernelRidgeRegression extends BaseRegression {\n constructor(inputs, outputs, options) {\n super();\n if (inputs === true) { // reloading model\n this.alpha = outputs.alpha;\n this.inputs = outputs.inputs;\n this.kernelType = outputs.kernelType;\n this.kernelOptions = outputs.kernelOptions;\n this.kernel = new Kernel(outputs.kernelType, outputs.kernelOptions);\n } else {\n options = Object.assign({}, defaultOptions, options);\n\n const kernelFunction = new Kernel(options.kernelType, options.kernelOptions);\n const K = kernelFunction.compute(inputs);\n const n = inputs.length;\n K.add(Matrix.eye(n, n).mul(options.lambda));\n\n this.alpha = solve(K, outputs);\n this.inputs = inputs;\n this.kernelType = options.kernelType;\n this.kernelOptions = options.kernelOptions;\n this.kernel = kernelFunction;\n }\n }\n\n _predict(newInputs) {\n return this.kernel.compute([newInputs], this.inputs).mmul(this.alpha)[0];\n }\n\n toJSON() {\n return {\n name: 'kernelRidgeRegression',\n alpha: this.alpha,\n inputs: this.inputs,\n kernelType: this.kernelType,\n kernelOptions: this.kernelOptions\n };\n }\n\n static load(json) {\n if (json.name !== 'kernelRidgeRegression') {\n throw new TypeError('not a KRR model');\n }\n return new KernelRidgeRegression(true, json);\n }\n}\n","import {Matrix, SVD} from 'ml-matrix';\nimport BaseRegression from 'ml-regression-base';\n\nconst defaultOptions = {\n order: 2\n};\n// Implements the Kernel ridge regression algorithm.\n// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf\nexport default class PolynomialFitRegression2D extends BaseRegression {\n /**\n * Constructor for the 2D polynomial fitting\n *\n * @param inputs\n * @param outputs\n * @param options\n * @constructor\n */\n constructor(inputs, outputs, options) {\n super();\n if (inputs === true) { // reloading model\n this.coefficients = Matrix.columnVector(outputs.coefficients);\n this.order = outputs.order;\n if (outputs.r) {\n this.r = outputs.r;\n this.r2 = outputs.r2;\n }\n if (outputs.chi2) {\n this.chi2 = outputs.chi2;\n }\n } else {\n options = Object.assign({}, defaultOptions, options);\n this.order = options.order;\n this.coefficients = [];\n this.X = inputs;\n this.y = outputs;\n\n this.train(this.X, this.y, options);\n }\n }\n\n /**\n * Function that fits the model given the data(X) and predictions(y).\n * The third argument is an object with the following options:\n * * order: order of the polynomial to fit.\n *\n * @param {Matrix} X - A matrix with n rows and 2 columns.\n * @param {Matrix} y - A vector of the prediction values.\n */\n train(X, y) {\n if (!Matrix.isMatrix(X)) X = new Matrix(X);\n if (!Matrix.isMatrix(y)) y = Matrix.columnVector(y);\n\n if (y.rows !== X.rows) {\n y = y.transpose();\n }\n\n if (X.columns !== 2) {\n throw new RangeError('You give X with ' + X.columns + ' columns and it must be 2');\n }\n if (X.rows !== y.rows) {\n throw new RangeError('X and y must have the same rows');\n }\n\n var examples = X.rows;\n var coefficients = ((this.order + 2) * (this.order + 1)) / 2;\n this.coefficients = new Array(coefficients);\n\n var x1 = X.getColumnVector(0);\n var x2 = X.getColumnVector(1);\n\n var scaleX1 = 1.0 / x1.clone().apply(abs).max();\n var scaleX2 = 1.0 / x2.clone().apply(abs).max();\n var scaleY = 1.0 / y.clone().apply(abs).max();\n\n x1.mulColumn(0, scaleX1);\n x2.mulColumn(0, scaleX2);\n y.mulColumn(0, scaleY);\n\n var A = new Matrix(examples, coefficients);\n var col = 0;\n\n for (var i = 0; i <= this.order; ++i) {\n var limit = this.order - i;\n for (var j = 0; j <= limit; ++j) {\n var result = powColVector(x1, i).mulColumnVector(powColVector(x2, j));\n A.setColumn(col, result);\n col++;\n }\n }\n\n var svd = new SVD(A.transpose(), {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: true,\n autoTranspose: false\n });\n\n var qqs = Matrix.rowVector(svd.diagonal);\n qqs = qqs.apply(function (i, j) {\n if (this[i][j] >= 1e-15) this[i][j] = 1 / this[i][j];\n else this[i][j] = 0;\n });\n\n var qqs1 = Matrix.zeros(examples, coefficients);\n for (i = 0; i < coefficients; ++i) {\n qqs1[i][i] = qqs[0][i];\n }\n\n qqs = qqs1;\n\n var U = svd.rightSingularVectors;\n var V = svd.leftSingularVectors;\n\n this.coefficients = V.mmul(qqs.transpose()).mmul(U.transpose()).mmul(y);\n\n col = 0;\n\n for (i = 0; i <= coefficients; ++i) {\n limit = this.order - i;\n for (j = 0; j <= limit; ++j) {\n this.coefficients[col][0] = (this.coefficients[col][0] * Math.pow(scaleX1, i) * Math.pow(scaleX2, j)) / scaleY;\n col++;\n }\n }\n }\n\n _predict(newInputs) {\n var x1 = newInputs[0];\n var x2 = newInputs[1];\n\n var y = 0;\n var column = 0;\n\n for (var i = 0; i <= this.order; i++) {\n for (var j = 0; j <= this.order - i; j++) {\n y += Math.pow(x1, i) * (Math.pow(x2, j)) * this.coefficients[column][0];\n column++;\n }\n }\n\n return y;\n }\n\n toJSON() {\n return {\n name: 'polyfit2D',\n order: this.order,\n coefficients: this.coefficients\n };\n }\n\n static load(json) {\n if (json.name !== 'polyfit2D') {\n throw new TypeError('not a polyfit2D model');\n }\n return new PolynomialFitRegression2D(true, json);\n }\n}\n\n/**\n * Function that given a column vector return this: vector^power\n *\n * @param x - Column vector.\n * @param power - Pow number.\n * @return {Suite|Matrix}\n */\nfunction powColVector(x, power) {\n var result = x.clone();\n for (var i = 0; i < x.rows; ++i) {\n result[i][0] = Math.pow(result[i][0], power);\n }\n return result;\n}\n\n/**\n * Function to use in the apply method to get the absolute value\n * of each element of the matrix\n *\n * @param i - current row.\n * @param j - current column.\n */\nfunction abs(i, j) {\n this[i][j] = Math.abs(this[i][j]);\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport {array} from 'ml-stat';\nconst median = array.median;\n\nexport default class TheilSenRegression extends BaseRegression {\n\n /**\n * Theil–Sen estimator\n * https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator\n * @param {Array|boolean} x\n * @param {Array|object} y\n * @constructor\n */\n constructor(x, y) {\n super();\n if (x === true) {\n // loads the model\n this.slope = y.slope;\n this.intercept = y.intercept;\n this.coefficients = y.coefficients;\n } else {\n // creates the model\n checkArrayLength(x, y);\n theilSen(this, x, y);\n }\n\n }\n\n toJSON() {\n return {\n name: 'TheilSenRegression',\n slope: this.slope,\n intercept: this.intercept\n };\n }\n\n _predict(input) {\n return this.slope * input + this.intercept;\n }\n\n computeX(input) {\n return (input - this.intercept) / this.slope;\n }\n\n toString(precision) {\n var result = 'f(x) = ';\n if (this.slope) {\n var xFactor = maybeToPrecision(this.slope, precision);\n result += (Math.abs(xFactor - 1) < 1e-5 ? '' : xFactor + ' * ') + 'x';\n if (this.intercept) {\n var absIntercept = Math.abs(this.intercept);\n var operator = absIntercept === this.intercept ? '+' : '-';\n result += ' ' + operator + ' ' + maybeToPrecision(absIntercept, precision);\n }\n } else {\n result += maybeToPrecision(this.intercept, precision);\n }\n return result;\n }\n\n toLaTeX(precision) {\n return this.toString(precision);\n }\n\n static load(json) {\n if (json.name !== 'TheilSenRegression') {\n throw new TypeError('not a Theil-Sen model');\n }\n return new TheilSenRegression(true, json);\n }\n}\n\nfunction theilSen(regression, x, y) {\n let len = x.length;\n let slopes = new Array(len * len);\n let count = 0;\n for (let i = 0; i < len; ++i) {\n for (let j = i + 1; j < len; ++j) {\n if (x[i] !== x[j]) {\n slopes[count++] = (y[j] - y[i]) / (x[j] - x[i]);\n }\n }\n }\n slopes.length = count;\n let medianSlope = median(slopes);\n\n let cuts = new Array(len);\n for (let i = 0; i < len; ++i) {\n cuts[i] = y[i] - medianSlope * x[i];\n }\n\n regression.slope = medianSlope;\n regression.intercept = median(cuts);\n regression.coefficients = [regression.intercept, regression.slope];\n}\n","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport {solve} from 'ml-matrix';\n\nexport default class RobustPolynomialRegression extends BaseRegression {\n constructor(x, y, degree) {\n super();\n if (x === true) {\n this.degree = y.degree;\n this.powers = y.powers;\n this.coefficients = y.coefficients;\n } else {\n checkArrayLength(x, y);\n robustPolynomial(this, x, y, degree);\n }\n }\n\n toJSON() {\n return {\n name: 'robustPolynomialRegression',\n degree: this.degree,\n powers: this.powers,\n coefficients: this.coefficients\n };\n }\n\n _predict(x) {\n return predict(x, this.powers, this.coefficients);\n }\n\n toString(precision) {\n return this._toFormula(precision, false);\n }\n\n toLaTeX(precision) {\n return this._toFormula(precision, true);\n }\n\n _toFormula(precision, isLaTeX) {\n let sup = '^';\n let closeSup = '';\n let times = ' * ';\n if (isLaTeX) {\n sup = '^{';\n closeSup = '}';\n times = '';\n }\n\n let fn = '';\n let str = '';\n for (let k = 0; k < this.coefficients.length; k++) {\n str = '';\n if (this.coefficients[k] !== 0) {\n if (this.powers[k] === 0) {\n str = maybeToPrecision(this.coefficients[k], precision);\n } else {\n if (this.powers[k] === 1) {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x';\n } else {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup;\n }\n }\n\n if (this.coefficients[k] > 0 && k !== (this.coefficients.length - 1)) {\n str = ' + ' + str;\n } else if (k !== (this.coefficients.length - 1)) {\n str = ' ' + str;\n }\n }\n fn = str + fn;\n }\n if (fn.charAt(0) === '+') {\n fn = fn.slice(1);\n }\n\n return 'f(x) = ' + fn;\n }\n\n static load(json) {\n if (json.name !== 'robustPolynomialRegression') {\n throw new TypeError('not a RobustPolynomialRegression model');\n }\n return new RobustPolynomialRegression(true, json);\n }\n}\n\nfunction robustPolynomial(regression, x, y, degree) {\n let powers = new Array(degree);\n for (let k = 0; k < degree; k++) {\n powers[k] = k;\n }\n\n const tuples = getRandomTuples(x, y, degree);\n var min;\n\n for (var i = 0; i < tuples.length; i++) {\n var tuple = tuples[i];\n var coefficients = calcCoefficients(tuple, powers);\n\n var residuals = x.slice();\n for (var j = 0; j < x.length; j++) {\n residuals[j] = y[j] - predict(x[j], powers, coefficients);\n residuals[j] = {\n residual: residuals[j] * residuals[j],\n coefficients\n };\n }\n\n var median = residualsMedian(residuals);\n if (!min || median.residual < min.residual) {\n min = median;\n }\n }\n\n regression.degree = degree;\n regression.powers = powers;\n regression.coefficients = min.coefficients;\n}\n\n/**\n * @ignore\n * @param {Array} x\n * @param {Array} y\n * @param {number} degree\n * @return {Array<{x:number,y:number}>}\n */\nfunction getRandomTuples(x, y, degree) {\n var len = Math.floor(x.length / degree);\n var tuples = new Array(len);\n\n for (var i = 0; i < x.length; i++) {\n var pos = Math.floor(Math.random() * len);\n\n var counter = 0;\n while (counter < x.length) {\n if (!tuples[pos]) {\n tuples[pos] = [{\n x: x[i],\n y: y[i]\n }];\n break;\n } else if (tuples[pos].length < degree) {\n tuples[pos].push({\n x: x[i],\n y: y[i]\n });\n break;\n } else {\n counter++;\n pos = (pos + 1) % len;\n }\n }\n\n if (counter === x.length) {\n return tuples;\n }\n }\n return tuples;\n}\n\n/**\n * @ignore\n * @param {{x:number,y:number}} tuple\n * @param {Array} powers\n * @return {Array}\n */\nfunction calcCoefficients(tuple, powers) {\n var X = tuple.slice();\n var Y = tuple.slice();\n for (var i = 0; i < X.length; i++) {\n Y[i] = [tuple[i].y];\n X[i] = new Array(powers.length);\n for (var j = 0; j < powers.length; j++) {\n X[i][j] = Math.pow(tuple[i].x, powers[j]);\n }\n }\n\n return solve(X, Y).to1DArray();\n}\n\nfunction predict(x, powers, coefficients) {\n let y = 0;\n for (let k = 0; k < powers.length; k++) {\n y += coefficients[k] * Math.pow(x, powers[k]);\n }\n return y;\n}\n\nfunction residualsMedian(residuals) {\n residuals.sort((a, b) => a.residual - b.residual);\n\n var l = residuals.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return residuals[half - 1];\n } else {\n return residuals[half];\n }\n}\n","export {default as SimpleLinearRegression, default as SLR} from 'ml-regression-simple-linear';\nexport {default as PolynomialRegression} from 'ml-regression-polynomial';\nexport {default as ExponentialRegression} from 'ml-regression-exponential';\nexport {default as PowerRegression} from 'ml-regression-power';\nexport {default as MultivariateLinearRegression} from 'ml-regression-multivariate-linear';\n\nimport PotentialRegression from './regression/potential-regression';\nconst NLR = {\n PotentialRegression\n};\nexport {NLR, NLR as NonLinearRegression};\n\nexport {default as KernelRidgeRegression, default as KRR} from './regression/kernel-ridge-regression';\nexport {default as PolinomialFitting2D} from './regression/poly-fit-regression2d';\n\n// robust regressions\nexport {default as TheilSenRegression} from 'ml-regression-theil-sen';\nexport {default as RobustPolynomialRegression} from 'ml-regression-robust-polynomial';\n","(function(){function a(d){for(var e=0,f=d.length-1,g=void 0,h=void 0,i=void 0,j=c(e,f);!0;){if(f<=e)return d[j];if(f==e+1)return d[e]>d[f]&&b(d,e,f),d[j];for(g=c(e,f),d[g]>d[f]&&b(d,g,f),d[e]>d[f]&&b(d,e,f),d[g]>d[e]&&b(d,g,e),b(d,g,e+1),h=e+1,i=f;!0;){do h++;while(d[e]>d[h]);do i--;while(d[i]>d[e]);if(i=j&&(f=i-1)}}var b=function b(d,e,f){var _ref;return _ref=[d[f],d[e]],d[e]=_ref[0],d[f]=_ref[1],_ref},c=function c(d,e){return~~((d+e)/2)};'undefined'!=typeof module&&module.exports?module.exports=a:window.median=a})();\n","'use strict';\n\nconst mlCart = require('ml-cart');\nconst mlRandomForest = require('ml-random-forest');\n\nconst ML = exports;\n\n// Try to keep this list in the same structure as the README.\n\n// Unsupervised learning\nML.PCA = require('ml-pca');\nML.HClust = require('ml-hclust');\nML.KMeans = require('ml-kmeans');\n\n// Supervised learning\nML.SVM = require('ml-svm');\nML.NaiveBayes = require('ml-naivebayes');\nML.KNN = require('ml-knn');\nML.PLS = require('ml-pls');\nML.CrossValidation = require('ml-cross-validation');\nML.ConfusionMatrix = require('ml-confusion-matrix');\nML.DecisionTreeClassifier = mlCart.DecisionTreeClassifier;\nML.RandomForestClassifier = mlRandomForest.RandomForestClassifier;\n\n// Artificial neural networks\nML.FNN = require('ml-fnn');\nML.SOM = require('ml-som');\n\n// Regression\nconst Regression = require('ml-regression');\nML.SimpleLinearRegression = Regression.SimpleLinearRegression;\nML.PolynomialRegression = Regression.PolynomialRegression;\nML.MultivariateLinearRegression = Regression.MultivariateLinearRegression;\nML.PowerRegression = Regression.PowerRegression;\nML.ExponentialRegression = Regression.ExponentialRegression;\nML.TheilSenRegression = Regression.TheilSenRegression;\nML.RobustPolynomialRegression = Regression.RobustPolynomialRegression;\nML.DecisionTreeRegression = mlCart.DecisionTreeRegression;\nML.RandomForestRegression = mlRandomForest.RandomForestRegression;\n\n// Optimization\nML.levenbergMarquardt = require('ml-levenberg-marquardt');\n\n// Math\nconst Matrix = require('ml-matrix');\nML.Matrix = Matrix.Matrix;\nML.SVD = Matrix.SVD;\nML.EVD = Matrix.EVD;\nML.CholeskyDecomposition = Matrix.CholeskyDecomposition;\nML.LuDecomposition = Matrix.LuDecomposition;\nML.QrDecomposition = Matrix.QrDecomposition;\n\nML.SparseMatrix = require('ml-sparse-matrix');\nML.Kernel = require('ml-kernel');\nML.Distance = require('ml-distance').distance;\nML.Similarity = require('ml-distance').similarity;\nML.distanceMatrix = require('ml-distance-matrix');\nML.XSadd = require('ml-xsadd').default;\n\n// Statistics\nML.Performance = require('ml-performance');\n\n// Data preprocessing\nML.savitzkyGolay = require('ml-savitzky-golay');\nML.savitzkyGolayGeneralized = require('ml-savitzky-golay-generalized');\n\n// Utility\nML.BitArray = require('ml-bit-array');\nML.HashTable = require('ml-hash-table');\nML.padArray = require('ml-pad-array');\nML.binarySearch = require('binary-search');\nML.numSort = require('num-sort');\nML.Random = require('ml-random').default;\n\n// Undocumented/deprecated packages\nML.ArrayUtils = require('ml-array-utils');\nML.Regression = require('ml-regression');\nML.MatrixUtil = require('ml-matrix');\nML.ArrayStat = require('ml-stat').array;\nML.MatrixStat = require('ml-stat').matrix;\n\nML.Array = {\n min: require('ml-array-min').default,\n max: require('ml-array-max').default,\n median: require('ml-array-median').default,\n mean: require('ml-array-mean').default,\n mode: require('ml-array-mode').default,\n normed: require('ml-array-normed').default,\n rescale: require('ml-array-rescale').default,\n sequentialFill: require('ml-array-sequential-fill').default,\n standardDeviation: require('ml-array-standard-deviation').default,\n variance: require('ml-array-variance').default\n};\n\nML.ArrayXY = {\n centroidsMerge: require('ml-array-xy-centroids-merge').default,\n closestX: require('ml-arrayxy-closestx').default,\n maxMerge: require('ml-array-xy-max-merge').default,\n maxY: require('ml-array-xy-max-y').default,\n sortX: require('ml-array-xy-sort-x').default,\n uniqueX: require('ml-arrayxy-uniquex').default,\n weightedMerge: require('ml-array-xy-weighted-merge').default,\n equallySpaced: require('ml-array-xy-equally-spaced').default,\n filterX: require('ml-array-xy-filter-x').default\n};\n","'use strict';\n\nconst matrixLib = require('ml-matrix');\nconst Matrix = matrixLib.Matrix;\nconst EVD = matrixLib.EVD;\nconst SVD = matrixLib.SVD;\nconst Stat = require('ml-stat/matrix');\nconst mean = Stat.mean;\nconst stdev = Stat.standardDeviation;\n\nconst defaultOptions = {\n isCovarianceMatrix: false,\n center: true,\n scale: false\n};\n\n/**\n * Creates new PCA (Principal Component Analysis) from the dataset\n * @param {Matrix} dataset - dataset or covariance matrix\n * @param {Object} options\n * @param {boolean} [options.isCovarianceMatrix=false] - true if the dataset is a covariance matrix\n * @param {boolean} [options.center=true] - should the data be centered (subtract the mean)\n * @param {boolean} [options.scale=false] - should the data be scaled (divide by the standard deviation)\n * */\nclass PCA {\n constructor(dataset, options) {\n if (dataset === true) {\n const model = options;\n this.center = model.center;\n this.scale = model.scale;\n this.means = model.means;\n this.stdevs = model.stdevs;\n this.U = Matrix.checkMatrix(model.U);\n this.S = model.S;\n return;\n }\n\n options = Object.assign({}, defaultOptions, options);\n\n this.center = false;\n this.scale = false;\n this.means = null;\n this.stdevs = null;\n\n if (options.isCovarianceMatrix) { // user provided a covariance matrix instead of dataset\n this._computeFromCovarianceMatrix(dataset);\n return;\n }\n\n var useCovarianceMatrix;\n if (typeof options.useCovarianceMatrix === 'boolean') {\n useCovarianceMatrix = options.useCovarianceMatrix;\n } else {\n useCovarianceMatrix = dataset.length > dataset[0].length;\n }\n\n if (useCovarianceMatrix) { // user provided a dataset but wants us to compute and use the covariance matrix\n dataset = this._adjust(dataset, options);\n const covarianceMatrix = dataset.transposeView().mmul(dataset).div(dataset.rows - 1);\n this._computeFromCovarianceMatrix(covarianceMatrix);\n } else {\n dataset = this._adjust(dataset, options);\n var svd = new SVD(dataset, {\n computeLeftSingularVectors: false,\n computeRightSingularVectors: true,\n autoTranspose: true\n });\n\n this.U = svd.rightSingularVectors;\n\n const singularValues = svd.diagonal;\n const eigenvalues = new Array(singularValues.length);\n for (var i = 0; i < singularValues.length; i++) {\n eigenvalues[i] = singularValues[i] * singularValues[i] / (dataset.length - 1);\n }\n this.S = eigenvalues;\n }\n }\n\n /**\n * Load a PCA model from JSON\n * @param {Object} model\n * @return {PCA}\n */\n static load(model) {\n if (model.name !== 'PCA')\n throw new RangeError('Invalid model: ' + model.name);\n return new PCA(true, model);\n }\n\n\n /**\n * Project the dataset into the PCA space\n * @param {Matrix} dataset\n * @param {Object} options\n * @return {Matrix} dataset projected in the PCA space\n */\n predict(dataset, options = {}) {\n const {\n nComponents = this.U.columns\n } = options;\n\n dataset = new Matrix(dataset);\n if (this.center) {\n dataset.subRowVector(this.means);\n if (this.scale) {\n dataset.divRowVector(this.stdevs);\n }\n }\n\n var predictions = dataset.mmul(this.U);\n return predictions.subMatrix(0, predictions.rows - 1, 0, nComponents - 1);\n }\n\n /**\n * Returns the proportion of variance for each component\n * @return {[number]}\n */\n getExplainedVariance() {\n var sum = 0;\n for (var i = 0; i < this.S.length; i++) {\n sum += this.S[i];\n }\n return this.S.map(value => value / sum);\n }\n\n /**\n * Returns the cumulative proportion of variance\n * @return {[number]}\n */\n getCumulativeVariance() {\n var explained = this.getExplainedVariance();\n for (var i = 1; i < explained.length; i++) {\n explained[i] += explained[i - 1];\n }\n return explained;\n }\n\n /**\n * Returns the Eigenvectors of the covariance matrix\n * @returns {Matrix}\n */\n getEigenvectors() {\n return this.U;\n }\n\n /**\n * Returns the Eigenvalues (on the diagonal)\n * @returns {[number]}\n */\n getEigenvalues() {\n return this.S;\n }\n\n /**\n * Returns the standard deviations of the principal components\n * @returns {[number]}\n */\n getStandardDeviations() {\n return this.S.map(x => Math.sqrt(x));\n }\n\n /**\n * Returns the loadings matrix\n * @return {Matrix}\n */\n getLoadings() {\n return this.U.transpose();\n }\n\n /**\n * Export the current model to a JSON object\n * @return {Object} model\n */\n toJSON() {\n return {\n name: 'PCA',\n center: this.center,\n scale: this.scale,\n means: this.means,\n stdevs: this.stdevs,\n U: this.U,\n S: this.S,\n };\n }\n\n _adjust(dataset, options) {\n this.center = !!options.center;\n this.scale = !!options.scale;\n\n dataset = new Matrix(dataset);\n\n if (this.center) {\n const means = mean(dataset);\n const stdevs = this.scale ? stdev(dataset, means, true) : null;\n this.means = means;\n dataset.subRowVector(means);\n if (this.scale) {\n for (var i = 0; i < stdevs.length; i++) {\n if (stdevs[i] === 0) {\n throw new RangeError('Cannot scale the dataset (standard deviation is zero at index ' + i);\n }\n }\n this.stdevs = stdevs;\n dataset.divRowVector(stdevs);\n }\n }\n\n return dataset;\n }\n\n _computeFromCovarianceMatrix(dataset) {\n const evd = new EVD(dataset, {assumeSymmetric: true});\n this.U = evd.eigenvectorMatrix;\n for (var i = 0; i < this.U.length; i++) {\n this.U[i].reverse();\n }\n this.S = evd.realEigenvalues.reverse();\n }\n}\n\nmodule.exports = PCA;\n","'use strict';\n\nexports.agnes = require('./agnes');\nexports.diana = require('./diana');\n//exports.birch = require('./birch');\n//exports.cure = require('./cure');\n//exports.chameleon = require('./chameleon');\n","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\nconst ClusterLeaf = require('./ClusterLeaf');\nconst Cluster = require('./Cluster');\nconst distanceMatrix = require('ml-distance-matrix');\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction simpleLink(cluster1, cluster2, disFun) {\n var m = 10e100;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n var d = disFun[cluster1[i]][ cluster2[j]];\n m = Math.min(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction completeLink(cluster1, cluster2, disFun) {\n var m = -1;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n var d = disFun[cluster1[i]][ cluster2[j]];\n m = Math.max(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction averageLink(cluster1, cluster2, disFun) {\n var m = 0;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n m += disFun[cluster1[i]][ cluster2[j]];\n }\n }\n return m / (cluster1.length * cluster2.length);\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {*}\n */\nfunction centroidLink(cluster1, cluster2, disFun) {\n var dist = new Array(cluster1.length * cluster2.length);\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n dist[i * cluster2.length + j] = (disFun[cluster1[i]][ cluster2[j]]);\n }\n }\n return median(dist);\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction wardLink(cluster1, cluster2, disFun) {\n return centroidLink(cluster1, cluster2, disFun)\n * cluster1.length * cluster2.length / (cluster1.length + cluster2.length);\n}\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nfunction median(values, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return (values[half - 1] + values[half]) * 0.5;\n } else {\n return values[half];\n }\n}\n\nvar defaultOptions = {\n disFunc: euclidean,\n kind: 'single',\n isDistanceMatrix: false\n\n};\n\n/**\n * Continuously merge nodes that have the least dissimilarity\n * @param {Array >} distance - Array of points to be clustered\n * @param {json} options\n * @option isDistanceMatrix: Is the input a distance matrix?\n * @constructor\n */\nfunction agnes(data, options) {\n options = Object.assign({}, defaultOptions, options);\n var len = data.length;\n var distance = data;//If source\n if (!options.isDistanceMatrix) {\n distance = distanceMatrix(data, options.disFunc);\n }\n\n\n // allows to use a string or a given function\n if (typeof options.kind === 'string') {\n switch (options.kind) {\n case 'single':\n options.kind = simpleLink;\n break;\n case 'complete':\n options.kind = completeLink;\n break;\n case 'average':\n options.kind = averageLink;\n break;\n case 'centroid':\n options.kind = centroidLink;\n break;\n case 'ward':\n options.kind = wardLink;\n break;\n default:\n throw new RangeError('Unknown kind of similarity');\n }\n } else if (typeof options.kind !== 'function') {\n throw new TypeError('Undefined kind of similarity');\n }\n\n var list = new Array(len);\n for (var i = 0; i < distance.length; i++) {\n list[i] = new ClusterLeaf(i);\n }\n var min = 10e5,\n d = {},\n dis = 0;\n\n while (list.length > 1) {\n // calculates the minimum distance\n d = {};\n min = 10e5;\n for (var j = 0; j < list.length; j++) {\n for (var k = j + 1; k < list.length; k++) {\n var fdistance, sdistance;\n if (list[j] instanceof ClusterLeaf) {\n fdistance = [list[j].index];\n } else {\n fdistance = new Array(list[j].index.length);\n for (var e = 0; e < fdistance.length; e++) {\n fdistance[e] = list[j].index[e].index;\n }\n }\n if (list[k] instanceof ClusterLeaf) {\n sdistance = [list[k].index];\n } else {\n sdistance = new Array(list[k].index.length);\n for (var f = 0; f < sdistance.length; f++) {\n sdistance[f] = list[k].index[f].index;\n }\n }\n dis = options.kind(fdistance, sdistance, distance).toFixed(4);\n if (dis in d) {\n d[dis].push([list[j], list[k]]);\n } else {\n d[dis] = [[list[j], list[k]]];\n }\n min = Math.min(dis, min);\n }\n }\n // cluster dots\n var dmin = d[min.toFixed(4)];\n var clustered = new Array(dmin.length);\n var aux,\n count = 0;\n while (dmin.length > 0) {\n aux = dmin.shift();\n for (var q = 0; q < dmin.length; q++) {\n var int = dmin[q].filter(function (n) {\n //noinspection JSReferencingMutableVariableFromClosure\n return aux.indexOf(n) !== -1;\n });\n if (int.length > 0) {\n var diff = dmin[q].filter(function (n) {\n //noinspection JSReferencingMutableVariableFromClosure\n return aux.indexOf(n) === -1;\n });\n aux = aux.concat(diff);\n dmin.splice(q--, 1);\n }\n }\n clustered[count++] = aux;\n }\n clustered.length = count;\n\n for (var ii = 0; ii < clustered.length; ii++) {\n var obj = new Cluster();\n obj.children = clustered[ii].concat();\n obj.distance = min;\n obj.index = new Array(len);\n var indCount = 0;\n for (var jj = 0; jj < clustered[ii].length; jj++) {\n if (clustered[ii][jj] instanceof ClusterLeaf) {\n obj.index[indCount++] = clustered[ii][jj];\n } else {\n indCount += clustered[ii][jj].index.length;\n obj.index = clustered[ii][jj].index.concat(obj.index);\n }\n list.splice((list.indexOf(clustered[ii][jj])), 1);\n }\n obj.index.length = indCount;\n list.push(obj);\n }\n }\n return list[0];\n}\n\nmodule.exports = agnes;\n","module.exports = require('./lib/heap');\n","// Generated by CoffeeScript 1.8.0\n(function() {\n var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;\n\n floor = Math.floor, min = Math.min;\n\n\n /*\n Default comparison function to be used\n */\n\n defaultCmp = function(x, y) {\n if (x < y) {\n return -1;\n }\n if (x > y) {\n return 1;\n }\n return 0;\n };\n\n\n /*\n Insert item x in list a, and keep it sorted assuming a is sorted.\n \n If x is already in a, insert it to the right of the rightmost x.\n \n Optional args lo (default 0) and hi (default a.length) bound the slice\n of a to be searched.\n */\n\n insort = function(a, x, lo, hi, cmp) {\n var mid;\n if (lo == null) {\n lo = 0;\n }\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (lo < 0) {\n throw new Error('lo must be non-negative');\n }\n if (hi == null) {\n hi = a.length;\n }\n while (lo < hi) {\n mid = floor((lo + hi) / 2);\n if (cmp(x, a[mid]) < 0) {\n hi = mid;\n } else {\n lo = mid + 1;\n }\n }\n return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);\n };\n\n\n /*\n Push item onto heap, maintaining the heap invariant.\n */\n\n heappush = function(array, item, cmp) {\n if (cmp == null) {\n cmp = defaultCmp;\n }\n array.push(item);\n return _siftdown(array, 0, array.length - 1, cmp);\n };\n\n\n /*\n Pop the smallest item off the heap, maintaining the heap invariant.\n */\n\n heappop = function(array, cmp) {\n var lastelt, returnitem;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n lastelt = array.pop();\n if (array.length) {\n returnitem = array[0];\n array[0] = lastelt;\n _siftup(array, 0, cmp);\n } else {\n returnitem = lastelt;\n }\n return returnitem;\n };\n\n\n /*\n Pop and return the current smallest value, and add the new item.\n \n This is more efficient than heappop() followed by heappush(), and can be\n more appropriate when using a fixed size heap. Note that the value\n returned may be larger than item! That constrains reasonable use of\n this routine unless written as part of a conditional replacement:\n if item > array[0]\n item = heapreplace(array, item)\n */\n\n heapreplace = function(array, item, cmp) {\n var returnitem;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n returnitem = array[0];\n array[0] = item;\n _siftup(array, 0, cmp);\n return returnitem;\n };\n\n\n /*\n Fast version of a heappush followed by a heappop.\n */\n\n heappushpop = function(array, item, cmp) {\n var _ref;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (array.length && cmp(array[0], item) < 0) {\n _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];\n _siftup(array, 0, cmp);\n }\n return item;\n };\n\n\n /*\n Transform list into a heap, in-place, in O(array.length) time.\n */\n\n heapify = function(array, cmp) {\n var i, _i, _j, _len, _ref, _ref1, _results, _results1;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n _ref1 = (function() {\n _results1 = [];\n for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }\n return _results1;\n }).apply(this).reverse();\n _results = [];\n for (_i = 0, _len = _ref1.length; _i < _len; _i++) {\n i = _ref1[_i];\n _results.push(_siftup(array, i, cmp));\n }\n return _results;\n };\n\n\n /*\n Update the position of the given item in the heap.\n This function should be called every time the item is being modified.\n */\n\n updateItem = function(array, item, cmp) {\n var pos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n pos = array.indexOf(item);\n if (pos === -1) {\n return;\n }\n _siftdown(array, 0, pos, cmp);\n return _siftup(array, pos, cmp);\n };\n\n\n /*\n Find the n largest elements in a dataset.\n */\n\n nlargest = function(array, n, cmp) {\n var elem, result, _i, _len, _ref;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n result = array.slice(0, n);\n if (!result.length) {\n return result;\n }\n heapify(result, cmp);\n _ref = array.slice(n);\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n heappushpop(result, elem, cmp);\n }\n return result.sort(cmp).reverse();\n };\n\n\n /*\n Find the n smallest elements in a dataset.\n */\n\n nsmallest = function(array, n, cmp) {\n var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (n * 10 <= array.length) {\n result = array.slice(0, n).sort(cmp);\n if (!result.length) {\n return result;\n }\n los = result[result.length - 1];\n _ref = array.slice(n);\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n if (cmp(elem, los) < 0) {\n insort(result, elem, 0, null, cmp);\n result.pop();\n los = result[result.length - 1];\n }\n }\n return result;\n }\n heapify(array, cmp);\n _results = [];\n for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) {\n _results.push(heappop(array, cmp));\n }\n return _results;\n };\n\n _siftdown = function(array, startpos, pos, cmp) {\n var newitem, parent, parentpos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n newitem = array[pos];\n while (pos > startpos) {\n parentpos = (pos - 1) >> 1;\n parent = array[parentpos];\n if (cmp(newitem, parent) < 0) {\n array[pos] = parent;\n pos = parentpos;\n continue;\n }\n break;\n }\n return array[pos] = newitem;\n };\n\n _siftup = function(array, pos, cmp) {\n var childpos, endpos, newitem, rightpos, startpos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n endpos = array.length;\n startpos = pos;\n newitem = array[pos];\n childpos = 2 * pos + 1;\n while (childpos < endpos) {\n rightpos = childpos + 1;\n if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {\n childpos = rightpos;\n }\n array[pos] = array[childpos];\n pos = childpos;\n childpos = 2 * pos + 1;\n }\n array[pos] = newitem;\n return _siftdown(array, startpos, pos, cmp);\n };\n\n Heap = (function() {\n Heap.push = heappush;\n\n Heap.pop = heappop;\n\n Heap.replace = heapreplace;\n\n Heap.pushpop = heappushpop;\n\n Heap.heapify = heapify;\n\n Heap.updateItem = updateItem;\n\n Heap.nlargest = nlargest;\n\n Heap.nsmallest = nsmallest;\n\n function Heap(cmp) {\n this.cmp = cmp != null ? cmp : defaultCmp;\n this.nodes = [];\n }\n\n Heap.prototype.push = function(x) {\n return heappush(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.pop = function() {\n return heappop(this.nodes, this.cmp);\n };\n\n Heap.prototype.peek = function() {\n return this.nodes[0];\n };\n\n Heap.prototype.contains = function(x) {\n return this.nodes.indexOf(x) !== -1;\n };\n\n Heap.prototype.replace = function(x) {\n return heapreplace(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.pushpop = function(x) {\n return heappushpop(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.heapify = function() {\n return heapify(this.nodes, this.cmp);\n };\n\n Heap.prototype.updateItem = function(x) {\n return updateItem(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.clear = function() {\n return this.nodes = [];\n };\n\n Heap.prototype.empty = function() {\n return this.nodes.length === 0;\n };\n\n Heap.prototype.size = function() {\n return this.nodes.length;\n };\n\n Heap.prototype.clone = function() {\n var heap;\n heap = new Heap();\n heap.nodes = this.nodes.slice(0);\n return heap;\n };\n\n Heap.prototype.toArray = function() {\n return this.nodes.slice(0);\n };\n\n Heap.prototype.insert = Heap.prototype.push;\n\n Heap.prototype.top = Heap.prototype.peek;\n\n Heap.prototype.front = Heap.prototype.peek;\n\n Heap.prototype.has = Heap.prototype.contains;\n\n Heap.prototype.copy = Heap.prototype.clone;\n\n return Heap;\n\n })();\n\n (function(root, factory) {\n if (typeof define === 'function' && define.amd) {\n return define([], factory);\n } else if (typeof exports === 'object') {\n return module.exports = factory();\n } else {\n return root.Heap = factory();\n }\n })(this, function() {\n return Heap;\n });\n\n}).call(this);\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||\n function getOwnPropertyDescriptors(obj) {\n var keys = Object.keys(obj);\n var descriptors = {};\n for (var i = 0; i < keys.length; i++) {\n descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);\n }\n return descriptors;\n };\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n if (!isString(f)) {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j':\n try {\n return JSON.stringify(args[i++]);\n } catch (_) {\n return '[Circular]';\n }\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (isNull(x) || !isObject(x)) {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexports.deprecate = function(fn, msg) {\n if (typeof process !== 'undefined' && process.noDeprecation === true) {\n return fn;\n }\n\n // Allow for deprecating things in the process of starting up.\n if (typeof process === 'undefined') {\n return function() {\n return exports.deprecate(fn, msg).apply(this, arguments);\n };\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnviron;\nexports.debuglog = function(set) {\n if (isUndefined(debugEnviron))\n debugEnviron = process.env.NODE_DEBUG || '';\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (new RegExp('\\\\b' + set + '\\\\b', 'i').test(debugEnviron)) {\n var pid = process.pid;\n debugs[set] = function() {\n var msg = exports.format.apply(exports, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nfunction inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (isBoolean(opts)) {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n exports._extend(ctx, opts);\n }\n // set default options\n if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n if (isUndefined(ctx.depth)) ctx.depth = 2;\n if (isUndefined(ctx.colors)) ctx.colors = false;\n if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\nexports.inspect = inspect;\n\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect &&\n value &&\n isFunction(value.inspect) &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== exports.inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n var ret = value.inspect(recurseTimes, ctx);\n if (!isString(ret)) {\n ret = formatValue(ctx, ret, recurseTimes);\n }\n return ret;\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // IE doesn't make error fields non-enumerable\n // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n if (isError(value)\n && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n return formatError(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (isFunction(value)) {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (isFunction(value)) {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n if (isUndefined(value))\n return ctx.stylize('undefined', 'undefined');\n if (isString(value)) {\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n }\n if (isNumber(value))\n return ctx.stylize('' + value, 'number');\n if (isBoolean(value))\n return ctx.stylize('' + value, 'boolean');\n // For some reason typeof null is \"object\", so special case here.\n if (isNull(value))\n return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (isNull(recurseTimes)) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (isUndefined(name)) {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nfunction isArray(ar) {\n return Array.isArray(ar);\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return isObject(re) && objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return isObject(d) && objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return isObject(e) &&\n (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('./support/isBuffer');\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexports.log = function() {\n console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexports.inherits = require('inherits');\n\nexports._extend = function(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || !isObject(add)) return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nvar kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;\n\nexports.promisify = function promisify(original) {\n if (typeof original !== 'function')\n throw new TypeError('The \"original\" argument must be of type Function');\n\n if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {\n var fn = original[kCustomPromisifiedSymbol];\n if (typeof fn !== 'function') {\n throw new TypeError('The \"util.promisify.custom\" argument must be of type Function');\n }\n Object.defineProperty(fn, kCustomPromisifiedSymbol, {\n value: fn, enumerable: false, writable: false, configurable: true\n });\n return fn;\n }\n\n function fn() {\n var promiseResolve, promiseReject;\n var promise = new Promise(function (resolve, reject) {\n promiseResolve = resolve;\n promiseReject = reject;\n });\n\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n args.push(function (err, value) {\n if (err) {\n promiseReject(err);\n } else {\n promiseResolve(value);\n }\n });\n\n try {\n original.apply(this, args);\n } catch (err) {\n promiseReject(err);\n }\n\n return promise;\n }\n\n Object.setPrototypeOf(fn, Object.getPrototypeOf(original));\n\n if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {\n value: fn, enumerable: false, writable: false, configurable: true\n });\n return Object.defineProperties(\n fn,\n getOwnPropertyDescriptors(original)\n );\n}\n\nexports.promisify.custom = kCustomPromisifiedSymbol\n\nfunction callbackifyOnRejected(reason, cb) {\n // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).\n // Because `null` is a special error value in callbacks which means \"no error\n // occurred\", we error-wrap so the callback consumer can distinguish between\n // \"the promise rejected with null\" or \"the promise fulfilled with undefined\".\n if (!reason) {\n var newReason = new Error('Promise was rejected with a falsy value');\n newReason.reason = reason;\n reason = newReason;\n }\n return cb(reason);\n}\n\nfunction callbackify(original) {\n if (typeof original !== 'function') {\n throw new TypeError('The \"original\" argument must be of type Function');\n }\n\n // We DO NOT return the promise as it gives the user a false sense that\n // the promise is actually somehow related to the callback's execution\n // and that the callback throwing will reject the promise.\n function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }\n\n Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));\n Object.defineProperties(callbackified,\n getOwnPropertyDescriptors(original));\n return callbackified;\n}\nexports.callbackify = callbackify;\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","module.exports = function isBuffer(arg) {\n return arg && typeof arg === 'object'\n && typeof arg.copy === 'function'\n && typeof arg.fill === 'function'\n && typeof arg.readUInt8 === 'function';\n}","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\nconst ClusterLeaf = require('./ClusterLeaf');\nconst Cluster = require('./Cluster');\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction simpleLink(cluster1, cluster2, disFun) {\n var m = 10e100;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = i; j < cluster2.length; j++) {\n var d = disFun(cluster1[i], cluster2[j]);\n m = Math.min(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction completeLink(cluster1, cluster2, disFun) {\n var m = -1;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = i; j < cluster2.length; j++) {\n var d = disFun(cluster1[i], cluster2[j]);\n m = Math.max(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction averageLink(cluster1, cluster2, disFun) {\n var m = 0;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n m += disFun(cluster1[i], cluster2[j]);\n }\n }\n return m / (cluster1.length * cluster2.length);\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction centroidLink(cluster1, cluster2, disFun) {\n var x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0;\n for (var i = 0; i < cluster1.length; i++) {\n x1 += cluster1[i][0];\n y1 += cluster1[i][1];\n }\n for (var j = 0; j < cluster2.length; j++) {\n x2 += cluster2[j][0];\n y2 += cluster2[j][1];\n }\n x1 /= cluster1.length;\n y1 /= cluster1.length;\n x2 /= cluster2.length;\n y2 /= cluster2.length;\n return disFun([x1, y1], [x2, y2]);\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction wardLink(cluster1, cluster2, disFun) {\n var x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0;\n for (var i = 0; i < cluster1.length; i++) {\n x1 += cluster1[i][0];\n y1 += cluster1[i][1];\n }\n for (var j = 0; j < cluster2.length; j++) {\n x2 += cluster2[j][0];\n y2 += cluster2[j][1];\n }\n x1 /= cluster1.length;\n y1 /= cluster1.length;\n x2 /= cluster2.length;\n y2 /= cluster2.length;\n return disFun([x1, y1], [x2, y2]) * cluster1.length * cluster2.length / (cluster1.length + cluster2.length);\n}\n\n/**\n * @private\n * Returns the most distant point and his distance\n * @param {Array >} splitting - Clusters to split\n * @param {Array >} data - Original data\n * @param {function} disFun - Distance function\n * @returns {{d: number, p: number}} - d: maximum difference between points, p: the point more distant\n */\nfunction diff(splitting, data, disFun) {\n var ans = {\n d: 0,\n p: 0\n };\n\n var Ci = new Array(splitting[0].length);\n for (var e = 0; e < splitting[0].length; e++) {\n Ci[e] = data[splitting[0][e]];\n }\n var Cj = new Array(splitting[1].length);\n for (var f = 0; f < splitting[1].length; f++) {\n Cj[f] = data[splitting[1][f]];\n }\n\n var dist, ndist;\n for (var i = 0; i < Ci.length; i++) {\n dist = 0;\n for (var j = 0; j < Ci.length; j++) {\n if (i !== j) {\n dist += disFun(Ci[i], Ci[j]);\n }\n }\n dist /= (Ci.length - 1);\n ndist = 0;\n for (var k = 0; k < Cj.length; k++) {\n ndist += disFun(Ci[i], Cj[k]);\n }\n ndist /= Cj.length;\n if ((dist - ndist) > ans.d) {\n ans.d = (dist - ndist);\n ans.p = i;\n }\n }\n return ans;\n}\n\nvar defaultOptions = {\n dist: euclidean,\n kind: 'single'\n};\n\n/**\n * @private\n * Intra-cluster distance\n * @param {Array} index\n * @param {Array} data\n * @param {function} disFun\n * @returns {number}\n */\nfunction intrDist(index, data, disFun) {\n var dist = 0,\n count = 0;\n for (var i = 0; i < index.length; i++) {\n for (var j = i; j < index.length; j++) {\n dist += disFun(data[index[i].index], data[index[j].index]);\n count++;\n }\n }\n return dist / count;\n}\n\n/**\n * Splits the higher level clusters\n * @param {Array >} data - Array of points to be clustered\n * @param {json} options\n * @constructor\n */\nfunction diana(data, options) {\n options = Object.assign({}, defaultOptions, options);\n if (typeof options.kind === 'string') {\n switch (options.kind) {\n case 'single':\n options.kind = simpleLink;\n break;\n case 'complete':\n options.kind = completeLink;\n break;\n case 'average':\n options.kind = averageLink;\n break;\n case 'centroid':\n options.kind = centroidLink;\n break;\n case 'ward':\n options.kind = wardLink;\n break;\n default:\n throw new RangeError('Unknown kind of similarity');\n }\n } else if (typeof options.kind !== 'function') {\n throw new TypeError('Undefined kind of similarity');\n }\n var tree = new Cluster();\n tree.children = new Array(data.length);\n tree.index = new Array(data.length);\n for (var ind = 0; ind < data.length; ind++) {\n tree.children[ind] = new ClusterLeaf(ind);\n tree.index[ind] = new ClusterLeaf(ind);\n }\n\n tree.distance = intrDist(tree.index, data, options.dist);\n var m, M, clId,\n dist, rebel;\n var list = [tree];\n while (list.length > 0) {\n M = 0;\n clId = 0;\n for (var i = 0; i < list.length; i++) {\n m = 0;\n for (var j = 0; j < list[i].length; j++) {\n for (var l = (j + 1); l < list[i].length; l++) {\n m = Math.max(options.dist(data[list[i].index[j].index], data[list[i].index[l].index]), m);\n }\n }\n if (m > M) {\n M = m;\n clId = i;\n }\n }\n M = 0;\n if (list[clId].index.length === 2) {\n list[clId].children = [list[clId].index[0], list[clId].index[1]];\n list[clId].distance = options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]);\n } else if (list[clId].index.length === 3) {\n list[clId].children = [list[clId].index[0], list[clId].index[1], list[clId].index[2]];\n var d = [\n options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]),\n options.dist(data[list[clId].index[1].index], data[list[clId].index[2].index])\n ];\n list[clId].distance = (d[0] + d[1]) / 2;\n } else {\n var C = new Cluster();\n var sG = new Cluster();\n var splitting = [new Array(list[clId].index.length), []];\n for (var spl = 0; spl < splitting[0].length; spl++) {\n splitting[0][spl] = spl;\n }\n for (var ii = 0; ii < splitting[0].length; ii++) {\n dist = 0;\n for (var jj = 0; jj < splitting[0].length; jj++) {\n if (ii !== jj) {\n dist += options.dist(data[list[clId].index[splitting[0][jj]].index], data[list[clId].index[splitting[0][ii]].index]);\n }\n }\n dist /= (splitting[0].length - 1);\n if (dist > M) {\n M = dist;\n rebel = ii;\n }\n }\n splitting[1] = [rebel];\n splitting[0].splice(rebel, 1);\n dist = diff(splitting, data, options.dist);\n while (dist.d > 0) {\n splitting[1].push(splitting[0][dist.p]);\n splitting[0].splice(dist.p, 1);\n dist = diff(splitting, data, options.dist);\n }\n var fData = new Array(splitting[0].length);\n C.index = new Array(splitting[0].length);\n for (var e = 0; e < fData.length; e++) {\n fData[e] = data[list[clId].index[splitting[0][e]].index];\n C.index[e] = list[clId].index[splitting[0][e]];\n C.children[e] = list[clId].index[splitting[0][e]];\n }\n var sData = new Array(splitting[1].length);\n sG.index = new Array(splitting[1].length);\n for (var f = 0; f < sData.length; f++) {\n sData[f] = data[list[clId].index[splitting[1][f]].index];\n sG.index[f] = list[clId].index[splitting[1][f]];\n sG.children[f] = list[clId].index[splitting[1][f]];\n }\n C.distance = intrDist(C.index, data, options.dist);\n sG.distance = intrDist(sG.index, data, options.dist);\n list.push(C);\n list.push(sG);\n list[clId].children = [C, sG];\n }\n list.splice(clId, 1);\n }\n return tree;\n}\n\nmodule.exports = diana;\n","'use strict';\nconst Kernel = require('ml-kernel');\nconst stat = require('ml-stat').array;\n\nvar defaultOptions = {\n C: 1,\n tol: 1e-4,\n maxPasses: 10,\n maxIterations: 10000,\n kernel: 'linear',\n alphaTol: 1e-6,\n random: Math.random,\n whitening: true\n};\n\n/**\n * Simplified version of the Sequential Minimal Optimization algorithm for training\n * support vector machines\n * @param {{Object}} options - SVM options\n * @param {Number} [options.C=1] - regularization parameter\n * @param {Number} [options.tol=1e-4] - numerical tolerance\n * @param {Number} [options.alphaTol=1e-6] - alpha tolerance, threshold to decide support vectors\n * @param {Number} [options.maxPasses=10] - max number of times to iterate over alphas without changing\n * @param {Number} [options.maxIterations=10000] - max number of iterations\n * @param {String} [options.kernel=linear] - the kind of kernel. {@link https://github.com/mljs/kernel/tree/1252de5f9012776e6e0eb06c7b434b8631fb21f0 List of kernels}\n * @param {Function} [options.random=Math.random] - custom random number generator\n * @constructor\n */\nfunction SVM(options) {\n this.options = Object.assign({}, defaultOptions, options);\n\n this.kernel = new Kernel(this.options.kernel, this.options.kernelOptions);\n this.b = 0;\n}\n\n/**\n * Train the SVM model\n * @param {Array >} features - training data features\n * @param {Array } labels - training data labels in the domain {1,-1}\n */\nSVM.prototype.train = function (features, labels) {\n if (features.length !== labels.length) {\n throw new Error('Features and labels should have the same length');\n }\n if (features.length < 2) {\n throw new Error('Cannot train with less than 2 observations');\n }\n this._trained = false;\n this._loaded = false;\n this.N = labels.length;\n this.D = features[0].length;\n if (this.options.whitening) {\n this.X = new Array(this.N);\n for (var i = 0; i < this.N; i++) {\n this.X[i] = new Array(this.D);\n }\n this.minMax = new Array(this.D);\n // Apply normalization and keep normalization parameters\n for (var j = 0; j < this.D; j++) {\n var d = new Array(this.N);\n for (i = 0; i < this.N; i++) {\n d[i] = features[i][j];\n }\n this.minMax[j] = stat.minMax(d);\n for (i = 0; i < this.N; i++) {\n this.X[i][j] = (features[i][j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min);\n }\n }\n } else {\n this.X = features;\n }\n this.Y = labels;\n this.b = 0;\n this.W = undefined;\n\n var kernel = this.kernel.compute(this.X);\n var m = labels.length;\n var alpha = new Array(m).fill(0);\n this.alphas = alpha;\n for (var a = 0; a < m; a++)\n alpha[a] = 0;\n\n var b1 = 0,\n b2 = 0,\n iter = 0,\n passes = 0,\n Ei = 0,\n Ej = 0,\n ai = 0,\n aj = 0,\n L = 0,\n H = 0,\n eta = 0;\n\n while (passes < this.options.maxPasses && iter < this.options.maxIterations) {\n var numChange = 0;\n for (i = 0; i < m; i++) {\n Ei = this._marginOnePrecomputed(i, kernel) - labels[i];\n if (labels[i] * Ei < -this.options.tol && alpha[i] < this.options.C || labels[i] * Ei > this.options.tol && alpha[i] > 0) {\n j = i;\n while (j === i) j = Math.floor(this.options.random() * m);\n Ej = this._marginOnePrecomputed(j, kernel) - labels[j];\n ai = alpha[i];\n aj = alpha[j];\n if (labels[i] === labels[j]) {\n L = Math.max(0, ai + aj - this.options.C);\n H = Math.min(this.options.C, ai + aj);\n } else {\n L = Math.max(0, aj - ai);\n H = Math.min(this.options.C, this.options.C + aj + ai);\n }\n if (Math.abs(L - H) < 1e-4) continue;\n\n eta = 2 * kernel[i][j] - kernel[i][i] - kernel[j][j];\n if (eta >= 0) continue;\n var newaj = alpha[j] - labels[j] * (Ei - Ej) / eta;\n if (newaj > H)\n newaj = H;\n else if (newaj < L)\n newaj = L;\n if (Math.abs(aj - newaj) < 10e-4) continue;\n alpha[j] = newaj;\n alpha[i] = alpha[i] + labels[i] * labels[j] * (aj - newaj);\n b1 = this.b - Ei - labels[i] * (alpha[i] - ai) * kernel[i][i] - labels[j] * (alpha[j] - aj) * kernel[i][j];\n b2 = this.b - Ej - labels[i] * (alpha[i] - ai) * kernel[i][j] - labels[j] * (alpha[j] - aj) * kernel[j][j];\n this.b = (b1 + b2) / 2;\n if (alpha[i] < this.options.C && alpha[i] > 0) this.b = b1;\n if (alpha[j] < this.options.C && alpha[j] > 0) this.b = b2;\n numChange += 1;\n }\n }\n iter++;\n if (numChange === 0)\n passes += 1;\n else\n passes = 0;\n }\n if (iter === this.options.maxIterations) {\n throw new Error('max iterations reached');\n }\n\n this.iterations = iter;\n\n // Compute the weights (useful for fast decision on new test instances when linear SVM)\n if (this.options.kernel === 'linear') {\n this.W = new Array(this.D);\n for (var r = 0; r < this.D; r++) {\n this.W[r] = 0;\n for (var w = 0; w < m; w++)\n this.W[r] += labels[w] * alpha[w] * this.X[w][r];\n }\n }\n\n // Keep only support vectors\n // It will compute decision on new test instances faster\n // We also keep the index of the support vectors\n // in the original data\n var nX = [];\n var nY = [];\n var nAlphas = [];\n this._supportVectorIdx = [];\n for (i = 0; i < this.N; i++) {\n if (this.alphas[i] > this.options.alphaTol) {\n nX.push(this.X[i]);\n nY.push(labels[i]);\n nAlphas.push(this.alphas[i]);\n this._supportVectorIdx.push(i);\n\n }\n }\n this.X = nX;\n this.Y = nY;\n this.N = nX.length;\n this.alphas = nAlphas;\n\n\n // A flag to say this SVM has been trained\n this._trained = true;\n};\n\n/**\n * Get prediction ({-1,1}) given one observation's features.\n * @private\n * @param p The observation's features.\n * @returns {number} Classification result ({-1,1})\n */\nSVM.prototype.predictOne = function (p) {\n var margin = this.marginOne(p);\n return margin > 0 ? 1 : -1;\n};\n\n/**\n * Predict the classification outcome of a trained svm given one or several observations' features.\n * @param {Array} features - The observation(s)' features\n * @returns {Array|Number} An array of {-1, 1} if several observations are given or a number if one observation\n * is given\n */\nSVM.prototype.predict = function (features) {\n if (!this._trained && !this._loaded) throw new Error('Cannot predict, you need to train the SVM first');\n if (Array.isArray(features) && Array.isArray(features[0])) {\n return features.map(this.predictOne.bind(this));\n } else {\n return this.predictOne(features);\n }\n};\n\n/**\n * Get margin given one observation's features\n * @private\n * @param {Array} features - Features\n * @returns {Number} - The computed margin\n */\nSVM.prototype.marginOne = function (features, noWhitening) {\n // Apply normalization\n if (this.options.whitening && !noWhitening) {\n features = this._applyWhitening(features);\n }\n var ans = this.b, i;\n if (this.options.kernel === 'linear' && this.W) {\n // Use weights, it's faster\n for (i = 0; i < this.W.length; i++) {\n ans += this.W[i] * features[i];\n }\n } else {\n for (i = 0; i < this.N; i++) {\n ans += this.alphas[i] * this.Y[i] * this.kernel.compute([features], [this.X[i]])[0][0];\n }\n }\n return ans;\n};\n\n\n/**\n * Get a margin using the precomputed kernel. Much faster than normal margin computation\n * @private\n * @param {Number} index - Train data index\n * @param {Array< Array >} kernel - The precomputed kernel\n * @returns {number} Computed margin\n * @private\n */\nSVM.prototype._marginOnePrecomputed = function (index, kernel) {\n var ans = this.b, i;\n for (i = 0; i < this.N; i++) {\n ans += this.alphas[i] * this.Y[i] * kernel[index][i];\n }\n return ans;\n};\n\n\n/**\n * Returns the margin of one or several observations given its features\n * @param {Array >|Array} features - Features from on or several observations.\n * @returns {Number|Array} The computed margin. Is an Array if several observations' features given, or a Number if\n * only one observation's features given\n */\nSVM.prototype.margin = function (features) {\n if (Array.isArray(features)) {\n return features.map(this.marginOne.bind(this));\n } else {\n return this.marginOne(features);\n }\n};\n\n/**\n * Get support vectors indexes of the trained classifier. WARINNG: this method does not work for svm instances\n * created from {@link #SVM.load load} if linear kernel\n * @returns {Array} The indices in the training vector of the support vectors\n */\nSVM.prototype.supportVectors = function () {\n if (!this._trained && !this._loaded) throw new Error('Cannot get support vectors, you need to train the SVM first');\n if (this._loaded && this.options.kernel === 'linear') throw new Error('Cannot get support vectors from saved linear model, you need to train the SVM to have them');\n return this._supportVectorIdx;\n};\n\n/**\n * Create a SVM instance from a saved model\n * @param {Object} model - Object such as returned by a trained SVM instance with {@link #SVM#toJSON toJSON}\n * @returns {SVM} Instance of svm classifier\n */\nSVM.load = function (model) {\n this._loaded = true;\n this._trained = false;\n var svm = new SVM(model.options);\n if (model.options.kernel === 'linear') {\n svm.W = model.W.slice();\n svm.D = svm.W.length;\n } else {\n svm.X = model.X.slice();\n svm.Y = model.Y.slice();\n svm.alphas = model.alphas.slice();\n svm.N = svm.X.length;\n svm.D = svm.X[0].length;\n }\n svm.minMax = model.minMax;\n svm.b = model.b;\n svm._loaded = true;\n svm._trained = false;\n return svm;\n};\n\n/**\n * Export the minimal object that enables to reload the model\n * @returns {Object} Model object that can be reused with {@link #SVM.load load}\n */\nSVM.prototype.toJSON = function () {\n if (!this._trained && !this._loaded) throw new Error('Cannot export, you need to train the SVM first');\n var model = {};\n model.options = Object.assign({}, this.options);\n model.b = this.b;\n model.minMax = this.minMax;\n if (model.options.kernel === 'linear') {\n model.W = this.W.slice();\n } else {\n // Exporting non-linear models is heavier\n model.X = this.X.slice();\n model.Y = this.Y.slice();\n model.alphas = this.alphas.slice();\n }\n return model;\n};\n\nSVM.prototype._applyWhitening = function (features) {\n if (!this.minMax) throw new Error('Could not apply whitening');\n var whitened = new Array(features.length);\n for (var j = 0; j < features.length; j++) {\n whitened[j] = (features[j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min);\n }\n return whitened;\n};\n\nmodule.exports = SVM;\n","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass GaussianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = GaussianKernel;\n","'use strict';\n\nconst defaultOptions = {\n degree: 1,\n constant: 1,\n scale: 1\n};\n\nclass PolynomialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n\n this.degree = options.degree;\n this.constant = options.constant;\n this.scale = options.scale;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.pow(this.scale * sum + this.constant, this.degree);\n }\n}\n\nmodule.exports = PolynomialKernel;\n","'use strict';\n\nconst defaultOptions = {\n sigma: 1,\n degree: 1\n};\n\nclass ANOVAKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.degree = options.degree;\n }\n\n compute(x, y) {\n var sum = 0;\n var len = Math.min(x.length, y.length);\n for (var i = 1; i <= len; ++i) {\n sum += Math.pow(Math.exp(-this.sigma * Math.pow(Math.pow(x[i - 1], i) -\n Math.pow(y[i - 1], i), 2)), this.degree);\n }\n return sum;\n }\n}\n\nmodule.exports = ANOVAKernel;\n","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass CauchyKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n return 1 / (1 + squaredEuclidean(x, y) / (this.sigma * this.sigma));\n }\n}\n\nmodule.exports = CauchyKernel;\n","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass ExponentialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = ExponentialKernel;\n","'use strict';\n\nclass HistogramIntersectionKernel {\n compute(x, y) {\n var min = Math.min(x.length, y.length);\n var sum = 0;\n for (var i = 0; i < min; ++i) {\n sum += Math.min(x[i], y[i]);\n }\n\n return sum;\n }\n}\n\nmodule.exports = HistogramIntersectionKernel;\n","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass LaplacianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.sigma);\n }\n}\n\nmodule.exports = LaplacianKernel;\n","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass MultiquadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n return Math.sqrt(squaredEuclidean(x, y) + this.constant * this.constant);\n }\n}\n\nmodule.exports = MultiquadraticKernel;\n","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass RationalQuadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return 1 - (distance / (distance + this.constant));\n }\n}\n\nmodule.exports = RationalQuadraticKernel;\n","'use strict';\n\nconst defaultOptions = {\n alpha: 0.01,\n constant: -Math.E\n};\n\nclass SigmoidKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.alpha = options.alpha;\n this.constant = options.constant;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.tanh(this.alpha * sum + this.constant);\n }\n}\n\nmodule.exports = SigmoidKernel;\n","'use strict';\n\nconst ConfusionMatrix = require('ml-confusion-matrix');\n\nconst CV = {};\nconst combinations = require('ml-combinations');\n\n/**\n * Performs a leave-one-out cross-validation (LOO-CV) of the given samples. In LOO-CV, 1 observation is used as the\n * validation set while the rest is used as the training set. This is repeated once for each observation. LOO-CV is a\n * special case of LPO-CV. @see leavePout\n * @param {function} Classifier - The classifier's constructor to use for the cross validation. Expect ml-classifier\n * api.\n * @param {Array} features - The features for all samples of the data-set\n * @param {Array} labels - The classification class of all samples of the data-set\n * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated.\n * @return {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.leaveOneOut = function (Classifier, features, labels, classifierOptions) {\n if (typeof labels === 'function') {\n var callback = labels;\n labels = features;\n features = Classifier;\n return CV.leavePOut(features, labels, 1, callback);\n }\n return CV.leavePOut(Classifier, features, labels, classifierOptions, 1);\n};\n\n\n/**\n * Performs a leave-p-out cross-validation (LPO-CV) of the given samples. In LPO-CV, p observations are used as the\n * validation set while the rest is used as the training set. This is repeated as many times as there are possible\n * ways to combine p observations from the set (unordered without replacement). Be aware that for relatively small\n * data-set size this can require a very large number of training and testing to do!\n * @param {function} Classifier - The classifier's constructor to use for the cross validation. Expect ml-classifier\n * api.\n * @param {Array} features - The features for all samples of the data-set\n * @param {Array} labels - The classification class of all samples of the data-set\n * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated.\n * @param {number} p - The size of the validation sub-samples' set\n * @return {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.leavePOut = function (Classifier, features, labels, classifierOptions, p) {\n if (typeof classifierOptions === 'function') {\n var callback = classifierOptions;\n p = labels;\n labels = features;\n features = Classifier;\n }\n check(features, labels);\n const distinct = getDistinct(labels);\n const confusionMatrix = initMatrix(distinct.length, distinct.length);\n\n var N = features.length;\n var gen = combinations(p, N);\n var allIdx = new Array(N);\n for (let i = 0; i < N; i++) {\n allIdx[i] = i;\n }\n for (const testIdx of gen) {\n var trainIdx = allIdx.slice();\n\n for (let i = testIdx.length - 1; i >= 0; i--) {\n trainIdx.splice(testIdx[i], 1);\n }\n\n if (callback) {\n validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback);\n } else {\n validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct);\n }\n\n }\n\n return new ConfusionMatrix(confusionMatrix, distinct);\n};\n\n/**\n * Performs k-fold cross-validation (KF-CV). KF-CV separates the data-set into k random equally sized partitions, and\n * uses each as a validation set, with all other partitions used in the training set. Observations left over from if k\n * does not divide the number of observations are left out of the cross-validation process.\n * @param {function} Classifier - The classifier's to use for the cross validation. Expect ml-classifier api.\n * @param {Array} features - The features for all samples of the data-set\n * @param {Array} labels - The classification class of all samples of the data-set\n * @param {object} classifierOptions - The classifier options with which the classifier should be instantiated.\n * @param {number} k - The number of partitions to create\n * @return {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.kFold = function (Classifier, features, labels, classifierOptions, k) {\n if (typeof classifierOptions === 'function') {\n var callback = classifierOptions;\n k = labels;\n labels = features;\n features = Classifier;\n }\n check(features, labels);\n const distinct = getDistinct(labels);\n const confusionMatrix = initMatrix(distinct.length, distinct.length);\n var N = features.length;\n var allIdx = new Array(N);\n for (var i = 0; i < N; i++) {\n allIdx[i] = i;\n }\n\n var l = Math.floor(N / k);\n // create random k-folds\n var current = [];\n var folds = [];\n while (allIdx.length) {\n var randi = Math.floor(Math.random() * allIdx.length);\n current.push(allIdx[randi]);\n allIdx.splice(randi, 1);\n if (current.length === l) {\n folds.push(current);\n current = [];\n }\n }\n if (current.length) folds.push(current);\n folds = folds.slice(0, k);\n\n\n for (i = 0; i < folds.length; i++) {\n var testIdx = folds[i];\n var trainIdx = [];\n for (var j = 0; j < folds.length; j++) {\n if (j !== i) trainIdx = trainIdx.concat(folds[j]);\n }\n\n if (callback) {\n validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback);\n } else {\n validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct);\n }\n }\n\n return new ConfusionMatrix(confusionMatrix, distinct);\n};\n\nfunction check(features, labels) {\n if (features.length !== labels.length) {\n throw new Error('features and labels should have the same length');\n }\n}\n\nfunction initMatrix(rows, columns) {\n return new Array(rows).fill(0).map(() => new Array(columns).fill(0));\n}\n\nfunction getDistinct(arr) {\n var s = new Set();\n for (let i = 0; i < arr.length; i++) {\n s.add(arr[i]);\n }\n return Array.from(s);\n}\n\nfunction validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct) {\n const {testFeatures, trainFeatures, testLabels, trainLabels} = getTrainTest(features, labels, testIdx, trainIdx);\n\n var classifier;\n if (Classifier.prototype.train) {\n classifier = new Classifier(classifierOptions);\n classifier.train(trainFeatures, trainLabels);\n } else {\n classifier = new Classifier(trainFeatures, trainLabels, classifierOptions);\n }\n\n var predictedLabels = classifier.predict(testFeatures);\n updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct);\n}\n\nfunction validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback) {\n const {testFeatures, trainFeatures, testLabels, trainLabels} = getTrainTest(features, labels, testIdx, trainIdx);\n const predictedLabels = callback(trainFeatures, trainLabels, testFeatures);\n updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct);\n}\n\nfunction updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct) {\n\n for (var i = 0; i < predictedLabels.length; i++) {\n const actualIdx = distinct.indexOf(testLabels[i]);\n const predictedIdx = distinct.indexOf(predictedLabels[i]);\n if (actualIdx < 0 || predictedIdx < 0) {\n // eslint-disable-next-line no-console\n console.warn(`ignore unknown predicted label ${predictedLabels[i]}`);\n }\n confusionMatrix[actualIdx][predictedIdx]++;\n }\n}\n\n\nfunction getTrainTest(features, labels, testIdx, trainIdx) {\n return {\n testFeatures: testIdx.map(function (index) {\n return features[index];\n }),\n trainFeatures: trainIdx.map(function (index) {\n return features[index];\n }),\n testLabels: testIdx.map(function (index) {\n return labels[index];\n }),\n trainLabels: trainIdx.map(function (index) {\n return labels[index];\n })\n };\n}\n\nmodule.exports = CV;\n","(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? factory() :\n\ttypeof define === 'function' && define.amd ? define(factory) :\n\t(factory());\n}(this, (function () { 'use strict';\n\n\tfunction createCommonjsModule(fn, module) {\n\t\treturn module = { exports: {} }, fn(module, module.exports), module.exports;\n\t}\n\n\tvar runtime = createCommonjsModule(function (module) {\n\t/**\n\t * Copyright (c) 2014-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t */\n\n\t!(function(global) {\n\n\t var Op = Object.prototype;\n\t var hasOwn = Op.hasOwnProperty;\n\t var undefined; // More compressible than void 0.\n\t var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n\t var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n\t var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n\t var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\t var runtime = global.regeneratorRuntime;\n\t if (runtime) {\n\t {\n\t // If regeneratorRuntime is defined globally and we're in a module,\n\t // make the exports object identical to regeneratorRuntime.\n\t module.exports = runtime;\n\t }\n\t // Don't bother evaluating the rest of this file if the runtime was\n\t // already defined globally.\n\t return;\n\t }\n\n\t // Define the runtime globally (as expected by generated code) as either\n\t // module.exports (if we're in a module) or a new, empty object.\n\t runtime = global.regeneratorRuntime = module.exports;\n\n\t function wrap(innerFn, outerFn, self, tryLocsList) {\n\t // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n\t var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n\t var generator = Object.create(protoGenerator.prototype);\n\t var context = new Context(tryLocsList || []);\n\n\t // The ._invoke method unifies the implementations of the .next,\n\t // .throw, and .return methods.\n\t generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n\t return generator;\n\t }\n\t runtime.wrap = wrap;\n\n\t // Try/catch helper to minimize deoptimizations. Returns a completion\n\t // record like context.tryEntries[i].completion. This interface could\n\t // have been (and was previously) designed to take a closure to be\n\t // invoked without arguments, but in all the cases we care about we\n\t // already have an existing method we want to call, so there's no need\n\t // to create a new function object. We can even get away with assuming\n\t // the method takes exactly one argument, since that happens to be true\n\t // in every case, so we don't have to touch the arguments object. The\n\t // only additional allocation required is the completion record, which\n\t // has a stable shape and so hopefully should be cheap to allocate.\n\t function tryCatch(fn, obj, arg) {\n\t try {\n\t return { type: \"normal\", arg: fn.call(obj, arg) };\n\t } catch (err) {\n\t return { type: \"throw\", arg: err };\n\t }\n\t }\n\n\t var GenStateSuspendedStart = \"suspendedStart\";\n\t var GenStateSuspendedYield = \"suspendedYield\";\n\t var GenStateExecuting = \"executing\";\n\t var GenStateCompleted = \"completed\";\n\n\t // Returning this object from the innerFn has the same effect as\n\t // breaking out of the dispatch switch statement.\n\t var ContinueSentinel = {};\n\n\t // Dummy constructor functions that we use as the .constructor and\n\t // .constructor.prototype properties for functions that return Generator\n\t // objects. For full spec compliance, you may wish to configure your\n\t // minifier not to mangle the names of these two functions.\n\t function Generator() {}\n\t function GeneratorFunction() {}\n\t function GeneratorFunctionPrototype() {}\n\n\t // This is a polyfill for %IteratorPrototype% for environments that\n\t // don't natively support it.\n\t var IteratorPrototype = {};\n\t IteratorPrototype[iteratorSymbol] = function () {\n\t return this;\n\t };\n\n\t var getProto = Object.getPrototypeOf;\n\t var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n\t if (NativeIteratorPrototype &&\n\t NativeIteratorPrototype !== Op &&\n\t hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n\t // This environment has a native %IteratorPrototype%; use it instead\n\t // of the polyfill.\n\t IteratorPrototype = NativeIteratorPrototype;\n\t }\n\n\t var Gp = GeneratorFunctionPrototype.prototype =\n\t Generator.prototype = Object.create(IteratorPrototype);\n\t GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n\t GeneratorFunctionPrototype.constructor = GeneratorFunction;\n\t GeneratorFunctionPrototype[toStringTagSymbol] =\n\t GeneratorFunction.displayName = \"GeneratorFunction\";\n\n\t // Helper for defining the .next, .throw, and .return methods of the\n\t // Iterator interface in terms of a single ._invoke method.\n\t function defineIteratorMethods(prototype) {\n\t [\"next\", \"throw\", \"return\"].forEach(function(method) {\n\t prototype[method] = function(arg) {\n\t return this._invoke(method, arg);\n\t };\n\t });\n\t }\n\n\t runtime.isGeneratorFunction = function(genFun) {\n\t var ctor = typeof genFun === \"function\" && genFun.constructor;\n\t return ctor\n\t ? ctor === GeneratorFunction ||\n\t // For the native GeneratorFunction constructor, the best we can\n\t // do is to check its .name property.\n\t (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n\t : false;\n\t };\n\n\t runtime.mark = function(genFun) {\n\t if (Object.setPrototypeOf) {\n\t Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n\t } else {\n\t genFun.__proto__ = GeneratorFunctionPrototype;\n\t if (!(toStringTagSymbol in genFun)) {\n\t genFun[toStringTagSymbol] = \"GeneratorFunction\";\n\t }\n\t }\n\t genFun.prototype = Object.create(Gp);\n\t return genFun;\n\t };\n\n\t // Within the body of any async function, `await x` is transformed to\n\t // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n\t // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n\t // meant to be awaited.\n\t runtime.awrap = function(arg) {\n\t return { __await: arg };\n\t };\n\n\t function AsyncIterator(generator) {\n\t function invoke(method, arg, resolve, reject) {\n\t var record = tryCatch(generator[method], generator, arg);\n\t if (record.type === \"throw\") {\n\t reject(record.arg);\n\t } else {\n\t var result = record.arg;\n\t var value = result.value;\n\t if (value &&\n\t typeof value === \"object\" &&\n\t hasOwn.call(value, \"__await\")) {\n\t return Promise.resolve(value.__await).then(function(value) {\n\t invoke(\"next\", value, resolve, reject);\n\t }, function(err) {\n\t invoke(\"throw\", err, resolve, reject);\n\t });\n\t }\n\n\t return Promise.resolve(value).then(function(unwrapped) {\n\t // When a yielded Promise is resolved, its final value becomes\n\t // the .value of the Promise<{value,done}> result for the\n\t // current iteration. If the Promise is rejected, however, the\n\t // result for this iteration will be rejected with the same\n\t // reason. Note that rejections of yielded Promises are not\n\t // thrown back into the generator function, as is the case\n\t // when an awaited Promise is rejected. This difference in\n\t // behavior between yield and await is important, because it\n\t // allows the consumer to decide what to do with the yielded\n\t // rejection (swallow it and continue, manually .throw it back\n\t // into the generator, abandon iteration, whatever). With\n\t // await, by contrast, there is no opportunity to examine the\n\t // rejection reason outside the generator function, so the\n\t // only option is to throw it from the await expression, and\n\t // let the generator function handle the exception.\n\t result.value = unwrapped;\n\t resolve(result);\n\t }, reject);\n\t }\n\t }\n\n\t var previousPromise;\n\n\t function enqueue(method, arg) {\n\t function callInvokeWithMethodAndArg() {\n\t return new Promise(function(resolve, reject) {\n\t invoke(method, arg, resolve, reject);\n\t });\n\t }\n\n\t return previousPromise =\n\t // If enqueue has been called before, then we want to wait until\n\t // all previous Promises have been resolved before calling invoke,\n\t // so that results are always delivered in the correct order. If\n\t // enqueue has not been called before, then it is important to\n\t // call invoke immediately, without waiting on a callback to fire,\n\t // so that the async generator function has the opportunity to do\n\t // any necessary setup in a predictable way. This predictability\n\t // is why the Promise constructor synchronously invokes its\n\t // executor callback, and why async functions synchronously\n\t // execute code before the first await. Since we implement simple\n\t // async functions in terms of async generators, it is especially\n\t // important to get this right, even though it requires care.\n\t previousPromise ? previousPromise.then(\n\t callInvokeWithMethodAndArg,\n\t // Avoid propagating failures to Promises returned by later\n\t // invocations of the iterator.\n\t callInvokeWithMethodAndArg\n\t ) : callInvokeWithMethodAndArg();\n\t }\n\n\t // Define the unified helper method that is used to implement .next,\n\t // .throw, and .return (see defineIteratorMethods).\n\t this._invoke = enqueue;\n\t }\n\n\t defineIteratorMethods(AsyncIterator.prototype);\n\t AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n\t return this;\n\t };\n\t runtime.AsyncIterator = AsyncIterator;\n\n\t // Note that simple async functions are implemented on top of\n\t // AsyncIterator objects; they just return a Promise for the value of\n\t // the final result produced by the iterator.\n\t runtime.async = function(innerFn, outerFn, self, tryLocsList) {\n\t var iter = new AsyncIterator(\n\t wrap(innerFn, outerFn, self, tryLocsList)\n\t );\n\n\t return runtime.isGeneratorFunction(outerFn)\n\t ? iter // If outerFn is a generator, return the full iterator.\n\t : iter.next().then(function(result) {\n\t return result.done ? result.value : iter.next();\n\t });\n\t };\n\n\t function makeInvokeMethod(innerFn, self, context) {\n\t var state = GenStateSuspendedStart;\n\n\t return function invoke(method, arg) {\n\t if (state === GenStateExecuting) {\n\t throw new Error(\"Generator is already running\");\n\t }\n\n\t if (state === GenStateCompleted) {\n\t if (method === \"throw\") {\n\t throw arg;\n\t }\n\n\t // Be forgiving, per 25.3.3.3.3 of the spec:\n\t // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n\t return doneResult();\n\t }\n\n\t context.method = method;\n\t context.arg = arg;\n\n\t while (true) {\n\t var delegate = context.delegate;\n\t if (delegate) {\n\t var delegateResult = maybeInvokeDelegate(delegate, context);\n\t if (delegateResult) {\n\t if (delegateResult === ContinueSentinel) continue;\n\t return delegateResult;\n\t }\n\t }\n\n\t if (context.method === \"next\") {\n\t // Setting context._sent for legacy support of Babel's\n\t // function.sent implementation.\n\t context.sent = context._sent = context.arg;\n\n\t } else if (context.method === \"throw\") {\n\t if (state === GenStateSuspendedStart) {\n\t state = GenStateCompleted;\n\t throw context.arg;\n\t }\n\n\t context.dispatchException(context.arg);\n\n\t } else if (context.method === \"return\") {\n\t context.abrupt(\"return\", context.arg);\n\t }\n\n\t state = GenStateExecuting;\n\n\t var record = tryCatch(innerFn, self, context);\n\t if (record.type === \"normal\") {\n\t // If an exception is thrown from innerFn, we leave state ===\n\t // GenStateExecuting and loop back for another invocation.\n\t state = context.done\n\t ? GenStateCompleted\n\t : GenStateSuspendedYield;\n\n\t if (record.arg === ContinueSentinel) {\n\t continue;\n\t }\n\n\t return {\n\t value: record.arg,\n\t done: context.done\n\t };\n\n\t } else if (record.type === \"throw\") {\n\t state = GenStateCompleted;\n\t // Dispatch the exception by looping back around to the\n\t // context.dispatchException(context.arg) call above.\n\t context.method = \"throw\";\n\t context.arg = record.arg;\n\t }\n\t }\n\t };\n\t }\n\n\t // Call delegate.iterator[context.method](context.arg) and handle the\n\t // result, either by returning a { value, done } result from the\n\t // delegate iterator, or by modifying context.method and context.arg,\n\t // setting context.delegate to null, and returning the ContinueSentinel.\n\t function maybeInvokeDelegate(delegate, context) {\n\t var method = delegate.iterator[context.method];\n\t if (method === undefined) {\n\t // A .throw or .return when the delegate iterator has no .throw\n\t // method always terminates the yield* loop.\n\t context.delegate = null;\n\n\t if (context.method === \"throw\") {\n\t if (delegate.iterator.return) {\n\t // If the delegate iterator has a return method, give it a\n\t // chance to clean up.\n\t context.method = \"return\";\n\t context.arg = undefined;\n\t maybeInvokeDelegate(delegate, context);\n\n\t if (context.method === \"throw\") {\n\t // If maybeInvokeDelegate(context) changed context.method from\n\t // \"return\" to \"throw\", let that override the TypeError below.\n\t return ContinueSentinel;\n\t }\n\t }\n\n\t context.method = \"throw\";\n\t context.arg = new TypeError(\n\t \"The iterator does not provide a 'throw' method\");\n\t }\n\n\t return ContinueSentinel;\n\t }\n\n\t var record = tryCatch(method, delegate.iterator, context.arg);\n\n\t if (record.type === \"throw\") {\n\t context.method = \"throw\";\n\t context.arg = record.arg;\n\t context.delegate = null;\n\t return ContinueSentinel;\n\t }\n\n\t var info = record.arg;\n\n\t if (! info) {\n\t context.method = \"throw\";\n\t context.arg = new TypeError(\"iterator result is not an object\");\n\t context.delegate = null;\n\t return ContinueSentinel;\n\t }\n\n\t if (info.done) {\n\t // Assign the result of the finished delegate to the temporary\n\t // variable specified by delegate.resultName (see delegateYield).\n\t context[delegate.resultName] = info.value;\n\n\t // Resume execution at the desired location (see delegateYield).\n\t context.next = delegate.nextLoc;\n\n\t // If context.method was \"throw\" but the delegate handled the\n\t // exception, let the outer generator proceed normally. If\n\t // context.method was \"next\", forget context.arg since it has been\n\t // \"consumed\" by the delegate iterator. If context.method was\n\t // \"return\", allow the original .return call to continue in the\n\t // outer generator.\n\t if (context.method !== \"return\") {\n\t context.method = \"next\";\n\t context.arg = undefined;\n\t }\n\n\t } else {\n\t // Re-yield the result returned by the delegate method.\n\t return info;\n\t }\n\n\t // The delegate iterator is finished, so forget it and continue with\n\t // the outer generator.\n\t context.delegate = null;\n\t return ContinueSentinel;\n\t }\n\n\t // Define Generator.prototype.{next,throw,return} in terms of the\n\t // unified ._invoke helper method.\n\t defineIteratorMethods(Gp);\n\n\t Gp[toStringTagSymbol] = \"Generator\";\n\n\t // A Generator should always return itself as the iterator object when the\n\t // @@iterator function is called on it. Some browsers' implementations of the\n\t // iterator prototype chain incorrectly implement this, causing the Generator\n\t // object to not be returned from this call. This ensures that doesn't happen.\n\t // See https://github.com/facebook/regenerator/issues/274 for more details.\n\t Gp[iteratorSymbol] = function() {\n\t return this;\n\t };\n\n\t Gp.toString = function() {\n\t return \"[object Generator]\";\n\t };\n\n\t function pushTryEntry(locs) {\n\t var entry = { tryLoc: locs[0] };\n\n\t if (1 in locs) {\n\t entry.catchLoc = locs[1];\n\t }\n\n\t if (2 in locs) {\n\t entry.finallyLoc = locs[2];\n\t entry.afterLoc = locs[3];\n\t }\n\n\t this.tryEntries.push(entry);\n\t }\n\n\t function resetTryEntry(entry) {\n\t var record = entry.completion || {};\n\t record.type = \"normal\";\n\t delete record.arg;\n\t entry.completion = record;\n\t }\n\n\t function Context(tryLocsList) {\n\t // The root entry object (effectively a try statement without a catch\n\t // or a finally block) gives us a place to store values thrown from\n\t // locations where there is no enclosing try statement.\n\t this.tryEntries = [{ tryLoc: \"root\" }];\n\t tryLocsList.forEach(pushTryEntry, this);\n\t this.reset(true);\n\t }\n\n\t runtime.keys = function(object) {\n\t var keys = [];\n\t for (var key in object) {\n\t keys.push(key);\n\t }\n\t keys.reverse();\n\n\t // Rather than returning an object with a next method, we keep\n\t // things simple and return the next function itself.\n\t return function next() {\n\t while (keys.length) {\n\t var key = keys.pop();\n\t if (key in object) {\n\t next.value = key;\n\t next.done = false;\n\t return next;\n\t }\n\t }\n\n\t // To avoid creating an additional object, we just hang the .value\n\t // and .done properties off the next function object itself. This\n\t // also ensures that the minifier will not anonymize the function.\n\t next.done = true;\n\t return next;\n\t };\n\t };\n\n\t function values(iterable) {\n\t if (iterable) {\n\t var iteratorMethod = iterable[iteratorSymbol];\n\t if (iteratorMethod) {\n\t return iteratorMethod.call(iterable);\n\t }\n\n\t if (typeof iterable.next === \"function\") {\n\t return iterable;\n\t }\n\n\t if (!isNaN(iterable.length)) {\n\t var i = -1, next = function next() {\n\t while (++i < iterable.length) {\n\t if (hasOwn.call(iterable, i)) {\n\t next.value = iterable[i];\n\t next.done = false;\n\t return next;\n\t }\n\t }\n\n\t next.value = undefined;\n\t next.done = true;\n\n\t return next;\n\t };\n\n\t return next.next = next;\n\t }\n\t }\n\n\t // Return an iterator with no values.\n\t return { next: doneResult };\n\t }\n\t runtime.values = values;\n\n\t function doneResult() {\n\t return { value: undefined, done: true };\n\t }\n\n\t Context.prototype = {\n\t constructor: Context,\n\n\t reset: function(skipTempReset) {\n\t this.prev = 0;\n\t this.next = 0;\n\t // Resetting context._sent for legacy support of Babel's\n\t // function.sent implementation.\n\t this.sent = this._sent = undefined;\n\t this.done = false;\n\t this.delegate = null;\n\n\t this.method = \"next\";\n\t this.arg = undefined;\n\n\t this.tryEntries.forEach(resetTryEntry);\n\n\t if (!skipTempReset) {\n\t for (var name in this) {\n\t // Not sure about the optimal order of these conditions:\n\t if (name.charAt(0) === \"t\" &&\n\t hasOwn.call(this, name) &&\n\t !isNaN(+name.slice(1))) {\n\t this[name] = undefined;\n\t }\n\t }\n\t }\n\t },\n\n\t stop: function() {\n\t this.done = true;\n\n\t var rootEntry = this.tryEntries[0];\n\t var rootRecord = rootEntry.completion;\n\t if (rootRecord.type === \"throw\") {\n\t throw rootRecord.arg;\n\t }\n\n\t return this.rval;\n\t },\n\n\t dispatchException: function(exception) {\n\t if (this.done) {\n\t throw exception;\n\t }\n\n\t var context = this;\n\t function handle(loc, caught) {\n\t record.type = \"throw\";\n\t record.arg = exception;\n\t context.next = loc;\n\n\t if (caught) {\n\t // If the dispatched exception was caught by a catch block,\n\t // then let that catch block handle the exception normally.\n\t context.method = \"next\";\n\t context.arg = undefined;\n\t }\n\n\t return !! caught;\n\t }\n\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t var record = entry.completion;\n\n\t if (entry.tryLoc === \"root\") {\n\t // Exception thrown outside of any try block that could handle\n\t // it, so set the completion value of the entire function to\n\t // throw the exception.\n\t return handle(\"end\");\n\t }\n\n\t if (entry.tryLoc <= this.prev) {\n\t var hasCatch = hasOwn.call(entry, \"catchLoc\");\n\t var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n\t if (hasCatch && hasFinally) {\n\t if (this.prev < entry.catchLoc) {\n\t return handle(entry.catchLoc, true);\n\t } else if (this.prev < entry.finallyLoc) {\n\t return handle(entry.finallyLoc);\n\t }\n\n\t } else if (hasCatch) {\n\t if (this.prev < entry.catchLoc) {\n\t return handle(entry.catchLoc, true);\n\t }\n\n\t } else if (hasFinally) {\n\t if (this.prev < entry.finallyLoc) {\n\t return handle(entry.finallyLoc);\n\t }\n\n\t } else {\n\t throw new Error(\"try statement without catch or finally\");\n\t }\n\t }\n\t }\n\t },\n\n\t abrupt: function(type, arg) {\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t if (entry.tryLoc <= this.prev &&\n\t hasOwn.call(entry, \"finallyLoc\") &&\n\t this.prev < entry.finallyLoc) {\n\t var finallyEntry = entry;\n\t break;\n\t }\n\t }\n\n\t if (finallyEntry &&\n\t (type === \"break\" ||\n\t type === \"continue\") &&\n\t finallyEntry.tryLoc <= arg &&\n\t arg <= finallyEntry.finallyLoc) {\n\t // Ignore the finally entry if control is not jumping to a\n\t // location outside the try/catch block.\n\t finallyEntry = null;\n\t }\n\n\t var record = finallyEntry ? finallyEntry.completion : {};\n\t record.type = type;\n\t record.arg = arg;\n\n\t if (finallyEntry) {\n\t this.method = \"next\";\n\t this.next = finallyEntry.finallyLoc;\n\t return ContinueSentinel;\n\t }\n\n\t return this.complete(record);\n\t },\n\n\t complete: function(record, afterLoc) {\n\t if (record.type === \"throw\") {\n\t throw record.arg;\n\t }\n\n\t if (record.type === \"break\" ||\n\t record.type === \"continue\") {\n\t this.next = record.arg;\n\t } else if (record.type === \"return\") {\n\t this.rval = this.arg = record.arg;\n\t this.method = \"return\";\n\t this.next = \"end\";\n\t } else if (record.type === \"normal\" && afterLoc) {\n\t this.next = afterLoc;\n\t }\n\n\t return ContinueSentinel;\n\t },\n\n\t finish: function(finallyLoc) {\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t if (entry.finallyLoc === finallyLoc) {\n\t this.complete(entry.completion, entry.afterLoc);\n\t resetTryEntry(entry);\n\t return ContinueSentinel;\n\t }\n\t }\n\t },\n\n\t \"catch\": function(tryLoc) {\n\t for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n\t var entry = this.tryEntries[i];\n\t if (entry.tryLoc === tryLoc) {\n\t var record = entry.completion;\n\t if (record.type === \"throw\") {\n\t var thrown = record.arg;\n\t resetTryEntry(entry);\n\t }\n\t return thrown;\n\t }\n\t }\n\n\t // The context.catch method must only be called with a location\n\t // argument that corresponds to a known catch block.\n\t throw new Error(\"illegal catch attempt\");\n\t },\n\n\t delegateYield: function(iterable, resultName, nextLoc) {\n\t this.delegate = {\n\t iterator: values(iterable),\n\t resultName: resultName,\n\t nextLoc: nextLoc\n\t };\n\n\t if (this.method === \"next\") {\n\t // Deliberately forget the last sent value so that we don't\n\t // accidentally pass it on to the delegate.\n\t this.arg = undefined;\n\t }\n\n\t return ContinueSentinel;\n\t }\n\t };\n\t})(\n\t // In sloppy mode, unbound `this` refers to the global object, fallback to\n\t // Function constructor if we're in global strict mode. That is sadly a form\n\t // of indirect eval which violates Content Security Policy.\n\t (function() { return this })() || Function(\"return this\")()\n\t);\n\t});\n\n\t/**\n\t * Copyright (c) 2014-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t */\n\n\t// This method of obtaining a reference to the global object needs to be\n\t// kept identical to the way it is obtained in runtime.js\n\tvar g = (function() { return this })() || Function(\"return this\")();\n\n\t// Use `getOwnPropertyNames` because not all browsers support calling\n\t// `hasOwnProperty` on the global `self` object in a worker. See #183.\n\tvar hadRuntime = g.regeneratorRuntime &&\n\t Object.getOwnPropertyNames(g).indexOf(\"regeneratorRuntime\") >= 0;\n\n\t// Save the old regeneratorRuntime in case it needs to be restored later.\n\tvar oldRuntime = hadRuntime && g.regeneratorRuntime;\n\n\t// Force reevalutation of runtime.js.\n\tg.regeneratorRuntime = undefined;\n\n\tvar runtimeModule = runtime;\n\n\tif (hadRuntime) {\n\t // Restore the original runtime.\n\t g.regeneratorRuntime = oldRuntime;\n\t} else {\n\t // Remove the global property added by runtime.js.\n\t try {\n\t delete g.regeneratorRuntime;\n\t } catch(e) {\n\t g.regeneratorRuntime = undefined;\n\t }\n\t}\n\n\tvar regenerator = runtimeModule;\n\n\tvar defaultOptions = {\n\t mode: 'index'\n\t};\n\n\tmodule.exports = /*#__PURE__*/regenerator.mark(function _callee(M, N, options) {\n\t var a, c, b, p, x, y, z, i, twiddle;\n\t return regenerator.wrap(function _callee$(_context) {\n\t while (1) {\n\t switch (_context.prev = _context.next) {\n\t case 0:\n\t twiddle = function twiddle() {\n\t var i, j, k;\n\t j = 1;\n\t while (p[j] <= 0) {\n\t j++;\n\t }\n\t if (p[j - 1] === 0) {\n\t for (i = j - 1; i !== 1; i--) {\n\t p[i] = -1;\n\t }\n\t p[j] = 0;\n\t x = z = 0;\n\t p[1] = 1;\n\t y = j - 1;\n\t } else {\n\t if (j > 1) {\n\t p[j - 1] = 0;\n\t }\n\t do {\n\t j++;\n\t } while (p[j] > 0);\n\t k = j - 1;\n\t i = j;\n\t while (p[i] === 0) {\n\t p[i++] = -1;\n\t }\n\t if (p[i] === -1) {\n\t p[i] = p[k];\n\t z = p[k] - 1;\n\t x = i - 1;\n\t y = k - 1;\n\t p[k] = -1;\n\t } else {\n\t if (i === p[0]) {\n\t return 0;\n\t } else {\n\t p[j] = p[i];\n\t z = p[i] - 1;\n\t p[i] = 0;\n\t x = j - 1;\n\t y = i - 1;\n\t }\n\t }\n\t }\n\t return 1;\n\t };\n\n\t options = Object.assign({}, defaultOptions, options);\n\t a = new Array(N);\n\t c = new Array(M);\n\t b = new Array(N);\n\t p = new Array(N + 2);\n\n\n\t // init a and b\n\t for (i = 0; i < N; i++) {\n\t a[i] = i;\n\t if (i < N - M) b[i] = 0;else b[i] = 1;\n\t }\n\n\t // init c\n\t for (i = 0; i < M; i++) {\n\t c[i] = N - M + i;\n\t }\n\n\t // init p\n\t for (i = 0; i < p.length; i++) {\n\t if (i === 0) p[i] = N + 1;else if (i <= N - M) p[i] = 0;else if (i <= N) p[i] = i - N + M;else p[i] = -2;\n\t }\n\n\t if (!(options.mode === 'index')) {\n\t _context.next = 20;\n\t break;\n\t }\n\n\t _context.next = 12;\n\t return c.slice();\n\n\t case 12:\n\t if (!twiddle()) {\n\t _context.next = 18;\n\t break;\n\t }\n\n\t c[z] = a[x];\n\t _context.next = 16;\n\t return c.slice();\n\n\t case 16:\n\t _context.next = 12;\n\t break;\n\n\t case 18:\n\t _context.next = 33;\n\t break;\n\n\t case 20:\n\t if (!(options.mode === 'mask')) {\n\t _context.next = 32;\n\t break;\n\t }\n\n\t _context.next = 23;\n\t return b.slice();\n\n\t case 23:\n\t if (!twiddle()) {\n\t _context.next = 30;\n\t break;\n\t }\n\n\t b[x] = 1;\n\t b[y] = 0;\n\t _context.next = 28;\n\t return b.slice();\n\n\t case 28:\n\t _context.next = 23;\n\t break;\n\n\t case 30:\n\t _context.next = 33;\n\t break;\n\n\t case 32:\n\t throw new Error('Invalid mode');\n\n\t case 33:\n\t case 'end':\n\t return _context.stop();\n\t }\n\t }\n\t }, _callee, this);\n\t});\n\n})));\n","'use strict';\n\nconst Matrix = require('ml-matrix').Matrix;\n\nconst Layer = require('./Layer');\nconst OutputLayer = require('./OutputLayer');\nconst Utils = require('./utils');\nconst ACTIVATION_FUNCTIONS = require('./activationFunctions');\n\nclass FeedForwardNeuralNetworks {\n\n /**\n * Create a new Feedforword neural network model.\n * @class FeedForwardNeuralNetworks\n * @param {object} [options]\n * @param {Array} [options.hiddenLayers=[10]] - Array that contains the sizes of the hidden layers.\n * @param {number} [options.iterations=50] - Number of iterations at the training step.\n * @param {number} [options.learningRate=0.01] - Learning rate of the neural net (also known as epsilon).\n * @param {number} [options.regularization=0.01] - Regularization parameter af the neural net.\n * @param {string} [options.activation='tanh'] - activation function to be used. (options: 'tanh'(default),\n * 'identity', 'logistic', 'arctan', 'softsign', 'relu', 'softplus', 'bent', 'sinusoid', 'sinc', 'gaussian').\n * (single-parametric options: 'parametric-relu', 'exponential-relu', 'soft-exponential').\n * @param {number} [options.activationParam=1] - if the selected activation function needs a parameter.\n */\n constructor(options) {\n options = options || {};\n if (options.model) {\n // load network\n this.hiddenLayers = options.hiddenLayers;\n this.iterations = options.iterations;\n this.learningRate = options.learningRate;\n this.regularization = options.regularization;\n this.dicts = options.dicts;\n this.activation = options.activation;\n this.activationParam = options.activationParam;\n this.model = new Array(options.layers.length);\n\n for (var i = 0; i < this.model.length - 1; ++i) {\n this.model[i] = Layer.load(options.layers[i]);\n }\n this.model[this.model.length - 1] = OutputLayer.load(options.layers[this.model.length - 1]);\n } else {\n // default constructor\n this.hiddenLayers = options.hiddenLayers || [10];\n this.iterations = options.iterations || 50;\n\n this.learningRate = options.learningRate || 0.01;\n this.regularization = options.regularization || 0.01;\n\n this.activation = options.activation || 'tanh';\n this.activationParam = options.activationParam || 1;\n if (!(this.activation in Object.keys(ACTIVATION_FUNCTIONS))) {\n this.activation = 'tanh';\n }\n }\n }\n\n /**\n * @private\n * Function that build and initialize the neural net.\n * @param {number} inputSize - total of features to fit.\n * @param {number} outputSize - total of labels of the prediction set.\n */\n buildNetwork(inputSize, outputSize) {\n var size = 2 + (this.hiddenLayers.length - 1);\n this.model = new Array(size);\n\n // input layer\n this.model[0] = new Layer({\n inputSize: inputSize,\n outputSize: this.hiddenLayers[0],\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n\n // hidden layers\n for (var i = 1; i < this.hiddenLayers.length; ++i) {\n this.model[i] = new Layer({\n inputSize: this.hiddenLayers[i - 1],\n outputSize: this.hiddenLayers[i],\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n }\n\n // output layer\n this.model[size - 1] = new OutputLayer({\n inputSize: this.hiddenLayers[this.hiddenLayers.length - 1],\n outputSize: outputSize,\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n }\n\n /**\n * Train the neural net with the given features and labels.\n * @param {Matrix|Array} features\n * @param {Matrix|Array} labels\n */\n train(features, labels) {\n features = Matrix.checkMatrix(features);\n this.dicts = Utils.dictOutputs(labels);\n\n var inputSize = features.columns;\n var outputSize = Object.keys(this.dicts.inputs).length;\n\n this.buildNetwork(inputSize, outputSize);\n\n for (var i = 0; i < this.iterations; ++i) {\n var probabilities = this.propagate(features);\n this.backpropagation(features, labels, probabilities);\n }\n }\n\n /**\n * @private\n * Propagate the input(training set) and retrives the probabilities of each class.\n * @param {Matrix} X\n * @return {Matrix} probabilities of each class.\n */\n propagate(X) {\n var input = X;\n for (var i = 0; i < this.model.length; ++i) {\n //console.log(i);\n input = this.model[i].forward(input);\n }\n\n // get probabilities\n return input.divColumnVector(Utils.sumRow(input));\n }\n\n /**\n * @private\n * Function that applies the backpropagation algorithm on each layer of the network\n * in order to fit the features and labels.\n * @param {Matrix} features\n * @param {Array} labels\n * @param {Matrix} probabilities - probabilities of each class of the feature set.\n */\n backpropagation(features, labels, probabilities) {\n for (var i = 0; i < probabilities.length; ++i) {\n probabilities[i][this.dicts.inputs[labels[i]]] -= 1;\n }\n\n // remember, the last delta doesn't matter\n var delta = probabilities;\n for (i = this.model.length - 1; i >= 0; --i) {\n var a = i > 0 ? this.model[i - 1].a : features;\n delta = this.model[i].backpropagation(delta, a);\n }\n\n for (i = 0; i < this.model.length; ++i) {\n this.model[i].update();\n }\n }\n\n /**\n * Predict the output given the feature set.\n * @param {Array|Matrix} features\n * @return {Array}\n */\n predict(features) {\n features = Matrix.checkMatrix(features);\n var outputs = new Array(features.rows);\n var probabilities = this.propagate(features);\n for (var i = 0; i < features.rows; ++i) {\n outputs[i] = this.dicts.outputs[probabilities.maxRowIndex(i)[1]];\n }\n\n return outputs;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} model\n */\n toJSON() {\n var model = {\n model: 'FNN',\n hiddenLayers: this.hiddenLayers,\n iterations: this.iterations,\n learningRate: this.learningRate,\n regularization: this.regularization,\n activation: this.activation,\n activationParam: this.activationParam,\n dicts: this.dicts,\n layers: new Array(this.model.length)\n };\n\n for (var i = 0; i < this.model.length; ++i) {\n model.layers[i] = this.model[i].toJSON();\n }\n\n return model;\n }\n\n /**\n * Load a Feedforward Neural Network with the current model.\n * @param {object} model\n * @return {FeedForwardNeuralNetworks}\n */\n static load(model) {\n if (model.model !== 'FNN') {\n throw new RangeError('the current model is not a feed forward network');\n }\n\n return new FeedForwardNeuralNetworks(model);\n }\n}\n\nmodule.exports = FeedForwardNeuralNetworks;\n","'use strict';\n\nvar Layer = require('./Layer');\n\nclass OutputLayer extends Layer {\n constructor(options) {\n super(options);\n\n this.activationFunction = function (i, j) {\n this[i][j] = Math.exp(this[i][j]);\n };\n }\n\n static load(model) {\n if (model.model !== 'Layer') {\n throw new RangeError('the current model is not a Layer model');\n }\n\n return new OutputLayer(model);\n }\n}\n\nmodule.exports = OutputLayer;\n","'use strict';\n\nvar NodeSquare = require('./node-square'),\n NodeHexagonal = require('./node-hexagonal');\n\nvar defaultOptions = {\n fields: 3,\n randomizer: Math.random,\n distance: squareEuclidean,\n iterations: 10,\n learningRate: 0.1,\n gridType: 'rect',\n torus: true,\n method: 'random'\n};\n\nfunction SOM(x, y, options, reload) {\n\n this.x = x;\n this.y = y;\n\n options = options || {};\n this.options = {};\n for (var i in defaultOptions) {\n if (options.hasOwnProperty(i)) {\n this.options[i] = options[i];\n } else {\n this.options[i] = defaultOptions[i];\n }\n }\n\n if (typeof this.options.fields === 'number') {\n this.numWeights = this.options.fields;\n } else if (Array.isArray(this.options.fields)) {\n this.numWeights = this.options.fields.length;\n var converters = getConverters(this.options.fields);\n this.extractor = converters.extractor;\n this.creator = converters.creator;\n } else {\n throw new Error('Invalid fields definition');\n }\n\n if (this.options.gridType === 'rect') {\n this.nodeType = NodeSquare;\n this.gridDim = {\n x: x,\n y: y\n };\n } else {\n this.nodeType = NodeHexagonal;\n var hx = this.x - Math.floor(this.y / 2);\n this.gridDim = {\n x: hx,\n y: this.y,\n z: -(0 - hx - this.y)\n };\n }\n\n this.torus = this.options.torus;\n this.distanceMethod = this.torus ? 'getDistanceTorus' : 'getDistance';\n\n this.distance = this.options.distance;\n\n this.maxDistance = getMaxDistance(this.distance, this.numWeights);\n\n if (reload === true) { // For model loading\n this.done = true;\n return;\n }\n if (!(x > 0 && y > 0)) {\n throw new Error('x and y must be positive');\n }\n\n this.times = {\n findBMU: 0,\n adjust: 0\n };\n\n this.randomizer = this.options.randomizer;\n\n this.iterationCount = 0;\n this.iterations = this.options.iterations;\n\n this.startLearningRate = this.learningRate = this.options.learningRate;\n\n this.mapRadius = Math.floor(Math.max(x, y) / 2);\n\n this.algorithmMethod = this.options.method;\n\n this._initNodes();\n\n this.done = false;\n}\n\nSOM.load = function loadModel(model, distance) {\n if (model.name === 'SOM') {\n var x = model.data.length,\n y = model.data[0].length;\n if (distance) {\n model.options.distance = distance;\n } else if (model.options.distance) {\n model.options.distance = eval('(' + model.options.distance + ')');\n }\n var som = new SOM(x, y, model.options, true);\n som.nodes = new Array(x);\n for (var i = 0; i < x; i++) {\n som.nodes[i] = new Array(y);\n for (var j = 0; j < y; j++) {\n som.nodes[i][j] = new som.nodeType(i, j, model.data[i][j], som);\n }\n }\n return som;\n } else {\n throw new Error('expecting a SOM model');\n }\n};\n\nSOM.prototype.export = function exportModel(includeDistance) {\n if (!this.done) {\n throw new Error('model is not ready yet');\n }\n var model = {\n name: 'SOM'\n };\n model.options = {\n fields: this.options.fields,\n gridType: this.options.gridType,\n torus: this.options.torus\n };\n model.data = new Array(this.x);\n for (var i = 0; i < this.x; i++) {\n model.data[i] = new Array(this.y);\n for (var j = 0; j < this.y; j++) {\n model.data[i][j] = this.nodes[i][j].weights;\n }\n }\n if (includeDistance) {\n model.options.distance = this.distance.toString();\n }\n return model;\n};\n\nSOM.prototype._initNodes = function initNodes() {\n var now = Date.now(),\n i, j, k;\n this.nodes = new Array(this.x);\n for (i = 0; i < this.x; i++) {\n this.nodes[i] = new Array(this.y);\n for (j = 0; j < this.y; j++) {\n var weights = new Array(this.numWeights);\n for (k = 0; k < this.numWeights; k++) {\n weights[k] = this.randomizer();\n }\n this.nodes[i][j] = new this.nodeType(i, j, weights, this);\n }\n }\n this.times.initNodes = Date.now() - now;\n};\n\nSOM.prototype.setTraining = function setTraining(trainingSet) {\n if (this.trainingSet) {\n throw new Error('training set has already been set');\n }\n var now = Date.now();\n var convertedSet = trainingSet;\n var i, l = trainingSet.length;\n if (this.extractor) {\n convertedSet = new Array(l);\n for (i = 0; i < l; i++) {\n convertedSet[i] = this.extractor(trainingSet[i]);\n }\n }\n this.numIterations = this.iterations * l;\n\n if (this.algorithmMethod === 'random') {\n this.timeConstant = this.numIterations / Math.log(this.mapRadius);\n } else {\n this.timeConstant = l / Math.log(this.mapRadius);\n }\n this.trainingSet = convertedSet;\n this.times.setTraining = Date.now() - now;\n};\n\nSOM.prototype.trainOne = function trainOne() {\n if (this.done) {\n\n return false;\n\n } else if (this.numIterations-- > 0) {\n\n var neighbourhoodRadius,\n trainingValue,\n trainingSetFactor;\n\n if (this.algorithmMethod === 'random') { // Pick a random value of the training set at each step\n neighbourhoodRadius = this.mapRadius * Math.exp(-this.iterationCount / this.timeConstant);\n trainingValue = getRandomValue(this.trainingSet, this.randomizer);\n this._adjust(trainingValue, neighbourhoodRadius);\n this.learningRate = this.startLearningRate * Math.exp(-this.iterationCount / this.numIterations);\n } else { // Get next input vector\n trainingSetFactor = -Math.floor(this.iterationCount / this.trainingSet.length);\n neighbourhoodRadius = this.mapRadius * Math.exp(trainingSetFactor / this.timeConstant);\n trainingValue = this.trainingSet[this.iterationCount % this.trainingSet.length];\n this._adjust(trainingValue, neighbourhoodRadius);\n if (((this.iterationCount + 1) % this.trainingSet.length) === 0) {\n this.learningRate = this.startLearningRate * Math.exp(trainingSetFactor / Math.floor(this.numIterations / this.trainingSet.length));\n }\n }\n\n this.iterationCount++;\n\n return true;\n\n } else {\n\n this.done = true;\n return false;\n\n }\n};\n\nSOM.prototype._adjust = function adjust(trainingValue, neighbourhoodRadius) {\n var now = Date.now(),\n x, y, dist, influence;\n\n var bmu = this._findBestMatchingUnit(trainingValue);\n\n var now2 = Date.now();\n this.times.findBMU += now2 - now;\n\n var radiusLimit = Math.floor(neighbourhoodRadius);\n var xMin = bmu.x - radiusLimit,\n xMax = bmu.x + radiusLimit,\n yMin = bmu.y - radiusLimit,\n yMax = bmu.y + radiusLimit;\n\n for (x = xMin; x <= xMax; x++) {\n var theX = x;\n if (x < 0) {\n theX += this.x;\n } else if (x >= this.x) {\n theX -= this.x;\n }\n for (y = yMin; y <= yMax; y++) {\n var theY = y;\n if (y < 0) {\n theY += this.y;\n } else if (y >= this.y) {\n theY -= this.y;\n }\n\n dist = bmu[this.distanceMethod](this.nodes[theX][theY]);\n\n if (dist < neighbourhoodRadius) {\n influence = Math.exp(-dist / (2 * neighbourhoodRadius));\n this.nodes[theX][theY].adjustWeights(trainingValue, this.learningRate, influence);\n }\n\n }\n }\n\n this.times.adjust += (Date.now() - now2);\n\n};\n\nSOM.prototype.train = function train(trainingSet) {\n if (!this.done) {\n this.setTraining(trainingSet);\n while (this.trainOne()) {\n }\n }\n};\n\nSOM.prototype.getConvertedNodes = function getConvertedNodes() {\n var result = new Array(this.x);\n for (var i = 0; i < this.x; i++) {\n result[i] = new Array(this.y);\n for (var j = 0; j < this.y; j++) {\n var node = this.nodes[i][j];\n result[i][j] = this.creator ? this.creator(node.weights) : node.weights;\n }\n }\n return result;\n};\n\nSOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) {\n\n var bmu,\n lowest = Infinity,\n dist;\n\n for (var i = 0; i < this.x; i++) {\n for (var j = 0; j < this.y; j++) {\n dist = this.distance(this.nodes[i][j].weights, candidate);\n if (dist < lowest) {\n lowest = dist;\n bmu = this.nodes[i][j];\n }\n }\n }\n\n return bmu;\n\n};\n\nSOM.prototype.predict = function predict(data, computePosition) {\n if (typeof data === 'boolean') {\n computePosition = data;\n data = null;\n }\n if (!data) {\n data = this.trainingSet;\n }\n if (Array.isArray(data) && (Array.isArray(data[0]) || (typeof data[0] === 'object'))) { // predict a dataset\n var self = this;\n return data.map(function (element) {\n return self._predict(element, computePosition);\n });\n } else { // predict a single element\n return this._predict(data, computePosition);\n }\n};\n\nSOM.prototype._predict = function _predict(element, computePosition) {\n if (!Array.isArray(element)) {\n element = this.extractor(element);\n }\n var bmu = this._findBestMatchingUnit(element);\n var result = [bmu.x, bmu.y];\n if (computePosition) {\n result[2] = bmu.getPosition(element);\n }\n return result;\n};\n\n// As seen in http://www.scholarpedia.org/article/Kohonen_network\nSOM.prototype.getQuantizationError = function getQuantizationError() {\n var fit = this.getFit(),\n l = fit.length,\n sum = 0;\n for (var i = 0; i < l; i++) {\n sum += fit[i];\n }\n return sum / l;\n};\n\nSOM.prototype.getFit = function getFit(dataset) {\n if (!dataset) {\n dataset = this.trainingSet;\n }\n var l = dataset.length,\n bmu,\n result = new Array(l);\n for (var i = 0; i < l; i++) {\n bmu = this._findBestMatchingUnit(dataset[i]);\n result[i] = Math.sqrt(this.distance(dataset[i], bmu.weights));\n }\n return result;\n};\n\nfunction getConverters(fields) {\n var l = fields.length,\n normalizers = new Array(l),\n denormalizers = new Array(l);\n for (var i = 0; i < l; i++) {\n normalizers[i] = getNormalizer(fields[i].range);\n denormalizers[i] = getDenormalizer(fields[i].range);\n }\n return {\n extractor: function extractor(value) {\n var result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = normalizers[i](value[fields[i].name]);\n }\n return result;\n },\n creator: function creator(value) {\n var result = {};\n for (var i = 0; i < l; i++) {\n result[fields[i].name] = denormalizers[i](value[i]);\n }\n return result;\n }\n };\n}\n\nfunction getNormalizer(minMax) {\n return function normalizer(value) {\n return (value - minMax[0]) / (minMax[1] - minMax[0]);\n };\n}\n\nfunction getDenormalizer(minMax) {\n return function denormalizer(value) {\n return (minMax[0] + value * (minMax[1] - minMax[0]));\n };\n}\n\nfunction squareEuclidean(a, b) {\n var d = 0;\n for (var i = 0, ii = a.length; i < ii; i++) {\n d += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return d;\n}\n\nfunction getRandomValue(arr, randomizer) {\n return arr[Math.floor(randomizer() * arr.length)];\n}\n\nfunction getMaxDistance(distance, numWeights) {\n var zero = new Array(numWeights),\n one = new Array(numWeights);\n for (var i = 0; i < numWeights; i++) {\n zero[i] = 0;\n one[i] = 1;\n }\n return distance(zero, one);\n}\n\nmodule.exports = SOM;","var NodeSquare = require('./node-square');\n\nfunction NodeHexagonal(x, y, weights, som) {\n\n NodeSquare.call(this, x, y, weights, som);\n\n this.hX = x - Math.floor(y / 2);\n this.z = 0 - this.hX - y;\n\n}\n\nNodeHexagonal.prototype = new NodeSquare;\nNodeHexagonal.prototype.constructor = NodeHexagonal;\n\nNodeHexagonal.prototype.getDistance = function getDistanceHexagonal(otherNode) {\n return Math.max(Math.abs(this.hX - otherNode.hX), Math.abs(this.y - otherNode.y), Math.abs(this.z - otherNode.z));\n};\n\nNodeHexagonal.prototype.getDistanceTorus = function getDistanceTorus(otherNode) {\n var distX = Math.abs(this.hX - otherNode.hX),\n distY = Math.abs(this.y - otherNode.y),\n distZ = Math.abs(this.z - otherNode.z);\n return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY), Math.min(distZ, this.som.gridDim.z - distZ));\n};\n\nNodeHexagonal.prototype.getPosition = function getPosition() {\n throw new Error('Unimplemented : cannot get position of the points for hexagonal grid');\n};\n\nmodule.exports = NodeHexagonal;","import HashTable from 'ml-hash-table';\n\nexport class SparseMatrix {\n constructor(rows, columns, options = {}) {\n if (rows instanceof SparseMatrix) { // clone\n const other = rows;\n this._init(other.rows, other.columns, other.elements.clone(), other.threshold);\n return;\n }\n\n if (Array.isArray(rows)) {\n const matrix = rows;\n rows = matrix.length;\n options = columns || {};\n columns = matrix[0].length;\n this._init(rows, columns, new HashTable(options), options.threshold);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n var value = matrix[i][j];\n if (this.threshold && Math.abs(value) < this.threshold) value = 0;\n if (value !== 0) {\n this.elements.set(i * columns + j, matrix[i][j]);\n }\n }\n }\n } else {\n this._init(rows, columns, new HashTable(options), options.threshold);\n }\n }\n\n _init(rows, columns, elements, threshold) {\n this.rows = rows;\n this.columns = columns;\n this.elements = elements;\n this.threshold = threshold || 0;\n }\n\n static eye(rows = 1, columns = rows) {\n const min = Math.min(rows, columns);\n const matrix = new SparseMatrix(rows, columns, {initialCapacity: min});\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, 1);\n }\n return matrix;\n }\n\n clone() {\n return new SparseMatrix(this);\n }\n\n to2DArray() {\n const copy = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n copy[i] = new Array(this.columns);\n for (var j = 0; j < this.columns; j++) {\n copy[i][j] = this.get(i, j);\n }\n }\n return copy;\n }\n\n isSquare() {\n return this.rows === this.columns;\n }\n\n isSymmetric() {\n if (!this.isSquare()) return false;\n\n var symmetric = true;\n this.forEachNonZero((i, j, v) => {\n if (this.get(j, i) !== v) {\n symmetric = false;\n return false;\n }\n return v;\n });\n return symmetric;\n }\n\n /**\n * Search for the wither band in the main diagonals\n * @return {number}\n */\n bandWidth() {\n let min = this.columns;\n let max = -1;\n this.forEachNonZero((i, j, v) => {\n let diff = i - j;\n min = Math.min(min, diff);\n max = Math.max(max, diff);\n return v;\n });\n return max - min;\n }\n\n /**\n * Test if a matrix is consider banded using a threshold\n * @param {number} width\n * @return {boolean}\n */\n isBanded(width) {\n let bandWidth = this.bandWidth();\n return bandWidth <= width;\n }\n\n get cardinality() {\n return this.elements.size;\n }\n\n get size() {\n return this.rows * this.columns;\n }\n\n get(row, column) {\n return this.elements.get(row * this.columns + column);\n }\n\n set(row, column, value) {\n if (this.threshold && Math.abs(value) < this.threshold) value = 0;\n if (value === 0) {\n this.elements.remove(row * this.columns + column);\n } else {\n this.elements.set(row * this.columns + column, value);\n }\n return this;\n }\n\n mmul(other) {\n if (this.columns !== other.rows) {\n // eslint-disable-next-line no-console\n console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\n }\n\n const m = this.rows;\n const p = other.columns;\n\n const result = new SparseMatrix(m, p);\n this.forEachNonZero((i, j, v1) => {\n other.forEachNonZero((k, l, v2) => {\n if (j === k) {\n result.set(i, l, result.get(i, l) + v1 * v2);\n }\n return v2;\n });\n return v1;\n });\n return result;\n }\n\n kroneckerProduct(other) {\n const m = this.rows;\n const n = this.columns;\n const p = other.rows;\n const q = other.columns;\n\n const result = new SparseMatrix(m * p, n * q, {\n initialCapacity: this.cardinality * other.cardinality\n });\n this.forEachNonZero((i, j, v1) => {\n other.forEachNonZero((k, l, v2) => {\n result.set(p * i + k, q * j + l, v1 * v2);\n return v2;\n });\n return v1;\n });\n return result;\n }\n\n forEachNonZero(callback) {\n this.elements.forEachPair((key, value) => {\n const i = (key / this.columns) | 0;\n const j = key % this.columns;\n let r = callback(i, j, value);\n if (r === false) return false; // stop iteration\n if (this.threshold && Math.abs(r) < this.threshold) r = 0;\n if (r !== value) {\n if (r === 0) {\n this.elements.remove(key, true);\n } else {\n this.elements.set(key, r);\n }\n }\n return true;\n });\n this.elements.maybeShrinkCapacity();\n return this;\n }\n\n getNonZeros() {\n const cardinality = this.cardinality;\n const rows = new Array(cardinality);\n const columns = new Array(cardinality);\n const values = new Array(cardinality);\n var idx = 0;\n this.forEachNonZero((i, j, value) => {\n rows[idx] = i;\n columns[idx] = j;\n values[idx] = value;\n idx++;\n return value;\n });\n return {rows, columns, values};\n }\n\n setThreshold(newThreshold) {\n if (newThreshold !== 0 && newThreshold !== this.threshold) {\n this.threshold = newThreshold;\n this.forEachNonZero((i, j, v) => v);\n }\n return this;\n }\n\n /**\n * @return {SparseMatrix} - New transposed sparse matrix\n */\n transpose() {\n let trans = new SparseMatrix(this.columns, this.rows, {initialCapacity: this.cardinality});\n this.forEachNonZero((i, j, value) => {\n trans.set(j, i, value);\n return value;\n });\n return trans;\n }\n}\n\nSparseMatrix.prototype.klass = 'Matrix';\n\nSparseMatrix.identity = SparseMatrix.eye;\nSparseMatrix.prototype.tensorProduct = SparseMatrix.prototype.kroneckerProduct;\n\n/*\n Add dynamically instance and static methods for mathematical operations\n */\n\nvar inplaceOperator = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\nvar inplaceOperatorScalar = `\n(function %name%S(value) {\n this.forEachNonZero((i, j, v) => v %op% value);\n return this;\n})\n`;\n\nvar inplaceOperatorMatrix = `\n(function %name%M(matrix) {\n matrix.forEachNonZero((i, j, v) => {\n this.set(i, j, this.get(i, j) %op% v);\n return v;\n });\n return this;\n})\n`;\n\nvar staticOperator = `\n(function %name%(matrix, value) {\n var newMatrix = new SparseMatrix(matrix);\n return newMatrix.%name%(value);\n})\n`;\n\nvar inplaceMethod = `\n(function %name%() {\n this.forEachNonZero((i, j, v) => %method%(v));\n return this;\n})\n`;\n\nvar staticMethod = `\n(function %name%(matrix) {\n var newMatrix = new SparseMatrix(matrix);\n return newMatrix.%name%();\n})\n`;\n\nconst operators = [\n // Arithmetic operators\n ['+', 'add'],\n ['-', 'sub', 'subtract'],\n ['*', 'mul', 'multiply'],\n ['/', 'div', 'divide'],\n ['%', 'mod', 'modulus'],\n // Bitwise operators\n ['&', 'and'],\n ['|', 'or'],\n ['^', 'xor'],\n ['<<', 'leftShift'],\n ['>>', 'signPropagatingRightShift'],\n ['>>>', 'rightShift', 'zeroFillRightShift']\n];\n\nfor (const operator of operators) {\n for (let i = 1; i < operator.length; i++) {\n SparseMatrix.prototype[operator[i]] = eval(fillTemplateFunction(inplaceOperator, {name: operator[i], op: operator[0]}));\n SparseMatrix.prototype[operator[i] + 'S'] = eval(fillTemplateFunction(inplaceOperatorScalar, {name: operator[i] + 'S', op: operator[0]}));\n SparseMatrix.prototype[operator[i] + 'M'] = eval(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[i] + 'M', op: operator[0]}));\n\n SparseMatrix[operator[i]] = eval(fillTemplateFunction(staticOperator, {name: operator[i]}));\n }\n}\n\nvar methods = [\n ['~', 'not']\n];\n\n[\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\n].forEach(function (mathMethod) {\n methods.push(['Math.' + mathMethod, mathMethod]);\n});\n\nfor (const method of methods) {\n for (let i = 1; i < method.length; i++) {\n SparseMatrix.prototype[method[i]] = eval(fillTemplateFunction(inplaceMethod, {name: method[i], method: method[0]}));\n SparseMatrix[method[i]] = eval(fillTemplateFunction(staticMethod, {name: method[i]}));\n }\n}\n\nfunction fillTemplateFunction(template, values) {\n for (const i in values) {\n template = template.replace(new RegExp('%' + i + '%', 'g'), values[i]);\n }\n return template;\n}\n","module.exports = newArray\n\nfunction newArray (n, value) {\n n = n || 0\n var array = new Array(n)\n for (var i = 0; i < n; i++) {\n array[i] = value\n }\n return array\n}\n","const binarySearch = require('binary-search');\nconst sortAsc = require('num-sort').asc;\n\nconst largestPrime = 0x7fffffff;\n\nconst primeNumbers = [\n //chunk #0\n largestPrime, // 2^31-1\n\n //chunk #1\n 5, 11, 23, 47, 97, 197, 397, 797, 1597, 3203, 6421, 12853, 25717, 51437, 102877, 205759,\n 411527, 823117, 1646237, 3292489, 6584983, 13169977, 26339969, 52679969, 105359939,\n 210719881, 421439783, 842879579, 1685759167,\n\n //chunk #2\n 433, 877, 1759, 3527, 7057, 14143, 28289, 56591, 113189, 226379, 452759, 905551, 1811107,\n 3622219, 7244441, 14488931, 28977863, 57955739, 115911563, 231823147, 463646329, 927292699,\n 1854585413,\n\n //chunk #3\n 953, 1907, 3821, 7643, 15287, 30577, 61169, 122347, 244703, 489407, 978821, 1957651, 3915341,\n 7830701, 15661423, 31322867, 62645741, 125291483, 250582987, 501165979, 1002331963,\n 2004663929,\n\n //chunk #4\n 1039, 2081, 4177, 8363, 16729, 33461, 66923, 133853, 267713, 535481, 1070981, 2141977, 4283963,\n 8567929, 17135863, 34271747, 68543509, 137087021, 274174111, 548348231, 1096696463,\n\n //chunk #5\n 31, 67, 137, 277, 557, 1117, 2237, 4481, 8963, 17929, 35863, 71741, 143483, 286973, 573953,\n 1147921, 2295859, 4591721, 9183457, 18366923, 36733847, 73467739, 146935499, 293871013,\n 587742049, 1175484103,\n\n //chunk #6\n 599, 1201, 2411, 4831, 9677, 19373, 38747, 77509, 155027, 310081, 620171, 1240361, 2480729,\n 4961459, 9922933, 19845871, 39691759, 79383533, 158767069, 317534141, 635068283, 1270136683,\n\n //chunk #7\n 311, 631, 1277, 2557, 5119, 10243, 20507, 41017, 82037, 164089, 328213, 656429, 1312867,\n 2625761, 5251529, 10503061, 21006137, 42012281, 84024581, 168049163, 336098327, 672196673,\n 1344393353,\n\n //chunk #8\n 3, 7, 17, 37, 79, 163, 331, 673, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899,\n 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557,\n 359339171, 718678369, 1437356741,\n\n //chunk #9\n 43, 89, 179, 359, 719, 1439, 2879, 5779, 11579, 23159, 46327, 92657, 185323, 370661, 741337,\n 1482707, 2965421, 5930887, 11861791, 23723597, 47447201, 94894427, 189788857, 379577741,\n 759155483, 1518310967,\n\n //chunk #10\n 379, 761, 1523, 3049, 6101, 12203, 24407, 48817, 97649, 195311, 390647, 781301, 1562611,\n 3125257, 6250537, 12501169, 25002389, 50004791, 100009607, 200019221, 400038451, 800076929,\n 1600153859,\n\n //chunk #11\n 13, 29, 59, 127, 257, 521, 1049, 2099, 4201, 8419, 16843, 33703, 67409, 134837, 269683,\n 539389, 1078787, 2157587, 4315183, 8630387, 17260781, 34521589, 69043189, 138086407,\n 276172823, 552345671, 1104691373,\n\n //chunk #12\n 19, 41, 83, 167, 337, 677,\n 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899,\n 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557,\n 359339171, 718678369, 1437356741,\n\n //chunk #13\n 53, 107, 223, 449, 907, 1823, 3659, 7321, 14653, 29311, 58631, 117269,\n 234539, 469099, 938207, 1876417, 3752839, 7505681, 15011389, 30022781,\n 60045577, 120091177, 240182359, 480364727, 960729461, 1921458943\n];\n\nprimeNumbers.sort(sortAsc);\n\nfunction nextPrime(value) {\n let index = binarySearch(primeNumbers, value, sortAsc);\n if (index < 0) {\n index = ~index;\n }\n return primeNumbers[index];\n}\n\nexports.nextPrime = nextPrime;\nexports.largestPrime = largestPrime;\n","'use strict';\nmodule.exports = Number.isNaN || function (x) {\n\treturn x !== x;\n};\n","\"use strict\";\n\nexports.additiveSymmetric = require('./distances/additiveSymmetric');\nexports.avg = require('./distances/avg');\nexports.bhattacharyya = require('./distances/bhattacharyya');\nexports.canberra = require('./distances/canberra');\nexports.chebyshev = require('./distances/chebyshev');\nexports.clark = require('./distances/clark');\nexports.czekanowski = require('./distances/czekanowski');\nexports.dice = require('./distances/dice');\nexports.divergence = require('./distances/divergence');\nexports.euclidean = require('ml-distance-euclidean');\nexports.fidelity = require('./distances/fidelity');\nexports.gower = require('./distances/gower');\nexports.harmonicMean = require('./distances/harmonicMean');\nexports.hellinger = require('./distances/hellinger');\nexports.innerProduct = require('./distances/innerProduct');\nexports.intersection = require('./distances/intersection');\nexports.jaccard = require('./distances/jaccard');\nexports.jeffreys = require('./distances/jeffreys');\nexports.jensenDifference = require('./distances/jensenDifference');\nexports.jensenShannon = require('./distances/jensenShannon');\nexports.kdivergence = require('./distances/kdivergence');\nexports.kulczynski = require('./distances/kulczynski');\nexports.kullbackLeibler = require('./distances/kullbackLeibler');\nexports.kumarHassebrook = require('./distances/kumarHassebrook');\nexports.kumarJohnson = require('./distances/kumarJohnson');\nexports.lorentzian = require('./distances/lorentzian');\nexports.manhattan = require('./distances/manhattan');\nexports.matusita = require('./distances/matusita');\nexports.minkowski = require('./distances/minkowski');\nexports.motyka = require('./distances/motyka');\nexports.neyman = require('./distances/neyman');\nexports.pearson = require('./distances/pearson');\nexports.probabilisticSymmetric = require('./distances/probabilisticSymmetric');\nexports.ruzicka = require('./distances/ruzicka');\nexports.soergel = require('./distances/soergel');\nexports.sorensen = require('./distances/sorensen');\nexports.squared = require('./distances/squared');\nexports.squaredChord = require('./distances/squaredChord');\nexports.squaredEuclidean = require('ml-distance-euclidean').squared;\nexports.taneja = require('./distances/taneja');\nexports.tanimoto = require('./distances/tanimoto');\nexports.topsoe = require('./distances/topsoe');\nexports.tree = require('ml-tree-similarity');\nexports.waveHedges = require('./distances/waveHedges');\n","module.exports = function additiveSymmetric(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i]) * (a[i] + b[i])) / (a[i] * b[i]);\n }\n return 2 * d;\n};\n","module.exports = function avg(a, b) {\n var ii = a.length,\n max = 0,\n ans = 0,\n aux = 0;\n for (var i = 0; i < ii ; i++) {\n aux = Math.abs(a[i] - b[i]);\n ans += aux;\n if (max < aux) {\n max = aux;\n }\n }\n return (max + ans) / 2;\n};\n","module.exports = function bhattacharyya(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return - Math.log(ans);\n};\n","module.exports = function canberra(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.abs(a[i] - b[i]) / (a[i] + b[i]);\n }\n return ans;\n};\n","module.exports = function chebyshev(a, b) {\n var ii = a.length,\n max = 0,\n aux = 0;\n for (var i = 0; i < ii ; i++) {\n aux = Math.abs(a[i] - b[i]);\n if (max < aux) {\n max = aux;\n }\n }\n return max;\n};\n","module.exports = function clark(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.sqrt(((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i])));\n }\n return 2 * d;\n};\n","'use strict';\n\nconst czekanowskiSimilarity = require('../similarities/czekanowski');\n\nmodule.exports = function czekanowskiDistance(a, b) {\n return 1 - czekanowskiSimilarity(a, b);\n};\n","module.exports = function divergence(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i]));\n }\n return 2 * d;\n};\n","module.exports = function fidelity(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return ans;\n};\n","module.exports = function gower(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.abs(a[i] - b[i]);\n }\n return ans / ii;\n};\n","module.exports = function harmonicMean(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] * b[i]) / (a[i] + b[i]);\n }\n return 2 * ans;\n};\n","module.exports = function hellinger(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return 2 * Math.sqrt(1 - ans);\n};\n","module.exports = function innerProduct(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * b[i];\n }\n return ans;\n};\n","module.exports = function jeffreys(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] - b[i]) * Math.log(a[i] / b[i]);\n }\n return ans;\n};\n","module.exports = function jensenDifference(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += ((a[i] * Math.log(a[i]) + b[i] * Math.log(b[i])) / 2) - ((a[i] + b[i]) / 2) * Math.log((a[i] + b[i]) / 2);\n }\n return ans;\n};\n","module.exports = function jensenShannon(a, b) {\n var ii = a.length,\n p = 0,\n q = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * Math.log(2 * a[i] / (a[i] + b[i]));\n q += b[i] * Math.log(2 * b[i] / (a[i] + b[i]));\n }\n return (p + q) / 2;\n};\n","module.exports = function kdivergence(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i]));\n }\n return ans;\n};\n","module.exports = function kullbackLeibler(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(a[i] / b[i]);\n }\n return ans;\n};\n","module.exports = function kumarHassebrook(a, b) {\n var ii = a.length,\n p = 0,\n p2 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * b[i];\n p2 += a[i] * a[i];\n q2 += b[i] * b[i];\n }\n return p / (p2 + q2 - p);\n};\n","module.exports = function kumarJohnson(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.pow(a[i] * a[i] - b[i] * b[i],2) / (2 * Math.pow(a[i] * b[i],1.5));\n }\n return ans;\n};\n","module.exports = function lorentzian(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.log(Math.abs(a[i] - b[i]) + 1);\n }\n return ans;\n};\n","module.exports = function manhattan(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.abs(a[i] - b[i]);\n }\n return d;\n};\n","module.exports = function matusita(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return Math.sqrt(2 - 2 * ans);\n};\n","module.exports = function minkowski(a, b, p) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.pow(Math.abs(a[i] - b[i]),p);\n }\n return Math.pow(d,(1/p));\n};\n","module.exports = function neyman(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / a[i];\n }\n return d;\n};\n","module.exports = function pearson(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / b[i];\n }\n return d;\n};\n","module.exports = function probabilisticSymmetric(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]);\n }\n return 2 * d;\n};\n","module.exports = function ruzicka(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.min(a[i],b[i]);\n down += Math.max(a[i],b[i]);\n }\n return up / down;\n};\n","module.exports = function soergel(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += Math.max(a[i],b[i]);\n }\n return up / down;\n};\n","module.exports = function sorensen(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += a[i] + b[i];\n }\n return up / down;\n};\n","module.exports = function squared(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]);\n }\n return d;\n};\n","module.exports = function taneja(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] + b[i]) / 2 * Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i])));\n }\n return ans;\n};\n","var tanimotoS = require('./../similarities/tanimoto');\n\nmodule.exports = function tanimoto(a, b, bitvector) {\n if (bitvector)\n return 1 - tanimotoS(a, b, bitvector);\n else {\n var ii = a.length,\n p = 0,\n q = 0,\n m = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i];\n q += b[i];\n m += Math.min(a[i],b[i]);\n }\n return (p + q - 2 * m) / (p + q - m);\n }\n};\n","module.exports = function topsoe(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])) + b[i] * Math.log(2 * b[i] / (a[i] + b[i]));\n }\n return ans;\n};\n","\"use strict\";\n\n/**\n * Function that creates the tree\n * @param {Array } X - chemical shifts of the signal\n * @param {Array } Y - intensity of the signal\n * @param {number} from - the low limit of x\n * @param {number} to - the top limit of x\n * @param {number} minWindow - smallest range to accept in x\n * @param {number} threshold - smallest range to accept in y\n * @returns {{sum: number, center: number, left: {json}, right: {json}}}\n * left and right have the same structure than the parent, or have a\n * undefined value if are leafs\n */\nfunction createTree (X, Y, from, to, minWindow, threshold) {\n minWindow = minWindow || 0.16;\n threshold = threshold || 0.01;\n if ((to - from) < minWindow)\n return undefined;\n var sum = 0;\n for (var i = 0; X[i] < to; i++) {\n if (X[i] > from)\n sum += Y[i];\n }\n if (sum < threshold) {\n return undefined;\n }\n var center = 0;\n for (var j = 0; X[j] < to; j++) {\n if (X[i] > from)\n center += X[j] * Y[j];\n }\n center = center / sum;\n if (((center - from) < 10e-6) || ((to - center) < 10e-6)) return undefined;\n if ((center - from) < (minWindow /4)) {\n return createTree(X, Y, center, to, minWindow, threshold);\n }\n else {\n if ((to - center) < (minWindow / 4)) {\n return createTree(X, Y, from, center, minWindow, threshold);\n }\n else {\n return {\n 'sum': sum,\n 'center': center,\n 'left': createTree(X, Y, from, center, minWindow, threshold),\n 'right': createTree(X, Y, center, to, minWindow, threshold)\n };\n }\n }\n}\n\n/**\n * Similarity between two nodes\n * @param {{sum: number, center: number, left: {json}, right: {json}}} a - tree A node\n * @param {{sum: number, center: number, left: {json}, right: {json}}} b - tree B node\n * @param {number} alpha - weights the relative importance of intensity vs. shift match\n * @param {number} beta - weights the relative importance of node matching and children matching\n * @param {number} gamma - controls the attenuation of the effect of chemical shift differences\n * @returns {number} similarity measure between tree nodes\n */\nfunction S(a, b, alpha, beta, gamma) {\n if (a === undefined || b === undefined) {\n return 0;\n }\n else {\n var C = (alpha*Math.min(a.sum, b.sum)/Math.max(a.sum, b.sum)+ (1-alpha)*Math.exp(-gamma*Math.abs(a.center - b.center)));\n }\n return beta*C + (1-beta)*(S(a.left, b.left, alpha, beta, gamma)+S(a.right, b.right, alpha, beta, gamma));\n}\n\n/**\n * @type {number} alpha - weights the relative importance of intensity vs. shift match\n * @type {number} beta - weights the relative importance of node matching and children matching\n * @type {number} gamma - controls the attenuation of the effect of chemical shift differences\n * @type {number} minWindow - smallest range to accept in x\n * @type {number} threshold - smallest range to accept in y\n */\nvar defaultOptions = {\n minWindow: 0.16,\n threshold : 0.01,\n alpha: 0.1,\n beta: 0.33,\n gamma: 0.001\n};\n\n/**\n * Builds a tree based in the spectra and compares this trees\n * @param {{x: Array, y: Array}} A - first spectra to be compared\n * @param {{x: Array, y: Array}} B - second spectra to be compared\n * @param {number} from - the low limit of x\n * @param {number} to - the top limit of x\n * @param {{minWindow: number, threshold: number, alpha: number, beta: number, gamma: number}} options\n * @returns {number} similarity measure between the spectra\n */\nfunction tree(A, B, from, to, options) {\n options = options || {};\n for (var o in defaultOptions)\n if (!options.hasOwnProperty(o)) {\n options[o] = defaultOptions[o];\n }\n var Atree, Btree;\n if (A.sum)\n Atree = A;\n else\n Atree = createTree(A.x, A.y, from, to, options.minWindow, options.threshold);\n if (B.sum)\n Btree = B;\n else\n Btree = createTree(B.x, B.y, from, to, options.minWindow, options.threshold);\n return S(Atree, Btree, options.alpha, options.beta, options.gamma);\n}\n\nmodule.exports = {\n calc: tree,\n createTree: createTree\n};","module.exports = function waveHedges(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += 1 - (Math.min(a[i], b[i]) / Math.max(a[i], b[i]));\n }\n return ans;\n};\n","\"use strict\";\n\nexports.cosine = require('./similarities/cosine');\nexports.czekanowski = require('./similarities/czekanowski');\nexports.dice = require('./similarities/dice');\nexports.intersection = require('./similarities/intersection');\nexports.jaccard = require('./similarities/jaccard');\nexports.kulczynski = require('./similarities/kulczynski');\nexports.motyka = require('./similarities/motyka');\nexports.pearson = require('./similarities/pearson');\nexports.squaredChord = require('./similarities/squaredChord');\nexports.tanimoto = require('./similarities/tanimoto');\n","var diceD = require('./../distances/dice');\n\nmodule.exports = function dice(a, b) {\n return 1 - diceD(a,b);\n};\n","var intersectionD = require('./../distances/intersection');\n\nmodule.exports = function intersection(a, b) {\n return 1 - intersectionD(a,b);\n};\n","var jaccardD = require('./../distances/jaccard');\n\nmodule.exports = function jaccard(a, b) {\n return 1 - jaccardD(a, b);\n};\n","var kulczynskiD = require('./../distances/kulczynski');\n\nmodule.exports = function kulczynski(a, b) {\n return 1 / kulczynskiD(a, b);\n};\n","var motykaD = require('./../distances/motyka');\n\nmodule.exports = function motyka(a, b) {\n return 1 - motykaD(a,b);\n};\n","'use strict';\n\nvar stat=require('ml-stat').array;\nvar cosine=require('./cosine');\n\nmodule.exports = function pearson(a, b) {\n var avgA=stat.mean(a);\n var avgB=stat.mean(b);\n\n var newA=new Array(a.length);\n var newB=new Array(b.length);\n for (var i=0; i a.pred - b.pred);\n } else {\n predP.sort((a, b) => b.pred - a.pred);\n }\n \n const cutoffs = this.cutoffs = [isDistance ? Number.MIN_VALUE : Number.MAX_VALUE];\n const fp = this.fp = [0];\n const tp = this.tp = [0];\n\n var nPos = 0;\n var nNeg = 0;\n\n var currentPred = predP[0].pred;\n var nTp = 0;\n var nFp = 0;\n for (var i = 0; i < predP.length; i++) {\n if (predP[i].pred !== currentPred) {\n cutoffs.push(currentPred);\n fp.push(nFp);\n tp.push(nTp);\n currentPred = predP[i].pred;\n }\n if (predP[i].targ) {\n nPos++;\n nTp++;\n } else {\n nNeg++;\n nFp++;\n }\n }\n cutoffs.push(currentPred);\n fp.push(nFp);\n tp.push(nTp);\n\n const l = cutoffs.length;\n const fn = this.fn = new Array(l);\n const tn = this.tn = new Array(l);\n const nPosPred = this.nPosPred = new Array(l);\n const nNegPred = this.nNegPred = new Array(l);\n\n for (var i = 0; i < l; i++) {\n fn[i] = nPos - tp[i];\n tn[i] = nNeg - fp[i];\n\n nPosPred[i] = tp[i] + fp[i];\n nNegPred[i] = tn[i] + fn[i];\n }\n\n this.nPos = nPos;\n this.nNeg = nNeg;\n this.nSamples = nPos + nNeg;\n }\n\n /**\n * Computes a measure from the prediction object.\n *\n * Many measures are available and can be combined :\n * To create a ROC curve, you need fpr and tpr\n * To create a DET curve, you need fnr and fpr\n * To create a Lift chart, you need rpp and lift\n *\n * Possible measures are : threshold (Threshold), acc (Accuracy), err (Error rate),\n * fpr (False positive rate), tpr (True positive rate), fnr (False negative rate), tnr (True negative rate), ppv (Positive predictive value),\n * npv (Negative predictive value), pcfall (Prediction-conditioned fallout), pcmiss (Prediction-conditioned miss), lift (Lift value), rpp (Rate of positive predictions), rnp (Rate of negative predictions)\n *\n * @param measure - The short name of the measure\n *\n * @return [number]\n */\n getMeasure(measure) {\n if (typeof measure !== 'string') {\n throw new Error('No measure specified');\n }\n if (!measures[measure]) {\n throw new Error(`The specified measure (${measure}) does not exist`);\n }\n return measures[measure](this);\n }\n\n /**\n * Returns the area under the ROC curve\n */\n getAURC() {\n const l = this.cutoffs.length;\n const x = new Array(l);\n const y = new Array(l);\n for (var i = 0; i < l; i++) {\n x[i] = this.fp[i] / this.nNeg;\n y[i] = this.tp[i] / this.nPos;\n }\n var auc = 0;\n for (i = 1; i < l; i++) {\n auc += 0.5 * (x[i] - x[i - 1]) * (y[i] + y[i - 1]);\n }\n return auc;\n }\n\n /**\n * Returns the area under the DET curve\n */\n getAUDC() {\n const l = this.cutoffs.length;\n const x = new Array(l);\n const y = new Array(l);\n for (var i = 0; i < l; i++) {\n x[i] = this.fn[i] / this.nPos;\n y[i] = this.fp[i] / this.nNeg;\n }\n var auc = 0;\n for (i = 1; i < l; i++) {\n auc += 0.5 * (x[i] + x[i - 1]) * (y[i] - y[i - 1]);\n }\n return auc;\n }\n\n getDistribution(options) {\n options = options || {};\n var cutLength = this.cutoffs.length;\n var cutLow = options.xMin || Math.floor(this.cutoffs[cutLength - 1] * 100) / 100;\n var cutHigh = options.xMax || Math.ceil(this.cutoffs[1] * 100) / 100;\n var interval = options.interval || Math.floor(((cutHigh - cutLow) / 20 * 10000000) - 1) / 10000000; // Trick to avoid the precision problem of float numbers\n\n var xLabels = [];\n var interValues = [];\n var intraValues = [];\n var interCumPercent = [];\n var intraCumPercent = [];\n\n var nTP = this.tp[cutLength - 1], currentTP = 0;\n var nFP = this.fp[cutLength - 1], currentFP = 0;\n\n for (var i = cutLow, j = (cutLength - 1); i <= cutHigh; i += interval) {\n while (this.cutoffs[j] < i)\n j--;\n\n xLabels.push(i);\n\n var thisTP = nTP - currentTP - this.tp[j];\n var thisFP = nFP - currentFP - this.fp[j];\n\n currentTP += thisTP;\n currentFP += thisFP;\n\n interValues.push(thisFP);\n intraValues.push(thisTP);\n\n interCumPercent.push(100 - (nFP - this.fp[j]) / nFP * 100);\n intraCumPercent.push(100 - (nTP - this.tp[j]) / nTP * 100);\n }\n\n return {\n xLabels: xLabels,\n interValues: interValues,\n intraValues: intraValues,\n interCumPercent: interCumPercent,\n intraCumPercent: intraCumPercent\n };\n }\n}\n\nPerformance.names = {\n acc: 'Accuracy',\n err: 'Error rate',\n fpr: 'False positive rate',\n tpr: 'True positive rate',\n fnr: 'False negative rate',\n tnr: 'True negative rate',\n ppv: 'Positive predictive value',\n npv: 'Negative predictive value',\n pcfall: 'Prediction-conditioned fallout',\n pcmiss: 'Prediction-conditioned miss',\n lift: 'Lift value',\n rpp: 'Rate of positive predictions',\n rnp: 'Rate of negative predictions',\n threshold: 'Threshold'\n};\n\nmodule.exports = Performance;\n","'use strict';\n\n// Accuracy\nexports.acc = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.tn[i] + pred.tp[i]) / (l - 1);\n }\n return result;\n};\n\n// Error rate\nexports.err = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.fp[i] / (l - 1));\n }\n return result;\n};\n\n// False positive rate\nexports.fpr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.fp[i] / pred.nNeg;\n }\n return result;\n};\n\n// True positive rate\nexports.tpr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.tp[i] / pred.nPos;\n }\n return result;\n};\n\n// False negative rate\nexports.fnr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.fn[i] / pred.nPos;\n }\n return result;\n};\n\n// True negative rate\nexports.tnr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.tn[i] / pred.nNeg;\n }\n return result;\n};\n\n// Positive predictive value\nexports.ppv = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 0;\n }\n return result;\n};\n\n// Negative predictive value\nexports.npv = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 0;\n }\n return result;\n};\n\n// Prediction conditioned fallout\nexports.pcfall = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? 1 - (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 1;\n }\n return result;\n};\n\n// Prediction conditioned miss\nexports.pcmiss = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? 1 - (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 1;\n }\n return result;\n};\n\n// Lift value\nexports.lift = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.nPosPred[i] !== 0) ? ((pred.tp[i] / pred.nPos) / (pred.nPosPred[i] / pred.nSamples)) : 0;\n }\n return result;\n};\n\n// Rate of positive predictions\nexports.rpp = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.nPosPred[i] / pred.nSamples;\n }\n return result;\n};\n\n// Rate of negative predictions\nexports.rnp = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.nNegPred[i] / pred.nSamples;\n }\n return result;\n};\n\n// Threshold\nexports.threshold = pred => {\n const clone = pred.cutoffs.slice();\n clone[0] = clone[1]; // Remove the infinite value\n return clone;\n};\n","'use strict';\n\nvar matrixLib = require('ml-matrix');\nvar Matrix = matrixLib.Matrix;\nvar inverse = matrixLib.inverse;\nvar padArray = require('ml-pad-array');\nvar extend = require('extend');\n\nvar defaultOptions = {\n windowSize: 5,\n derivative: 1,\n polynomial: 2,\n pad: 'none',\n padValue: 'replicate'\n};\n\n/**\n * Savitzky-Golay filter\n * @param {Array } data\n * @param {number} h\n * @param {Object} options\n * @returns {Array}\n */\nfunction SavitzkyGolay (data, h, options) {\n options = extend({}, defaultOptions, options);\n if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize)))\n throw new RangeError('Invalid window size (should be odd and at least 5 integer number)');\n if ((options.derivative < 0) || !(Number.isInteger(options.derivative)))\n throw new RangeError('Derivative should be a positive integer');\n if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial)))\n throw new RangeError('Polynomial should be a positive integer');\n\n var C, norm;\n var step = Math.floor(options.windowSize / 2);\n\n if (options.pad === 'pre') {\n data = padArray(data, {size: step, value: options.padValue});\n }\n\n var ans = new Array(data.length - 2*step);\n\n if ((options.windowSize === 5) && (options.polynomial === 2) && ((options.derivative === 1) || (options.derivative === 2))) {\n if (options.derivative === 1) {\n C = [-2,-1,0,1,2];\n norm = 10;\n }\n else {\n C = [2, -1, -2, -1, 2];\n norm = 7;\n }\n }\n else {\n var J = Matrix.ones(options.windowSize, options.polynomial + 1);\n var inic = -(options.windowSize - 1) / 2;\n for (var i = 0; i < J.length; i++) {\n for (var j = 0; j < J[i].length; j++) {\n if ((inic + 1 !== 0) || (j !== 0))\n J[i][j] = Math.pow((inic + i), j);\n }\n }\n var Jtranspose = J.transposeView();\n var Jinv = inverse(Jtranspose.mmul(J));\n C = Jinv.mmul(Jtranspose);\n C = C[options.derivative];\n norm = 1;\n }\n var det = norm * Math.pow(h, options.derivative);\n for (var k = step; k < (data.length - step); k++) {\n var d = 0;\n for (var l = 0; l < C.length; l++)\n d += C[l] * data[l + k - step] / det;\n ans[k - step] = d;\n }\n\n if (options.pad === 'post') {\n ans = padArray(ans, {size: step, value: options.padValue});\n }\n\n return ans;\n}\n\nmodule.exports = SavitzkyGolay;\n","//Code translate from Pascal source in http://pubs.acs.org/doi/pdf/10.1021/ac00205a007\nvar extend = require('extend');\nvar stat = require('ml-stat');\n\nvar defaultOptions = {\n windowSize: 9,\n derivative: 0,\n polynomial: 3,\n};\n\n\nfunction SavitzkyGolay(data, h, options) {\n options = extend({}, defaultOptions, options);\n\n if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize)))\n throw new RangeError('Invalid window size (should be odd and at least 5 integer number)')\n\n\n if (options.windowSize>data.length)\n throw new RangeError('Window size is higher than the data length '+options.windowSize+\">\"+data.length);\n if ((options.derivative < 0) || !(Number.isInteger(options.derivative)))\n throw new RangeError('Derivative should be a positive integer');\n if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial)))\n throw new RangeError('Polynomial should be a positive integer');\n if (options.polynomial >= 6)\n console.warn('You should not use polynomial grade higher than 5 if you are' +\n ' not sure that your data arises from such a model. Possible polynomial oscillation problems');\n\n var windowSize = options.windowSize;\n\n var half = Math.floor(windowSize/2);\n var np = data.length;\n var ans = new Array(np);\n var weights = fullWeights(windowSize,options.polynomial,options.derivative);\n var hs = 0;\n var constantH = true;\n if( Object.prototype.toString.call( h ) === '[object Array]' ) {\n constantH = false;\n }\n else{\n hs = Math.pow(h, options.derivative);\n }\n //console.log(\"Constant h: \"+constantH);\n //For the borders\n for(var i=0;i=0 && i < h.length-1){\n hs+= (h[i+1]-h[i]);\n count++;\n }\n }\n return Math.pow(hs/count,derivative);\n}\n\nfunction GramPoly(i,m,k,s){\n var Grampoly = 0;\n if(k>0){\n Grampoly = (4*k-2)/(k*(2*m-k+1))*(i*GramPoly(i,m,k-1,s) +\n s*GramPoly(i,m,k-1,s-1)) - ((k-1)*(2*m+k))/(k*(2*m-k+1))*GramPoly(i,m,k-2,s);\n }\n else{\n if(k==0&&s==0){\n Grampoly=1;\n }\n else{\n Grampoly=0;\n }\n }\n //console.log(Grampoly);\n return Grampoly;\n}\n\nfunction GenFact(a,b){\n var gf=1;\n if(a>=b){\n for(var j=a-b+1;j<=a;j++){\n gf*=j;\n }\n }\n return gf;\n}\n\nfunction Weight(i,t,m,n,s){\n var sum=0;\n for(var k=0;k<=n;k++){\n //console.log(k);\n sum+=(2*k+1)*(GenFact(2*m,k)/GenFact(2*m+k+1,k+1))*GramPoly(i,m,k,0)*GramPoly(t,m,k,s)\n }\n return sum;\n}\n\n/**\n *\n * @param m Number of points\n * @param n Polynomial grade\n * @param s Derivative\n */\nfunction fullWeights(m,n,s){\n var weights = new Array(m);\n var np = Math.floor(m/2);\n for(var t=-np;t<=np;t++){\n weights[t+np] = new Array(m);\n for(var j=-np;j<=np;j++){\n weights[t+np][j+np]=Weight(j,t,np,n,s);\n }\n }\n return weights;\n}\n\n/*function entropy(data,h,options){\n var trend = SavitzkyGolay(data,h,trendOptions);\n var copy = new Array(data.length);\n var sum = 0;\n var max = 0;\n for(var i=0;i> 8) & 0xff] + eightBits[(arr[i] >> 16) & 0xff] + eightBits[(arr[i] >> 24) & 0xff];\n }\n return c;\n}\n\n/**\n * Logical AND operation\n * @param {Array} arr1\n * @param {Array} arr2\n * @return {Array}\n */\nfunction and(arr1, arr2) {\n var ans = new Array(arr1.length);\n for (var i = 0; i < arr1.length; i++)\n ans[i] = arr1[i] & arr2[i];\n return ans;\n}\n\n/**\n * Logical OR operation\n * @param {Array} arr1\n * @param {Array} arr2\n * @return {Array}\n */\nfunction or(arr1, arr2) {\n var ans = new Array(arr1.length);\n for (var i = 0; i < arr1.length; i++)\n ans[i] = arr1[i] | arr2[i];\n return ans;\n}\n\n/**\n * Logical XOR operation\n * @param {Array} arr1\n * @param {Array} arr2\n * @return {Array}\n */\nfunction xor(arr1, arr2) {\n var ans = new Array(arr1.length);\n for (var i = 0; i < arr1.length; i++)\n ans[i] = arr1[i] ^ arr2[i];\n return ans;\n}\n\n/**\n * Logical NOT operation\n * @param {Array} arr\n * @return {Array}\n */\nfunction not(arr) {\n var ans = new Array(arr.length);\n for (var i = 0; i < ans.length; i++)\n ans[i] = ~arr[i];\n return ans;\n}\n\n/**\n * Gets the n value of array arr\n * @param {Array} arr\n * @param {number} n\n * @return {boolean}\n */\nfunction getBit(arr, n) {\n var index = n >> 5; // Same as Math.floor(n/32)\n var mask = 1 << (31 - n % 32);\n return Boolean(arr[index] & mask);\n}\n\n/**\n * Sets the n value of array arr to the value val\n * @param {Array} arr\n * @param {number} n\n * @param {boolean} val\n * @return {Array}\n */\nfunction setBit(arr, n, val) {\n var index = n >> 5; // Same as Math.floor(n/32)\n var mask = 1 << (31 - n % 32);\n if (val)\n arr[index] = mask | arr[index];\n else\n arr[index] = ~mask & arr[index];\n return arr;\n}\n\n/**\n * Translates an array of numbers to a string of bits\n * @param {Array} arr\n * @returns {string}\n */\nfunction toBinaryString(arr) {\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n var obj = (arr[i] >>> 0).toString(2);\n str += '00000000000000000000000000000000'.substr(obj.length) + obj;\n }\n return str;\n}\n\n/**\n * Creates an array of numbers based on a string of bits\n * @param {string} str\n * @returns {Array}\n */\nfunction parseBinaryString(str) {\n var len = str.length / 32;\n var ans = new Array(len);\n for (var i = 0; i < len; i++) {\n ans[i] = parseInt(str.substr(i*32, 32), 2) | 0;\n }\n return ans;\n}\n\n/**\n * Translates an array of numbers to a hex string\n * @param {Array} arr\n * @returns {string}\n */\nfunction toHexString(arr) {\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n var obj = (arr[i] >>> 0).toString(16);\n str += '00000000'.substr(obj.length) + obj;\n }\n return str;\n}\n\n/**\n * Creates an array of numbers based on a hex string\n * @param {string} str\n * @returns {Array}\n */\nfunction parseHexString(str) {\n var len = str.length / 8;\n var ans = new Array(len);\n for (var i = 0; i < len; i++) {\n ans[i] = parseInt(str.substr(i*8, 8), 16) | 0;\n }\n return ans;\n}\n\n/**\n * Creates a human readable string of the array\n * @param {Array} arr\n * @returns {string}\n */\nfunction toDebug(arr) {\n var binary = toBinaryString(arr);\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n str += '0000'.substr((i * 32).toString(16).length) + (i * 32).toString(16) + ':';\n for (var j = 0; j < 32; j += 4) {\n str += ' ' + binary.substr(i * 32 + j, 4);\n }\n if (i < arr.length - 1) str += '\\n';\n }\n return str\n}\n\nmodule.exports = {\n count: count,\n and: and,\n or: or,\n xor: xor,\n not: not,\n getBit: getBit,\n setBit: setBit,\n toBinaryString: toBinaryString,\n parseBinaryString: parseBinaryString,\n toHexString: toHexString,\n parseHexString: parseHexString,\n toDebug: toDebug\n};\n","// auxiliary file to create the 256 look at table elements\n\nvar ans = new Array(256);\nfor (var i = 0; i < 256; i++) {\n var num = i;\n var c = 0;\n while (num) {\n num = num & (num - 1);\n c++;\n }\n ans[i] = c;\n}\n\nmodule.exports = ans;","'use strict';\n\nmodule.exports = exports = require('./ArrayUtils');\n\nexports.getEquallySpacedData = require('./getEquallySpaced').getEquallySpacedData;\nexports.SNV = require('./snv').SNV;\n","'use strict';\n\nconst Stat = require('ml-stat').array;\n/**\n * Function that returns an array of points given 1D array as follows:\n *\n * [x1, y1, .. , x2, y2, ..]\n *\n * And receive the number of dimensions of each point.\n * @param array\n * @param dimensions\n * @returns {Array} - Array of points.\n */\nfunction coordArrayToPoints(array, dimensions) {\n if (array.length % dimensions !== 0) {\n throw new RangeError('Dimensions number must be accordance with the size of the array.');\n }\n\n var length = array.length / dimensions;\n var pointsArr = new Array(length);\n\n var k = 0;\n for (var i = 0; i < array.length; i += dimensions) {\n var point = new Array(dimensions);\n for (var j = 0; j < dimensions; ++j) {\n point[j] = array[i + j];\n }\n\n pointsArr[k] = point;\n k++;\n }\n\n return pointsArr;\n}\n\n\n/**\n * Function that given an array as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * Returns an array as follows:\n * [[x1, x2, ..], [y1, y2, ..], [ .. ]]\n *\n * And receives the number of dimensions of each coordinate.\n * @param array\n * @param dimensions\n * @returns {Array} - Matrix of coordinates\n */\nfunction coordArrayToCoordMatrix(array, dimensions) {\n if (array.length % dimensions !== 0) {\n throw new RangeError('Dimensions number must be accordance with the size of the array.');\n }\n\n var coordinatesArray = new Array(dimensions);\n var points = array.length / dimensions;\n for (var i = 0; i < coordinatesArray.length; i++) {\n coordinatesArray[i] = new Array(points);\n }\n\n for (i = 0; i < array.length; i += dimensions) {\n for (var j = 0; j < dimensions; ++j) {\n var currentPoint = Math.floor(i / dimensions);\n coordinatesArray[j][currentPoint] = array[i + j];\n }\n }\n\n return coordinatesArray;\n}\n\n/**\n * Function that receives a coordinate matrix as follows:\n * [[x1, x2, ..], [y1, y2, ..], [ .. ]]\n *\n * Returns an array of coordinates as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * @param coordMatrix\n * @returns {Array}\n */\nfunction coordMatrixToCoordArray(coordMatrix) {\n var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length);\n var k = 0;\n for (var i = 0; i < coordMatrix[0].length; ++i) {\n for (var j = 0; j < coordMatrix.length; ++j) {\n coodinatesArray[k] = coordMatrix[j][i];\n ++k;\n }\n }\n\n return coodinatesArray;\n}\n\n/**\n * Tranpose a matrix, this method is for coordMatrixToPoints and\n * pointsToCoordMatrix, that because only transposing the matrix\n * you can change your representation.\n *\n * @param matrix\n * @returns {Array}\n */\nfunction transpose(matrix) {\n var resultMatrix = new Array(matrix[0].length);\n for (var i = 0; i < resultMatrix.length; ++i) {\n resultMatrix[i] = new Array(matrix.length);\n }\n\n for (i = 0; i < matrix.length; ++i) {\n for (var j = 0; j < matrix[0].length; ++j) {\n resultMatrix[j][i] = matrix[i][j];\n }\n }\n\n return resultMatrix;\n}\n\n/**\n * Function that transform an array of points into a coordinates array\n * as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * @param points\n * @returns {Array}\n */\nfunction pointsToCoordArray(points) {\n var coodinatesArray = new Array(points.length * points[0].length);\n var k = 0;\n for (var i = 0; i < points.length; ++i) {\n for (var j = 0; j < points[0].length; ++j) {\n coodinatesArray[k] = points[i][j];\n ++k;\n }\n }\n\n return coodinatesArray;\n}\n\n/**\n * Apply the dot product between the smaller vector and a subsets of the\n * largest one.\n *\n * @param firstVector\n * @param secondVector\n * @returns {Array} each dot product of size of the difference between the\n * larger and the smallest one.\n */\nfunction applyDotProduct(firstVector, secondVector) {\n var largestVector, smallestVector;\n if (firstVector.length <= secondVector.length) {\n smallestVector = firstVector;\n largestVector = secondVector;\n } else {\n smallestVector = secondVector;\n largestVector = firstVector;\n }\n\n var difference = largestVector.length - smallestVector.length + 1;\n var dotProductApplied = new Array(difference);\n\n for (var i = 0; i < difference; ++i) {\n var sum = 0;\n for (var j = 0; j < smallestVector.length; ++j) {\n sum += smallestVector[j] * largestVector[i + j];\n }\n dotProductApplied[i] = sum;\n }\n\n return dotProductApplied;\n}\n/**\n * To scale the input array between the specified min and max values. The operation is performed inplace\n * if the options.inplace is specified. If only one of the min or max parameters is specified, then the scaling\n * will multiply the input array by min/min(input) or max/max(input)\n * @param input\n * @param options\n * @returns {*}\n */\nfunction scale(input, options = {}) {\n const {\n min,\n max\n } = options;\n\n var y = options.inPlace ? input : (new Array(input.length));\n var minMax = Stat.minMax(input);\n\n if (typeof max === 'number') {\n if (typeof min === 'number') {\n let factor = (max - min) / (minMax.max - minMax.min);\n for (let i = 0; i < y.length; i++) {\n y[i] = (input[i] - minMax.min) * factor + min;\n }\n } else if (minMax.max !== 0) {\n let factor = max / minMax.max;\n for (let i = 0; i < y.length; i++) {\n y[i] = input[i] * factor;\n }\n } else {\n options.min = minMax.min;\n y = scale(input, options);\n }\n } else if (typeof min === 'number') {\n if (minMax.min !== 0) {\n let factor = min / minMax.min;\n for (let i = 0; i < y.length; i++) {\n y[i] = input[i] * factor;\n }\n\n } else {\n options.max = minMax.max;\n y = scale(input, options);\n }\n }\n return y;\n}\n\nmodule.exports = {\n coordArrayToPoints: coordArrayToPoints,\n coordArrayToCoordMatrix: coordArrayToCoordMatrix,\n coordMatrixToCoordArray: coordMatrixToCoordArray,\n coordMatrixToPoints: transpose,\n pointsToCoordArray: pointsToCoordArray,\n pointsToCoordMatrix: transpose,\n applyDotProduct: applyDotProduct,\n scale: scale\n};\n\n","'use strict';\n\n/**\n *\n * Function that returns a Number array of equally spaced numberOfPoints\n * containing a representation of intensities of the spectra arguments x\n * and y.\n *\n * The options parameter contains an object in the following form:\n * from: starting point\n * to: last point\n * numberOfPoints: number of points between from and to\n * variant: \"slot\" or \"smooth\" - smooth is the default option\n *\n * The slot variant consist that each point in the new array is calculated\n * averaging the existing points between the slot that belongs to the current\n * value. The smooth variant is the same but takes the integral of the range\n * of the slot and divide by the step size between two points in the new array.\n *\n * @param x - sorted increasing x values\n * @param y\n * @param options\n * @returns {Array} new array with the equally spaced data.\n *\n */\nfunction getEquallySpacedData(x, y, options = {}) {\n var xLength = x.length;\n if (x.length > 1 && x[0] > x[1]) {\n x = x.slice().reverse();\n y = y.slice().reverse();\n }\n\n var {\n from = x[0],\n to = x[xLength - 1],\n variant = 'smooth',\n numberOfPoints = 100\n } = options;\n\n if (xLength !== y.length) {\n throw new RangeError(\"the x and y vector doesn't have the same size.\");\n }\n\n if (typeof from !== 'number' || isNaN(from)) {\n throw new RangeError(\"'from' option must be a number\");\n }\n\n if (typeof to !== 'number' || isNaN(to)) {\n throw new RangeError(\"'to' option must be a number\");\n }\n\n var reverse = from > to;\n if (reverse) {\n [from, to] = [to, from];\n }\n\n if (typeof numberOfPoints !== 'number' || isNaN(numberOfPoints)) {\n throw new RangeError(\"'numberOfPoints' option must be a number\");\n }\n if (numberOfPoints < 1) {\n throw new RangeError('the number of points must be at least 1');\n }\n\n var output = variant === 'slot' ? getEquallySpacedSlot(x, y, from, to, numberOfPoints) : getEquallySpacedSmooth(x, y, from, to, numberOfPoints);\n\n return reverse ? output.reverse() : output;\n}\n\n/**\n * function that retrieves the getEquallySpacedData with the variant \"smooth\"\n *\n * @param x\n * @param y\n * @param from - Initial point\n * @param to - Final point\n * @param numberOfPoints\n * @returns {Array} - Array of y's equally spaced with the variant \"smooth\"\n */\nfunction getEquallySpacedSmooth(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n\n var output = new Array(numberOfPoints);\n\n var initialOriginalStep = x[1] - x[0];\n var lastOriginalStep = x[xLength - 1] - x[xLength - 2];\n\n // Init main variables\n var min = from - halfStep;\n var max = from + halfStep;\n\n var previousX = Number.MIN_VALUE;\n var previousY = 0;\n var nextX = x[0] - initialOriginalStep;\n var nextY = 0;\n\n var currentValue = 0;\n var slope = 0;\n var intercept = 0;\n var sumAtMin = 0;\n var sumAtMax = 0;\n\n var i = 0; // index of input\n var j = 0; // index of output\n\n function getSlope(x0, y0, x1, y1) {\n return (y1 - y0) / (x1 - x0);\n }\n\n main: while (true) {\n\n if (previousX <= min && min <= nextX) {\n add = integral(0, min - previousX, slope, previousY);\n sumAtMin = currentValue + add;\n }\n\n while (nextX - max >= 0) {\n // no overlap with original point, just consume current value\n var add = integral(0, max - previousX, slope, previousY);\n sumAtMax = currentValue + add;\n\n output[j++] = (sumAtMax - sumAtMin) / step;\n\n if (j === numberOfPoints) {\n break main;\n }\n\n min = max;\n max += step;\n sumAtMin = sumAtMax;\n }\n\n currentValue += integral(previousX, nextX, slope, intercept);\n\n previousX = nextX;\n previousY = nextY;\n\n if (i < xLength) {\n nextX = x[i];\n nextY = y[i];\n i++;\n } else if (i === xLength) {\n nextX += lastOriginalStep;\n nextY = 0;\n }\n\n slope = getSlope(previousX, previousY, nextX, nextY);\n intercept = -slope * previousX + previousY;\n }\n\n return output;\n}\n\n/**\n * function that retrieves the getEquallySpacedData with the variant \"slot\"\n *\n * @param x\n * @param y\n * @param from - Initial point\n * @param to - Final point\n * @param numberOfPoints\n * @returns {Array} - Array of y's equally spaced with the variant \"slot\"\n */\nfunction getEquallySpacedSlot(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n var lastStep = x[x.length - 1] - x[x.length - 2];\n\n var start = from - halfStep;\n var output = new Array(numberOfPoints);\n\n // Init main variables\n var min = start;\n var max = start + step;\n\n var previousX = -Number.MAX_VALUE;\n var previousY = 0;\n var nextX = x[0];\n var nextY = y[0];\n var frontOutsideSpectra = 0;\n var backOutsideSpectra = true;\n\n var currentValue = 0;\n\n // for slot algorithm\n var currentPoints = 0;\n\n var i = 1; // index of input\n var j = 0; // index of output\n\n main: while (true) {\n if (previousX >= nextX) throw (new Error('x must be an increasing serie'));\n while (previousX - max > 0) {\n // no overlap with original point, just consume current value\n if (backOutsideSpectra) {\n currentPoints++;\n backOutsideSpectra = false;\n }\n\n output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints;\n j++;\n\n if (j === numberOfPoints) {\n break main;\n }\n\n min = max;\n max += step;\n currentValue = 0;\n currentPoints = 0;\n }\n\n if (previousX > min) {\n currentValue += previousY;\n currentPoints++;\n }\n\n if (previousX === -Number.MAX_VALUE || frontOutsideSpectra > 1) {\n currentPoints--;\n }\n\n previousX = nextX;\n previousY = nextY;\n\n if (i < xLength) {\n nextX = x[i];\n nextY = y[i];\n i++;\n } else {\n nextX += lastStep;\n nextY = 0;\n frontOutsideSpectra++;\n }\n }\n\n return output;\n}\n/**\n * Function that calculates the integral of the line between two\n * x-coordinates, given the slope and intercept of the line.\n * @param x0\n * @param x1\n * @param slope\n * @param intercept\n * @returns {number} integral value.\n */\nfunction integral(x0, x1, slope, intercept) {\n return (0.5 * slope * x1 * x1 + intercept * x1) - (0.5 * slope * x0 * x0 + intercept * x0);\n}\n\nexports.getEquallySpacedData = getEquallySpacedData;\nexports.integral = integral;\n","'use strict';\n\nexports.SNV = SNV;\nvar Stat = require('ml-stat').array;\n\n/**\n * Function that applies the standard normal variate (SNV) to an array of values.\n *\n * @param data - Array of values.\n * @returns {Array} - applied the SNV.\n */\nfunction SNV(data) {\n var mean = Stat.mean(data);\n var std = Stat.standardDeviation(data);\n var result = data.slice();\n for (var i = 0; i < data.length; i++) {\n result[i] = (result[i] - mean) / std;\n }\n return result;\n}\n","import isArray from 'is-any-array';\n\n/**\n * Computes the mode of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction mode(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var maxValue = 0;\n var maxCount = 0;\n var count = 0;\n var counts = {};\n\n for (var i = 0; i < input.length; ++i) {\n var element = input[i];\n count = counts[element];\n\n if (count) {\n counts[element]++;\n count++;\n } else {\n counts[element] = count = 1;\n }\n\n if (count > maxCount) {\n maxCount = count;\n maxValue = input[i];\n }\n }\n\n return maxValue;\n}\n\nexport default mode;\n","/**\n * Computes the norm of the given values\n * @param {Array} input\n * @param {object} [options={}]\n * @param {string} [algorithm='absolute']\n * @return {number}\n */\nfunction norm(input) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var _options$algorithm = options.algorithm,\n algorithm = _options$algorithm === void 0 ? 'absolute' : _options$algorithm;\n\n if (!Array.isArray(input)) {\n throw new Error('input must be an array');\n }\n\n if (input.length === 0) {\n throw new Error('input must not be empty');\n }\n\n switch (algorithm.toLowerCase()) {\n case 'absolute':\n var sum = absoluteSum(input);\n if (sum === 0) return input.slice(0);\n return input.map(function (element) {\n return element / sum;\n });\n\n default:\n throw new Error(\"norm: unknown algorithm: \".concat(algorithm));\n }\n}\n\nfunction absoluteSum(input) {\n var sum = 0;\n\n for (var i = 0; i < input.length; i++) {\n sum += Math.abs(input[i]);\n }\n\n return sum;\n}\n\nexport default norm;\n","import variance from 'ml-array-variance';\n\n/**\n * Computes the standard deviation of the given values\n * @param {Array} values\n * @param {object} [options]\n * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n.\n * @param {number} [options.mean = arrayMean] - precalculated mean, if any.\n * @return {number}\n */\n\nfunction standardDeviation(values) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return Math.sqrt(variance(values, options));\n}\n\nexport default standardDeviation;\n","/**\n * Merge abscissa values if the ordinate value is in a list of centroids\n * @param {object} originalPoints\n * @param {Array} originalPoints.x\n * @param {Array} originalPoints.y\n * @param {Array} centroids\n * @param {object} [options]\n * @param {number} [options.window = 0.01] - has to be a positive number\n * @return {{x: Array, y: Array}}\n */\nexport default function mergeByCentroids(\n originalPoints,\n centroids,\n options = {}\n) {\n const { window = 0.01 } = options;\n\n var mergedPoints = {\n x: centroids.slice(),\n y: new Array(centroids.length).fill(0)\n };\n\n var originalIndex = 0;\n var mergedIndex = 0;\n while (\n originalIndex < originalPoints.x.length &&\n mergedIndex < centroids.length\n ) {\n var diff = originalPoints.x[originalIndex] - centroids[mergedIndex];\n if (Math.abs(diff) < window) {\n mergedPoints.y[mergedIndex] += originalPoints.y[originalIndex++];\n } else if (diff < 0) {\n originalIndex++;\n } else {\n mergedIndex++;\n }\n }\n\n return mergedPoints;\n}\n","import binarySearch from 'binary-search';\nimport { asc, desc } from 'num-sort';\n\n/**\n *\n * @param {object} points\n * @param {Array} originalPoints.x\n * @param {Array} originalPoints.y\n * @param {*} options\n * @return {{x: Array, y: Array}}\n */\nexport default function closestX(points, options) {\n const { x, y } = points;\n const { target = x[0], reverse = false } = options;\n\n let index;\n if (reverse) {\n index = binarySearch(x, target, desc);\n } else {\n index = binarySearch(x, target, asc);\n }\n\n if (index >= 0) {\n return {\n x: x[index],\n y: y[index]\n };\n } else {\n index = ~index;\n if (\n (index !== 0 && Math.abs(x[index] - target) > 0.5) ||\n index === x.length\n ) {\n return {\n x: x[index - 1],\n y: y[index - 1]\n };\n } else {\n return {\n x: x[index],\n y: y[index]\n };\n }\n }\n}\n","/**\n * Merge abscissas values on similar ordinates and weight the group of abscissas\n * @param {object} points\n * @param {Array} points.x - sorted abscissas values\n * @param {Array} points.y - ordinates values\n * @param {object} [options]\n * @param {number} [options.groupWidth = 0.001] - window for abscissas to merge\n * @return {{x: Array, y: Array}}\n */\nexport default function maxMerge(points, options = {}) {\n const { x, y } = points;\n const { groupWidth = 0.001 } = options;\n\n var merged = { x: [], y: [] };\n var maxAbscissa = { x: [], y: [] };\n var size = 0;\n var index = 0;\n\n while (index < x.length) {\n if (size === 0 || x[index] - merged.x[size - 1] > groupWidth) {\n maxAbscissa.x.push(x[index]);\n maxAbscissa.y.push(y[index]);\n merged.x.push(x[index]);\n merged.y.push(y[index]);\n index++;\n size++;\n } else {\n if (y[index] > maxAbscissa.y[size - 1]) {\n maxAbscissa.x[size - 1] = x[index];\n maxAbscissa.y[size - 1] = y[index];\n }\n merged.x[size - 1] = x[index];\n merged.y[size - 1] += y[index];\n index++;\n }\n }\n\n merged.x = maxAbscissa.x.slice();\n\n return merged;\n}\n","import binarySearch from 'binary-search';\nimport { asc, desc } from 'num-sort';\n\n/**\n * @param {object} points\n * @param {Array} points.x - sorted abscissas values\n * @param {Array} points.y - ordinates values\n * @param {object} [options]\n * @param {object} [options.from = {index: 0}]\n * @param {object} [options.to = {index: x.length-1}]\n * @param {boolean} [options.reverse = false]\n * @return {{index: number, value: number}}\n */\nexport default function maxY(points, options = {}) {\n const { x, y } = points;\n let {\n from = { index: 0 },\n to = { index: x.length },\n reverse = false\n } = options;\n\n if (from.value !== undefined && from.index === undefined) {\n from.index = calculateIndex(from.value, x, reverse);\n }\n\n if (to.value !== undefined && to.index === undefined) {\n to.index = calculateIndex(to.value, x, reverse);\n }\n\n var currentMax = Number.MIN_VALUE;\n var currentIndex;\n for (var i = from.index; i < to.index; i++) {\n if (currentMax < y[i]) {\n currentMax = y[i];\n currentIndex = i;\n }\n }\n\n return {\n index: currentIndex,\n value: currentMax\n };\n}\n\n/**\n * @param {number} value\n * @param {Array} x\n * @param {boolean} reverse\n * @return {number} index of the value in the array\n */\nfunction calculateIndex(value, x, reverse) {\n let index;\n if (reverse) {\n index = binarySearch(x, value, desc);\n } else {\n index = binarySearch(x, value, asc);\n }\n\n if (index < 0) {\n throw new Error(`the value ${value} doesn't belongs to the abscissa value`);\n }\n\n return index;\n}\n","export default function sortX(points, options = {}) {\n const { x, y } = points;\n const { reverse = false } = options;\n\n var sortFunc;\n if (!reverse) {\n sortFunc = (a, b) => a.x - b.x;\n } else {\n sortFunc = (a, b) => b.x - a.x;\n }\n\n var grouped = x\n .map((val, index) => ({\n x: val,\n y: y[index]\n }))\n .sort(sortFunc);\n\n var response = { x: x.slice(), y: y.slice() };\n for (var i = 0; i < x.length; i++) {\n response.x[i] = grouped[i].x;\n response.y[i] = grouped[i].y;\n }\n\n return response;\n}\n","\n/**\n * In place modification of the 2 arrays to make X unique and sum the Y if X has the same value\n * @param {object} [points={}] : Object of points contains property x (an array) and y (an array)\n * @return points\n */\n\nexport default function uniqueX(points = {}) {\n const { x, y } = points;\n if (x.length < 2) return;\n if (x.length !== y.length) {\n throw new Error('The X and Y arrays mush have the same length');\n }\n\n let current = x[0];\n let counter = 0;\n\n for (let i = 1; i < x.length; i++) {\n if (current !== x[i]) {\n counter++;\n current = x[i];\n x[counter] = x[i];\n if (i !== counter) {\n y[counter] = 0;\n }\n }\n if (i !== counter) {\n y[counter] += y[i];\n }\n }\n\n x.length = counter + 1;\n y.length = counter + 1;\n}\n","/**\n * Merge abscissas values on similar ordinates and weight the group of abscissas\n * @param {object} points\n * @param {Array} points.x - sorted abscissas values\n * @param {Array} points.y - ordinates values\n * @param {object} [options]\n * @param {number} [options.groupWidth = 0.001] - window for abscissas to merge\n * @return {{x: Array, y: Array}}\n */\nexport default function weightedMerge(points, options = {}) {\n const { x, y } = points;\n const { groupWidth = 0.001 } = options;\n\n var merged = { x: [], y: [] };\n var weightedAbscissa = { x: [], y: [] };\n var size = 0;\n var index = 0;\n\n while (index < x.length) {\n if (size === 0 || x[index] - merged.x[size - 1] > groupWidth) {\n weightedAbscissa.x.push(x[index] * y[index]);\n weightedAbscissa.y.push(y[index]);\n merged.x.push(x[index]);\n merged.y.push(y[index]);\n index++;\n size++;\n } else {\n weightedAbscissa.x[size - 1] += x[index] * y[index];\n weightedAbscissa.y[size - 1] += y[index];\n merged.x[size - 1] = x[index];\n merged.y[size - 1] += y[index];\n index++;\n }\n }\n\n for (var i = 0; i < merged.x.length; i++) {\n merged.x[i] = weightedAbscissa.x[i] / weightedAbscissa.y[i];\n }\n\n return merged;\n}\n","export function squaredEuclidean(p, q) {\r\n let d = 0;\r\n for (let i = 0; i < p.length; i++) {\r\n d += (p[i] - q[i]) * (p[i] - q[i]);\r\n }\r\n return d;\r\n}\r\nexport function euclidean(p, q) {\r\n return Math.sqrt(squaredEuclidean(p, q));\r\n}\r\n","export function squaredEuclidean(p, q) {\r\n let d = 0;\r\n for (let i = 0; i < p.length; i++) {\r\n d += (p[i] - q[i]) * (p[i] - q[i]);\r\n }\r\n return d;\r\n}\r\nexport function euclidean(p, q) {\r\n return Math.sqrt(squaredEuclidean(p, q));\r\n}\r\n","'use strict';\nimport { squaredEuclidean } from 'ml-distance-euclidean';\nconst defaultOptions = {\n distanceFunction: squaredEuclidean\n};\nexport default function nearestVector(listVectors, vector, options = defaultOptions) {\n const distanceFunction = options.distanceFunction || defaultOptions.distanceFunction;\n const similarityFunction = options.similarityFunction || defaultOptions.similarityFunction;\n let vectorIndex = -1;\n if (typeof similarityFunction === 'function') {\n // maximum similarity\n let maxSim = Number.MIN_VALUE;\n for (let j = 0; j < listVectors.length; j++) {\n const sim = similarityFunction(vector, listVectors[j]);\n if (sim > maxSim) {\n maxSim = sim;\n vectorIndex = j;\n }\n }\n }\n else if (typeof distanceFunction === 'function') {\n // minimum distance\n let minDist = Number.MAX_VALUE;\n for (let i = 0; i < listVectors.length; i++) {\n const dist = distanceFunction(vector, listVectors[i]);\n if (dist < minDist) {\n minDist = dist;\n vectorIndex = i;\n }\n }\n }\n else {\n throw new Error(\"A similarity or distance function it's required\");\n }\n return vectorIndex;\n}\nexport function findNearestVector(vectorList, vector, options = defaultOptions) {\n const index = nearestVector(vectorList, vector, options);\n return vectorList[index];\n}\n","import nearestVector from 'ml-nearest-vector';\n\n/**\n * Calculates the distance matrix for a given array of points\n * @ignore\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @param {function} distance - Distance function to use between the points\n * @return {Array>} - matrix with the distance values\n */\nexport function calculateDistanceMatrix(data, distance) {\n var distanceMatrix = new Array(data.length);\n for (var i = 0; i < data.length; ++i) {\n for (var j = i; j < data.length; ++j) {\n if (!distanceMatrix[i]) {\n distanceMatrix[i] = new Array(data.length);\n }\n if (!distanceMatrix[j]) {\n distanceMatrix[j] = new Array(data.length);\n }\n const dist = distance(data[i], data[j]);\n distanceMatrix[i][j] = dist;\n distanceMatrix[j][i] = dist;\n }\n }\n return distanceMatrix;\n}\n\n/**\n * Updates the cluster identifier based in the new data\n * @ignore\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @param {Array>} centers - the K centers in format [x,y,z,...]\n * @param {Array } clusterID - the cluster identifier for each data dot\n * @param {function} distance - Distance function to use between the points\n * @return {Array} the cluster identifier for each data dot\n */\nexport function updateClusterID(data, centers, clusterID, distance) {\n for (var i = 0; i < data.length; i++) {\n clusterID[i] = nearestVector(centers, data[i], {\n distanceFunction: distance\n });\n }\n return clusterID;\n}\n\n/**\n * Update the center values based in the new configurations of the clusters\n * @ignore\n * @param {Array>} prevCenters - Centroids from the previous iteration\n * @param {Array >} data - the [x,y,z,...] points to cluster\n * @param {Array } clusterID - the cluster identifier for each data dot\n * @param {number} K - Number of clusters\n * @return {Array} he K centers in format [x,y,z,...]\n */\nexport function updateCenters(prevCenters, data, clusterID, K) {\n const nDim = data[0].length;\n\n // copy previous centers\n var centers = new Array(K);\n var centersLen = new Array(K);\n for (var i = 0; i < K; i++) {\n centers[i] = new Array(nDim);\n centersLen[i] = 0;\n for (var j = 0; j < nDim; j++) {\n centers[i][j] = 0;\n }\n }\n\n // add the value for all dimensions of the point\n for (var l = 0; l < data.length; l++) {\n centersLen[clusterID[l]]++;\n for (var dim = 0; dim < nDim; dim++) {\n centers[clusterID[l]][dim] += data[l][dim];\n }\n }\n\n // divides by length\n for (var id = 0; id < K; id++) {\n for (var d = 0; d < nDim; d++) {\n if (centersLen[id]) {\n centers[id][d] /= centersLen[id];\n } else {\n centers[id][d] = prevCenters[id][d];\n }\n }\n }\n return centers;\n}\n\n/**\n * The centers have moved more than the tolerance value?\n * @ignore\n * @param {Array>} centers - the K centers in format [x,y,z,...]\n * @param {Array>} oldCenters - the K old centers in format [x,y,z,...]\n * @param {function} distanceFunction - Distance function to use between the points\n * @param {number} tolerance - Allowed distance for the centroids to move\n * @return {boolean}\n */\nexport function hasConverged(centers, oldCenters, distanceFunction, tolerance) {\n for (var i = 0; i < centers.length; i++) {\n if (distanceFunction(centers[i], oldCenters[i]) > tolerance) {\n return false;\n }\n }\n return true;\n}\n","import Random from 'ml-random';\nimport { squaredEuclidean } from 'ml-distance-euclidean';\nimport { Matrix } from 'ml-matrix';\n\n/**\n * Choose K different random points from the original data\n * @ignore\n * @param {Array>} data - Points in the format to cluster [x,y,z,...]\n * @param {number} K - number of clusters\n * @param {number} seed - seed for random number generation\n * @return {Array>} - Initial random points\n */\nexport function random(data, K, seed) {\n const random = new Random(seed);\n return random.choice(data, { size: K });\n}\n\n/**\n * Chooses the most distant points to a first random pick\n * @ignore\n * @param {Array>} data - Points in the format to cluster [x,y,z,...]\n * @param {number} K - number of clusters\n * @param {Array>} distanceMatrix - matrix with the distance values\n * @param {number} seed - seed for random number generation\n * @return {Array>} - Initial random points\n */\nexport function mostDistant(data, K, distanceMatrix, seed) {\n const random = new Random(seed);\n var ans = new Array(K);\n // chooses a random point as initial cluster\n ans[0] = Math.floor(random.random() * data.length);\n\n if (K > 1) {\n // chooses the more distant point\n var maxDist = { dist: -1, index: -1 };\n for (var l = 0; l < data.length; ++l) {\n if (distanceMatrix[ans[0]][l] > maxDist.dist) {\n maxDist.dist = distanceMatrix[ans[0]][l];\n maxDist.index = l;\n }\n }\n ans[1] = maxDist.index;\n\n if (K > 2) {\n // chooses the set of points that maximises the min distance\n for (var k = 2; k < K; ++k) {\n var center = { dist: -1, index: -1 };\n for (var m = 0; m < data.length; ++m) {\n // minimum distance to centers\n var minDistCent = { dist: Number.MAX_VALUE, index: -1 };\n for (var n = 0; n < k; ++n) {\n if (\n distanceMatrix[n][m] < minDistCent.dist &&\n ans.indexOf(m) === -1\n ) {\n minDistCent = {\n dist: distanceMatrix[n][m],\n index: m\n };\n }\n }\n\n if (\n minDistCent.dist !== Number.MAX_VALUE &&\n minDistCent.dist > center.dist\n ) {\n center = Object.assign({}, minDistCent);\n }\n }\n\n ans[k] = center.index;\n }\n }\n }\n\n return ans.map((index) => data[index]);\n}\n\n// Implementation inspired from scikit\nexport function kmeanspp(X, K, options = {}) {\n X = new Matrix(X);\n const nSamples = X.length;\n const random = new Random(options.seed);\n // Set the number of trials\n const centers = [];\n const localTrials = options.localTrials || 2 + Math.floor(Math.log(K));\n\n // Pick the first center at random from the dataset\n const firstCenterIdx = random.randInt(nSamples);\n centers.push(X[firstCenterIdx].slice());\n\n // Init closest distances\n let closestDistSquared = [X.map((x) => squaredEuclidean(x, centers[0]))];\n let cumSumClosestDistSquared = [cumSum(closestDistSquared[0])];\n const factor = 1 / cumSumClosestDistSquared[0][nSamples - 1];\n let probabilities = Matrix.mul(closestDistSquared, factor);\n\n // Iterate over the remaining centers\n for (let i = 1; i < K; i++) {\n const candidateIdx = random.choice(nSamples, {\n replace: true,\n size: localTrials,\n probabilities: probabilities[0]\n });\n\n const candidates = X.selection(candidateIdx, range(X[0].length));\n const distanceToCandidates = euclidianDistances(candidates, X);\n\n let bestCandidate;\n let bestPot;\n let bestDistSquared;\n\n for (let j = 0; j < localTrials; j++) {\n const newDistSquared = Matrix.min(closestDistSquared, [distanceToCandidates[j]]);\n const newPot = newDistSquared.sum();\n if (bestCandidate === undefined || newPot < bestPot) {\n bestCandidate = candidateIdx[j];\n bestPot = newPot;\n bestDistSquared = newDistSquared;\n }\n }\n centers[i] = X[bestCandidate].slice();\n closestDistSquared = bestDistSquared;\n cumSumClosestDistSquared = [cumSum(closestDistSquared[0])];\n probabilities = Matrix.mul(\n closestDistSquared,\n 1 / cumSumClosestDistSquared[0][nSamples - 1]\n );\n }\n return centers;\n}\n\nfunction euclidianDistances(A, B) {\n const result = new Matrix(A.length, B.length);\n for (let i = 0; i < A.length; i++) {\n for (let j = 0; j < B.length; j++) {\n result.set(i, j, squaredEuclidean(A.getRow(i), B.getRow(j)));\n }\n }\n return result;\n}\n\nfunction range(l) {\n let r = [];\n for (let i = 0; i < l; i++) {\n r.push(i);\n }\n return r;\n}\n\nfunction cumSum(arr) {\n let cumSum = [arr[0]];\n for (let i = 1; i < arr.length; i++) {\n cumSum[i] = cumSum[i - 1] + arr[i];\n }\n return cumSum;\n}\n","import { updateClusterID } from './utils';\n\nconst distanceSymbol = Symbol('distance');\n\nexport default class KMeansResult {\n /**\n * Result of the kmeans algorithm\n * @param {Array} clusters - the cluster identifier for each data dot\n * @param {Array>} centroids - the K centers in format [x,y,z,...], the error and size of the cluster\n * @param {boolean} converged - Converge criteria satisfied\n * @param {number} iterations - Current number of iterations\n * @param {function} distance - (*Private*) Distance function to use between the points\n * @constructor\n */\n constructor(clusters, centroids, converged, iterations, distance) {\n this.clusters = clusters;\n this.centroids = centroids;\n this.converged = converged;\n this.iterations = iterations;\n this[distanceSymbol] = distance;\n }\n\n /**\n * Allows to compute for a new array of points their cluster id\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @return {Array} - cluster id for each point\n */\n nearest(data) {\n const clusterID = new Array(data.length);\n const centroids = this.centroids.map(function (centroid) {\n return centroid.centroid;\n });\n return updateClusterID(data, centroids, clusterID, this[distanceSymbol]);\n }\n\n /**\n * Returns a KMeansResult with the error and size of the cluster\n * @ignore\n * @param {Array>} data - the [x,y,z,...] points to cluster\n * @return {KMeansResult}\n */\n computeInformation(data) {\n var enrichedCentroids = this.centroids.map(function (centroid) {\n return {\n centroid: centroid,\n error: 0,\n size: 0\n };\n });\n\n for (var i = 0; i < data.length; i++) {\n enrichedCentroids[this.clusters[i]].error += this[distanceSymbol](\n data[i],\n this.centroids[this.clusters[i]]\n );\n enrichedCentroids[this.clusters[i]].size++;\n }\n\n for (var j = 0; j < this.centroids.length; j++) {\n if (enrichedCentroids[j].size) {\n enrichedCentroids[j].error /= enrichedCentroids[j].size;\n } else {\n enrichedCentroids[j].error = null;\n }\n }\n\n return new KMeansResult(\n this.clusters,\n enrichedCentroids,\n this.converged,\n this.iterations,\n this[distanceSymbol]\n );\n }\n}\n","import { squaredEuclidean } from 'ml-distance-euclidean';\n\nimport {\n updateClusterID,\n updateCenters,\n hasConverged,\n calculateDistanceMatrix\n} from './utils';\nimport { mostDistant, random, kmeanspp } from './initialization';\nimport KMeansResult from './KMeansResult';\n\nconst defaultOptions = {\n maxIterations: 100,\n tolerance: 1e-6,\n withIterations: false,\n initialization: 'kmeans++',\n distanceFunction: squaredEuclidean\n};\n\n/**\n * Each step operation for kmeans\n * @ignore\n * @param {Array>} centers - K centers in format [x,y,z,...]\n * @param {Array>} data - Points [x,y,z,...] to cluster\n * @param {Array} clusterID - Cluster identifier for each data dot\n * @param {number} K - Number of clusters\n * @param {object} [options] - Option object\n * @param {number} iterations - Current number of iterations\n * @return {KMeansResult}\n */\nfunction step(centers, data, clusterID, K, options, iterations) {\n clusterID = updateClusterID(\n data,\n centers,\n clusterID,\n options.distanceFunction\n );\n var newCenters = updateCenters(centers, data, clusterID, K);\n var converged = hasConverged(\n newCenters,\n centers,\n options.distanceFunction,\n options.tolerance\n );\n return new KMeansResult(\n clusterID,\n newCenters,\n converged,\n iterations,\n options.distanceFunction\n );\n}\n\n/**\n * Generator version for the algorithm\n * @ignore\n * @param {Array>} centers - K centers in format [x,y,z,...]\n * @param {Array>} data - Points [x,y,z,...] to cluster\n * @param {Array} clusterID - Cluster identifier for each data dot\n * @param {number} K - Number of clusters\n * @param {object} [options] - Option object\n */\nfunction* kmeansGenerator(centers, data, clusterID, K, options) {\n var converged = false;\n var stepNumber = 0;\n var stepResult;\n while (!converged && stepNumber < options.maxIterations) {\n stepResult = step(centers, data, clusterID, K, options, ++stepNumber);\n yield stepResult.computeInformation(data);\n converged = stepResult.converged;\n centers = stepResult.centroids;\n }\n}\n\n/**\n * K-means algorithm\n * @param {Array>} data - Points in the format to cluster [x,y,z,...]\n * @param {number} K - Number of clusters\n * @param {object} [options] - Option object\n * @param {number} [options.maxIterations = 100] - Maximum of iterations allowed\n * @param {number} [options.tolerance = 1e-6] - Error tolerance\n * @param {boolean} [options.withIterations = false] - Store clusters and centroids for each iteration\n * @param {function} [options.distanceFunction = squaredDistance] - Distance function to use between the points\n * @param {number} [options.seed] - Seed for random initialization.\n * @param {string|Array>} [options.initialization = 'kmeans++'] - K centers in format [x,y,z,...] or a method for initialize the data:\n * * You can either specify your custom start centroids, or select one of the following initialization method:\n * * `'kmeans++'` will use the kmeans++ method as described by http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf\n * * `'random'` will choose K random different values.\n * * `'mostDistant'` will choose the more distant points to a first random pick\n * @return {KMeansResult} - Cluster identifier for each data dot and centroids with the following fields:\n * * `'clusters'`: Array of indexes for the clusters.\n * * `'centroids'`: Array with the resulting centroids.\n * * `'iterations'`: Number of iterations that took to converge\n */\nexport default function kmeans(data, K, options) {\n options = Object.assign({}, defaultOptions, options);\n\n if (K <= 0 || K > data.length || !Number.isInteger(K)) {\n throw new Error(\n 'K should be a positive integer smaller than the number of points'\n );\n }\n\n var centers;\n if (Array.isArray(options.initialization)) {\n if (options.initialization.length !== K) {\n throw new Error('The initial centers should have the same length as K');\n } else {\n centers = options.initialization;\n }\n } else {\n switch (options.initialization) {\n case 'kmeans++':\n centers = kmeanspp(data, K, options);\n break;\n case 'random':\n centers = random(data, K, options.seed);\n break;\n case 'mostDistant':\n centers = mostDistant(\n data,\n K,\n calculateDistanceMatrix(data, options.distanceFunction),\n options.seed\n );\n break;\n default:\n throw new Error(\n `Unknown initialization method: \"${options.initialization}\"`\n );\n }\n }\n\n // infinite loop until convergence\n if (options.maxIterations === 0) {\n options.maxIterations = Number.MAX_VALUE;\n }\n\n var clusterID = new Array(data.length);\n if (options.withIterations) {\n return kmeansGenerator(centers, data, clusterID, K, options);\n } else {\n var converged = false;\n var stepNumber = 0;\n var stepResult;\n while (!converged && stepNumber < options.maxIterations) {\n stepResult = step(centers, data, clusterID, K, options, ++stepNumber);\n converged = stepResult.converged;\n centers = stepResult.centroids;\n }\n return stepResult.computeInformation(data);\n }\n}\n","import Random from 'random-js';\nimport Matrix from 'ml-matrix';\n\nexport function checkFloat(n) {\n return n > 0.0 && n <= 1.0;\n}\n\n/**\n * Select n with replacement elements on the training set and values, where n is the size of the training set.\n * @ignore\n * @param {Matrix} trainingSet\n * @param {Array} trainingValue\n * @param {number} seed - seed for the random selection, must be a 32-bit integer.\n * @return {object} with new X and y.\n */\nexport function examplesBaggingWithReplacement(trainingSet, trainingValue, seed) {\n var engine = Random.engines.mt19937();\n var distribution = Random.integer(0, trainingSet.rows - 1);\n if (seed === undefined) {\n engine = engine.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = engine.seed(seed);\n } else {\n throw new RangeError(`Expected seed must be undefined or integer not ${seed}`);\n }\n\n var Xr = new Array(trainingSet.rows);\n var yr = new Array(trainingSet.rows);\n\n for (var i = 0; i < trainingSet.rows; ++i) {\n var index = distribution(engine);\n Xr[i] = trainingSet[index];\n yr[i] = trainingValue[index];\n }\n\n return {\n X: new Matrix(Xr),\n y: yr\n };\n}\n\n/**\n * selects n features from the training set with or without replacement, returns the new training set and the indexes used.\n * @ignore\n * @param {Matrix} trainingSet\n * @param {number} n - features.\n * @param {boolean} replacement\n * @param {number} seed - seed for the random selection, must be a 32-bit integer.\n * @return {object}\n */\nexport function featureBagging(trainingSet, n, replacement, seed) {\n if (trainingSet.columns < n) {\n throw new RangeError('N should be less or equal to the number of columns of X');\n }\n\n var distribution = Random.integer(0, trainingSet.columns - 1);\n var engine = Random.engines.mt19937();\n if (seed === undefined) {\n engine = engine.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = engine.seed(seed);\n } else {\n throw new RangeError(`Expected seed must be undefined or integer not ${seed}`);\n }\n\n var toRet = new Matrix(trainingSet.rows, n);\n\n if (replacement) {\n var usedIndex = new Array(n);\n for (var i = 0; i < n; ++i) {\n var index = distribution(engine);\n usedIndex[i] = index;\n toRet.setColumn(i, trainingSet.getColumn(index));\n }\n } else {\n usedIndex = new Set();\n index = distribution(engine);\n for (i = 0; i < n; ++i) {\n while (usedIndex.has(index)) {\n index = distribution(engine);\n }\n toRet.setColumn(i, trainingSet.getColumn(index));\n usedIndex.add(index);\n }\n usedIndex = Array.from(usedIndex);\n }\n\n return {\n X: toRet,\n usedIndex: usedIndex\n };\n}\n","import {\n DecisionTreeClassifier as DTClassifier,\n DecisionTreeRegression as DTRegression\n} from 'ml-cart';\nimport { Matrix, WrapperMatrix2D } from 'ml-matrix';\n\nimport * as Utils from './utils';\n\n/**\n * @class RandomForestBase\n */\nexport class RandomForestBase {\n /**\n * Create a new base random forest for a classifier or regression model.\n * @constructor\n * @param {object} options\n * @param {number|String} [options.maxFeatures] - the number of features used on each estimator.\n * * if is an integer it selects maxFeatures elements over the sample features.\n * * if is a float between (0, 1), it takes the percentage of features.\n * @param {boolean} [options.replacement] - use replacement over the sample features.\n * @param {number} [options.seed] - seed for feature and samples selection, must be a 32-bit integer.\n * @param {number} [options.nEstimators] - number of estimator to use.\n * @param {object} [options.treeOptions] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/}\n * @param {boolean} [options.isClassifier] - boolean to check if is a classifier or regression model (used by subclasses).\n * @param {boolean} [options.useSampleBagging] - use bagging over training samples.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.replacement = model.replacement;\n this.maxFeatures = model.maxFeatures;\n this.nEstimators = model.nEstimators;\n this.treeOptions = model.treeOptions;\n this.isClassifier = model.isClassifier;\n this.seed = model.seed;\n this.n = model.n;\n this.indexes = model.indexes;\n this.useSampleBagging = model.useSampleBagging;\n\n var Estimator = this.isClassifier ? DTClassifier : DTRegression;\n this.estimators = model.estimators.map((est) => Estimator.load(est));\n } else {\n this.replacement = options.replacement;\n this.maxFeatures = options.maxFeatures;\n this.nEstimators = options.nEstimators;\n this.treeOptions = options.treeOptions;\n this.isClassifier = options.isClassifier;\n this.seed = options.seed;\n this.useSampleBagging = options.useSampleBagging;\n }\n }\n\n /**\n * Train the decision tree with the given training set and labels.\n * @param {Matrix|Array} trainingSet\n * @param {Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n\n this.maxFeatures = this.maxFeatures || trainingSet.columns;\n\n if (Utils.checkFloat(this.maxFeatures)) {\n this.n = Math.floor(trainingSet.columns * this.maxFeatures);\n } else if (Number.isInteger(this.maxFeatures)) {\n if (this.maxFeatures > trainingSet.columns) {\n throw new RangeError(`The maxFeatures parameter should be less than ${trainingSet.columns}`);\n } else {\n this.n = this.maxFeatures;\n }\n } else {\n throw new RangeError(`Cannot process the maxFeatures parameter ${this.maxFeatures}`);\n }\n\n\n if (this.isClassifier) {\n var Estimator = DTClassifier;\n } else {\n Estimator = DTRegression;\n }\n\n this.estimators = new Array(this.nEstimators);\n this.indexes = new Array(this.nEstimators);\n\n for (var i = 0; i < this.nEstimators; ++i) {\n var res = this.useSampleBagging ? Utils.examplesBaggingWithReplacement(trainingSet, trainingValues, this.seed) : { X: trainingSet, y: trainingValues };\n var X = res.X;\n var y = res.y;\n\n res = Utils.featureBagging(X, this.n, this.replacement, this.seed);\n X = res.X;\n\n this.indexes[i] = res.usedIndex;\n this.estimators[i] = new Estimator(this.treeOptions);\n this.estimators[i].train(X, y);\n }\n }\n\n /**\n * Method that returns the way the algorithm generates the predictions, for example, in classification\n * you can return the mode of all predictions retrieved by the trees, or in case of regression you can\n * use the mean or the median.\n * @abstract\n * @param {Array} values - predictions of the estimators.\n * @return {number} prediction.\n */\n // eslint-disable-next-line no-unused-vars\n selection(values) {\n throw new Error('Abstract method \\'selection\\' not implemented!');\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Matrix|Array} toPredict\n * @return {Array} predictions\n */\n predict(toPredict) {\n var predictionValues = new Array(this.nEstimators);\n toPredict = Matrix.checkMatrix(toPredict);\n for (var i = 0; i < this.nEstimators; ++i) {\n var X = toPredict.columnSelectionView(this.indexes[i]); // get features for estimator\n predictionValues[i] = this.estimators[i].predict(X);\n }\n\n predictionValues = new WrapperMatrix2D(predictionValues).transposeView();\n var predictions = new Array(predictionValues.rows);\n for (i = 0; i < predictionValues.rows; ++i) {\n predictions[i] = this.selection(predictionValues.getRow(i));\n }\n\n return predictions;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n indexes: this.indexes,\n n: this.n,\n replacement: this.replacement,\n maxFeatures: this.maxFeatures,\n nEstimators: this.nEstimators,\n treeOptions: this.treeOptions,\n isClassifier: this.isClassifier,\n seed: this.seed,\n estimators: this.estimators.map((est) => est.toJSON()),\n useSampleBagging: this.useSampleBagging\n };\n }\n}\n","import { RandomForestBase } from './RandomForestBase';\n\nconst defaultOptions = {\n maxFeatures: 1.0,\n replacement: true,\n nEstimators: 10,\n seed: 42,\n useSampleBagging: false\n};\n\n/**\n * @class RandomForestClassifier\n * @augments RandomForestBase\n */\nexport class RandomForestClassifier extends RandomForestBase {\n /**\n * Create a new base random forest for a classifier or regression model.\n * @constructor\n * @param {object} options\n * @param {number} [options.maxFeatures=1.0] - the number of features used on each estimator.\n * * if is an integer it selects maxFeatures elements over the sample features.\n * * if is a float between (0, 1), it takes the percentage of features.\n * @param {boolean} [options.replacement=true] - use replacement over the sample features.\n * @param {number} [options.seed=42] - seed for feature and samples selection, must be a 32-bit integer.\n * @param {number} [options.nEstimators=10] - number of estimator to use.\n * @param {object} [options.treeOptions={}] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/}\n * @param {boolean} [options.useSampleBagging=false] - use bagging over training samples.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n super(true, model.baseModel);\n } else {\n options = Object.assign({}, defaultOptions, options);\n options.isClassifier = true;\n super(options);\n }\n }\n\n /**\n * retrieve the prediction given the selection method.\n * @param {Array} values - predictions of the estimators.\n * @return {number} prediction\n */\n selection(values) {\n return mode(values);\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n var baseModel = super.toJSON();\n return {\n baseModel: baseModel,\n name: 'RFClassifier'\n };\n }\n\n /**\n * Load a Decision tree classifier with the given model.\n * @param {object} model\n * @return {RandomForestClassifier}\n */\n static load(model) {\n if (model.name !== 'RFClassifier') {\n throw new RangeError(`Invalid model: ${model.name}`);\n }\n\n return new RandomForestClassifier(true, model);\n }\n}\n\n/**\n * Return the most repeated element on the array.\n * @param {Array} arr\n * @return {number} mode\n */\nfunction mode(arr) {\n return arr.sort((a, b) =>\n arr.filter((v) => v === a).length\n - arr.filter((v) => v === b).length\n ).pop();\n}\n","import arrayMean from 'ml-array-mean';\nimport arrayMedian from 'ml-array-median';\n\nimport { RandomForestBase } from './RandomForestBase';\n\nconst selectionMethods = {\n mean: arrayMean,\n median: arrayMedian\n};\n\nconst defaultOptions = {\n maxFeatures: 1.0,\n replacement: false,\n nEstimators: 10,\n treeOptions: {},\n selectionMethod: 'mean',\n seed: 42,\n useSampleBagging: false\n};\n\n/**\n * @class RandomForestRegression\n * @augments RandomForestBase\n */\nexport class RandomForestRegression extends RandomForestBase {\n /**\n * Create a new base random forest for a classifier or regression model.\n * @constructor\n * @param {object} options\n * @param {number} [options.maxFeatures=1.0] - the number of features used on each estimator.\n * * if is an integer it selects maxFeatures elements over the sample features.\n * * if is a float between (0, 1), it takes the percentage of features.\n * @param {boolean} [options.replacement=true] - use replacement over the sample features.\n * @param {number} [options.seed=42] - seed for feature and samples selection, must be a 32-bit integer.\n * @param {number} [options.nEstimators=10] - number of estimator to use.\n * @param {object} [options.treeOptions={}] - options for the tree classifier, see [ml-cart]{@link https://mljs.github.io/decision-tree-cart/}\n * @param {string} [options.selectionMethod=\"mean\"] - the way to calculate the prediction from estimators, \"mean\" and \"median\" are supported.\n * @param {boolean} [options.useSampleBagging=false] - use bagging over training samples.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n super(true, model.baseModel);\n this.selectionMethod = model.selectionMethod;\n } else {\n options = Object.assign({}, defaultOptions, options);\n\n if (!(options.selectionMethod === 'mean' || options.selectionMethod === 'median')) {\n throw new RangeError(`Unsupported selection method ${options.selectionMethod}`);\n }\n\n options.isClassifier = false;\n\n super(options);\n this.selectionMethod = options.selectionMethod;\n }\n }\n\n /**\n * retrieve the prediction given the selection method.\n * @param {Array} values - predictions of the estimators.\n * @return {number} prediction\n */\n selection(values) {\n return selectionMethods[this.selectionMethod](values);\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n var baseModel = super.toJSON();\n return {\n baseModel: baseModel,\n selectionMethod: this.selectionMethod,\n name: 'RFRegression'\n };\n }\n\n /**\n * Load a Decision tree classifier with the given model.\n * @param {object} model\n * @return {RandomForestRegression}\n */\n static load(model) {\n if (model.name !== 'RFRegression') {\n throw new RangeError(`Invalid model: ${model.name}`);\n }\n\n return new RandomForestRegression(true, model);\n }\n}\n","export { RandomForestClassifier } from './RandomForestClassifier';\nexport { RandomForestRegression } from './RandomForestRegression';\n","/**\n * Function that calculates the integral of the line between two\n * x-coordinates, given the slope and intercept of the line.\n * @param {number} x0\n * @param {number} x1\n * @param {number} slope\n * @param {number} intercept\n * @return {number} integral value.\n */\nexport default function integral(x0, x1, slope, intercept) {\n return (\n 0.5 * slope * x1 * x1 +\n intercept * x1 -\n (0.5 * slope * x0 * x0 + intercept * x0)\n );\n}\n","import sequentialFill from 'ml-array-sequential-fill';\n\nimport equallySpacedSmooth from './equallySpacedSmooth';\nimport equallySpacedSlot from './equallySpacedSlot';\nimport getZones from './getZones';\n\n/**\n * Function that returns a Number array of equally spaced numberOfPoints\n * containing a representation of intensities of the spectra arguments x\n * and y.\n *\n * The options parameter contains an object in the following form:\n * from: starting point\n * to: last point\n * numberOfPoints: number of points between from and to\n * variant: \"slot\" or \"smooth\" - smooth is the default option\n *\n * The slot variant consist that each point in the new array is calculated\n * averaging the existing points between the slot that belongs to the current\n * value. The smooth variant is the same but takes the integral of the range\n * of the slot and divide by the step size between two points in the new array.\n *\n * @param {object} [arrayXY={}] - object containing 2 properties x and y (both an array)\n * @param {object} [options={}]\n * @param {number} [options.from=x[0]]\n * @param {number} [options.to=x[x.length-1]]\n * @param {string} [options.variant='smooth']\n * @param {number} [options.numberOfPoints=100]\n * @param {Array} [options.exclusions=[]] array of from / to that should be skipped for the generation of the points\n * @return {object} new object with x / y array with the equally spaced data.\n */\n\nexport default function equallySpaced(arrayXY = {}, options = {}) {\n let { x, y } = arrayXY;\n let xLength = x.length;\n let reverse = false;\n if (x.length > 1 && x[0] > x[1]) {\n x = x.slice().reverse();\n y = y.slice().reverse();\n reverse = true;\n }\n\n let {\n from = x[0],\n to = x[xLength - 1],\n variant = 'smooth',\n numberOfPoints = 100,\n exclusions = []\n } = options;\n\n if (xLength !== y.length) {\n throw new RangeError(\"the x and y vector doesn't have the same size.\");\n }\n\n if (typeof from !== 'number' || isNaN(from)) {\n throw new RangeError(\"'from' option must be a number\");\n }\n\n if (typeof to !== 'number' || isNaN(to)) {\n throw new RangeError(\"'to' option must be a number\");\n }\n\n if (typeof numberOfPoints !== 'number' || isNaN(numberOfPoints)) {\n throw new RangeError(\"'numberOfPoints' option must be a number\");\n }\n\n let zones = getZones(from, to, numberOfPoints, exclusions);\n\n let xResult = [];\n let yResult = [];\n for (let zone of zones) {\n let zoneResult = processZone(\n x,\n y,\n zone.from,\n zone.to,\n zone.numberOfPoints,\n variant,\n reverse\n );\n xResult.push(...zoneResult.x);\n yResult.push(...zoneResult.y);\n }\n\n if (reverse) {\n if (from < to) {\n return { x: xResult.reverse(), y: yResult.reverse() };\n } else {\n return { x: xResult, y: yResult };\n }\n } else {\n if (from < to) {\n return { x: xResult, y: yResult };\n } else {\n return { x: xResult.reverse(), y: yResult.reverse() };\n }\n }\n}\n\nfunction processZone(x, y, from, to, numberOfPoints, variant) {\n if (numberOfPoints < 1) {\n throw new RangeError('the number of points must be at least 1');\n }\n\n var output =\n variant === 'slot'\n ? equallySpacedSlot(x, y, from, to, numberOfPoints)\n : equallySpacedSmooth(x, y, from, to, numberOfPoints);\n\n return {\n x: sequentialFill({\n from,\n to,\n size: numberOfPoints\n }),\n y: output\n };\n}\n","export default function getZones(from, to, numberOfPoints, exclusions = []) {\n if (from > to) {\n [from, to] = [to, from];\n }\n\n // in exclusions from and to have to be defined\n exclusions = exclusions.filter(\n (exclusion) => exclusion.from !== undefined && exclusion.to !== undefined\n );\n\n exclusions = JSON.parse(JSON.stringify(exclusions));\n // we ensure that from before to\n exclusions.forEach((exclusion) => {\n if (exclusion.from > exclusion.to) {\n [exclusion.to, exclusion.from] = [exclusion.from, exclusion.to];\n }\n });\n\n exclusions.sort((a, b) => a.from - b.from);\n\n // we will rework the exclusions in order to remove overlap and outside range (from / to)\n exclusions.forEach((exclusion) => {\n if (exclusion.from < from) exclusion.from = from;\n if (exclusion.to > to) exclusion.to = to;\n });\n for (let i = 0; i < exclusions.length - 1; i++) {\n if (exclusions[i].to > exclusions[i + 1].from) {\n exclusions[i].to = exclusions[i + 1].from;\n }\n }\n exclusions = exclusions.filter((exclusion) => exclusion.from < exclusion.to);\n\n if (!exclusions || exclusions.length === 0) {\n return [{ from, to, numberOfPoints }];\n }\n\n // need to deal with overlapping exclusions and out of bound exclusions\n\n let toRemove = exclusions.reduce(\n (previous, exclusion) => (previous += exclusion.to - exclusion.from),\n 0\n );\n let total = to - from;\n let unitsPerPoint = (total - toRemove) / numberOfPoints;\n let zones = [];\n let currentFrom = from;\n let totalPoints = 0;\n for (let exclusion of exclusions) {\n let currentNbPoints = Math.round(\n (exclusion.from - currentFrom) / unitsPerPoint\n );\n totalPoints += currentNbPoints;\n if (currentNbPoints > 0) {\n zones.push({\n from: currentFrom,\n to: exclusion.from,\n numberOfPoints: currentNbPoints\n });\n }\n\n currentFrom = exclusion.to;\n }\n if (numberOfPoints - totalPoints > 0) {\n zones.push({\n from: currentFrom,\n to: to,\n numberOfPoints: numberOfPoints - totalPoints\n });\n }\n\n return zones;\n}\n","/**\n * function that retrieves the getEquallySpacedData with the variant \"slot\"\n *\n * @param {Array} x\n * @param {Array} y\n * @param {number} from - Initial point\n * @param {number} to - Final point\n * @param {number} numberOfPoints\n * @return {Array} - Array of y's equally spaced with the variant \"slot\"\n */\nexport default function equallySpacedSlot(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n var lastStep = x[x.length - 1] - x[x.length - 2];\n\n var start = from - halfStep;\n var output = new Array(numberOfPoints);\n\n // Init main variables\n var min = start;\n var max = start + step;\n\n var previousX = -Number.MAX_VALUE;\n var previousY = 0;\n var nextX = x[0];\n var nextY = y[0];\n var frontOutsideSpectra = 0;\n var backOutsideSpectra = true;\n\n var currentValue = 0;\n\n // for slot algorithm\n var currentPoints = 0;\n\n var i = 1; // index of input\n var j = 0; // index of output\n\n main: while (true) {\n if (previousX >= nextX) throw new Error('x must be an increasing serie');\n while (previousX - max > 0) {\n // no overlap with original point, just consume current value\n if (backOutsideSpectra) {\n currentPoints++;\n backOutsideSpectra = false;\n }\n\n output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints;\n j++;\n\n if (j === numberOfPoints) {\n break main;\n }\n\n min = max;\n max += step;\n currentValue = 0;\n currentPoints = 0;\n }\n\n if (previousX > min) {\n currentValue += previousY;\n currentPoints++;\n }\n\n if (previousX === -Number.MAX_VALUE || frontOutsideSpectra > 1) {\n currentPoints--;\n }\n\n previousX = nextX;\n previousY = nextY;\n\n if (i < xLength) {\n nextX = x[i];\n nextY = y[i];\n i++;\n } else {\n nextX += lastStep;\n nextY = 0;\n frontOutsideSpectra++;\n }\n }\n\n return output;\n}\n","import integral from './integral';\n\n/**\n * function that retrieves the getEquallySpacedData with the variant \"smooth\"\n *\n * @param {Array} x\n * @param {Array} y\n * @param {number} from - Initial point\n * @param {number} to - Final point\n * @param {number} numberOfPoints\n * @return {Array} - Array of y's equally spaced with the variant \"smooth\"\n */\nexport default function equallySpacedSmooth(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n\n var output = new Array(numberOfPoints);\n\n var initialOriginalStep = x[1] - x[0];\n var lastOriginalStep = x[xLength - 1] - x[xLength - 2];\n\n // Init main variables\n var min = from - halfStep;\n var max = from + halfStep;\n\n var previousX = Number.MIN_VALUE;\n var previousY = 0;\n var nextX = x[0] - initialOriginalStep;\n var nextY = 0;\n\n var currentValue = 0;\n var slope = 0;\n var intercept = 0;\n var sumAtMin = 0;\n var sumAtMax = 0;\n\n var i = 0; // index of input\n var j = 0; // index of output\n\n function getSlope(x0, y0, x1, y1) {\n return (y1 - y0) / (x1 - x0);\n }\n\n main: while (true) {\n if (previousX <= min && min <= nextX) {\n add = integral(0, min - previousX, slope, previousY);\n sumAtMin = currentValue + add;\n }\n\n while (nextX - max >= 0) {\n // no overlap with original point, just consume current value\n var add = integral(0, max - previousX, slope, previousY);\n sumAtMax = currentValue + add;\n\n output[j++] = (sumAtMax - sumAtMin) / step;\n\n if (j === numberOfPoints) {\n break main;\n }\n\n min = max;\n max += step;\n sumAtMin = sumAtMax;\n }\n\n currentValue += integral(previousX, nextX, slope, intercept);\n\n previousX = nextX;\n previousY = nextY;\n\n if (i < xLength) {\n nextX = x[i];\n nextY = y[i];\n i++;\n } else if (i === xLength) {\n nextX += lastOriginalStep;\n nextY = 0;\n }\n\n slope = getSlope(previousX, previousY, nextX, nextY);\n intercept = -slope * previousX + previousY;\n }\n\n return output;\n}\n","import Matrix from 'ml-matrix';\n\n/**\n * @private\n * Function that retuns an array of matrices of the cases that belong to each class.\n * @param {Matrix} X - dataset\n * @param {Array} y - predictions\n * @return {Array}\n */\nexport function separateClasses(X, y) {\n var features = X.columns;\n\n var classes = 0;\n var totalPerClasses = new Array(10000); // max upperbound of classes\n for (var i = 0; i < y.length; i++) {\n if (totalPerClasses[y[i]] === undefined) {\n totalPerClasses[y[i]] = 0;\n classes++;\n }\n totalPerClasses[y[i]]++;\n }\n var separatedClasses = new Array(classes);\n var currentIndex = new Array(classes);\n for (i = 0; i < classes; ++i) {\n separatedClasses[i] = new Matrix(totalPerClasses[i], features);\n currentIndex[i] = 0;\n }\n for (i = 0; i < X.rows; ++i) {\n separatedClasses[y[i]].setRow(currentIndex[y[i]], X.getRow(i));\n currentIndex[y[i]]++;\n }\n return separatedClasses;\n}\n","import Matrix from 'ml-matrix';\nimport Stat from 'ml-stat';\nimport {separateClasses} from './utils';\n\n/**\n * @class GaussianNB\n */\nexport class GaussianNB {\n\n /**\n * @constructor\n * Constructor for the Gaussian Naive Bayes classifier, the parameters here is just for loading purposes.\n *\n * @param {boolean} reload\n * @param {object} model\n */\n constructor(reload, model) {\n if (reload) {\n this.means = model.means;\n this.calculateProbabilities = model.calculateProbabilities;\n }\n }\n\n /**\n * Function that trains the classifier with a matrix that represents the training set and an array that\n * represents the label of each row in the training set. the labels must be numbers between 0 to n-1 where\n * n represents the number of classes.\n *\n * WARNING: in the case that one class, all the cases in one or more features have the same value, the\n * Naive Bayes classifier will not work well.\n * @param {Matrix|Array} trainingSet\n * @param {Matrix|Array} trainingLabels\n */\n train(trainingSet, trainingLabels) {\n var C1 = Math.sqrt(2 * Math.PI); // constant to precalculate the squared root\n trainingSet = Matrix.checkMatrix(trainingSet);//if (!Matrix.isMatrix(trainingSet)) trainingSet = new Matrix(trainingSet);\n\n if (trainingSet.rows !== trainingLabels.length) {\n throw new RangeError('the size of the training set and the training labels must be the same.');\n }\n\n var separatedClasses = separateClasses(trainingSet, trainingLabels);\n var calculateProbabilities = new Array(separatedClasses.length);\n this.means = new Array(separatedClasses.length);\n for (var i = 0; i < separatedClasses.length; ++i) {\n var means = Stat.matrix.mean(separatedClasses[i]);\n var std = Stat.matrix.standardDeviation(separatedClasses[i], means);\n\n var logPriorProbability = Math.log(separatedClasses[i].rows / trainingSet.rows);\n calculateProbabilities[i] = new Array(means.length + 1);\n\n calculateProbabilities[i][0] = logPriorProbability;\n for (var j = 1; j < means.length + 1; ++j) {\n var currentStd = std[j - 1];\n calculateProbabilities[i][j] = [(1 / (C1 * currentStd)), -2 * currentStd * currentStd];\n }\n\n this.means[i] = means;\n }\n\n this.calculateProbabilities = calculateProbabilities;\n }\n\n /**\n * function that predicts each row of the dataset (must be a matrix).\n *\n * @param {Matrix|Array} dataset\n * @return {Array}\n */\n predict(dataset) {\n if (dataset[0].length === this.calculateProbabilities[0].length) {\n throw new RangeError('the dataset must have the same features as the training set');\n }\n\n var predictions = new Array(dataset.length);\n\n for (var i = 0; i < predictions.length; ++i) {\n predictions[i] = getCurrentClass(dataset[i], this.means, this.calculateProbabilities);\n }\n\n return predictions;\n }\n\n /**\n * Function that export the NaiveBayes model.\n * @return {object}\n */\n toJSON() {\n return {\n modelName: 'NaiveBayes',\n means: this.means,\n calculateProbabilities: this.calculateProbabilities\n };\n }\n\n /**\n * Function that create a GaussianNB classifier with the given model.\n * @param {object} model\n * @return {GaussianNB}\n */\n static load(model) {\n if (model.modelName !== 'NaiveBayes') {\n throw new RangeError('The current model is not a Multinomial Naive Bayes, current model:', model.name);\n }\n\n return new GaussianNB(true, model);\n }\n}\n\n/**\n * @private\n * Function the retrieves a prediction with one case.\n *\n * @param {Array} currentCase\n * @param {Array} mean - Precalculated means of each class trained\n * @param {Array} classes - Precalculated value of each class (Prior probability and probability function of each feature)\n * @return {number}\n */\nfunction getCurrentClass(currentCase, mean, classes) {\n var maxProbability = 0;\n var predictedClass = -1;\n\n // going through all precalculated values for the classes\n for (var i = 0; i < classes.length; ++i) {\n var currentProbability = classes[i][0]; // initialize with the prior probability\n for (var j = 1; j < classes[0][1].length + 1; ++j) {\n currentProbability += calculateLogProbability(currentCase[j - 1], mean[i][j - 1], classes[i][j][0], classes[i][j][1]);\n }\n\n currentProbability = Math.exp(currentProbability);\n if (currentProbability > maxProbability) {\n maxProbability = currentProbability;\n predictedClass = i;\n }\n }\n\n return predictedClass;\n}\n\n/**\n * @private\n * function that retrieves the probability of the feature given the class.\n * @param {number} value - value of the feature.\n * @param {number} mean - mean of the feature for the given class.\n * @param {number} C1 - precalculated value of (1 / (sqrt(2*pi) * std)).\n * @param {number} C2 - precalculated value of (2 * std^2) for the denominator of the exponential.\n * @return {number}\n */\nfunction calculateLogProbability(value, mean, C1, C2) {\n value = value - mean;\n return Math.log(C1 * Math.exp((value * value) / C2));\n}\n","import Matrix from 'ml-matrix';\nimport {separateClasses} from './utils';\n\n/**\n * @class MultinomialNB\n */\nexport class MultinomialNB {\n\n /**\n * @constructor\n * Constructor for Multinomial Naive Bayes, the model parameter is for load purposes.\n *\n * @param {object} model - for load purposes.\n */\n constructor(model) {\n if (model) {\n this.conditionalProbability = Matrix.checkMatrix(model.conditionalProbability);\n this.priorProbability = Matrix.checkMatrix(model.priorProbability);\n }\n }\n\n /**\n * Train the classifier with the current training set and labels, the labels must be numbers between 0 and n.\n * @param {Matrix|Array} trainingSet\n * @param {Array} trainingLabels\n */\n train(trainingSet, trainingLabels) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n\n if (trainingSet.rows !== trainingLabels.length) {\n throw new RangeError('the size of the training set and the training labels must be the same.');\n }\n\n var separateClass = separateClasses(trainingSet, trainingLabels);\n this.priorProbability = new Matrix(separateClass.length, 1);\n\n for (var i = 0; i < separateClass.length; ++i) {\n this.priorProbability[i][0] = Math.log(separateClass[i].length / trainingSet.rows);\n }\n\n var features = trainingSet.columns;\n this.conditionalProbability = new Matrix(separateClass.length, features);\n for (i = 0; i < separateClass.length; ++i) {\n var classValues = Matrix.checkMatrix(separateClass[i]);\n var total = classValues.sum();\n var divisor = total + features;\n this.conditionalProbability.setRow(i, classValues.sum('column').add(1).div(divisor).apply(matrixLog));\n }\n }\n\n /**\n * Retrieves the predictions for the dataset with the current model.\n * @param {Matrix|Array} dataset\n * @return {Array} - predictions from the dataset.\n */\n predict(dataset) {\n dataset = Matrix.checkMatrix(dataset);\n var predictions = new Array(dataset.rows);\n for (var i = 0; i < dataset.rows; ++i) {\n var currentElement = dataset.getRowVector(i);\n predictions[i] = this.conditionalProbability.clone().mulRowVector(currentElement).sum('row')\n .add(this.priorProbability).maxIndex()[0];\n }\n\n return predictions;\n }\n\n /**\n * Function that saves the current model.\n * @return {object} - model in JSON format.\n */\n toJSON() {\n return {\n name: 'MultinomialNB',\n priorProbability: this.priorProbability,\n conditionalProbability: this.conditionalProbability\n };\n }\n\n /**\n * Creates a new MultinomialNB from the given model\n * @param {object} model\n * @return {MultinomialNB}\n */\n static load(model) {\n if (model.name !== 'MultinomialNB') {\n throw new RangeError(`${model.name} is not a Multinomial Naive Bayes`);\n }\n\n return new MultinomialNB(model);\n }\n}\n\nfunction matrixLog(i, j) {\n this[i][j] = Math.log(this[i][j]);\n}\n","export {GaussianNB} from './GaussianNB';\nexport {MultinomialNB} from './MultinomialNB';\n","import Matrix from 'ml-matrix';\nimport Stat from 'ml-stat/matrix';\n\n/**\n * @private\n * Function that given vector, returns his norm\n * @param {Vector} X\n * @return {number} Norm of the vector\n */\nexport function norm(X) {\n return Math.sqrt(X.clone().apply(pow2array).sum());\n}\n\n/**\n * @private\n * Function that pow 2 each element of a Matrix or a Vector,\n * used in the apply method of the Matrix object\n * @param {number} i - index i.\n * @param {number} j - index j.\n * @return {Matrix} The Matrix object modified at the index i, j.\n * */\nexport function pow2array(i, j) {\n this[i][j] = this[i][j] * this[i][j];\n return this;\n}\n\n/**\n * @private\n * Function that normalize the dataset and return the means and\n * standard deviation of each feature.\n * @param {Matrix} dataset\n * @return {object} dataset normalized, means and standard deviations\n */\nexport function featureNormalize(dataset) {\n var means = Stat.mean(dataset);\n var std = Stat.standardDeviation(dataset, means, true);\n var result = Matrix.checkMatrix(dataset).subRowVector(means);\n return {result: result.divRowVector(std), means: means, std: std};\n}\n\n/**\n * @private\n * Function that initialize an array of matrices.\n * @param {Array} array\n * @param {boolean} isMatrix\n * @return {Array} array with the matrices initialized.\n */\nexport function initializeMatrices(array, isMatrix) {\n if (isMatrix) {\n for (var i = 0; i < array.length; ++i) {\n for (var j = 0; j < array[i].length; ++j) {\n var elem = array[i][j];\n array[i][j] = elem !== null ? new Matrix(array[i][j]) : undefined;\n }\n }\n } else {\n for (i = 0; i < array.length; ++i) {\n array[i] = new Matrix(array[i]);\n }\n }\n\n return array;\n}\n","import Matrix from 'ml-matrix';\nimport Stat from 'ml-stat/matrix';\nimport * as Utils from './utils';\n\n/**\n * @class PLS\n */\nexport class PLS {\n\n /**\n * Constructor for Partial Least Squares (PLS)\n * @param {object} options\n * @param {number} [options.latentVectors] - Number of latent vector to get (if the algorithm doesn't find a good model below the tolerance)\n * @param {number} [options.tolerance=1e-5]\n * @param {boolean} [options.scale=true] - rescale dataset using mean.\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.meanX = model.meanX;\n this.stdDevX = model.stdDevX;\n this.meanY = model.meanY;\n this.stdDevY = model.stdDevY;\n this.PBQ = Matrix.checkMatrix(model.PBQ);\n this.R2X = model.R2X;\n this.scale = model.scale;\n this.scaleMethod = model.scaleMethod;\n this.tolerance = model.tolerance;\n } else {\n var {\n tolerance = 1e-5,\n scale = true,\n } = options;\n this.tolerance = tolerance;\n this.scale = scale;\n this.latentVectors = options.latentVectors;\n }\n }\n\n /**\n * Fits the model with the given data and predictions, in this function is calculated the\n * following outputs:\n *\n * T - Score matrix of X\n * P - Loading matrix of X\n * U - Score matrix of Y\n * Q - Loading matrix of Y\n * B - Matrix of regression coefficient\n * W - Weight matrix of X\n *\n * @param {Matrix|Array} trainingSet\n * @param {Matrix|Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n trainingValues = Matrix.checkMatrix(trainingValues);\n\n if (trainingSet.length !== trainingValues.length) {\n throw new RangeError('The number of X rows must be equal to the number of Y rows');\n }\n\n this.meanX = Stat.mean(trainingSet);\n this.stdDevX = Stat.standardDeviation(trainingSet, this.meanX, true);\n this.meanY = Stat.mean(trainingValues);\n this.stdDevY = Stat.standardDeviation(trainingValues, this.meanY, true);\n\n if (this.scale) { // here should be the ml-preprocess project\n trainingSet = trainingSet.clone().subRowVector(this.meanX).divRowVector(this.stdDevX);\n trainingValues = trainingValues.clone().subRowVector(this.meanY).divRowVector(this.stdDevY);\n }\n\n if (this.latentVectors === undefined) {\n this.latentVectors = Math.min(trainingSet.length - 1, trainingSet[0].length);\n }\n\n var rx = trainingSet.rows;\n var cx = trainingSet.columns;\n var ry = trainingValues.rows;\n var cy = trainingValues.columns;\n\n var ssqXcal = trainingSet.clone().mul(trainingSet).sum(); // for the r²\n var sumOfSquaresY = trainingValues.clone().mul(trainingValues).sum();\n\n var tolerance = this.tolerance;\n var n = this.latentVectors;\n var T = Matrix.zeros(rx, n);\n var P = Matrix.zeros(cx, n);\n var U = Matrix.zeros(ry, n);\n var Q = Matrix.zeros(cy, n);\n var B = Matrix.zeros(n, n);\n var W = P.clone();\n var k = 0;\n\n while (Utils.norm(trainingValues) > tolerance && k < n) {\n var transposeX = trainingSet.transpose();\n var transposeY = trainingValues.transpose();\n\n var tIndex = maxSumColIndex(trainingSet.clone().mulM(trainingSet));\n var uIndex = maxSumColIndex(trainingValues.clone().mulM(trainingValues));\n\n var t1 = trainingSet.getColumnVector(tIndex);\n var u = trainingValues.getColumnVector(uIndex);\n var t = Matrix.zeros(rx, 1);\n\n while (Utils.norm(t1.clone().sub(t)) > tolerance) {\n var w = transposeX.mmul(u);\n w.div(Utils.norm(w));\n t = t1;\n t1 = trainingSet.mmul(w);\n var q = transposeY.mmul(t1);\n q.div(Utils.norm(q));\n u = trainingValues.mmul(q);\n }\n\n t = t1;\n var num = transposeX.mmul(t);\n var den = (t.transpose().mmul(t))[0][0];\n var p = num.div(den);\n var pnorm = Utils.norm(p);\n p.div(pnorm);\n t.mul(pnorm);\n w.mul(pnorm);\n\n num = u.transpose().mmul(t);\n den = (t.transpose().mmul(t))[0][0];\n var b = (num.div(den))[0][0];\n trainingSet.sub(t.mmul(p.transpose()));\n trainingValues.sub(t.clone().mul(b).mmul(q.transpose()));\n\n T.setColumn(k, t);\n P.setColumn(k, p);\n U.setColumn(k, u);\n Q.setColumn(k, q);\n W.setColumn(k, w);\n\n B[k][k] = b;\n k++;\n }\n\n k--;\n T = T.subMatrix(0, T.rows - 1, 0, k);\n P = P.subMatrix(0, P.rows - 1, 0, k);\n U = U.subMatrix(0, U.rows - 1, 0, k);\n Q = Q.subMatrix(0, Q.rows - 1, 0, k);\n W = W.subMatrix(0, W.rows - 1, 0, k);\n B = B.subMatrix(0, k, 0, k);\n\n // TODO: review of R2Y\n //this.R2Y = t.transpose().mmul(t).mul(q[k][0]*q[k][0]).divS(ssqYcal)[0][0];\n //\n this.ssqYcal = sumOfSquaresY;\n this.E = trainingSet;\n this.F = trainingValues;\n this.T = T;\n this.P = P;\n this.U = U;\n this.Q = Q;\n this.W = W;\n this.B = B;\n this.PBQ = P.mmul(B).mmul(Q.transpose());\n this.R2X = t.transpose().mmul(t).mmul(p.transpose().mmul(p)).div(ssqXcal)[0][0];\n }\n\n /**\n * Predicts the behavior of the given dataset.\n * @param {Matrix|Array} dataset - data to be predicted.\n * @return {Matrix} - predictions of each element of the dataset.\n */\n predict(dataset) {\n var X = Matrix.checkMatrix(dataset);\n if (this.scale) {\n X = X.subRowVector(this.meanX).divRowVector(this.stdDevX);\n }\n var Y = X.mmul(this.PBQ);\n Y = Y.mulRowVector(this.stdDevY).addRowVector(this.meanY);\n return Y;\n }\n\n /**\n * Returns the explained variance on training of the PLS model\n * @return {number}\n */\n getExplainedVariance() {\n return this.R2X;\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n name: 'PLS',\n R2X: this.R2X,\n meanX: this.meanX,\n stdDevX: this.stdDevX,\n meanY: this.meanY,\n stdDevY: this.stdDevY,\n PBQ: this.PBQ,\n tolerance: this.tolerance,\n scale: this.scale,\n };\n }\n\n /**\n * Load a PLS model from a JSON Object\n * @param {object} model\n * @return {PLS} - PLS object from the given model\n */\n static load(model) {\n if (model.name !== 'PLS') {\n throw new RangeError('Invalid model: ' + model.name);\n }\n return new PLS(true, model);\n }\n}\n\n/**\n * @private\n * Function that returns the index where the sum of each\n * column vector is maximum.\n * @param {Matrix} data\n * @return {number} index of the maximum\n */\nfunction maxSumColIndex(data) {\n return data.sum('column').maxIndex()[0];\n}\n","import {Matrix, SingularValueDecomposition, inverse} from 'ml-matrix';\nimport {initializeMatrices} from './utils';\n\n/**\n * @class KOPLS\n */\nexport class KOPLS {\n\n /**\n * Constructor for Kernel-based Orthogonal Projections to Latent Structures (K-OPLS)\n * @param {object} options\n * @param {number} [options.predictiveComponents] - Number of predictive components to use.\n * @param {number} [options.orthogonalComponents] - Number of Y-Orthogonal components.\n * @param {Kernel} [options.kernel] - Kernel object to apply, see [ml-kernel](https://github.com/mljs/kernel).\n * @param {object} model - for load purposes.\n */\n constructor(options, model) {\n if (options === true) {\n this.trainingSet = new Matrix(model.trainingSet);\n this.YLoadingMat = new Matrix(model.YLoadingMat);\n this.SigmaPow = new Matrix(model.SigmaPow);\n this.YScoreMat = new Matrix(model.YScoreMat);\n this.predScoreMat = initializeMatrices(model.predScoreMat, false);\n this.YOrthLoadingVec = initializeMatrices(model.YOrthLoadingVec, false);\n this.YOrthEigen = model.YOrthEigen;\n this.YOrthScoreMat = initializeMatrices(model.YOrthScoreMat, false);\n this.toNorm = initializeMatrices(model.toNorm, false);\n this.TURegressionCoeff = initializeMatrices(model.TURegressionCoeff, false);\n this.kernelX = initializeMatrices(model.kernelX, true);\n this.kernel = model.kernel;\n this.orthogonalComp = model.orthogonalComp;\n this.predictiveComp = model.predictiveComp;\n } else {\n if (options.predictiveComponents === undefined) {\n throw new RangeError('no predictive components found!');\n }\n if (options.orthogonalComponents === undefined) {\n throw new RangeError('no orthogonal components found!');\n }\n if (options.kernel === undefined) {\n throw new RangeError('no kernel found!');\n }\n\n this.orthogonalComp = options.orthogonalComponents;\n this.predictiveComp = options.predictiveComponents;\n this.kernel = options.kernel;\n }\n }\n\n /**\n * Train the K-OPLS model with the given training set and labels.\n * @param {Matrix|Array} trainingSet\n * @param {Matrix|Array} trainingValues\n */\n train(trainingSet, trainingValues) {\n trainingSet = Matrix.checkMatrix(trainingSet);\n trainingValues = Matrix.checkMatrix(trainingValues);\n\n // to save and compute kernel with the prediction dataset.\n this.trainingSet = trainingSet.clone();\n\n var kernelX = this.kernel.compute(trainingSet);\n\n var Identity = Matrix.eye(kernelX.rows, kernelX.rows, 1);\n var temp = kernelX;\n kernelX = new Matrix(this.orthogonalComp + 1, this.orthogonalComp + 1);\n kernelX[0][0] = temp;\n\n var result = new SingularValueDecomposition(trainingValues.transpose().mmul(kernelX[0][0]).mmul(trainingValues), {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: false\n });\n var YLoadingMat = result.leftSingularVectors;\n var Sigma = result.diagonalMatrix;\n\n YLoadingMat = YLoadingMat.subMatrix(0, YLoadingMat.rows - 1, 0, this.predictiveComp - 1);\n Sigma = Sigma.subMatrix(0, this.predictiveComp - 1, 0, this.predictiveComp - 1);\n\n var YScoreMat = trainingValues.mmul(YLoadingMat);\n\n var predScoreMat = new Array(this.orthogonalComp + 1);\n var TURegressionCoeff = new Array(this.orthogonalComp + 1);\n var YOrthScoreMat = new Array(this.orthogonalComp);\n var YOrthLoadingVec = new Array(this.orthogonalComp);\n var YOrthEigen = new Array(this.orthogonalComp);\n var YOrthScoreNorm = new Array(this.orthogonalComp);\n\n var SigmaPow = Matrix.pow(Sigma, -0.5);\n // to avoid errors, check infinity\n SigmaPow.apply(function (i, j) {\n if (this[i][j] === Infinity) {\n this[i][j] = 0.0;\n }\n });\n\n for (var i = 0; i < this.orthogonalComp; ++i) {\n predScoreMat[i] = kernelX[0][i].transpose().mmul(YScoreMat).mmul(SigmaPow);\n\n var TpiPrime = predScoreMat[i].transpose();\n TURegressionCoeff[i] = inverse(TpiPrime.mmul(predScoreMat[i])).mmul(TpiPrime).mmul(YScoreMat);\n\n result = new SingularValueDecomposition(TpiPrime.mmul(Matrix.sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime))).mmul(predScoreMat[i]), {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: false\n });\n var CoTemp = result.leftSingularVectors;\n var SoTemp = result.diagonalMatrix;\n\n YOrthLoadingVec[i] = CoTemp.subMatrix(0, CoTemp.rows - 1, 0, 0);\n YOrthEigen[i] = SoTemp[0][0];\n\n YOrthScoreMat[i] = Matrix.sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime)).mmul(predScoreMat[i]).mmul(YOrthLoadingVec[i]).mul(Math.pow(YOrthEigen[i], -0.5));\n\n var toiPrime = YOrthScoreMat[i].transpose();\n YOrthScoreNorm[i] = Matrix.sqrt(toiPrime.mmul(YOrthScoreMat[i]));\n\n YOrthScoreMat[i] = YOrthScoreMat[i].divRowVector(YOrthScoreNorm[i]);\n\n var ITo = Matrix.sub(Identity, YOrthScoreMat[i].mmul(YOrthScoreMat[i].transpose()));\n\n kernelX[0][i + 1] = kernelX[0][i].mmul(ITo);\n kernelX[i + 1][i + 1] = ITo.mmul(kernelX[i][i]).mmul(ITo);\n }\n\n var lastScoreMat = predScoreMat[this.orthogonalComp] = kernelX[0][this.orthogonalComp].transpose().mmul(YScoreMat).mmul(SigmaPow);\n\n var lastTpPrime = lastScoreMat.transpose();\n TURegressionCoeff[this.orthogonalComp] = inverse(lastTpPrime.mmul(lastScoreMat)).mmul(lastTpPrime).mmul(YScoreMat);\n\n this.YLoadingMat = YLoadingMat;\n this.SigmaPow = SigmaPow;\n this.YScoreMat = YScoreMat;\n this.predScoreMat = predScoreMat;\n this.YOrthLoadingVec = YOrthLoadingVec;\n this.YOrthEigen = YOrthEigen;\n this.YOrthScoreMat = YOrthScoreMat;\n this.toNorm = YOrthScoreNorm;\n this.TURegressionCoeff = TURegressionCoeff;\n this.kernelX = kernelX;\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Matrix|Array} toPredict\n * @return {{y: Matrix, predScoreMat: Array, predYOrthVectors: Array}} predictions\n */\n predict(toPredict) {\n\n var KTestTrain = this.kernel.compute(toPredict, this.trainingSet);\n\n var temp = KTestTrain;\n KTestTrain = new Matrix(this.orthogonalComp + 1, this.orthogonalComp + 1);\n KTestTrain[0][0] = temp;\n\n var YOrthScoreVector = new Array(this.orthogonalComp);\n var predScoreMat = new Array(this.orthogonalComp);\n\n var i;\n for (i = 0; i < this.orthogonalComp; ++i) {\n predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow);\n\n YOrthScoreVector[i] = Matrix.sub(KTestTrain[i][i], predScoreMat[i].mmul(this.predScoreMat[i].transpose())).mmul(this.predScoreMat[i]).mmul(this.YOrthLoadingVec[i]).mul(Math.pow(this.YOrthEigen[i], -0.5));\n\n YOrthScoreVector[i] = YOrthScoreVector[i].divRowVector(this.toNorm[i]);\n\n var scoreMatPrime = this.YOrthScoreMat[i].transpose();\n KTestTrain[i + 1][0] = Matrix.sub(KTestTrain[i][0], YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[0][i].transpose()));\n\n var p1 = Matrix.sub(KTestTrain[i][0], KTestTrain[i][i].mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime));\n var p2 = YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[i][i]);\n var p3 = p2.mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime);\n\n KTestTrain[i + 1][i + 1] = p1.sub(p2).add(p3);\n }\n\n predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow);\n var prediction = predScoreMat[i].mmul(this.TURegressionCoeff[i]).mmul(this.YLoadingMat.transpose());\n\n return {\n prediction: prediction,\n predScoreMat: predScoreMat,\n predYOrthVectors: YOrthScoreVector\n };\n }\n\n /**\n * Export the current model to JSON.\n * @return {object} - Current model.\n */\n toJSON() {\n return {\n name: 'K-OPLS',\n YLoadingMat: this.YLoadingMat,\n SigmaPow: this.SigmaPow,\n YScoreMat: this.YScoreMat,\n predScoreMat: this.predScoreMat,\n YOrthLoadingVec: this.YOrthLoadingVec,\n YOrthEigen: this.YOrthEigen,\n YOrthScoreMat: this.YOrthScoreMat,\n toNorm: this.toNorm,\n TURegressionCoeff: this.TURegressionCoeff,\n kernelX: this.kernelX,\n trainingSet: this.trainingSet,\n orthogonalComp: this.orthogonalComp,\n predictiveComp: this.predictiveComp\n };\n }\n\n /**\n * Load a K-OPLS with the given model.\n * @param {object} model\n * @param {Kernel} kernel - kernel used on the model, see [ml-kernel](https://github.com/mljs/kernel).\n * @return {KOPLS}\n */\n static load(model, kernel) {\n if (model.name !== 'K-OPLS') {\n throw new RangeError('Invalid model: ' + model.name);\n }\n\n if (!kernel) {\n throw new RangeError('You must provide a kernel for the model!');\n }\n\n model.kernel = kernel;\n return new KOPLS(true, model);\n }\n}\n","export {PLS} from './pls';\nexport {KOPLS} from './kopls';\n","/**\n * Calculate current error\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} parameters - Array of current parameter values\n * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @return {number}\n */\nexport default function errorCalculation(\n data,\n parameters,\n parameterizedFunction\n) {\n var error = 0;\n const func = parameterizedFunction(parameters);\n\n for (var i = 0; i < data.x.length; i++) {\n error += Math.abs(data.y[i] - func(data.x[i]));\n }\n\n return error;\n}\n","import { inverse, Matrix } from 'ml-matrix';\n\n/**\n * Difference of the matrix function over the parameters\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} evaluatedData - Array of previous evaluated function values\n * @param {Array} params - Array of previous parameter values\n * @param {number} gradientDifference - Adjustment for decrease the damping parameter\n * @param {function} paramFunction - The parameters and returns a function with the independent variable as a parameter\n * @return {Matrix}\n */\nfunction gradientFunction(\n data,\n evaluatedData,\n params,\n gradientDifference,\n paramFunction\n) {\n const n = params.length;\n const m = data.x.length;\n\n var ans = new Array(n);\n\n for (var param = 0; param < n; param++) {\n ans[param] = new Array(m);\n var auxParams = params.concat();\n auxParams[param] += gradientDifference;\n var funcParam = paramFunction(auxParams);\n\n for (var point = 0; point < m; point++) {\n ans[param][point] = evaluatedData[point] - funcParam(data.x[point]);\n }\n }\n return new Matrix(ans);\n}\n\n/**\n * Matrix function over the samples\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} evaluatedData - Array of previous evaluated function values\n * @return {Matrix}\n */\nfunction matrixFunction(data, evaluatedData) {\n const m = data.x.length;\n\n var ans = new Array(m);\n\n for (var point = 0; point < m; point++) {\n ans[point] = [data.y[point] - evaluatedData[point]];\n }\n\n return new Matrix(ans);\n}\n\n/**\n * Iteration for Levenberg-Marquardt\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} params - Array of previous parameter values\n * @param {number} damping - Levenberg-Marquardt parameter\n * @param {number} gradientDifference - Adjustment for decrease the damping parameter\n * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @return {Array}\n */\nexport default function step(\n data,\n params,\n damping,\n gradientDifference,\n parameterizedFunction\n) {\n var value = damping * gradientDifference * gradientDifference;\n var identity = Matrix.eye(params.length, params.length, value);\n\n const func = parameterizedFunction(params);\n var evaluatedData = data.x.map((e) => func(e));\n\n var gradientFunc = gradientFunction(\n data,\n evaluatedData,\n params,\n gradientDifference,\n parameterizedFunction\n );\n var matrixFunc = matrixFunction(data, evaluatedData);\n var inverseMatrix = inverse(\n identity.add(gradientFunc.mmul(gradientFunc.transpose()))\n );\n\n params = new Matrix([params]);\n params = params.sub(\n inverseMatrix\n .mmul(gradientFunc)\n .mmul(matrixFunc)\n .mul(gradientDifference)\n .transpose()\n );\n\n return params.to1DArray();\n}\n","import errorCalculation from './errorCalculation';\nimport step from './step';\n\n/**\n * Curve fitting algorithm\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @param {object} [options] - Options object\n * @param {number} [options.damping] - Levenberg-Marquardt parameter\n * @param {number} [options.gradientDifference = 10e-2] - Adjustment for decrease the damping parameter\n * @param {Array} [options.minValues] - Minimum allowed values for parameters\n * @param {Array} [options.maxValues] - Maximum allowed values for parameters\n * @param {Array} [options.initialValues] - Array of initial parameter values\n * @param {number} [options.maxIterations = 100] - Maximum of allowed iterations\n * @param {number} [options.errorTolerance = 10e-3] - Minimum uncertainty allowed for each point\n * @return {{parameterValues: Array, parameterError: number, iterations: number}}\n */\nexport default function levenbergMarquardt(\n data,\n parameterizedFunction,\n options = {}\n) {\n let {\n maxIterations = 100,\n gradientDifference = 10e-2,\n damping = 0,\n errorTolerance = 10e-3,\n minValues,\n maxValues,\n initialValues\n } = options;\n\n if (damping <= 0) {\n throw new Error('The damping option must be a positive number');\n } else if (!data.x || !data.y) {\n throw new Error('The data parameter must have x and y elements');\n } else if (\n !Array.isArray(data.x) ||\n data.x.length < 2 ||\n !Array.isArray(data.y) ||\n data.y.length < 2\n ) {\n throw new Error(\n 'The data parameter elements must be an array with more than 2 points'\n );\n } else if (data.x.length !== data.y.length) {\n throw new Error('The data parameter elements must have the same size');\n }\n\n var parameters =\n initialValues || new Array(parameterizedFunction.length).fill(1);\n let parLen = parameters.length;\n maxValues = maxValues || new Array(parLen).fill(Number.MAX_SAFE_INTEGER);\n minValues = minValues || new Array(parLen).fill(Number.MIN_SAFE_INTEGER);\n\n if (maxValues.length !== minValues.length) {\n throw new Error('minValues and maxValues must be the same size');\n }\n\n if (!Array.isArray(parameters)) {\n throw new Error('initialValues must be an array');\n }\n\n var error = errorCalculation(data, parameters, parameterizedFunction);\n\n var converged = error <= errorTolerance;\n\n for (\n var iteration = 0;\n iteration < maxIterations && !converged;\n iteration++\n ) {\n parameters = step(\n data,\n parameters,\n damping,\n gradientDifference,\n parameterizedFunction\n );\n\n for (let k = 0; k < parLen; k++) {\n parameters[k] = Math.min(\n Math.max(minValues[k], parameters[k]),\n maxValues[k]\n );\n }\n\n error = errorCalculation(data, parameters, parameterizedFunction);\n if (isNaN(error)) break;\n converged = error <= errorTolerance;\n }\n\n return {\n parameterValues: parameters,\n parameterError: error,\n iterations: iteration\n };\n}\n","import getZones from './getZones';\n\n/**\n * Filter an array x/y based on various criteria\n * x points are expected to be sorted\n *\n * @param {object} points\n * @param {object} [options={}]\n * @param {array} [options.from]\n * @param {array} [options.to]\n * @param {array} [options.exclusions=[]]\n * @return {{x: Array, y: Array}}\n */\n\nexport default function filterX(points, options = {}) {\n const { x, y } = points;\n const { from = x[0], to = x[x.length - 1], exclusions = [] } = options;\n\n let zones = getZones(from, to, exclusions);\n\n\n let currentZoneIndex = 0;\n let newX = [];\n let newY = [];\n let position = 0;\n while (position < x.length) {\n if (\n x[position] <= zones[currentZoneIndex].to &&\n x[position] >= zones[currentZoneIndex].from\n ) {\n newX.push(x[position]);\n newY.push(y[position]);\n } else {\n if (x[position] > zones[currentZoneIndex].to) {\n currentZoneIndex++;\n if (!zones[currentZoneIndex]) break;\n }\n }\n position++;\n }\n\n return {\n x: newX,\n y: newY\n };\n}\n","export default function getZones(from, to, exclusions = []) {\n if (from > to) {\n [from, to] = [to, from];\n }\n\n // in exclusions from and to have to be defined\n exclusions = exclusions.filter(\n (exclusion) => exclusion.from !== undefined && exclusion.to !== undefined\n );\n\n exclusions = JSON.parse(JSON.stringify(exclusions));\n // we ensure that from before to\n exclusions.forEach((exclusion) => {\n if (exclusion.from > exclusion.to) {\n [exclusion.to, exclusion.from] = [exclusion.from, exclusion.to];\n }\n });\n\n exclusions.sort((a, b) => a.from - b.from);\n\n // we will rework the exclusions in order to remove overlap and outside range (from / to)\n exclusions.forEach((exclusion) => {\n if (exclusion.from < from) exclusion.from = from;\n if (exclusion.to > to) exclusion.to = to;\n });\n for (let i = 0; i < exclusions.length - 1; i++) {\n if (exclusions[i].to > exclusions[i + 1].from) {\n exclusions[i].to = exclusions[i + 1].from;\n }\n }\n exclusions = exclusions.filter((exclusion) => exclusion.from < exclusion.to);\n\n if (!exclusions || exclusions.length === 0) {\n return [{ from, to }];\n }\n\n let zones = [];\n let currentFrom = from;\n for (let exclusion of exclusions) {\n if (currentFrom < exclusion.from) {\n zones.push({\n from: currentFrom,\n to: exclusion.from\n });\n }\n\n currentFrom = exclusion.to;\n }\n if (currentFrom < to) {\n zones.push({\n from: currentFrom,\n to: to\n });\n }\n\n return zones;\n}\n","/*\n * Original code from:\n *\n * k-d Tree JavaScript - V 1.01\n *\n * https://github.com/ubilabs/kd-tree-javascript\n *\n * @author Mircea Pricop , 2012\n * @author Martin Kleppe , 2012\n * @author Ubilabs http://ubilabs.net, 2012\n * @license MIT License \n */\n\nfunction Node(obj, dimension, parent) {\n this.obj = obj;\n this.left = null;\n this.right = null;\n this.parent = parent;\n this.dimension = dimension;\n}\n\nexport default class KDTree {\n constructor(points, metric) {\n // If points is not an array, assume we're loading a pre-built tree\n if (!Array.isArray(points)) {\n this.dimensions = points.dimensions;\n this.root = points;\n restoreParent(this.root);\n } else {\n this.dimensions = new Array(points[0].length);\n for (var i = 0; i < this.dimensions.length; i++) {\n this.dimensions[i] = i;\n }\n this.root = buildTree(points, 0, null, this.dimensions);\n }\n this.metric = metric;\n }\n\n // Convert to a JSON serializable structure; this just requires removing\n // the `parent` property\n toJSON() {\n const result = toJSONImpl(this.root, true);\n result.dimensions = this.dimensions;\n return result;\n }\n\n nearest(point, maxNodes, maxDistance) {\n const metric = this.metric;\n const dimensions = this.dimensions;\n var i;\n\n const bestNodes = new BinaryHeap(\n function (e) {\n return -e[1];\n }\n );\n\n function nearestSearch(node) {\n const dimension = dimensions[node.dimension];\n const ownDistance = metric(point, node.obj);\n const linearPoint = {};\n var bestChild,\n linearDistance,\n otherChild,\n i;\n\n function saveNode(node, distance) {\n bestNodes.push([node, distance]);\n if (bestNodes.size() > maxNodes) {\n bestNodes.pop();\n }\n }\n\n for (i = 0; i < dimensions.length; i += 1) {\n if (i === node.dimension) {\n linearPoint[dimensions[i]] = point[dimensions[i]];\n } else {\n linearPoint[dimensions[i]] = node.obj[dimensions[i]];\n }\n }\n\n linearDistance = metric(linearPoint, node.obj);\n\n if (node.right === null && node.left === null) {\n if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {\n saveNode(node, ownDistance);\n }\n return;\n }\n\n if (node.right === null) {\n bestChild = node.left;\n } else if (node.left === null) {\n bestChild = node.right;\n } else {\n if (point[dimension] < node.obj[dimension]) {\n bestChild = node.left;\n } else {\n bestChild = node.right;\n }\n }\n\n nearestSearch(bestChild);\n\n if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {\n saveNode(node, ownDistance);\n }\n\n if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) {\n if (bestChild === node.left) {\n otherChild = node.right;\n } else {\n otherChild = node.left;\n }\n if (otherChild !== null) {\n nearestSearch(otherChild);\n }\n }\n }\n\n if (maxDistance) {\n for (i = 0; i < maxNodes; i += 1) {\n bestNodes.push([null, maxDistance]);\n }\n }\n\n if (this.root) {\n nearestSearch(this.root);\n }\n\n const result = [];\n for (i = 0; i < Math.min(maxNodes, bestNodes.content.length); i += 1) {\n if (bestNodes.content[i][0]) {\n result.push([bestNodes.content[i][0].obj, bestNodes.content[i][1]]);\n }\n }\n return result;\n }\n}\n\nfunction toJSONImpl(src) {\n const dest = new Node(src.obj, src.dimension, null);\n if (src.left) dest.left = toJSONImpl(src.left);\n if (src.right) dest.right = toJSONImpl(src.right);\n return dest;\n}\n\nfunction buildTree(points, depth, parent, dimensions) {\n const dim = depth % dimensions.length;\n\n if (points.length === 0) {\n return null;\n }\n if (points.length === 1) {\n return new Node(points[0], dim, parent);\n }\n\n points.sort((a, b) => a[dimensions[dim]] - b[dimensions[dim]]);\n\n const median = Math.floor(points.length / 2);\n const node = new Node(points[median], dim, parent);\n node.left = buildTree(points.slice(0, median), depth + 1, node, dimensions);\n node.right = buildTree(points.slice(median + 1), depth + 1, node, dimensions);\n\n return node;\n}\n\nfunction restoreParent(root) {\n if (root.left) {\n root.left.parent = root;\n restoreParent(root.left);\n }\n\n if (root.right) {\n root.right.parent = root;\n restoreParent(root.right);\n }\n}\n\n// Binary heap implementation from:\n// http://eloquentjavascript.net/appendix2.html\nclass BinaryHeap {\n constructor(scoreFunction) {\n this.content = [];\n this.scoreFunction = scoreFunction;\n }\n\n push(element) {\n // Add the new element to the end of the array.\n this.content.push(element);\n // Allow it to bubble up.\n this.bubbleUp(this.content.length - 1);\n }\n\n pop() {\n // Store the first element so we can return it later.\n var result = this.content[0];\n // Get the element at the end of the array.\n var end = this.content.pop();\n // If there are any elements left, put the end element at the\n // start, and let it sink down.\n if (this.content.length > 0) {\n this.content[0] = end;\n this.sinkDown(0);\n }\n return result;\n }\n\n peek() {\n return this.content[0];\n }\n\n size() {\n return this.content.length;\n }\n\n bubbleUp(n) {\n // Fetch the element that has to be moved.\n var element = this.content[n];\n // When at 0, an element can not go up any further.\n while (n > 0) {\n // Compute the parent element's index, and fetch it.\n const parentN = Math.floor((n + 1) / 2) - 1;\n const parent = this.content[parentN];\n // Swap the elements if the parent is greater.\n if (this.scoreFunction(element) < this.scoreFunction(parent)) {\n this.content[parentN] = element;\n this.content[n] = parent;\n // Update 'n' to continue at the new position.\n n = parentN;\n } else { // Found a parent that is less, no need to move it further.\n break;\n }\n }\n }\n\n sinkDown(n) {\n // Look up the target element and its score.\n var length = this.content.length;\n var element = this.content[n];\n var elemScore = this.scoreFunction(element);\n\n while (true) {\n // Compute the indices of the child elements.\n var child2N = (n + 1) * 2;\n var child1N = child2N - 1;\n // This is used to store the new position of the element,\n // if any.\n var swap = null;\n // If the first child exists (is inside the array)...\n if (child1N < length) {\n // Look it up and compute its score.\n var child1 = this.content[child1N];\n var child1Score = this.scoreFunction(child1);\n // If the score is less than our element's, we need to swap.\n if (child1Score < elemScore) {\n swap = child1N;\n }\n }\n // Do the same checks for the other child.\n if (child2N < length) {\n var child2 = this.content[child2N];\n var child2Score = this.scoreFunction(child2);\n if (child2Score < (swap === null ? elemScore : child1Score)) {\n swap = child2N;\n }\n }\n\n // If the element needs to be moved, swap it, and continue.\n if (swap !== null) {\n this.content[n] = this.content[swap];\n this.content[swap] = element;\n n = swap;\n } else {\n // Otherwise, we are done.\n break;\n }\n }\n }\n}\n","import KDTree from './KDTree';\nimport euclideanDistance from 'ml-distance-euclidean';\n\nexport default class KNN {\n\n /**\n * @param {Array} dataset\n * @param {Array} labels\n * @param {object} options\n * @param {number} [options.k=numberOfClasses + 1] - Number of neighbors to classify.\n * @param {function} [options.distance=euclideanDistance] - Distance function that takes two parameters.\n */\n constructor(dataset, labels, options = {}) {\n if (dataset === true) {\n const model = labels;\n this.kdTree = new KDTree(model.kdTree, options);\n this.k = model.k;\n this.classes = new Set(model.classes);\n this.isEuclidean = model.isEuclidean;\n return;\n }\n\n const classes = new Set(labels);\n\n const {\n distance = euclideanDistance,\n k = classes.size + 1\n } = options;\n\n const points = new Array(dataset.length);\n for (var i = 0; i < points.length; ++i) {\n points[i] = dataset[i].slice();\n }\n\n for (i = 0; i < labels.length; ++i) {\n points[i].push(labels[i]);\n }\n\n this.kdTree = new KDTree(points, distance);\n this.k = k;\n this.classes = classes;\n this.isEuclidean = distance === euclideanDistance;\n }\n\n /**\n * Create a new KNN instance with the given model.\n * @param {object} model\n * @param {function} distance=euclideanDistance - distance function must be provided if the model wasn't trained with euclidean distance.\n * @return {KNN}\n */\n static load(model, distance = euclideanDistance) {\n if (model.name !== 'KNN') {\n throw new Error('invalid model: ' + model.name);\n }\n if (!model.isEuclidean && distance === euclideanDistance) {\n throw new Error('a custom distance function was used to create the model. Please provide it again');\n }\n if (model.isEuclidean && distance !== euclideanDistance) {\n throw new Error('the model was created with the default distance function. Do not load it with another one');\n }\n return new KNN(true, model, distance);\n }\n\n /**\n * Return a JSON containing the kd-tree model.\n * @return {object} JSON KNN model.\n */\n toJSON() {\n return {\n name: 'KNN',\n kdTree: this.kdTree,\n k: this.k,\n classes: Array.from(this.classes),\n isEuclidean: this.isEuclidean\n };\n }\n\n /**\n * Predicts the output given the matrix to predict.\n * @param {Array} dataset\n * @return {Array} predictions\n */\n predict(dataset) {\n if (Array.isArray(dataset)) {\n if (typeof dataset[0] === 'number') {\n return getSinglePrediction(this, dataset);\n } else if (Array.isArray(dataset[0]) && typeof dataset[0][0] === 'number') {\n const predictions = new Array(dataset.length);\n for (var i = 0; i < dataset.length; i++) {\n predictions[i] = getSinglePrediction(this, dataset[i]);\n }\n return predictions;\n }\n }\n throw new TypeError('dataset to predict must be an array or a matrix');\n }\n}\n\nfunction getSinglePrediction(knn, currentCase) {\n var nearestPoints = knn.kdTree.nearest(currentCase, knn.k);\n var pointsPerClass = {};\n var predictedClass = -1;\n var maxPoints = -1;\n var lastElement = nearestPoints[0][0].length - 1;\n\n for (var element of knn.classes) {\n pointsPerClass[element] = 0;\n }\n\n for (var i = 0; i < nearestPoints.length; ++i) {\n var currentClass = nearestPoints[i][0][lastElement];\n var currentPoints = ++pointsPerClass[currentClass];\n if (currentPoints > maxPoints) {\n predictedClass = currentClass;\n maxPoints = currentPoints;\n }\n }\n\n return predictedClass;\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index d62a806..426ac68 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "ml", - "version": "3.5.0", + "version": "3.6.0", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 7f092cf..4790e3c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ml", - "version": "3.5.0", + "version": "3.6.0", "description": "Machine learning tools", "main": "src/index.js", "scripts": { @@ -33,27 +33,27 @@ }, "homepage": "https://github.com/mljs/ml", "dependencies": { - "binary-search": "^1.3.4", - "ml-array-max": "^1.0.2", - "ml-array-mean": "^1.0.2", - "ml-array-median": "^1.0.2", - "ml-array-min": "^1.0.2", - "ml-array-mode": "^1.0.1", - "ml-array-normed": "^1.0.1", - "ml-array-rescale": "^1.1.1", - "ml-array-sequential-fill": "^1.0.1", - "ml-array-standard-deviation": "^1.0.1", + "binary-search": "^1.3.5", + "ml-array-max": "^1.1.1", + "ml-array-mean": "^1.1.1", + "ml-array-median": "^1.1.1", + "ml-array-min": "^1.1.1", + "ml-array-mode": "^1.1.1", + "ml-array-normed": "^1.0.2", + "ml-array-rescale": "^1.2.1", + "ml-array-sequential-fill": "^1.1.1", + "ml-array-standard-deviation": "^1.1.1", "ml-array-utils": "^0.4.0", - "ml-array-variance": "^1.0.1", - "ml-array-xy-centroids-merge": "^0.2.4", + "ml-array-variance": "^1.1.1", + "ml-array-xy-centroids-merge": "^0.2.5", "ml-array-xy-equally-spaced": "^0.2.9", "ml-array-xy-filter-x": "0.0.5", - "ml-array-xy-max-merge": "^0.2.4", - "ml-array-xy-max-y": "^0.2.5", - "ml-array-xy-sort-x": "^0.2.4", - "ml-array-xy-weighted-merge": "^0.2.6", - "ml-arrayxy-closestx": "^1.2.2", - "ml-arrayxy-uniquex": "^0.2.5", + "ml-array-xy-max-merge": "^0.2.5", + "ml-array-xy-max-y": "^0.2.7", + "ml-array-xy-sort-x": "^0.2.5", + "ml-array-xy-weighted-merge": "^0.2.7", + "ml-arrayxy-closestx": "^1.2.4", + "ml-arrayxy-uniquex": "^0.2.6", "ml-bit-array": "^1.0.0", "ml-cart": "^1.0.8", "ml-confusion-matrix": "^0.3.0", @@ -64,10 +64,10 @@ "ml-hash-table": "^0.2.1", "ml-hclust": "^1.3.0", "ml-kernel": "^2.3.4", - "ml-kmeans": "^4.1.0", + "ml-kmeans": "^4.2.1", "ml-knn": "^2.1.3", - "ml-levenberg-marquardt": "^1.0.3", - "ml-matrix": "^5.1.1", + "ml-levenberg-marquardt": "^1.0.4", + "ml-matrix": "^5.3.0", "ml-naivebayes": "^3.0.0", "ml-pad-array": "^1.0.0", "ml-pca": "^2.1.0", @@ -89,6 +89,6 @@ "babel-plugin-remove-comments": "^2.0.0", "babel-preset-babili": "^0.1.4", "babel-preset-es2015": "^6.24.1", - "cheminfo-tools": "^1.20.2" + "cheminfo-tools": "^1.23.3" } }