From fce26add53261187695c56f1253a2d7186db1ade Mon Sep 17 00:00:00 2001 From: cheminfo bot Date: Wed, 7 Oct 2020 16:39:28 +0000 Subject: [PATCH] Release v5.2.0 --- bower.json | 2 +- dist/ml.js | 26542 ++++++++++++++++++++++++------------------- dist/ml.js.map | 2 +- dist/ml.min.js | 4 +- dist/ml.min.js.map | 2 +- package.json | 10 +- 6 files changed, 14665 insertions(+), 11897 deletions(-) diff --git a/bower.json b/bower.json index b604599..f281f62 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "ml", - "version": "5.1.1", + "version": "5.2.0", "main": [ "dist/ml.js", "dist/ml.min.js" diff --git a/dist/ml.js b/dist/ml.js index ccd022b..d90a48b 100644 --- a/dist/ml.js +++ b/dist/ml.js @@ -1,31 +1,24 @@ /** * ml - Machine learning tools - * @version v5.1.1 + * @version v5.2.0 * @link https://github.com/mljs/ml * @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : - (global = global || self, factory(global.ML = {})); -}(this, function (exports) { 'use strict'; + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ML = {})); +}(this, (function (exports) { 'use strict'; const toString = Object.prototype.toString; - function isAnyArray(object) { return toString.call(object).endsWith('Array]'); } - var src = isAnyArray; - - /** - * Computes the maximum of the given values - * @param {Array} input - * @return {number} - */ - function max(input) { - if (!src(input)) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!isAnyArray(input)) { throw new TypeError('input must be an array'); } @@ -33,23 +26,32 @@ throw new TypeError('input must not be empty'); } - var maxValue = input[0]; + var _options$fromIndex = options.fromIndex, + fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex, + _options$toIndex = options.toIndex, + toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex; - for (var i = 1; i < input.length; i++) { + if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) { + throw new Error('fromIndex must be a positive integer smaller than length'); + } + + if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) { + throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length'); + } + + var maxValue = input[fromIndex]; + + for (var i = fromIndex + 1; i < toIndex; i++) { if (input[i] > maxValue) maxValue = input[i]; } return maxValue; } - /** - * Computes the minimum of the given values - * @param {Array} input - * @return {number} - */ - function min(input) { - if (!src(input)) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!isAnyArray(input)) { throw new TypeError('input must be an array'); } @@ -57,9 +59,22 @@ throw new TypeError('input must not be empty'); } - var minValue = input[0]; + var _options$fromIndex = options.fromIndex, + fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex, + _options$toIndex = options.toIndex, + toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex; + + if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) { + throw new Error('fromIndex must be a positive integer smaller than length'); + } + + if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) { + throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length'); + } + + var minValue = input[fromIndex]; - for (var i = 1; i < input.length; i++) { + for (var i = fromIndex + 1; i < toIndex; i++) { if (input[i] < minValue) minValue = input[i]; } @@ -69,7 +84,7 @@ function rescale(input) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (!src(input)) { + if (!isAnyArray(input)) { throw new TypeError('input must be an array'); } else if (input.length === 0) { throw new TypeError('input must not be empty'); @@ -78,7 +93,7 @@ var output; if (options.output !== undefined) { - if (!src(options.output)) { + if (!isAnyArray(options.output)) { throw new TypeError('output option must be an array if specified'); } @@ -112,442 +127,169 @@ return output; } - /** - * @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) { - let max = outer ? matrix.rows : matrix.rows - 1; - - if (index < 0 || index > max) { - throw new RangeError('Row index out of range'); - } + const indent = ' '.repeat(2); + const indentData = ' '.repeat(4); + function inspectMatrix() { + return inspectMatrixWithOptions(this); } - /** - * @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) { - let max = outer ? matrix.columns : matrix.columns - 1; - - if (index < 0 || index > max) { - throw new RangeError('Column index out of range'); - } + function inspectMatrixWithOptions(matrix, options = {}) { + const { + maxRows = 15, + maxColumns = 10, + maxNumSize = 8 + } = options; + return `${matrix.constructor.name} { +${indent}[ +${indentData}${inspectData(matrix, maxRows, maxColumns, maxNumSize)} +${indent}] +${indent}rows: ${matrix.rows} +${indent}columns: ${matrix.columns} +}`; } - /** - * @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'); - } + function inspectData(matrix, maxRows, maxColumns, maxNumSize) { + const { + rows, + columns + } = matrix; + const maxI = Math.min(rows, maxRows); + const maxJ = Math.min(columns, maxColumns); + const result = []; - 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} - */ + for (let i = 0; i < maxI; i++) { + let line = []; - function checkColumnVector(matrix, vector) { - if (vector.to1DArray) { - vector = vector.to1DArray(); - } + for (let j = 0; j < maxJ; j++) { + line.push(formatNumber(matrix.get(i, j), maxNumSize)); + } - if (vector.length !== matrix.rows) { - throw new RangeError('vector size must be the same as the number of rows'); + result.push(`${line.join(' ')}`); } - 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'); + if (maxJ !== columns) { + result[result.length - 1] += ` ... ${columns - maxColumns} more columns`; } - let rowOut = rowIndices.some(r => { - return r < 0 || r >= matrix.rows; - }); - - if (rowOut) { - throw new RangeError('row indices are out of range'); + if (maxI !== rows) { + result.push(`... ${rows - maxRows} more rows`); } - if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices); - return rowIndices; + return result.join(`\n${indentData}`); } - function checkColumnIndices(matrix, columnIndices) { - if (typeof columnIndices !== 'object') { - throw new TypeError('unexpected type for column indices'); - } - - let columnOut = columnIndices.some(c => { - return c < 0 || c >= matrix.columns; - }); - if (columnOut) { - throw new RangeError('column indices are out of range'); - } + function formatNumber(num, maxNumSize) { + const numStr = String(num); - 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'); + if (numStr.length <= maxNumSize) { + return numStr.padEnd(maxNumSize, ' '); } - checkNumber('startRow', startRow); - checkNumber('endRow', endRow); - checkNumber('startColumn', startColumn); - checkNumber('endColumn', endColumn); + const precise = num.toPrecision(maxNumSize - 2); - 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 (precise.length <= maxNumSize) { + return precise; } + + const exponential = num.toExponential(maxNumSize - 2); + const eIndex = exponential.indexOf('e'); + const e = exponential.slice(eIndex); + return exponential.slice(0, maxNumSize - e.length) + e; } - function newArray(length) { - let value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - let array = []; - for (let i = 0; i < length; i++) { - array.push(value); - } + function installMathOperations(AbstractMatrix, Matrix) { + AbstractMatrix.prototype.add = function add(value) { + if (typeof value === 'number') return this.addS(value); + return this.addM(value); + }; - return array; - } + AbstractMatrix.prototype.addS = function addS(value) { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + value); + } + } - function checkNumber(name, value) { - if (typeof value !== 'number') { - throw new TypeError("".concat(name, " must be a number")); - } - } + return this; + }; - function sumByRow(matrix) { - let sum = newArray(matrix.rows); + AbstractMatrix.prototype.addM = function addM(matrix) { + matrix = Matrix.checkMatrix(matrix); - for (let i = 0; i < matrix.rows; ++i) { - for (let j = 0; j < matrix.columns; ++j) { - sum[i] += matrix.get(i, j); + if (this.rows !== matrix.rows || this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); } - } - - return sum; - } - function sumByColumn(matrix) { - let sum = newArray(matrix.columns); - for (let i = 0; i < matrix.rows; ++i) { - for (let j = 0; j < matrix.columns; ++j) { - sum[j] += matrix.get(i, j); + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + matrix.get(i, j)); + } } - } - return sum; - } - function sumAll(matrix) { - let v = 0; + return this; + }; - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - v += matrix.get(i, j); - } - } + AbstractMatrix.add = function add(matrix, value) { + const newMatrix = new Matrix(matrix); + return newMatrix.add(value); + }; - return v; - } - function productByRow(matrix) { - let sum = newArray(matrix.rows, 1); + AbstractMatrix.prototype.sub = function sub(value) { + if (typeof value === 'number') return this.subS(value); + return this.subM(value); + }; - for (let i = 0; i < matrix.rows; ++i) { - for (let j = 0; j < matrix.columns; ++j) { - sum[i] *= matrix.get(i, j); + AbstractMatrix.prototype.subS = function subS(value) { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - value); + } } - } - return sum; - } - function productByColumn(matrix) { - let sum = newArray(matrix.columns, 1); + return this; + }; - for (let i = 0; i < matrix.rows; ++i) { - for (let j = 0; j < matrix.columns; ++j) { - sum[j] *= matrix.get(i, j); - } - } + AbstractMatrix.prototype.subM = function subM(matrix) { + matrix = Matrix.checkMatrix(matrix); - return sum; - } - function productAll(matrix) { - let v = 1; + if (this.rows !== matrix.rows || this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - v *= matrix.get(i, j); + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - matrix.get(i, j)); + } } - } - return v; - } - function varianceByRow(matrix, unbiased, mean) { - const rows = matrix.rows; - const cols = matrix.columns; - const variance = []; - - for (let i = 0; i < rows; i++) { - let sum1 = 0; - let sum2 = 0; - let x = 0; - - for (let j = 0; j < cols; j++) { - x = matrix.get(i, j) - mean[i]; - sum1 += x; - sum2 += x * x; - } - - if (unbiased) { - variance.push((sum2 - sum1 * sum1 / cols) / (cols - 1)); - } else { - variance.push((sum2 - sum1 * sum1 / cols) / cols); - } - } - - return variance; - } - function varianceByColumn(matrix, unbiased, mean) { - const rows = matrix.rows; - const cols = matrix.columns; - const variance = []; - - for (let j = 0; j < cols; j++) { - let sum1 = 0; - let sum2 = 0; - let x = 0; - - for (let i = 0; i < rows; i++) { - x = matrix.get(i, j) - mean[j]; - sum1 += x; - sum2 += x * x; - } - - if (unbiased) { - variance.push((sum2 - sum1 * sum1 / rows) / (rows - 1)); - } else { - variance.push((sum2 - sum1 * sum1 / rows) / rows); - } - } - - return variance; - } - function varianceAll(matrix, unbiased, mean) { - const rows = matrix.rows; - const cols = matrix.columns; - const size = rows * cols; - let sum1 = 0; - let sum2 = 0; - let x = 0; - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - x = matrix.get(i, j) - mean; - sum1 += x; - sum2 += x * x; - } - } - - if (unbiased) { - return (sum2 - sum1 * sum1 / size) / (size - 1); - } else { - return (sum2 - sum1 * sum1 / size) / size; - } - } - function centerByRow(matrix, mean) { - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - matrix.set(i, j, matrix.get(i, j) - mean[i]); - } - } - } - function centerByColumn(matrix, mean) { - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - matrix.set(i, j, matrix.get(i, j) - mean[j]); - } - } - } - function centerAll(matrix, mean) { - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - matrix.set(i, j, matrix.get(i, j) - mean); - } - } - } - function getScaleByRow(matrix) { - const scale = []; - - for (let i = 0; i < matrix.rows; i++) { - let sum = 0; - - for (let j = 0; j < matrix.columns; j++) { - sum += Math.pow(matrix.get(i, j), 2) / (matrix.columns - 1); - } - - scale.push(Math.sqrt(sum)); - } - - return scale; - } - function scaleByRow(matrix, scale) { - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - matrix.set(i, j, matrix.get(i, j) / scale[i]); - } - } - } - function getScaleByColumn(matrix) { - const scale = []; - - for (let j = 0; j < matrix.columns; j++) { - let sum = 0; - - for (let i = 0; i < matrix.rows; i++) { - sum += Math.pow(matrix.get(i, j), 2) / (matrix.rows - 1); - } - - scale.push(Math.sqrt(sum)); - } - - return scale; - } - function scaleByColumn(matrix, scale) { - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - matrix.set(i, j, matrix.get(i, j) / scale[j]); - } - } - } - function getScaleAll(matrix) { - const divider = matrix.size - 1; - let sum = 0; - - for (let j = 0; j < matrix.columns; j++) { - for (let i = 0; i < matrix.rows; i++) { - sum += Math.pow(matrix.get(i, j), 2) / divider; - } - } - - return Math.sqrt(sum); - } - function scaleAll(matrix, scale) { - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - matrix.set(i, j, matrix.get(i, j) / scale); - } - } - } - - function inspectMatrix() { - const indent = ' '.repeat(2); - const indentData = ' '.repeat(4); - return "".concat(this.constructor.name, " {\n").concat(indent, "[\n").concat(indentData).concat(inspectData(this, indentData), "\n").concat(indent, "]\n").concat(indent, "rows: ").concat(this.rows, "\n").concat(indent, "columns: ").concat(this.columns, "\n}"); - } - const maxRows = 15; - const maxColumns = 10; - const maxNumSize = 8; - - function inspectData(matrix, indent) { - const { - rows, - columns - } = matrix; - const maxI = Math.min(rows, maxRows); - const maxJ = Math.min(columns, maxColumns); - const result = []; - - for (let i = 0; i < maxI; i++) { - let line = []; - - for (let j = 0; j < maxJ; j++) { - line.push(formatNumber(matrix.get(i, j))); - } - - result.push("".concat(line.join(' '))); - } - - if (maxJ !== columns) { - result[result.length - 1] += " ... ".concat(columns - maxColumns, " more columns"); - } - - if (maxI !== rows) { - result.push("... ".concat(rows - maxRows, " more rows")); - } - - return result.join("\n".concat(indent)); - } - - function formatNumber(num) { - const numStr = String(num); - - if (numStr.length <= maxNumSize) { - return numStr.padEnd(maxNumSize, ' '); - } - - const precise = num.toPrecision(maxNumSize - 2); + return this; + }; - if (precise.length <= maxNumSize) { - return precise; - } + AbstractMatrix.sub = function sub(matrix, value) { + const newMatrix = new Matrix(matrix); + return newMatrix.sub(value); + }; - const exponential = num.toExponential(maxNumSize - 2); - const eIndex = exponential.indexOf('e'); - const e = exponential.substring(eIndex); - return exponential.substring(0, maxNumSize - e.length) + e; - } + AbstractMatrix.prototype.subtract = AbstractMatrix.prototype.sub; + AbstractMatrix.prototype.subtractS = AbstractMatrix.prototype.subS; + AbstractMatrix.prototype.subtractM = AbstractMatrix.prototype.subM; + AbstractMatrix.subtract = AbstractMatrix.sub; - function installMathOperations(AbstractMatrix, Matrix) { - AbstractMatrix.prototype.add = function add(value) { - if (typeof value === 'number') return this.addS(value); - return this.addM(value); + AbstractMatrix.prototype.mul = function mul(value) { + if (typeof value === 'number') return this.mulS(value); + return this.mulM(value); }; - AbstractMatrix.prototype.addS = function addS(value) { + AbstractMatrix.prototype.mulS = function mulS(value) { for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) + value); + this.set(i, j, this.get(i, j) * value); } } return this; }; - AbstractMatrix.prototype.addM = function addM(matrix) { + AbstractMatrix.prototype.mulM = function mulM(matrix) { matrix = Matrix.checkMatrix(matrix); if (this.rows !== matrix.rows || this.columns !== matrix.columns) { @@ -556,34 +298,39 @@ for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) + matrix.get(i, j)); + this.set(i, j, this.get(i, j) * matrix.get(i, j)); } } return this; }; - AbstractMatrix.add = function add(matrix, value) { + AbstractMatrix.mul = function mul(matrix, value) { const newMatrix = new Matrix(matrix); - return newMatrix.add(value); + return newMatrix.mul(value); }; - AbstractMatrix.prototype.sub = function sub(value) { - if (typeof value === 'number') return this.subS(value); - return this.subM(value); + AbstractMatrix.prototype.multiply = AbstractMatrix.prototype.mul; + AbstractMatrix.prototype.multiplyS = AbstractMatrix.prototype.mulS; + AbstractMatrix.prototype.multiplyM = AbstractMatrix.prototype.mulM; + AbstractMatrix.multiply = AbstractMatrix.mul; + + AbstractMatrix.prototype.div = function div(value) { + if (typeof value === 'number') return this.divS(value); + return this.divM(value); }; - AbstractMatrix.prototype.subS = function subS(value) { + AbstractMatrix.prototype.divS = function divS(value) { for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) - value); + this.set(i, j, this.get(i, j) / value); } } return this; }; - AbstractMatrix.prototype.subM = function subM(matrix) { + AbstractMatrix.prototype.divM = function divM(matrix) { matrix = Matrix.checkMatrix(matrix); if (this.rows !== matrix.rows || this.columns !== matrix.columns) { @@ -592,98 +339,16 @@ for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) - matrix.get(i, j)); + this.set(i, j, this.get(i, j) / matrix.get(i, j)); } } return this; }; - AbstractMatrix.sub = function sub(matrix, value) { + AbstractMatrix.div = function div(matrix, value) { const newMatrix = new Matrix(matrix); - return newMatrix.sub(value); - }; - - AbstractMatrix.prototype.subtract = AbstractMatrix.prototype.sub; - AbstractMatrix.prototype.subtractS = AbstractMatrix.prototype.subS; - AbstractMatrix.prototype.subtractM = AbstractMatrix.prototype.subM; - AbstractMatrix.subtract = AbstractMatrix.sub; - - AbstractMatrix.prototype.mul = function mul(value) { - if (typeof value === 'number') return this.mulS(value); - return this.mulM(value); - }; - - AbstractMatrix.prototype.mulS = function mulS(value) { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) * value); - } - } - - return this; - }; - - AbstractMatrix.prototype.mulM = function mulM(matrix) { - matrix = Matrix.checkMatrix(matrix); - - if (this.rows !== matrix.rows || this.columns !== matrix.columns) { - throw new RangeError('Matrices dimensions must be equal'); - } - - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) * matrix.get(i, j)); - } - } - - return this; - }; - - AbstractMatrix.mul = function mul(matrix, value) { - const newMatrix = new Matrix(matrix); - return newMatrix.mul(value); - }; - - AbstractMatrix.prototype.multiply = AbstractMatrix.prototype.mul; - AbstractMatrix.prototype.multiplyS = AbstractMatrix.prototype.mulS; - AbstractMatrix.prototype.multiplyM = AbstractMatrix.prototype.mulM; - AbstractMatrix.multiply = AbstractMatrix.mul; - - AbstractMatrix.prototype.div = function div(value) { - if (typeof value === 'number') return this.divS(value); - return this.divM(value); - }; - - AbstractMatrix.prototype.divS = function divS(value) { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) / value); - } - } - - return this; - }; - - AbstractMatrix.prototype.divM = function divM(matrix) { - matrix = Matrix.checkMatrix(matrix); - - if (this.rows !== matrix.rows || this.columns !== matrix.columns) { - throw new RangeError('Matrices dimensions must be equal'); - } - - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) / matrix.get(i, j)); - } - } - - return this; - }; - - AbstractMatrix.div = function div(matrix, value) { - const newMatrix = new Matrix(matrix); - return newMatrix.div(value); + return newMatrix.div(value); }; AbstractMatrix.prototype.divide = AbstractMatrix.prototype.div; @@ -1425,14869 +1090,17859 @@ }; } - class AbstractMatrix { - static from1DArray(newRows, newColumns, newData) { - let length = newRows * newColumns; + /** + * @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) { + let max = outer ? matrix.rows : matrix.rows - 1; - if (length !== newData.length) { - throw new RangeError('data length does not match given dimensions'); - } + 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] + */ - let newMatrix = new Matrix(newRows, newColumns); + function checkColumnIndex(matrix, index, outer) { + let max = outer ? matrix.columns : matrix.columns - 1; - for (let row = 0; row < newRows; row++) { - for (let column = 0; column < newColumns; column++) { - newMatrix.set(row, column, newData[row * newColumns + column]); - } - } + 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} + */ - return newMatrix; + function checkRowVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); } - static rowVector(newData) { - let vector = new Matrix(1, newData.length); + if (vector.length !== matrix.columns) { + throw new RangeError('vector size must be the same as the number of columns'); + } - for (let i = 0; i < newData.length; i++) { - vector.set(0, i, newData[i]); - } + 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} + */ - return vector; + function checkColumnVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); } - static columnVector(newData) { - let vector = new Matrix(newData.length, 1); - - for (let i = 0; i < newData.length; i++) { - vector.set(i, 0, newData[i]); - } + if (vector.length !== matrix.rows) { + throw new RangeError('vector size must be the same as the number of rows'); + } - return vector; + 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'); } - static zeros(rows, columns) { - return new Matrix(rows, columns); + let rowOut = rowIndices.some(r => { + return r < 0 || r >= matrix.rows; + }); + + if (rowOut) { + throw new RangeError('row indices are out of range'); } - static ones(rows, columns) { - return new Matrix(rows, columns).fill(1); + 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'); } - static rand(rows, columns) { - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + let columnOut = columnIndices.some(c => { + return c < 0 || c >= matrix.columns; + }); - if (typeof options !== 'object') { - throw new TypeError('options must be an object'); - } + if (columnOut) { + throw new RangeError('column indices are out of range'); + } - const { - random = Math.random - } = options; - let matrix = new Matrix(rows, columns); + 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'); + } - for (let i = 0; i < rows; i++) { - for (let j = 0; j < columns; j++) { - matrix.set(i, j, random()); - } - } + checkNumber('startRow', startRow); + checkNumber('endRow', endRow); + checkNumber('startColumn', startColumn); + checkNumber('endColumn', endColumn); - return matrix; + 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 newArray(length, value = 0) { + let array = []; - static randInt(rows, columns) { - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + for (let i = 0; i < length; i++) { + array.push(value); + } - if (typeof options !== 'object') { - throw new TypeError('options must be an object'); - } + return array; + } - const { - min = 0, - max = 1000, - random = Math.random - } = options; - if (!Number.isInteger(min)) throw new TypeError('min must be an integer'); - if (!Number.isInteger(max)) throw new TypeError('max must be an integer'); - if (min >= max) throw new RangeError('min must be smaller than max'); - let interval = max - min; - let matrix = new Matrix(rows, columns); + function checkNumber(name, value) { + if (typeof value !== 'number') { + throw new TypeError(`${name} must be a number`); + } + } - for (let i = 0; i < rows; i++) { - for (let j = 0; j < columns; j++) { - let value = min + Math.round(random() * interval); - matrix.set(i, j, value); - } - } + function sumByRow(matrix) { + let sum = newArray(matrix.rows); - return matrix; + for (let i = 0; i < matrix.rows; ++i) { + for (let j = 0; j < matrix.columns; ++j) { + sum[i] += matrix.get(i, j); + } } - static eye(rows, columns, value) { - if (columns === undefined) columns = rows; - if (value === undefined) value = 1; - let min = Math.min(rows, columns); - let matrix = this.zeros(rows, columns); + return sum; + } + function sumByColumn(matrix) { + let sum = newArray(matrix.columns); - for (let i = 0; i < min; i++) { - matrix.set(i, i, value); + for (let i = 0; i < matrix.rows; ++i) { + for (let j = 0; j < matrix.columns; ++j) { + sum[j] += matrix.get(i, j); } - - return matrix; } - static diag(data, rows, columns) { - let l = data.length; - if (rows === undefined) rows = l; - if (columns === undefined) columns = rows; - let min = Math.min(l, rows, columns); - let matrix = this.zeros(rows, columns); + return sum; + } + function sumAll(matrix) { + let v = 0; - for (let i = 0; i < min; i++) { - matrix.set(i, i, data[i]); + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + v += matrix.get(i, j); } - - return matrix; } - static min(matrix1, matrix2) { - matrix1 = this.checkMatrix(matrix1); - matrix2 = this.checkMatrix(matrix2); - let rows = matrix1.rows; - let columns = matrix1.columns; - let result = new Matrix(rows, columns); + return v; + } + function productByRow(matrix) { + let sum = newArray(matrix.rows, 1); - for (let i = 0; i < rows; i++) { - for (let j = 0; j < columns; j++) { - result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j))); - } + for (let i = 0; i < matrix.rows; ++i) { + for (let j = 0; j < matrix.columns; ++j) { + sum[i] *= matrix.get(i, j); } - - return result; } - static max(matrix1, matrix2) { - matrix1 = this.checkMatrix(matrix1); - matrix2 = this.checkMatrix(matrix2); - let rows = matrix1.rows; - let columns = matrix1.columns; - let result = new this(rows, columns); + return sum; + } + function productByColumn(matrix) { + let sum = newArray(matrix.columns, 1); - for (let i = 0; i < rows; i++) { - for (let j = 0; j < columns; j++) { - result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j))); - } + for (let i = 0; i < matrix.rows; ++i) { + for (let j = 0; j < matrix.columns; ++j) { + sum[j] *= matrix.get(i, j); } - - return result; } - static checkMatrix(value) { - return AbstractMatrix.isMatrix(value) ? value : new Matrix(value); - } + return sum; + } + function productAll(matrix) { + let v = 1; - static isMatrix(value) { - return value != null && value.klass === 'Matrix'; + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + v *= matrix.get(i, j); + } } - get size() { - return this.rows * this.columns; - } + return v; + } + function varianceByRow(matrix, unbiased, mean) { + const rows = matrix.rows; + const cols = matrix.columns; + const variance = []; - apply(callback) { - if (typeof callback !== 'function') { - throw new TypeError('callback must be a function'); - } + for (let i = 0; i < rows; i++) { + let sum1 = 0; + let sum2 = 0; + let x = 0; - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - callback.call(this, i, j); - } + for (let j = 0; j < cols; j++) { + x = matrix.get(i, j) - mean[i]; + sum1 += x; + sum2 += x * x; } - return this; + if (unbiased) { + variance.push((sum2 - sum1 * sum1 / cols) / (cols - 1)); + } else { + variance.push((sum2 - sum1 * sum1 / cols) / cols); + } } - to1DArray() { - let array = []; + return variance; + } + function varianceByColumn(matrix, unbiased, mean) { + const rows = matrix.rows; + const cols = matrix.columns; + const variance = []; - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - array.push(this.get(i, j)); - } + for (let j = 0; j < cols; j++) { + let sum1 = 0; + let sum2 = 0; + let x = 0; + + for (let i = 0; i < rows; i++) { + x = matrix.get(i, j) - mean[j]; + sum1 += x; + sum2 += x * x; } - return array; + if (unbiased) { + variance.push((sum2 - sum1 * sum1 / rows) / (rows - 1)); + } else { + variance.push((sum2 - sum1 * sum1 / rows) / rows); + } } - to2DArray() { - let copy = []; - - for (let i = 0; i < this.rows; i++) { - copy.push([]); + return variance; + } + function varianceAll(matrix, unbiased, mean) { + const rows = matrix.rows; + const cols = matrix.columns; + const size = rows * cols; + let sum1 = 0; + let sum2 = 0; + let x = 0; - for (let j = 0; j < this.columns; j++) { - copy[i].push(this.get(i, j)); - } + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + x = matrix.get(i, j) - mean; + sum1 += x; + sum2 += x * x; } - - return copy; } - toJSON() { - return this.to2DArray(); + if (unbiased) { + return (sum2 - sum1 * sum1 / size) / (size - 1); + } else { + return (sum2 - sum1 * sum1 / size) / size; } - - isRowVector() { - return this.rows === 1; + } + function centerByRow(matrix, mean) { + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + matrix.set(i, j, matrix.get(i, j) - mean[i]); + } } - - isColumnVector() { - return this.columns === 1; + } + function centerByColumn(matrix, mean) { + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + matrix.set(i, j, matrix.get(i, j) - mean[j]); + } + } + } + function centerAll(matrix, mean) { + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + matrix.set(i, j, matrix.get(i, j) - mean); + } } + } + function getScaleByRow(matrix) { + const scale = []; - isVector() { - return this.rows === 1 || this.columns === 1; + for (let i = 0; i < matrix.rows; i++) { + let sum = 0; + + for (let j = 0; j < matrix.columns; j++) { + sum += Math.pow(matrix.get(i, j), 2) / (matrix.columns - 1); + } + + scale.push(Math.sqrt(sum)); } - isSquare() { - return this.rows === this.columns; + return scale; + } + function scaleByRow(matrix, scale) { + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + matrix.set(i, j, matrix.get(i, j) / scale[i]); + } } + } + function getScaleByColumn(matrix) { + const scale = []; - isSymmetric() { - if (this.isSquare()) { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j <= i; j++) { - if (this.get(i, j) !== this.get(j, i)) { - return false; - } - } - } + for (let j = 0; j < matrix.columns; j++) { + let sum = 0; - return true; + for (let i = 0; i < matrix.rows; i++) { + sum += Math.pow(matrix.get(i, j), 2) / (matrix.rows - 1); } - return false; + scale.push(Math.sqrt(sum)); } - isEchelonForm() { - let i = 0; - let j = 0; - let previousColumn = -1; - let isEchelonForm = true; - let checked = false; + return scale; + } + function scaleByColumn(matrix, scale) { + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + matrix.set(i, j, matrix.get(i, j) / scale[j]); + } + } + } + function getScaleAll(matrix) { + const divider = matrix.size - 1; + let sum = 0; - 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++; + for (let j = 0; j < matrix.columns; j++) { + for (let i = 0; i < matrix.rows; i++) { + sum += Math.pow(matrix.get(i, j), 2) / divider; } - - return isEchelonForm; } - 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 Math.sqrt(sum); + } + function scaleAll(matrix, scale) { + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + matrix.set(i, j, matrix.get(i, j) / scale); } - - return isReducedEchelonForm; } + } - echelonForm() { - let result = this.clone(); - let h = 0; - let k = 0; - - while (h < result.rows && k < result.columns) { - let iMax = h; - - for (let i = h; i < result.rows; i++) { - if (result.get(i, k) > result.get(iMax, k)) { - iMax = i; - } - } - - if (result.get(iMax, k) === 0) { - k++; - } else { - result.swapRows(h, iMax); - let tmp = result.get(h, k); - - for (let j = k; j < result.columns; j++) { - result.set(h, j, result.get(h, j) / tmp); - } + class AbstractMatrix { + static from1DArray(newRows, newColumns, newData) { + let length = newRows * newColumns; - for (let i = h + 1; i < result.rows; i++) { - let factor = result.get(i, k) / result.get(h, k); - result.set(i, k, 0); + if (length !== newData.length) { + throw new RangeError('data length does not match given dimensions'); + } - for (let j = k + 1; j < result.columns; j++) { - result.set(i, j, result.get(i, j) - result.get(h, j) * factor); - } - } + let newMatrix = new Matrix(newRows, newColumns); - h++; - k++; + for (let row = 0; row < newRows; row++) { + for (let column = 0; column < newColumns; column++) { + newMatrix.set(row, column, newData[row * newColumns + column]); } } - return result; + return newMatrix; } - reducedEchelonForm() { - let result = this.echelonForm(); - let m = result.columns; - let n = result.rows; - let h = n - 1; - - while (h >= 0) { - if (result.maxRow(h) === 0) { - h--; - } else { - let p = 0; - let pivot = false; + static rowVector(newData) { + let vector = new Matrix(1, newData.length); - while (p < n && pivot === false) { - if (result.get(h, p) === 1) { - pivot = true; - } else { - p++; - } - } + for (let i = 0; i < newData.length; i++) { + vector.set(0, i, newData[i]); + } - for (let i = 0; i < h; i++) { - let factor = result.get(i, p); + return vector; + } - for (let j = p; j < m; j++) { - let tmp = result.get(i, j) - factor * result.get(h, j); - result.set(i, j, tmp); - } - } + static columnVector(newData) { + let vector = new Matrix(newData.length, 1); - h--; - } + for (let i = 0; i < newData.length; i++) { + vector.set(i, 0, newData[i]); } - return result; + return vector; } - set() { - throw new Error('set method is unimplemented'); + static zeros(rows, columns) { + return new Matrix(rows, columns); } - get() { - throw new Error('get method is unimplemented'); + static ones(rows, columns) { + return new Matrix(rows, columns).fill(1); } - repeat() { - let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - + static rand(rows, columns, options = {}) { if (typeof options !== 'object') { throw new TypeError('options must be an object'); } const { - rows = 1, - columns = 1 + random = Math.random } = options; + let matrix = new Matrix(rows, columns); - if (!Number.isInteger(rows) || rows <= 0) { - throw new TypeError('rows must be a positive integer'); + for (let i = 0; i < rows; i++) { + for (let j = 0; j < columns; j++) { + matrix.set(i, j, random()); + } } - if (!Number.isInteger(columns) || columns <= 0) { - throw new TypeError('columns must be a positive integer'); + return matrix; + } + + static randInt(rows, columns, options = {}) { + if (typeof options !== 'object') { + throw new TypeError('options must be an object'); } - let matrix = new Matrix(this.rows * rows, this.columns * columns); + const { + min = 0, + max = 1000, + random = Math.random + } = options; + if (!Number.isInteger(min)) throw new TypeError('min must be an integer'); + if (!Number.isInteger(max)) throw new TypeError('max must be an integer'); + if (min >= max) throw new RangeError('min must be smaller than max'); + let interval = max - min; + let matrix = new Matrix(rows, columns); for (let i = 0; i < rows; i++) { for (let j = 0; j < columns; j++) { - matrix.setSubMatrix(this, this.rows * i, this.columns * j); + let value = min + Math.round(random() * interval); + matrix.set(i, j, value); } } return matrix; } - fill(value) { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, value); - } - } + static eye(rows, columns, value) { + if (columns === undefined) columns = rows; + if (value === undefined) value = 1; + let min = Math.min(rows, columns); + let matrix = this.zeros(rows, columns); - return this; - } + for (let i = 0; i < min; i++) { + matrix.set(i, i, value); + } - neg() { - return this.mulS(-1); + return matrix; } - getRow(index) { - checkRowIndex(this, index); - let row = []; + static diag(data, rows, columns) { + let l = data.length; + if (rows === undefined) rows = l; + if (columns === undefined) columns = rows; + let min = Math.min(l, rows, columns); + let matrix = this.zeros(rows, columns); - for (let i = 0; i < this.columns; i++) { - row.push(this.get(index, i)); + for (let i = 0; i < min; i++) { + matrix.set(i, i, data[i]); } - return row; + return matrix; } - getRowVector(index) { - return Matrix.rowVector(this.getRow(index)); + static min(matrix1, matrix2) { + matrix1 = this.checkMatrix(matrix1); + matrix2 = this.checkMatrix(matrix2); + let rows = matrix1.rows; + let columns = matrix1.columns; + let result = new Matrix(rows, columns); + + for (let i = 0; i < rows; i++) { + for (let j = 0; j < columns; j++) { + result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j))); + } + } + + return result; } - setRow(index, array) { - checkRowIndex(this, index); - array = checkRowVector(this, array); + static max(matrix1, matrix2) { + matrix1 = this.checkMatrix(matrix1); + matrix2 = this.checkMatrix(matrix2); + let rows = matrix1.rows; + let columns = matrix1.columns; + let result = new this(rows, columns); - for (let i = 0; i < this.columns; i++) { - this.set(index, i, array[i]); + for (let i = 0; i < rows; i++) { + for (let j = 0; j < columns; j++) { + result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j))); + } } - return this; + return result; } - swapRows(row1, row2) { - checkRowIndex(this, row1); - checkRowIndex(this, row2); - - for (let i = 0; i < this.columns; i++) { - let temp = this.get(row1, i); - this.set(row1, i, this.get(row2, i)); - this.set(row2, i, temp); - } - - return this; - } - - getColumn(index) { - checkColumnIndex(this, index); - let column = []; - - for (let i = 0; i < this.rows; i++) { - column.push(this.get(i, index)); - } - - return column; + static checkMatrix(value) { + return AbstractMatrix.isMatrix(value) ? value : new Matrix(value); } - getColumnVector(index) { - return Matrix.columnVector(this.getColumn(index)); + static isMatrix(value) { + return value != null && value.klass === 'Matrix'; } - setColumn(index, array) { - checkColumnIndex(this, index); - array = checkColumnVector(this, array); - - for (let i = 0; i < this.rows; i++) { - this.set(i, index, array[i]); - } - - return this; + get size() { + return this.rows * this.columns; } - swapColumns(column1, column2) { - checkColumnIndex(this, column1); - checkColumnIndex(this, column2); - - for (let i = 0; i < this.rows; i++) { - let temp = this.get(i, column1); - this.set(i, column1, this.get(i, column2)); - this.set(i, column2, temp); + apply(callback) { + if (typeof callback !== 'function') { + throw new TypeError('callback must be a function'); } - return this; - } - - addRowVector(vector) { - vector = checkRowVector(this, vector); - for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) + vector[j]); + callback.call(this, i, j); } } return this; } - subRowVector(vector) { - vector = checkRowVector(this, vector); + to1DArray() { + let array = []; for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) - vector[j]); + array.push(this.get(i, j)); } } - return this; + return array; } - mulRowVector(vector) { - vector = checkRowVector(this, vector); + to2DArray() { + let copy = []; for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) * vector[j]); - } - } - - return this; - } - - divRowVector(vector) { - vector = checkRowVector(this, vector); + copy.push([]); - for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) / vector[j]); + copy[i].push(this.get(i, j)); } } - return this; + return copy; } - addColumnVector(vector) { - vector = checkColumnVector(this, vector); - - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) + vector[i]); - } - } - - return this; + toJSON() { + return this.to2DArray(); } - subColumnVector(vector) { - vector = checkColumnVector(this, vector); + isRowVector() { + return this.rows === 1; + } - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) - vector[i]); - } - } + isColumnVector() { + return this.columns === 1; + } - return this; + isVector() { + return this.rows === 1 || this.columns === 1; } - mulColumnVector(vector) { - vector = checkColumnVector(this, vector); + isSquare() { + return this.rows === this.columns; + } - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) * vector[i]); + isSymmetric() { + if (this.isSquare()) { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j <= i; j++) { + if (this.get(i, j) !== this.get(j, i)) { + return false; + } + } } + + return true; } - return this; + return false; } - divColumnVector(vector) { - vector = checkColumnVector(this, vector); - - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) / vector[i]); - } - } + isEchelonForm() { + let i = 0; + let j = 0; + let previousColumn = -1; + let isEchelonForm = true; + let checked = false; - return this; - } + while (i < this.rows && isEchelonForm) { + j = 0; + checked = false; - mulRow(index, value) { - checkRowIndex(this, index); + 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; + } + } - for (let i = 0; i < this.columns; i++) { - this.set(index, i, this.get(index, i) * value); + i++; } - return this; + return isEchelonForm; } - mulColumn(index, value) { - checkColumnIndex(this, index); - - for (let i = 0; i < this.rows; i++) { - this.set(i, index, this.get(i, index) * value); - } + isReducedEchelonForm() { + let i = 0; + let j = 0; + let previousColumn = -1; + let isReducedEchelonForm = true; + let checked = false; - return this; - } + while (i < this.rows && isReducedEchelonForm) { + j = 0; + checked = false; - max() { - let v = this.get(0, 0); + 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 i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - if (this.get(i, j) > v) { - v = this.get(i, j); + for (let k = j + 1; k < this.rows; k++) { + if (this.get(i, k) !== 0) { + isReducedEchelonForm = false; } } + + i++; } - return v; + return isReducedEchelonForm; } - maxIndex() { - let v = this.get(0, 0); - let idx = [0, 0]; + echelonForm() { + let result = this.clone(); + let h = 0; + let k = 0; - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - if (this.get(i, j) > v) { - v = this.get(i, j); - idx[0] = i; - idx[1] = j; + while (h < result.rows && k < result.columns) { + let iMax = h; + + for (let i = h; i < result.rows; i++) { + if (result.get(i, k) > result.get(iMax, k)) { + iMax = i; } } - } - return idx; - } + if (result.get(iMax, k) === 0) { + k++; + } else { + result.swapRows(h, iMax); + let tmp = result.get(h, k); - min() { - let v = this.get(0, 0); + for (let j = k; j < result.columns; j++) { + result.set(h, j, result.get(h, j) / tmp); + } - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - if (this.get(i, j) < v) { - v = this.get(i, j); + for (let i = h + 1; i < result.rows; i++) { + let factor = result.get(i, k) / result.get(h, k); + result.set(i, k, 0); + + for (let j = k + 1; j < result.columns; j++) { + result.set(i, j, result.get(i, j) - result.get(h, j) * factor); + } } + + h++; + k++; } } - return v; + return result; } - minIndex() { - let v = this.get(0, 0); - let idx = [0, 0]; + reducedEchelonForm() { + let result = this.echelonForm(); + let m = result.columns; + let n = result.rows; + let h = n - 1; - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - if (this.get(i, j) < v) { - v = this.get(i, j); - idx[0] = i; - idx[1] = j; + while (h >= 0) { + if (result.maxRow(h) === 0) { + h--; + } else { + let p = 0; + let pivot = false; + + while (p < n && pivot === false) { + if (result.get(h, p) === 1) { + pivot = true; + } else { + p++; + } + } + + for (let i = 0; i < h; i++) { + let factor = result.get(i, p); + + for (let j = p; j < m; j++) { + let tmp = result.get(i, j) - factor * result.get(h, j); + result.set(i, j, tmp); + } } + + h--; } } - return idx; + return result; } - maxRow(row) { - checkRowIndex(this, row); - let v = this.get(row, 0); + set() { + throw new Error('set method is unimplemented'); + } - for (let i = 1; i < this.columns; i++) { - if (this.get(row, i) > v) { - v = this.get(row, i); - } + get() { + throw new Error('get method is unimplemented'); + } + + repeat(options = {}) { + if (typeof options !== 'object') { + throw new TypeError('options must be an object'); } - return v; - } + const { + rows = 1, + columns = 1 + } = options; - maxRowIndex(row) { - checkRowIndex(this, row); - let v = this.get(row, 0); - let idx = [row, 0]; + if (!Number.isInteger(rows) || rows <= 0) { + throw new TypeError('rows must be a positive integer'); + } - for (let i = 1; i < this.columns; i++) { - if (this.get(row, i) > v) { - v = this.get(row, i); - idx[1] = i; + if (!Number.isInteger(columns) || columns <= 0) { + throw new TypeError('columns must be a positive integer'); + } + + let matrix = new Matrix(this.rows * rows, this.columns * columns); + + for (let i = 0; i < rows; i++) { + for (let j = 0; j < columns; j++) { + matrix.setSubMatrix(this, this.rows * i, this.columns * j); } } - return idx; + return matrix; } - minRow(row) { - checkRowIndex(this, row); - let v = this.get(row, 0); - - for (let i = 1; i < this.columns; i++) { - if (this.get(row, i) < v) { - v = this.get(row, i); + fill(value) { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, value); } } - return v; + return this; } - minRowIndex(row) { - checkRowIndex(this, row); - let v = this.get(row, 0); - let idx = [row, 0]; + neg() { + return this.mulS(-1); + } - for (let i = 1; i < this.columns; i++) { - if (this.get(row, i) < v) { - v = this.get(row, i); - idx[1] = i; - } + getRow(index) { + checkRowIndex(this, index); + let row = []; + + for (let i = 0; i < this.columns; i++) { + row.push(this.get(index, i)); } - return idx; + return row; } - maxColumn(column) { - checkColumnIndex(this, column); - let v = this.get(0, column); + getRowVector(index) { + return Matrix.rowVector(this.getRow(index)); + } - for (let i = 1; i < this.rows; i++) { - if (this.get(i, column) > v) { - v = this.get(i, column); - } + setRow(index, array) { + checkRowIndex(this, index); + array = checkRowVector(this, array); + + for (let i = 0; i < this.columns; i++) { + this.set(index, i, array[i]); } - return v; + return this; } - maxColumnIndex(column) { - checkColumnIndex(this, column); - let v = this.get(0, column); - let idx = [0, column]; + swapRows(row1, row2) { + checkRowIndex(this, row1); + checkRowIndex(this, row2); - for (let i = 1; i < this.rows; i++) { - if (this.get(i, column) > v) { - v = this.get(i, column); - idx[0] = i; - } + for (let i = 0; i < this.columns; i++) { + let temp = this.get(row1, i); + this.set(row1, i, this.get(row2, i)); + this.set(row2, i, temp); } - return idx; + return this; } - minColumn(column) { - checkColumnIndex(this, column); - let v = this.get(0, column); + getColumn(index) { + checkColumnIndex(this, index); + let column = []; - for (let i = 1; i < this.rows; i++) { - if (this.get(i, column) < v) { - v = this.get(i, column); - } + for (let i = 0; i < this.rows; i++) { + column.push(this.get(i, index)); } - return v; + return column; } - minColumnIndex(column) { - checkColumnIndex(this, column); - let v = this.get(0, column); - let idx = [0, column]; + getColumnVector(index) { + return Matrix.columnVector(this.getColumn(index)); + } - for (let i = 1; i < this.rows; i++) { - if (this.get(i, column) < v) { - v = this.get(i, column); - idx[0] = i; - } + setColumn(index, array) { + checkColumnIndex(this, index); + array = checkColumnVector(this, array); + + for (let i = 0; i < this.rows; i++) { + this.set(i, index, array[i]); } - return idx; + return this; } - diag() { - let min = Math.min(this.rows, this.columns); - let diag = []; + swapColumns(column1, column2) { + checkColumnIndex(this, column1); + checkColumnIndex(this, column2); - for (let i = 0; i < min; i++) { - diag.push(this.get(i, i)); + for (let i = 0; i < this.rows; i++) { + let temp = this.get(i, column1); + this.set(i, column1, this.get(i, column2)); + this.set(i, column2, temp); } - return diag; + return this; } - norm() { - let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'frobenius'; - let result = 0; + addRowVector(vector) { + vector = checkRowVector(this, vector); - if (type === 'max') { - return this.max(); - } else if (type === 'frobenius') { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - result = result + this.get(i, j) * this.get(i, j); - } + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + vector[j]); } - - return Math.sqrt(result); - } else { - throw new RangeError("unknown norm type: ".concat(type)); } + + return this; } - cumulativeSum() { - let sum = 0; + subRowVector(vector) { + vector = checkRowVector(this, vector); for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { - sum += this.get(i, j); - this.set(i, j, sum); + this.set(i, j, this.get(i, j) - vector[j]); } } return this; } - dot(vector2) { - if (AbstractMatrix.isMatrix(vector2)) vector2 = vector2.to1DArray(); - let vector1 = this.to1DArray(); + mulRowVector(vector) { + vector = checkRowVector(this, vector); - if (vector1.length !== vector2.length) { - throw new RangeError('vectors do not have the same size'); + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * vector[j]); + } } - let dot = 0; + return this; + } - for (let i = 0; i < vector1.length; i++) { - dot += vector1[i] * vector2[i]; + divRowVector(vector) { + vector = checkRowVector(this, vector); + + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) / vector[j]); + } } - return dot; + return this; } - mmul(other) { - other = Matrix.checkMatrix(other); - let m = this.rows; - let n = this.columns; - let p = other.columns; - let result = new Matrix(m, p); - let Bcolj = new Float64Array(n); + addColumnVector(vector) { + vector = checkColumnVector(this, vector); - for (let j = 0; j < p; j++) { - for (let k = 0; k < n; k++) { - Bcolj[k] = other.get(k, j); + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + vector[i]); } + } - for (let i = 0; i < m; i++) { - let s = 0; + return this; + } - for (let k = 0; k < n; k++) { - s += this.get(i, k) * Bcolj[k]; - } + subColumnVector(vector) { + vector = checkColumnVector(this, vector); - result.set(i, j, s); + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - vector[i]); } } - return result; + return this; } - strassen2x2(other) { - other = Matrix.checkMatrix(other); - let result = new Matrix(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. + mulColumnVector(vector) { + vector = checkColumnVector(this, vector); - 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. + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * vector[i]); + } + } - 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; + return this; } - strassen3x3(other) { - other = Matrix.checkMatrix(other); - let result = new Matrix(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; - } + divColumnVector(vector) { + vector = checkColumnVector(this, vector); - mmulStrassen(y) { - y = Matrix.checkMatrix(y); - let x = this.clone(); - let r1 = x.rows; - let c1 = x.columns; - let r2 = y.rows; - let c2 = y.columns; + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) / vector[i]); + } + } - 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. + return this; + } + mulRow(index, value) { + checkRowIndex(this, index); - function embed(mat, rows, cols) { - let r = mat.rows; - let c = mat.columns; + for (let i = 0; i < this.columns; i++) { + this.set(index, i, this.get(index, i) * value); + } - if (r === rows && c === cols) { - return mat; - } else { - let resultat = AbstractMatrix.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. + return this; + } + mulColumn(index, value) { + checkColumnIndex(this, index); - let r = Math.max(r1, r2); - let c = Math.max(c1, c2); - x = embed(x, r, c); - y = embed(y, r, c); // Our recursive multiplication function. + for (let i = 0; i < this.rows; i++) { + this.set(i, index, this.get(i, index) * value); + } - 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. + return this; + } + max() { + let v = this.get(0, 0); - 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 (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + if (this.get(i, j) > v) { + v = this.get(i, j); + } } + } - let halfRows = parseInt(a.rows / 2, 10); - let halfCols = parseInt(a.columns / 2, 10); // Subdivide input matrices. - - let a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1); - let b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1); - let a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1); - let b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1); - let a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1); - let b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1); - let a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1); - let b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1); // Compute intermediate values. - - let m1 = blockMult(AbstractMatrix.add(a11, a22), AbstractMatrix.add(b11, b22), halfRows, halfCols); - let m2 = blockMult(AbstractMatrix.add(a21, a22), b11, halfRows, halfCols); - let m3 = blockMult(a11, AbstractMatrix.sub(b12, b22), halfRows, halfCols); - let m4 = blockMult(a22, AbstractMatrix.sub(b21, b11), halfRows, halfCols); - let m5 = blockMult(AbstractMatrix.add(a11, a12), b22, halfRows, halfCols); - let m6 = blockMult(AbstractMatrix.sub(a21, a11), AbstractMatrix.add(b11, b12), halfRows, halfCols); - let m7 = blockMult(AbstractMatrix.sub(a12, a22), AbstractMatrix.add(b21, b22), halfRows, halfCols); // Combine intermediate values into the output. + return v; + } - let c11 = AbstractMatrix.add(m1, m4); - c11.sub(m5); - c11.add(m7); - let c12 = AbstractMatrix.add(m3, m5); - let c21 = AbstractMatrix.add(m2, m4); - let c22 = AbstractMatrix.sub(m1, m2); - c22.add(m3); - c22.add(m6); // Crop output to the desired size (undo dynamic padding). + maxIndex() { + let v = this.get(0, 0); + let idx = [0, 0]; - let resultat = AbstractMatrix.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 (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + if (this.get(i, j) > v) { + v = this.get(i, j); + idx[0] = i; + idx[1] = j; + } + } } - return blockMult(x, y, r, c); + return idx; } - scaleRows() { - let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + min() { + let v = this.get(0, 0); - if (typeof options !== 'object') { - throw new TypeError('options must be an object'); + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + if (this.get(i, j) < v) { + v = this.get(i, j); + } + } } - const { - min = 0, - max = 1 - } = options; - if (!Number.isFinite(min)) throw new TypeError('min must be a number'); - if (!Number.isFinite(max)) throw new TypeError('max must be a number'); - if (min >= max) throw new RangeError('min must be smaller than max'); - let newMatrix = new Matrix(this.rows, this.columns); - - for (let i = 0; i < this.rows; i++) { - const row = this.getRow(i); - rescale(row, { - min, - max, - output: row - }); - newMatrix.setRow(i, row); - } - - return newMatrix; - } - - scaleColumns() { - let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - if (typeof options !== 'object') { - throw new TypeError('options must be an object'); - } - - const { - min = 0, - max = 1 - } = options; - if (!Number.isFinite(min)) throw new TypeError('min must be a number'); - if (!Number.isFinite(max)) throw new TypeError('max must be a number'); - if (min >= max) throw new RangeError('min must be smaller than max'); - let newMatrix = new Matrix(this.rows, this.columns); - - for (let i = 0; i < this.columns; i++) { - const column = this.getColumn(i); - rescale(column, { - min: min, - max: max, - output: column - }); - newMatrix.setColumn(i, column); - } - - return newMatrix; + return v; } - flipRows() { - const middle = Math.ceil(this.columns / 2); + minIndex() { + let v = this.get(0, 0); + let idx = [0, 0]; for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < middle; j++) { - let first = this.get(i, j); - let last = this.get(i, this.columns - 1 - j); - this.set(i, j, last); - this.set(i, this.columns - 1 - j, first); + for (let j = 0; j < this.columns; j++) { + if (this.get(i, j) < v) { + v = this.get(i, j); + idx[0] = i; + idx[1] = j; + } } } - return this; + return idx; } - flipColumns() { - const middle = Math.ceil(this.rows / 2); + maxRow(row) { + checkRowIndex(this, row); + let v = this.get(row, 0); - for (let j = 0; j < this.columns; j++) { - for (let i = 0; i < middle; i++) { - let first = this.get(i, j); - let last = this.get(this.rows - 1 - i, j); - this.set(i, j, last); - this.set(this.rows - 1 - i, j, first); + for (let i = 1; i < this.columns; i++) { + if (this.get(row, i) > v) { + v = this.get(row, i); } } - return this; + return v; } - kroneckerProduct(other) { - other = Matrix.checkMatrix(other); - let m = this.rows; - let n = this.columns; - let p = other.rows; - let q = other.columns; - let result = new Matrix(m * p, n * q); + maxRowIndex(row) { + checkRowIndex(this, row); + let v = this.get(row, 0); + let idx = [row, 0]; - for (let i = 0; i < m; i++) { - for (let j = 0; j < n; j++) { - for (let k = 0; k < p; k++) { - for (let l = 0; l < q; l++) { - result.set(p * i + k, q * j + l, this.get(i, j) * other.get(k, l)); - } - } + for (let i = 1; i < this.columns; i++) { + if (this.get(row, i) > v) { + v = this.get(row, i); + idx[1] = i; } } - return result; + return idx; } - transpose() { - let result = new Matrix(this.columns, this.rows); + minRow(row) { + checkRowIndex(this, row); + let v = this.get(row, 0); - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - result.set(j, i, this.get(i, j)); + for (let i = 1; i < this.columns; i++) { + if (this.get(row, i) < v) { + v = this.get(row, i); } } - return result; + return v; } - sortRows() { - let compareFunction = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : compareNumbers; + minRowIndex(row) { + checkRowIndex(this, row); + let v = this.get(row, 0); + let idx = [row, 0]; - for (let i = 0; i < this.rows; i++) { - this.setRow(i, this.getRow(i).sort(compareFunction)); + for (let i = 1; i < this.columns; i++) { + if (this.get(row, i) < v) { + v = this.get(row, i); + idx[1] = i; + } } - return this; + return idx; } - sortColumns() { - let compareFunction = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : compareNumbers; + maxColumn(column) { + checkColumnIndex(this, column); + let v = this.get(0, column); - for (let i = 0; i < this.columns; i++) { - this.setColumn(i, this.getColumn(i).sort(compareFunction)); + for (let i = 1; i < this.rows; i++) { + if (this.get(i, column) > v) { + v = this.get(i, column); + } } - return this; + return v; } - subMatrix(startRow, endRow, startColumn, endColumn) { - checkRange(this, startRow, endRow, startColumn, endColumn); - let newMatrix = new Matrix(endRow - startRow + 1, endColumn - startColumn + 1); + maxColumnIndex(column) { + checkColumnIndex(this, column); + let v = this.get(0, column); + let idx = [0, column]; - for (let i = startRow; i <= endRow; i++) { - for (let j = startColumn; j <= endColumn; j++) { - newMatrix.set(i - startRow, j - startColumn, this.get(i, j)); + for (let i = 1; i < this.rows; i++) { + if (this.get(i, column) > v) { + v = this.get(i, column); + idx[0] = i; } } - return newMatrix; + return idx; } - subMatrixRow(indices, startColumn, endColumn) { - if (startColumn === undefined) startColumn = 0; - if (endColumn === undefined) endColumn = this.columns - 1; + minColumn(column) { + checkColumnIndex(this, column); + let v = this.get(0, column); - if (startColumn > endColumn || startColumn < 0 || startColumn >= this.columns || endColumn < 0 || endColumn >= this.columns) { - throw new RangeError('Argument out of range'); + for (let i = 1; i < this.rows; i++) { + if (this.get(i, column) < v) { + v = this.get(i, column); + } } - let newMatrix = new Matrix(indices.length, endColumn - startColumn + 1); + return v; + } - for (let i = 0; i < indices.length; i++) { - for (let j = startColumn; j <= endColumn; j++) { - if (indices[i] < 0 || indices[i] >= this.rows) { - throw new RangeError("Row index out of range: ".concat(indices[i])); - } + minColumnIndex(column) { + checkColumnIndex(this, column); + let v = this.get(0, column); + let idx = [0, column]; - newMatrix.set(i, j - startColumn, this.get(indices[i], j)); + for (let i = 1; i < this.rows; i++) { + if (this.get(i, column) < v) { + v = this.get(i, column); + idx[0] = i; } } - return newMatrix; + return idx; } - subMatrixColumn(indices, startRow, endRow) { - if (startRow === undefined) startRow = 0; - if (endRow === undefined) endRow = this.rows - 1; + diag() { + let min = Math.min(this.rows, this.columns); + let diag = []; - if (startRow > endRow || startRow < 0 || startRow >= this.rows || endRow < 0 || endRow >= this.rows) { - throw new RangeError('Argument out of range'); + for (let i = 0; i < min; i++) { + diag.push(this.get(i, i)); } - let newMatrix = new Matrix(endRow - startRow + 1, indices.length); + return diag; + } - for (let i = 0; i < indices.length; i++) { - for (let j = startRow; j <= endRow; j++) { - if (indices[i] < 0 || indices[i] >= this.columns) { - throw new RangeError("Column index out of range: ".concat(indices[i])); - } + norm(type = 'frobenius') { + let result = 0; - newMatrix.set(j - startRow, i, this.get(j, indices[i])); + if (type === 'max') { + return this.max(); + } else if (type === 'frobenius') { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + result = result + this.get(i, j) * this.get(i, j); + } } - } - return newMatrix; + return Math.sqrt(result); + } else { + throw new RangeError(`unknown norm type: ${type}`); + } } - setSubMatrix(matrix, startRow, startColumn) { - matrix = Matrix.checkMatrix(matrix); - let endRow = startRow + matrix.rows - 1; - let endColumn = startColumn + matrix.columns - 1; - checkRange(this, startRow, endRow, startColumn, endColumn); + cumulativeSum() { + let sum = 0; - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - this.set(startRow + i, startColumn + j, matrix.get(i, j)); + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + sum += this.get(i, j); + this.set(i, j, sum); } } return this; } - selection(rowIndices, columnIndices) { - let indices = checkIndices(this, rowIndices, columnIndices); - let newMatrix = new Matrix(rowIndices.length, columnIndices.length); + dot(vector2) { + if (AbstractMatrix.isMatrix(vector2)) vector2 = vector2.to1DArray(); + let vector1 = this.to1DArray(); - for (let i = 0; i < indices.row.length; i++) { - let rowIndex = indices.row[i]; + if (vector1.length !== vector2.length) { + throw new RangeError('vectors do not have the same size'); + } - for (let j = 0; j < indices.column.length; j++) { - let columnIndex = indices.column[j]; - newMatrix.set(i, j, this.get(rowIndex, columnIndex)); - } + let dot = 0; + + for (let i = 0; i < vector1.length; i++) { + dot += vector1[i] * vector2[i]; } - return newMatrix; + return dot; } - trace() { - let min = Math.min(this.rows, this.columns); - let trace = 0; + mmul(other) { + other = Matrix.checkMatrix(other); + let m = this.rows; + let n = this.columns; + let p = other.columns; + let result = new Matrix(m, p); + let Bcolj = new Float64Array(n); - for (let i = 0; i < min; i++) { - trace += this.get(i, i); - } + for (let j = 0; j < p; j++) { + for (let k = 0; k < n; k++) { + Bcolj[k] = other.get(k, j); + } - return trace; - } + for (let i = 0; i < m; i++) { + let s = 0; - clone() { - let newMatrix = new Matrix(this.rows, this.columns); + for (let k = 0; k < n; k++) { + s += this.get(i, k) * Bcolj[k]; + } - for (let row = 0; row < this.rows; row++) { - for (let column = 0; column < this.columns; column++) { - newMatrix.set(row, column, this.get(row, column)); + result.set(i, j, s); } } - return newMatrix; + return result; } - sum(by) { - switch (by) { - case 'row': - return sumByRow(this); + strassen2x2(other) { + other = Matrix.checkMatrix(other); + let result = new Matrix(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. - case 'column': - return sumByColumn(this); + 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. - case undefined: - return sumAll(this); + 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; + } - default: - throw new Error("invalid option: ".concat(by)); - } + strassen3x3(other) { + other = Matrix.checkMatrix(other); + let result = new Matrix(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; } - product(by) { - switch (by) { - case 'row': - return productByRow(this); + mmulStrassen(y) { + y = Matrix.checkMatrix(y); + let x = this.clone(); + let r1 = x.rows; + let c1 = x.columns; + let r2 = y.rows; + let c2 = y.columns; - case 'column': - return productByColumn(this); + if (c1 !== r2) { + // eslint-disable-next-line no-console + console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${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. - case undefined: - return productAll(this); - default: - throw new Error("invalid option: ".concat(by)); - } - } + function embed(mat, rows, cols) { + let r = mat.rows; + let c = mat.columns; - mean(by) { - const sum = this.sum(by); + if (r === rows && c === cols) { + return mat; + } else { + let resultat = AbstractMatrix.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. - switch (by) { - case 'row': - { - for (let i = 0; i < this.rows; i++) { - sum[i] /= this.columns; - } - return sum; - } + let r = Math.max(r1, r2); + let c = Math.max(c1, c2); + x = embed(x, r, c); + y = embed(y, r, c); // Our recursive multiplication function. - case 'column': - { - for (let i = 0; i < this.columns; i++) { - sum[i] /= this.rows; - } + 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. - return sum; - } - case undefined: - return sum / this.size; + 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); + } - default: - throw new Error("invalid option: ".concat(by)); - } - } + let halfRows = parseInt(a.rows / 2, 10); + let halfCols = parseInt(a.columns / 2, 10); // Subdivide input matrices. - variance(by) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + let a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1); + let b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1); + let a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1); + let b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1); + let a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1); + let b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1); + let a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1); + let b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1); // Compute intermediate values. - if (typeof by === 'object') { - options = by; - by = undefined; + let m1 = blockMult(AbstractMatrix.add(a11, a22), AbstractMatrix.add(b11, b22), halfRows, halfCols); + let m2 = blockMult(AbstractMatrix.add(a21, a22), b11, halfRows, halfCols); + let m3 = blockMult(a11, AbstractMatrix.sub(b12, b22), halfRows, halfCols); + let m4 = blockMult(a22, AbstractMatrix.sub(b21, b11), halfRows, halfCols); + let m5 = blockMult(AbstractMatrix.add(a11, a12), b22, halfRows, halfCols); + let m6 = blockMult(AbstractMatrix.sub(a21, a11), AbstractMatrix.add(b11, b12), halfRows, halfCols); + let m7 = blockMult(AbstractMatrix.sub(a12, a22), AbstractMatrix.add(b21, b22), halfRows, halfCols); // Combine intermediate values into the output. + + let c11 = AbstractMatrix.add(m1, m4); + c11.sub(m5); + c11.add(m7); + let c12 = AbstractMatrix.add(m3, m5); + let c21 = AbstractMatrix.add(m2, m4); + let c22 = AbstractMatrix.sub(m1, m2); + c22.add(m3); + c22.add(m6); // Crop output to the desired size (undo dynamic padding). + + let resultat = AbstractMatrix.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); + } + + scaleRows(options = {}) { if (typeof options !== 'object') { throw new TypeError('options must be an object'); } const { - unbiased = true, - mean = this.mean(by) + min = 0, + max = 1 } = options; + if (!Number.isFinite(min)) throw new TypeError('min must be a number'); + if (!Number.isFinite(max)) throw new TypeError('max must be a number'); + if (min >= max) throw new RangeError('min must be smaller than max'); + let newMatrix = new Matrix(this.rows, this.columns); - if (typeof unbiased !== 'boolean') { - throw new TypeError('unbiased must be a boolean'); + for (let i = 0; i < this.rows; i++) { + const row = this.getRow(i); + rescale(row, { + min, + max, + output: row + }); + newMatrix.setRow(i, row); } - switch (by) { - case 'row': - { - if (!Array.isArray(mean)) { - throw new TypeError('mean must be an array'); - } + return newMatrix; + } - return varianceByRow(this, unbiased, mean); - } + scaleColumns(options = {}) { + if (typeof options !== 'object') { + throw new TypeError('options must be an object'); + } - case 'column': - { - if (!Array.isArray(mean)) { - throw new TypeError('mean must be an array'); - } + const { + min = 0, + max = 1 + } = options; + if (!Number.isFinite(min)) throw new TypeError('min must be a number'); + if (!Number.isFinite(max)) throw new TypeError('max must be a number'); + if (min >= max) throw new RangeError('min must be smaller than max'); + let newMatrix = new Matrix(this.rows, this.columns); - return varianceByColumn(this, unbiased, mean); - } + for (let i = 0; i < this.columns; i++) { + const column = this.getColumn(i); + rescale(column, { + min: min, + max: max, + output: column + }); + newMatrix.setColumn(i, column); + } - case undefined: - { - if (typeof mean !== 'number') { - throw new TypeError('mean must be a number'); - } + return newMatrix; + } - return varianceAll(this, unbiased, mean); - } + flipRows() { + const middle = Math.ceil(this.columns / 2); - default: - throw new Error("invalid option: ".concat(by)); + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < middle; j++) { + let first = this.get(i, j); + let last = this.get(i, this.columns - 1 - j); + this.set(i, j, last); + this.set(i, this.columns - 1 - j, first); + } } + + return this; } - standardDeviation(by, options) { - if (typeof by === 'object') { - options = by; - by = undefined; + flipColumns() { + const middle = Math.ceil(this.rows / 2); + + for (let j = 0; j < this.columns; j++) { + for (let i = 0; i < middle; i++) { + let first = this.get(i, j); + let last = this.get(this.rows - 1 - i, j); + this.set(i, j, last); + this.set(this.rows - 1 - i, j, first); + } } - const variance = this.variance(by, options); + return this; + } - if (by === undefined) { - return Math.sqrt(variance); - } else { - for (let i = 0; i < variance.length; i++) { - variance[i] = Math.sqrt(variance[i]); - } + kroneckerProduct(other) { + other = Matrix.checkMatrix(other); + let m = this.rows; + let n = this.columns; + let p = other.rows; + let q = other.columns; + let result = new Matrix(m * p, n * q); - return variance; + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + for (let k = 0; k < p; k++) { + for (let l = 0; l < q; l++) { + result.set(p * i + k, q * j + l, this.get(i, j) * other.get(k, l)); + } + } + } } + + return result; } - center(by) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + transpose() { + let result = new Matrix(this.columns, this.rows); - if (typeof by === 'object') { - options = by; - by = undefined; + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + result.set(j, i, this.get(i, j)); + } } - if (typeof options !== 'object') { - throw new TypeError('options must be an object'); + return result; + } + + sortRows(compareFunction = compareNumbers) { + for (let i = 0; i < this.rows; i++) { + this.setRow(i, this.getRow(i).sort(compareFunction)); } - const { - center = this.mean(by) - } = options; + return this; + } - switch (by) { - case 'row': - { - if (!Array.isArray(center)) { - throw new TypeError('center must be an array'); - } + sortColumns(compareFunction = compareNumbers) { + for (let i = 0; i < this.columns; i++) { + this.setColumn(i, this.getColumn(i).sort(compareFunction)); + } - centerByRow(this, center); - return this; - } + return this; + } - case 'column': - { - if (!Array.isArray(center)) { - throw new TypeError('center must be an array'); - } + subMatrix(startRow, endRow, startColumn, endColumn) { + checkRange(this, startRow, endRow, startColumn, endColumn); + let newMatrix = new Matrix(endRow - startRow + 1, endColumn - startColumn + 1); - centerByColumn(this, center); - return this; - } + for (let i = startRow; i <= endRow; i++) { + for (let j = startColumn; j <= endColumn; j++) { + newMatrix.set(i - startRow, j - startColumn, this.get(i, j)); + } + } - case undefined: - { - if (typeof center !== 'number') { - throw new TypeError('center must be a number'); - } + return newMatrix; + } - centerAll(this, center); - return this; - } + subMatrixRow(indices, startColumn, endColumn) { + if (startColumn === undefined) startColumn = 0; + if (endColumn === undefined) endColumn = this.columns - 1; - default: - throw new Error("invalid option: ".concat(by)); + if (startColumn > endColumn || startColumn < 0 || startColumn >= this.columns || endColumn < 0 || endColumn >= this.columns) { + throw new RangeError('Argument out of range'); } - } - scale(by) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + let newMatrix = new Matrix(indices.length, endColumn - startColumn + 1); - if (typeof by === 'object') { - options = by; - by = undefined; - } + for (let i = 0; i < indices.length; i++) { + for (let j = startColumn; j <= endColumn; j++) { + if (indices[i] < 0 || indices[i] >= this.rows) { + throw new RangeError(`Row index out of range: ${indices[i]}`); + } - if (typeof options !== 'object') { - throw new TypeError('options must be an object'); + newMatrix.set(i, j - startColumn, this.get(indices[i], j)); + } } - let scale = options.scale; + return newMatrix; + } - switch (by) { - case 'row': - { - if (scale === undefined) { - scale = getScaleByRow(this); - } else if (!Array.isArray(scale)) { - throw new TypeError('scale must be an array'); - } + subMatrixColumn(indices, startRow, endRow) { + if (startRow === undefined) startRow = 0; + if (endRow === undefined) endRow = this.rows - 1; - scaleByRow(this, scale); - return this; - } + if (startRow > endRow || startRow < 0 || startRow >= this.rows || endRow < 0 || endRow >= this.rows) { + throw new RangeError('Argument out of range'); + } - case 'column': - { - if (scale === undefined) { - scale = getScaleByColumn(this); - } else if (!Array.isArray(scale)) { - throw new TypeError('scale must be an array'); - } + let newMatrix = new Matrix(endRow - startRow + 1, indices.length); - scaleByColumn(this, scale); - return this; + for (let i = 0; i < indices.length; i++) { + for (let j = startRow; j <= endRow; j++) { + if (indices[i] < 0 || indices[i] >= this.columns) { + throw new RangeError(`Column index out of range: ${indices[i]}`); } - case undefined: - { - if (scale === undefined) { - scale = getScaleAll(this); - } else if (typeof scale !== 'number') { - throw new TypeError('scale must be a number'); - } + newMatrix.set(j - startRow, i, this.get(j, indices[i])); + } + } - scaleAll(this, scale); - return this; - } + return newMatrix; + } - default: - throw new Error("invalid option: ".concat(by)); + setSubMatrix(matrix, startRow, startColumn) { + matrix = Matrix.checkMatrix(matrix); + let endRow = startRow + matrix.rows - 1; + let endColumn = startColumn + matrix.columns - 1; + checkRange(this, startRow, endRow, startColumn, endColumn); + + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + this.set(startRow + i, startColumn + j, matrix.get(i, j)); + } } + + return this; } - } - AbstractMatrix.prototype.klass = 'Matrix'; - - if (typeof Symbol !== 'undefined') { - AbstractMatrix.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspectMatrix; - } - - function compareNumbers(a, b) { - return a - b; - } // Synonyms + selection(rowIndices, columnIndices) { + let indices = checkIndices(this, rowIndices, columnIndices); + let newMatrix = new Matrix(rowIndices.length, columnIndices.length); + for (let i = 0; i < indices.row.length; i++) { + let rowIndex = indices.row[i]; - AbstractMatrix.random = AbstractMatrix.rand; - AbstractMatrix.randomInt = AbstractMatrix.randInt; - AbstractMatrix.diagonal = AbstractMatrix.diag; - AbstractMatrix.prototype.diagonal = AbstractMatrix.prototype.diag; - AbstractMatrix.identity = AbstractMatrix.eye; - AbstractMatrix.prototype.negate = AbstractMatrix.prototype.neg; - AbstractMatrix.prototype.tensorProduct = AbstractMatrix.prototype.kroneckerProduct; - class Matrix extends AbstractMatrix { - constructor(nRows, nColumns) { - super(); + for (let j = 0; j < indices.column.length; j++) { + let columnIndex = indices.column[j]; + newMatrix.set(i, j, this.get(rowIndex, columnIndex)); + } + } - if (Matrix.isMatrix(nRows)) { - return nRows.clone(); - } else if (Number.isInteger(nRows) && nRows > 0) { - // Create an empty matrix - this.data = []; + return newMatrix; + } - if (Number.isInteger(nColumns) && nColumns > 0) { - for (let i = 0; i < nRows; i++) { - this.data.push(new Float64Array(nColumns)); - } - } else { - throw new TypeError('nColumns must be a positive integer'); - } - } else if (Array.isArray(nRows)) { - // Copy the values from the 2D array - const arrayData = nRows; - nRows = arrayData.length; - nColumns = arrayData[0].length; + trace() { + let min = Math.min(this.rows, this.columns); + let trace = 0; - if (typeof nColumns !== 'number' || nColumns === 0) { - throw new TypeError('Data must be a 2D array with at least one element'); - } + for (let i = 0; i < min; i++) { + trace += this.get(i, i); + } - this.data = []; + return trace; + } - for (let i = 0; i < nRows; i++) { - if (arrayData[i].length !== nColumns) { - throw new RangeError('Inconsistent array dimensions'); - } + clone() { + let newMatrix = new Matrix(this.rows, this.columns); - this.data.push(Float64Array.from(arrayData[i])); + for (let row = 0; row < this.rows; row++) { + for (let column = 0; column < this.columns; column++) { + newMatrix.set(row, column, this.get(row, column)); } - } else { - throw new TypeError('First argument must be a positive number or an array'); } - this.rows = nRows; - this.columns = nColumns; - return this; + return newMatrix; } - set(rowIndex, columnIndex, value) { - this.data[rowIndex][columnIndex] = value; - return this; - } + sum(by) { + switch (by) { + case 'row': + return sumByRow(this); - get(rowIndex, columnIndex) { - return this.data[rowIndex][columnIndex]; - } + case 'column': + return sumByColumn(this); - removeRow(index) { - checkRowIndex(this, index); + case undefined: + return sumAll(this); - if (this.rows === 1) { - throw new RangeError('A matrix cannot have less than one row'); + default: + throw new Error(`invalid option: ${by}`); } - - this.data.splice(index, 1); - this.rows -= 1; - return this; } - addRow(index, array) { - if (array === undefined) { - array = index; - index = this.rows; - } + product(by) { + switch (by) { + case 'row': + return productByRow(this); - checkRowIndex(this, index, true); - array = Float64Array.from(checkRowVector(this, array)); - this.data.splice(index, 0, array); - this.rows += 1; - return this; - } + case 'column': + return productByColumn(this); - removeColumn(index) { - checkColumnIndex(this, index); + case undefined: + return productAll(this); - if (this.columns === 1) { - throw new RangeError('A matrix cannot have less than one column'); + default: + throw new Error(`invalid option: ${by}`); } + } - for (let i = 0; i < this.rows; i++) { - const newRow = new Float64Array(this.columns - 1); + mean(by) { + const sum = this.sum(by); - for (let j = 0; j < index; j++) { - newRow[j] = this.data[i][j]; - } + switch (by) { + case 'row': + { + for (let i = 0; i < this.rows; i++) { + sum[i] /= this.columns; + } - for (let j = index + 1; j < this.columns; j++) { - newRow[j - 1] = this.data[i][j]; - } + return sum; + } - this.data[i] = newRow; - } + case 'column': + { + for (let i = 0; i < this.columns; i++) { + sum[i] /= this.rows; + } - this.columns -= 1; - return this; - } + return sum; + } - addColumn(index, array) { - if (typeof array === 'undefined') { - array = index; - index = this.columns; + case undefined: + return sum / this.size; + + default: + throw new Error(`invalid option: ${by}`); } + } - checkColumnIndex(this, index, true); - array = checkColumnVector(this, array); + variance(by, options = {}) { + if (typeof by === 'object') { + options = by; + by = undefined; + } - for (let i = 0; i < this.rows; i++) { - const newRow = new Float64Array(this.columns + 1); - let j = 0; + if (typeof options !== 'object') { + throw new TypeError('options must be an object'); + } - for (; j < index; j++) { - newRow[j] = this.data[i][j]; - } + const { + unbiased = true, + mean = this.mean(by) + } = options; - newRow[j++] = array[i]; + if (typeof unbiased !== 'boolean') { + throw new TypeError('unbiased must be a boolean'); + } - for (; j < this.columns + 1; j++) { - newRow[j] = this.data[i][j - 1]; - } + switch (by) { + case 'row': + { + if (!Array.isArray(mean)) { + throw new TypeError('mean must be an array'); + } - this.data[i] = newRow; - } + return varianceByRow(this, unbiased, mean); + } - this.columns += 1; - return this; - } + case 'column': + { + if (!Array.isArray(mean)) { + throw new TypeError('mean must be an array'); + } - } - installMathOperations(AbstractMatrix, Matrix); + return varianceByColumn(this, unbiased, mean); + } - class BaseView extends AbstractMatrix { - constructor(matrix, rows, columns) { - super(); - this.matrix = matrix; - this.rows = rows; - this.columns = columns; - } + case undefined: + { + if (typeof mean !== 'number') { + throw new TypeError('mean must be a number'); + } - } + return varianceAll(this, unbiased, mean); + } - class MatrixColumnView extends BaseView { - constructor(matrix, column) { - checkColumnIndex(matrix, column); - super(matrix, matrix.rows, 1); - this.column = column; + default: + throw new Error(`invalid option: ${by}`); + } } - set(rowIndex, columnIndex, value) { - this.matrix.set(rowIndex, this.column, value); - return this; - } + standardDeviation(by, options) { + if (typeof by === 'object') { + options = by; + by = undefined; + } - get(rowIndex) { - return this.matrix.get(rowIndex, this.column); - } + const variance = this.variance(by, options); - } + if (by === undefined) { + return Math.sqrt(variance); + } else { + for (let i = 0; i < variance.length; i++) { + variance[i] = Math.sqrt(variance[i]); + } - class MatrixColumnSelectionView extends BaseView { - constructor(matrix, columnIndices) { - columnIndices = checkColumnIndices(matrix, columnIndices); - super(matrix, matrix.rows, columnIndices.length); - this.columnIndices = columnIndices; + return variance; + } } - set(rowIndex, columnIndex, value) { - this.matrix.set(rowIndex, this.columnIndices[columnIndex], value); - return this; - } + center(by, options = {}) { + if (typeof by === 'object') { + options = by; + by = undefined; + } - get(rowIndex, columnIndex) { - return this.matrix.get(rowIndex, this.columnIndices[columnIndex]); - } + if (typeof options !== 'object') { + throw new TypeError('options must be an object'); + } - } + const { + center = this.mean(by) + } = options; - class MatrixFlipColumnView extends BaseView { - constructor(matrix) { - super(matrix, matrix.rows, matrix.columns); - } + switch (by) { + case 'row': + { + if (!Array.isArray(center)) { + throw new TypeError('center must be an array'); + } - set(rowIndex, columnIndex, value) { - this.matrix.set(rowIndex, this.columns - columnIndex - 1, value); - return this; - } + centerByRow(this, center); + return this; + } - get(rowIndex, columnIndex) { - return this.matrix.get(rowIndex, this.columns - columnIndex - 1); - } + case 'column': + { + if (!Array.isArray(center)) { + throw new TypeError('center must be an array'); + } - } + centerByColumn(this, center); + return this; + } - class MatrixFlipRowView extends BaseView { - constructor(matrix) { - super(matrix, matrix.rows, matrix.columns); - } + case undefined: + { + if (typeof center !== 'number') { + throw new TypeError('center must be a number'); + } - set(rowIndex, columnIndex, value) { - this.matrix.set(this.rows - rowIndex - 1, columnIndex, value); - return this; - } + centerAll(this, center); + return this; + } - get(rowIndex, columnIndex) { - return this.matrix.get(this.rows - rowIndex - 1, columnIndex); + default: + throw new Error(`invalid option: ${by}`); + } } - } - - class MatrixRowView extends BaseView { - constructor(matrix, row) { - checkRowIndex(matrix, row); - super(matrix, 1, matrix.columns); - this.row = row; - } + scale(by, options = {}) { + if (typeof by === 'object') { + options = by; + by = undefined; + } - set(rowIndex, columnIndex, value) { - this.matrix.set(this.row, columnIndex, value); - return this; - } + if (typeof options !== 'object') { + throw new TypeError('options must be an object'); + } - get(rowIndex, columnIndex) { - return this.matrix.get(this.row, columnIndex); - } + let scale = options.scale; - } + switch (by) { + case 'row': + { + if (scale === undefined) { + scale = getScaleByRow(this); + } else if (!Array.isArray(scale)) { + throw new TypeError('scale must be an array'); + } - class MatrixRowSelectionView extends BaseView { - constructor(matrix, rowIndices) { - rowIndices = checkRowIndices(matrix, rowIndices); - super(matrix, rowIndices.length, matrix.columns); - this.rowIndices = rowIndices; - } + scaleByRow(this, scale); + return this; + } - set(rowIndex, columnIndex, value) { - this.matrix.set(this.rowIndices[rowIndex], columnIndex, value); - return this; - } + case 'column': + { + if (scale === undefined) { + scale = getScaleByColumn(this); + } else if (!Array.isArray(scale)) { + throw new TypeError('scale must be an array'); + } - get(rowIndex, columnIndex) { - return this.matrix.get(this.rowIndices[rowIndex], columnIndex); - } + scaleByColumn(this, scale); + return this; + } - } + case undefined: + { + if (scale === undefined) { + scale = getScaleAll(this); + } else if (typeof scale !== 'number') { + throw new TypeError('scale must be a number'); + } - class MatrixSelectionView extends BaseView { - constructor(matrix, rowIndices, columnIndices) { - let indices = checkIndices(matrix, rowIndices, columnIndices); - super(matrix, indices.row.length, indices.column.length); - this.rowIndices = indices.row; - this.columnIndices = indices.column; - } + scaleAll(this, scale); + return this; + } - set(rowIndex, columnIndex, value) { - this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value); - return this; + default: + throw new Error(`invalid option: ${by}`); + } } - get(rowIndex, columnIndex) { - return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]); + toString(options) { + return inspectMatrixWithOptions(this, options); } } + AbstractMatrix.prototype.klass = 'Matrix'; - class MatrixSubView extends 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; - } + if (typeof Symbol !== 'undefined') { + AbstractMatrix.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspectMatrix; + } - set(rowIndex, columnIndex, value) { - this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex, value); - return this; - } + function compareNumbers(a, b) { + return a - b; + } // Synonyms - get(rowIndex, columnIndex) { - return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex); - } - } + AbstractMatrix.random = AbstractMatrix.rand; + AbstractMatrix.randomInt = AbstractMatrix.randInt; + AbstractMatrix.diagonal = AbstractMatrix.diag; + AbstractMatrix.prototype.diagonal = AbstractMatrix.prototype.diag; + AbstractMatrix.identity = AbstractMatrix.eye; + AbstractMatrix.prototype.negate = AbstractMatrix.prototype.neg; + AbstractMatrix.prototype.tensorProduct = AbstractMatrix.prototype.kroneckerProduct; + class Matrix extends AbstractMatrix { + constructor(nRows, nColumns) { + super(); - class MatrixTransposeView extends BaseView { - constructor(matrix) { - super(matrix, matrix.columns, matrix.rows); - } + if (Matrix.isMatrix(nRows)) { + return nRows.clone(); + } else if (Number.isInteger(nRows) && nRows > 0) { + // Create an empty matrix + this.data = []; - set(rowIndex, columnIndex, value) { - this.matrix.set(columnIndex, rowIndex, value); - return this; - } + if (Number.isInteger(nColumns) && nColumns > 0) { + for (let i = 0; i < nRows; i++) { + this.data.push(new Float64Array(nColumns)); + } + } else { + throw new TypeError('nColumns must be a positive integer'); + } + } else if (Array.isArray(nRows)) { + // Copy the values from the 2D array + const arrayData = nRows; + nRows = arrayData.length; + nColumns = arrayData[0].length; - get(rowIndex, columnIndex) { - return this.matrix.get(columnIndex, rowIndex); - } + if (typeof nColumns !== 'number' || nColumns === 0) { + throw new TypeError('Data must be a 2D array with at least one element'); + } - } + this.data = []; - class WrapperMatrix1D extends AbstractMatrix { - constructor(data) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - const { - rows = 1 - } = options; + for (let i = 0; i < nRows; i++) { + if (arrayData[i].length !== nColumns) { + throw new RangeError('Inconsistent array dimensions'); + } - if (data.length % rows !== 0) { - throw new Error('the data length is not divisible by the number of rows'); + this.data.push(Float64Array.from(arrayData[i])); + } + } else { + throw new TypeError('First argument must be a positive number or an array'); } - super(); - this.rows = rows; - this.columns = data.length / rows; - this.data = data; + this.rows = nRows; + this.columns = nColumns; + return this; } set(rowIndex, columnIndex, value) { - let index = this._calculateIndex(rowIndex, columnIndex); - - this.data[index] = value; + this.data[rowIndex][columnIndex] = value; return this; } get(rowIndex, columnIndex) { - let index = this._calculateIndex(rowIndex, columnIndex); - - return this.data[index]; + return this.data[rowIndex][columnIndex]; } - _calculateIndex(row, column) { - return row * this.columns + column; - } + removeRow(index) { + checkRowIndex(this, index); - } + if (this.rows === 1) { + throw new RangeError('A matrix cannot have less than one row'); + } - class WrapperMatrix2D extends AbstractMatrix { - constructor(data) { - super(); - this.data = data; - this.rows = data.length; - this.columns = data[0].length; - } - - set(rowIndex, columnIndex, value) { - this.data[rowIndex][columnIndex] = value; + this.data.splice(index, 1); + this.rows -= 1; return this; } - get(rowIndex, columnIndex) { - return this.data[rowIndex][columnIndex]; - } - - } - - function wrap(array, options) { - if (Array.isArray(array)) { - if (array[0] && Array.isArray(array[0])) { - return new WrapperMatrix2D(array); - } else { - return new WrapperMatrix1D(array, options); + addRow(index, array) { + if (array === undefined) { + array = index; + index = this.rows; } - } else { - throw new Error('the argument is not an array'); + + checkRowIndex(this, index, true); + array = Float64Array.from(checkRowVector(this, array)); + this.data.splice(index, 0, array); + this.rows += 1; + return this; } - } - class LuDecomposition { - constructor(matrix) { - matrix = WrapperMatrix2D.checkMatrix(matrix); - let lu = matrix.clone(); - let rows = lu.rows; - let columns = lu.columns; - let pivotVector = new Float64Array(rows); - let pivotSign = 1; - let i, j, k, p, s, t, v; - let LUcolj, kmax; + removeColumn(index) { + checkColumnIndex(this, index); - for (i = 0; i < rows; i++) { - pivotVector[i] = i; + if (this.columns === 1) { + throw new RangeError('A matrix cannot have less than one column'); } - LUcolj = new Float64Array(rows); - - 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]); - } - - p = j; - - for (i = j + 1; i < rows; i++) { - if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) { - p = i; - } - } - - 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); - } + for (let i = 0; i < this.rows; i++) { + const newRow = new Float64Array(this.columns - 1); - v = pivotVector[p]; - pivotVector[p] = pivotVector[j]; - pivotVector[j] = v; - pivotSign = -pivotSign; + for (let j = 0; j < index; j++) { + newRow[j] = this.data[i][j]; } - 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)); - } + for (let j = index + 1; j < this.columns; j++) { + newRow[j - 1] = this.data[i][j]; } - } - - this.LU = lu; - this.pivotVector = pivotVector; - this.pivotSign = pivotSign; - } - isSingular() { - let data = this.LU; - let col = data.columns; - - for (let j = 0; j < col; j++) { - if (data.get(j, j) === 0) { - return true; - } + this.data[i] = newRow; } - return false; + this.columns -= 1; + return this; } - solve(value) { - value = Matrix.checkMatrix(value); - let lu = this.LU; - let rows = lu.rows; - - if (rows !== value.rows) { - throw new Error('Invalid matrix dimensions'); + addColumn(index, array) { + if (typeof array === 'undefined') { + array = index; + index = this.columns; } - if (this.isSingular()) { - throw new Error('LU matrix is singular'); - } + checkColumnIndex(this, index, true); + array = checkColumnVector(this, array); - let count = value.columns; - let X = value.subMatrixRow(this.pivotVector, 0, count - 1); - let columns = lu.columns; - let i, j, k; + for (let i = 0; i < this.rows; i++) { + const newRow = new Float64Array(this.columns + 1); + let j = 0; - for (k = 0; k < columns; k++) { - for (i = k + 1; i < columns; i++) { - for (j = 0; j < count; j++) { - X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k)); - } + for (; j < index; j++) { + newRow[j] = this.data[i][j]; } - } - for (k = columns - 1; k >= 0; k--) { - for (j = 0; j < count; j++) { - X.set(k, j, X.get(k, j) / lu.get(k, k)); - } + newRow[j++] = array[i]; - for (i = 0; i < k; i++) { - for (j = 0; j < count; j++) { - X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k)); - } + for (; j < this.columns + 1; j++) { + newRow[j] = this.data[i][j - 1]; } - } - - return X; - } - - get determinant() { - let data = this.LU; - - if (!data.isSquare()) { - throw new Error('Matrix must be square'); - } - - let determinant = this.pivotSign; - let col = data.columns; - for (let j = 0; j < col; j++) { - determinant *= data.get(j, j); + this.data[i] = newRow; } - return determinant; + this.columns += 1; + return this; } - get lowerTriangularMatrix() { - let data = this.LU; - let rows = data.rows; - let columns = data.columns; - let X = new Matrix(rows, columns); - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < columns; j++) { - if (i > j) { - X.set(i, j, data.get(i, j)); - } else if (i === j) { - X.set(i, j, 1); - } else { - X.set(i, j, 0); - } - } - } + } + installMathOperations(AbstractMatrix, Matrix); - return X; + class BaseView extends AbstractMatrix { + constructor(matrix, rows, columns) { + super(); + this.matrix = matrix; + this.rows = rows; + this.columns = columns; } - get upperTriangularMatrix() { - let data = this.LU; - let rows = data.rows; - let columns = data.columns; - let X = new Matrix(rows, columns); + } - for (let i = 0; i < rows; i++) { - for (let j = 0; j < columns; j++) { - if (i <= j) { - X.set(i, j, data.get(i, j)); - } else { - X.set(i, j, 0); - } - } - } + class MatrixColumnView extends BaseView { + constructor(matrix, column) { + checkColumnIndex(matrix, column); + super(matrix, matrix.rows, 1); + this.column = column; + } - return X; + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.column, value); + return this; } - get pivotPermutationVector() { - return Array.from(this.pivotVector); + get(rowIndex) { + return this.matrix.get(rowIndex, this.column); } } - function hypotenuse(a, b) { - let r = 0; + class MatrixColumnSelectionView extends BaseView { + constructor(matrix, columnIndices) { + columnIndices = checkColumnIndices(matrix, columnIndices); + super(matrix, matrix.rows, columnIndices.length); + this.columnIndices = columnIndices; + } - if (Math.abs(a) > Math.abs(b)) { - r = b / a; - return Math.abs(a) * Math.sqrt(1 + r * r); + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.columnIndices[columnIndex], value); + return this; } - if (b !== 0) { - r = a / b; - return Math.abs(b) * Math.sqrt(1 + r * r); + get(rowIndex, columnIndex) { + return this.matrix.get(rowIndex, this.columnIndices[columnIndex]); } - return 0; } - class QrDecomposition { - constructor(value) { - value = WrapperMatrix2D.checkMatrix(value); - let qr = value.clone(); - let m = value.rows; - let n = value.columns; - let rdiag = new Float64Array(n); - let i, j, k, s; - - for (k = 0; k < n; k++) { - let nrm = 0; + class MatrixFlipColumnView extends BaseView { + constructor(matrix) { + super(matrix, matrix.rows, matrix.columns); + } - for (i = k; i < m; i++) { - nrm = hypotenuse(nrm, qr.get(i, k)); - } + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.columns - columnIndex - 1, value); + return this; + } - if (nrm !== 0) { - if (qr.get(k, k) < 0) { - nrm = -nrm; - } + get(rowIndex, columnIndex) { + return this.matrix.get(rowIndex, this.columns - columnIndex - 1); + } - for (i = k; i < m; i++) { - qr.set(i, k, qr.get(i, k) / nrm); - } + } - qr.set(k, k, qr.get(k, k) + 1); + class MatrixFlipRowView extends BaseView { + constructor(matrix) { + super(matrix, matrix.rows, matrix.columns); + } - for (j = k + 1; j < n; j++) { - s = 0; + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rows - rowIndex - 1, columnIndex, value); + return this; + } - for (i = k; i < m; i++) { - s += qr.get(i, k) * qr.get(i, j); - } + get(rowIndex, columnIndex) { + return this.matrix.get(this.rows - rowIndex - 1, columnIndex); + } - 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)); - } - } - } + class MatrixRowView extends BaseView { + constructor(matrix, row) { + checkRowIndex(matrix, row); + super(matrix, 1, matrix.columns); + this.row = row; + } - rdiag[k] = -nrm; - } + set(rowIndex, columnIndex, value) { + this.matrix.set(this.row, columnIndex, value); + return this; + } - this.QR = qr; - this.Rdiag = rdiag; + get(rowIndex, columnIndex) { + return this.matrix.get(this.row, columnIndex); } - solve(value) { - value = Matrix.checkMatrix(value); - let qr = this.QR; - let m = qr.rows; + } - if (value.rows !== m) { - throw new Error('Matrix row dimensions must agree'); - } + class MatrixRowSelectionView extends BaseView { + constructor(matrix, rowIndices) { + rowIndices = checkRowIndices(matrix, rowIndices); + super(matrix, rowIndices.length, matrix.columns); + this.rowIndices = rowIndices; + } - if (!this.isFullRank()) { - throw new Error('Matrix is rank deficient'); - } + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rowIndices[rowIndex], columnIndex, value); + return this; + } - let count = value.columns; - let X = value.clone(); - let n = qr.columns; - let i, j, k, s; + get(rowIndex, columnIndex) { + return this.matrix.get(this.rowIndices[rowIndex], columnIndex); + } - for (k = 0; k < n; k++) { - for (j = 0; j < count; j++) { - s = 0; + } - for (i = k; i < m; i++) { - s += qr.get(i, k) * X.get(i, j); - } + class MatrixSelectionView extends BaseView { + constructor(matrix, rowIndices, columnIndices) { + let indices = checkIndices(matrix, rowIndices, columnIndices); + super(matrix, indices.row.length, indices.column.length); + this.rowIndices = indices.row; + this.columnIndices = indices.column; + } - s = -s / qr.get(k, k); + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value); + return this; + } - for (i = k; i < m; i++) { - X.set(i, j, X.get(i, j) + s * qr.get(i, k)); - } - } - } + get(rowIndex, columnIndex) { + return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]); + } - for (k = n - 1; k >= 0; k--) { - for (j = 0; j < count; j++) { - X.set(k, j, X.get(k, j) / this.Rdiag[k]); - } + } - for (i = 0; i < k; i++) { - for (j = 0; j < count; j++) { - X.set(i, j, X.get(i, j) - X.get(k, j) * qr.get(i, k)); - } - } - } + class MatrixSubView extends 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; + } - return X.subMatrix(0, n - 1, 0, count - 1); + set(rowIndex, columnIndex, value) { + this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex, value); + return this; } - isFullRank() { - let columns = this.QR.columns; + get(rowIndex, columnIndex) { + return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex); + } - for (let i = 0; i < columns; i++) { - if (this.Rdiag[i] === 0) { - return false; - } - } + } - return true; + class MatrixTransposeView extends BaseView { + constructor(matrix) { + super(matrix, matrix.columns, matrix.rows); } - get upperTriangularMatrix() { - let qr = this.QR; - let n = qr.columns; - let X = new Matrix(n, n); - let i, j; + set(rowIndex, columnIndex, value) { + this.matrix.set(columnIndex, rowIndex, value); + return this; + } - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - if (i < j) { - X.set(i, j, qr.get(i, j)); - } else if (i === j) { - X.set(i, j, this.Rdiag[i]); - } else { - X.set(i, j, 0); - } - } + get(rowIndex, columnIndex) { + return this.matrix.get(columnIndex, rowIndex); + } + + } + + class WrapperMatrix1D extends AbstractMatrix { + constructor(data, options = {}) { + const { + rows = 1 + } = options; + + if (data.length % rows !== 0) { + throw new Error('the data length is not divisible by the number of rows'); } - return X; + super(); + this.rows = rows; + this.columns = data.length / rows; + this.data = data; } - get orthogonalMatrix() { - let qr = this.QR; - let rows = qr.rows; - let columns = qr.columns; - let X = new Matrix(rows, columns); - let i, j, k, s; + set(rowIndex, columnIndex, value) { + let index = this._calculateIndex(rowIndex, columnIndex); - for (k = columns - 1; k >= 0; k--) { - for (i = 0; i < rows; i++) { - X.set(i, k, 0); - } + this.data[index] = value; + return this; + } - X.set(k, k, 1); + get(rowIndex, columnIndex) { + let index = this._calculateIndex(rowIndex, columnIndex); - for (j = k; j < columns; j++) { - if (qr.get(k, k) !== 0) { - s = 0; + return this.data[index]; + } - for (i = k; i < rows; i++) { - s += qr.get(i, k) * X.get(i, j); - } + _calculateIndex(row, column) { + return row * this.columns + column; + } - s = -s / qr.get(k, k); + } - for (i = k; i < rows; i++) { - X.set(i, j, X.get(i, j) + s * qr.get(i, k)); - } - } - } - } + class WrapperMatrix2D extends AbstractMatrix { + constructor(data) { + super(); + this.data = data; + this.rows = data.length; + this.columns = data[0].length; + } - return X; + set(rowIndex, columnIndex, value) { + this.data[rowIndex][columnIndex] = value; + return this; + } + + get(rowIndex, columnIndex) { + return this.data[rowIndex][columnIndex]; } } - class SingularValueDecomposition { - constructor(value) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - value = WrapperMatrix2D.checkMatrix(value); - let m = value.rows; - let n = value.columns; - const { - computeLeftSingularVectors = true, - computeRightSingularVectors = true, - autoTranspose = false - } = options; - let wantu = Boolean(computeLeftSingularVectors); - let wantv = Boolean(computeRightSingularVectors); - let swapped = false; - let 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'); - } else { - a = value.transpose(); - m = a.rows; - n = a.columns; - swapped = true; - let aux = wantu; - wantu = wantv; - wantv = aux; - } + function wrap(array, options) { + if (Array.isArray(array)) { + if (array[0] && Array.isArray(array[0])) { + return new WrapperMatrix2D(array); } else { - a = value.clone(); + return new WrapperMatrix1D(array, options); } + } else { + throw new Error('the argument is not an array'); + } + } - let nu = Math.min(m, n); - let ni = Math.min(m + 1, n); - let s = new Float64Array(ni); - let U = new Matrix(m, nu); - let V = new Matrix(n, n); - let e = new Float64Array(n); - let work = new Float64Array(m); - let si = new Float64Array(ni); - - for (let i = 0; i < ni; i++) si[i] = i; - - let nct = Math.min(m - 1, n); - let nrt = Math.max(0, Math.min(n - 2, m)); - let mrc = Math.max(nct, nrt); + class LuDecomposition { + constructor(matrix) { + matrix = WrapperMatrix2D.checkMatrix(matrix); + let lu = matrix.clone(); + let rows = lu.rows; + let columns = lu.columns; + let pivotVector = new Float64Array(rows); + let pivotSign = 1; + let i, j, k, p, s, t, v; + let LUcolj, kmax; - for (let k = 0; k < mrc; k++) { - if (k < nct) { - s[k] = 0; + for (i = 0; i < rows; i++) { + pivotVector[i] = i; + } - for (let i = k; i < m; i++) { - s[k] = hypotenuse(s[k], a.get(i, k)); - } + LUcolj = new Float64Array(rows); - if (s[k] !== 0) { - if (a.get(k, k) < 0) { - s[k] = -s[k]; - } + for (j = 0; j < columns; j++) { + for (i = 0; i < rows; i++) { + LUcolj[i] = lu.get(i, j); + } - for (let i = k; i < m; i++) { - a.set(i, k, a.get(i, k) / s[k]); - } + for (i = 0; i < rows; i++) { + kmax = Math.min(i, j); + s = 0; - a.set(k, k, a.get(k, k) + 1); + for (k = 0; k < kmax; k++) { + s += lu.get(i, k) * LUcolj[k]; } - s[k] = -s[k]; + LUcolj[i] -= s; + lu.set(i, j, LUcolj[i]); } - for (let j = k + 1; j < n; j++) { - if (k < nct && s[k] !== 0) { - let t = 0; - - for (let i = k; i < m; i++) { - t += a.get(i, k) * a.get(i, j); - } + p = j; - t = -t / a.get(k, k); + for (i = j + 1; i < rows; i++) { + if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) { + p = i; + } + } - for (let i = k; i < m; i++) { - a.set(i, j, a.get(i, j) + t * a.get(i, k)); - } + 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); } - e[j] = a.get(k, j); + v = pivotVector[p]; + pivotVector[p] = pivotVector[j]; + pivotVector[j] = v; + pivotSign = -pivotSign; } - if (wantu && k < nct) { - for (let i = k; i < m; i++) { - U.set(i, k, a.get(i, k)); + 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)); } } + } - if (k < nrt) { - e[k] = 0; - - for (let i = k + 1; i < n; i++) { - e[k] = hypotenuse(e[k], e[i]); - } + this.LU = lu; + this.pivotVector = pivotVector; + this.pivotSign = pivotSign; + } - if (e[k] !== 0) { - if (e[k + 1] < 0) { - e[k] = 0 - e[k]; - } + isSingular() { + let data = this.LU; + let col = data.columns; - for (let i = k + 1; i < n; i++) { - e[i] /= e[k]; - } + for (let j = 0; j < col; j++) { + if (data.get(j, j) === 0) { + return true; + } + } - e[k + 1] += 1; - } + return false; + } - e[k] = -e[k]; + solve(value) { + value = Matrix.checkMatrix(value); + let lu = this.LU; + let rows = lu.rows; - if (k + 1 < m && e[k] !== 0) { - for (let i = k + 1; i < m; i++) { - work[i] = 0; - } + if (rows !== value.rows) { + throw new Error('Invalid matrix dimensions'); + } - for (let i = k + 1; i < m; i++) { - for (let j = k + 1; j < n; j++) { - work[i] += e[j] * a.get(i, j); - } - } + if (this.isSingular()) { + throw new Error('LU matrix is singular'); + } - for (let j = k + 1; j < n; j++) { - let t = -e[j] / e[k + 1]; + let count = value.columns; + let X = value.subMatrixRow(this.pivotVector, 0, count - 1); + let columns = lu.columns; + let i, j, k; - for (let i = k + 1; i < m; i++) { - a.set(i, j, a.get(i, j) + t * work[i]); - } - } + for (k = 0; k < columns; k++) { + for (i = k + 1; i < columns; i++) { + for (j = 0; j < count; j++) { + X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k)); } + } + } - if (wantv) { - for (let i = k + 1; i < n; i++) { - V.set(i, k, e[i]); - } + for (k = columns - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + X.set(k, j, X.get(k, j) / lu.get(k, k)); + } + + for (i = 0; i < k; i++) { + for (j = 0; j < count; j++) { + X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k)); } } } - let p = Math.min(n, m + 1); + return X; + } - if (nct < n) { - s[nct] = a.get(nct, nct); - } + get determinant() { + let data = this.LU; - if (m < p) { - s[p - 1] = 0; + if (!data.isSquare()) { + throw new Error('Matrix must be square'); } - if (nrt + 1 < p) { - e[nrt] = a.get(nrt, p - 1); + let determinant = this.pivotSign; + let col = data.columns; + + for (let j = 0; j < col; j++) { + determinant *= data.get(j, j); } - e[p - 1] = 0; + return determinant; + } - if (wantu) { - for (let j = nct; j < nu; j++) { - for (let i = 0; i < m; i++) { - U.set(i, j, 0); - } + get lowerTriangularMatrix() { + let data = this.LU; + let rows = data.rows; + let columns = data.columns; + let X = new Matrix(rows, columns); - U.set(j, j, 1); + for (let i = 0; i < rows; i++) { + for (let j = 0; j < columns; j++) { + if (i > j) { + X.set(i, j, data.get(i, j)); + } else if (i === j) { + X.set(i, j, 1); + } else { + X.set(i, j, 0); + } } + } - for (let k = nct - 1; k >= 0; k--) { - if (s[k] !== 0) { - for (let j = k + 1; j < nu; j++) { - let t = 0; + return X; + } - for (let i = k; i < m; i++) { - t += U.get(i, k) * U.get(i, j); - } + get upperTriangularMatrix() { + let data = this.LU; + let rows = data.rows; + let columns = data.columns; + let X = new Matrix(rows, columns); - t = -t / U.get(k, k); - - for (let i = k; i < m; i++) { - U.set(i, j, U.get(i, j) + t * U.get(i, k)); - } - } - - for (let i = k; i < m; i++) { - U.set(i, k, -U.get(i, k)); - } - - U.set(k, k, 1 + U.get(k, k)); - - for (let i = 0; i < k - 1; i++) { - U.set(i, k, 0); - } + for (let i = 0; i < rows; i++) { + for (let j = 0; j < columns; j++) { + if (i <= j) { + X.set(i, j, data.get(i, j)); } else { - for (let i = 0; i < m; i++) { - U.set(i, k, 0); - } - - U.set(k, k, 1); + X.set(i, j, 0); } } } - 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; + return X; + } - for (let i = k + 1; i < n; i++) { - t += V.get(i, k) * V.get(i, j); - } + get pivotPermutationVector() { + return Array.from(this.pivotVector); + } - t = -t / V.get(k + 1, k); + } - for (let i = k + 1; i < n; i++) { - V.set(i, j, V.get(i, j) + t * V.get(i, k)); - } - } - } + function hypotenuse(a, b) { + let r = 0; - for (let i = 0; i < n; i++) { - V.set(i, k, 0); - } + if (Math.abs(a) > Math.abs(b)) { + r = b / a; + return Math.abs(a) * Math.sqrt(1 + r * r); + } - V.set(k, k, 1); - } - } + if (b !== 0) { + r = a / b; + return Math.abs(b) * Math.sqrt(1 + r * r); + } - let pp = p - 1; - let eps = Number.EPSILON; + return 0; + } - while (p > 0) { - let k, kase; + class QrDecomposition { + constructor(value) { + value = WrapperMatrix2D.checkMatrix(value); + let qr = value.clone(); + let m = value.rows; + let n = value.columns; + let rdiag = new Float64Array(n); + let i, j, k, s; - for (k = p - 2; k >= -1; k--) { - if (k === -1) { - break; - } + for (k = 0; k < n; k++) { + let nrm = 0; - const alpha = Number.MIN_VALUE + eps * Math.abs(s[k] + Math.abs(s[k + 1])); + for (i = k; i < m; i++) { + nrm = hypotenuse(nrm, qr.get(i, k)); + } - if (Math.abs(e[k]) <= alpha || Number.isNaN(e[k])) { - e[k] = 0; - break; + if (nrm !== 0) { + if (qr.get(k, k) < 0) { + nrm = -nrm; } - } - if (k === p - 2) { - kase = 4; - } else { - let ks; + for (i = k; i < m; i++) { + qr.set(i, k, qr.get(i, k) / nrm); + } - for (ks = p - 1; ks >= k; ks--) { - if (ks === k) { - break; - } + qr.set(k, k, qr.get(k, k) + 1); - let t = (ks !== p ? Math.abs(e[ks]) : 0) + (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0); + for (j = k + 1; j < n; j++) { + s = 0; - if (Math.abs(s[ks]) <= eps * t) { - s[ks] = 0; - break; + for (i = k; i < m; i++) { + s += qr.get(i, k) * qr.get(i, j); } - } - if (ks === k) { - kase = 3; - } else if (ks === p - 1) { - kase = 1; - } else { - kase = 2; - k = ks; + 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)); + } } } - k++; + rdiag[k] = -nrm; + } - switch (kase) { - case 1: - { - let f = e[p - 2]; - e[p - 2] = 0; + this.QR = qr; + this.Rdiag = rdiag; + } - 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; + solve(value) { + value = Matrix.checkMatrix(value); + let qr = this.QR; + let m = qr.rows; - if (j !== k) { - f = -sn * e[j - 1]; - e[j - 1] = cs * e[j - 1]; - } + if (value.rows !== m) { + throw new Error('Matrix row dimensions must agree'); + } - if (wantv) { - for (let i = 0; i < n; i++) { - t = cs * V.get(i, j) + sn * V.get(i, p - 1); - V.set(i, p - 1, -sn * V.get(i, j) + cs * V.get(i, p - 1)); - V.set(i, j, t); - } - } - } + if (!this.isFullRank()) { + throw new Error('Matrix is rank deficient'); + } - break; - } + let count = value.columns; + let X = value.clone(); + let n = qr.columns; + let i, j, k, s; - case 2: - { - let f = e[k - 1]; - e[k - 1] = 0; + for (k = 0; k < n; k++) { + for (j = 0; j < count; j++) { + s = 0; - 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]; + for (i = k; i < m; i++) { + s += qr.get(i, k) * X.get(i, j); + } - if (wantu) { - for (let i = 0; i < m; i++) { - t = cs * U.get(i, j) + sn * U.get(i, k - 1); - U.set(i, k - 1, -sn * U.get(i, j) + cs * U.get(i, k - 1)); - U.set(i, j, t); - } - } - } + s = -s / qr.get(k, k); - break; - } + for (i = k; i < m; i++) { + X.set(i, j, X.get(i, j) + s * qr.get(i, k)); + } + } + } - 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; + for (k = n - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + X.set(k, j, X.get(k, j) / this.Rdiag[k]); + } - if (b !== 0 || c !== 0) { - if (b < 0) { - shift = 0 - Math.sqrt(b * b + c); - } else { - shift = Math.sqrt(b * b + c); - } + for (i = 0; i < k; i++) { + for (j = 0; j < count; j++) { + X.set(i, j, X.get(i, j) - X.get(k, j) * qr.get(i, k)); + } + } + } - shift = c / (b + shift); - } + return X.subMatrix(0, n - 1, 0, count - 1); + } - let f = (sk + sp) * (sk - sp) + shift; - let g = sk * ek; + isFullRank() { + let columns = this.QR.columns; - 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; + for (let i = 0; i < columns; i++) { + if (this.Rdiag[i] === 0) { + return false; + } + } - if (j !== k) { - e[j - 1] = t; - } + return true; + } - 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]; - - if (wantv) { - for (let i = 0; i < n; i++) { - t = cs * V.get(i, j) + sn * V.get(i, j + 1); - V.set(i, j + 1, -sn * V.get(i, j) + cs * V.get(i, j + 1)); - V.set(i, j, t); - } - } - - 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]; + get upperTriangularMatrix() { + let qr = this.QR; + let n = qr.columns; + let X = new Matrix(n, n); + let i, j; - if (wantu && j < m - 1) { - for (let i = 0; i < m; i++) { - t = cs * U.get(i, j) + sn * U.get(i, j + 1); - U.set(i, j + 1, -sn * U.get(i, j) + cs * U.get(i, j + 1)); - U.set(i, j, t); - } - } - } + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + if (i < j) { + X.set(i, j, qr.get(i, j)); + } else if (i === j) { + X.set(i, j, this.Rdiag[i]); + } else { + X.set(i, j, 0); + } + } + } - e[p - 2] = f; - break; - } + return X; + } - case 4: - { - if (s[k] <= 0) { - s[k] = s[k] < 0 ? -s[k] : 0; + get orthogonalMatrix() { + let qr = this.QR; + let rows = qr.rows; + let columns = qr.columns; + let X = new Matrix(rows, columns); + let i, j, k, s; - if (wantv) { - for (let i = 0; i <= pp; i++) { - V.set(i, k, -V.get(i, k)); - } - } - } + for (k = columns - 1; k >= 0; k--) { + for (i = 0; i < rows; i++) { + X.set(i, k, 0); + } - while (k < pp) { - if (s[k] >= s[k + 1]) { - break; - } + X.set(k, k, 1); - let t = s[k]; - s[k] = s[k + 1]; - s[k + 1] = t; + for (j = k; j < columns; j++) { + if (qr.get(k, k) !== 0) { + s = 0; - if (wantv && k < n - 1) { - for (let i = 0; i < n; i++) { - t = V.get(i, k + 1); - V.set(i, k + 1, V.get(i, k)); - V.set(i, k, t); - } - } + for (i = k; i < rows; i++) { + s += qr.get(i, k) * X.get(i, j); + } - if (wantu && k < m - 1) { - for (let i = 0; i < m; i++) { - t = U.get(i, k + 1); - U.set(i, k + 1, U.get(i, k)); - U.set(i, k, t); - } - } + s = -s / qr.get(k, k); - k++; - } - p--; - break; + for (i = k; i < rows; i++) { + X.set(i, j, X.get(i, j) + s * qr.get(i, k)); } - // no default + } } } - if (swapped) { - let tmp = V; - V = U; - U = tmp; - } - - this.m = m; - this.n = n; - this.s = s; - this.U = U; - this.V = V; + return X; } - solve(value) { - let Y = value; - let e = this.threshold; - let scols = this.s.length; - let Ls = Matrix.zeros(scols, scols); + } - for (let i = 0; i < scols; i++) { - if (Math.abs(this.s[i]) <= e) { - Ls.set(i, i, 0); + class SingularValueDecomposition { + constructor(value, options = {}) { + value = WrapperMatrix2D.checkMatrix(value); + let m = value.rows; + let n = value.columns; + const { + computeLeftSingularVectors = true, + computeRightSingularVectors = true, + autoTranspose = false + } = options; + let wantu = Boolean(computeLeftSingularVectors); + let wantv = Boolean(computeRightSingularVectors); + let swapped = false; + let 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'); } else { - Ls.set(i, i, 1 / this.s[i]); + a = value.transpose(); + m = a.rows; + n = a.columns; + swapped = true; + let aux = wantu; + wantu = wantv; + wantv = aux; } + } else { + a = value.clone(); } - let U = this.U; - let V = this.rightSingularVectors; - let VL = V.mmul(Ls); - let vrows = V.rows; - let urows = U.rows; - let VLU = Matrix.zeros(vrows, urows); + let nu = Math.min(m, n); + let ni = Math.min(m + 1, n); + let s = new Float64Array(ni); + let U = new Matrix(m, nu); + let V = new Matrix(n, n); + let e = new Float64Array(n); + let work = new Float64Array(m); + let si = new Float64Array(ni); - for (let i = 0; i < vrows; i++) { - for (let j = 0; j < urows; j++) { - let sum = 0; + for (let i = 0; i < ni; i++) si[i] = i; - for (let k = 0; k < scols; k++) { - sum += VL.get(i, k) * U.get(j, k); - } + let nct = Math.min(m - 1, n); + let nrt = Math.max(0, Math.min(n - 2, m)); + let mrc = Math.max(nct, nrt); - VLU.set(i, j, sum); - } - } + for (let k = 0; k < mrc; k++) { + if (k < nct) { + s[k] = 0; - return VLU.mmul(Y); - } + for (let i = k; i < m; i++) { + s[k] = hypotenuse(s[k], a.get(i, k)); + } - solveForDiagonal(value) { - return this.solve(Matrix.diag(value)); - } + if (s[k] !== 0) { + if (a.get(k, k) < 0) { + s[k] = -s[k]; + } - inverse() { - let V = this.V; - let e = this.threshold; - let vrows = V.rows; - let vcols = V.columns; - let X = new Matrix(vrows, this.s.length); + for (let i = k; i < m; i++) { + a.set(i, k, a.get(i, k) / s[k]); + } - for (let i = 0; i < vrows; i++) { - for (let j = 0; j < vcols; j++) { - if (Math.abs(this.s[j]) > e) { - X.set(i, j, V.get(i, j) / this.s[j]); + a.set(k, k, a.get(k, k) + 1); } + + s[k] = -s[k]; } - } - let U = this.U; - let urows = U.rows; - let ucols = U.columns; - let Y = new Matrix(vrows, urows); + for (let j = k + 1; j < n; j++) { + if (k < nct && s[k] !== 0) { + let t = 0; - for (let i = 0; i < vrows; i++) { - for (let j = 0; j < urows; j++) { - let sum = 0; + for (let i = k; i < m; i++) { + t += a.get(i, k) * a.get(i, j); + } - for (let k = 0; k < ucols; k++) { - sum += X.get(i, k) * U.get(j, k); + t = -t / a.get(k, k); + + for (let i = k; i < m; i++) { + a.set(i, j, a.get(i, j) + t * a.get(i, k)); + } } - Y.set(i, j, sum); + e[j] = a.get(k, j); } - } - return Y; - } + if (wantu && k < nct) { + for (let i = k; i < m; i++) { + U.set(i, k, a.get(i, k)); + } + } - get condition() { - return this.s[0] / this.s[Math.min(this.m, this.n) - 1]; - } + if (k < nrt) { + e[k] = 0; - get norm2() { - return this.s[0]; - } + for (let i = k + 1; i < n; i++) { + e[k] = hypotenuse(e[k], e[i]); + } - get rank() { - let tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON; - let r = 0; - let s = this.s; - - for (let i = 0, ii = s.length; i < ii; i++) { - if (s[i] > tol) { - r++; - } - } - - return r; - } - - get diagonal() { - return Array.from(this.s); - } - - get threshold() { - return Number.EPSILON / 2 * Math.max(this.m, this.n) * this.s[0]; - } + if (e[k] !== 0) { + if (e[k + 1] < 0) { + e[k] = 0 - e[k]; + } - get leftSingularVectors() { - return this.U; - } + for (let i = k + 1; i < n; i++) { + e[i] /= e[k]; + } - get rightSingularVectors() { - return this.V; - } + e[k + 1] += 1; + } - get diagonalMatrix() { - return Matrix.diag(this.s); - } + e[k] = -e[k]; - } + if (k + 1 < m && e[k] !== 0) { + for (let i = k + 1; i < m; i++) { + work[i] = 0; + } - function inverse(matrix) { - let useSVD = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - matrix = WrapperMatrix2D.checkMatrix(matrix); + for (let i = k + 1; i < m; i++) { + for (let j = k + 1; j < n; j++) { + work[i] += e[j] * a.get(i, j); + } + } - if (useSVD) { - return new SingularValueDecomposition(matrix).inverse(); - } else { - return solve(matrix, Matrix.eye(matrix.rows)); - } - } - function solve(leftHandSide, rightHandSide) { - let useSVD = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - leftHandSide = WrapperMatrix2D.checkMatrix(leftHandSide); - rightHandSide = WrapperMatrix2D.checkMatrix(rightHandSide); + for (let j = k + 1; j < n; j++) { + let t = -e[j] / e[k + 1]; - if (useSVD) { - return new SingularValueDecomposition(leftHandSide).solve(rightHandSide); - } else { - return leftHandSide.isSquare() ? new LuDecomposition(leftHandSide).solve(rightHandSide) : new QrDecomposition(leftHandSide).solve(rightHandSide); - } - } + for (let i = k + 1; i < m; i++) { + a.set(i, j, a.get(i, j) + t * work[i]); + } + } + } - function determinant(matrix) { - matrix = Matrix.checkMatrix(matrix); + if (wantv) { + for (let i = k + 1; i < n; i++) { + V.set(i, k, e[i]); + } + } + } + } - if (matrix.isSquare()) { - let a, b, c, d; + let p = Math.min(n, m + 1); - if (matrix.columns === 2) { - // 2 x 2 matrix - a = matrix.get(0, 0); - b = matrix.get(0, 1); - c = matrix.get(1, 0); - d = matrix.get(1, 1); - return a * d - b * c; - } else if (matrix.columns === 3) { - // 3 x 3 matrix - let subMatrix0, subMatrix1, subMatrix2; - subMatrix0 = new MatrixSelectionView(matrix, [1, 2], [1, 2]); - subMatrix1 = new MatrixSelectionView(matrix, [1, 2], [0, 2]); - subMatrix2 = new MatrixSelectionView(matrix, [1, 2], [0, 1]); - a = matrix.get(0, 0); - b = matrix.get(0, 1); - c = matrix.get(0, 2); - return a * determinant(subMatrix0) - b * determinant(subMatrix1) + c * determinant(subMatrix2); - } else { - // general purpose determinant using the LU decomposition - return new LuDecomposition(matrix).determinant; + if (nct < n) { + s[nct] = a.get(nct, nct); } - } else { - throw Error('determinant can only be calculated for a square matrix'); - } - } - - function xrange(n, exception) { - let range = []; - for (let i = 0; i < n; i++) { - if (i !== exception) { - range.push(i); + if (m < p) { + s[p - 1] = 0; } - } - return range; - } + if (nrt + 1 < p) { + e[nrt] = a.get(nrt, p - 1); + } - 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; + e[p - 1] = 0; - if (error > thresholdError) { - return new Array(matrix.rows + 1).fill(0); - } else { - let returnArray = matrix.addRow(index, [0]); + if (wantu) { + for (let j = nct; j < nu; j++) { + for (let i = 0; i < m; i++) { + U.set(i, j, 0); + } - for (let i = 0; i < returnArray.rows; i++) { - if (Math.abs(returnArray.get(i, 0)) < thresholdValue) { - returnArray.set(i, 0, 0); + U.set(j, j, 1); } - } - - return returnArray.to1DArray(); - } - } - function linearDependencies(matrix) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - const { - thresholdValue = 10e-10, - thresholdError = 10e-10 - } = options; - matrix = Matrix.checkMatrix(matrix); - let n = matrix.rows; - let results = new Matrix(n, n); + for (let k = nct - 1; k >= 0; k--) { + if (s[k] !== 0) { + for (let j = k + 1; j < nu; j++) { + let t = 0; - for (let i = 0; i < n; i++) { - let b = Matrix.columnVector(matrix.getRow(i)); - let Abis = matrix.subMatrixRow(xrange(n, i)).transpose(); - let svd = new SingularValueDecomposition(Abis); - let x = svd.solve(b); - let error = Matrix.sub(b, Abis.mmul(x)).abs().max(); - results.setRow(i, dependenciesOneRow(error, x, i, thresholdValue, thresholdError)); - } + for (let i = k; i < m; i++) { + t += U.get(i, k) * U.get(i, j); + } - return results; - } + t = -t / U.get(k, k); - function pseudoInverse(matrix) { - let threshold = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Number.EPSILON; - matrix = Matrix.checkMatrix(matrix); - let svdSolution = new SingularValueDecomposition(matrix, { - autoTranspose: true - }); - let U = svdSolution.leftSingularVectors; - let V = svdSolution.rightSingularVectors; - let s = svdSolution.diagonal; + for (let i = k; i < m; i++) { + U.set(i, j, U.get(i, j) + t * U.get(i, k)); + } + } - for (let i = 0; i < s.length; i++) { - if (Math.abs(s[i]) > threshold) { - s[i] = 1.0 / s[i]; - } else { - s[i] = 0.0; - } - } + for (let i = k; i < m; i++) { + U.set(i, k, -U.get(i, k)); + } - return V.mmul(Matrix.diag(s).mmul(U.transpose())); - } + U.set(k, k, 1 + U.get(k, k)); - function covariance(xMatrix) { - let yMatrix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : xMatrix; - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - xMatrix = Matrix.checkMatrix(xMatrix); - let yIsSame = false; + for (let i = 0; i < k - 1; i++) { + U.set(i, k, 0); + } + } else { + for (let i = 0; i < m; i++) { + U.set(i, k, 0); + } - if (typeof yMatrix === 'object' && !Matrix.isMatrix(yMatrix) && !Array.isArray(yMatrix)) { - options = yMatrix; - yMatrix = xMatrix; - yIsSame = true; - } else { - yMatrix = Matrix.checkMatrix(yMatrix); - } + U.set(k, k, 1); + } + } + } - if (xMatrix.rows !== yMatrix.rows) { - throw new TypeError('Both matrices must have the same number of rows'); - } + 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; - const { - center = true - } = options; + for (let i = k + 1; i < n; i++) { + t += V.get(i, k) * V.get(i, j); + } - if (center) { - xMatrix = xMatrix.center('column'); + t = -t / V.get(k + 1, k); - if (!yIsSame) { - yMatrix = yMatrix.center('column'); - } - } + for (let i = k + 1; i < n; i++) { + V.set(i, j, V.get(i, j) + t * V.get(i, k)); + } + } + } - const cov = xMatrix.transpose().mmul(yMatrix); + for (let i = 0; i < n; i++) { + V.set(i, k, 0); + } - for (let i = 0; i < cov.rows; i++) { - for (let j = 0; j < cov.columns; j++) { - cov.set(i, j, cov.get(i, j) * (1 / (xMatrix.rows - 1))); + V.set(k, k, 1); + } } - } - return cov; - } + let pp = p - 1; + let eps = Number.EPSILON; - function correlation(xMatrix) { - let yMatrix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : xMatrix; - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - xMatrix = Matrix.checkMatrix(xMatrix); - let yIsSame = false; + while (p > 0) { + let k, kase; - if (typeof yMatrix === 'object' && !Matrix.isMatrix(yMatrix) && !Array.isArray(yMatrix)) { - options = yMatrix; - yMatrix = xMatrix; - yIsSame = true; - } else { - yMatrix = Matrix.checkMatrix(yMatrix); - } - - if (xMatrix.rows !== yMatrix.rows) { - throw new TypeError('Both matrices must have the same number of rows'); - } - - const { - center = true, - scale = true - } = options; - - if (center) { - xMatrix.center('column'); - - if (!yIsSame) { - yMatrix.center('column'); - } - } - - if (scale) { - xMatrix.scale('column'); - - if (!yIsSame) { - yMatrix.scale('column'); - } - } - - const sdx = xMatrix.standardDeviation('column', { - unbiased: true - }); - const sdy = yIsSame ? sdx : yMatrix.standardDeviation('column', { - unbiased: true - }); - const corr = xMatrix.transpose().mmul(yMatrix); - - for (let i = 0; i < corr.rows; i++) { - for (let j = 0; j < corr.columns; j++) { - corr.set(i, j, corr.get(i, j) * (1 / (sdx[i] * sdy[j])) * (1 / (xMatrix.rows - 1))); - } - } + for (k = p - 2; k >= -1; k--) { + if (k === -1) { + break; + } - return corr; - } + const alpha = Number.MIN_VALUE + eps * Math.abs(s[k] + Math.abs(s[k + 1])); - class EigenvalueDecomposition { - constructor(matrix) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - const { - assumeSymmetric = false - } = options; - matrix = WrapperMatrix2D.checkMatrix(matrix); + if (Math.abs(e[k]) <= alpha || Number.isNaN(e[k])) { + e[k] = 0; + break; + } + } - if (!matrix.isSquare()) { - throw new Error('Matrix is not a square matrix'); - } + if (k === p - 2) { + kase = 4; + } else { + let ks; - let n = matrix.columns; - let V = new Matrix(n, n); - let d = new Float64Array(n); - let e = new Float64Array(n); - let value = matrix; - let i, j; - let isSymmetric = false; + for (ks = p - 1; ks >= k; ks--) { + if (ks === k) { + break; + } - if (assumeSymmetric) { - isSymmetric = true; - } else { - isSymmetric = matrix.isSymmetric(); - } + let t = (ks !== p ? Math.abs(e[ks]) : 0) + (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0); - if (isSymmetric) { - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - V.set(i, j, value.get(i, j)); + if (Math.abs(s[ks]) <= eps * t) { + s[ks] = 0; + break; + } } - } - - tred2(n, e, d, V); - tql2(n, e, d, V); - } else { - let H = new Matrix(n, n); - let ort = new Float64Array(n); - for (j = 0; j < n; j++) { - for (i = 0; i < n; i++) { - H.set(i, j, value.get(i, j)); + if (ks === k) { + kase = 3; + } else if (ks === p - 1) { + kase = 1; + } else { + kase = 2; + k = ks; } } - orthes(n, H, ort, V); - hqr2(n, e, d, V, H); - } + k++; - this.n = n; - this.e = e; - this.d = d; - this.V = V; - } + switch (kase) { + case 1: + { + let f = e[p - 2]; + e[p - 2] = 0; - get realEigenvalues() { - return Array.from(this.d); - } + 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; - get imaginaryEigenvalues() { - return Array.from(this.e); - } + if (j !== k) { + f = -sn * e[j - 1]; + e[j - 1] = cs * e[j - 1]; + } - get eigenvectorMatrix() { - return this.V; - } + if (wantv) { + for (let i = 0; i < n; i++) { + t = cs * V.get(i, j) + sn * V.get(i, p - 1); + V.set(i, p - 1, -sn * V.get(i, j) + cs * V.get(i, p - 1)); + V.set(i, j, t); + } + } + } - get diagonalMatrix() { - let n = this.n; - let e = this.e; - let d = this.d; - let X = new Matrix(n, n); - let i, j; + break; + } - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - X.set(i, j, 0); - } + case 2: + { + let f = e[k - 1]; + e[k - 1] = 0; - X.set(i, i, d[i]); + 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]; - if (e[i] > 0) { - X.set(i, i + 1, e[i]); - } else if (e[i] < 0) { - X.set(i, i - 1, e[i]); - } - } + if (wantu) { + for (let i = 0; i < m; i++) { + t = cs * U.get(i, j) + sn * U.get(i, k - 1); + U.set(i, k - 1, -sn * U.get(i, j) + cs * U.get(i, k - 1)); + U.set(i, j, t); + } + } + } - return X; - } + break; + } - } + 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; - function tred2(n, e, d, V) { - let f, g, h, i, j, k, hh, scale; + if (b !== 0 || c !== 0) { + if (b < 0) { + shift = 0 - Math.sqrt(b * b + c); + } else { + shift = Math.sqrt(b * b + c); + } - for (j = 0; j < n; j++) { - d[j] = V.get(n - 1, j); - } + shift = c / (b + shift); + } - for (i = n - 1; i > 0; i--) { - scale = 0; - h = 0; + let f = (sk + sp) * (sk - sp) + shift; + let g = sk * ek; - for (k = 0; k < i; k++) { - scale = scale + Math.abs(d[k]); - } + 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; - if (scale === 0) { - e[i] = d[i - 1]; + if (j !== k) { + e[j - 1] = t; + } - for (j = 0; j < i; j++) { - d[j] = V.get(i - 1, j); - V.set(i, j, 0); - V.set(j, i, 0); - } - } else { - for (k = 0; k < i; k++) { - d[k] /= scale; - h += d[k] * d[k]; - } + 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]; - f = d[i - 1]; - g = Math.sqrt(h); + if (wantv) { + for (let i = 0; i < n; i++) { + t = cs * V.get(i, j) + sn * V.get(i, j + 1); + V.set(i, j + 1, -sn * V.get(i, j) + cs * V.get(i, j + 1)); + V.set(i, j, t); + } + } - if (f > 0) { - g = -g; - } + 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]; - e[i] = scale * g; - h = h - f * g; - d[i - 1] = f - g; + if (wantu && j < m - 1) { + for (let i = 0; i < m; i++) { + t = cs * U.get(i, j) + sn * U.get(i, j + 1); + U.set(i, j + 1, -sn * U.get(i, j) + cs * U.get(i, j + 1)); + U.set(i, j, t); + } + } + } - for (j = 0; j < i; j++) { - e[j] = 0; - } + e[p - 2] = f; + break; + } - for (j = 0; j < i; j++) { - f = d[j]; - V.set(j, i, f); - g = e[j] + V.get(j, j) * f; + case 4: + { + if (s[k] <= 0) { + s[k] = s[k] < 0 ? -s[k] : 0; - for (k = j + 1; k <= i - 1; k++) { - g += V.get(k, j) * d[k]; - e[k] += V.get(k, j) * f; - } + if (wantv) { + for (let i = 0; i <= pp; i++) { + V.set(i, k, -V.get(i, k)); + } + } + } - e[j] = g; - } + while (k < pp) { + if (s[k] >= s[k + 1]) { + break; + } - f = 0; + let t = s[k]; + s[k] = s[k + 1]; + s[k + 1] = t; - for (j = 0; j < i; j++) { - e[j] /= h; - f += e[j] * d[j]; + if (wantv && k < n - 1) { + for (let i = 0; i < n; i++) { + t = V.get(i, k + 1); + V.set(i, k + 1, V.get(i, k)); + V.set(i, k, t); + } + } + + if (wantu && k < m - 1) { + for (let i = 0; i < m; i++) { + t = U.get(i, k + 1); + U.set(i, k + 1, U.get(i, k)); + U.set(i, k, t); + } + } + + k++; + } + p--; + break; + } + // no default } + } - hh = f / (h + h); + if (swapped) { + let tmp = V; + V = U; + U = tmp; + } - for (j = 0; j < i; j++) { - e[j] -= hh * d[j]; + this.m = m; + this.n = n; + this.s = s; + this.U = U; + this.V = V; + } + + solve(value) { + let Y = value; + let e = this.threshold; + let scols = this.s.length; + let Ls = Matrix.zeros(scols, scols); + + for (let i = 0; i < scols; i++) { + if (Math.abs(this.s[i]) <= e) { + Ls.set(i, i, 0); + } else { + Ls.set(i, i, 1 / this.s[i]); } + } - for (j = 0; j < i; j++) { - f = d[j]; - g = e[j]; + let U = this.U; + let V = this.rightSingularVectors; + let VL = V.mmul(Ls); + let vrows = V.rows; + let urows = U.rows; + let VLU = Matrix.zeros(vrows, urows); - for (k = j; k <= i - 1; k++) { - V.set(k, j, V.get(k, j) - (f * e[k] + g * d[k])); + 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.get(i, k) * U.get(j, k); } - d[j] = V.get(i - 1, j); - V.set(i, j, 0); + VLU.set(i, j, sum); } } - d[i] = h; + return VLU.mmul(Y); } - for (i = 0; i < n - 1; i++) { - V.set(n - 1, i, V.get(i, i)); - V.set(i, i, 1); - h = d[i + 1]; + solveForDiagonal(value) { + return this.solve(Matrix.diag(value)); + } - if (h !== 0) { - for (k = 0; k <= i; k++) { - d[k] = V.get(k, i + 1) / h; + inverse() { + let V = this.V; + let e = this.threshold; + let vrows = V.rows; + let vcols = V.columns; + let X = new 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.set(i, j, V.get(i, j) / this.s[j]); + } } + } - for (j = 0; j <= i; j++) { - g = 0; + let U = this.U; + let urows = U.rows; + let ucols = U.columns; + let Y = new Matrix(vrows, urows); - for (k = 0; k <= i; k++) { - g += V.get(k, i + 1) * V.get(k, j); - } + for (let i = 0; i < vrows; i++) { + for (let j = 0; j < urows; j++) { + let sum = 0; - for (k = 0; k <= i; k++) { - V.set(k, j, V.get(k, j) - g * d[k]); + for (let k = 0; k < ucols; k++) { + sum += X.get(i, k) * U.get(j, k); } + + Y.set(i, j, sum); } } - for (k = 0; k <= i; k++) { - V.set(k, i + 1, 0); - } + return Y; } - for (j = 0; j < n; j++) { - d[j] = V.get(n - 1, j); - V.set(n - 1, j, 0); + get condition() { + return this.s[0] / this.s[Math.min(this.m, this.n) - 1]; } - V.set(n - 1, n - 1, 1); - e[0] = 0; - } - - function tql2(n, e, d, V) { - let g, h, i, j, k, l, m, p, r, dl1, c, c2, c3, el1, s, s2; - - for (i = 1; i < n; i++) { - e[i - 1] = e[i]; + get norm2() { + return this.s[0]; } - e[n - 1] = 0; - let f = 0; - let tst1 = 0; - let eps = Number.EPSILON; - - for (l = 0; l < n; l++) { - tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l])); - m = l; + get rank() { + let tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON; + let r = 0; + let s = this.s; - while (m < n) { - if (Math.abs(e[m]) <= eps * tst1) { - break; + for (let i = 0, ii = s.length; i < ii; i++) { + if (s[i] > tol) { + r++; } - - m++; } - if (m > l) { + return r; + } - do { - g = d[l]; - p = (d[l + 1] - g) / (2 * e[l]); - r = hypotenuse(p, 1); + get diagonal() { + return Array.from(this.s); + } - if (p < 0) { - r = -r; - } + get threshold() { + return Number.EPSILON / 2 * Math.max(this.m, this.n) * this.s[0]; + } - d[l] = e[l] / (p + r); - d[l + 1] = e[l] * (p + r); - dl1 = d[l + 1]; - h = g - d[l]; + get leftSingularVectors() { + return this.U; + } - for (i = l + 2; i < n; i++) { - d[i] -= h; - } + get rightSingularVectors() { + return this.V; + } - f = f + h; - p = d[m]; - c = 1; - c2 = c; - c3 = c; - el1 = e[l + 1]; - s = 0; - s2 = 0; + get diagonalMatrix() { + return Matrix.diag(this.s); + } - 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.get(k, i + 1); - V.set(k, i + 1, s * V.get(k, i) + c * h); - V.set(k, i, c * V.get(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); - } + function inverse(matrix, useSVD = false) { + matrix = WrapperMatrix2D.checkMatrix(matrix); - d[l] = d[l] + f; - e[l] = 0; + if (useSVD) { + return new SingularValueDecomposition(matrix).inverse(); + } else { + return solve(matrix, Matrix.eye(matrix.rows)); } + } + function solve(leftHandSide, rightHandSide, useSVD = false) { + leftHandSide = WrapperMatrix2D.checkMatrix(leftHandSide); + rightHandSide = WrapperMatrix2D.checkMatrix(rightHandSide); - for (i = 0; i < n - 1; i++) { - k = i; - p = d[i]; + if (useSVD) { + return new SingularValueDecomposition(leftHandSide).solve(rightHandSide); + } else { + return leftHandSide.isSquare() ? new LuDecomposition(leftHandSide).solve(rightHandSide) : new QrDecomposition(leftHandSide).solve(rightHandSide); + } + } - for (j = i + 1; j < n; j++) { - if (d[j] < p) { - k = j; - p = d[j]; - } - } + function determinant(matrix) { + matrix = Matrix.checkMatrix(matrix); - if (k !== i) { - d[k] = d[i]; - d[i] = p; + if (matrix.isSquare()) { + let a, b, c, d; - for (j = 0; j < n; j++) { - p = V.get(j, i); - V.set(j, i, V.get(j, k)); - V.set(j, k, p); - } + if (matrix.columns === 2) { + // 2 x 2 matrix + a = matrix.get(0, 0); + b = matrix.get(0, 1); + c = matrix.get(1, 0); + d = matrix.get(1, 1); + return a * d - b * c; + } else if (matrix.columns === 3) { + // 3 x 3 matrix + let subMatrix0, subMatrix1, subMatrix2; + subMatrix0 = new MatrixSelectionView(matrix, [1, 2], [1, 2]); + subMatrix1 = new MatrixSelectionView(matrix, [1, 2], [0, 2]); + subMatrix2 = new MatrixSelectionView(matrix, [1, 2], [0, 1]); + a = matrix.get(0, 0); + b = matrix.get(0, 1); + c = matrix.get(0, 2); + return a * determinant(subMatrix0) - b * determinant(subMatrix1) + c * determinant(subMatrix2); + } else { + // general purpose determinant using the LU decomposition + return new LuDecomposition(matrix).determinant; } + } else { + throw Error('determinant can only be calculated for a square matrix'); } } - function orthes(n, H, ort, V) { - let low = 0; - let high = n - 1; - let f, g, h, i, j, m; - let scale; - - for (m = low + 1; m <= high - 1; m++) { - scale = 0; + function xrange(n, exception) { + let range = []; - for (i = m; i <= high; i++) { - scale = scale + Math.abs(H.get(i, m - 1)); + for (let i = 0; i < n; i++) { + if (i !== exception) { + range.push(i); } + } - if (scale !== 0) { - h = 0; - - for (i = high; i >= m; i--) { - ort[i] = H.get(i, m - 1) / scale; - h += ort[i] * ort[i]; - } + return range; + } - g = Math.sqrt(h); + function dependenciesOneRow(error, matrix, index, thresholdValue = 10e-10, thresholdError = 10e-10) { + if (error > thresholdError) { + return new Array(matrix.rows + 1).fill(0); + } else { + let returnArray = matrix.addRow(index, [0]); - if (ort[m] > 0) { - g = -g; + for (let i = 0; i < returnArray.rows; i++) { + if (Math.abs(returnArray.get(i, 0)) < thresholdValue) { + returnArray.set(i, 0, 0); } + } - h = h - ort[m] * g; - ort[m] = ort[m] - g; - - for (j = m; j < n; j++) { - f = 0; + return returnArray.to1DArray(); + } + } - for (i = high; i >= m; i--) { - f += ort[i] * H.get(i, j); - } + function linearDependencies(matrix, options = {}) { + const { + thresholdValue = 10e-10, + thresholdError = 10e-10 + } = options; + matrix = Matrix.checkMatrix(matrix); + let n = matrix.rows; + let results = new Matrix(n, n); - f = f / h; + for (let i = 0; i < n; i++) { + let b = Matrix.columnVector(matrix.getRow(i)); + let Abis = matrix.subMatrixRow(xrange(n, i)).transpose(); + let svd = new SingularValueDecomposition(Abis); + let x = svd.solve(b); + let error = Matrix.sub(b, Abis.mmul(x)).abs().max(); + results.setRow(i, dependenciesOneRow(error, x, i, thresholdValue, thresholdError)); + } - for (i = m; i <= high; i++) { - H.set(i, j, H.get(i, j) - f * ort[i]); - } - } + return results; + } - for (i = 0; i <= high; i++) { - f = 0; + function pseudoInverse(matrix, threshold = Number.EPSILON) { + matrix = Matrix.checkMatrix(matrix); + let svdSolution = new SingularValueDecomposition(matrix, { + autoTranspose: true + }); + let U = svdSolution.leftSingularVectors; + let V = svdSolution.rightSingularVectors; + let s = svdSolution.diagonal; - for (j = high; j >= m; j--) { - f += ort[j] * H.get(i, j); - } + for (let i = 0; i < s.length; i++) { + if (Math.abs(s[i]) > threshold) { + s[i] = 1.0 / s[i]; + } else { + s[i] = 0.0; + } + } - f = f / h; + return V.mmul(Matrix.diag(s).mmul(U.transpose())); + } - for (j = m; j <= high; j++) { - H.set(i, j, H.get(i, j) - f * ort[j]); - } - } + function covariance(xMatrix, yMatrix = xMatrix, options = {}) { + xMatrix = new Matrix(xMatrix); + let yIsSame = false; - ort[m] = scale * ort[m]; - H.set(m, m - 1, scale * g); - } + if (typeof yMatrix === 'object' && !Matrix.isMatrix(yMatrix) && !Array.isArray(yMatrix)) { + options = yMatrix; + yMatrix = xMatrix; + yIsSame = true; + } else { + yMatrix = new Matrix(yMatrix); } - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - V.set(i, j, i === j ? 1 : 0); - } + if (xMatrix.rows !== yMatrix.rows) { + throw new TypeError('Both matrices must have the same number of rows'); } - for (m = high - 1; m >= low + 1; m--) { - if (H.get(m, m - 1) !== 0) { - for (i = m + 1; i <= high; i++) { - ort[i] = H.get(i, m - 1); - } + const { + center = true + } = options; - for (j = m; j <= high; j++) { - g = 0; + if (center) { + xMatrix = xMatrix.center('column'); - for (i = m; i <= high; i++) { - g += ort[i] * V.get(i, j); - } + if (!yIsSame) { + yMatrix = yMatrix.center('column'); + } + } - g = g / ort[m] / H.get(m, m - 1); + const cov = xMatrix.transpose().mmul(yMatrix); - for (i = m; i <= high; i++) { - V.set(i, j, V.get(i, j) + g * ort[i]); - } - } + for (let i = 0; i < cov.rows; i++) { + for (let j = 0; j < cov.columns; j++) { + cov.set(i, j, cov.get(i, j) * (1 / (xMatrix.rows - 1))); } } + + return cov; } - function hqr2(nn, e, d, V, H) { - let n = nn - 1; - let low = 0; - let high = nn - 1; - let eps = Number.EPSILON; - let exshift = 0; - let norm = 0; - let p = 0; - let q = 0; - let r = 0; - let s = 0; - let z = 0; - let iter = 0; - let i, j, k, l, m, t, w, x, y; - let ra, sa, vr, vi; - let notlast, cdivres; + function correlation(xMatrix, yMatrix = xMatrix, options = {}) { + xMatrix = new Matrix(xMatrix); + let yIsSame = false; - for (i = 0; i < nn; i++) { - if (i < low || i > high) { - d[i] = H.get(i, i); - e[i] = 0; - } + if (typeof yMatrix === 'object' && !Matrix.isMatrix(yMatrix) && !Array.isArray(yMatrix)) { + options = yMatrix; + yMatrix = xMatrix; + yIsSame = true; + } else { + yMatrix = new Matrix(yMatrix); + } - for (j = Math.max(i - 1, 0); j < nn; j++) { - norm = norm + Math.abs(H.get(i, j)); - } + if (xMatrix.rows !== yMatrix.rows) { + throw new TypeError('Both matrices must have the same number of rows'); } - while (n >= low) { - l = n; + const { + center = true, + scale = true + } = options; - while (l > low) { - s = Math.abs(H.get(l - 1, l - 1)) + Math.abs(H.get(l, l)); + if (center) { + xMatrix.center('column'); - if (s === 0) { - s = norm; - } + if (!yIsSame) { + yMatrix.center('column'); + } + } - if (Math.abs(H.get(l, l - 1)) < eps * s) { - break; - } + if (scale) { + xMatrix.scale('column'); - l--; + if (!yIsSame) { + yMatrix.scale('column'); } + } - if (l === n) { - H.set(n, n, H.get(n, n) + exshift); - d[n] = H.get(n, n); - e[n] = 0; - n--; - iter = 0; - } else if (l === n - 1) { - w = H.get(n, n - 1) * H.get(n - 1, n); - p = (H.get(n - 1, n - 1) - H.get(n, n)) / 2; - q = p * p + w; - z = Math.sqrt(Math.abs(q)); - H.set(n, n, H.get(n, n) + exshift); - H.set(n - 1, n - 1, H.get(n - 1, n - 1) + exshift); - x = H.get(n, n); + const sdx = xMatrix.standardDeviation('column', { + unbiased: true + }); + const sdy = yIsSame ? sdx : yMatrix.standardDeviation('column', { + unbiased: true + }); + const corr = xMatrix.transpose().mmul(yMatrix); - if (q >= 0) { - z = p >= 0 ? p + z : p - z; - d[n - 1] = x + z; - d[n] = d[n - 1]; + for (let i = 0; i < corr.rows; i++) { + for (let j = 0; j < corr.columns; j++) { + corr.set(i, j, corr.get(i, j) * (1 / (sdx[i] * sdy[j])) * (1 / (xMatrix.rows - 1))); + } + } - if (z !== 0) { - d[n] = x - w / z; - } + return corr; + } - e[n - 1] = 0; - e[n] = 0; - x = H.get(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; + class EigenvalueDecomposition { + constructor(matrix, options = {}) { + const { + assumeSymmetric = false + } = options; + matrix = WrapperMatrix2D.checkMatrix(matrix); - for (j = n - 1; j < nn; j++) { - z = H.get(n - 1, j); - H.set(n - 1, j, q * z + p * H.get(n, j)); - H.set(n, j, q * H.get(n, j) - p * z); - } + if (!matrix.isSquare()) { + throw new Error('Matrix is not a square matrix'); + } - for (i = 0; i <= n; i++) { - z = H.get(i, n - 1); - H.set(i, n - 1, q * z + p * H.get(i, n)); - H.set(i, n, q * H.get(i, n) - p * z); - } + let n = matrix.columns; + let V = new Matrix(n, n); + let d = new Float64Array(n); + let e = new Float64Array(n); + let value = matrix; + let i, j; + let isSymmetric = false; - for (i = low; i <= high; i++) { - z = V.get(i, n - 1); - V.set(i, n - 1, q * z + p * V.get(i, n)); - V.set(i, n, q * V.get(i, n) - p * z); + if (assumeSymmetric) { + isSymmetric = true; + } else { + isSymmetric = matrix.isSymmetric(); + } + + if (isSymmetric) { + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V.set(i, j, value.get(i, j)); } - } else { - d[n - 1] = x + p; - d[n] = x + p; - e[n - 1] = z; - e[n] = -z; } - n = n - 2; - iter = 0; + tred2(n, e, d, V); + tql2(n, e, d, V); } else { - x = H.get(n, n); - y = 0; - w = 0; + let H = new Matrix(n, n); + let ort = new Float64Array(n); - if (l < n) { - y = H.get(n - 1, n - 1); - w = H.get(n, n - 1) * H.get(n - 1, n); + for (j = 0; j < n; j++) { + for (i = 0; i < n; i++) { + H.set(i, j, value.get(i, j)); + } } - if (iter === 10) { - exshift += x; + orthes(n, H, ort, V); + hqr2(n, e, d, V, H); + } - for (i = low; i <= n; i++) { - H.set(i, i, H.get(i, i) - x); - } + this.n = n; + this.e = e; + this.d = d; + this.V = V; + } - s = Math.abs(H.get(n, n - 1)) + Math.abs(H.get(n - 1, n - 2)); - x = y = 0.75 * s; - w = -0.4375 * s * s; - } + get realEigenvalues() { + return Array.from(this.d); + } - if (iter === 30) { - s = (y - x) / 2; - s = s * s + w; + get imaginaryEigenvalues() { + return Array.from(this.e); + } - if (s > 0) { - s = Math.sqrt(s); + get eigenvectorMatrix() { + return this.V; + } - if (y < x) { - s = -s; - } + get diagonalMatrix() { + let n = this.n; + let e = this.e; + let d = this.d; + let X = new Matrix(n, n); + let i, j; - s = x - w / ((y - x) / 2 + s); + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + X.set(i, j, 0); + } - for (i = low; i <= n; i++) { - H.set(i, i, H.get(i, i) - s); - } + X.set(i, i, d[i]); - exshift += s; - x = y = w = 0.964; - } + if (e[i] > 0) { + X.set(i, i + 1, e[i]); + } else if (e[i] < 0) { + X.set(i, i - 1, e[i]); } + } - iter = iter + 1; - m = n - 2; + return X; + } - while (m >= l) { - z = H.get(m, m); - r = x - z; - s = y - z; - p = (r * s - w) / H.get(m + 1, m) + H.get(m, m + 1); - q = H.get(m + 1, m + 1) - z - r - s; - r = H.get(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; - } + function tred2(n, e, d, V) { + let f, g, h, i, j, k, hh, scale; - if (Math.abs(H.get(m, m - 1)) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H.get(m - 1, m - 1)) + Math.abs(z) + Math.abs(H.get(m + 1, m + 1))))) { - break; - } + for (j = 0; j < n; j++) { + d[j] = V.get(n - 1, j); + } - m--; + 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.get(i - 1, j); + V.set(i, j, 0); + V.set(j, i, 0); + } + } else { + for (k = 0; k < i; k++) { + d[k] /= scale; + h += d[k] * d[k]; } - for (i = m + 2; i <= n; i++) { - H.set(i, i - 2, 0); + f = d[i - 1]; + g = Math.sqrt(h); - if (i > m + 2) { - H.set(i, i - 3, 0); - } + if (f > 0) { + g = -g; } - for (k = m; k <= n - 1; k++) { - notlast = k !== n - 1; + e[i] = scale * g; + h = h - f * g; + d[i - 1] = f - g; - if (k !== m) { - p = H.get(k, k - 1); - q = H.get(k + 1, k - 1); - r = notlast ? H.get(k + 2, k - 1) : 0; - x = Math.abs(p) + Math.abs(q) + Math.abs(r); + for (j = 0; j < i; j++) { + e[j] = 0; + } - if (x !== 0) { - p = p / x; - q = q / x; - r = r / x; - } - } + for (j = 0; j < i; j++) { + f = d[j]; + V.set(j, i, f); + g = e[j] + V.get(j, j) * f; - if (x === 0) { - break; + for (k = j + 1; k <= i - 1; k++) { + g += V.get(k, j) * d[k]; + e[k] += V.get(k, j) * f; } - s = Math.sqrt(p * p + q * q + r * r); + e[j] = g; + } - if (p < 0) { - s = -s; - } + f = 0; - if (s !== 0) { - if (k !== m) { - H.set(k, k - 1, -s * x); - } else if (l !== m) { - H.set(k, k - 1, -H.get(k, k - 1)); - } + for (j = 0; j < i; j++) { + e[j] /= h; + f += e[j] * d[j]; + } - p = p + s; - x = p / s; - y = q / s; - z = r / s; - q = q / p; - r = r / p; + hh = f / (h + h); - for (j = k; j < nn; j++) { - p = H.get(k, j) + q * H.get(k + 1, j); + for (j = 0; j < i; j++) { + e[j] -= hh * d[j]; + } - if (notlast) { - p = p + r * H.get(k + 2, j); - H.set(k + 2, j, H.get(k + 2, j) - p * z); - } + for (j = 0; j < i; j++) { + f = d[j]; + g = e[j]; - H.set(k, j, H.get(k, j) - p * x); - H.set(k + 1, j, H.get(k + 1, j) - p * y); - } + for (k = j; k <= i - 1; k++) { + V.set(k, j, V.get(k, j) - (f * e[k] + g * d[k])); + } - for (i = 0; i <= Math.min(n, k + 3); i++) { - p = x * H.get(i, k) + y * H.get(i, k + 1); + d[j] = V.get(i - 1, j); + V.set(i, j, 0); + } + } - if (notlast) { - p = p + z * H.get(i, k + 2); - H.set(i, k + 2, H.get(i, k + 2) - p * r); - } + d[i] = h; + } - H.set(i, k, H.get(i, k) - p); - H.set(i, k + 1, H.get(i, k + 1) - p * q); - } + for (i = 0; i < n - 1; i++) { + V.set(n - 1, i, V.get(i, i)); + V.set(i, i, 1); + h = d[i + 1]; - for (i = low; i <= high; i++) { - p = x * V.get(i, k) + y * V.get(i, k + 1); + if (h !== 0) { + for (k = 0; k <= i; k++) { + d[k] = V.get(k, i + 1) / h; + } - if (notlast) { - p = p + z * V.get(i, k + 2); - V.set(i, k + 2, V.get(i, k + 2) - p * r); - } + for (j = 0; j <= i; j++) { + g = 0; - V.set(i, k, V.get(i, k) - p); - V.set(i, k + 1, V.get(i, k + 1) - p * q); - } + for (k = 0; k <= i; k++) { + g += V.get(k, i + 1) * V.get(k, j); + } + + for (k = 0; k <= i; k++) { + V.set(k, j, V.get(k, j) - g * d[k]); } } } - } - if (norm === 0) { - return; + for (k = 0; k <= i; k++) { + V.set(k, i + 1, 0); + } } - for (n = nn - 1; n >= 0; n--) { - p = d[n]; - q = e[n]; - - if (q === 0) { - l = n; - H.set(n, n, 1); + for (j = 0; j < n; j++) { + d[j] = V.get(n - 1, j); + V.set(n - 1, j, 0); + } - for (i = n - 1; i >= 0; i--) { - w = H.get(i, i) - p; - r = 0; + V.set(n - 1, n - 1, 1); + e[0] = 0; + } - for (j = l; j <= n; j++) { - r = r + H.get(i, j) * H.get(j, n); - } + function tql2(n, e, d, V) { + let g, h, i, j, k, l, m, p, r, dl1, c, c2, c3, el1, s, s2; - if (e[i] < 0) { - z = w; - s = r; - } else { - l = i; + for (i = 1; i < n; i++) { + e[i - 1] = e[i]; + } - if (e[i] === 0) { - H.set(i, n, w !== 0 ? -r / w : -r / (eps * norm)); - } else { - x = H.get(i, i + 1); - y = H.get(i + 1, i); - q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; - t = (x * s - z * r) / q; - H.set(i, n, t); - H.set(i + 1, n, Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z); - } + e[n - 1] = 0; + let f = 0; + let tst1 = 0; + let eps = Number.EPSILON; - t = Math.abs(H.get(i, n)); + for (l = 0; l < n; l++) { + tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l])); + m = l; - if (eps * t * t > 1) { - for (j = i; j <= n; j++) { - H.set(j, n, H.get(j, n) / t); - } - } - } + while (m < n) { + if (Math.abs(e[m]) <= eps * tst1) { + break; } - } else if (q < 0) { - l = n - 1; - if (Math.abs(H.get(n, n - 1)) > Math.abs(H.get(n - 1, n))) { - H.set(n - 1, n - 1, q / H.get(n, n - 1)); - H.set(n - 1, n, -(H.get(n, n) - p) / H.get(n, n - 1)); - } else { - cdivres = cdiv(0, -H.get(n - 1, n), H.get(n - 1, n - 1) - p, q); - H.set(n - 1, n - 1, cdivres[0]); - H.set(n - 1, n, cdivres[1]); - } + m++; + } - H.set(n, n - 1, 0); - H.set(n, n, 1); + if (m > l) { - for (i = n - 2; i >= 0; i--) { - ra = 0; - sa = 0; + do { + g = d[l]; + p = (d[l + 1] - g) / (2 * e[l]); + r = hypotenuse(p, 1); - for (j = l; j <= n; j++) { - ra = ra + H.get(i, j) * H.get(j, n - 1); - sa = sa + H.get(i, j) * H.get(j, n); + if (p < 0) { + r = -r; } - w = H.get(i, i) - p; - - if (e[i] < 0) { - z = w; - r = ra; - s = sa; - } else { - l = i; + d[l] = e[l] / (p + r); + d[l + 1] = e[l] * (p + r); + dl1 = d[l + 1]; + h = g - d[l]; - if (e[i] === 0) { - cdivres = cdiv(-ra, -sa, w, q); - H.set(i, n - 1, cdivres[0]); - H.set(i, n, cdivres[1]); - } else { - x = H.get(i, i + 1); - y = H.get(i + 1, i); - vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; - vi = (d[i] - p) * 2 * q; + for (i = l + 2; i < n; i++) { + d[i] -= h; + } - if (vr === 0 && vi === 0) { - vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z)); - } + f = f + h; + p = d[m]; + c = 1; + c2 = c; + c3 = c; + el1 = e[l + 1]; + s = 0; + s2 = 0; - cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); - H.set(i, n - 1, cdivres[0]); - H.set(i, n, cdivres[1]); + 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]); - if (Math.abs(x) > Math.abs(z) + Math.abs(q)) { - H.set(i + 1, n - 1, (-ra - w * H.get(i, n - 1) + q * H.get(i, n)) / x); - H.set(i + 1, n, (-sa - w * H.get(i, n) - q * H.get(i, n - 1)) / x); - } else { - cdivres = cdiv(-r - y * H.get(i, n - 1), -s - y * H.get(i, n), z, q); - H.set(i + 1, n - 1, cdivres[0]); - H.set(i + 1, n, cdivres[1]); - } + for (k = 0; k < n; k++) { + h = V.get(k, i + 1); + V.set(k, i + 1, s * V.get(k, i) + c * h); + V.set(k, i, c * V.get(k, i) - s * h); } + } - t = Math.max(Math.abs(H.get(i, n - 1)), Math.abs(H.get(i, n))); + p = -s * s2 * c3 * el1 * e[l] / dl1; + e[l] = s * p; + d[l] = c * p; + } while (Math.abs(e[l]) > eps * tst1); + } - if (eps * t * t > 1) { - for (j = i; j <= n; j++) { - H.set(j, n - 1, H.get(j, n - 1) / t); - H.set(j, n, H.get(j, n) / t); - } - } - } - } - } + d[l] = d[l] + f; + e[l] = 0; } - for (i = 0; i < nn; i++) { - if (i < low || i > high) { - for (j = i; j < nn; j++) { - V.set(i, j, H.get(i, j)); + 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]; } } - } - for (j = nn - 1; j >= low; j--) { - for (i = low; i <= high; i++) { - z = 0; + if (k !== i) { + d[k] = d[i]; + d[i] = p; - for (k = low; k <= Math.min(j, high); k++) { - z = z + V.get(i, k) * H.get(k, j); + for (j = 0; j < n; j++) { + p = V.get(j, i); + V.set(j, i, V.get(j, k)); + V.set(j, k, p); } - - V.set(i, j, z); } } } - function cdiv(xr, xi, yr, yi) { - let 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]; - } - } + function orthes(n, H, ort, V) { + let low = 0; + let high = n - 1; + let f, g, h, i, j, m; + let scale; - class CholeskyDecomposition { - constructor(value) { - value = WrapperMatrix2D.checkMatrix(value); + for (m = low + 1; m <= high - 1; m++) { + scale = 0; - if (!value.isSymmetric()) { - throw new Error('Matrix is not symmetric'); + for (i = m; i <= high; i++) { + scale = scale + Math.abs(H.get(i, m - 1)); } - let a = value; - let dimension = a.rows; - let l = new Matrix(dimension, dimension); - let positiveDefinite = true; - let i, j, k; + if (scale !== 0) { + h = 0; - for (j = 0; j < dimension; j++) { - let d = 0; + for (i = high; i >= m; i--) { + ort[i] = H.get(i, m - 1) / scale; + h += ort[i] * ort[i]; + } - for (k = 0; k < j; k++) { - let s = 0; + g = Math.sqrt(h); - for (i = 0; i < k; i++) { - s += l.get(k, i) * l.get(j, i); + 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.get(i, j); } - s = (a.get(j, k) - s) / l.get(k, k); - l.set(j, k, s); - d = d + s * s; + f = f / h; + + for (i = m; i <= high; i++) { + H.set(i, j, H.get(i, j) - f * ort[i]); + } } - d = a.get(j, j) - d; - positiveDefinite &= d > 0; - l.set(j, j, Math.sqrt(Math.max(d, 0))); + for (i = 0; i <= high; i++) { + f = 0; - for (k = j + 1; k < dimension; k++) { - l.set(j, k, 0); + for (j = high; j >= m; j--) { + f += ort[j] * H.get(i, j); + } + + f = f / h; + + for (j = m; j <= high; j++) { + H.set(i, j, H.get(i, j) - f * ort[j]); + } } - } - this.L = l; - this.positiveDefinite = Boolean(positiveDefinite); + ort[m] = scale * ort[m]; + H.set(m, m - 1, scale * g); + } } - isPositiveDefinite() { - return this.positiveDefinite; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V.set(i, j, i === j ? 1 : 0); + } } - solve(value) { - value = WrapperMatrix2D.checkMatrix(value); - let l = this.L; - let dimension = l.rows; + for (m = high - 1; m >= low + 1; m--) { + if (H.get(m, m - 1) !== 0) { + for (i = m + 1; i <= high; i++) { + ort[i] = H.get(i, m - 1); + } - if (value.rows !== dimension) { - throw new Error('Matrix dimensions do not match'); - } + for (j = m; j <= high; j++) { + g = 0; - if (this.isPositiveDefinite() === false) { - throw new Error('Matrix is not positive definite'); - } + for (i = m; i <= high; i++) { + g += ort[i] * V.get(i, j); + } - let count = value.columns; - let B = value.clone(); - let i, j, k; + g = g / ort[m] / H.get(m, m - 1); - for (k = 0; k < dimension; k++) { - for (j = 0; j < count; j++) { - for (i = 0; i < k; i++) { - B.set(k, j, B.get(k, j) - B.get(i, j) * l.get(k, i)); + for (i = m; i <= high; i++) { + V.set(i, j, V.get(i, j) + g * ort[i]); } - - B.set(k, j, B.get(k, j) / l.get(k, k)); } } + } + } - for (k = dimension - 1; k >= 0; k--) { - for (j = 0; j < count; j++) { - for (i = k + 1; i < dimension; i++) { - B.set(k, j, B.get(k, j) - B.get(i, j) * l.get(i, k)); - } + function hqr2(nn, e, d, V, H) { + let n = nn - 1; + let low = 0; + let high = nn - 1; + let eps = Number.EPSILON; + let exshift = 0; + let norm = 0; + let p = 0; + let q = 0; + let r = 0; + let s = 0; + let z = 0; + let iter = 0; + let i, j, k, l, m, t, w, x, y; + let ra, sa, vr, vi; + let notlast, cdivres; - B.set(k, j, B.get(k, j) / l.get(k, k)); - } + for (i = 0; i < nn; i++) { + if (i < low || i > high) { + d[i] = H.get(i, i); + e[i] = 0; } - return B; - } - - get lowerTriangularMatrix() { - return this.L; + for (j = Math.max(i - 1, 0); j < nn; j++) { + norm = norm + Math.abs(H.get(i, j)); + } } - } + while (n >= low) { + l = n; - class nipals { - constructor(X) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - X = WrapperMatrix2D.checkMatrix(X); - let { - Y - } = options; - const { - scaleScores = false, - maxIterations = 1000, - terminationCriteria = 1e-10 - } = options; - let u; + while (l > low) { + s = Math.abs(H.get(l - 1, l - 1)) + Math.abs(H.get(l, l)); - if (Y) { - if (Array.isArray(Y) && typeof Y[0] === 'number') { - Y = Matrix.columnVector(Y); - } else { - Y = WrapperMatrix2D.checkMatrix(Y); + if (s === 0) { + s = norm; } - if (!Y.isColumnVector() || Y.rows !== X.rows) { - throw new Error('Y must be a column vector of length X.rows'); + if (Math.abs(H.get(l, l - 1)) < eps * s) { + break; } - u = Y; - } else { - u = X.getColumnVector(0); + l--; } - let diff = 1; - let t, q, w, tOld; + if (l === n) { + H.set(n, n, H.get(n, n) + exshift); + d[n] = H.get(n, n); + e[n] = 0; + n--; + iter = 0; + } else if (l === n - 1) { + w = H.get(n, n - 1) * H.get(n - 1, n); + p = (H.get(n - 1, n - 1) - H.get(n, n)) / 2; + q = p * p + w; + z = Math.sqrt(Math.abs(q)); + H.set(n, n, H.get(n, n) + exshift); + H.set(n - 1, n - 1, H.get(n - 1, n - 1) + exshift); + x = H.get(n, n); - for (let counter = 0; counter < maxIterations && diff > terminationCriteria; counter++) { - w = X.transpose().mmul(u).div(u.transpose().mmul(u).get(0, 0)); - w = w.div(w.norm()); - t = X.mmul(w).div(w.transpose().mmul(w).get(0, 0)); + if (q >= 0) { + z = p >= 0 ? p + z : p - z; + d[n - 1] = x + z; + d[n] = d[n - 1]; - if (counter > 0) { - diff = t.clone().sub(tOld).pow(2).sum(); - } + if (z !== 0) { + d[n] = x - w / z; + } - tOld = t.clone(); + e[n - 1] = 0; + e[n] = 0; + x = H.get(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; - if (Y) { - q = Y.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0)); - q = q.div(q.norm()); - u = Y.mmul(q).div(q.transpose().mmul(q).get(0, 0)); + for (j = n - 1; j < nn; j++) { + z = H.get(n - 1, j); + H.set(n - 1, j, q * z + p * H.get(n, j)); + H.set(n, j, q * H.get(n, j) - p * z); + } + + for (i = 0; i <= n; i++) { + z = H.get(i, n - 1); + H.set(i, n - 1, q * z + p * H.get(i, n)); + H.set(i, n, q * H.get(i, n) - p * z); + } + + for (i = low; i <= high; i++) { + z = V.get(i, n - 1); + V.set(i, n - 1, q * z + p * V.get(i, n)); + V.set(i, n, q * V.get(i, n) - p * z); + } } else { - u = t; + d[n - 1] = x + p; + d[n] = x + p; + e[n - 1] = z; + e[n] = -z; } - } - if (Y) { - let p = X.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0)); - p = p.div(p.norm()); - let xResidual = X.clone().sub(t.clone().mmul(p.transpose())); - let residual = u.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0)); - let yResidual = Y.clone().sub(t.clone().mulS(residual.get(0, 0)).mmul(q.transpose())); - this.t = t; - this.p = p.transpose(); - this.w = w.transpose(); - this.q = q; - this.u = u; - this.s = t.transpose().mmul(t); - this.xResidual = xResidual; - this.yResidual = yResidual; - this.betas = residual; + n = n - 2; + iter = 0; } else { - this.w = w.transpose(); - this.s = t.transpose().mmul(t).sqrt(); + x = H.get(n, n); + y = 0; + w = 0; - if (scaleScores) { - this.t = t.clone().div(this.s.get(0, 0)); - } else { - this.t = t; + if (l < n) { + y = H.get(n - 1, n - 1); + w = H.get(n, n - 1) * H.get(n - 1, n); } - this.xResidual = X.sub(t.mmul(w.transpose())); - } - } + if (iter === 10) { + exshift += x; - } + for (i = low; i <= n; i++) { + H.set(i, i, H.get(i, i) - x); + } + s = Math.abs(H.get(n, n - 1)) + Math.abs(H.get(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; - var MatrixLib = /*#__PURE__*/Object.freeze({ - __proto__: null, - AbstractMatrix: AbstractMatrix, - 'default': Matrix, - Matrix: Matrix, - wrap: wrap, - WrapperMatrix1D: WrapperMatrix1D, - WrapperMatrix2D: WrapperMatrix2D, - solve: solve, - inverse: inverse, - determinant: determinant, - linearDependencies: linearDependencies, - pseudoInverse: pseudoInverse, - covariance: covariance, - correlation: correlation, - SingularValueDecomposition: SingularValueDecomposition, - SVD: SingularValueDecomposition, - EigenvalueDecomposition: EigenvalueDecomposition, - EVD: EigenvalueDecomposition, - CholeskyDecomposition: CholeskyDecomposition, - CHO: CholeskyDecomposition, - LuDecomposition: LuDecomposition, - LU: LuDecomposition, - QrDecomposition: QrDecomposition, - QR: QrDecomposition, - Nipals: nipals, - NIPALS: nipals, - MatrixColumnView: MatrixColumnView, - MatrixColumnSelectionView: MatrixColumnSelectionView, - MatrixFlipColumnView: MatrixFlipColumnView, - MatrixFlipRowView: MatrixFlipRowView, - MatrixRowView: MatrixRowView, - MatrixRowSelectionView: MatrixRowSelectionView, - MatrixSelectionView: MatrixSelectionView, - MatrixSubView: MatrixSubView, - MatrixTransposeView: MatrixTransposeView - }); + if (s > 0) { + s = Math.sqrt(s); - /** - * Computes the mean of the given values - * @param {Array} input - * @return {number} - */ + if (y < x) { + s = -s; + } - function sum(input) { - if (!src(input)) { - throw new TypeError('input must be an array'); - } + s = x - w / ((y - x) / 2 + s); - if (input.length === 0) { - throw new TypeError('input must not be empty'); - } + for (i = low; i <= n; i++) { + H.set(i, i, H.get(i, i) - s); + } - var sumValue = 0; + exshift += s; + x = y = w = 0.964; + } + } - for (var i = 0; i < input.length; i++) { - sumValue += input[i]; - } + iter = iter + 1; + m = n - 2; - return sumValue; - } + while (m >= l) { + z = H.get(m, m); + r = x - z; + s = y - z; + p = (r * s - w) / H.get(m + 1, m) + H.get(m, m + 1); + q = H.get(m + 1, m + 1) - z - r - s; + r = H.get(m + 2, m + 1); + s = Math.abs(p) + Math.abs(q) + Math.abs(r); + p = p / s; + q = q / s; + r = r / s; - /** - * Computes the mean of the given values - * @param {Array} input - * @return {number} - */ + if (m === l) { + break; + } - function mean(input) { - return sum(input) / input.length; - } + if (Math.abs(H.get(m, m - 1)) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H.get(m - 1, m - 1)) + Math.abs(z) + Math.abs(H.get(m + 1, m + 1))))) { + break; + } - /** - * @private - * return an array of probabilities of each class - * @param {Array} array - contains the classes - * @param {number} numberOfClasses - * @return {Matrix} - rowVector of probabilities. - */ + m--; + } - function toDiscreteDistribution(array, numberOfClasses) { - let counts = new Array(numberOfClasses).fill(0); + for (i = m + 2; i <= n; i++) { + H.set(i, i - 2, 0); - for (let i = 0; i < array.length; ++i) { - counts[array[i]] += 1 / array.length; - } + if (i > m + 2) { + H.set(i, i - 3, 0); + } + } - return Matrix.rowVector(counts); - } - /** - * @private - * Retrieves the impurity of array of predictions - * @param {Array} array - predictions. - * @return {number} Gini impurity - */ + for (k = m; k <= n - 1; k++) { + notlast = k !== n - 1; - function giniImpurity(array) { - if (array.length === 0) { - return 0; - } + if (k !== m) { + p = H.get(k, k - 1); + q = H.get(k + 1, k - 1); + r = notlast ? H.get(k + 2, k - 1) : 0; + x = Math.abs(p) + Math.abs(q) + Math.abs(r); - let probabilities = toDiscreteDistribution(array, getNumberOfClasses(array)).getRow(0); - let sum = 0.0; + if (x !== 0) { + p = p / x; + q = q / x; + r = r / x; + } + } - for (let i = 0; i < probabilities.length; ++i) { - sum += probabilities[i] * probabilities[i]; - } + if (x === 0) { + break; + } - return 1 - sum; - } - /** - * @private - * Return the number of classes given the array of predictions. - * @param {Array} array - predictions. - * @return {number} Number of classes. - */ + s = Math.sqrt(p * p + q * q + r * r); - function getNumberOfClasses(array) { - return array.filter(function (val, i, arr) { - return arr.indexOf(val) === i; - }).map(val => val + 1).reduce((a, b) => Math.max(a, b)); - } - /** - * @private - * Calculates the Gini Gain of an array of predictions and those predictions splitted by a feature. - * @param {Array} array - Predictions - * @param {object} splitted - Object with elements "greater" and "lesser" that contains an array of predictions splitted. - * @return {number} - Gini Gain. - */ + if (p < 0) { + s = -s; + } - function giniGain(array, splitted) { - let splitsImpurity = 0.0; - let splits = ['greater', 'lesser']; + if (s !== 0) { + if (k !== m) { + H.set(k, k - 1, -s * x); + } else if (l !== m) { + H.set(k, k - 1, -H.get(k, k - 1)); + } - for (let i = 0; i < splits.length; ++i) { - let currentSplit = splitted[splits[i]]; - splitsImpurity += giniImpurity(currentSplit) * currentSplit.length / array.length; - } + p = p + s; + x = p / s; + y = q / s; + z = r / s; + q = q / p; + r = r / p; - return giniImpurity(array) - splitsImpurity; - } - /** - * @private - * Calculates the squared error of a predictions values. - * @param {Array} array - predictions values - * @return {number} squared error. - */ + for (j = k; j < nn; j++) { + p = H.get(k, j) + q * H.get(k + 1, j); - function squaredError(array) { - let l = array.length; - let m = mean(array); - let error = 0.0; + if (notlast) { + p = p + r * H.get(k + 2, j); + H.set(k + 2, j, H.get(k + 2, j) - p * z); + } - for (let i = 0; i < l; ++i) { - let currentElement = array[i]; - error += (currentElement - m) * (currentElement - m); - } + H.set(k, j, H.get(k, j) - p * x); + H.set(k + 1, j, H.get(k + 1, j) - p * y); + } - return error; - } - /** - * @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. - */ + for (i = 0; i <= Math.min(n, k + 3); i++) { + p = x * H.get(i, k) + y * H.get(i, k + 1); - function regressionError(array, splitted) { - let error = 0.0; - let splits = ['greater', 'lesser']; + if (notlast) { + p = p + z * H.get(i, k + 2); + H.set(i, k + 2, H.get(i, k + 2) - p * r); + } - for (let i = 0; i < splits.length; ++i) { - let currentSplit = splitted[splits[i]]; - error += squaredError(currentSplit); - } + H.set(i, k, H.get(i, k) - p); + H.set(i, k + 1, H.get(i, k + 1) - p * q); + } - 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 (i = low; i <= high; i++) { + p = x * V.get(i, k) + y * V.get(i, k + 1); - function matrixSplitter(X, y, column, value) { - let lesserX = []; - let greaterX = []; - let lesserY = []; - let greaterY = []; + if (notlast) { + p = p + z * V.get(i, k + 2); + V.set(i, k + 2, V.get(i, k + 2) - p * r); + } - for (let i = 0; i < X.rows; ++i) { - if (X.get(i, column) < value) { - lesserX.push(X.getRow(i)); - lesserY.push(y[i]); - } else { - greaterX.push(X.getRow(i)); - greaterY.push(y[i]); + V.set(i, k, V.get(i, k) - p); + V.set(i, k + 1, V.get(i, k + 1) - p * q); + } + } + } } } - return { - greaterX: greaterX, - greaterY: greaterY, - lesserX: lesserX, - lesserY: lesserY - }; - } - /** - * @private - * Calculates the mean between two values - * @param {number} a - * @param {number} b - * @return {number} - */ - - function mean$1(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: ".concat(a.length, " is different from b: ").concat(b.length)); + if (norm === 0) { + return; } - let ret = new Array(a.length); - - for (let i = 0; i < a.length; ++i) { - ret[i] = [a[i], b[i]]; - } + for (n = nn - 1; n >= 0; n--) { + p = d[n]; + q = e[n]; - return ret; - } + if (q === 0) { + l = n; + H.set(n, n, 1); - const gainFunctions = { - gini: giniGain, - regression: regressionError - }; - const splitFunctions = { - mean: mean$1 - }; - 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; - } - /** - * @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. - */ + for (i = n - 1; i >= 0; i--) { + w = H.get(i, i) - p; + r = 0; + for (j = l; j <= n; j++) { + r = r + H.get(i, j) * H.get(j, n); + } - bestSplit(XTranspose, y) { - // Depending in the node tree class, we set the variables to check information gain (to classify) - // or error (for regression) - let bestGain = this.kind === 'classifier' ? -Infinity : Infinity; - let check = this.kind === 'classifier' ? (a, b) => a > b : (a, b) => a < b; - let maxColumn; - let maxValue; + if (e[i] < 0) { + z = w; + s = r; + } else { + l = i; - for (let i = 0; i < XTranspose.rows; ++i) { - let currentFeature = XTranspose.getRow(i); - let splitValues = this.featureSplit(currentFeature, y); + if (e[i] === 0) { + H.set(i, n, w !== 0 ? -r / w : -r / (eps * norm)); + } else { + x = H.get(i, i + 1); + y = H.get(i + 1, i); + q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; + t = (x * s - z * r) / q; + H.set(i, n, t); + H.set(i + 1, n, Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z); + } - for (let j = 0; j < splitValues.length; ++j) { - let currentSplitVal = splitValues[j]; - let splitted = this.split(currentFeature, y, currentSplitVal); - let gain = gainFunctions[this.gainFunction](y, splitted); + t = Math.abs(H.get(i, n)); - if (check(gain, bestGain)) { - maxColumn = i; - maxValue = currentSplitVal; - bestGain = gain; + if (eps * t * t > 1) { + for (j = i; j <= n; j++) { + H.set(j, n, H.get(j, n) / t); + } + } } } - } - - 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} - */ - - - split(x, y, splitValue) { - let lesser = []; - let greater = []; + } else if (q < 0) { + l = n - 1; - for (let i = 0; i < x.length; ++i) { - if (x[i] < splitValue) { - lesser.push(y[i]); + if (Math.abs(H.get(n, n - 1)) > Math.abs(H.get(n - 1, n))) { + H.set(n - 1, n - 1, q / H.get(n, n - 1)); + H.set(n - 1, n, -(H.get(n, n) - p) / H.get(n, n - 1)); } else { - greater.push(y[i]); + cdivres = cdiv(0, -H.get(n - 1, n), H.get(n - 1, n - 1) - p, q); + H.set(n - 1, n - 1, cdivres[0]); + H.set(n - 1, n, cdivres[1]); } - } - - 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. - */ + H.set(n, n - 1, 0); + H.set(n, n, 1); - featureSplit(x, y) { - let splitValues = []; - let arr = zip(x, y); - arr.sort(function (a, b) { - return a[0] - b[0]; - }); + for (i = n - 2; i >= 0; i--) { + ra = 0; + sa = 0; - for (let 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 (j = l; j <= n; j++) { + ra = ra + H.get(i, j) * H.get(j, n - 1); + sa = sa + H.get(i, j) * H.get(j, n); + } - return splitValues; - } - /** - * @private - * Calculate the predictions of a leaf tree node given the training labels or values - * @param {Array} y - */ + w = H.get(i, i) - p; + if (e[i] < 0) { + z = w; + r = ra; + s = sa; + } else { + l = i; - calculatePrediction(y) { - if (this.kind === 'classifier') { - this.distribution = toDiscreteDistribution(y, getNumberOfClasses(y)); + if (e[i] === 0) { + cdivres = cdiv(-ra, -sa, w, q); + H.set(i, n - 1, cdivres[0]); + H.set(i, n, cdivres[1]); + } else { + x = H.get(i, i + 1); + y = H.get(i + 1, i); + vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; + vi = (d[i] - p) * 2 * q; - if (this.distribution.columns === 0) { - throw new TypeError('Error on calculate the prediction'); - } - } else { - this.distribution = mean(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. - */ + 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.set(i, n - 1, cdivres[0]); + H.set(i, n, cdivres[1]); - train(X, y, currentDepth, parentGain) { - if (X.rows <= this.minNumSamples) { - this.calculatePrediction(y); - return; - } + if (Math.abs(x) > Math.abs(z) + Math.abs(q)) { + H.set(i + 1, n - 1, (-ra - w * H.get(i, n - 1) + q * H.get(i, n)) / x); + H.set(i + 1, n, (-sa - w * H.get(i, n) - q * H.get(i, n - 1)) / x); + } else { + cdivres = cdiv(-r - y * H.get(i, n - 1), -s - y * H.get(i, n), z, q); + H.set(i + 1, n - 1, cdivres[0]); + H.set(i + 1, n, cdivres[1]); + } + } - if (parentGain === undefined) parentGain = 0.0; - let XTranspose = X.transpose(); - let split = this.bestSplit(XTranspose, y); - this.splitValue = split.maxValue; - this.splitColumn = split.maxColumn; - this.gain = split.maxGain; - let splittedMatrix = matrixSplitter(X, y, this.splitColumn, this.splitValue); + t = Math.max(Math.abs(H.get(i, n - 1)), Math.abs(H.get(i, n))); - 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); - let lesserX = new Matrix(splittedMatrix.lesserX); - let greaterX = new Matrix(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); + if (eps * t * t > 1) { + for (j = i; j <= n; j++) { + H.set(j, n - 1, H.get(j, n - 1) / t); + H.set(j, n, H.get(j, n) / t); + } + } + } + } } } - /** - * @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); + for (i = 0; i < nn; i++) { + if (i < low || i > high) { + for (j = i; j < nn; j++) { + V.set(i, j, H.get(i, j)); } } - - 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. - */ + for (j = nn - 1; j >= low; j--) { + for (i = low; i <= high; i++) { + z = 0; - setNodeParameters(node) { - if (node.distribution !== undefined) { - this.distribution = node.distribution.constructor === Array ? new Matrix(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); - - if (node.left !== {}) { - this.left.setNodeParameters(node.left); + for (k = low; k <= Math.min(j, high); k++) { + z = z + V.get(i, k) * H.get(k, j); } - if (node.right !== {}) { - this.right.setNodeParameters(node.right); - } + V.set(i, j, z); } } + } + + function cdiv(xr, xi, yr, yi) { + let 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]; + } } - const defaultOptions = { - gainFunction: 'gini', - splitFunction: 'mean', - minNumSamples: 3, - maxDepth: Infinity - }; - class 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(model.options); - this.root.setNodeParameters(model.root); - } else { - this.options = Object.assign({}, defaultOptions, options); - this.options.kind = 'classifier'; + class CholeskyDecomposition { + constructor(value) { + value = WrapperMatrix2D.checkMatrix(value); + + if (!value.isSymmetric()) { + throw new Error('Matrix is not symmetric'); } - } - /** - * Train the decision tree with the given training set and labels. - * @param {Matrix|MatrixTransposeView|Array} trainingSet - * @param {Array} trainingLabels - */ + let a = value; + let dimension = a.rows; + let l = new Matrix(dimension, dimension); + let positiveDefinite = true; + let i, j, k; - train(trainingSet, trainingLabels) { - this.root = new TreeNode(this.options); - trainingSet = Matrix.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 - */ + for (j = 0; j < dimension; j++) { + let d = 0; + for (k = 0; k < j; k++) { + let s = 0; - predict(toPredict) { - toPredict = Matrix.checkMatrix(toPredict); - let predictions = new Array(toPredict.rows); + for (i = 0; i < k; i++) { + s += l.get(k, i) * l.get(j, i); + } - for (let i = 0; i < toPredict.rows; ++i) { - predictions[i] = this.root.classify(toPredict.getRow(i)).maxRowIndex(0)[1]; + s = (a.get(j, k) - s) / l.get(k, k); + l.set(j, k, s); + d = d + s * s; + } + + d = a.get(j, j) - d; + positiveDefinite &= d > 0; + l.set(j, j, Math.sqrt(Math.max(d, 0))); + + for (k = j + 1; k < dimension; k++) { + l.set(j, k, 0); + } } - return predictions; + this.L = l; + this.positiveDefinite = Boolean(positiveDefinite); } - /** - * Export the current model to JSON. - * @return {object} - Current model. - */ - - - toJSON() { - return { - options: this.options, - root: this.root, - name: 'DTClassifier' - }; - } - /** - * 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: ".concat(model.name)); - } - return new DecisionTreeClassifier(true, model); + isPositiveDefinite() { + return this.positiveDefinite; } - } + solve(value) { + value = WrapperMatrix2D.checkMatrix(value); + let l = this.L; + let dimension = l.rows; - const defaultOptions$1 = { - gainFunction: 'regression', - splitFunction: 'mean', - minNumSamples: 3, - maxDepth: Infinity - }; - class 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(model.options); - this.root.setNodeParameters(model.root); - } else { - this.options = Object.assign({}, defaultOptions$1, options); - this.options.kind = 'regression'; + if (value.rows !== dimension) { + throw new Error('Matrix dimensions do not match'); } - } - /** - * 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(this.options); - - if (typeof trainingSet[0] !== 'undefined' && trainingSet[0].length === undefined) { - trainingSet = Matrix.columnVector(trainingSet); - } else { - trainingSet = Matrix.checkMatrix(trainingSet); + if (this.isPositiveDefinite() === false) { + throw new Error('Matrix is not positive definite'); } - this.root.train(trainingSet, trainingValues, 0); - } - /** - * Predicts the values given the matrix to predict. - * @param {Matrix|MatrixTransposeView|Array} toPredict - * @return {Array} predictions - */ + let count = value.columns; + let B = value.clone(); + let i, j, k; + for (k = 0; k < dimension; k++) { + for (j = 0; j < count; j++) { + for (i = 0; i < k; i++) { + B.set(k, j, B.get(k, j) - B.get(i, j) * l.get(k, i)); + } - predict(toPredict) { - if (typeof toPredict[0] !== 'undefined' && toPredict[0].length === undefined) { - toPredict = Matrix.columnVector(toPredict); + B.set(k, j, B.get(k, j) / l.get(k, k)); + } } - toPredict = Matrix.checkMatrix(toPredict); - let predictions = new Array(toPredict.rows); + for (k = dimension - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + for (i = k + 1; i < dimension; i++) { + B.set(k, j, B.get(k, j) - B.get(i, j) * l.get(i, k)); + } - for (let i = 0; i < toPredict.rows; ++i) { - predictions[i] = this.root.classify(toPredict.getRow(i)); + B.set(k, j, B.get(k, j) / l.get(k, k)); + } } - return predictions; + return B; } - /** - * Export the current model to JSON. - * @return {object} - Current model. - */ - - toJSON() { - return { - options: this.options, - root: this.root, - name: 'DTRegression' - }; + get lowerTriangularMatrix() { + return this.L; } - /** - * 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:".concat(model.name)); - } + class nipals { + constructor(X, options = {}) { + X = WrapperMatrix2D.checkMatrix(X); + let { + Y + } = options; + const { + scaleScores = false, + maxIterations = 1000, + terminationCriteria = 1e-10 + } = options; + let u; - return new DecisionTreeRegression(true, model); - } + if (Y) { + if (Array.isArray(Y) && typeof Y[0] === 'number') { + Y = Matrix.columnVector(Y); + } else { + Y = WrapperMatrix2D.checkMatrix(Y); + } - } + if (!Y.isColumnVector() || Y.rows !== X.rows) { + throw new Error('Y must be a column vector of length X.rows'); + } - const SMALLEST_UNSAFE_INTEGER = 0x20000000000000; - const LARGEST_SAFE_INTEGER = SMALLEST_UNSAFE_INTEGER - 1; - const UINT32_MAX = -1 >>> 0; - const UINT32_SIZE = UINT32_MAX + 1; - const INT32_SIZE = UINT32_SIZE / 2; - const INT32_MAX = INT32_SIZE - 1; - const UINT21_SIZE = 1 << 21; - const UINT21_MAX = UINT21_SIZE - 1; - /** - * Returns a value within [-0x80000000, 0x7fffffff] - */ + u = Y; + } else { + u = X.getColumnVector(0); + } - function int32(engine) { - return engine.next() | 0; - } + let diff = 1; + let t, q, w, tOld; - function add(distribution, addend) { - if (addend === 0) { - return distribution; - } else { - return engine => distribution(engine) + addend; - } - } - /** - * Returns a value within [-0x20000000000000, 0x1fffffffffffff] - */ + for (let counter = 0; counter < maxIterations && diff > terminationCriteria; counter++) { + w = X.transpose().mmul(u).div(u.transpose().mmul(u).get(0, 0)); + w = w.div(w.norm()); + t = X.mmul(w).div(w.transpose().mmul(w).get(0, 0)); + if (counter > 0) { + diff = t.clone().sub(tOld).pow(2).sum(); + } - function int53(engine) { - const high = engine.next() | 0; - const low = engine.next() >>> 0; - return (high & UINT21_MAX) * UINT32_SIZE + low + (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0); - } - /** - * Returns a value within [-0x20000000000000, 0x20000000000000] - */ + tOld = t.clone(); + if (Y) { + q = Y.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0)); + q = q.div(q.norm()); + u = Y.mmul(q).div(q.transpose().mmul(q).get(0, 0)); + } else { + u = t; + } + } - function int53Full(engine) { - while (true) { - const high = engine.next() | 0; + if (Y) { + let p = X.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0)); + p = p.div(p.norm()); + let xResidual = X.clone().sub(t.clone().mmul(p.transpose())); + let residual = u.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0)); + let yResidual = Y.clone().sub(t.clone().mulS(residual.get(0, 0)).mmul(q.transpose())); + this.t = t; + this.p = p.transpose(); + this.w = w.transpose(); + this.q = q; + this.u = u; + this.s = t.transpose().mmul(t); + this.xResidual = xResidual; + this.yResidual = yResidual; + this.betas = residual; + } else { + this.w = w.transpose(); + this.s = t.transpose().mmul(t).sqrt(); - if (high & 0x400000) { - if ((high & 0x7fffff) === 0x400000 && (engine.next() | 0) === 0) { - return SMALLEST_UNSAFE_INTEGER; + if (scaleScores) { + this.t = t.clone().div(this.s.get(0, 0)); + } else { + this.t = t; } - } else { - const low = engine.next() >>> 0; - return (high & UINT21_MAX) * UINT32_SIZE + low + (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0); + + this.xResidual = X.sub(t.mmul(w.transpose())); } } - } - /** - * Returns a value within [0, 0xffffffff] - */ - - function uint32(engine) { - return engine.next() >>> 0; } - /** - * Returns a value within [0, 0x1fffffffffffff] - */ + var MatrixLib = /*#__PURE__*/Object.freeze({ + __proto__: null, + AbstractMatrix: AbstractMatrix, + 'default': Matrix, + Matrix: Matrix, + wrap: wrap, + WrapperMatrix1D: WrapperMatrix1D, + WrapperMatrix2D: WrapperMatrix2D, + solve: solve, + inverse: inverse, + determinant: determinant, + linearDependencies: linearDependencies, + pseudoInverse: pseudoInverse, + covariance: covariance, + correlation: correlation, + SingularValueDecomposition: SingularValueDecomposition, + SVD: SingularValueDecomposition, + EigenvalueDecomposition: EigenvalueDecomposition, + EVD: EigenvalueDecomposition, + CholeskyDecomposition: CholeskyDecomposition, + CHO: CholeskyDecomposition, + LuDecomposition: LuDecomposition, + LU: LuDecomposition, + QrDecomposition: QrDecomposition, + QR: QrDecomposition, + Nipals: nipals, + NIPALS: nipals, + MatrixColumnView: MatrixColumnView, + MatrixColumnSelectionView: MatrixColumnSelectionView, + MatrixFlipColumnView: MatrixFlipColumnView, + MatrixFlipRowView: MatrixFlipRowView, + MatrixRowView: MatrixRowView, + MatrixRowSelectionView: MatrixRowSelectionView, + MatrixSelectionView: MatrixSelectionView, + MatrixSubView: MatrixSubView, + MatrixTransposeView: MatrixTransposeView + }); - function uint53(engine) { - const high = engine.next() & UINT21_MAX; - const low = engine.next() >>> 0; - return high * UINT32_SIZE + low; - } - /** - * Returns a value within [0, 0x20000000000000] - */ - + const toString$1 = Object.prototype.toString; + function isAnyArray$1(object) { + return toString$1.call(object).endsWith('Array]'); + } - function uint53Full(engine) { - while (true) { - const high = engine.next() | 0; + function sum(input) { + if (!isAnyArray$1(input)) { + throw new TypeError('input must be an array'); + } - if (high & UINT21_SIZE) { - if ((high & UINT21_MAX) === 0 && (engine.next() | 0) === 0) { - return SMALLEST_UNSAFE_INTEGER; - } - } else { - const low = engine.next() >>> 0; - return (high & UINT21_MAX) * UINT32_SIZE + low; - } + if (input.length === 0) { + throw new TypeError('input must not be empty'); } - } - function isPowerOfTwoMinusOne(value) { - return (value + 1 & value) === 0; - } + var sumValue = 0; - function bitmask(masking) { - return engine => engine.next() & masking; + for (var i = 0; i < input.length; i++) { + sumValue += input[i]; + } + + return sumValue; } - function downscaleToLoopCheckedRange(range) { - const extendedRange = range + 1; - const maximum = extendedRange * Math.floor(UINT32_SIZE / extendedRange); - return engine => { - let value = 0; + function mean(input) { + return sum(input) / input.length; + } - do { - value = engine.next() >>> 0; - } while (value >= maximum); + /** + * @private + * return an array of probabilities of each class + * @param {Array} array - contains the classes + * @param {number} numberOfClasses + * @return {Matrix} - rowVector of probabilities. + */ - return value % extendedRange; - }; - } + function toDiscreteDistribution(array, numberOfClasses) { + let counts = new Array(numberOfClasses).fill(0); - function downscaleToRange(range) { - if (isPowerOfTwoMinusOne(range)) { - return bitmask(range); - } else { - return downscaleToLoopCheckedRange(range); + for (let i = 0; i < array.length; ++i) { + counts[array[i]] += 1 / array.length; } - } - function isEvenlyDivisibleByMaxInt32(value) { - return (value | 0) === 0; + return Matrix.rowVector(counts); } + /** + * @private + * Retrieves the impurity of array of predictions + * @param {Array} array - predictions. + * @return {number} Gini impurity + */ - function upscaleWithHighMasking(masking) { - return engine => { - const high = engine.next() & masking; - const low = engine.next() >>> 0; - return high * UINT32_SIZE + low; - }; - } + function giniImpurity(array) { + if (array.length === 0) { + return 0; + } - function upscaleToLoopCheckedRange(extendedRange) { - const maximum = extendedRange * Math.floor(SMALLEST_UNSAFE_INTEGER / extendedRange); - return engine => { - let ret = 0; + let probabilities = toDiscreteDistribution(array, getNumberOfClasses(array)).getRow(0); + let sum = 0.0; - do { - const high = engine.next() & UINT21_MAX; - const low = engine.next() >>> 0; - ret = high * UINT32_SIZE + low; - } while (ret >= maximum); + for (let i = 0; i < probabilities.length; ++i) { + sum += probabilities[i] * probabilities[i]; + } - return ret % extendedRange; - }; + return 1 - sum; } + /** + * @private + * Return the number of classes given the array of predictions. + * @param {Array} array - predictions. + * @return {number} Number of classes. + */ - function upscaleWithinU53(range) { - const extendedRange = range + 1; + function getNumberOfClasses(array) { + return array.filter(function (val, i, arr) { + return arr.indexOf(val) === i; + }).map(val => val + 1).reduce((a, b) => Math.max(a, b)); + } + /** + * @private + * Calculates the Gini Gain of an array of predictions and those predictions splitted by a feature. + * @param {Array} array - Predictions + * @param {object} splitted - Object with elements "greater" and "lesser" that contains an array of predictions splitted. + * @return {number} - Gini Gain. + */ - if (isEvenlyDivisibleByMaxInt32(extendedRange)) { - const highRange = (extendedRange / UINT32_SIZE | 0) - 1; + function giniGain(array, splitted) { + let splitsImpurity = 0.0; + let splits = ['greater', 'lesser']; - if (isPowerOfTwoMinusOne(highRange)) { - return upscaleWithHighMasking(highRange); - } + for (let i = 0; i < splits.length; ++i) { + let currentSplit = splitted[splits[i]]; + splitsImpurity += giniImpurity(currentSplit) * currentSplit.length / array.length; } - return upscaleToLoopCheckedRange(extendedRange); + return giniImpurity(array) - splitsImpurity; } + /** + * @private + * Calculates the squared error of a predictions values. + * @param {Array} array - predictions values + * @return {number} squared error. + */ - function upscaleWithinI53AndLoopCheck(min, max) { - return engine => { - let ret = 0; + function squaredError(array) { + let l = array.length; + let m = mean(array); + let error = 0.0; - do { - const high = engine.next() | 0; - const low = engine.next() >>> 0; - ret = (high & UINT21_MAX) * UINT32_SIZE + low + (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0); - } while (ret < min || ret > max); + for (let i = 0; i < l; ++i) { + let currentElement = array[i]; + error += (currentElement - m) * (currentElement - m); + } - return ret; - }; + return error; } - /** - * Returns a Distribution to return a value within [min, max] - * @param min The minimum integer value, inclusive. No less than -0x20000000000000. - * @param max The maximum integer value, inclusive. No greater than 0x20000000000000. + /** + * @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) { + let error = 0.0; + let splits = ['greater', 'lesser']; - function integer(min, max) { - min = Math.floor(min); - max = Math.floor(max); - - if (min < -SMALLEST_UNSAFE_INTEGER || !isFinite(min)) { - throw new RangeError("Expected min to be at least ".concat(-SMALLEST_UNSAFE_INTEGER)); - } else if (max > SMALLEST_UNSAFE_INTEGER || !isFinite(max)) { - throw new RangeError("Expected max to be at most ".concat(SMALLEST_UNSAFE_INTEGER)); + for (let i = 0; i < splits.length; ++i) { + let currentSplit = splitted[splits[i]]; + error += squaredError(currentSplit); } - const range = max - min; + 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. + */ - if (range <= 0 || !isFinite(range)) { - return () => min; - } else if (range === UINT32_MAX) { - if (min === 0) { - return uint32; + function matrixSplitter(X, y, column, value) { + let lesserX = []; + let greaterX = []; + let lesserY = []; + let greaterY = []; + + for (let i = 0; i < X.rows; ++i) { + if (X.get(i, column) < value) { + lesserX.push(X.getRow(i)); + lesserY.push(y[i]); } else { - return add(int32, min + INT32_SIZE); + greaterX.push(X.getRow(i)); + greaterY.push(y[i]); } - } else if (range < UINT32_MAX) { - return add(downscaleToRange(range), min); - } else if (range === LARGEST_SAFE_INTEGER) { - return add(uint53, min); - } else if (range < LARGEST_SAFE_INTEGER) { - return add(upscaleWithinU53(range), min); - } else if (max - 1 - min === LARGEST_SAFE_INTEGER) { - return add(uint53Full, min); - } else if (min === -SMALLEST_UNSAFE_INTEGER && max === SMALLEST_UNSAFE_INTEGER) { - return int53Full; - } else if (min === -SMALLEST_UNSAFE_INTEGER && max === LARGEST_SAFE_INTEGER) { - return int53; - } else if (min === -LARGEST_SAFE_INTEGER && max === SMALLEST_UNSAFE_INTEGER) { - return add(int53, 1); - } else if (max === SMALLEST_UNSAFE_INTEGER) { - return add(upscaleWithinI53AndLoopCheck(min - 1, max - 1), 1); - } else { - return upscaleWithinI53AndLoopCheck(min, max); } - } - // has 2**x chars, for faster uniform distribution - - const DEFAULT_STRING_POOL = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"; + return { + greaterX: greaterX, + greaterY: greaterY, + lesserX: lesserX, + lesserY: lesserY + }; + } + /** + * @private + * Calculates the mean between two values + * @param {number} a + * @param {number} b + * @return {number} + */ - function string() { - let pool = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_STRING_POOL; - const poolLength = pool.length; + function mean$1(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. + */ - if (!poolLength) { - throw new Error("Expected pool not to be an empty string"); + 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}`); } - const distribution = integer(0, poolLength - 1); - return (engine, length) => { - let result = ""; + let ret = new Array(a.length); - for (let i = 0; i < length; ++i) { - const j = distribution(engine); - result += pool.charAt(j); - } + for (let i = 0; i < a.length; ++i) { + ret[i] = [a[i], b[i]]; + } - return result; - }; + return ret; } - const LOWER_HEX_POOL = "0123456789abcdef"; - const lowerHex = string(LOWER_HEX_POOL); - const upperHex = string(LOWER_HEX_POOL.toUpperCase()); - - const stringRepeat = (() => { - try { - if ("x".repeat(3) === "xxx") { - return (pattern, count) => pattern.repeat(count); - } - } catch (_) {// nothing to do here + const gainFunctions = { + gini: giniGain, + regression: regressionError + }; + const splitFunctions = { + mean: mean$1 + }; + 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; } + /** + * @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. + */ - return (pattern, count) => { - let result = ""; - while (count > 0) { - if (count & 1) { - result += pattern; - } + bestSplit(XTranspose, y) { + // Depending in the node tree class, we set the variables to check information gain (to classify) + // or error (for regression) + let bestGain = this.kind === 'classifier' ? -Infinity : Infinity; + let check = this.kind === 'classifier' ? (a, b) => a > b : (a, b) => a < b; + let maxColumn; + let maxValue; - count >>= 1; - pattern += pattern; - } + for (let i = 0; i < XTranspose.rows; ++i) { + let currentFeature = XTranspose.getRow(i); + let splitValues = this.featureSplit(currentFeature, y); - return result; - }; - })(); - /** - * An int32-producing Engine that uses `Math.random()` - */ + for (let j = 0; j < splitValues.length; ++j) { + let currentSplitVal = splitValues[j]; + let splitted = this.split(currentFeature, y, currentSplitVal); + let gain = gainFunctions[this.gainFunction](y, splitted); + if (check(gain, bestGain)) { + maxColumn = i; + maxValue = currentSplitVal; + bestGain = gain; + } + } + } - const nativeMath = { - next() { - return Math.random() * UINT32_SIZE | 0; + return { + maxGain: bestGain, + maxColumn: maxColumn, + maxValue: maxValue + }; } - - }; // tslint:disable:unified-signatures - /** - * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array - */ + /** + * @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} + */ - const I32Array = (() => { - try { - const buffer = new ArrayBuffer(4); - const view = new Int32Array(buffer); - view[0] = INT32_SIZE; + split(x, y, splitValue) { + let lesser = []; + let greater = []; - if (view[0] === -INT32_SIZE) { - return Int32Array; + for (let i = 0; i < x.length; ++i) { + if (x[i] < splitValue) { + lesser.push(y[i]); + } else { + greater.push(y[i]); + } } - } catch (_) {// nothing to do here + + 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. + */ - return Array; - })(); - /** - * Returns an array of random int32 values, based on current time - * and a random number engine - * - * @param engine an Engine to pull random values from, default `nativeMath` - * @param length the length of the Array, minimum 1, default 16 - */ - function createEntropy() { - let engine = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : nativeMath; - let length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 16; - const array = []; - array.push(new Date().getTime() | 0); + featureSplit(x, y) { + let splitValues = []; + let arr = zip(x, y); + arr.sort(function (a, b) { + return a[0] - b[0]; + }); - for (let i = 1; i < length; ++i) { - array[i] = engine.next() | 0; + for (let 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])); + } + } + + return splitValues; } + /** + * @private + * Calculate the predictions of a leaf tree node given the training labels or values + * @param {Array} y + */ - return array; - } - /** - * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul - */ + calculatePrediction(y) { + if (this.kind === 'classifier') { + this.distribution = toDiscreteDistribution(y, getNumberOfClasses(y)); - const imul = (() => { - try { - if (Math.imul(UINT32_MAX, 5) === -5) { - return Math.imul; + if (this.distribution.columns === 0) { + throw new TypeError('Error on calculate the prediction'); + } + } else { + this.distribution = mean(y); } - } catch (_) {// nothing to do here } + /** + * @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. + */ - const UINT16_MAX = 0xffff; - return (a, b) => { - const ah = a >>> 16 & UINT16_MAX; - const al = a & UINT16_MAX; - const bh = b >>> 16 & UINT16_MAX; - const bl = b & UINT16_MAX; // 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; - }; - })(); + train(X, y, currentDepth, parentGain) { + if (X.rows <= this.minNumSamples) { + this.calculatePrediction(y); + return; + } - const ARRAY_SIZE = 624; - const ARRAY_MAX = ARRAY_SIZE - 1; - const M = 397; - const ARRAY_SIZE_MINUS_M = ARRAY_SIZE - M; - const A = 0x9908b0df; - /** - * An Engine that is a pseudorandom number generator using the Mersenne - * Twister algorithm based on the prime 2**19937 − 1 - * - * See http://en.wikipedia.org/wiki/Mersenne_twister - */ + if (parentGain === undefined) parentGain = 0.0; + let XTranspose = X.transpose(); + let split = this.bestSplit(XTranspose, y); + this.splitValue = split.maxValue; + this.splitColumn = split.maxColumn; + this.gain = split.maxGain; + let splittedMatrix = matrixSplitter(X, y, this.splitColumn, this.splitValue); - class MersenneTwister19937 { - /** - * MersenneTwister19937 should not be instantiated directly. - * Instead, use the static methods `seed`, `seedWithArray`, or `autoSeed`. + 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); + let lesserX = new Matrix(splittedMatrix.lesserX); + let greaterX = new Matrix(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. */ - constructor() { - this.data = new I32Array(ARRAY_SIZE); - this.index = 0; // integer within [0, 624] - this.uses = 0; + + classify(row) { + if (this.right && this.left) { + if (row[this.splitColumn] < this.splitValue) { + return this.left.classify(row); + } else { + return this.right.classify(row); + } + } + + return this.distribution; } - /** - * Returns a MersenneTwister19937 seeded with an initial int32 value - * @param initial the initial seed value + /** + * @private + * Set the parameter of the current node and their children. + * @param {object} node - parameters of the current node and the children. */ - static seed(initial) { - return new MersenneTwister19937().seed(initial); + setNodeParameters(node) { + if (node.distribution !== undefined) { + this.distribution = node.distribution.constructor === Array ? new Matrix(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); + + if (node.left !== {}) { + this.left.setNodeParameters(node.left); + } + + if (node.right !== {}) { + this.right.setNodeParameters(node.right); + } + } } - /** - * Returns a MersenneTwister19937 seeded with zero or more int32 values - * @param source A series of int32 values - */ + } - static seedWithArray(source) { - return new MersenneTwister19937().seedWithArray(source); + const defaultOptions = { + gainFunction: 'gini', + splitFunction: 'mean', + minNumSamples: 3, + maxDepth: Infinity + }; + class 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(model.options); + this.root.setNodeParameters(model.root); + } else { + this.options = Object.assign({}, defaultOptions, options); + this.options.kind = 'classifier'; + } } - /** - * Returns a MersenneTwister19937 seeded with the current time and - * a series of natively-generated random values + /** + * Train the decision tree with the given training set and labels. + * @param {Matrix|MatrixTransposeView|Array} trainingSet + * @param {Array} trainingLabels */ - static autoSeed() { - return MersenneTwister19937.seedWithArray(createEntropy()); + train(trainingSet, trainingLabels) { + this.root = new TreeNode(this.options); + trainingSet = Matrix.checkMatrix(trainingSet); + this.root.train(trainingSet, trainingLabels, 0, null); } - /** - * Returns the next int32 value of the sequence + /** + * Predicts the output given the matrix to predict. + * @param {Matrix|MatrixTransposeView|Array} toPredict + * @return {Array} predictions */ - next() { - if ((this.index | 0) >= ARRAY_SIZE) { - refreshData(this.data); - this.index = 0; + predict(toPredict) { + toPredict = Matrix.checkMatrix(toPredict); + let predictions = new Array(toPredict.rows); + + for (let i = 0; i < toPredict.rows; ++i) { + predictions[i] = this.root.classify(toPredict.getRow(i)).maxRowIndex(0)[1]; } - const value = this.data[this.index]; - this.index = this.index + 1 | 0; - this.uses += 1; - return temper(value) | 0; + return predictions; } - /** - * Returns the number of times that the Engine has been used. - * - * This can be provided to an unused MersenneTwister19937 with the same - * seed, bringing it to the exact point that was left off. + /** + * Export the current model to JSON. + * @return {object} - Current model. */ - getUseCount() { - return this.uses; + toJSON() { + return { + options: this.options, + root: this.root, + name: 'DTClassifier' + }; } - /** - * Discards one or more items from the engine - * @param count The count of items to discard + /** + * Load a Decision tree classifier with the given model. + * @param {object} model + * @return {DecisionTreeClassifier} */ - discard(count) { - if (count <= 0) { - return this; + static load(model) { + if (model.name !== 'DTClassifier') { + throw new RangeError(`Invalid model: ${model.name}`); } - this.uses += count; + return new DecisionTreeClassifier(true, model); + } - if ((this.index | 0) >= ARRAY_SIZE) { - refreshData(this.data); - this.index = 0; - } + } - while (count + this.index > ARRAY_SIZE) { - count -= ARRAY_SIZE - this.index; - refreshData(this.data); - this.index = 0; + const defaultOptions$1 = { + gainFunction: 'regression', + splitFunction: 'mean', + minNumSamples: 3, + maxDepth: Infinity + }; + class 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(model.options); + this.root.setNodeParameters(model.root); + } else { + this.options = Object.assign({}, defaultOptions$1, options); + this.options.kind = 'regression'; } - - this.index = this.index + count | 0; - return this; } + /** + * Train the decision tree with the given training set and values. + * @param {Matrix|MatrixTransposeView|Array} trainingSet + * @param {Array} trainingValues + */ - seed(initial) { - let previous = 0; - this.data[0] = previous = initial | 0; - for (let i = 1; i < ARRAY_SIZE; i = i + 1 | 0) { - this.data[i] = previous = imul(previous ^ previous >>> 30, 0x6c078965) + i | 0; + train(trainingSet, trainingValues) { + this.root = new TreeNode(this.options); + + if (typeof trainingSet[0] !== 'undefined' && trainingSet[0].length === undefined) { + trainingSet = Matrix.columnVector(trainingSet); + } else { + trainingSet = Matrix.checkMatrix(trainingSet); } - this.index = ARRAY_SIZE; - this.uses = 0; - return this; + this.root.train(trainingSet, trainingValues, 0); } + /** + * Predicts the values given the matrix to predict. + * @param {Matrix|MatrixTransposeView|Array} toPredict + * @return {Array} predictions + */ - seedWithArray(source) { - this.seed(0x012bd6aa); - seedWithArray(this.data, source); - return this; - } - } + predict(toPredict) { + if (typeof toPredict[0] !== 'undefined' && toPredict[0].length === undefined) { + toPredict = Matrix.columnVector(toPredict); + } - function refreshData(data) { - let k = 0; - let tmp = 0; + toPredict = Matrix.checkMatrix(toPredict); + let predictions = new Array(toPredict.rows); - for (; (k | 0) < ARRAY_SIZE_MINUS_M; k = k + 1 | 0) { - tmp = data[k] & INT32_SIZE | data[k + 1 | 0] & INT32_MAX; - data[k] = data[k + M | 0] ^ tmp >>> 1 ^ (tmp & 0x1 ? A : 0); - } + for (let i = 0; i < toPredict.rows; ++i) { + predictions[i] = this.root.classify(toPredict.getRow(i)); + } - for (; (k | 0) < ARRAY_MAX; k = k + 1 | 0) { - tmp = data[k] & INT32_SIZE | data[k + 1 | 0] & INT32_MAX; - data[k] = data[k - ARRAY_SIZE_MINUS_M | 0] ^ tmp >>> 1 ^ (tmp & 0x1 ? A : 0); + return predictions; } + /** + * Export the current model to JSON. + * @return {object} - Current model. + */ - tmp = data[ARRAY_MAX] & INT32_SIZE | data[0] & INT32_MAX; - data[ARRAY_MAX] = data[M - 1] ^ tmp >>> 1 ^ (tmp & 0x1 ? A : 0); - } - - function temper(value) { - value ^= value >>> 11; - value ^= value << 7 & 0x9d2c5680; - value ^= value << 15 & 0xefc60000; - return value ^ value >>> 18; - } - function seedWithArray(data, source) { - let i = 1; - let j = 0; - const sourceLength = source.length; - let k = Math.max(sourceLength, ARRAY_SIZE) | 0; - let previous = data[0] | 0; + toJSON() { + return { + options: this.options, + root: this.root, + name: 'DTRegression' + }; + } + /** + * Load a Decision tree regression with the given model. + * @param {object} model + * @return {DecisionTreeRegression} + */ - 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) > ARRAY_MAX) { - data[0] = data[ARRAY_MAX]; - i = 1; + static load(model) { + if (model.name !== 'DTRegression') { + throw new RangeError(`Invalid model:${model.name}`); } - if (j >= sourceLength) { - j = 0; - } + return new DecisionTreeRegression(true, model); } - for (k = ARRAY_MAX; (k | 0) > 0; --k) { - data[i] = previous = (data[i] ^ imul(previous ^ previous >>> 30, 0x5d588b65)) - i | 0; - i = i + 1 | 0; + } - if ((i | 0) > ARRAY_MAX) { - data[0] = data[ARRAY_MAX]; - i = 1; - } - } + const SMALLEST_UNSAFE_INTEGER = 0x20000000000000; + const LARGEST_SAFE_INTEGER = SMALLEST_UNSAFE_INTEGER - 1; + const UINT32_MAX = -1 >>> 0; + const UINT32_SIZE = UINT32_MAX + 1; + const INT32_SIZE = UINT32_SIZE / 2; + const INT32_MAX = INT32_SIZE - 1; + const UINT21_SIZE = 1 << 21; + const UINT21_MAX = UINT21_SIZE - 1; + /** + * Returns a value within [-0x80000000, 0x7fffffff] + */ - data[0] = INT32_SIZE; + function int32(engine) { + return engine.next() | 0; } - function checkFloat(n) { - return n > 0.0 && n <= 1.0; + function add(distribution, addend) { + if (addend === 0) { + return distribution; + } else { + return engine => distribution(engine) + addend; + } } - /** - * 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. + /** + * Returns a value within [-0x20000000000000, 0x1fffffffffffff] */ - function examplesBaggingWithReplacement(trainingSet, trainingValue, seed) { - let engine; - let distribution = integer(0, trainingSet.rows - 1); - if (seed === undefined) { - engine = MersenneTwister19937.autoSeed(); - } else if (Number.isInteger(seed)) { - engine = MersenneTwister19937.seed(seed); - } else { - throw new RangeError("Expected seed must be undefined or integer not ".concat(seed)); - } + function int53(engine) { + const high = engine.next() | 0; + const low = engine.next() >>> 0; + return (high & UINT21_MAX) * UINT32_SIZE + low + (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0); + } + /** + * Returns a value within [-0x20000000000000, 0x20000000000000] + */ - let Xr = new Array(trainingSet.rows); - let yr = new Array(trainingSet.rows); - for (let i = 0; i < trainingSet.rows; ++i) { - let index = distribution(engine); - Xr[i] = trainingSet.getRow(index); - yr[i] = trainingValue[index]; + function int53Full(engine) { + while (true) { + const high = engine.next() | 0; + + if (high & 0x400000) { + if ((high & 0x7fffff) === 0x400000 && (engine.next() | 0) === 0) { + return SMALLEST_UNSAFE_INTEGER; + } + } else { + const low = engine.next() >>> 0; + return (high & UINT21_MAX) * UINT32_SIZE + low + (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0); + } } + } + /** + * Returns a value within [0, 0xffffffff] + */ - return { - X: new Matrix(Xr), - y: yr - }; + + function uint32(engine) { + return engine.next() >>> 0; } - /** - * 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} + /** + * Returns a value within [0, 0x1fffffffffffff] */ - 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'); - } - let distribution = integer(0, trainingSet.columns - 1); - let engine; + function uint53(engine) { + const high = engine.next() & UINT21_MAX; + const low = engine.next() >>> 0; + return high * UINT32_SIZE + low; + } + /** + * Returns a value within [0, 0x20000000000000] + */ - if (seed === undefined) { - engine = MersenneTwister19937.autoSeed(); - } else if (Number.isInteger(seed)) { - engine = MersenneTwister19937.seed(seed); - } else { - throw new RangeError("Expected seed must be undefined or integer not ".concat(seed)); + + function uint53Full(engine) { + while (true) { + const high = engine.next() | 0; + + if (high & UINT21_SIZE) { + if ((high & UINT21_MAX) === 0 && (engine.next() | 0) === 0) { + return SMALLEST_UNSAFE_INTEGER; + } + } else { + const low = engine.next() >>> 0; + return (high & UINT21_MAX) * UINT32_SIZE + low; + } } + } - let toRet = new Matrix(trainingSet.rows, n); - let usedIndex; - let index; + function isPowerOfTwoMinusOne(value) { + return (value + 1 & value) === 0; + } - if (replacement) { - usedIndex = new Array(n); + function bitmask(masking) { + return engine => engine.next() & masking; + } - for (let i = 0; i < n; ++i) { - index = distribution(engine); - usedIndex[i] = index; - toRet.setColumn(i, trainingSet.getColumn(index)); - } - } else { - usedIndex = new Set(); - index = distribution(engine); + function downscaleToLoopCheckedRange(range) { + const extendedRange = range + 1; + const maximum = extendedRange * Math.floor(UINT32_SIZE / extendedRange); + return engine => { + let value = 0; - for (let i = 0; i < n; ++i) { - while (usedIndex.has(index)) { - index = distribution(engine); - } + do { + value = engine.next() >>> 0; + } while (value >= maximum); - toRet.setColumn(i, trainingSet.getColumn(index)); - usedIndex.add(index); - } + return value % extendedRange; + }; + } - usedIndex = Array.from(usedIndex); + function downscaleToRange(range) { + if (isPowerOfTwoMinusOne(range)) { + return bitmask(range); + } else { + return downscaleToLoopCheckedRange(range); } + } - return { - X: toRet, - usedIndex: usedIndex + function isEvenlyDivisibleByMaxInt32(value) { + return (value | 0) === 0; + } + + function upscaleWithHighMasking(masking) { + return engine => { + const high = engine.next() & masking; + const low = engine.next() >>> 0; + return high * UINT32_SIZE + low; }; } - /** - * @class RandomForestBase - */ + function upscaleToLoopCheckedRange(extendedRange) { + const maximum = extendedRange * Math.floor(SMALLEST_UNSAFE_INTEGER / extendedRange); + return engine => { + let ret = 0; - 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; - let Estimator = this.isClassifier ? DecisionTreeClassifier : 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; + do { + const high = engine.next() & UINT21_MAX; + const low = engine.next() >>> 0; + ret = high * UINT32_SIZE + low; + } while (ret >= maximum); + + return ret % extendedRange; + }; + } + + function upscaleWithinU53(range) { + const extendedRange = range + 1; + + if (isEvenlyDivisibleByMaxInt32(extendedRange)) { + const highRange = (extendedRange / UINT32_SIZE | 0) - 1; + + if (isPowerOfTwoMinusOne(highRange)) { + return upscaleWithHighMasking(highRange); } } - /** - * Train the decision tree with the given training set and labels. - * @param {Matrix|Array} trainingSet - * @param {Array} trainingValues - */ + return upscaleToLoopCheckedRange(extendedRange); + } - train(trainingSet, trainingValues) { - trainingSet = Matrix.checkMatrix(trainingSet); - this.maxFeatures = this.maxFeatures || trainingSet.columns; + function upscaleWithinI53AndLoopCheck(min, max) { + return engine => { + let ret = 0; - 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)); - } + do { + const high = engine.next() | 0; + const low = engine.next() >>> 0; + ret = (high & UINT21_MAX) * UINT32_SIZE + low + (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0); + } while (ret < min || ret > max); - let Estimator; + return ret; + }; + } + /** + * Returns a Distribution to return a value within [min, max] + * @param min The minimum integer value, inclusive. No less than -0x20000000000000. + * @param max The maximum integer value, inclusive. No greater than 0x20000000000000. + */ - if (this.isClassifier) { - Estimator = DecisionTreeClassifier; - } else { - Estimator = DecisionTreeRegression; - } - this.estimators = new Array(this.nEstimators); - this.indexes = new Array(this.nEstimators); + function integer(min, max) { + min = Math.floor(min); + max = Math.floor(max); - for (let i = 0; i < this.nEstimators; ++i) { - let res = this.useSampleBagging ? examplesBaggingWithReplacement(trainingSet, trainingValues, this.seed) : { - X: trainingSet, - y: trainingValues - }; - let X = res.X; - let 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); - } + if (min < -SMALLEST_UNSAFE_INTEGER || !isFinite(min)) { + throw new RangeError(`Expected min to be at least ${-SMALLEST_UNSAFE_INTEGER}`); + } else if (max > SMALLEST_UNSAFE_INTEGER || !isFinite(max)) { + throw new RangeError(`Expected max to be at most ${SMALLEST_UNSAFE_INTEGER}`); } - /** - * 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 + const range = max - min; - selection(values) { - throw new Error("Abstract method 'selection' not implemented!"); + if (range <= 0 || !isFinite(range)) { + return () => min; + } else if (range === UINT32_MAX) { + if (min === 0) { + return uint32; + } else { + return add(int32, min + INT32_SIZE); + } + } else if (range < UINT32_MAX) { + return add(downscaleToRange(range), min); + } else if (range === LARGEST_SAFE_INTEGER) { + return add(uint53, min); + } else if (range < LARGEST_SAFE_INTEGER) { + return add(upscaleWithinU53(range), min); + } else if (max - 1 - min === LARGEST_SAFE_INTEGER) { + return add(uint53Full, min); + } else if (min === -SMALLEST_UNSAFE_INTEGER && max === SMALLEST_UNSAFE_INTEGER) { + return int53Full; + } else if (min === -SMALLEST_UNSAFE_INTEGER && max === LARGEST_SAFE_INTEGER) { + return int53; + } else if (min === -LARGEST_SAFE_INTEGER && max === SMALLEST_UNSAFE_INTEGER) { + return add(int53, 1); + } else if (max === SMALLEST_UNSAFE_INTEGER) { + return add(upscaleWithinI53AndLoopCheck(min - 1, max - 1), 1); + } else { + return upscaleWithinI53AndLoopCheck(min, max); } - /** - * Predicts the output given the matrix to predict. - * @param {Matrix|Array} toPredict - * @return {Array} predictions - */ + } + // has 2**x chars, for faster uniform distribution - predict(toPredict) { - let predictionValues = new Array(this.nEstimators); - toPredict = Matrix.checkMatrix(toPredict); + const DEFAULT_STRING_POOL = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"; - for (let i = 0; i < this.nEstimators; ++i) { - let X = new MatrixColumnSelectionView(toPredict, this.indexes[i]); // get features for estimator + function string(pool = DEFAULT_STRING_POOL) { + const poolLength = pool.length; - predictionValues[i] = this.estimators[i].predict(X); - } + if (!poolLength) { + throw new Error("Expected pool not to be an empty string"); + } - predictionValues = new MatrixTransposeView(new WrapperMatrix2D(predictionValues)); - let predictions = new Array(predictionValues.rows); + const distribution = integer(0, poolLength - 1); + return (engine, length) => { + let result = ""; - for (let i = 0; i < predictionValues.rows; ++i) { - predictions[i] = this.selection(predictionValues.getRow(i)); + for (let i = 0; i < length; ++i) { + const j = distribution(engine); + result += pool.charAt(j); } - return predictions; - } - /** - * Export the current model to JSON. - * @return {object} - Current model. - */ + return result; + }; + } + const LOWER_HEX_POOL = "0123456789abcdef"; + const lowerHex = string(LOWER_HEX_POOL); + const upperHex = string(LOWER_HEX_POOL.toUpperCase()); - 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 - }; + const stringRepeat = (() => { + try { + if ("x".repeat(3) === "xxx") { + return (pattern, count) => pattern.repeat(count); + } + } catch (_) {// nothing to do here } - } + return (pattern, count) => { + let result = ""; - const defaultOptions$2 = { - maxFeatures: 1.0, - replacement: true, - nEstimators: 10, - seed: 42, - useSampleBagging: false - }; - /** - * @class RandomForestClassifier - * @augments RandomForestBase - */ + while (count > 0) { + if (count & 1) { + result += pattern; + } - class RandomForestClassifier extends 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$2, options); - options.isClassifier = true; - super(options); + count >>= 1; + pattern += pattern; } - } - /** - * retrieve the prediction given the selection method. - * @param {Array} values - predictions of the estimators. - * @return {number} prediction - */ - - selection(values) { - return mode(values); - } - /** - * Export the current model to JSON. - * @return {object} - Current model. - */ + return result; + }; + })(); + /** + * An int32-producing Engine that uses `Math.random()` + */ - toJSON() { - let baseModel = super.toJSON(); - return { - baseModel: baseModel, - name: 'RFClassifier' - }; + const nativeMath = { + next() { + return Math.random() * UINT32_SIZE | 0; } - /** - * Load a Decision tree classifier with the given model. - * @param {object} model - * @return {RandomForestClassifier} - */ + }; // tslint:disable:unified-signatures + /** + * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array + */ - static load(model) { - if (model.name !== 'RFClassifier') { - throw new RangeError("Invalid model: ".concat(model.name)); - } - return new RandomForestClassifier(true, model); + const I32Array = (() => { + try { + const buffer = new ArrayBuffer(4); + const view = new Int32Array(buffer); + view[0] = INT32_SIZE; + + if (view[0] === -INT32_SIZE) { + return Int32Array; + } + } catch (_) {// nothing to do here } - } - /** - * Return the most repeated element on the array. - * @param {Array} arr - * @return {number} mode + return Array; + })(); + /** + * Returns an array of random int32 values, based on current time + * and a random number engine + * + * @param engine an Engine to pull random values from, default `nativeMath` + * @param length the length of the Array, minimum 1, default 16 */ - function mode(arr) { - return arr.sort((a, b) => arr.filter(v => v === a).length - arr.filter(v => v === b).length).pop(); - } + function createEntropy(engine = nativeMath, length = 16) { + const array = []; + array.push(new Date().getTime() | 0); - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + for (let i = 1; i < length; ++i) { + array[i] = engine.next() | 0; + } - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; + return array; } + /** + * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul + */ - var medianQuickselect_min = createCommonjsModule(function (module) { - (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 < h) break; - b(d, h, i); - } - b(d, e, i), i <= j && (e = h), i >= j && (f = i - 1); - } + const imul = (() => { + try { + if (Math.imul(UINT32_MAX, 5) === -5) { + return Math.imul; } + } catch (_) {// nothing to do here + } - 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); - }; + const UINT16_MAX = 0xffff; + return (a, b) => { + const ah = a >>> 16 & UINT16_MAX; + const al = a & UINT16_MAX; + const bh = b >>> 16 & UINT16_MAX; + const bl = b & UINT16_MAX; // the shift by 0 fixes the sign on the high part + // the final |0 converts the unsigned value into a signed value - module.exports ? module.exports = a : window.median = a; - })(); - }); + return al * bl + (ah * bl + al * bh << 16 >>> 0) | 0; + }; + })(); - /** - * Computes the median of the given values - * @param {Array} input - * @return {number} + const ARRAY_SIZE = 624; + const ARRAY_MAX = ARRAY_SIZE - 1; + const M = 397; + const ARRAY_SIZE_MINUS_M = ARRAY_SIZE - M; + const A = 0x9908b0df; + /** + * An Engine that is a pseudorandom number generator using the Mersenne + * Twister algorithm based on the prime 2**19937 − 1 + * + * See http://en.wikipedia.org/wiki/Mersenne_twister */ - function median(input) { - if (!src(input)) { - throw new TypeError('input must be an array'); - } + class MersenneTwister19937 { + /** + * MersenneTwister19937 should not be instantiated directly. + * Instead, use the static methods `seed`, `seedWithArray`, or `autoSeed`. + */ + constructor() { + this.data = new I32Array(ARRAY_SIZE); + this.index = 0; // integer within [0, 624] - if (input.length === 0) { - throw new TypeError('input must not be empty'); + this.uses = 0; } + /** + * Returns a MersenneTwister19937 seeded with an initial int32 value + * @param initial the initial seed value + */ - return medianQuickselect_min(input.slice()); - } - const selectionMethods = { - mean: mean, - median: median - }; - const defaultOptions$3 = { - maxFeatures: 1.0, - replacement: false, - nEstimators: 10, - treeOptions: {}, - selectionMethod: 'mean', - seed: 42, - useSampleBagging: false - }; - /** - * @class RandomForestRegression - * @augments RandomForestBase - */ + static seed(initial) { + return new MersenneTwister19937().seed(initial); + } + /** + * Returns a MersenneTwister19937 seeded with zero or more int32 values + * @param source A series of int32 values + */ - class RandomForestRegression extends 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. + + static seedWithArray(source) { + return new MersenneTwister19937().seedWithArray(source); + } + /** + * Returns a MersenneTwister19937 seeded with the current time and + * a series of natively-generated random values */ - constructor(options, model) { - if (options === true) { - super(true, model.baseModel); - this.selectionMethod = model.selectionMethod; - } else { - options = Object.assign({}, defaultOptions$3, options); - if (!(options.selectionMethod === 'mean' || options.selectionMethod === 'median')) { - throw new RangeError("Unsupported selection method ".concat(options.selectionMethod)); - } - options.isClassifier = false; - super(options); - this.selectionMethod = options.selectionMethod; - } + static autoSeed() { + return MersenneTwister19937.seedWithArray(createEntropy()); } - /** - * retrieve the prediction given the selection method. - * @param {Array} values - predictions of the estimators. - * @return {number} prediction + /** + * Returns the next int32 value of the sequence */ - selection(values) { - return selectionMethods[this.selectionMethod](values); + next() { + if ((this.index | 0) >= ARRAY_SIZE) { + refreshData(this.data); + this.index = 0; + } + + const value = this.data[this.index]; + this.index = this.index + 1 | 0; + this.uses += 1; + return temper(value) | 0; } - /** - * Export the current model to JSON. - * @return {object} - Current model. + /** + * Returns the number of times that the Engine has been used. + * + * This can be provided to an unused MersenneTwister19937 with the same + * seed, bringing it to the exact point that was left off. */ - toJSON() { - let baseModel = super.toJSON(); - return { - baseModel: baseModel, - selectionMethod: this.selectionMethod, - name: 'RFRegression' - }; + getUseCount() { + return this.uses; } - /** - * Load a Decision tree classifier with the given model. - * @param {object} model - * @return {RandomForestRegression} + /** + * Discards one or more items from the engine + * @param count The count of items to discard */ - static load(model) { - if (model.name !== 'RFRegression') { - throw new RangeError("Invalid model: ".concat(model.name)); + discard(count) { + if (count <= 0) { + return this; } - return new RandomForestRegression(true, model); - } - - } + this.uses += count; - /** - * 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 {string} [options.method='SVD'] - select which method to use: SVD (default), covarianceMatrirx or NIPALS. - * @param {number} [options.nCompNIPALS=2] - number of components to be computed with NIPALS. - * @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). - * @param {boolean} [options.ignoreZeroVariance=false] - ignore columns with zero variance if `scale` is `true`. - * */ - - class PCA { - constructor(dataset) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if ((this.index | 0) >= ARRAY_SIZE) { + refreshData(this.data); + this.index = 0; + } - 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; - this.R = model.R; - this.excludedFeatures = model.excludedFeatures || []; - return; + while (count + this.index > ARRAY_SIZE) { + count -= ARRAY_SIZE - this.index; + refreshData(this.data); + this.index = 0; } - dataset = new Matrix(dataset); - const { - isCovarianceMatrix = false, - method = 'SVD', - nCompNIPALS = 2, - center = true, - scale = false, - ignoreZeroVariance = false - } = options; - this.center = center; - this.scale = scale; - this.means = null; - this.stdevs = null; - this.excludedFeatures = []; + this.index = this.index + count | 0; + return this; + } - if (isCovarianceMatrix) { - // User provided a covariance matrix instead of dataset. - this._computeFromCovarianceMatrix(dataset); + seed(initial) { + let previous = 0; + this.data[0] = previous = initial | 0; - return; + for (let i = 1; i < ARRAY_SIZE; i = i + 1 | 0) { + this.data[i] = previous = imul(previous ^ previous >>> 30, 0x6c078965) + i | 0; } - this._adjust(dataset, ignoreZeroVariance); - - switch (method) { - case 'covarianceMatrix': - { - // User provided a dataset but wants us to compute and use the covariance matrix. - const covarianceMatrix = new MatrixTransposeView(dataset).mmul(dataset).div(dataset.rows - 1); + this.index = ARRAY_SIZE; + this.uses = 0; + return this; + } - this._computeFromCovarianceMatrix(covarianceMatrix); + seedWithArray(source) { + this.seed(0x012bd6aa); + seedWithArray(this.data, source); + return this; + } - break; - } + } - case 'NIPALS': - { - this._computeWithNIPALS(dataset, nCompNIPALS); + function refreshData(data) { + let k = 0; + let tmp = 0; - break; - } + for (; (k | 0) < ARRAY_SIZE_MINUS_M; k = k + 1 | 0) { + tmp = data[k] & INT32_SIZE | data[k + 1 | 0] & INT32_MAX; + data[k] = data[k + M | 0] ^ tmp >>> 1 ^ (tmp & 0x1 ? A : 0); + } - case 'SVD': - { - const svd = new SingularValueDecomposition(dataset, { - computeLeftSingularVectors: false, - computeRightSingularVectors: true, - autoTranspose: true - }); - this.U = svd.rightSingularVectors; - const singularValues = svd.diagonal; - const eigenvalues = []; + for (; (k | 0) < ARRAY_MAX; k = k + 1 | 0) { + tmp = data[k] & INT32_SIZE | data[k + 1 | 0] & INT32_MAX; + data[k] = data[k - ARRAY_SIZE_MINUS_M | 0] ^ tmp >>> 1 ^ (tmp & 0x1 ? A : 0); + } - for (const singularValue of singularValues) { - eigenvalues.push(singularValue * singularValue / (dataset.rows - 1)); - } + tmp = data[ARRAY_MAX] & INT32_SIZE | data[0] & INT32_MAX; + data[ARRAY_MAX] = data[M - 1] ^ tmp >>> 1 ^ (tmp & 0x1 ? A : 0); + } - this.S = eigenvalues; - break; - } + function temper(value) { + value ^= value >>> 11; + value ^= value << 7 & 0x9d2c5680; + value ^= value << 15 & 0xefc60000; + return value ^ value >>> 18; + } - default: - { - throw new Error("unknown method: ".concat(method)); - } - } - } - /** - * Load a PCA model from JSON - * @param {Object} model - * @return {PCA} - */ + function seedWithArray(data, source) { + let i = 1; + let j = 0; + const sourceLength = source.length; + let k = Math.max(sourceLength, ARRAY_SIZE) | 0; + let 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; - static load(model) { - if (typeof model.name !== 'string') { - throw new TypeError('model must have a name property'); + if ((i | 0) > ARRAY_MAX) { + data[0] = data[ARRAY_MAX]; + i = 1; } - if (model.name !== 'PCA') { - throw new RangeError("invalid model: ".concat(model.name)); + if (j >= sourceLength) { + j = 0; } - - 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 - */ - - - predict(dataset) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - const { - nComponents = this.U.columns - } = options; - dataset = new Matrix(dataset); - - if (this.center) { - dataset.subRowVector(this.means); - if (this.scale) { - for (let i of this.excludedFeatures) { - dataset.removeColumn(i); - } + for (k = ARRAY_MAX; (k | 0) > 0; --k) { + data[i] = previous = (data[i] ^ imul(previous ^ previous >>> 30, 0x5d588b65)) - i | 0; + i = i + 1 | 0; - dataset.divRowVector(this.stdevs); - } + if ((i | 0) > ARRAY_MAX) { + data[0] = data[ARRAY_MAX]; + i = 1; } - - var predictions = dataset.mmul(this.U); - return predictions.subMatrix(0, predictions.rows - 1, 0, nComponents - 1); } - /** - * Calculates the inverse PCA transform - * @param {Matrix} dataset - * @return {Matrix} dataset projected in the PCA space - */ + data[0] = INT32_SIZE; + } - invert(dataset) { - dataset = Matrix.checkMatrix(dataset); - var inverse = dataset.mmul(this.U.transpose()); - - if (this.center) { - if (this.scale) { - inverse.mulRowVector(this.stdevs); - } + 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. + */ - inverse.addRowVector(this.means); - } + function examplesBaggingWithReplacement(trainingSet, trainingValue, seed) { + let engine; + let distribution = integer(0, trainingSet.rows - 1); - return inverse; + if (seed === undefined) { + engine = MersenneTwister19937.autoSeed(); + } else if (Number.isInteger(seed)) { + engine = MersenneTwister19937.seed(seed); + } else { + throw new RangeError(`Expected seed must be undefined or integer not ${seed}`); } - /** - * Returns the proportion of variance for each component - * @return {[number]} - */ + let Xr = new Array(trainingSet.rows); + let yr = new Array(trainingSet.rows); - getExplainedVariance() { - var sum = 0; + for (let i = 0; i < trainingSet.rows; ++i) { + let index = distribution(engine); + Xr[i] = trainingSet.getRow(index); + yr[i] = trainingValue[index]; + } - for (const s of this.S) { - sum += s; - } + return { + X: new Matrix(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} + */ - return this.S.map(value => value / sum); + 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'); } - /** - * Returns the cumulative proportion of variance - * @return {[number]} - */ + let distribution = integer(0, trainingSet.columns - 1); + let engine; - getCumulativeVariance() { - var explained = this.getExplainedVariance(); + if (seed === undefined) { + engine = MersenneTwister19937.autoSeed(); + } else if (Number.isInteger(seed)) { + engine = MersenneTwister19937.seed(seed); + } else { + throw new RangeError(`Expected seed must be undefined or integer not ${seed}`); + } - for (var i = 1; i < explained.length; i++) { - explained[i] += explained[i - 1]; + let toRet = new Matrix(trainingSet.rows, n); + let usedIndex; + let index; + + if (replacement) { + usedIndex = new Array(n); + + for (let i = 0; i < n; ++i) { + index = distribution(engine); + usedIndex[i] = index; + toRet.setColumn(i, trainingSet.getColumn(index)); } + } else { + usedIndex = new Set(); + index = distribution(engine); - return explained; - } - /** - * Returns the Eigenvectors of the covariance matrix - * @returns {Matrix} - */ + for (let i = 0; i < n; ++i) { + while (usedIndex.has(index)) { + index = distribution(engine); + } + toRet.setColumn(i, trainingSet.getColumn(index)); + usedIndex.add(index); + } - getEigenvectors() { - return this.U; + usedIndex = Array.from(usedIndex); } - /** - * Returns the Eigenvalues (on the diagonal) - * @returns {[number]} - */ + return { + X: toRet, + usedIndex: usedIndex + }; + } + + /** + * @class RandomForestBase + */ - getEigenvalues() { - return this.S; + 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; + let Estimator = this.isClassifier ? DecisionTreeClassifier : 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; + } } /** - * Returns the standard deviations of the principal components - * @returns {[number]} + * Train the decision tree with the given training set and labels. + * @param {Matrix|Array} trainingSet + * @param {Array} trainingValues */ - getStandardDeviations() { - return this.S.map(x => Math.sqrt(x)); + train(trainingSet, trainingValues) { + trainingSet = 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 ${trainingSet.columns}`); + } else { + this.n = this.maxFeatures; + } + } else { + throw new RangeError(`Cannot process the maxFeatures parameter ${this.maxFeatures}`); + } + + let Estimator; + + if (this.isClassifier) { + Estimator = DecisionTreeClassifier; + } else { + Estimator = DecisionTreeRegression; + } + + this.estimators = new Array(this.nEstimators); + this.indexes = new Array(this.nEstimators); + + for (let i = 0; i < this.nEstimators; ++i) { + let res = this.useSampleBagging ? examplesBaggingWithReplacement(trainingSet, trainingValues, this.seed) : { + X: trainingSet, + y: trainingValues + }; + let X = res.X; + let 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); + } } /** - * Returns the loadings matrix - * @return {Matrix} + * 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 - getLoadings() { - return this.U.transpose(); + selection(values) { + throw new Error("Abstract method 'selection' not implemented!"); } /** - * Export the current model to a JSON object - * @return {Object} model + * Predicts the output given the matrix to predict. + * @param {Matrix|Array} toPredict + * @return {Array} predictions */ - toJSON() { - return { - name: 'PCA', - center: this.center, - scale: this.scale, - means: this.means, - stdevs: this.stdevs, - U: this.U, - S: this.S, - excludedFeatures: this.excludedFeatures - }; - } - - _adjust(dataset, ignoreZeroVariance) { - if (this.center) { - const mean = dataset.mean('column'); - const stdevs = this.scale ? dataset.standardDeviation('column', { - mean - }) : null; - this.means = mean; - dataset.subRowVector(mean); + predict(toPredict) { + let predictionValues = new Array(this.nEstimators); + toPredict = Matrix.checkMatrix(toPredict); - if (this.scale) { - for (let i = 0; i < stdevs.length; i++) { - if (stdevs[i] === 0) { - if (ignoreZeroVariance) { - dataset.removeColumn(i); - stdevs.splice(i, 1); - this.excludedFeatures.push(i); - i--; - } else { - throw new RangeError("Cannot scale the dataset (standard deviation is zero at index ".concat(i)); - } - } - } + for (let i = 0; i < this.nEstimators; ++i) { + let X = new MatrixColumnSelectionView(toPredict, this.indexes[i]); // get features for estimator - this.stdevs = stdevs; - dataset.divRowVector(stdevs); - } + predictionValues[i] = this.estimators[i].predict(X); } - } - - _computeFromCovarianceMatrix(dataset) { - const evd = new EigenvalueDecomposition(dataset, { - assumeSymmetric: true - }); - this.U = evd.eigenvectorMatrix; - this.U.flipRows(); - this.S = evd.realEigenvalues; - this.S.reverse(); - } - _computeWithNIPALS(dataset, nCompNIPALS) { - this.U = new Matrix(nCompNIPALS, dataset.columns); - this.S = []; - let x = dataset; + predictionValues = new MatrixTransposeView(new WrapperMatrix2D(predictionValues)); + let predictions = new Array(predictionValues.rows); - for (let i = 0; i < nCompNIPALS; i++) { - let dc = new nipals(x); - this.U.setRow(i, dc.w.transpose()); - this.S.push(Math.pow(dc.s.get(0, 0), 2)); - x = dc.xResidual; + for (let i = 0; i < predictionValues.rows; ++i) { + predictions[i] = this.selection(predictionValues.getRow(i)); } - this.U = this.U.transpose(); // to be compatible with API + return predictions; } + /** + * Export the current model to JSON. + * @return {object} - Current model. + */ - } - - function squaredEuclidean(p, q) { - let d = 0; - for (let i = 0; i < p.length; i++) { - d += (p[i] - q[i]) * (p[i] - q[i]); + 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 d; - } - function euclidean(p, q) { - return Math.sqrt(squaredEuclidean(p, q)); } - var euclidean$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - squaredEuclidean: squaredEuclidean, - euclidean: euclidean - }); - + const defaultOptions$2 = { + maxFeatures: 1.0, + replacement: true, + nEstimators: 10, + seed: 42, + useSampleBagging: false + }; /** - * 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 distance/similarity matrix. The matrix is square and has a size equal to the length of - * the data array + * @class RandomForestClassifier + * @augments RandomForestBase */ - function distanceMatrix(data, distanceFn) { - const result = getMatrix(data.length); // Compute upper distance matrix - for (let i = 0; i < data.length; i++) { - for (let j = 0; j <= i; j++) { - result[i][j] = distanceFn(data[i], data[j]); - result[j][i] = result[i][j]; + class RandomForestClassifier extends 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$2, options); + options.isClassifier = true; + super(options); } } + /** + * retrieve the prediction given the selection method. + * @param {Array} values - predictions of the estimators. + * @return {number} prediction + */ - return result; - } - function getMatrix(size) { - const matrix = []; + selection(values) { + return mode(values); + } + /** + * Export the current model to JSON. + * @return {object} - Current model. + */ - for (let i = 0; i < size; i++) { - const row = []; - matrix.push(row); - for (let j = 0; j < size; j++) { - row.push(0); - } + toJSON() { + let baseModel = super.toJSON(); + return { + baseModel: baseModel, + name: 'RFClassifier' + }; } + /** + * Load a Decision tree classifier with the given model. + * @param {object} model + * @return {RandomForestClassifier} + */ - return matrix; - } - var heap = createCommonjsModule(function (module, exports) { - // Generated by CoffeeScript 1.8.0 - (function () { - var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup; + static load(model) { + if (model.name !== 'RFClassifier') { + throw new RangeError(`Invalid model: ${model.name}`); + } - floor = Math.floor, min = Math.min; - /* - Default comparison function to be used - */ + return new RandomForestClassifier(true, model); + } - defaultCmp = function defaultCmp(x, y) { - if (x < y) { - return -1; - } + } + /** + * Return the most repeated element on the array. + * @param {Array} arr + * @return {number} mode + */ - if (x > y) { - return 1; - } + function mode(arr) { + return arr.sort((a, b) => arr.filter(v => v === a).length - arr.filter(v => v === b).length).pop(); + } - 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. - */ + const toString$2 = Object.prototype.toString; + function isAnyArray$2(object) { + return toString$2.call(object).endsWith('Array]'); + } + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - insort = function insort(a, x, lo, hi, cmp) { - var mid; + function createCommonjsModule(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function (path, base) { + return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); + } + }, fn(module, module.exports), module.exports; + } - if (lo == null) { - lo = 0; - } + function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var a = Object.defineProperty({}, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; + } - if (cmp == null) { - cmp = defaultCmp; - } + function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); + } - if (lo < 0) { - throw new Error('lo must be non-negative'); - } + var medianQuickselect_min = createCommonjsModule(function (module) { + (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]; - if (hi == null) { - hi = a.length; - } + 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]); - while (lo < hi) { - mid = floor((lo + hi) / 2); + do i--; while (d[i] > d[e]); - if (cmp(x, a[mid]) < 0) { - hi = mid; - } else { - lo = mid + 1; + if (i < h) break; + b(d, h, i); } + + b(d, e, i), i <= j && (e = h), i >= j && (f = i - 1); } + } - return [].splice.apply(a, [lo, lo - lo].concat(x)), x; + 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); }; - /* - Push item onto heap, maintaining the heap invariant. - */ + module.exports ? module.exports = a : window.median = a; + })(); + }); - heappush = function heappush(array, item, cmp) { - if (cmp == null) { - cmp = defaultCmp; - } + function median(input) { + if (!isAnyArray$2(input)) { + throw new TypeError('input must be an array'); + } - array.push(item); - return _siftdown(array, 0, array.length - 1, cmp); - }; - /* - Pop the smallest item off the heap, maintaining the heap invariant. - */ + if (input.length === 0) { + throw new TypeError('input must not be empty'); + } + return medianQuickselect_min(input.slice()); + } - heappop = function heappop(array, cmp) { - var lastelt, returnitem; + const selectionMethods = { + mean: mean, + median: median + }; + const defaultOptions$3 = { + maxFeatures: 1.0, + replacement: false, + nEstimators: 10, + treeOptions: {}, + selectionMethod: 'mean', + seed: 42, + useSampleBagging: false + }; + /** + * @class RandomForestRegression + * @augments RandomForestBase + */ - if (cmp == null) { - cmp = defaultCmp; + class RandomForestRegression extends 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$3, options); + + if (!(options.selectionMethod === 'mean' || options.selectionMethod === 'median')) { + throw new RangeError(`Unsupported selection method ${options.selectionMethod}`); } - lastelt = array.pop(); + options.isClassifier = false; + super(options); + this.selectionMethod = options.selectionMethod; + } + } + /** + * retrieve the prediction given the selection method. + * @param {Array} values - predictions of the estimators. + * @return {number} prediction + */ - if (array.length) { - returnitem = array[0]; - array[0] = lastelt; - _siftup(array, 0, cmp); - } else { - returnitem = lastelt; - } + selection(values) { + return selectionMethods[this.selectionMethod](values); + } + /** + * Export the current model to JSON. + * @return {object} - Current model. + */ - return returnitem; + + toJSON() { + let baseModel = super.toJSON(); + return { + baseModel: baseModel, + selectionMethod: this.selectionMethod, + name: 'RFRegression' }; - /* - 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) - */ + } + /** + * Load a Decision tree classifier with the given model. + * @param {object} model + * @return {RandomForestRegression} + */ - heapreplace = function heapreplace(array, item, cmp) { - var returnitem; + static load(model) { + if (model.name !== 'RFRegression') { + throw new RangeError(`Invalid model: ${model.name}`); + } - if (cmp == null) { - cmp = defaultCmp; - } + return new RandomForestRegression(true, model); + } - returnitem = array[0]; - array[0] = item; + } - _siftup(array, 0, cmp); + /** + * 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 {string} [options.method='SVD'] - select which method to use: SVD (default), covarianceMatrirx or NIPALS. + * @param {number} [options.nCompNIPALS=2] - number of components to be computed with NIPALS. + * @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). + * @param {boolean} [options.ignoreZeroVariance=false] - ignore columns with zero variance if `scale` is `true`. + * */ - return returnitem; - }; - /* - Fast version of a heappush followed by a heappop. - */ + 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; + this.R = model.R; + this.excludedFeatures = model.excludedFeatures || []; + return; + } + dataset = new Matrix(dataset); + const { + isCovarianceMatrix = false, + method = 'SVD', + nCompNIPALS = 2, + center = true, + scale = false, + ignoreZeroVariance = false + } = options; + this.center = center; + this.scale = scale; + this.means = null; + this.stdevs = null; + this.excludedFeatures = []; - heappushpop = function heappushpop(array, item, cmp) { - var _ref; + if (isCovarianceMatrix) { + // User provided a covariance matrix instead of dataset. + this._computeFromCovarianceMatrix(dataset); - if (cmp == null) { - cmp = defaultCmp; - } + return; + } - if (array.length && cmp(array[0], item) < 0) { - _ref = [array[0], item], item = _ref[0], array[0] = _ref[1]; + this._adjust(dataset, ignoreZeroVariance); - _siftup(array, 0, cmp); - } + switch (method) { + case 'covarianceMatrix': + { + // User provided a dataset but wants us to compute and use the covariance matrix. + const covarianceMatrix = new MatrixTransposeView(dataset).mmul(dataset).div(dataset.rows - 1); - return item; - }; - /* - Transform list into a heap, in-place, in O(array.length) time. - */ + this._computeFromCovarianceMatrix(covarianceMatrix); + break; + } - heapify = function heapify(array, cmp) { - var i, _i, _len, _ref1, _results, _results1; + case 'NIPALS': + { + this._computeWithNIPALS(dataset, nCompNIPALS); - if (cmp == null) { - cmp = defaultCmp; - } + break; + } - _ref1 = function () { - _results1 = []; + case 'SVD': + { + const svd = new SingularValueDecomposition(dataset, { + computeLeftSingularVectors: false, + computeRightSingularVectors: true, + autoTranspose: true + }); + this.U = svd.rightSingularVectors; + const singularValues = svd.diagonal; + const eigenvalues = []; - for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--) { - _results1.push(_j); + for (const singularValue of singularValues) { + eigenvalues.push(singularValue * singularValue / (dataset.rows - 1)); + } + + this.S = eigenvalues; + break; } - return _results1; - }.apply(this).reverse(); + default: + { + throw new Error(`unknown method: ${method}`); + } + } + } + /** + * Load a PCA model from JSON + * @param {Object} model + * @return {PCA} + */ - _results = []; - for (_i = 0, _len = _ref1.length; _i < _len; _i++) { - i = _ref1[_i]; + static load(model) { + if (typeof model.name !== 'string') { + throw new TypeError('model must have a name property'); + } - _results.push(_siftup(array, i, cmp)); - } + if (model.name !== 'PCA') { + throw new RangeError(`invalid model: ${model.name}`); + } - return _results; - }; - /* - Update the position of the given item in the heap. - This function should be called every time the item is being modified. - */ + 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 + */ - updateItem = function updateItem(array, item, cmp) { - var pos; + predict(dataset, options = {}) { + const { + nComponents = this.U.columns + } = options; + dataset = new Matrix(dataset); - if (cmp == null) { - cmp = defaultCmp; - } + if (this.center) { + dataset.subRowVector(this.means); - pos = array.indexOf(item); + if (this.scale) { + for (let i of this.excludedFeatures) { + dataset.removeColumn(i); + } - if (pos === -1) { - return; + dataset.divRowVector(this.stdevs); } + } - _siftdown(array, 0, pos, cmp); - - return _siftup(array, pos, cmp); - }; - /* - Find the n largest elements in a dataset. - */ + var predictions = dataset.mmul(this.U); + return predictions.subMatrix(0, predictions.rows - 1, 0, nComponents - 1); + } + /** + * Calculates the inverse PCA transform + * @param {Matrix} dataset + * @return {Matrix} dataset projected in the PCA space + */ - nlargest = function nlargest(array, n, cmp) { - var elem, result, _i, _len, _ref; + invert(dataset) { + dataset = Matrix.checkMatrix(dataset); + var inverse = dataset.mmul(this.U.transpose()); - if (cmp == null) { - cmp = defaultCmp; + if (this.center) { + if (this.scale) { + inverse.mulRowVector(this.stdevs); } - result = array.slice(0, n); + inverse.addRowVector(this.means); + } - if (!result.length) { - return result; - } + return inverse; + } + /** + * Returns the proportion of variance for each component + * @return {[number]} + */ - heapify(result, cmp); - _ref = array.slice(n); - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - elem = _ref[_i]; - heappushpop(result, elem, cmp); - } + getExplainedVariance() { + var sum = 0; - return result.sort(cmp).reverse(); - }; - /* - Find the n smallest elements in a dataset. - */ + for (const s of this.S) { + sum += s; + } + return this.S.map(value => value / sum); + } + /** + * Returns the cumulative proportion of variance + * @return {[number]} + */ - nsmallest = function nsmallest(array, n, cmp) { - var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results; - if (cmp == null) { - cmp = defaultCmp; - } + getCumulativeVariance() { + var explained = this.getExplainedVariance(); - if (n * 10 <= array.length) { - result = array.slice(0, n).sort(cmp); + for (var i = 1; i < explained.length; i++) { + explained[i] += explained[i - 1]; + } - if (!result.length) { - return result; - } + return explained; + } + /** + * Returns the Eigenvectors of the covariance matrix + * @returns {Matrix} + */ - los = result[result.length - 1]; - _ref = array.slice(n); - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - elem = _ref[_i]; + getEigenvectors() { + return this.U; + } + /** + * Returns the Eigenvalues (on the diagonal) + * @returns {[number]} + */ - if (cmp(elem, los) < 0) { - insort(result, elem, 0, null, cmp); - result.pop(); - los = result[result.length - 1]; - } - } - return result; - } + getEigenvalues() { + return this.S; + } + /** + * Returns the standard deviations of the principal components + * @returns {[number]} + */ - 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)); - } + getStandardDeviations() { + return this.S.map(x => Math.sqrt(x)); + } + /** + * Returns the loadings matrix + * @return {Matrix} + */ - return _results; - }; - _siftdown = function _siftdown(array, startpos, pos, cmp) { - var newitem, parent, parentpos; + getLoadings() { + return this.U.transpose(); + } + /** + * Export the current model to a JSON object + * @return {Object} model + */ - if (cmp == null) { - cmp = defaultCmp; - } - newitem = array[pos]; + toJSON() { + return { + name: 'PCA', + center: this.center, + scale: this.scale, + means: this.means, + stdevs: this.stdevs, + U: this.U, + S: this.S, + excludedFeatures: this.excludedFeatures + }; + } - while (pos > startpos) { - parentpos = pos - 1 >> 1; - parent = array[parentpos]; + _adjust(dataset, ignoreZeroVariance) { + if (this.center) { + const mean = dataset.mean('column'); + const stdevs = this.scale ? dataset.standardDeviation('column', { + mean + }) : null; + this.means = mean; + dataset.subRowVector(mean); - if (cmp(newitem, parent) < 0) { - array[pos] = parent; - pos = parentpos; - continue; + if (this.scale) { + for (let i = 0; i < stdevs.length; i++) { + if (stdevs[i] === 0) { + if (ignoreZeroVariance) { + dataset.removeColumn(i); + stdevs.splice(i, 1); + this.excludedFeatures.push(i); + i--; + } else { + throw new RangeError(`Cannot scale the dataset (standard deviation is zero at index ${i}`); + } + } } - break; + this.stdevs = stdevs; + dataset.divRowVector(stdevs); } + } + } - return array[pos] = newitem; - }; + _computeFromCovarianceMatrix(dataset) { + const evd = new EigenvalueDecomposition(dataset, { + assumeSymmetric: true + }); + this.U = evd.eigenvectorMatrix; + this.U.flipRows(); + this.S = evd.realEigenvalues; + this.S.reverse(); + } - _siftup = function _siftup(array, pos, cmp) { - var childpos, endpos, newitem, rightpos, startpos; + _computeWithNIPALS(dataset, nCompNIPALS) { + this.U = new Matrix(nCompNIPALS, dataset.columns); + this.S = []; + let x = dataset; - if (cmp == null) { - cmp = defaultCmp; - } + for (let i = 0; i < nCompNIPALS; i++) { + let dc = new nipals(x); + this.U.setRow(i, dc.w.transpose()); + this.S.push(Math.pow(dc.s.get(0, 0), 2)); + x = dc.xResidual; + } - endpos = array.length; - startpos = pos; - newitem = array[pos]; - childpos = 2 * pos + 1; + this.U = this.U.transpose(); // to be compatible with API + } - while (childpos < endpos) { - rightpos = childpos + 1; + } - if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) { - childpos = rightpos; - } + function squaredEuclidean(p, q) { + let d = 0; - array[pos] = array[childpos]; - pos = childpos; - childpos = 2 * pos + 1; - } + for (let i = 0; i < p.length; i++) { + d += (p[i] - q[i]) * (p[i] - q[i]); + } - array[pos] = newitem; - return _siftdown(array, startpos, pos, cmp); - }; + return d; + } + function euclidean(p, q) { + return Math.sqrt(squaredEuclidean(p, q)); + } - 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; + var euclidean$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + squaredEuclidean: squaredEuclidean, + euclidean: euclidean + }); - function Heap(cmp) { - this.cmp = cmp != null ? cmp : defaultCmp; - this.nodes = []; - } + /** + * 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 distance/similarity matrix. The matrix is square and has a size equal to the length of + * the data array + */ + function distanceMatrix(data, distanceFn) { + const result = getMatrix(data.length); // Compute upper distance matrix - Heap.prototype.push = function (x) { - return heappush(this.nodes, x, this.cmp); - }; + for (let i = 0; i < data.length; i++) { + for (let j = 0; j <= i; j++) { + result[i][j] = distanceFn(data[i], data[j]); + result[j][i] = result[i][j]; + } + } - Heap.prototype.pop = function () { - return heappop(this.nodes, this.cmp); - }; + return result; + } - Heap.prototype.peek = function () { - return this.nodes[0]; - }; + function getMatrix(size) { + const matrix = []; - Heap.prototype.contains = function (x) { - return this.nodes.indexOf(x) !== -1; - }; + for (let i = 0; i < size; i++) { + const row = []; + matrix.push(row); - Heap.prototype.replace = function (x) { - return heapreplace(this.nodes, x, this.cmp); - }; + for (let j = 0; j < size; j++) { + row.push(0); + } + } - Heap.prototype.pushpop = function (x) { - return heappushpop(this.nodes, x, this.cmp); - }; + return matrix; + } - Heap.prototype.heapify = function () { - return heapify(this.nodes, this.cmp); - }; + var heap = createCommonjsModule(function (module, exports) { + // Generated by CoffeeScript 1.8.0 + (function () { + var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup; - Heap.prototype.updateItem = function (x) { - return updateItem(this.nodes, x, this.cmp); - }; + floor = Math.floor, min = Math.min; + /* + Default comparison function to be used + */ - Heap.prototype.clear = function () { - return this.nodes = []; - }; + defaultCmp = function (x, y) { + if (x < y) { + return -1; + } - Heap.prototype.empty = function () { - return this.nodes.length === 0; - }; + if (x > y) { + return 1; + } - Heap.prototype.size = function () { - return this.nodes.length; - }; + 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. + */ - Heap.prototype.clone = function () { - var heap; - heap = new Heap(); - heap.nodes = this.nodes.slice(0); - return heap; - }; - Heap.prototype.toArray = function () { - return this.nodes.slice(0); - }; + insort = function (a, x, lo, hi, cmp) { + var mid; - 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; - }(); + if (lo == null) { + lo = 0; + } - (function (root, factory) { - { - return module.exports = factory(); + if (cmp == null) { + cmp = defaultCmp; } - })(this, function () { - return Heap; - }); - }).call(commonjsGlobal); - }); - var heap$1 = heap; + if (lo < 0) { + throw new Error('lo must be non-negative'); + } - class Cluster { - constructor() { - this.children = []; - this.height = 0; - this.size = 1; - this.index = -1; - this.isLeaf = false; - } - /** - * Creates an array of clusters where the maximum height is smaller than the threshold - * @param {number} threshold - * @return {Array} - */ + if (hi == null) { + hi = a.length; + } + while (lo < hi) { + mid = floor((lo + hi) / 2); - cut(threshold) { - if (typeof threshold !== 'number') { - throw new TypeError('threshold must be a number'); - } + if (cmp(x, a[mid]) < 0) { + hi = mid; + } else { + lo = mid + 1; + } + } - if (threshold < 0) { - throw new RangeError('threshold must be a positive number'); - } + return [].splice.apply(a, [lo, lo - lo].concat(x)), x; + }; + /* + Push item onto heap, maintaining the heap invariant. + */ - let list = [this]; - const ans = []; - while (list.length > 0) { - const aux = list.shift(); + heappush = function (array, item, cmp) { + if (cmp == null) { + cmp = defaultCmp; + } - if (threshold >= aux.height) { - ans.push(aux); - } else { - list = list.concat(aux.children); + array.push(item); + return _siftdown(array, 0, array.length - 1, cmp); + }; + /* + Pop the smallest item off the heap, maintaining the heap invariant. + */ + + + heappop = function (array, cmp) { + var lastelt, returnitem; + + if (cmp == null) { + cmp = defaultCmp; } - } - return ans; - } - /** - * Merge the leaves in the minimum way to have `groups` number of clusters. - * @param {number} groups - Them number of children the first level of the tree should have. - * @return {Cluster} - */ + lastelt = array.pop(); + if (array.length) { + returnitem = array[0]; + array[0] = lastelt; - group(groups) { - if (!Number.isInteger(groups) || groups < 1) { - throw new RangeError('groups must be a positive integer'); - } + _siftup(array, 0, cmp); + } else { + returnitem = lastelt; + } - const heap = new heap$1((a, b) => { - return b.height - a.height; - }); - heap.push(this); + 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) + */ - while (heap.size() < groups) { - var first = heap.pop(); - if (first.children.length === 0) { - break; + heapreplace = function (array, item, cmp) { + var returnitem; + + if (cmp == null) { + cmp = defaultCmp; } - first.children.forEach(child => heap.push(child)); - } + returnitem = array[0]; + array[0] = item; - var root = new Cluster(); - root.children = heap.toArray(); - root.height = this.height; - return root; - } - /** - * Traverses the tree depth-first and calls the provided callback with each individual node - * @param {function} cb - The callback to be called on each node encounter - */ + _siftup(array, 0, cmp); + return returnitem; + }; + /* + Fast version of a heappush followed by a heappop. + */ - traverse(cb) { - function visit(root, callback) { - callback(root); - if (root.children) { - for (const child of root.children) { - visit(child, callback); - } + heappushpop = function (array, item, cmp) { + var _ref; + + if (cmp == null) { + cmp = defaultCmp; } - } - visit(this, cb); - } - /** - * Returns a list of indices for all the leaves of this cluster. - * The list is ordered in such a way that a dendrogram could be drawn without crossing branches. - * @returns {Array} - */ + if (array.length && cmp(array[0], item) < 0) { + _ref = [array[0], item], item = _ref[0], array[0] = _ref[1]; + _siftup(array, 0, cmp); + } - indices() { - const result = []; - this.traverse(cluster => { - if (cluster.isLeaf) { - result.push(cluster.index); + return item; + }; + /* + Transform list into a heap, in-place, in O(array.length) time. + */ + + + heapify = function (array, cmp) { + var i, _i, _len, _ref1, _results, _results1; + + if (cmp == null) { + cmp = defaultCmp; } - }); - return result; - } - } + _ref1 = function () { + _results1 = []; - function singleLink(dKI, dKJ) { - return Math.min(dKI, dKJ); - } + for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--) { + _results1.push(_j); + } - function completeLink(dKI, dKJ) { - return Math.max(dKI, dKJ); - } + return _results1; + }.apply(this).reverse(); - function averageLink(dKI, dKJ, dIJ, ni, nj) { - const ai = ni / (ni + nj); - const aj = nj / (ni + nj); - return ai * dKI + aj * dKJ; - } + _results = []; - function weightedAverageLink(dKI, dKJ) { - return (dKI + dKJ) / 2; - } + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + i = _ref1[_i]; - function centroidLink(dKI, dKJ, dIJ, ni, nj) { - const ai = ni / (ni + nj); - const aj = nj / (ni + nj); - const b = -(ni * nj) / (ni + nj) ** 2; - return ai * dKI + aj * dKJ + b * dIJ; - } + _results.push(_siftup(array, i, cmp)); + } - function medianLink(dKI, dKJ, dIJ) { - return dKI / 2 + dKJ / 2 - dIJ / 4; - } + return _results; + }; + /* + Update the position of the given item in the heap. + This function should be called every time the item is being modified. + */ - function wardLink(dKI, dKJ, dIJ, ni, nj, nk) { - const ai = (ni + nk) / (ni + nj + nk); - const aj = (nj + nk) / (ni + nj + nk); - const b = -nk / (ni + nj + nk); - return ai * dKI + aj * dKJ + b * dIJ; - } - - function wardLink2(dKI, dKJ, dIJ, ni, nj, nk) { - const ai = (ni + nk) / (ni + nj + nk); - const aj = (nj + nk) / (ni + nj + nk); - const b = -nk / (ni + nj + nk); - return Math.sqrt(ai * dKI * dKI + aj * dKJ * dKJ + b * dIJ * dIJ); - } - /** - * Continuously merge nodes that have the least dissimilarity - * @param {Array>} data - Array of points to be clustered - * @param {object} [options] - * @param {Function} [options.distanceFunction] - * @param {string} [options.method] - Default: `'complete'` - * @param {boolean} [options.isDistanceMatrix] - Is the input already a distance matrix? - * @constructor - */ + updateItem = function (array, item, cmp) { + var pos; - function agnes(data) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - const { - distanceFunction = euclidean, - method = 'complete', - isDistanceMatrix = false - } = options; - let updateFunc; + if (cmp == null) { + cmp = defaultCmp; + } - if (!isDistanceMatrix) { - data = distanceMatrix(data, distanceFunction); - } + pos = array.indexOf(item); - let distanceMatrix$1 = new Matrix(data); - const numLeaves = distanceMatrix$1.rows; // allows to use a string or a given function + if (pos === -1) { + return; + } - if (typeof method === 'string') { - switch (method.toLowerCase()) { - case 'single': - updateFunc = singleLink; - break; + _siftdown(array, 0, pos, cmp); - case 'complete': - updateFunc = completeLink; - break; + return _siftup(array, pos, cmp); + }; + /* + Find the n largest elements in a dataset. + */ - case 'average': - case 'upgma': - updateFunc = averageLink; - break; - case 'wpgma': - updateFunc = weightedAverageLink; - break; + nlargest = function (array, n, cmp) { + var elem, result, _i, _len, _ref; - case 'centroid': - case 'upgmc': - updateFunc = centroidLink; - break; + if (cmp == null) { + cmp = defaultCmp; + } - case 'median': - case 'wpgmc': - updateFunc = medianLink; - break; + result = array.slice(0, n); - case 'ward': - updateFunc = wardLink; - break; + if (!result.length) { + return result; + } - case 'ward2': - updateFunc = wardLink2; - break; + heapify(result, cmp); + _ref = array.slice(n); - default: - throw new RangeError("unknown clustering method: ".concat(method)); - } - } else if (typeof method !== 'function') { - throw new TypeError('method must be a string or function'); - } + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + elem = _ref[_i]; + heappushpop(result, elem, cmp); + } - let clusters = []; + return result.sort(cmp).reverse(); + }; + /* + Find the n smallest elements in a dataset. + */ - for (let i = 0; i < numLeaves; i++) { - const cluster = new Cluster(); - cluster.isLeaf = true; - cluster.index = i; - clusters.push(cluster); - } - for (let n = 0; n < numLeaves - 1; n++) { - const [row, column, distance] = getSmallestDistance(distanceMatrix$1); - const cluster1 = clusters[row]; - const cluster2 = clusters[column]; - const newCluster = new Cluster(); - newCluster.size = cluster1.size + cluster2.size; - newCluster.children.push(cluster1, cluster2); - newCluster.height = distance; - const newClusters = [newCluster]; - const newDistanceMatrix = new Matrix(distanceMatrix$1.rows - 1, distanceMatrix$1.rows - 1); + nsmallest = function (array, n, cmp) { + var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results; - const previous = newIndex => getPreviousIndex(newIndex, Math.min(row, column), Math.max(row, column)); + if (cmp == null) { + cmp = defaultCmp; + } - for (let i = 1; i < newDistanceMatrix.rows; i++) { - const prevI = previous(i); - const prevICluster = clusters[prevI]; - newClusters.push(prevICluster); + if (n * 10 <= array.length) { + result = array.slice(0, n).sort(cmp); - for (let j = 0; j < i; j++) { - if (j === 0) { - const dKI = distanceMatrix$1.get(row, prevI); - const dKJ = distanceMatrix$1.get(prevI, column); - const val = updateFunc(dKI, dKJ, distance, cluster1.size, cluster2.size, prevICluster.size); - newDistanceMatrix.set(i, j, val); - newDistanceMatrix.set(j, i, val); - } else { - // Just copy distance from previous matrix - const val = distanceMatrix$1.get(prevI, previous(j)); - newDistanceMatrix.set(i, j, val); - newDistanceMatrix.set(j, i, val); + if (!result.length) { + return result; } - } - } - clusters = newClusters; - distanceMatrix$1 = newDistanceMatrix; - } + los = result[result.length - 1]; + _ref = array.slice(n); - return clusters[0]; - } + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + elem = _ref[_i]; - function getSmallestDistance(distance) { - let smallest = Infinity; - let smallestI = 0; - let smallestJ = 0; + if (cmp(elem, los) < 0) { + insort(result, elem, 0, null, cmp); + result.pop(); + los = result[result.length - 1]; + } + } - for (let i = 1; i < distance.rows; i++) { - for (let j = 0; j < i; j++) { - if (distance.get(i, j) < smallest) { - smallest = distance.get(i, j); - smallestI = i; - smallestJ = j; + return result; } - } - } - return [smallestI, smallestJ, smallest]; - } + heapify(array, cmp); + _results = []; - function getPreviousIndex(newIndex, prev1, prev2) { - newIndex -= 1; - if (newIndex >= prev1) newIndex++; - if (newIndex >= prev2) newIndex++; - return newIndex; - } + 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)); + } - // export * from './birch'; - // export * './cure'; - // export * from './chameleon'; + return _results; + }; - var index = /*#__PURE__*/Object.freeze({ - __proto__: null, - agnes: agnes - }); + _siftdown = function (array, startpos, pos, cmp) { + var newitem, parent, parentpos; - const defaultOptions$4 = { - distanceFunction: squaredEuclidean - }; - function nearestVector(listVectors, vector) { - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultOptions$4; - const distanceFunction = options.distanceFunction || defaultOptions$4.distanceFunction; - const similarityFunction = options.similarityFunction || defaultOptions$4.similarityFunction; - let vectorIndex = -1; + if (cmp == null) { + cmp = defaultCmp; + } - if (typeof similarityFunction === 'function') { - // maximum similarity - let maxSim = Number.MIN_VALUE; + newitem = array[pos]; - for (let j = 0; j < listVectors.length; j++) { - const sim = similarityFunction(vector, listVectors[j]); + while (pos > startpos) { + parentpos = pos - 1 >> 1; + parent = array[parentpos]; - if (sim > maxSim) { - maxSim = sim; - vectorIndex = j; + if (cmp(newitem, parent) < 0) { + array[pos] = parent; + pos = parentpos; + continue; + } + + break; } - } - } else if (typeof distanceFunction === 'function') { - // minimum distance - let minDist = Number.MAX_VALUE; - for (let i = 0; i < listVectors.length; i++) { - const dist = distanceFunction(vector, listVectors[i]); + return array[pos] = newitem; + }; - if (dist < minDist) { - minDist = dist; - vectorIndex = i; + _siftup = function (array, pos, cmp) { + var childpos, endpos, newitem, rightpos, startpos; + + if (cmp == null) { + cmp = defaultCmp; } - } - } else { - throw new Error("A similarity or distance function it's required"); - } - return vectorIndex; - } + endpos = array.length; + startpos = pos; + newitem = array[pos]; + childpos = 2 * pos + 1; - /** - * 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 - */ + while (childpos < endpos) { + rightpos = childpos + 1; - function calculateDistanceMatrix(data, distance) { - var distanceMatrix = new Array(data.length); + if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) { + childpos = rightpos; + } - 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); + array[pos] = array[childpos]; + pos = childpos; + childpos = 2 * pos + 1; } - if (!distanceMatrix[j]) { - distanceMatrix[j] = new Array(data.length); - } + array[pos] = newitem; + return _siftdown(array, startpos, pos, cmp); + }; - const dist = distance(data[i], data[j]); - distanceMatrix[i][j] = dist; - distanceMatrix[j][i] = dist; - } - } + 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; - 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 Heap(cmp) { + this.cmp = cmp != null ? cmp : defaultCmp; + this.nodes = []; + } - function updateClusterID(data, centers, clusterID, distance) { - for (var i = 0; i < data.length; i++) { - clusterID[i] = nearestVector(centers, data[i], { - distanceFunction: distance - }); - } + Heap.prototype.push = function (x) { + return heappush(this.nodes, x, this.cmp); + }; - 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,...] - */ + Heap.prototype.pop = function () { + return heappop(this.nodes, this.cmp); + }; - function updateCenters(prevCenters, data, clusterID, K) { - const nDim = data[0].length; // copy previous centers + Heap.prototype.peek = function () { + return this.nodes[0]; + }; - var centers = new Array(K); - var centersLen = new Array(K); + Heap.prototype.contains = function (x) { + return this.nodes.indexOf(x) !== -1; + }; - for (var i = 0; i < K; i++) { - centers[i] = new Array(nDim); - centersLen[i] = 0; + Heap.prototype.replace = function (x) { + return heapreplace(this.nodes, x, this.cmp); + }; - for (var j = 0; j < nDim; j++) { - centers[i][j] = 0; - } - } // add the value for all dimensions of the point + Heap.prototype.pushpop = function (x) { + return heappushpop(this.nodes, x, this.cmp); + }; + Heap.prototype.heapify = function () { + return heapify(this.nodes, this.cmp); + }; - for (var l = 0; l < data.length; l++) { - centersLen[clusterID[l]]++; + Heap.prototype.updateItem = function (x) { + return updateItem(this.nodes, x, this.cmp); + }; - for (var dim = 0; dim < nDim; dim++) { - centers[clusterID[l]][dim] += data[l][dim]; - } - } // divides by length + Heap.prototype.clear = function () { + return this.nodes = []; + }; + Heap.prototype.empty = function () { + return this.nodes.length === 0; + }; - 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]; - } - } - } + Heap.prototype.size = function () { + return this.nodes.length; + }; - 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} - */ + Heap.prototype.clone = function () { + var heap; + heap = new Heap(); + heap.nodes = this.nodes.slice(0); + return heap; + }; - function hasConverged(centers, oldCenters, distanceFunction, tolerance) { - for (var i = 0; i < centers.length; i++) { - if (distanceFunction(centers[i], oldCenters[i]) > tolerance) { - return false; - } - } + Heap.prototype.toArray = function () { + return this.nodes.slice(0); + }; - return true; - } + 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; + }(); - const LOOP = 8; - const FLOAT_MUL = 1 / 16777216; - const sh1 = 15; - const sh2 = 18; - const sh3 = 11; + (function (root, factory) { + { + return module.exports = factory(); + } + })(this, function () { + return Heap; + }); + }).call(commonjsGlobal); + }); - function multiply_uint32(n, m) { - n >>>= 0; - m >>>= 0; - const nlo = n & 0xffff; - const nhi = n - nlo; - return (nhi * m >>> 0) + nlo * m >>> 0; - } + var heap$1 = heap; - class XSadd { + class Cluster { 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; + this.children = []; + this.height = 0; + this.size = 1; + this.index = -1; + this.isLeaf = false; } /** - * Returns a floating point number r (0.0 <= r < 1.0) + * Creates an array of clusters where the maximum height is smaller than the threshold + * @param {number} threshold + * @return {Array} */ - getFloat() { - return (this.getUint32() >>> 8) * FLOAT_MUL; - } - - init(seed) { - if (!Number.isInteger(seed)) { - throw new TypeError('seed must be an integer'); + cut(threshold) { + if (typeof threshold !== 'number') { + throw new TypeError('threshold must be a number'); } - 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; + if (threshold < 0) { + throw new RangeError('threshold must be a positive number'); } - this.periodCertification(); + let list = [this]; + const ans = []; - for (let i = 0; i < LOOP; i++) { - this.nextState(); + while (list.length > 0) { + const aux = list.shift(); + + if (threshold >= aux.height) { + ans.push(aux); + } else { + list = list.concat(aux.children); + } } + + return ans; } + /** + * Merge the leaves in the minimum way to have `groups` number of clusters. + * @param {number} groups - Them number of children the first level of the tree should have. + * @return {Cluster} + */ - 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 + group(groups) { + if (!Number.isInteger(groups) || groups < 1) { + throw new RangeError('groups must be a positive integer'); + } - this.state[2] = 65; // A + const heap = new heap$1((a, b) => { + return b.height - a.height; + }); + heap.push(this); - this.state[3] = 68; // D - } - } + while (heap.size() < groups) { + var first = heap.pop(); - 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; - } - - } - - const PROB_TOLERANCE = 0.00000001; + if (first.children.length === 0) { + break; + } - 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; + first.children.forEach(child => heap.push(child)); + } - if (typeof values === 'number') { - valuesArr = getArray(values); - } else { - valuesArr = values.slice(); + var root = new Cluster(); + root.children = heap.toArray(); + root.height = this.height; + return root; } + /** + * Traverses the tree depth-first and calls the provided callback with each individual node + * @param {function} cb - The callback to be called on each node encounter + */ - 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]; - } + traverse(cb) { + function visit(root, callback) { + callback(root); - 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])); + if (root.children) { + for (const child of root.children) { + visit(child, callback); + } + } } - } - if (replace === false && size > valuesArr.length) { - throw new Error('size option is too large'); + visit(this, cb); } + /** + * Returns a list of indices for all the leaves of this cluster. + * The list is ordered in such a way that a dendrogram could be drawn without crossing branches. + * @returns {Array} + */ - 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); - } + indices() { + const result = []; + this.traverse(cluster => { + if (cluster.isLeaf) { + result.push(cluster.index); + } + }); + return result; } - return result; } - function getArray(n) { - const arr = []; + function singleLink(dKI, dKJ) { + return Math.min(dKI, dKJ); + } - for (let i = 0; i < n; i++) { - arr.push(i); - } + function completeLink(dKI, dKJ) { + return Math.max(dKI, dKJ); + } - return arr; + function averageLink(dKI, dKJ, dIJ, ni, nj) { + const ai = ni / (ni + nj); + const aj = nj / (ni + nj); + return ai * dKI + aj * dKJ; } - function randomIndex(n, random, cumSum) { - const rand = random(); + function weightedAverageLink(dKI, dKJ) { + return (dKI + dKJ) / 2; + } - if (!cumSum) { - return Math.floor(rand * n); - } else { - let idx = 0; + function centroidLink(dKI, dKJ, dIJ, ni, nj) { + const ai = ni / (ni + nj); + const aj = nj / (ni + nj); + const b = -(ni * nj) / (ni + nj) ** 2; + return ai * dKI + aj * dKJ + b * dIJ; + } - while (rand > cumSum[idx]) { - idx++; - } + function medianLink(dKI, dKJ, dIJ) { + return dKI / 2 + dKJ / 2 - dIJ / 4; + } - return idx; - } + function wardLink(dKI, dKJ, dIJ, ni, nj, nk) { + const ai = (ni + nk) / (ni + nj + nk); + const aj = (nj + nk) / (ni + nj + nk); + const b = -nk / (ni + nj + nk); + return ai * dKI + aj * dKJ + b * dIJ; } - // tslint:disable-next-line + function wardLink2(dKI, dKJ, dIJ, ni, nj, nk) { + const ai = (ni + nk) / (ni + nj + nk); + const aj = (nj + nk) / (ni + nj + nk); + const b = -nk / (ni + nj + nk); + return Math.sqrt(ai * dKI * dKI + aj * dKJ * dKJ + b * dIJ * dIJ); + } /** - * @classdesc Random class + * Continuously merge nodes that have the least dissimilarity + * @param {Array>} data - Array of points to be clustered + * @param {object} [options] + * @param {Function} [options.distanceFunction] + * @param {string} [options.method] - Default: `'complete'` + * @param {boolean} [options.isDistanceMatrix] - Is the input already a distance matrix? + * @constructor */ - 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() { - let seedOrRandom = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Math.random; - if (typeof seedOrRandom === 'number') { - const xsadd = new XSadd(seedOrRandom); - this.randomGenerator = xsadd.random; - } else { - this.randomGenerator = seedOrRandom; - } + function agnes(data, options = {}) { + const { + distanceFunction = euclidean, + method = 'complete', + isDistanceMatrix = false + } = options; + let updateFunc; + + if (!isDistanceMatrix) { + data = distanceMatrix(data, distanceFunction); } - choice(values, options) { - if (typeof values === 'number') { - return randomChoice(values, options, this.randomGenerator); - } + let distanceMatrix$1 = new Matrix(data); + const numLeaves = distanceMatrix$1.rows; // allows to use a string or a given function - return randomChoice(values, options, this.randomGenerator); - } - /** - * Draw a random number from a uniform distribution on [0,1) - * @return The random number - */ + if (typeof method === 'string') { + switch (method.toLowerCase()) { + case 'single': + updateFunc = singleLink; + break; + case 'complete': + updateFunc = completeLink; + break; - 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. - */ + case 'average': + case 'upgma': + updateFunc = averageLink; + break; + case 'wpgma': + updateFunc = weightedAverageLink; + break; - randInt(low, high) { - if (high === undefined) { - high = low; - low = 0; - } + case 'centroid': + case 'upgmc': + updateFunc = centroidLink; + break; - 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. - */ + case 'median': + case 'wpgmc': + updateFunc = medianLink; + break; + case 'ward': + updateFunc = wardLink; + break; - randomSample(size) { - const result = []; + case 'ward2': + updateFunc = wardLink2; + break; - for (let i = 0; i < size; i++) { - result.push(this.random()); + default: + throw new RangeError(`unknown clustering method: ${method}`); } - - return result; + } else if (typeof method !== 'function') { + throw new TypeError('method must be a string or function'); } - } + let clusters = []; - /** - * 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 - */ + for (let i = 0; i < numLeaves; i++) { + const cluster = new Cluster(); + cluster.isLeaf = true; + cluster.index = i; + clusters.push(cluster); + } - function random(data, K, seed) { - const random = new Random(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) { - const random = new Random(seed); - var ans = new Array(K); // chooses a random point as initial cluster + for (let n = 0; n < numLeaves - 1; n++) { + const [row, column, distance] = getSmallestDistance(distanceMatrix$1); + const cluster1 = clusters[row]; + const cluster2 = clusters[column]; + const newCluster = new Cluster(); + newCluster.size = cluster1.size + cluster2.size; + newCluster.children.push(cluster1, cluster2); + newCluster.height = distance; + const newClusters = [newCluster]; + const newDistanceMatrix = new Matrix(distanceMatrix$1.rows - 1, distanceMatrix$1.rows - 1); - ans[0] = Math.floor(random.random() * data.length); + const previous = newIndex => getPreviousIndex(newIndex, Math.min(row, column), Math.max(row, column)); - if (K > 1) { - // chooses the more distant point - var maxDist = { - dist: -1, - index: -1 - }; + for (let i = 1; i < newDistanceMatrix.rows; i++) { + const prevI = previous(i); + const prevICluster = clusters[prevI]; + newClusters.push(prevICluster); - for (var l = 0; l < data.length; ++l) { - if (distanceMatrix[ans[0]][l] > maxDist.dist) { - maxDist.dist = distanceMatrix[ans[0]][l]; - maxDist.index = l; + for (let j = 0; j < i; j++) { + if (j === 0) { + const dKI = distanceMatrix$1.get(row, prevI); + const dKJ = distanceMatrix$1.get(prevI, column); + const val = updateFunc(dKI, dKJ, distance, cluster1.size, cluster2.size, prevICluster.size); + newDistanceMatrix.set(i, j, val); + newDistanceMatrix.set(j, i, val); + } else { + // Just copy distance from previous matrix + const val = distanceMatrix$1.get(prevI, previous(j)); + newDistanceMatrix.set(i, j, val); + newDistanceMatrix.set(j, i, val); + } } } - 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 - }; + clusters = newClusters; + distanceMatrix$1 = newDistanceMatrix; + } - for (var n = 0; n < k; ++n) { - if (distanceMatrix[n][m] < minDistCent.dist && ans.indexOf(m) === -1) { - minDistCent = { - dist: distanceMatrix[n][m], - index: m - }; - } - } + return clusters[0]; + } - if (minDistCent.dist !== Number.MAX_VALUE && minDistCent.dist > center.dist) { - center = Object.assign({}, minDistCent); - } - } + function getSmallestDistance(distance) { + let smallest = Infinity; + let smallestI = 0; + let smallestJ = 0; - ans[k] = center.index; + for (let i = 1; i < distance.rows; i++) { + for (let j = 0; j < i; j++) { + if (distance.get(i, j) < smallest) { + smallest = distance.get(i, j); + smallestI = i; + smallestJ = j; } } } - return ans.map(index => data[index]); - } // Implementation inspired from scikit + return [smallestI, smallestJ, smallest]; + } - function kmeanspp(X, K) { - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - X = new Matrix(X); - const nSamples = X.rows; - const random = new Random(options.seed); // Set the number of trials + function getPreviousIndex(newIndex, prev1, prev2) { + newIndex -= 1; + if (newIndex >= prev1) newIndex++; + if (newIndex >= prev2) newIndex++; + return newIndex; + } - const centers = []; - const localTrials = options.localTrials || 2 + Math.floor(Math.log(K)); // Pick the first center at random from the dataset + // export * from './birch'; + // export * './cure'; + // export * from './chameleon'; - const firstCenterIdx = random.randInt(nSamples); - centers.push(X.getRow(firstCenterIdx)); // Init closest distances + var index = /*#__PURE__*/Object.freeze({ + __proto__: null, + agnes: agnes + }); - let closestDistSquared = new Matrix(1, X.rows); + const defaultOptions$4 = { + distanceFunction: squaredEuclidean + }; + function nearestVector(listVectors, vector, options = defaultOptions$4) { + const distanceFunction = options.distanceFunction || defaultOptions$4.distanceFunction; + const similarityFunction = options.similarityFunction || defaultOptions$4.similarityFunction; + let vectorIndex = -1; - for (let i = 0; i < X.rows; i++) { - closestDistSquared.set(0, i, squaredEuclidean(X.getRow(i), centers[0])); - } + if (typeof similarityFunction === 'function') { + // maximum similarity + let maxSim = Number.MIN_VALUE; - let cumSumClosestDistSquared = [cumSum(closestDistSquared.getRow(0))]; - const factor = 1 / cumSumClosestDistSquared[0][nSamples - 1]; - let probabilities = Matrix.mul(closestDistSquared, factor); // Iterate over the remaining centers + for (let j = 0; j < listVectors.length; j++) { + const sim = similarityFunction(vector, listVectors[j]); - 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.columns)); - const distanceToCandidates = euclideanDistances(candidates, X); - let bestCandidate; - let bestPot; - let bestDistSquared; + if (sim > maxSim) { + maxSim = sim; + vectorIndex = j; + } + } + } else if (typeof distanceFunction === 'function') { + // minimum distance + let minDist = Number.MAX_VALUE; - for (let j = 0; j < localTrials; j++) { - const newDistSquared = Matrix.min(closestDistSquared, [distanceToCandidates.getRow(j)]); - const newPot = newDistSquared.sum(); + for (let i = 0; i < listVectors.length; i++) { + const dist = distanceFunction(vector, listVectors[i]); - if (bestCandidate === undefined || newPot < bestPot) { - bestCandidate = candidateIdx[j]; - bestPot = newPot; - bestDistSquared = newDistSquared; + if (dist < minDist) { + minDist = dist; + vectorIndex = i; } } - - centers[i] = X.getRow(bestCandidate); - closestDistSquared = bestDistSquared; - cumSumClosestDistSquared = [cumSum(closestDistSquared.getRow(0))]; - probabilities = Matrix.mul(closestDistSquared, 1 / cumSumClosestDistSquared[0][nSamples - 1]); + } else { + throw new Error("A similarity or distance function it's required"); } - return centers; + return vectorIndex; } - function euclideanDistances(A, B) { - const result = new Matrix(A.rows, B.rows); + /** + * 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 + */ - for (let i = 0; i < A.rows; i++) { - for (let j = 0; j < B.rows; j++) { - result.set(i, j, squaredEuclidean(A.getRow(i), B.getRow(j))); + 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); + } + + const dist = distance(data[i], data[j]); + distanceMatrix[i][j] = dist; + distanceMatrix[j][i] = dist; } } - return result; + 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 range(l) { - let r = []; - - for (let i = 0; i < l; i++) { - r.push(i); + function updateClusterID(data, centers, clusterID, distance) { + for (var i = 0; i < data.length; i++) { + clusterID[i] = nearestVector(centers, data[i], { + distanceFunction: distance + }); } - return r; + 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 cumSum(arr) { - let cumSum = [arr[0]]; + function updateCenters(prevCenters, data, clusterID, K) { + const nDim = data[0].length; // copy previous centers - for (let i = 1; i < arr.length; i++) { - cumSum[i] = cumSum[i - 1] + arr[i]; - } + var centers = new Array(K); + var centersLen = new Array(K); - return cumSum; - } + for (var i = 0; i < K; i++) { + centers[i] = new Array(nDim); + centersLen[i] = 0; - const distanceSymbol = Symbol('distance'); - 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; - } - /** - * 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) { - 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} - */ + for (var j = 0; j < nDim; j++) { + centers[i][j] = 0; + } + } // add the value for all dimensions of the point - computeInformation(data) { - var enrichedCentroids = this.centroids.map(function (centroid) { - return { - centroid: centroid, - error: 0, - size: 0 - }; - }); + for (var l = 0; l < data.length; l++) { + centersLen[clusterID[l]]++; - 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++; + for (var dim = 0; dim < nDim; dim++) { + centers[clusterID[l]][dim] += data[l][dim]; } + } // divides by length - for (var j = 0; j < this.centroids.length; j++) { - if (enrichedCentroids[j].size) { - enrichedCentroids[j].error /= enrichedCentroids[j].size; + + for (var id = 0; id < K; id++) { + for (var d = 0; d < nDim; d++) { + if (centersLen[id]) { + centers[id][d] /= centersLen[id]; } else { - enrichedCentroids[j].error = null; + centers[id][d] = prevCenters[id][d]; } } - - return new KMeansResult(this.clusters, enrichedCentroids, this.converged, this.iterations, this[distanceSymbol]); } + return centers; } - - const defaultOptions$5 = { - maxIterations: 100, - tolerance: 1e-6, - withIterations: false, - initialization: 'kmeans++', - distanceFunction: squaredEuclidean - }; /** - * Each step operation for kmeans + * The centers have moved more than the tolerance value? * @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} + * @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 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(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 - */ + 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; + } - function* kmeansGenerator(centers, data, clusterID, K, options) { - var converged = false; - var stepNumber = 0; - var stepResult; + const LOOP = 8; + const FLOAT_MUL = 1 / 16777216; + const sh1 = 15; + const sh2 = 18; + const sh3 = 11; - while (!converged && stepNumber < options.maxIterations) { - stepResult = step(centers, data, clusterID, K, options, ++stepNumber); - yield stepResult.computeInformation(data); - converged = stepResult.converged; - centers = stepResult.centroids; - } + function multiply_uint32(n, m) { + n >>>= 0; + m >>>= 0; + const nlo = n & 0xffff; + const nhi = n - nlo; + return (nhi * m >>> 0) + nlo * m >>> 0; } - /** - * 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 - */ + class XSadd { + constructor(seed = 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) + */ - function kmeans(data, K, options) { - options = Object.assign({}, defaultOptions$5, 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'); + getUint32() { + this.nextState(); + return this.state[3] + this.state[2] >>> 0; } + /** + * Returns a floating point number r (0.0 <= r < 1.0) + */ - 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 = kmeanspp(data, K, options); - break; + getFloat() { + return (this.getUint32() >>> 8) * FLOAT_MUL; + } - case 'random': - centers = random(data, K, options.seed); - break; + init(seed) { + if (!Number.isInteger(seed)) { + throw new TypeError('seed must be an integer'); + } - case 'mostDistant': - centers = mostDistant(data, K, calculateDistanceMatrix(data, options.distanceFunction), options.seed); - break; + this.state[0] = seed; + this.state[1] = 0; + this.state[2] = 0; + this.state[3] = 0; - default: - throw new Error("Unknown initialization method: \"".concat(options.initialization, "\"")); + 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; } - } // infinite loop until convergence + this.periodCertification(); - if (options.maxIterations === 0) { - options.maxIterations = Number.MAX_VALUE; + for (let i = 0; i < LOOP; i++) { + this.nextState(); + } } - var clusterID = new Array(data.length); + periodCertification() { + if (this.state[0] === 0 && this.state[1] === 0 && this.state[2] === 0 && this.state[3] === 0) { + this.state[0] = 88; // X - if (options.withIterations) { - return kmeansGenerator(centers, data, clusterID, K, options); - } else { - var converged = false; - var stepNumber = 0; - var stepResult; + this.state[1] = 83; // S - while (!converged && stepNumber < options.maxIterations) { - stepResult = step(centers, data, clusterID, K, options, ++stepNumber); - converged = stepResult.converged; - centers = stepResult.centroids; + this.state[2] = 65; // A + + this.state[3] = 68; // D } + } - return stepResult.computeInformation(data); + 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; } - } - /** - * @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 + const PROB_TOLERANCE = 0.00000001; - for (var i = 0; i < y.length; i++) { - if (totalPerClasses[y[i]] === undefined) { - totalPerClasses[y[i]] = 0; - classes++; - } + function randomChoice(values, options = {}, random = Math.random) { + const { + size = 1, + replace = false, + probabilities + } = options; + let valuesArr; + let cumSum; - totalPerClasses[y[i]]++; + if (typeof values === 'number') { + valuesArr = getArray(values); + } else { + valuesArr = values.slice(); } - var separatedClasses = new Array(classes); - var currentIndex = new Array(classes); + if (probabilities) { + if (!replace) { + throw new Error('choice with probabilities and no replacement is not implemented'); + } // check input is sane - for (i = 0; i < classes; ++i) { - separatedClasses[i] = new Matrix(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]]++; - } + if (probabilities.length !== valuesArr.length) { + throw new Error('the length of probabilities option should be equal to the number of choices'); + } - return separatedClasses; - } + cumSum = [probabilities[0]]; - class GaussianNB { - /** - * Constructor for the Gaussian Naive Bayes classifier, the parameters here is just for loading purposes. - * @constructor - * @param {boolean} reload - * @param {object} model - */ - constructor(reload, model) { - if (reload) { - this.means = model.means; - this.calculateProbabilities = model.calculateProbabilities; + 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 ${cumSum[cumSum.length - 1]}`); } } - /** - * 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 - */ + if (replace === false && size > valuesArr.length) { + throw new Error('size option is too large'); + } - train(trainingSet, trainingLabels) { - var C1 = Math.sqrt(2 * Math.PI); // constant to precalculate the squared root + const result = []; - trainingSet = Matrix.checkMatrix(trainingSet); + for (let i = 0; i < size; i++) { + const index = randomIndex(valuesArr.length, random, cumSum); + result.push(valuesArr[index]); - if (trainingSet.rows !== trainingLabels.length) { - throw new RangeError('the size of the training set and the training labels must be the same.'); + if (!replace) { + valuesArr.splice(index, 1); } + } - var separatedClasses = separateClasses(trainingSet, trainingLabels); - var calculateProbabilities = new Array(separatedClasses.length); - this.means = new Array(separatedClasses.length); + return result; + } - for (var i = 0; i < separatedClasses.length; ++i) { - var means = separatedClasses[i].mean('column'); - var std = separatedClasses[i].standardDeviation('column', { - mean: means - }); - var logPriorProbability = Math.log(separatedClasses[i].rows / trainingSet.rows); - calculateProbabilities[i] = new Array(means.length + 1); - calculateProbabilities[i][0] = logPriorProbability; + function getArray(n) { + const arr = []; - for (var j = 1; j < means.length + 1; ++j) { - var currentStd = std[j - 1]; - calculateProbabilities[i][j] = [1 / (C1 * currentStd), -2 * currentStd * currentStd]; - } + for (let i = 0; i < n; i++) { + arr.push(i); + } - this.means[i] = means; + 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++; } - this.calculateProbabilities = calculateProbabilities; + return idx; } - /** - * function that predicts each row of the dataset (must be a matrix). - * - * @param {Matrix|Array} dataset - * @return {Array} - */ - + } - predict(dataset) { - dataset = Matrix.checkMatrix(dataset); + // tslint:disable-next-line + /** + * @classdesc Random class + */ - if (dataset.rows === this.calculateProbabilities[0].length) { - throw new RangeError('the dataset must have the same features as the training set'); + 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') { + const xsadd = new XSadd(seedOrRandom); + this.randomGenerator = xsadd.random; + } else { + this.randomGenerator = seedOrRandom; } + } - var predictions = new Array(dataset.rows); - - for (var i = 0; i < predictions.length; ++i) { - predictions[i] = getCurrentClass(dataset.getRow(i), this.means, this.calculateProbabilities); + choice(values, options) { + if (typeof values === 'number') { + return randomChoice(values, options, this.randomGenerator); } - return predictions; + return randomChoice(values, options, this.randomGenerator); } /** - * Function that export the NaiveBayes model. - * @return {object} + * Draw a random number from a uniform distribution on [0,1) + * @return The random number */ - toJSON() { - return { - modelName: 'NaiveBayes', - means: this.means, - calculateProbabilities: this.calculateProbabilities - }; + random() { + return this.randomGenerator(); } /** - * Function that create a GaussianNB classifier with the given model. - * @param {object} model - * @return {GaussianNB} + * 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. */ - static load(model) { - if (model.modelName !== 'NaiveBayes') { - throw new RangeError('The current model is not a Multinomial Naive Bayes, current model:', model.name); + randInt(low, high) { + if (high === undefined) { + high = low; + low = 0; } - return new GaussianNB(true, model); + 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. + */ - } - /** - * @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} - */ - - 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 + randomSample(size) { + const result = []; - 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]); + for (let i = 0; i < size; i++) { + result.push(this.random()); } - currentProbability = Math.exp(currentProbability); - - if (currentProbability > maxProbability) { - maxProbability = currentProbability; - predictedClass = i; - } + return result; } - 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} + * 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 calculateLogProbability(value, mean, C1, C2) { - value = value - mean; - return Math.log(C1 * Math.exp(value * value / C2)); + function random(data, K, seed) { + const random = new Random(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 + */ - class MultinomialNB { - /** - * Constructor for Multinomial Naive Bayes, the model parameter is for load purposes. - * @constructor - * @param {object} model - for load purposes. - */ - constructor(model) { - if (model) { - this.conditionalProbability = Matrix.checkMatrix(model.conditionalProbability); - this.priorProbability = Matrix.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 - */ + function mostDistant(data, K, distanceMatrix, seed) { + const random = new Random(seed); + var ans = new Array(K); // chooses a random point as initial cluster + ans[0] = Math.floor(random.random() * data.length); - train(trainingSet, trainingLabels) { - trainingSet = Matrix.checkMatrix(trainingSet); + if (K > 1) { + // chooses the more distant point + var maxDist = { + dist: -1, + index: -1 + }; - if (trainingSet.rows !== trainingLabels.length) { - throw new RangeError('the size of the training set and the training labels must be the same.'); + for (var l = 0; l < data.length; ++l) { + if (distanceMatrix[ans[0]][l] > maxDist.dist) { + maxDist.dist = distanceMatrix[ans[0]][l]; + maxDist.index = l; + } } - var separateClass = separateClasses(trainingSet, trainingLabels); - this.priorProbability = new Matrix(separateClass.length, 1); + ans[1] = maxDist.index; - for (var i = 0; i < separateClass.length; ++i) { - this.priorProbability.set(i, 0, Math.log(separateClass[i].rows / trainingSet.rows)); - } + 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 + }; - var features = trainingSet.columns; - this.conditionalProbability = new Matrix(separateClass.length, features); + for (var m = 0; m < data.length; ++m) { + // minimum distance to centers + var minDistCent = { + dist: Number.MAX_VALUE, + index: -1 + }; - for (i = 0; i < separateClass.length; ++i) { - var classValues = Matrix.checkMatrix(separateClass[i]); - var total = classValues.sum(); - var divisor = total + features; - this.conditionalProbability.setRow(i, Matrix.rowVector(classValues.sum('column')).add(1).div(divisor).apply(matrixLog)); + for (var n = 0; n < k; ++n) { + if (distanceMatrix[n][m] < minDistCent.dist && ans.indexOf(m) === -1) { + minDistCent = { + dist: distanceMatrix[n][m], + index: m + }; + } + } + + if (minDistCent.dist !== Number.MAX_VALUE && minDistCent.dist > center.dist) { + center = Object.assign({}, minDistCent); + } + } + + ans[k] = center.index; + } } } - /** - * Retrieves the predictions for the dataset with the current model. - * @param {Matrix|Array} dataset - * @return {Array} - predictions from the dataset. - */ + return ans.map(index => data[index]); + } // Implementation inspired from scikit - predict(dataset) { - dataset = Matrix.checkMatrix(dataset); - var predictions = new Array(dataset.rows); + function kmeanspp(X, K, options = {}) { + X = new Matrix(X); + const nSamples = X.rows; + const random = new Random(options.seed); // Set the number of trials - for (var i = 0; i < dataset.rows; ++i) { - var currentElement = dataset.getRowVector(i); - const v = Matrix.columnVector(this.conditionalProbability.clone().mulRowVector(currentElement).sum('row')); - predictions[i] = v.add(this.priorProbability).maxIndex()[0]; - } + const centers = []; + const localTrials = options.localTrials || 2 + Math.floor(Math.log(K)); // Pick the first center at random from the dataset - return predictions; - } - /** - * Function that saves the current model. - * @return {object} - model in JSON format. - */ + const firstCenterIdx = random.randInt(nSamples); + centers.push(X.getRow(firstCenterIdx)); // Init closest distances + let closestDistSquared = new Matrix(1, X.rows); - toJSON() { - return { - name: 'MultinomialNB', - priorProbability: this.priorProbability, - conditionalProbability: this.conditionalProbability - }; + for (let i = 0; i < X.rows; i++) { + closestDistSquared.set(0, i, squaredEuclidean(X.getRow(i), centers[0])); } - /** - * Creates a new MultinomialNB from the given model - * @param {object} model - * @return {MultinomialNB} - */ + let cumSumClosestDistSquared = [cumSum(closestDistSquared.getRow(0))]; + const factor = 1 / cumSumClosestDistSquared[0][nSamples - 1]; + let probabilities = Matrix.mul(closestDistSquared, factor); // Iterate over the remaining centers - static load(model) { - if (model.name !== 'MultinomialNB') { - throw new RangeError("".concat(model.name, " is not a Multinomial Naive Bayes")); + 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.columns)); + const distanceToCandidates = euclideanDistances(candidates, X); + let bestCandidate; + let bestPot; + let bestDistSquared; + + for (let j = 0; j < localTrials; j++) { + const newDistSquared = Matrix.min(closestDistSquared, [distanceToCandidates.getRow(j)]); + const newPot = newDistSquared.sum(); + + if (bestCandidate === undefined || newPot < bestPot) { + bestCandidate = candidateIdx[j]; + bestPot = newPot; + bestDistSquared = newDistSquared; + } } - return new MultinomialNB(model); + centers[i] = X.getRow(bestCandidate); + closestDistSquared = bestDistSquared; + cumSumClosestDistSquared = [cumSum(closestDistSquared.getRow(0))]; + probabilities = Matrix.mul(closestDistSquared, 1 / cumSumClosestDistSquared[0][nSamples - 1]); } + return centers; } - function matrixLog(i, j) { - this.set(i, j, Math.log(this.get(i, j))); - } + function euclideanDistances(A, B) { + const result = new Matrix(A.rows, B.rows); + for (let i = 0; i < A.rows; i++) { + for (let j = 0; j < B.rows; j++) { + result.set(i, j, squaredEuclidean(A.getRow(i), B.getRow(j))); + } + } + return result; + } - var index$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - GaussianNB: GaussianNB, - MultinomialNB: MultinomialNB - }); + function range(l) { + let r = []; - /* - * 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 - */ - function Node(obj, dimension, parent) { - this.obj = obj; - this.left = null; - this.right = null; - this.parent = parent; - this.dimension = dimension; + for (let i = 0; i < l; i++) { + r.push(i); + } + + return r; } - 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); + function cumSum(arr) { + let cumSum = [arr[0]]; - for (var i = 0; i < this.dimensions.length; i++) { - this.dimensions[i] = i; - } + for (let i = 1; i < arr.length; i++) { + cumSum[i] = cumSum[i - 1] + arr[i]; + } - this.root = buildTree(points, 0, null, this.dimensions); - } + return cumSum; + } - this.metric = metric; - } // Convert to a JSON serializable structure; this just requires removing - // the `parent` property + const distanceSymbol = Symbol('distance'); + 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; + } + /** + * 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 + */ - toJSON() { - const result = toJSONImpl(this.root); - result.dimensions = this.dimensions; - return result; + 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} + */ - nearest(point, maxNodes, maxDistance) { - const metric = this.metric; - const dimensions = this.dimensions; - var i; - const bestNodes = new BinaryHeap(function (e) { - return -e[1]; - }); - function nearestSearch(node) { - const dimension = dimensions[node.dimension]; - const ownDistance = metric(point, node.obj); - const linearPoint = {}; - var bestChild, linearDistance, otherChild, i; + computeInformation(data) { + var enrichedCentroids = this.centroids.map(function (centroid) { + return { + centroid: centroid, + error: 0, + size: 0 + }; + }); - function saveNode(node, distance) { - bestNodes.push([node, distance]); + 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 (bestNodes.size() > maxNodes) { - bestNodes.pop(); - } + for (var j = 0; j < this.centroids.length; j++) { + if (enrichedCentroids[j].size) { + enrichedCentroids[j].error /= enrichedCentroids[j].size; + } else { + enrichedCentroids[j].error = null; } + } - 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 new KMeansResult(this.clusters, enrichedCentroids, this.converged, this.iterations, this[distanceSymbol]); + } - linearDistance = metric(linearPoint, node.obj); + } - if (node.right === null && node.left === null) { - if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { - saveNode(node, ownDistance); - } + const defaultOptions$5 = { + 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} + */ - return; - } + 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(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 + */ - 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; - } - } - nearestSearch(bestChild); + function* kmeansGenerator(centers, data, clusterID, K, options) { + var converged = false; + var stepNumber = 0; + var stepResult; - if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { - saveNode(node, ownDistance); - } + 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 + */ - 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); - } - } - } + function kmeans(data, K, options) { + options = Object.assign({}, defaultOptions$5, options); - if (maxDistance) { - for (i = 0; i < maxNodes; i += 1) { - bestNodes.push([null, maxDistance]); - } - } + if (K <= 0 || K > data.length || !Number.isInteger(K)) { + throw new Error('K should be a positive integer smaller than the number of points'); + } - if (this.root) { - nearestSearch(this.root); + 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 = kmeanspp(data, K, options); + break; - const result = []; + case 'random': + centers = random(data, K, options.seed); + break; - 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]]); - } + case 'mostDistant': + centers = mostDistant(data, K, calculateDistanceMatrix(data, options.distanceFunction), options.seed); + break; + + default: + throw new Error(`Unknown initialization method: "${options.initialization}"`); } + } // infinite loop until convergence - return result; + + if (options.maxIterations === 0) { + options.maxIterations = Number.MAX_VALUE; } - } + var clusterID = new Array(data.length); - 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; - } + if (options.withIterations) { + return kmeansGenerator(centers, data, clusterID, K, options); + } else { + var converged = false; + var stepNumber = 0; + var stepResult; - function buildTree(points, depth, parent, dimensions) { - const dim = depth % dimensions.length; + while (!converged && stepNumber < options.maxIterations) { + stepResult = step(centers, data, clusterID, K, options, ++stepNumber); + converged = stepResult.converged; + centers = stepResult.centroids; + } - if (points.length === 0) { - return null; + return stepResult.computeInformation(data); } + } - if (points.length === 1) { - return new Node(points[0], dim, parent); - } + /** + * @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} + */ - 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; - } + function separateClasses(X, y) { + var features = X.columns; + var classes = 0; + var totalPerClasses = new Array(10000); // max upperbound of classes - function restoreParent(root) { - if (root.left) { - root.left.parent = root; - restoreParent(root.left); - } + for (var i = 0; i < y.length; i++) { + if (totalPerClasses[y[i]] === undefined) { + totalPerClasses[y[i]] = 0; + classes++; + } - if (root.right) { - root.right.parent = root; - restoreParent(root.right); + totalPerClasses[y[i]]++; } - } // Binary heap implementation from: - // http://eloquentjavascript.net/appendix2.html + var separatedClasses = new Array(classes); + var currentIndex = new Array(classes); - class BinaryHeap { - constructor(scoreFunction) { - this.content = []; - this.scoreFunction = scoreFunction; + for (i = 0; i < classes; ++i) { + separatedClasses[i] = new Matrix(totalPerClasses[i], features); + currentIndex[i] = 0; } - 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); + for (i = 0; i < X.rows; ++i) { + separatedClasses[y[i]].setRow(currentIndex[y[i]], X.getRow(i)); + currentIndex[y[i]]++; } - 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. + return separatedClasses; + } - 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); + class GaussianNB { + /** + * Constructor for the Gaussian Naive Bayes classifier, the parameters here is just for loading purposes. + * @constructor + * @param {boolean} reload + * @param {object} model + */ + constructor(reload, model) { + if (reload) { + this.means = model.means; + this.calculateProbabilities = model.calculateProbabilities; } - - return result; - } - - peek() { - return this.content[0]; - } - - size() { - return this.content.length; } + /** + * 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 + */ - 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. - const parentN = Math.floor((n + 1) / 2) - 1; - const parent = this.content[parentN]; // Swap the elements if the parent is greater. + train(trainingSet, trainingLabels) { + var C1 = Math.sqrt(2 * Math.PI); // constant to precalculate the squared root - if (this.scoreFunction(element) < this.scoreFunction(parent)) { - this.content[parentN] = element; - this.content[n] = parent; // Update 'n' to continue at the new position. + trainingSet = Matrix.checkMatrix(trainingSet); - n = parentN; - } else { - // Found a parent that is less, no need to move it further. - break; - } + if (trainingSet.rows !== trainingLabels.length) { + throw new RangeError('the size of the training set and the training labels must be the same.'); } - } - - 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; - } - } // If the element needs to be moved, swap it, and continue. + var separatedClasses = 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 = separatedClasses[i].mean('column'); + var std = separatedClasses[i].standardDeviation('column', { + mean: means + }); + var logPriorProbability = Math.log(separatedClasses[i].rows / trainingSet.rows); + calculateProbabilities[i] = new Array(means.length + 1); + calculateProbabilities[i][0] = logPriorProbability; - if (swap !== null) { - this.content[n] = this.content[swap]; - this.content[swap] = element; - n = swap; - } else { - // Otherwise, we are done. - break; + for (var j = 1; j < means.length + 1; ++j) { + var currentStd = std[j - 1]; + calculateProbabilities[i][j] = [1 / (C1 * currentStd), -2 * currentStd * currentStd]; } - } - } - - } - - class 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, - k = classes.size + 1 - } = options; - const points = new Array(dataset.length); - - for (var i = 0; i < points.length; ++i) { - points[i] = dataset[i].slice(); - } - for (i = 0; i < labels.length; ++i) { - points[i].push(labels[i]); + this.means[i] = means; } - this.kdTree = new KDTree(points, distance); - this.k = k; - this.classes = classes; - this.isEuclidean = distance === euclidean; + this.calculateProbabilities = calculateProbabilities; } /** - * 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} + * function that predicts each row of the dataset (must be a matrix). + * + * @param {Matrix|Array} dataset + * @return {Array} */ - static load(model) { - let distance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : euclidean; + predict(dataset) { + dataset = Matrix.checkMatrix(dataset); - if (model.name !== 'KNN') { - throw new Error("invalid model: ".concat(model.name)); + if (dataset.rows === this.calculateProbabilities[0].length) { + throw new RangeError('the dataset must have the same features as the training set'); } - if (!model.isEuclidean && distance === euclidean) { - throw new Error('a custom distance function was used to create the model. Please provide it again'); - } + var predictions = new Array(dataset.rows); - if (model.isEuclidean && distance !== euclidean) { - throw new Error('the model was created with the default distance function. Do not load it with another one'); + for (var i = 0; i < predictions.length; ++i) { + predictions[i] = getCurrentClass(dataset.getRow(i), this.means, this.calculateProbabilities); } - return new KNN(true, model, distance); + return predictions; } /** - * Return a JSON containing the kd-tree model. - * @return {object} JSON KNN model. + * Function that export the NaiveBayes model. + * @return {object} */ toJSON() { return { - name: 'KNN', - kdTree: this.kdTree, - k: this.k, - classes: Array.from(this.classes), - isEuclidean: this.isEuclidean + modelName: 'NaiveBayes', + means: this.means, + calculateProbabilities: this.calculateProbabilities }; } /** - * Predicts the output given the matrix to predict. - * @param {Array} dataset - * @return {Array} predictions + * Function that create a GaussianNB classifier with the given model. + * @param {object} model + * @return {GaussianNB} */ - 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); - - for (var i = 0; i < dataset.length; i++) { - predictions[i] = getSinglePrediction(this, dataset[i]); - } - - return predictions; - } + static load(model) { + if (model.modelName !== 'NaiveBayes') { + throw new RangeError('The current model is not a Multinomial Naive Bayes, current model:', model.name); } - throw new TypeError('dataset to predict must be an array or a matrix'); + return new GaussianNB(true, model); } } + /** + * @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} + */ - 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; + function getCurrentClass(currentCase, mean, classes) { + var maxProbability = 0; + var predictedClass = -1; // going through all precalculated values for the classes - for (var element of knn.classes) { - pointsPerClass[element] = 0; - } + for (var i = 0; i < classes.length; ++i) { + var currentProbability = classes[i][0]; // initialize with the prior probability - for (var i = 0; i < nearestPoints.length; ++i) { - var currentClass = nearestPoints[i][0][lastElement]; - var currentPoints = ++pointsPerClass[currentClass]; + 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]); + } - if (currentPoints > maxPoints) { - predictedClass = currentClass; - maxPoints = currentPoints; + currentProbability = Math.exp(currentProbability); + + if (currentProbability > maxProbability) { + maxProbability = currentProbability; + predictedClass = i; } } return predictedClass; } - /** * @private - * Function that given vector, returns its norm - * @param {Vector} X - * @return {number} Norm of the vector - */ - - 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. - * */ - - function pow2array(i, j) { - this.set(i, j, this.get(i, j) ** 2); - } - /** - * @private - * Function that initialize an array of matrices. - * @param {Array} array - * @param {boolean} isMatrix - * @return {Array} array with the matrices initialized. + * 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 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 Matrix(array[i][j]) : undefined; - } - } - } else { - for (i = 0; i < array.length; ++i) { - array[i] = new Matrix(array[i]); - } - } - return array; + function calculateLogProbability(value, mean, C1, C2) { + value = value - mean; + return Math.log(C1 * Math.exp(value * value / C2)); } - /** - * @class PLS - */ - - class PLS { + class MultinomialNB { /** - * 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. + * Constructor for Multinomial Naive Bayes, the model parameter is for load purposes. + * @constructor * @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 = Matrix.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; + constructor(model) { + if (model) { + this.conditionalProbability = Matrix.checkMatrix(model.conditionalProbability); + this.priorProbability = Matrix.checkMatrix(model.priorProbability); } } /** - * 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 - * + * Train the classifier with the current training set and labels, the labels must be numbers between 0 and n. * @param {Matrix|Array} trainingSet - * @param {Matrix|Array} trainingValues + * @param {Array} trainingLabels */ - train(trainingSet, trainingValues) { + train(trainingSet, trainingLabels) { trainingSet = Matrix.checkMatrix(trainingSet); - trainingValues = Matrix.checkMatrix(trainingValues); - if (trainingSet.length !== trainingValues.length) { - throw new RangeError('The number of X rows must be equal to the number of Y rows'); + if (trainingSet.rows !== trainingLabels.length) { + throw new RangeError('the size of the training set and the training labels must be the same.'); } - this.meanX = trainingSet.mean('column'); - this.stdDevX = trainingSet.standardDeviation('column', { - mean: this.meanX, - unbiased: true - }); - this.meanY = trainingValues.mean('column'); - this.stdDevY = trainingValues.standardDeviation('column', { - mean: this.meanY, - unbiased: true - }); - - if (this.scale) { - trainingSet = trainingSet.clone().subRowVector(this.meanX).divRowVector(this.stdDevX); - trainingValues = trainingValues.clone().subRowVector(this.meanY).divRowVector(this.stdDevY); - } + var separateClass = separateClasses(trainingSet, trainingLabels); + this.priorProbability = new Matrix(separateClass.length, 1); - if (this.latentVectors === undefined) { - this.latentVectors = Math.min(trainingSet.rows - 1, trainingSet.columns); + for (var i = 0; i < separateClass.length; ++i) { + this.priorProbability.set(i, 0, Math.log(separateClass[i].rows / trainingSet.rows)); } - 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 = Matrix.zeros(rx, n); - var P = Matrix.zeros(cx, n); - var U = Matrix.zeros(ry, n); - var Q = Matrix.zeros(cy, n); - var B = Matrix.zeros(n, n); - var W = P.clone(); - var k = 0; - - while (norm(trainingValues) > tolerance && k < n) { - var transposeX = trainingSet.transpose(); - var transposeY = trainingValues.transpose(); - var tIndex = maxSumColIndex(trainingSet.clone().mul(trainingSet)); - var uIndex = maxSumColIndex(trainingValues.clone().mul(trainingValues)); - var t1 = trainingSet.getColumnVector(tIndex); - var u = trainingValues.getColumnVector(uIndex); - var t = Matrix.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); - } + var features = trainingSet.columns; + this.conditionalProbability = new Matrix(separateClass.length, features); - t = t1; - var num = transposeX.mmul(t); - var den = t.transpose().mmul(t).get(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).get(0, 0); - var b = num.div(den).get(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.set(k, k, b); - k++; + for (i = 0; i < separateClass.length; ++i) { + var classValues = Matrix.checkMatrix(separateClass[i]); + var total = classValues.sum(); + var divisor = total + features; + this.conditionalProbability.setRow(i, Matrix.rowVector(classValues.sum('column')).add(1).div(divisor).apply(matrixLog)); } - - 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).get(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. + * Retrieves the predictions for the dataset with the current model. + * @param {Matrix|Array} dataset + * @return {Array} - predictions from the dataset. */ predict(dataset) { - var X = Matrix.checkMatrix(dataset); + dataset = Matrix.checkMatrix(dataset); + var predictions = new Array(dataset.rows); - if (this.scale) { - X = X.subRowVector(this.meanX).divRowVector(this.stdDevX); + for (var i = 0; i < dataset.rows; ++i) { + var currentElement = dataset.getRowVector(i); + const v = Matrix.columnVector(this.conditionalProbability.clone().mulRowVector(currentElement).sum('row')); + predictions[i] = v.add(this.priorProbability).maxIndex()[0]; } - 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; + return predictions; } /** - * Export the current model to JSON. - * @return {object} - Current model. + * Function that saves the current model. + * @return {object} - model in JSON format. */ 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 + name: 'MultinomialNB', + priorProbability: this.priorProbability, + conditionalProbability: this.conditionalProbability }; } /** - * Load a PLS model from a JSON Object + * Creates a new MultinomialNB from the given model * @param {object} model - * @return {PLS} - PLS object from the given model + * @return {MultinomialNB} */ static load(model) { - if (model.name !== 'PLS') { - throw new RangeError("Invalid model: ".concat(model.name)); + if (model.name !== 'MultinomialNB') { + throw new RangeError(`${model.name} is not a Multinomial Naive Bayes`); } - return new PLS(true, model); + return new MultinomialNB(model); } } - /** - * @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 maxSumColIndex(data) { - return Matrix.rowVector(data.sum('column')).maxIndex()[0]; + function matrixLog(i, j) { + this.set(i, j, Math.log(this.get(i, j))); } - /** - * @class KOPLS + var index$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + GaussianNB: GaussianNB, + MultinomialNB: MultinomialNB + }); + + /* + * 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 */ + function Node(obj, dimension, parent) { + this.obj = obj; + this.left = null; + this.right = null; + this.parent = parent; + this.dimension = dimension; + } - class KOPLS { - /** - * 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 Matrix(model.trainingSet); - this.YLoadingMat = new Matrix(model.YLoadingMat); - this.SigmaPow = new Matrix(model.SigmaPow); - this.YScoreMat = new Matrix(model.YScoreMat); - this.predScoreMat = initializeMatrices(model.predScoreMat, false); - this.YOrthLoadingVec = initializeMatrices(model.YOrthLoadingVec, false); - this.YOrthEigen = model.YOrthEigen; - this.YOrthScoreMat = initializeMatrices(model.YOrthScoreMat, false); - this.toNorm = initializeMatrices(model.toNorm, false); - this.TURegressionCoeff = initializeMatrices(model.TURegressionCoeff, false); - this.kernelX = initializeMatrices(model.kernelX, true); - this.kernel = model.kernel; - this.orthogonalComp = model.orthogonalComp; - this.predictiveComp = model.predictiveComp; + 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 { - if (options.predictiveComponents === undefined) { - throw new RangeError('no predictive components found!'); - } - - if (options.orthogonalComponents === undefined) { - throw new RangeError('no orthogonal components found!'); - } + this.dimensions = new Array(points[0].length); - if (options.kernel === undefined) { - throw new RangeError('no kernel found!'); + for (var i = 0; i < this.dimensions.length; i++) { + this.dimensions[i] = i; } - this.orthogonalComp = options.orthogonalComponents; - this.predictiveComp = options.predictiveComponents; - this.kernel = options.kernel; + this.root = buildTree(points, 0, null, this.dimensions); } - } - /** - * Train the K-OPLS model with the given training set and labels. - * @param {Matrix|Array} trainingSet - * @param {Matrix|Array} trainingValues - */ - - train(trainingSet, trainingValues) { - trainingSet = Matrix.checkMatrix(trainingSet); - trainingValues = Matrix.checkMatrix(trainingValues); // to save and compute kernel with the prediction dataset. + this.metric = metric; + } // Convert to a JSON serializable structure; this just requires removing + // the `parent` property - this.trainingSet = trainingSet.clone(); - var kernelX = this.kernel.compute(trainingSet); - var Identity = Matrix.eye(kernelX.rows, kernelX.rows, 1); - var temp = kernelX; - kernelX = new Array(this.orthogonalComp + 1); - for (let i = 0; i < this.orthogonalComp + 1; i++) { - kernelX[i] = new Array(this.orthogonalComp + 1); - } + toJSON() { + const result = toJSONImpl(this.root); + result.dimensions = this.dimensions; + return result; + } - kernelX[0][0] = temp; - var result = new SingularValueDecomposition(trainingValues.transpose().mmul(kernelX[0][0]).mmul(trainingValues), { - computeLeftSingularVectors: true, - computeRightSingularVectors: false + nearest(point, maxNodes, maxDistance) { + const metric = this.metric; + const dimensions = this.dimensions; + var i; + const bestNodes = new BinaryHeap(function (e) { + return -e[1]; }); - 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 = Matrix.pow(Sigma, -0.5); // to avoid errors, check infinity - SigmaPow.apply(function (i, j) { - if (this.get(i, j) === Infinity) { - this.set(i, j, 0); - } - }); + function nearestSearch(node) { + const dimension = dimensions[node.dimension]; + const ownDistance = metric(point, node.obj); + const linearPoint = {}; + var bestChild, linearDistance, otherChild, i; - 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] = inverse(TpiPrime.mmul(predScoreMat[i])).mmul(TpiPrime).mmul(YScoreMat); - result = new SingularValueDecomposition(TpiPrime.mmul(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.get(0, 0); - YOrthScoreMat[i] = 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] = Matrix.sqrt(toiPrime.mmul(YOrthScoreMat[i])); - YOrthScoreMat[i] = YOrthScoreMat[i].divRowVector(YOrthScoreNorm[i]); - var ITo = 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); - } + function saveNode(node, distance) { + bestNodes.push([node, distance]); - var lastScoreMat = predScoreMat[this.orthogonalComp] = kernelX[0][this.orthogonalComp].transpose().mmul(YScoreMat).mmul(SigmaPow); - var lastTpPrime = lastScoreMat.transpose(); - TURegressionCoeff[this.orthogonalComp] = 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 - */ + if (bestNodes.size() > maxNodes) { + bestNodes.pop(); + } + } + 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]]; + } + } - predict(toPredict) { - var KTestTrain = this.kernel.compute(toPredict, this.trainingSet); - var temp = KTestTrain; - KTestTrain = new Array(this.orthogonalComp + 1); + linearDistance = metric(linearPoint, node.obj); - for (let i = 0; i < this.orthogonalComp + 1; i++) { - KTestTrain[i] = new Array(this.orthogonalComp + 1); - } + if (node.right === null && node.left === null) { + if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { + saveNode(node, ownDistance); + } - KTestTrain[0][0] = temp; - var YOrthScoreVector = new Array(this.orthogonalComp); - var predScoreMat = new Array(this.orthogonalComp); - var i; + return; + } - for (i = 0; i < this.orthogonalComp; ++i) { - predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow); - 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)); - YOrthScoreVector[i] = YOrthScoreVector[i].divRowVector(this.toNorm[i]); - var scoreMatPrime = this.YOrthScoreMat[i].transpose(); - KTestTrain[i + 1][0] = Matrix.sub(KTestTrain[i][0], YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[0][i].transpose())); - var p1 = 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); - } + 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; + } + } - 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. - */ + nearestSearch(bestChild); + if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { + saveNode(node, ownDistance); + } - 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} - */ + 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); + } + } + } - static load(model, kernel) { - if (model.name !== 'K-OPLS') { - throw new RangeError("Invalid model: ".concat(model.name)); + if (maxDistance) { + for (i = 0; i < maxNodes; i += 1) { + bestNodes.push([null, maxDistance]); + } } - if (!kernel) { - throw new RangeError('You must provide a kernel for the model!'); + if (this.root) { + nearestSearch(this.root); } - model.kernel = kernel; - return new KOPLS(true, model); + const 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; } } - /** - * 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'); - } + 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; + } - if (labels.length !== matrix.length) { - throw new Error('Confusion matrix and labels should have the same length'); - } + function buildTree(points, depth, parent, dimensions) { + const dim = depth % dimensions.length; - this.labels = labels; - this.matrix = matrix; + if (points.length === 0) { + return null; } - /** - * 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) { - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + if (points.length === 1) { + return new Node(points[0], dim, parent); + } - if (predicted.length !== actual.length) { - throw new Error('predicted and actual must have the same length'); - } + 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; + } - let distinctLabels; + function restoreParent(root) { + if (root.left) { + root.left.parent = root; + restoreParent(root.left); + } - if (options.labels) { - distinctLabels = new Set(options.labels); - } else { - distinctLabels = new Set([...actual, ...predicted]); - } + if (root.right) { + root.right.parent = root; + restoreParent(root.right); + } + } // Binary heap implementation from: + // http://eloquentjavascript.net/appendix2.html - distinctLabels = Array.from(distinctLabels); - if (options.sort) { - distinctLabels.sort(options.sort); - } // Create confusion matrix and fill with 0's + 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. - const matrix = Array.from({ - length: distinctLabels.length - }); + this.bubbleUp(this.content.length - 1); + } - for (let i = 0; i < matrix.length; i++) { - matrix[i] = new Array(matrix.length); - matrix[i].fill(0); - } + 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. - for (let i = 0; i < predicted.length; i++) { - const actualIdx = distinctLabels.indexOf(actual[i]); - const predictedIdx = distinctLabels.indexOf(predicted[i]); + var end = this.content.pop(); // If there are any elements left, put the end element at the + // start, and let it sink down. - if (actualIdx >= 0 && predictedIdx >= 0) { - matrix[actualIdx][predictedIdx]++; - } + if (this.content.length > 0) { + this.content[0] = end; + this.sinkDown(0); } - return new ConfusionMatrix(matrix, distinctLabels); + return result; } - /** - * Get the confusion matrix - * @return {Array >} - */ - - getMatrix() { - return this.matrix; + peek() { + return this.content[0]; } - getLabels() { - return this.labels; + size() { + return this.content.length; } - /** - * Get the total number of samples - * @return {number} - */ + 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. - getTotalCount() { - let predicted = 0; + 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. - for (var i = 0; i < this.matrix.length; i++) { - for (var j = 0; j < this.matrix.length; j++) { - predicted += this.matrix[i][j]; + 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; } } - - return predicted; } - /** - * Get the total number of true predictions - * @return {number} - */ + 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); - getTrueCount() { - var count = 0; - - for (var i = 0; i < this.matrix.length; i++) { - count += this.matrix[i][i]; - } + 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. - return count; - } - /** - * Get the total number of false predictions. - * @return {number} - */ + 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. - 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} - */ + if (child1Score < elemScore) { + swap = child1N; + } + } // Do the same checks for the other child. - 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} - */ + 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. - 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]; - } + if (swap !== null) { + this.content[n] = this.content[swap]; + this.content[swap] = element; + n = swap; + } else { + // Otherwise, we are done. + break; } } - - return count; } + + } + + class KNN { /** - * Get the number of false positive predictions. - * @param {any} label - The label that should be considered "positive" - * @return {number} + * @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) { + 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, + k = classes.size + 1 + } = options; + const points = new Array(dataset.length); - getFalsePositiveCount(label) { - const index = this.getIndex(label); - var count = 0; + for (var i = 0; i < points.length; ++i) { + points[i] = dataset[i].slice(); + } - for (var i = 0; i < this.matrix.length; i++) { - if (i !== index) { - count += this.matrix[i][index]; - } + for (i = 0; i < labels.length; ++i) { + points[i].push(labels[i]); } - return count; + this.kdTree = new KDTree(points, distance); + this.k = k; + this.classes = classes; + this.isEuclidean = distance === euclidean; } /** - * Get the number of false negative predictions. - * @param {any} label - The label that should be considered "positive" - * @return {number} + * 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} */ - getFalseNegativeCount(label) { - const index = this.getIndex(label); - var count = 0; + static load(model, distance = euclidean) { + if (model.name !== 'KNN') { + throw new Error(`invalid model: ${model.name}`); + } - for (var i = 0; i < this.matrix.length; i++) { - if (i !== index) { - count += this.matrix[index][i]; - } + if (!model.isEuclidean && distance === euclidean) { + throw new Error('a custom distance function was used to create the model. Please provide it again'); } - return count; + if (model.isEuclidean && distance !== euclidean) { + 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); } /** - * Get the number of real positive samples. - * @param {any} label - The label that should be considered "positive" - * @return {number} + * Return a JSON containing the kd-tree model. + * @return {object} JSON KNN model. */ - 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); + toJSON() { + return { + name: 'KNN', + kdTree: this.kdTree, + k: this.k, + classes: Array.from(this.classes), + isEuclidean: this.isEuclidean + }; } /** - * 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} + * Predicts the output given the matrix to predict. + * @param {Array} dataset + * @return {Array} predictions */ - 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] - */ - + 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); - 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} - */ + for (var i = 0; i < dataset.length; i++) { + predictions[i] = getSinglePrediction(this, dataset[i]); + } + return predictions; + } + } - getTrueNegativeRate(label) { - return this.getTrueNegativeCount(label) / this.getNegativeCount(label); + throw new TypeError('dataset to predict must be an array or a matrix'); } - /** - * 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) { - 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} - */ - + 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; - getNegativePredictiveValue(label) { - const TN = this.getTrueNegativeCount(label); - return TN / (TN + this.getFalseNegativeCount(label)); + for (var element of knn.classes) { + pointsPerClass[element] = 0; } - /** - * 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} - */ + for (var i = 0; i < nearestPoints.length; ++i) { + var currentClass = nearestPoints[i][0][lastElement]; + var currentPoints = ++pointsPerClass[currentClass]; - getFalseNegativeRate(label) { - return 1 - this.getTruePositiveRate(label); + if (currentPoints > maxPoints) { + predictedClass = currentClass; + maxPoints = currentPoints; + } } - /** - * 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} - */ + return predictedClass; + } - 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} - */ - + /** + * @private + * Function that given vector, returns its norm + * @param {Vector} X + * @return {number} Norm of the vector + */ - 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} - */ + 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. + * */ + function pow2array(i, j) { + this.set(i, j, this.get(i, j) ** 2); + } + /** + * @private + * Function that initialize an array of matrices. + * @param {Array} array + * @param {boolean} isMatrix + * @return {Array} array with the matrices initialized. + */ - getFalseOmissionRate(label) { - const FN = this.getFalseNegativeCount(label); - return FN / (FN + this.getTruePositiveCount(label)); + function initializeMatrices(array, isMatrix) { + if (isMatrix) { + for (let i = 0; i < array.length; ++i) { + for (let j = 0; j < array[i].length; ++j) { + let elem = array[i][j]; + array[i][j] = elem !== null ? new Matrix(array[i][j]) : undefined; + } + } + } else { + for (let i = 0; i < array.length; ++i) { + array[i] = new Matrix(array[i]); + } } - /** - * F1 score - * {@link https://en.wikipedia.org/wiki/F1_score} - * @param {any} label - The label that should be considered "positive" - * @return {number} - */ - - 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} - */ + return array; + } + /** + * @class PLS + */ - 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)); - } + class PLS { /** - * Informedness - * {@link https://en.wikipedia.org/wiki/Youden%27s_J_statistic} - * @param {any} label - The label that should be considered "positive" - * @return {number} + * 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. */ - - - getInformedness(label) { - return this.getTruePositiveRate(label) + this.getTrueNegativeRate(label) - 1; + constructor(options, model) { + if (options === true) { + this.meanX = model.meanX; + this.stdDevX = model.stdDevX; + this.meanY = model.meanY; + this.stdDevY = model.stdDevY; + this.PBQ = Matrix.checkMatrix(model.PBQ); + this.R2X = model.R2X; + this.scale = model.scale; + this.scaleMethod = model.scaleMethod; + this.tolerance = model.tolerance; + } else { + let { + tolerance = 1e-5, + scale = true + } = options; + this.tolerance = tolerance; + this.scale = scale; + this.latentVectors = options.latentVectors; + } } /** - * Markedness - * @param {any} label - The label that should be considered "positive" - * @return {number} + * 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 */ - 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]] - */ + train(trainingSet, trainingValues) { + trainingSet = Matrix.checkMatrix(trainingSet); + trainingValues = Matrix.checkMatrix(trainingValues); + if (trainingSet.length !== trainingValues.length) { + throw new RangeError('The number of X rows must be equal to the number of Y rows'); + } - getConfusionTable(label) { - return [[this.getTruePositiveCount(label), this.getFalseNegativeCount(label)], [this.getFalsePositiveCount(label), this.getTrueNegativeCount(label)]]; + this.meanX = trainingSet.mean('column'); + this.stdDevX = trainingSet.standardDeviation('column', { + mean: this.meanX, + unbiased: true + }); + this.meanY = trainingValues.mean('column'); + this.stdDevY = trainingValues.standardDeviation('column', { + mean: this.meanY, + unbiased: true + }); + + if (this.scale) { + trainingSet = trainingSet.clone().subRowVector(this.meanX).divRowVector(this.stdDevX); + trainingValues = trainingValues.clone().subRowVector(this.meanY).divRowVector(this.stdDevY); + } + + if (this.latentVectors === undefined) { + this.latentVectors = Math.min(trainingSet.rows - 1, trainingSet.columns); + } + + let rx = trainingSet.rows; + let cx = trainingSet.columns; + let ry = trainingValues.rows; + let cy = trainingValues.columns; + let ssqXcal = trainingSet.clone().mul(trainingSet).sum(); // for the r² + + let sumOfSquaresY = trainingValues.clone().mul(trainingValues).sum(); + let tolerance = this.tolerance; + let n = this.latentVectors; + let T = Matrix.zeros(rx, n); + let P = Matrix.zeros(cx, n); + let U = Matrix.zeros(ry, n); + let Q = Matrix.zeros(cy, n); + let B = Matrix.zeros(n, n); + let W = P.clone(); + let k = 0; + let t; + let w; + let q; + let p; + + while (norm(trainingValues) > tolerance && k < n) { + let transposeX = trainingSet.transpose(); + let transposeY = trainingValues.transpose(); + let tIndex = maxSumColIndex(trainingSet.clone().mul(trainingSet)); + let uIndex = maxSumColIndex(trainingValues.clone().mul(trainingValues)); + let t1 = trainingSet.getColumnVector(tIndex); + let u = trainingValues.getColumnVector(uIndex); + t = Matrix.zeros(rx, 1); + + while (norm(t1.clone().sub(t)) > tolerance) { + w = transposeX.mmul(u); + w.div(norm(w)); + t = t1; + t1 = trainingSet.mmul(w); + q = transposeY.mmul(t1); + q.div(norm(q)); + u = trainingValues.mmul(q); + } + + t = t1; + let num = transposeX.mmul(t); + let den = t.transpose().mmul(t).get(0, 0); + p = num.div(den); + let pnorm = norm(p); + p.div(pnorm); + t.mul(pnorm); + w.mul(pnorm); + num = u.transpose().mmul(t); + den = t.transpose().mmul(t).get(0, 0); + let b = num.div(den).get(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.set(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); + 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).get(0, 0); } /** - * Get total accuracy. - * @return {number} - The ratio between the number of true predictions and total number of classifications ([0-1]) + * Predicts the behavior of the given dataset. + * @param {Matrix|Array} dataset - data to be predicted. + * @return {Matrix} - predictions of each element of the dataset. */ - getAccuracy() { - let correct = 0; - let incorrect = 0; + predict(dataset) { + let X = Matrix.checkMatrix(dataset); - 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]; - } + if (this.scale) { + X = X.subRowVector(this.meanX).divRowVector(this.stdDevX); } - return correct / (correct + incorrect); + let Y = X.mmul(this.PBQ); + Y = Y.mulRowVector(this.stdDevY).addRowVector(this.meanY); + return Y; } /** - * 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 + * Returns the explained variance on training of the PLS model + * @return {number} */ - getCount(actual, predicted) { - const actualIndex = this.getIndex(actual); - const predictedIndex = this.getIndex(predicted); - return this.matrix[actualIndex][predictedIndex]; + getExplainedVariance() { + return this.R2X; } /** - * Compute the general prediction accuracy - * @deprecated Use getAccuracy - * @return {number} - The prediction accuracy ([0-1] + * Export the current model to JSON. + * @return {object} - Current model. */ - get accuracy() { - return this.getAccuracy(); + 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 + }; } /** - * Compute the number of predicted observations - * @deprecated Use getTotalCount - * @return {number} + * Load a PLS model from a JSON Object + * @param {object} model + * @return {PLS} - PLS object from the given model */ - get total() { - return this.getTotalCount(); + static load(model) { + if (model.name !== 'PLS') { + throw new RangeError(`Invalid model: ${model.name}`); + } + + return new PLS(true, model); } } + /** + * @private + * Function that returns the index where the sum of each + * column vector is maximum. + * @param {Matrix} data + * @return {number} index of the maximum + */ - var src$1 = ConfusionMatrix; - - const defaultOptions$6 = { - mode: 'index' - }; - - var src$2 = function* src(M, N, options) { - options = Object.assign({}, defaultOptions$6, options); - var a = new Array(N); - var c = new Array(M); - var b = new Array(N); - var p = new Array(N + 2); - var x, y, z; // init a and b + function maxSumColIndex(data) { + return Matrix.rowVector(data.sum('column')).maxIndex()[0]; + } - for (var i = 0; i < N; i++) { - a[i] = i; - if (i < N - M) b[i] = 0;else b[i] = 1; - } // init c + /** + * @class KOPLS + */ + class KOPLS { + /** + * 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 Matrix(model.trainingSet); + this.YLoadingMat = new Matrix(model.YLoadingMat); + this.SigmaPow = new Matrix(model.SigmaPow); + this.YScoreMat = new Matrix(model.YScoreMat); + this.predScoreMat = initializeMatrices(model.predScoreMat, false); + this.YOrthLoadingVec = initializeMatrices(model.YOrthLoadingVec, false); + this.YOrthEigen = model.YOrthEigen; + this.YOrthScoreMat = initializeMatrices(model.YOrthScoreMat, false); + this.toNorm = initializeMatrices(model.toNorm, false); + this.TURegressionCoeff = initializeMatrices(model.TURegressionCoeff, false); + this.kernelX = 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!'); + } - for (i = 0; i < M; i++) { - c[i] = N - M + i; - } // init p + if (options.orthogonalComponents === undefined) { + throw new RangeError('no orthogonal components found!'); + } + if (options.kernel === undefined) { + throw new RangeError('no kernel found!'); + } - 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; + this.orthogonalComp = options.orthogonalComponents; + this.predictiveComp = options.predictiveComponents; + this.kernel = options.kernel; + } } + /** + * Train the K-OPLS model with the given training set and labels. + * @param {Matrix|Array} trainingSet + * @param {Matrix|Array} trainingValues + */ - 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; - } + train(trainingSet, trainingValues) { + trainingSet = Matrix.checkMatrix(trainingSet); + trainingValues = Matrix.checkMatrix(trainingValues); // to save and compute kernel with the prediction dataset. - p[j] = 0; - x = z = 0; - p[1] = 1; - y = j - 1; - } else { - if (j > 1) { - p[j - 1] = 0; - } + this.trainingSet = trainingSet.clone(); + let kernelX = this.kernel.compute(trainingSet); + let Identity = Matrix.eye(kernelX.rows, kernelX.rows, 1); + let temp = kernelX; + kernelX = new Array(this.orthogonalComp + 1); - do { - j++; - } while (p[j] > 0); + for (let i = 0; i < this.orthogonalComp + 1; i++) { + kernelX[i] = new Array(this.orthogonalComp + 1); + } - k = j - 1; - i = j; + kernelX[0][0] = temp; + let result = new SingularValueDecomposition(trainingValues.transpose().mmul(kernelX[0][0]).mmul(trainingValues), { + computeLeftSingularVectors: true, + computeRightSingularVectors: false + }); + let YLoadingMat = result.leftSingularVectors; + let 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); + let YScoreMat = trainingValues.mmul(YLoadingMat); + let predScoreMat = new Array(this.orthogonalComp + 1); + let TURegressionCoeff = new Array(this.orthogonalComp + 1); + let YOrthScoreMat = new Array(this.orthogonalComp); + let YOrthLoadingVec = new Array(this.orthogonalComp); + let YOrthEigen = new Array(this.orthogonalComp); + let YOrthScoreNorm = new Array(this.orthogonalComp); + let SigmaPow = Matrix.pow(Sigma, -0.5); // to avoid errors, check infinity - while (p[i] === 0) { - p[i++] = -1; + SigmaPow.apply(function (i, j) { + if (this.get(i, j) === Infinity) { + this.set(i, j, 0); } + }); - 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; - } - } + for (let i = 0; i < this.orthogonalComp; ++i) { + predScoreMat[i] = kernelX[0][i].transpose().mmul(YScoreMat).mmul(SigmaPow); + let TpiPrime = predScoreMat[i].transpose(); + TURegressionCoeff[i] = inverse(TpiPrime.mmul(predScoreMat[i])).mmul(TpiPrime).mmul(YScoreMat); + result = new SingularValueDecomposition(TpiPrime.mmul(Matrix.sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime))).mmul(predScoreMat[i]), { + computeLeftSingularVectors: true, + computeRightSingularVectors: false + }); + let CoTemp = result.leftSingularVectors; + let SoTemp = result.diagonalMatrix; + YOrthLoadingVec[i] = CoTemp.subMatrix(0, CoTemp.rows - 1, 0, 0); + YOrthEigen[i] = SoTemp.get(0, 0); + YOrthScoreMat[i] = Matrix.sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime)).mmul(predScoreMat[i]).mmul(YOrthLoadingVec[i]).mul(Math.pow(YOrthEigen[i], -0.5)); + let toiPrime = YOrthScoreMat[i].transpose(); + YOrthScoreNorm[i] = Matrix.sqrt(toiPrime.mmul(YOrthScoreMat[i])); + YOrthScoreMat[i] = YOrthScoreMat[i].divRowVector(YOrthScoreNorm[i]); + let ITo = 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); } - return 1; + let lastScoreMat = predScoreMat[this.orthogonalComp] = kernelX[0][this.orthogonalComp].transpose().mmul(YScoreMat).mmul(SigmaPow); + let lastTpPrime = lastScoreMat.transpose(); + TURegressionCoeff[this.orthogonalComp] = 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 + */ - if (options.mode === 'index') { - yield c.slice(); - while (twiddle()) { - c[z] = a[x]; - yield c.slice(); - } - } else if (options.mode === 'mask') { - yield b.slice(); + predict(toPredict) { + let KTestTrain = this.kernel.compute(toPredict, this.trainingSet); + let temp = KTestTrain; + KTestTrain = new Array(this.orthogonalComp + 1); - while (twiddle()) { - b[x] = 1; - b[y] = 0; - yield b.slice(); + for (let i = 0; i < this.orthogonalComp + 1; i++) { + KTestTrain[i] = new Array(this.orthogonalComp + 1); } - } else { - throw new Error('Invalid mode'); - } - }; - const CV = {}; - /** - * 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); - } - - 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 - */ + KTestTrain[0][0] = temp; + let YOrthScoreVector = new Array(this.orthogonalComp); + let predScoreMat = new Array(this.orthogonalComp); + let i; + for (i = 0; i < this.orthogonalComp; ++i) { + predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow); + 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)); + YOrthScoreVector[i] = YOrthScoreVector[i].divRowVector(this.toNorm[i]); + let scoreMatPrime = this.YOrthScoreMat[i].transpose(); + KTestTrain[i + 1][0] = Matrix.sub(KTestTrain[i][0], YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[0][i].transpose())); + let p1 = Matrix.sub(KTestTrain[i][0], KTestTrain[i][i].mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime)); + let p2 = YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[i][i]); + let p3 = p2.mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime); + KTestTrain[i + 1][i + 1] = p1.sub(p2).add(p3); + } - CV.leavePOut = function (Classifier, features, labels, classifierOptions, p) { - if (typeof classifierOptions === 'function') { - var callback = classifierOptions; - p = labels; - labels = features; - features = Classifier; + predScoreMat[i] = KTestTrain[i][0].mmul(this.YScoreMat).mmul(this.SigmaPow); + let 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. + */ - check(features, labels); - const distinct = getDistinct(labels); - const confusionMatrix = initMatrix(distinct.length, distinct.length); - var N = features.length; - var gen = src$2(p, N); - var allIdx = new Array(N); - for (let i = 0; i < N; i++) { - allIdx[i] = i; + 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} + */ - for (const testIdx of gen) { - var trainIdx = allIdx.slice(); - for (let i = testIdx.length - 1; i >= 0; i--) { - trainIdx.splice(testIdx[i], 1); + static load(model, kernel) { + if (model.name !== 'K-OPLS') { + throw new RangeError(`Invalid model: ${model.name}`); } - if (callback) { - validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback); - } else { - validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct); + if (!kernel) { + throw new RangeError('You must provide a kernel for the model!'); } + + model.kernel = kernel; + return new KOPLS(true, model); } - return new src$1(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 + * 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'); + } - CV.kFold = function (Classifier, features, labels, classifierOptions, k) { - if (typeof classifierOptions === 'function') { - var callback = classifierOptions; - k = labels; - labels = features; - features = Classifier; + 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 + */ - check(features, labels); - const distinct = getDistinct(labels); - const 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; - } + static fromLabels(actual, predicted, options = {}) { + if (predicted.length !== actual.length) { + throw new Error('predicted and actual must have the same length'); + } - var l = Math.floor(N / k); // create random k-folds + let distinctLabels; - var current = []; - var folds = []; + if (options.labels) { + distinctLabels = new Set(options.labels); + } else { + distinctLabels = new Set([...actual, ...predicted]); + } - while (allIdx.length) { - var randi = Math.floor(Math.random() * allIdx.length); - current.push(allIdx[randi]); - allIdx.splice(randi, 1); + distinctLabels = Array.from(distinctLabels); - if (current.length === l) { - folds.push(current); - current = []; - } - } + if (options.sort) { + distinctLabels.sort(options.sort); + } // Create confusion matrix and fill with 0's - if (current.length) folds.push(current); - folds = folds.slice(0, k); - for (i = 0; i < folds.length; i++) { - var testIdx = folds[i]; - var trainIdx = []; + const matrix = Array.from({ + length: distinctLabels.length + }); - for (var j = 0; j < folds.length; j++) { - if (j !== i) trainIdx = trainIdx.concat(folds[j]); + for (let i = 0; i < matrix.length; i++) { + matrix[i] = new Array(matrix.length); + matrix[i].fill(0); } - if (callback) { - validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback); - } else { - validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct); - } - } + for (let i = 0; i < predicted.length; i++) { + const actualIdx = distinctLabels.indexOf(actual[i]); + const predictedIdx = distinctLabels.indexOf(predicted[i]); - return new src$1(confusionMatrix, distinct); - }; + if (actualIdx >= 0 && predictedIdx >= 0) { + matrix[actualIdx][predictedIdx]++; + } + } - function check(features, labels) { - if (features.length !== labels.length) { - throw new Error('features and labels should have the same length'); + return new ConfusionMatrix(matrix, distinctLabels); } - } + /** + * Get the confusion matrix + * @return {Array >} + */ - function initMatrix(rows, columns) { - return new Array(rows).fill(0).map(() => new Array(columns).fill(0)); - } - function getDistinct(arr) { - var s = new Set(); + getMatrix() { + return this.matrix; + } - for (let i = 0; i < arr.length; i++) { - s.add(arr[i]); + getLabels() { + return this.labels; } + /** + * Get the total number of samples + * @return {number} + */ - return Array.from(s); - } - function validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct) { - const { - testFeatures, - trainFeatures, - testLabels, - trainLabels - } = getTrainTest(features, labels, testIdx, trainIdx); - var classifier; + getTotalCount() { + let predicted = 0; - if (Classifier.prototype.train) { - classifier = new Classifier(classifierOptions); - classifier.train(trainFeatures, trainLabels); - } else { - classifier = new Classifier(trainFeatures, trainLabels, classifierOptions); - } + for (let i = 0; i < this.matrix.length; i++) { + for (let j = 0; j < this.matrix.length; j++) { + predicted += this.matrix[i][j]; + } + } - var predictedLabels = classifier.predict(testFeatures); - updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct); - } + return predicted; + } + /** + * Get the total number of true predictions + * @return {number} + */ - 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 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]); + getTrueCount() { + let count = 0; - if (actualIdx < 0 || predictedIdx < 0) { - // eslint-disable-next-line no-console - console.warn("ignore unknown predicted label ".concat(predictedLabels[i])); + for (let i = 0; i < this.matrix.length; i++) { + count += this.matrix[i][i]; } - confusionMatrix[actualIdx][predictedIdx]++; + return count; } - } + /** + * Get the total number of false predictions. + * @return {number} + */ - 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]; - }) - }; - } - var src$3 = CV; - - function logistic(val) { - return 1 / (1 + Math.exp(-val)); - } + 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} + */ - function expELU(val, param) { - return val < 0 ? param * (Math.exp(val) - 1) : val; - } - function softExponential(val, param) { - if (param < 0) { - return -Math.log(1 - param * (val + param)) / param; + 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} + */ - if (param > 0) { - return (Math.exp(param * val) - 1) / param + param; - } - return val; - } + getTrueNegativeCount(label) { + const index = this.getIndex(label); + let count = 0; - function softExponentialPrime(val, param) { - if (param < 0) { - return 1 / (1 - param * (param + val)); - } else { - return Math.exp(param * val); - } - } + for (let i = 0; i < this.matrix.length; i++) { + for (let j = 0; j < this.matrix.length; j++) { + if (i !== index && j !== index) { + count += this.matrix[i][j]; + } + } + } - 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 + return count; } - }; + /** + * Get the number of false positive predictions. + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - class Layer { + + getFalsePositiveCount(label) { + const index = this.getIndex(label); + let count = 0; + + for (let i = 0; i < this.matrix.length; i++) { + if (i !== index) { + count += this.matrix[i][index]; + } + } + + return count; + } /** - * @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; + * Get the number of false negative predictions. + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - this.activationFunction = function (i, j) { - this.set(i, j, actFunction(this.get(i, j))); - }; - this.derivate = function (i, j) { - this.set(i, j, derFunction(this.get(i, j))); - }; + getFalseNegativeCount(label) { + const index = this.getIndex(label); + let count = 0; - if (options.model) { - // load model - this.W = Matrix.Matrix.checkMatrix(options.W); - this.b = Matrix.Matrix.checkMatrix(options.b); - } else { - // default constructor - this.W = Matrix.Matrix.rand(this.inputSize, this.outputSize); - this.b = Matrix.Matrix.zeros(1, this.outputSize); - this.W.apply(function (i, j) { - this.set(i, j, this.get(i, j) / Math.sqrt(options.inputSize)); - }); + for (let i = 0; i < this.matrix.length; i++) { + if (i !== index) { + count += this.matrix[index][i]; + } } + + return count; } /** - * @private - * propagate the given input through the current layer. - * @param {Matrix} X - input. - * @return {Matrix} output at the current layer. - */ + * Get the number of real positive samples. + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - forward(X) { - var z = X.mmul(this.W).addRowVector(this.b); - z.apply(this.activationFunction); - this.a = z.clone(); - return z; + getPositiveCount(label) { + return this.getTruePositiveCount(label) + this.getFalseNegativeCount(label); } /** - * @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. - */ + * Get the number of real negative samples. + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ - backpropagation(delta, a) { - this.dW = a.transpose().mmul(delta); - this.db = Matrix.Matrix.rowVector(delta.sum('column')); - var aCopy = a.clone(); - return delta.mmul(this.W.transpose()).mul(aCopy.apply(this.derivate)); + getNegativeCount(label) { + return this.getTrueNegativeCount(label) + this.getFalsePositiveCount(label); } /** - * @private - * Function that updates the weights at the current layer with the derivatives. - */ + * 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} + */ - 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)); + getIndex(label) { + const index = this.labels.indexOf(label); + if (index === -1) throw new Error('The label does not exist'); + return index; } /** - * @private - * Export the current layer to JSON. - * @return {object} model - */ + * 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] + */ - 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 - }; + getTruePositiveRate(label) { + return this.getTruePositiveCount(label) / this.getPositiveCount(label); } /** - * @private - * Creates a new Layer with the given model. - * @param {object} model - * @return {Layer} - */ + * 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) { + 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} + */ + + + 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} + */ + + + 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} + */ + + + 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) { + 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} + */ + + + 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} + */ + + + 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} + */ + + + 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} + */ + + + getInformedness(label) { + return this.getTruePositiveRate(label) + this.getTrueNegativeRate(label) - 1; + } + /** + * Markedness + * @param {any} label - The label that should be considered "positive" + * @return {number} + */ + + + 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]] + */ + + + 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]) + */ + + + getAccuracy() { + let correct = 0; + let incorrect = 0; + + for (let i = 0; i < this.matrix.length; i++) { + for (let 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) { + 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] + */ + + + get accuracy() { + return this.getAccuracy(); + } + /** + * Compute the number of predicted observations + * @deprecated Use getTotalCount + * @return {number} + */ + + + get total() { + return this.getTotalCount(); + } + + } + + var lib = createCommonjsModule(function (module, exports) { + (function (global, factory) { + factory() ; + })(commonjsGlobal, function () { + + function createCommonjsModule(fn, module) { + return module = { + exports: {} + }, fn(module, module.exports), module.exports; + } + + 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$1; // 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$1) { + // 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$1; + 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$1; + } + } 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$1; + 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$1, + done: true + }; + } + + Context.prototype = { + constructor: Context, + reset: function (skipTempReset) { + this.prev = 0; + this.next = 0; // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + + this.sent = this._sent = undefined$1; + this.done = false; + this.delegate = null; + this.method = "next"; + this.arg = undefined$1; + 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$1; + } + } + } + }, + stop: function () { + this.done = true; + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + dispatchException: function (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$1; + } + + 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 (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 (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 (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 (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 (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$1; + } + + 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); + }); + }); + }); + + /** + * get folds indexes + * @param {Array} features + * @param {Number} k - number of folds, a + */ + function getFolds(features, k = 5) { + let N = features.length; + let allIdx = new Array(N); + + for (let i = 0; i < N; i++) { + allIdx[i] = i; + } + + let l = Math.floor(N / k); // create random k-folds + + let current = []; + let folds = []; + + while (allIdx.length) { + let randi = Math.floor(Math.random() * allIdx.length); + current.push(allIdx[randi]); + allIdx.splice(randi, 1); + + if (current.length === l) { + folds.push(current); + current = []; + } + } // we push the remaining to the last fold so that the total length is + // preserved. Otherwise the Q2 will fail. + + + if (current.length) current.forEach(e => folds[k - 1].push(e)); + folds = folds.slice(0, k); + let foldsIndex = folds.map((x, idx) => ({ + testIndex: x, + trainIndex: [].concat(...folds.filter((el, idx2) => idx2 !== idx)) + })); + return foldsIndex; + } + + /** + * A function to sample a dataset maintaining classes equilibrated + * @param {Array} classVector - an array containing class or group information + * @param {Number} fraction - a fraction of the class to sample + * @return {Object} - an object with indexes + */ + function sampleAClass(classVector, fraction) { + // sort the vector + let classVectorSorted = JSON.parse(JSON.stringify(classVector)); + let result = Array.from(Array(classVectorSorted.length).keys()).sort((a, b) => classVectorSorted[a] < classVectorSorted[b] ? -1 : classVectorSorted[b] < classVectorSorted[a] | 0); + classVectorSorted.sort((a, b) => a < b ? -1 : b < a | 0); // counts the class elements + + let counts = {}; + classVectorSorted.forEach(x => counts[x] = (counts[x] || 0) + 1); // pick a few per class + + let indexOfSelected = []; + Object.keys(counts).forEach((e, i) => { + let shift = []; + Object.values(counts).reduce((a, c, item) => shift[item] = a + c, 0); + let arr = [...Array(counts[e]).keys()]; + let r = []; + + for (let j = 0; j < Math.floor(counts[e] * fraction); j++) { + let n = arr[Math.floor(Math.random() * arr.length)]; + r.push(n); + let ind = arr.indexOf(n); + arr.splice(ind, 1); + } + + if (i === 0) { + indexOfSelected = indexOfSelected.concat(r); + } else { + indexOfSelected = indexOfSelected.concat(r.map(x => x + shift[i - 1])); + } + }); // sort back the index + + let trainIndex = []; + indexOfSelected.forEach(e => trainIndex.push(result[e])); + let testIndex = []; + let mask = []; + classVector.forEach((el, idx) => { + if (trainIndex.includes(idx)) { + mask.push(true); + } else { + mask.push(false); + testIndex.push(idx); + } + }); + return { + trainIndex, + testIndex, + mask + }; + } + + /** + * 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 + */ + + function leaveOneOut(Classifier, features, labels, classifierOptions) { + if (typeof labels === 'function') { + let callback = labels; + labels = features; + features = Classifier; + return leavePOut(features, labels, 1, callback); + } + + return 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 + */ + + function leavePOut(Classifier, features, labels, classifierOptions, p) { + let callback; + + if (typeof classifierOptions === 'function') { + callback = classifierOptions; + p = labels; + labels = features; + features = Classifier; + } + + check(features, labels); + const distinct = getDistinct(labels); + const confusionMatrix = initMatrix(distinct.length, distinct.length); + let N = features.length; + let gen = lib(p, N); + let allIdx = new Array(N); + + for (let i = 0; i < N; i++) { + allIdx[i] = i; + } + + for (const testIdx of gen) { + let trainIdx = allIdx.slice(); + + for (let 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); + } + } + + 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 + */ + + function kFold(Classifier, features, labels, classifierOptions, k) { + let callback; + + if (typeof classifierOptions === 'function') { + callback = classifierOptions; + k = labels; + labels = features; + features = Classifier; + } + + check(features, labels); + const distinct = getDistinct(labels); + const confusionMatrix = initMatrix(distinct.length, distinct.length); + let folds = getFolds(features, k); + + for (let i = 0; i < folds.length; i++) { + let testIdx = folds[i].testIndex; + let trainIdx = folds[i].trainIndex; + + if (callback) { + validateWithCallback(features, labels, testIdx, trainIdx, confusionMatrix, distinct, callback); + } else { + validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct); + } + } + + return new ConfusionMatrix(confusionMatrix, distinct); + } + + function check(features, labels) { + if (features.length !== labels.length) { + throw new Error('features and labels should have the same length'); + } + } + + function initMatrix(rows, columns) { + return new Array(rows).fill(0).map(() => new Array(columns).fill(0)); + } + + function getDistinct(arr) { + let s = new Set(); + + for (let i = 0; i < arr.length; i++) { + s.add(arr[i]); + } + + return Array.from(s); + } + + function validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct) { + const { + testFeatures, + trainFeatures, + testLabels, + trainLabels + } = getTrainTest(features, labels, testIdx, trainIdx); + let classifier; + + if (Classifier.prototype.train) { + classifier = new Classifier(classifierOptions); + classifier.train(trainFeatures, trainLabels); + } else { + classifier = new Classifier(trainFeatures, trainLabels, classifierOptions); + } + + let predictedLabels = classifier.predict(testFeatures); + updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct); + } + + 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 updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct) { + for (let 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 ${predictedLabels[i]}`); + } + + confusionMatrix[actualIdx][predictedIdx]++; + } + } + + 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]; + }) + }; + } + + var index$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + leaveOneOut: leaveOneOut, + leavePOut: leavePOut, + kFold: kFold, + getTrainTest: getTrainTest, + sampleAClass: sampleAClass, + getFolds: getFolds + }); + + /** + * OPLS loop + * @param {Array} x a matrix with features + * @param {Array} y an array of labels (dependent variable) + * @param {Object} options an object with options + * @return {Object} an object with model (filteredX: err, + loadingsXOrtho: pOrtho, + scoresXOrtho: tOrtho, + weightsXOrtho: wOrtho, + weightsPred: w, + loadingsXpred: p, + scoresXpred: t, + loadingsY:) + */ + + function OPLSNipals(x, y, options = {}) { + const { + numberOSC = 100 + } = options; + let X = Matrix.checkMatrix(x); + let Y = Matrix.checkMatrix(y); + let u = Y.getColumnVector(0); + let diff = 1; + let t, c, w, uNew; + + for (let i = 0; i < numberOSC && diff > 1e-10; i++) { + w = u.transpose().mmul(X).div(u.transpose().mmul(u).get(0, 0)); + w = w.transpose().div(norm(w)); + t = X.mmul(w).div(w.transpose().mmul(w).get(0, 0)); // t_h paso 3 + // calc loading + + c = t.transpose().mmul(Y).div(t.transpose().mmul(t).get(0, 0)); // calc new u and compare with one in previus iteration (stop criterion) + + uNew = Y.mmul(c.transpose()); + uNew = uNew.div(c.transpose().mmul(c).get(0, 0)); + + if (i > 0) { + diff = uNew.clone().sub(u).pow(2).sum() / uNew.clone().pow(2).sum(); + } + + u = uNew.clone(); + } // calc loadings + + + let p = t.transpose().mmul(X).div(t.transpose().mmul(t).get(0, 0)); + let wOrtho = p.clone().sub(w.transpose().mmul(p.transpose()).div(w.transpose().mmul(w).get(0, 0)).mmul(w.transpose())); + wOrtho.div(norm(wOrtho)); // orthogonal scores + + let tOrtho = X.mmul(wOrtho.transpose()).div(wOrtho.mmul(wOrtho.transpose()).get(0, 0)); // orthogonal loadings + + let pOrtho = tOrtho.transpose().mmul(X).div(tOrtho.transpose().mmul(tOrtho).get(0, 0)); // filtered data + + let err = X.clone().sub(tOrtho.mmul(pOrtho)); + return { + filteredX: err, + weightsXOrtho: wOrtho, + loadingsXOrtho: pOrtho, + scoresXOrtho: tOrtho, + weightsXPred: w, + loadingsXpred: p, + scoresXpred: t, + loadingsY: c + }; + } + + /** + * Get total sum of square + * @param {Array} x an array + * @return {Number} - the sum of the squares + */ + + function tss(x) { + return Matrix.mul(x, x).sum(); + } + + /** + * Creates new OPLS (orthogonal partial latent structures) from features and labels. + * @param {Matrix} data - matrix containing data (X). + * @param {Array} labels - 1D Array containing metadata (Y). + * @param {Object} [options] + * @param {number} [options.nComp = 3] - number of latent structures computed. + * @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). + * @param {Array} [options.cvFolds = []] - allows to provide folds as 2D array for testing purpose. + * */ + + class OPLS { + constructor(data, labels, options = {}) { + if (data === true) { + const opls = options; + this.center = opls.center; + this.scale = opls.scale; + this.means = opls.means; + this.meansY = opls.meansY; + this.stdevs = opls.stdevs; + this.stdevs = opls.stdevsY; + this.model = opls.model; + this.tCV = opls.tCV; + this.tOrthCV = opls.tOrthCV; + this.yHatCV = opls.yHatCV; + this.mode = opls.mode; + return; + } + + let features = data.clone(); // set default values + // cvFolds allows to define folds for testing purpose + + const { + nComp = 3, + center = true, + scale = true, + cvFolds = [] + } = options; + let group; + + if (typeof labels[0] === 'number') { + // numeric labels: OPLS regression is used + this.mode = 'regression'; + group = Matrix.from1DArray(labels.length, 1, labels); + } else if (typeof labels[0] === 'string') { + // non-numeric labels: OPLS-DA is used + this.mode = 'discriminantAnalysis'; + group = labels; + throw new Error('discriminant analysis is not yet supported'); + } // check types of features and labels + + + if (features.constructor.name !== 'Matrix') { + throw new TypeError('features must be of class Matrix'); + } // getting center and scale the features (all) + + + this.center = center; + + if (this.center) { + this.means = features.mean('column'); + this.meansY = group.mean('column'); + } else { + this.stdevs = null; + } + + this.scale = scale; + + if (this.scale) { + this.stdevs = features.standardDeviation('column'); + this.stdevsY = group.standardDeviation('column'); + } else { + this.means = null; + } // check and remove for features with sd = 0 TODO here + // check opls.R line 70 + + + let folds; + + if (cvFolds.length > 0) { + folds = cvFolds; + } else { + folds = getFolds(labels, 5); + } + + let Q2 = []; + this.model = []; + this.tCV = []; + this.tOrthCV = []; + this.yHatCV = []; + let oplsCV = []; + let modelNC = []; // this code could be made more efficient by reverting the order of the loops + // this is a legacy loop to be consistent with R code from MetaboMate package + // this allows for having statistic (R2) from CV to decide wether to continue + // with more latent structures + + let nc; + + for (nc = 0; nc < nComp; nc++) { + let yHatk = new Matrix(group.rows, 1); + let tPredk = new Matrix(group.rows, 1); + let tOrthk = new Matrix(group.rows, 1); + let oplsk = []; + let f = 0; + + for (let fold of folds) { + let trainTest = this._getTrainTest(features, group, fold); + + let testXk = trainTest.testFeatures; + let Xk = trainTest.trainFeatures; + let Yk = trainTest.trainLabels; // determine center and scale of training set + + let dataCenter = Xk.mean('column'); + let dataSD = Xk.standardDeviation('column'); // center and scale training set + + if (center) { + Xk.center('column'); + Yk.center('column'); + } + + if (scale) { + Xk.scale('column'); + Yk.scale('column'); + } // perform opls + + + if (nc === 0) { + oplsk[f] = OPLSNipals(Xk, Yk); + } else { + oplsk[f] = OPLSNipals(oplsCV[nc - 1][f].filteredX, Yk); + } // store model for next component + + + oplsCV[nc] = oplsk; + let plsCV = new nipals(oplsk[f].filteredX, { + Y: Yk + }); // scaling the test dataset with respect to the train + + testXk.center('column', { + center: dataCenter + }); + testXk.scale('column', { + scale: dataSD + }); + let Eh = testXk; // removing the orthogonal components from PLS + + let scores; + + for (let idx = 0; idx < nc + 1; idx++) { + scores = Eh.mmul(oplsCV[idx][f].weightsXOrtho.transpose()); // ok + + Eh.sub(scores.mmul(oplsCV[idx][f].loadingsXOrtho)); + } // prediction + + + let tPred = Eh.mmul(plsCV.w.transpose()); // this should be summed over ncomp (pls_prediction.R line 23) + + let yHat = tPred.mmul(plsCV.betas); // ok + // adding all prediction from all folds + + for (let i = 0; i < fold.testIndex.length; i++) { + yHatk.setRow(fold.testIndex[i], [yHat.get(i, 0)]); + tPredk.setRow(fold.testIndex[i], [tPred.get(i, 0)]); + tOrthk.setRow(fold.testIndex[i], [scores.get(i, 0)]); + } + + f++; + } // end of loop over folds + + + this.tCV.push(tPredk); + this.tOrthCV.push(tOrthk); + this.yHatCV.push(yHatk); // calculate Q2y for all the prediction (all folds) + // ROC for DA is not implemented (check opls.R line 183) TODO + + if (this.mode === 'regression') { + let tssy = tss(group.center('column').scale('column')); + let press = tss(group.clone().sub(yHatk)); + let Q2y = 1 - press / tssy; + Q2.push(Q2y); + } else if (this.mode === 'discriminantAnalysis') { + throw new Error('discriminant analysis is not yet supported'); + } // calculate the R2y for the complete data + + + if (nc === 0) { + modelNC = this._predictAll(features, group); + } else { + modelNC = this._predictAll(modelNC.xRes, group, options = { + scale: false, + center: false + }); + } // adding the predictive statistics from CV + + + modelNC.Q2y = Q2; // store the model for each component + + this.model.push(modelNC); // console.warn(`OPLS iteration over # of Components: ${nc + 1}`); + } // end of loop over nc + // store scores from CV + + + let tCV = this.tCV; + let tOrthCV = this.tOrthCV; + let m = this.model[nc - 1]; + let XOrth = m.XOrth; + let FeaturesCS = features.center('column').scale('column'); + let labelsCS = group.center('column').scale('column'); + let Xres = FeaturesCS.clone().sub(XOrth); + let plsCall = new nipals(Xres, { + Y: labelsCS + }); + let E = Xres.clone().sub(plsCall.t.mmul(plsCall.p)); + let R2x = this.model.map(x => x.R2x); + let R2y = this.model.map(x => x.R2y); + this.output = { + Q2y: Q2, + R2x, + R2y, + tPred: m.plsC.t, + pPred: m.plsC.p, + wPred: m.plsC.w, + betasPred: m.plsC.betas, + Qpc: m.plsC.q, + tCV, + tOrthCV, + tOrth: m.tOrth, + pOrth: m.pOrth, + wOrth: m.wOrth, + XOrth, + yHat: m.totalPred, + Yres: m.plsC.yResidual, + E + }; + } + /** + * get access to all the computed elements + * Mainly for debug and testing + * @return {Object} output object + */ + + + getLogs() { + return this.output; + } + + getScores() { + let scoresX = this.tCV.map(x => x.to1DArray()); + let scoresY = this.tOrthCV.map(x => x.to1DArray()); + return { + scoresX, + scoresY + }; + } + /** + * Load an OPLS model from JSON + * @param {Object} model + * @return {OPLS} + */ + + + static load(model) { + if (typeof model.name !== 'string') { + throw new TypeError('model must have a name property'); + } + + if (model.name !== 'OPLS') { + throw new RangeError(`invalid model: ${model.name}`); + } + + return new OPLS(true, [], model); + } + /** + * Export the current model to a JSON object + * @return {Object} model + */ + + + toJSON() { + return { + name: 'OPLS', + center: this.center, + scale: this.scale, + means: this.means, + stdevs: this.stdevs, + model: this.model, + tCV: this.tCV, + tOrthCV: this.tOrthCV, + yHatCV: this.yHatCV + }; + } + /** + * Predict scores for new data + * @param {Matrix} features - a matrix containing new data + * @param {Object} [options] + * @param {Array} [options.trueLabel] - an array with true values to compute confusion matrix + * @param {Number} [options.nc] - the number of components to be used + * @return {Object} - predictions + */ + + + predict(newData, options = {}) { + let { + trueLabels = [], + nc = 1 + } = options; + let labels = []; + + if (trueLabels.length > 0) { + trueLabels = Matrix.from1DArray(trueLabels.length, 1, trueLabels); + labels = trueLabels.clone(); + } + + let features = newData.clone(); // scaling the test dataset with respect to the train + + if (this.center) { + features.center('column', { + center: this.means + }); + + if (labels.rows > 0 && this.mode === 'regression') { + labels.center('column', { + center: this.meansY + }); + } + } + + if (this.scale) { + features.scale('column', { + scale: this.stdevs + }); + + if (labels.rows > 0 && this.mode === 'regression') { + labels.scale('column', { + scale: this.stdevsY + }); + } + } + + let Eh = features.clone(); // removing the orthogonal components from PLS + + let tOrth; + let wOrth; + let pOrth; + let yHat; + let tPred; + + for (let idx = 0; idx < nc; idx++) { + wOrth = this.model[idx].wOrth.transpose(); + pOrth = this.model[idx].pOrth; + tOrth = Eh.mmul(wOrth); + Eh.sub(tOrth.mmul(pOrth)); // prediction + + tPred = Eh.mmul(this.model[idx].plsC.w.transpose()); // this should be summed over ncomp (pls_prediction.R line 23) + + yHat = tPred.mmul(this.model[idx].plsC.betas); + } + + if (labels.rows > 0) { + if (this.mode === 'regression') { + let tssy = tss(labels); + let press = tss(labels.clone().sub(yHat)); + let Q2y = 1 - press / tssy; + return { + tPred, + tOrth, + yHat, + Q2y + }; + } else if (this.mode === 'discriminantAnalysis') { + let confusionMatrix = []; + confusionMatrix = ConfusionMatrix.fromLabels(trueLabels.to1DArray(), yHat.to1DArray()); + return { + tPred, + tOrth, + yHat, + confusionMatrix + }; + } + } else { + return { + tPred, + tOrth, + yHat + }; + } + } + + _predictAll(features, labels, options = {}) { + // cannot use the global this.center here + // since it is used in the NC loop and + // centering and scaling should only be + // performed once + const { + center = true, + scale = true + } = options; + + if (center) { + features.center('column'); + labels.center('column'); + } + + if (scale) { + features.scale('column'); + labels.scale('column'); // reevaluate tssy and tssx after scaling + // must be global because re-used for next nc iteration + // tssx is only evaluate the first time + + this.tssy = tss(labels); + this.tssx = tss(features); + } + + let oplsC = OPLSNipals(features, labels); + let plsC = new nipals(oplsC.filteredX, { + Y: labels + }); + let tPred = oplsC.filteredX.mmul(plsC.w.transpose()); + let yHat = tPred.mmul(plsC.betas); + let rss = tss(labels.clone().sub(yHat)); + let R2y = 1 - rss / this.tssy; + let xEx = plsC.t.mmul(plsC.p); + let rssx = tss(xEx); + let R2x = rssx / this.tssx; + return { + R2y, + R2x, + xRes: oplsC.filteredX, + tOrth: oplsC.scoresXOrtho, + pOrth: oplsC.loadingsXOrtho, + wOrth: oplsC.weightsXOrtho, + tPred: tPred, + totalPred: yHat, + XOrth: oplsC.scoresXOrtho.mmul(oplsC.loadingsXOrtho), + oplsC, + plsC + }; + } + /** + * + * @param {*} X - dataset matrix object + * @param {*} group - labels matrix object + * @param {*} index - train and test index (output from getFold()) + */ + + + _getTrainTest(X, group, index) { + let testFeatures = new Matrix(index.testIndex.length, X.columns); + let testLabels = new Matrix(index.testIndex.length, 1); + index.testIndex.forEach((el, idx) => { + testFeatures.setRow(idx, X.getRow(el)); + testLabels.setRow(idx, group.getRow(el)); + }); + let trainFeatures = new Matrix(index.trainIndex.length, X.columns); + let trainLabels = new Matrix(index.trainIndex.length, 1); + index.trainIndex.forEach((el, idx) => { + trainFeatures.setRow(idx, X.getRow(el)); + trainLabels.setRow(idx, group.getRow(el)); + }); + return { + trainFeatures, + testFeatures, + trainLabels, + testLabels + }; + } + + } + + var require$$0 = /*@__PURE__*/getAugmentedNamespace(MatrixLib); + + function logistic(val) { + return 1 / (1 + Math.exp(-val)); + } + + function expELU(val, param) { + 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; + } + + function softExponentialPrime(val, param) { + if (param < 0) { + return 1 / (1 - param * (param + val)); + } else { + return Math.exp(param * val); + } + } + + 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 + } + }; + + 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.set(i, j, actFunction(this.get(i, j))); + }; + + this.derivate = function (i, j) { + this.set(i, j, derFunction(this.get(i, j))); + }; + + if (options.model) { + // load model + this.W = require$$0.Matrix.checkMatrix(options.W); + this.b = require$$0.Matrix.checkMatrix(options.b); + } else { + // default constructor + this.W = require$$0.Matrix.rand(this.inputSize, this.outputSize); + this.b = require$$0.Matrix.zeros(1, this.outputSize); + this.W.apply(function (i, j) { + this.set(i, j, this.get(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. + */ + + + 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.transpose().mmul(delta); + this.db = require$$0.Matrix.rowVector(delta.sum('column')); + var aCopy = a.clone(); + return delta.mmul(this.W.transpose()).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)); + } + /** + * @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); + } + + } + + class OutputLayer extends Layer { + constructor(options) { + super(options); + + this.activationFunction = function (i, j) { + this.set(i, j, Math.exp(this.get(i, j))); + }; + } + + static load(model) { + if (model.model !== 'Layer') { + throw new RangeError('the current model is not a Layer model'); + } + + return new OutputLayer(model); + } + + } + + class FeedForwardNeuralNetworks { + /** + * Create a new Feedforward 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; + 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. + */ + + + 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 + */ + + + train(features, labels) { + features = require$$0.Matrix.checkMatrix(features); + this.dicts = dictOutputs(labels); + var inputSize = features.columns; + var outputSize = Object.keys(this.dicts.inputs).length; + + if (!this.model) { + this.buildNetwork(inputSize, outputSize); + } + + 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. + */ + + + propagate(X) { + var input = X; + + for (var i = 0; i < this.model.length; ++i) { + input = this.model[i].forward(input); + } // get probabilities + + + return input.divColumnVector(input.sum('row')); + } + /** + * @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.rows; ++i) { + probabilities.set(i, this.dicts.inputs[labels[i]], probabilities.get(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); + } + + 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} + */ + + + predict(features) { + features = require$$0.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 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) + }; + + for (var i = 0; i < this.model.length; ++i) { + model.layers[i] = this.model[i].toJSON(); + } + + return model; + } + /** + * 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 new FeedForwardNeuralNetworks(model); + } + + } + /** + * @private + * Method that given an array of labels(predictions), returns two dictionaries, one to transform from labels to + * numbers and other in the reverse way + * @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++; + } + } + + return { + inputs: inputs, + outputs: outputs + }; + } + + var FeedForwardNeuralNetwork = FeedForwardNeuralNetworks; + + function NodeSquare(x, y, weights, som) { + 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]); + } + }; + + NodeSquare.prototype.getDistance = function getDistance(otherNode) { + 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)); + }; + + 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 (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)]; + }; + + var nodeSquare = NodeSquare; + + 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; + } + + 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)); + }; + + NodeHexagonal.prototype.getPosition = function getPosition() { + throw new Error('Unimplemented : cannot get position of the points for hexagonal grid'); + }; + var nodeHexagonal = NodeHexagonal; - static load(model) { - if (model.model !== 'Layer') { - throw new RangeError('the current model is not a Layer model'); - } + var defaultOptions$6 = { + fields: 3, + randomizer: Math.random, + distance: squareEuclidean, + iterations: 10, + learningRate: 0.1, + gridType: 'rect', + torus: true, + method: 'random' + }; - return new Layer(model); - } + function SOM(x, y, options, reload) { + this.x = x; + this.y = y; + options = options || {}; + this.options = {}; - } + for (var i in defaultOptions$6) { + if (options.hasOwnProperty(i)) { + this.options[i] = options[i]; + } else { + this.options[i] = defaultOptions$6[i]; + } + } - class OutputLayer extends Layer { - constructor(options) { - super(options); + 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'); + } - this.activationFunction = function (i, j) { - this.set(i, j, Math.exp(this.get(i, j))); + 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) }; } - static load(model) { - if (model.model !== 'Layer') { - throw new RangeError('the current model is not a Layer model'); - } + this.torus = this.options.torus; + this.distanceMethod = this.torus ? 'getDistanceTorus' : 'getDistance'; + this.distance = this.options.distance; + this.maxDistance = getMaxDistance(this.distance, this.numWeights); - return new OutputLayer(model); + if (reload === true) { + // For model loading + this.done = true; + return; } - } + if (!(x > 0 && y > 0)) { + throw new Error('x and y must be positive'); + } - class FeedForwardNeuralNetworks { - /** - * Create a new Feedforward 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 || {}; + 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; - 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); + this._initNodes(); - for (var i = 0; i < this.model.length - 1; ++i) { - this.model[i] = Layer.load(options.layers[i]); - } + this.done = false; + } - 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; - this.activation = options.activation || 'tanh'; - this.activationParam = options.activationParam || 1; + SOM.load = function loadModel(model, distance) { + if (model.name === 'SOM') { + var x = model.data.length, + y = model.data[0].length; - if (!(this.activation in Object.keys(ACTIVATION_FUNCTIONS))) { - this.activation = 'tanh'; - } + if (distance) { + model.options.distance = distance; + } else if (model.options.distance) { + model.options.distance = eval('(' + model.options.distance + ')'); } - } - /** - * @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 - }); // hidden layers + var som = new SOM(x, y, model.options, true); + som.nodes = new Array(x); - 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 + 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); + } + } - 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 - }); + return som; + } else { + throw new Error('expecting a SOM model'); } - /** - * Train the neural net with the given features and labels. - * @param {Matrix|Array} features - * @param {Matrix|Array} labels - */ + }; + SOM.prototype.export = function exportModel(includeDistance) { + if (!this.done) { + throw new Error('model is not ready yet'); + } - train(features, labels) { - features = Matrix.Matrix.checkMatrix(features); - this.dicts = dictOutputs(labels); - var inputSize = features.columns; - var outputSize = Object.keys(this.dicts.inputs).length; + var model = { + name: 'SOM' + }; + model.options = { + fields: this.options.fields, + gridType: this.options.gridType, + torus: this.options.torus + }; + model.data = new Array(this.x); - if (!this.model) { - this.buildNetwork(inputSize, outputSize); - } + for (var i = 0; i < this.x; i++) { + model.data[i] = new Array(this.y); - for (var i = 0; i < this.iterations; ++i) { - var probabilities = this.propagate(features); - this.backpropagation(features, labels, probabilities); + for (var j = 0; j < this.y; j++) { + model.data[i][j] = this.nodes[i][j].weights; } } - /** - * @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) { - input = this.model[i].forward(input); - } // get probabilities - - - return input.divColumnVector(input.sum('row')); + if (includeDistance) { + model.options.distance = this.distance.toString(); } - /** - * @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. - */ + return model; + }; - backpropagation(features, labels, probabilities) { - for (var i = 0; i < probabilities.rows; ++i) { - probabilities.set(i, this.dicts.inputs[labels[i]], probabilities.get(i, this.dicts.inputs[labels[i]]) - 1); - } // remember, the last delta doesn't matter + 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); - var delta = probabilities; + for (j = 0; j < this.y; j++) { + var weights = new Array(this.numWeights); - 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); - } + for (k = 0; k < this.numWeights; k++) { + weights[k] = this.randomizer(); + } - for (i = 0; i < this.model.length; ++i) { - this.model[i].update(); + this.nodes[i][j] = new this.nodeType(i, j, weights, this); } } - /** - * Predict the output given the feature set. - * @param {Array|Matrix} features - * @return {Array} - */ - - - predict(features) { - features = Matrix.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]]; - } + this.times.initNodes = Date.now() - now; + }; - return outputs; + SOM.prototype.setTraining = function setTraining(trainingSet) { + if (this.trainingSet) { + throw new Error('training set has already been set'); } - /** - * Export the current model to JSON. - * @return {object} model - */ + var now = Date.now(); + var convertedSet = trainingSet; + var i, + l = trainingSet.length; - 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) - }; + if (this.extractor) { + convertedSet = new Array(l); - for (var i = 0; i < this.model.length; ++i) { - model.layers[i] = this.model[i].toJSON(); + for (i = 0; i < l; i++) { + convertedSet[i] = this.extractor(trainingSet[i]); } - - return model; } - /** - * 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'); - } + this.numIterations = this.iterations * l; - return new FeedForwardNeuralNetworks(model); + if (this.algorithmMethod === 'random') { + this.timeConstant = this.numIterations / Math.log(this.mapRadius); + } else { + this.timeConstant = l / Math.log(this.mapRadius); } - } - /** - * @private - * Method that given an array of labels(predictions), returns two dictionaries, one to transform from labels to - * numbers and other in the reverse way - * @param {Array} array - * @return {object} - */ + this.trainingSet = convertedSet; + this.times.setTraining = Date.now() - now; + }; + SOM.prototype.trainOne = function trainOne() { + if (this.done) { + return false; + } else if (this.numIterations-- > 0) { + var neighbourhoodRadius, trainingValue, trainingSetFactor; - function dictOutputs(array) { - var inputs = {}; - var outputs = {}; - var index = 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); - for (var i = 0; i < array.length; i += 1) { - if (inputs[array[i]] === undefined) { - inputs[array[i]] = index; - outputs[index] = array[i]; - index++; - } - } + this._adjust(trainingValue, neighbourhoodRadius); - return { - inputs: inputs, - outputs: outputs - }; - } + 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]; - var FeedForwardNeuralNetwork = FeedForwardNeuralNetworks; + this._adjust(trainingValue, neighbourhoodRadius); - function NodeSquare(x, y, weights, som) { - this.x = x; - this.y = y; - this.weights = weights; - this.som = som; - this.neighbors = {}; - } + if ((this.iterationCount + 1) % this.trainingSet.length === 0) { + this.learningRate = this.startLearningRate * Math.exp(trainingSetFactor / Math.floor(this.numIterations / this.trainingSet.length)); + } + } - 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]); + this.iterationCount++; + return true; + } else { + this.done = true; + return false; } }; - NodeSquare.prototype.getDistance = function getDistance(otherNode) { - return Math.max(Math.abs(this.x - otherNode.x), Math.abs(this.y - otherNode.y)); - }; + SOM.prototype._adjust = function adjust(trainingValue, neighbourhoodRadius) { + var now = Date.now(), + x, + y, + dist, + influence; - 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 bmu = this._findBestMatchingUnit(trainingValue); - NodeSquare.prototype.getNeighbors = function getNeighbors(xy) { - if (!this.neighbors[xy]) { - this.neighbors[xy] = new Array(2); // left or bottom neighbor + 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; - var v; + for (x = xMin; x <= xMax; x++) { + var theX = x; - if (this[xy] > 0) { - v = this[xy] - 1; - } else if (this.som.torus) { - v = this.som.gridDim[xy] - 1; + if (x < 0) { + theX += this.x; + } else if (x >= this.x) { + theX -= this.x; } - if (typeof v !== 'undefined') { - var x, y; + for (y = yMin; y <= yMax; y++) { + var theY = y; - if (xy === 'x') { - x = v; - y = this.y; - } else { - x = this.x; - y = v; + if (y < 0) { + theY += this.y; + } else if (y >= this.y) { + theY -= this.y; } - this.neighbors[xy][0] = this.som.nodes[x][y]; - } // top or right neighbor + 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); + } + } + } - var w; + this.times.adjust += Date.now() - now2; + }; - if (this[xy] < this.som.gridDim[xy] - 1) { - w = this[xy] + 1; - } else if (this.som.torus) { - w = 0; - } + SOM.prototype.train = function train(trainingSet) { + if (!this.done) { + this.setTraining(trainingSet); - if (typeof w !== 'undefined') { - if (xy === 'x') { - x = w; - y = this.y; - } else { - x = this.x; - y = w; - } + while (this.trainOne()) {} + } + }; - this.neighbors[xy][1] = this.som.nodes[x][y]; + 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 this.neighbors[xy]; + return result; }; - 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); + SOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) { + var bmu, + lowest = Infinity, + dist; - if (dist1 < dist2) { - bestNeighbor = neighbors[0]; - direction = -1; - } else { - bestNeighbor = neighbors[1]; - direction = 1; + 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]; } - } 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; + return bmu; }; - NodeSquare.prototype.getPosition = function getPosition(element) { - return [this.getPos('x', element), this.getPos('y', element)]; - }; + SOM.prototype.predict = function predict(data, computePosition) { + if (typeof data === 'boolean') { + computePosition = data; + data = null; + } - var nodeSquare = NodeSquare; + if (!data) { + data = this.trainingSet; + } - 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; - } + 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); + } + }; - NodeHexagonal.prototype = new nodeSquare(); - NodeHexagonal.prototype.constructor = NodeHexagonal; + SOM.prototype._predict = function _predict(element, computePosition) { + if (!Array.isArray(element)) { + element = this.extractor(element); + } - 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)); - }; + var bmu = this._findBestMatchingUnit(element); - 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)); - }; + var result = [bmu.x, bmu.y]; - NodeHexagonal.prototype.getPosition = function getPosition() { - throw new Error('Unimplemented : cannot get position of the points for hexagonal grid'); - }; + if (computePosition) { + result[2] = bmu.getPosition(element); + } - var nodeHexagonal = NodeHexagonal; + return result; + }; // As seen in http://www.scholarpedia.org/article/Kohonen_network - var defaultOptions$7 = { - fields: 3, - randomizer: Math.random, - distance: squareEuclidean, - iterations: 10, - learningRate: 0.1, - gridType: 'rect', - torus: true, - method: 'random' - }; - function SOM(x, y, options, reload) { - this.x = x; - this.y = y; - options = options || {}; - this.options = {}; + SOM.prototype.getQuantizationError = function getQuantizationError() { + var fit = this.getFit(), + l = fit.length, + sum = 0; - for (var i in defaultOptions$7) { - if (options.hasOwnProperty(i)) { - this.options[i] = options[i]; - } else { - this.options[i] = defaultOptions$7[i]; - } + for (var i = 0; i < l; i++) { + sum += fit[i]; } - 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'); - } + return sum / l; + }; - 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) - }; + SOM.prototype.getFit = function getFit(dataset) { + if (!dataset) { + dataset = this.trainingSet; } - this.torus = this.options.torus; - this.distanceMethod = this.torus ? 'getDistanceTorus' : 'getDistance'; - this.distance = this.options.distance; - this.maxDistance = getMaxDistance(this.distance, this.numWeights); + var l = dataset.length, + bmu, + result = new Array(l); - if (reload === true) { - // For model loading - this.done = true; - return; + for (var i = 0; i < l; i++) { + bmu = this._findBestMatchingUnit(dataset[i]); + result[i] = Math.sqrt(this.distance(dataset[i], bmu.weights)); } - if (!(x > 0 && y > 0)) { - throw new Error('x and y must be positive'); + 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); } - 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; + return { + extractor: function extractor(value) { + var result = new Array(l); - this._initNodes(); + for (var i = 0; i < l; i++) { + result[i] = normalizers[i](value[fields[i].name]); + } - this.done = false; - } + return result; + }, + creator: function creator(value) { + var result = {}; - SOM.load = function loadModel(model, distance) { - if (model.name === 'SOM') { - var x = model.data.length, - y = model.data[0].length; + for (var i = 0; i < l; i++) { + result[fields[i].name] = denormalizers[i](value[i]); + } - if (distance) { - model.options.distance = distance; - } else if (model.options.distance) { - model.options.distance = eval('(' + model.options.distance + ')'); + return result; } + }; + } - var som = new SOM(x, y, model.options, true); - som.nodes = new Array(x); + function getNormalizer(minMax) { + return function normalizer(value) { + return (value - minMax[0]) / (minMax[1] - minMax[0]); + }; + } - for (var i = 0; i < x; i++) { - som.nodes[i] = new Array(y); + function getDenormalizer(minMax) { + return function denormalizer(value) { + return minMax[0] + value * (minMax[1] - minMax[0]); + }; + } - for (var j = 0; j < y; j++) { - som.nodes[i][j] = new som.nodeType(i, j, model.data[i][j], som); - } - } + function squareEuclidean(a, b) { + var d = 0; - return som; - } else { - throw new Error('expecting a SOM model'); + for (var i = 0, ii = a.length; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]); } - }; - SOM.prototype.export = function exportModel(includeDistance) { - if (!this.done) { - throw new Error('model is not ready yet'); + 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; } - var model = { - name: 'SOM' - }; - model.options = { - fields: this.options.fields, - gridType: this.options.gridType, - torus: this.options.torus - }; - model.data = new Array(this.x); + return distance(zero, one); + } - for (var i = 0; i < this.x; i++) { - model.data[i] = new Array(this.y); + var src = SOM; - for (var j = 0; j < this.y; j++) { - model.data[i][j] = this.nodes[i][j].weights; + 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(); } } + } - if (includeDistance) { - model.options.distance = this.distance.toString(); + function checkArraySize(x, y) { + if (!Array.isArray(x) || !Array.isArray(y)) { + throw new TypeError('x and y must be arrays'); } - return model; - }; - - SOM.prototype._initNodes = function initNodes() { - var now = Date.now(), - i, - j, - k; - this.nodes = new Array(this.x); + if (x.length !== y.length) { + throw new RangeError('x and y arrays must have the same length'); + } + } - for (i = 0; i < this.x; i++) { - this.nodes[i] = new Array(this.y); + class BaseRegression { + constructor() { + if (new.target === BaseRegression) { + throw new Error('BaseRegression must be subclassed'); + } + } - for (j = 0; j < this.y; j++) { - var weights = new Array(this.numWeights); + predict(x) { + if (typeof x === 'number') { + return this._predict(x); + } else if (Array.isArray(x)) { + const y = []; - for (k = 0; k < this.numWeights; k++) { - weights[k] = this.randomizer(); + for (let i = 0; i < x.length; i++) { + y.push(this._predict(x[i])); } - this.nodes[i][j] = new this.nodeType(i, j, weights, this); + return y; + } else { + throw new TypeError('x must be a number or array'); } } - this.times.initNodes = Date.now() - now; - }; - - SOM.prototype.setTraining = function setTraining(trainingSet) { - if (this.trainingSet) { - throw new Error('training set has already been set'); + _predict() { + throw new Error('_predict must be implemented'); } - 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]); - } + train() {// Do nothing for this package } - this.numIterations = this.iterations * l; + toString() { + return ''; + } - if (this.algorithmMethod === 'random') { - this.timeConstant = this.numIterations / Math.log(this.mapRadius); - } else { - this.timeConstant = l / Math.log(this.mapRadius); + toLaTeX() { + return ''; } + /** + * Return the correlation coefficient of determination (r) and chi-square. + * @param {Array} x + * @param {Array} y + * @return {object} + */ - this.trainingSet = convertedSet; - this.times.setTraining = Date.now() - now; - }; - SOM.prototype.trainOne = function trainOne() { - if (this.done) { - return false; - } else if (this.numIterations-- > 0) { - var neighbourhoodRadius, trainingValue, trainingSetFactor; + 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'); + } - 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); + const n = x.length; + const y2 = new Array(n); - this._adjust(trainingValue, neighbourhoodRadius); + for (let i = 0; i < n; i++) { + y2[i] = this._predict(x[i]); + } - 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]; + let xSum = 0; + let ySum = 0; + let chi2 = 0; + let rmsd = 0; + let xSquared = 0; + let ySquared = 0; + let xY = 0; - this._adjust(trainingValue, neighbourhoodRadius); + 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]; - if ((this.iterationCount + 1) % this.trainingSet.length === 0) { - this.learningRate = this.startLearningRate * Math.exp(trainingSetFactor / Math.floor(this.numIterations / this.trainingSet.length)); + if (y[i] !== 0) { + chi2 += (y[i] - y2[i]) * (y[i] - y2[i]) / y[i]; } + + rmsd += (y[i] - y2[i]) * (y[i] - y2[i]); } - this.iterationCount++; - return true; - } else { - this.done = true; - return false; + 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: Math.sqrt(rmsd / n) + }; } - }; - - 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; + class PolynomialRegression extends BaseRegression { + constructor(x, y, degree) { + super(); - if (x < 0) { - theX += this.x; - } else if (x >= this.x) { - theX -= this.x; + if (x === true) { + this.degree = y.degree; + this.powers = y.powers; + this.coefficients = y.coefficients; + } else { + checkArraySize(x, y); + regress(this, x, y, degree); } + } - for (y = yMin; y <= yMax; y++) { - var theY = y; - - if (y < 0) { - theY += this.y; - } else if (y >= this.y) { - theY -= this.y; - } - - dist = bmu[this.distanceMethod](this.nodes[theX][theY]); + _predict(x) { + let y = 0; - if (dist < neighbourhoodRadius) { - influence = Math.exp(-dist / (2 * neighbourhoodRadius)); - this.nodes[theX][theY].adjustWeights(trainingValue, this.learningRate, influence); - } + for (let k = 0; k < this.powers.length; k++) { + y += this.coefficients[k] * Math.pow(x, this.powers[k]); } - } - this.times.adjust += Date.now() - now2; - }; + return y; + } - SOM.prototype.train = function train(trainingSet) { - if (!this.done) { - this.setTraining(trainingSet); + toJSON() { + return { + name: 'polynomialRegression', + degree: this.degree, + powers: this.powers, + coefficients: this.coefficients + }; + } - while (this.trainOne()) {} + toString(precision) { + return this._toFormula(precision, false); } - }; - SOM.prototype.getConvertedNodes = function getConvertedNodes() { - var result = new Array(this.x); + toLaTeX(precision) { + return this._toFormula(precision, true); + } - for (var i = 0; i < this.x; i++) { - result[i] = new Array(this.y); + _toFormula(precision, isLaTeX) { + let sup = '^'; + let closeSup = ''; + let times = ' * '; - 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; + if (isLaTeX) { + sup = '^{'; + closeSup = '}'; + times = ''; } - } - return result; - }; + let fn = ''; + let str = ''; - SOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) { - var bmu, - lowest = Infinity, - dist; + for (let k = 0; k < this.coefficients.length; k++) { + str = ''; - 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 (this.coefficients[k] !== 0) { + if (this.powers[k] === 0) { + str = maybeToPrecision(this.coefficients[k], precision); + } else { + 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}`; + } + } - if (dist < lowest) { - lowest = dist; - bmu = this.nodes[i][j]; + if (this.coefficients[k] > 0 && k !== this.coefficients.length - 1) { + str = ` + ${str}`; + } else if (k !== this.coefficients.length - 1) { + str = ` ${str}`; + } } + + fn = str + fn; } - } - return bmu; - }; + if (fn.charAt(0) === '+') { + fn = fn.slice(1); + } - SOM.prototype.predict = function predict(data, computePosition) { - if (typeof data === 'boolean') { - computePosition = data; - data = null; + return `f(x) = ${fn}`; } - if (!data) { - data = this.trainingSet; - } + static load(json) { + if (json.name !== 'polynomialRegression') { + throw new TypeError('not a polynomial regression model'); + } - 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); + return new PolynomialRegression(true, json); } - }; - SOM.prototype._predict = function _predict(element, computePosition) { - if (!Array.isArray(element)) { - element = this.extractor(element); - } + } - var bmu = this._findBestMatchingUnit(element); + function regress(pr, x, y, degree) { + const n = x.length; + let powers; - var result = [bmu.x, bmu.y]; + if (Array.isArray(degree)) { + powers = degree; + degree = powers.length; + } else { + degree++; + powers = new Array(degree); - if (computePosition) { - result[2] = bmu.getPosition(element); + for (let k = 0; k < degree; k++) { + powers[k] = k; + } } - 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; + const F = new Matrix(n, degree); + const Y = new Matrix([y]); - for (var i = 0; i < l; i++) { - sum += fit[i]; + for (let k = 0; k < degree; k++) { + for (let i = 0; i < n; i++) { + if (powers[k] === 0) { + F.set(i, k, 1); + } else { + F.set(i, k, Math.pow(x[i], powers[k])); + } + } } - return sum / l; - }; - - SOM.prototype.getFit = function getFit(dataset) { - if (!dataset) { - dataset = this.trainingSet; - } + const FT = new MatrixTransposeView(F); + const A = FT.mmul(F); + const B = FT.mmul(new MatrixTransposeView(Y)); + pr.degree = degree - 1; + pr.powers = powers; + pr.coefficients = solve(A, B).to1DArray(); + } - var l = dataset.length, - bmu, - result = new Array(l); + class SimpleLinearRegression extends BaseRegression { + constructor(x, y) { + super(); - for (var i = 0; i < l; i++) { - bmu = this._findBestMatchingUnit(dataset[i]); - result[i] = Math.sqrt(this.distance(dataset[i], bmu.weights)); + if (x === true) { + this.slope = y.slope; + this.intercept = y.intercept; + this.coefficients = [y.intercept, y.slope]; + } else { + checkArraySize(x, y); + regress$1(this, x, y); + } } - return result; - }; + toJSON() { + return { + name: 'simpleLinearRegression', + slope: this.slope, + intercept: this.intercept + }; + } - function getConverters(fields) { - var l = fields.length, - normalizers = new Array(l), - denormalizers = new Array(l); + _predict(x) { + return this.slope * x + this.intercept; + } - for (var i = 0; i < l; i++) { - normalizers[i] = getNormalizer(fields[i].range); - denormalizers[i] = getDenormalizer(fields[i].range); + computeX(y) { + return (y - this.intercept) / this.slope; } - return { - extractor: function extractor(value) { - var result = new Array(l); + toString(precision) { + let result = 'f(x) = '; - for (var i = 0; i < l; i++) { - result[i] = normalizers[i](value[fields[i].name]); + if (this.slope !== 0) { + const xFactor = maybeToPrecision(this.slope, precision); + result += `${xFactor === '1' ? '' : `${xFactor} * `}x`; + + if (this.intercept !== 0) { + const absIntercept = Math.abs(this.intercept); + const operator = absIntercept === this.intercept ? '+' : '-'; + result += ` ${operator} ${maybeToPrecision(absIntercept, precision)}`; } + } else { + result += maybeToPrecision(this.intercept, precision); + } - return result; - }, - creator: function creator(value) { - var result = {}; + return result; + } - for (var i = 0; i < l; i++) { - result[fields[i].name] = denormalizers[i](value[i]); - } + toLaTeX(precision) { + return this.toString(precision); + } - return result; + static load(json) { + if (json.name !== 'simpleLinearRegression') { + throw new TypeError('not a SLR model'); } - }; - } - function getNormalizer(minMax) { - return function normalizer(value) { - return (value - minMax[0]) / (minMax[1] - minMax[0]); - }; - } + return new SimpleLinearRegression(true, json); + } - function getDenormalizer(minMax) { - return function denormalizer(value) { - return minMax[0] + value * (minMax[1] - minMax[0]); - }; } - function squareEuclidean(a, b) { - var d = 0; + function regress$1(slr, x, y) { + const n = x.length; + let xSum = 0; + let ySum = 0; + let xSquared = 0; + let xY = 0; - for (var i = 0, ii = a.length; i < ii; i++) { - d += (a[i] - b[i]) * (a[i] - b[i]); + for (let i = 0; i < n; i++) { + xSum += x[i]; + ySum += y[i]; + xSquared += x[i] * x[i]; + xY += x[i] * y[i]; } - return d; - } - - function getRandomValue(arr, randomizer) { - return arr[Math.floor(randomizer() * arr.length)]; + 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]; } - function getMaxDistance(distance, numWeights) { - var zero = new Array(numWeights), - one = new Array(numWeights); + class ExponentialRegression extends BaseRegression { + constructor(x, y) { + super(); - for (var i = 0; i < numWeights; i++) { - zero[i] = 0; - one[i] = 1; + if (x === true) { + this.A = y.A; + this.B = y.B; + } else { + checkArraySize(x, y); + regress$2(this, x, y); + } } - return distance(zero, one); - } + _predict(input) { + return this.B * Math.exp(input * this.A); + } - var src$4 = SOM; + toJSON() { + return { + name: 'exponentialRegression', + A: this.A, + B: this.B + }; + } - function maybeToPrecision(value, digits) { - if (value < 0) { - value = 0 - value; + toString(precision) { + return `f(x) = ${maybeToPrecision(this.B, precision)} * e^(${maybeToPrecision(this.A, precision)} * x)`; + } - if (typeof digits === 'number') { - return "- ".concat(value.toPrecision(digits)); - } else { - return "- ".concat(value.toString()); - } - } else { - if (typeof digits === 'number') { - return value.toPrecision(digits); + toLaTeX(precision) { + if (this.A >= 0) { + return `f(x) = ${maybeToPrecision(this.B, precision)}e^{${maybeToPrecision(this.A, precision)}x}`; } else { - return value.toString(); + return `f(x) = \\frac{${maybeToPrecision(this.B, precision)}}{e^{${maybeToPrecision(-this.A, precision)}x}}`; } } - } - function checkArraySize(x, y) { - if (!Array.isArray(x) || !Array.isArray(y)) { - throw new TypeError('x and y must be arrays'); - } + static load(json) { + if (json.name !== 'exponentialRegression') { + throw new TypeError('not a exponential regression model'); + } - if (x.length !== y.length) { - throw new RangeError('x and y arrays must have the same length'); + return new ExponentialRegression(true, json); } + } - class BaseRegression { - constructor() { - if (new.target === BaseRegression) { - throw new Error('BaseRegression must be subclassed'); - } + function regress$2(er, x, y) { + const n = x.length; + const yl = new Array(n); + + for (let i = 0; i < n; i++) { + yl[i] = Math.log(y[i]); } - predict(x) { - if (typeof x === 'number') { - return this._predict(x); - } else if (Array.isArray(x)) { - const y = []; + const linear = new SimpleLinearRegression(x, yl); + er.A = linear.slope; + er.B = Math.exp(linear.intercept); + } - for (let i = 0; i < x.length; i++) { - y.push(this._predict(x[i])); - } + class PowerRegression extends BaseRegression { + constructor(x, y) { + super(); - return y; + if (x === true) { + // reloading model + this.A = y.A; + this.B = y.B; } else { - throw new TypeError('x must be a number or array'); + checkArraySize(x, y); + regress$3(this, x, y); } } - _predict() { - throw new Error('_predict must be implemented'); - } - - train() {// Do nothing for this package + _predict(newInputs) { + return this.A * Math.pow(newInputs, this.B); } - toString() { - return ''; + toJSON() { + return { + name: 'powerRegression', + A: this.A, + B: this.B + }; } - toLaTeX() { - return ''; + toString(precision) { + return `f(x) = ${maybeToPrecision(this.A, precision)} * x^${maybeToPrecision(this.B, precision)}`; } - /** - * Return the correlation coefficient of determination (r) and chi-square. - * @param {Array} x - * @param {Array} y - * @return {object} - */ + toLaTeX(precision) { + let latex = ''; - 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'); + if (this.B >= 0) { + latex = `f(x) = ${maybeToPrecision(this.A, precision)}x^{${maybeToPrecision(this.B, precision)}}`; + } else { + latex = `f(x) = \\frac{${maybeToPrecision(this.A, precision)}}{x^{${maybeToPrecision(-this.B, precision)}}}`; } - const n = x.length; - const y2 = new Array(n); + latex = latex.replace(/e([+-]?[0-9]+)/g, 'e^{$1}'); + return latex; + } - for (let i = 0; i < n; i++) { - y2[i] = this._predict(x[i]); + static load(json) { + if (json.name !== 'powerRegression') { + throw new TypeError('not a power regression model'); } - let xSum = 0; - let ySum = 0; - let chi2 = 0; - let rmsd = 0; - let xSquared = 0; - let ySquared = 0; - let xY = 0; - - 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]; + return new PowerRegression(true, json); + } - if (y[i] !== 0) { - chi2 += (y[i] - y2[i]) * (y[i] - y2[i]) / y[i]; - } + } - rmsd += (y[i] - y2[i]) * (y[i] - y2[i]); - } + function regress$3(pr, x, y) { + const n = x.length; + const xl = new Array(n); + const yl = new Array(n); - 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: Math.sqrt(rmsd / n) - }; + for (let i = 0; i < n; i++) { + xl[i] = Math.log(x[i]); + yl[i] = Math.log(y[i]); } + const linear = new SimpleLinearRegression(xl, yl); + pr.A = Math.exp(linear.intercept); + pr.B = linear.slope; } - class PolynomialRegression extends BaseRegression { - constructor(x, y, degree) { - super(); + class MultivariateLinearRegression { + constructor(x, y, options = {}) { + const { + intercept = true, + statistics = true + } = options; + this.statistics = statistics; if (x === true) { - this.degree = y.degree; - this.powers = y.powers; - this.coefficients = y.coefficients; + this.weights = y.weights; + this.inputs = y.inputs; + this.outputs = y.outputs; + this.intercept = y.intercept; } else { - checkArraySize(x, y); - regress(this, x, y, degree); - } - } + x = new Matrix(x); + y = new Matrix(y); - _predict(x) { - let y = 0; + if (intercept) { + x.addColumn(new Array(x.rows).fill(1)); + } - for (let k = 0; k < this.powers.length; k++) { - y += this.coefficients[k] * Math.pow(x, this.powers[k]); - } + let xt = x.transpose(); + const xx = xt.mmul(x); + const xy = xt.mmul(y); + const invxx = new SingularValueDecomposition(xx).inverse(); + const beta = xy.transpose().mmul(invxx).transpose(); + this.weights = beta.to2DArray(); + this.inputs = x.columns; + this.outputs = y.columns; + if (intercept) this.inputs--; + this.intercept = intercept; - return y; + 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 = y.clone().addM(fittedValues.neg()); + const variance = residuals.to2DArray().map(ri => Math.pow(ri[0], 2)).reduce((a, b) => a + b) / (y.rows - x.columns); + this.stdError = Math.sqrt(variance); + this.stdErrorMatrix = pseudoInverse(xx).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]); + } + } } - toJSON() { - return { - name: 'polynomialRegression', - degree: this.degree, - powers: this.powers, - coefficients: this.coefficients - }; - } + 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); - toString(precision) { - return this._toFormula(precision, false); - } + for (let i = 0; i < x.length; i++) { + y[i] = this._predict(x[i]); + } - toLaTeX(precision) { - return this._toFormula(precision, true); - } + return y; + } + } else if (Matrix.isMatrix(x)) { + const y = new Matrix(x.rows, this.outputs); - _toFormula(precision, isLaTeX) { - let sup = '^'; - let closeSup = ''; - let times = ' * '; + for (let i = 0; i < x.rows; i++) { + y.setRow(i, this._predict(x.getRow(i))); + } - if (isLaTeX) { - sup = '^{'; - closeSup = '}'; - times = ''; + return y; } - let fn = ''; - let str = ''; - - for (let k = 0; k < this.coefficients.length; k++) { - str = ''; + throw new TypeError('x must be a matrix or array of numbers'); + } - if (this.coefficients[k] !== 0) { - if (this.powers[k] === 0) { - str = maybeToPrecision(this.coefficients[k], precision); - } else { - if (this.powers[k] === 1) { - str = "".concat(maybeToPrecision(this.coefficients[k], precision) + times, "x"); - } else { - str = "".concat(maybeToPrecision(this.coefficients[k], precision) + times, "x").concat(sup).concat(this.powers[k]).concat(closeSup); - } - } + _predict(x) { + const result = new Array(this.outputs); - if (this.coefficients[k] > 0 && k !== this.coefficients.length - 1) { - str = " + ".concat(str); - } else if (k !== this.coefficients.length - 1) { - str = " ".concat(str); - } + if (this.intercept) { + for (let i = 0; i < this.outputs; i++) { + result[i] = this.weights[this.inputs][i]; } + } else { + result.fill(0); + } - fn = str + fn; + for (let i = 0; i < this.inputs; i++) { + for (let j = 0; j < this.outputs; j++) { + result[j] += this.weights[i][j] * x[i]; + } } - if (fn.charAt(0) === '+') { - fn = fn.slice(1); + return result; + } + + score() { + throw new Error('score method is not implemented yet'); + } + + 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 + }; + } + + static load(model) { + if (model.name !== 'multivariateLinearRegression') { + throw new Error('not a MLR model'); } - return "f(x) = ".concat(fn); + return new MultivariateLinearRegression(true, model); } - static load(json) { - if (json.name !== 'polynomialRegression') { - throw new TypeError('not a polynomial regression model'); - } + } - return new PolynomialRegression(true, json); + var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(euclidean$1); + + const { + squaredEuclidean: squaredEuclidean$1 + } = require$$0$1; + const defaultOptions$7 = { + sigma: 1 + }; + + class GaussianKernel { + constructor(options) { + options = Object.assign({}, defaultOptions$7, options); + this.sigma = options.sigma; + this.divisor = 2 * options.sigma * options.sigma; + } + + compute(x, y) { + const distance = squaredEuclidean$1(x, y); + return Math.exp(-distance / this.divisor); } } - function regress(pr, x, y, degree) { - const n = x.length; - let powers; + var gaussianKernel = GaussianKernel; - if (Array.isArray(degree)) { - powers = degree; - degree = powers.length; - } else { - degree++; - powers = new Array(degree); + const defaultOptions$8 = { + degree: 1, + constant: 1, + scale: 1 + }; - for (let k = 0; k < degree; k++) { - powers[k] = k; - } + class PolynomialKernel { + constructor(options) { + options = Object.assign({}, defaultOptions$8, options); + this.degree = options.degree; + this.constant = options.constant; + this.scale = options.scale; } - const F = new Matrix(n, degree); - const Y = new Matrix([y]); + compute(x, y) { + var sum = 0; - for (let k = 0; k < degree; k++) { - for (let i = 0; i < n; i++) { - if (powers[k] === 0) { - F.set(i, k, 1); - } else { - F.set(i, k, Math.pow(x[i], powers[k])); - } + for (var i = 0; i < x.length; i++) { + sum += x[i] * y[i]; } + + return Math.pow(this.scale * sum + this.constant, this.degree); } - const FT = new MatrixTransposeView(F); - const A = FT.mmul(F); - const B = FT.mmul(new MatrixTransposeView(Y)); - pr.degree = degree - 1; - pr.powers = powers; - pr.coefficients = solve(A, B).to1DArray(); } - class SimpleLinearRegression extends BaseRegression { - constructor(x, y) { - super(); + var polynomialKernel = PolynomialKernel; - if (x === true) { - this.slope = y.slope; - this.intercept = y.intercept; - this.coefficients = [y.intercept, y.slope]; - } else { - checkArraySize(x, y); - regress$1(this, x, y); - } - } + const defaultOptions$9 = { + alpha: 0.01, + constant: -Math.E + }; - toJSON() { - return { - name: 'simpleLinearRegression', - slope: this.slope, - intercept: this.intercept - }; + class SigmoidKernel { + constructor(options) { + options = Object.assign({}, defaultOptions$9, options); + this.alpha = options.alpha; + this.constant = options.constant; } - _predict(x) { - return this.slope * x + this.intercept; - } + compute(x, y) { + var sum = 0; - computeX(y) { - return (y - this.intercept) / this.slope; + for (var i = 0; i < x.length; i++) { + sum += x[i] * y[i]; + } + + return Math.tanh(this.alpha * sum + this.constant); } - toString(precision) { - let result = 'f(x) = '; + } - if (this.slope !== 0) { - const xFactor = maybeToPrecision(this.slope, precision); - result += "".concat(xFactor === '1' ? '' : "".concat(xFactor, " * "), "x"); + var sigmoidKernel = SigmoidKernel; - if (this.intercept !== 0) { - const absIntercept = Math.abs(this.intercept); - const operator = absIntercept === this.intercept ? '+' : '-'; - result += " ".concat(operator, " ").concat(maybeToPrecision(absIntercept, precision)); - } - } else { - result += maybeToPrecision(this.intercept, precision); - } + const defaultOptions$a = { + sigma: 1, + degree: 1 + }; - return result; + class ANOVAKernel { + constructor(options) { + options = Object.assign({}, defaultOptions$a, options); + this.sigma = options.sigma; + this.degree = options.degree; } - toLaTeX(precision) { - return this.toString(precision); - } + compute(x, y) { + var sum = 0; + var len = Math.min(x.length, y.length); - static load(json) { - if (json.name !== 'simpleLinearRegression') { - throw new TypeError('not a SLR model'); + 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 new SimpleLinearRegression(true, json); + return sum; } } - function regress$1(slr, x, y) { - const n = x.length; - let xSum = 0; - let ySum = 0; - let xSquared = 0; - let xY = 0; + var anovaKernel = ANOVAKernel; - for (let i = 0; i < n; i++) { - xSum += x[i]; - ySum += y[i]; - xSquared += x[i] * x[i]; - xY += x[i] * y[i]; + const { + squaredEuclidean: squaredEuclidean$2 + } = require$$0$1; + const defaultOptions$b = { + sigma: 1 + }; + + class CauchyKernel { + constructor(options) { + options = Object.assign({}, defaultOptions$b, options); + this.sigma = options.sigma; + } + + compute(x, y) { + return 1 / (1 + squaredEuclidean$2(x, y) / (this.sigma * this.sigma)); } - 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]; } - class ExponentialRegression extends BaseRegression { - constructor(x, y) { - super(); + var cauchyKernel = CauchyKernel; - if (x === true) { - this.A = y.A; - this.B = y.B; - } else { - checkArraySize(x, y); - regress$2(this, x, y); - } - } + const { + euclidean: euclidean$2 + } = require$$0$1; + const defaultOptions$c = { + sigma: 1 + }; - _predict(input) { - return this.B * Math.exp(input * this.A); + class ExponentialKernel { + constructor(options) { + options = Object.assign({}, defaultOptions$c, options); + this.sigma = options.sigma; + this.divisor = 2 * options.sigma * options.sigma; } - toJSON() { - return { - name: 'exponentialRegression', - A: this.A, - B: this.B - }; + compute(x, y) { + const distance = euclidean$2(x, y); + return Math.exp(-distance / this.divisor); } - toString(precision) { - return "f(x) = ".concat(maybeToPrecision(this.B, precision), " * e^(").concat(maybeToPrecision(this.A, precision), " * x)"); - } + } - toLaTeX(precision) { - if (this.A >= 0) { - return "f(x) = ".concat(maybeToPrecision(this.B, precision), "e^{").concat(maybeToPrecision(this.A, precision), "x}"); - } else { - return "f(x) = \\frac{".concat(maybeToPrecision(this.B, precision), "}{e^{").concat(maybeToPrecision(-this.A, precision), "x}}"); + var exponentialKernel = ExponentialKernel; + + 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 sum; } - static load(json) { - if (json.name !== 'exponentialRegression') { - throw new TypeError('not a exponential regression model'); - } + } + + var histogramIntersectionKernel = HistogramIntersectionKernel; + + const { + euclidean: euclidean$3 + } = require$$0$1; + const defaultOptions$d = { + sigma: 1 + }; + + class LaplacianKernel { + constructor(options) { + options = Object.assign({}, defaultOptions$d, options); + this.sigma = options.sigma; + } - return new ExponentialRegression(true, json); + compute(x, y) { + const distance = euclidean$3(x, y); + return Math.exp(-distance / this.sigma); } } - function regress$2(er, x, y) { - const n = x.length; - const yl = new Array(n); + var laplacianKernel = LaplacianKernel; - for (let i = 0; i < n; i++) { - yl[i] = Math.log(y[i]); + const { + squaredEuclidean: squaredEuclidean$3 + } = require$$0$1; + const defaultOptions$e = { + constant: 1 + }; + + class MultiquadraticKernel { + constructor(options) { + options = Object.assign({}, defaultOptions$e, options); + this.constant = options.constant; + } + + compute(x, y) { + return Math.sqrt(squaredEuclidean$3(x, y) + this.constant * this.constant); } - const linear = new SimpleLinearRegression(x, yl); - er.A = linear.slope; - er.B = Math.exp(linear.intercept); } - class PowerRegression extends BaseRegression { - constructor(x, y) { - super(); + var multiquadraticKernel = MultiquadraticKernel; - if (x === true) { - // reloading model - this.A = y.A; - this.B = y.B; - } else { - checkArraySize(x, y); - regress$3(this, x, y); - } - } + const { + squaredEuclidean: squaredEuclidean$4 + } = require$$0$1; + const defaultOptions$f = { + constant: 1 + }; - _predict(newInputs) { - return this.A * Math.pow(newInputs, this.B); + class RationalQuadraticKernel { + constructor(options) { + options = Object.assign({}, defaultOptions$f, options); + this.constant = options.constant; } - toJSON() { - return { - name: 'powerRegression', - A: this.A, - B: this.B - }; + compute(x, y) { + const distance = squaredEuclidean$4(x, y); + return 1 - distance / (distance + this.constant); } - toString(precision) { - return "f(x) = ".concat(maybeToPrecision(this.A, precision), " * x^").concat(maybeToPrecision(this.B, precision)); - } + } - toLaTeX(precision) { - let latex = ''; + var rationalQuadraticKernel = RationalQuadraticKernel; - if (this.B >= 0) { - latex = "f(x) = ".concat(maybeToPrecision(this.A, precision), "x^{").concat(maybeToPrecision(this.B, precision), "}"); + const { + Matrix: Matrix$1, + MatrixTransposeView: MatrixTransposeView$1 + } = require$$0; + const kernelType = { + gaussian: gaussianKernel, + rbf: gaussianKernel, + polynomial: polynomialKernel, + poly: polynomialKernel, + anova: anovaKernel, + cauchy: cauchyKernel, + exponential: exponentialKernel, + histogram: histogramIntersectionKernel, + min: histogramIntersectionKernel, + laplacian: laplacianKernel, + multiquadratic: multiquadraticKernel, + rational: rationalQuadraticKernel, + 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 { - latex = "f(x) = \\frac{".concat(maybeToPrecision(this.A, precision), "}{x^{").concat(maybeToPrecision(-this.B, precision), "}}"); + throw new TypeError('first argument must be a valid kernel type or instance'); } - - latex = latex.replace(/e([+-]?[0-9]+)/g, 'e^{$1}'); - return latex; } - static load(json) { - if (json.name !== 'powerRegression') { - throw new TypeError('not a power regression model'); + compute(inputs, landmarks) { + inputs = Matrix$1.checkMatrix(inputs); + + if (landmarks === undefined) { + landmarks = inputs; + } else { + landmarks = Matrix$1.checkMatrix(landmarks); } - return new PowerRegression(true, json); - } + if (this.kernelType === 'linear') { + return inputs.mmul(new MatrixTransposeView$1(landmarks)); + } - } + const kernelMatrix = new Matrix$1(inputs.rows, landmarks.rows); - function regress$3(pr, x, y) { - const n = x.length; - const xl = new Array(n); - const yl = new Array(n); + if (inputs === landmarks) { + // fast path, matrix is symmetric + for (let i = 0; i < inputs.rows; i++) { + for (let j = i; j < inputs.rows; j++) { + const value = this.kernelFunction.compute(inputs.getRow(i), inputs.getRow(j)); + kernelMatrix.set(i, j, value); + kernelMatrix.set(j, i, value); + } + } + } else { + for (let i = 0; i < inputs.rows; i++) { + for (let j = 0; j < landmarks.rows; j++) { + kernelMatrix.set(i, j, this.kernelFunction.compute(inputs.getRow(i), landmarks.getRow(j))); + } + } + } - for (let i = 0; i < n; i++) { - xl[i] = Math.log(x[i]); - yl[i] = Math.log(y[i]); + return kernelMatrix; } - const linear = new SimpleLinearRegression(xl, yl); - pr.A = Math.exp(linear.intercept); - pr.B = linear.slope; } - class MultivariateLinearRegression { + var kernel = Kernel; + + class 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) { - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - const { - intercept = true, - statistics = true - } = options; - this.statistics = statistics; + super(); if (x === true) { - this.weights = y.weights; - this.inputs = y.inputs; - this.outputs = y.outputs; + // loads the model + this.slope = y.slope; this.intercept = y.intercept; + this.coefficients = y.coefficients; } else { - x = new Matrix(x); - y = new Matrix(y); + // creates the model + checkArraySize(x, y); + theilSen(this, x, y); + } + } - if (intercept) { - x.addColumn(new Array(x.rows).fill(1)); - } + toJSON() { + return { + name: 'TheilSenRegression', + slope: this.slope, + intercept: this.intercept + }; + } - let xt = x.transpose(); - const xx = xt.mmul(x); - const xy = xt.mmul(y); - const invxx = new SingularValueDecomposition(xx).inverse(); - const beta = xy.transpose().mmul(invxx).transpose(); - this.weights = beta.to2DArray(); - this.inputs = x.columns; - this.outputs = y.columns; - if (intercept) this.inputs--; - this.intercept = intercept; + _predict(input) { + return this.slope * input + this.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" - */ - const fittedValues = x.mmul(beta); - const residuals = y.clone().addM(fittedValues.neg()); - const variance = residuals.to2DArray().map(ri => Math.pow(ri[0], 2)).reduce((a, b) => a + b) / (y.rows - x.columns); - this.stdError = Math.sqrt(variance); - this.stdErrorMatrix = pseudoInverse(xx).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]); - } - } + computeX(input) { + return (input - this.intercept) / this.slope; } - 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); + toString(precision) { + var result = 'f(x) = '; - for (let i = 0; i < x.length; i++) { - y[i] = this._predict(x[i]); - } + if (this.slope) { + var xFactor = maybeToPrecision(this.slope, precision); + result += `${Math.abs(xFactor - 1) < 1e-5 ? '' : `${xFactor} * `}x`; - return y; + if (this.intercept) { + var absIntercept = Math.abs(this.intercept); + var operator = absIntercept === this.intercept ? '+' : '-'; + result += ` ${operator} ${maybeToPrecision(absIntercept, precision)}`; } - } else if (Matrix.isMatrix(x)) { - const y = new Matrix(x.rows, this.outputs); + } else { + result += maybeToPrecision(this.intercept, precision); + } - for (let i = 0; i < x.rows; i++) { - y.setRow(i, this._predict(x.getRow(i))); - } + return result; + } - return y; + toLaTeX(precision) { + return this.toString(precision); + } + + static load(json) { + if (json.name !== 'TheilSenRegression') { + throw new TypeError('not a Theil-Sen model'); } - throw new TypeError('x must be a matrix or array of numbers'); + return new TheilSenRegression(true, json); } - _predict(x) { - const result = new Array(this.outputs); + } - if (this.intercept) { - for (let i = 0; i < this.outputs; i++) { - result[i] = this.weights[this.inputs][i]; - } - } else { - result.fill(0); - } + function theilSen(regression, x, y) { + let len = x.length; + let slopes = new Array(len * len); + let count = 0; - for (let i = 0; i < this.inputs; i++) { - for (let j = 0; j < this.outputs; j++) { - result[j] += this.weights[i][j] * x[i]; + 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]); } } + } - return result; + slopes.length = count; + let medianSlope = median(slopes); + let cuts = new Array(len); + + for (let i = 0; i < len; ++i) { + cuts[i] = y[i] - medianSlope * x[i]; } - score() { - throw new Error('score method is not implemented yet'); + regression.slope = medianSlope; + regression.intercept = median(cuts); + regression.coefficients = [regression.intercept, regression.slope]; + } + + /** + * @class RobustPolynomialRegression + * @param {Array} x + * @param {Array} y + * @param {number} degree - polynomial degree + */ + + class 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); + } } 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 + name: 'robustPolynomialRegression', + degree: this.degree, + powers: this.powers, + coefficients: this.coefficients }; } - static load(model) { - if (model.name !== 'multivariateLinearRegression') { - throw new Error('not a MLR model'); - } + _predict(x) { + return predict(x, this.powers, this.coefficients); + } + /** + * Display the formula + * @param {number} precision - precision for the numbers + * @return {string} + */ - return new MultivariateLinearRegression(true, model); + + toString(precision) { + return this._toFormula(precision, false); + } + /** + * Display the formula in LaTeX format + * @param {number} precision - precision for the numbers + * @return {string} + */ + + + toLaTeX(precision) { + return this._toFormula(precision, true); } - } + _toFormula(precision, isLaTeX) { + let sup = '^'; + let closeSup = ''; + let times = ' * '; - const { - squaredEuclidean: squaredEuclidean$1 - } = euclidean$1; - const defaultOptions$8 = { - sigma: 1 - }; + if (isLaTeX) { + sup = '^{'; + closeSup = '}'; + times = ''; + } - class GaussianKernel { - constructor(options) { - options = Object.assign({}, defaultOptions$8, options); - this.sigma = options.sigma; - this.divisor = 2 * options.sigma * options.sigma; + let fn = ''; + let str = ''; + + for (let k = 0; k < this.coefficients.length; k++) { + str = ''; + + if (this.coefficients[k] !== 0) { + if (this.powers[k] === 0) { + str = maybeToPrecision(this.coefficients[k], precision); + } else { + 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}`; + } + } + + 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); + } + + return `f(x) = ${fn}`; } - compute(x, y) { - const distance = squaredEuclidean$1(x, y); - return Math.exp(-distance / this.divisor); + static load(json) { + if (json.name !== 'robustPolynomialRegression') { + throw new TypeError('not a RobustPolynomialRegression model'); + } + + return new RobustPolynomialRegression(true, json); } } - var gaussianKernel = GaussianKernel; + function robustPolynomial(regression, x, y, degree) { + let powers = Array(degree).fill(0).map((_, index) => index); + const tuples = getRandomTuples(x, y, degree); + var min; - const defaultOptions$9 = { - degree: 1, - constant: 1, - scale: 1 - }; + for (var i = 0; i < tuples.length; i++) { + var tuple = tuples[i]; + var coefficients = calcCoefficients(tuple, powers); + var residuals = x.slice(); - class PolynomialKernel { - constructor(options) { - options = Object.assign({}, defaultOptions$9, options); - this.degree = options.degree; - this.constant = options.constant; - this.scale = options.scale; - } + 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 + }; + } - compute(x, y) { - var sum = 0; + var median = residualsMedian(residuals); - for (var i = 0; i < x.length; i++) { - sum += x[i] * y[i]; + if (!min || median.residual < min.residual) { + min = median; } - - return Math.pow(this.scale * sum + this.constant, this.degree); } + regression.degree = degree; + regression.powers = powers; + regression.coefficients = min.coefficients; } + /** + * @ignore + * @param {Array} x + * @param {Array} y + * @param {number} degree + * @return {Array<{x:number,y:number}>} + */ - var polynomialKernel = PolynomialKernel; - const defaultOptions$a = { - alpha: 0.01, - constant: -Math.E - }; + function getRandomTuples(x, y, degree) { + var len = Math.floor(x.length / degree); + var tuples = new Array(len); - class SigmoidKernel { - constructor(options) { - options = Object.assign({}, defaultOptions$a, options); - this.alpha = options.alpha; - this.constant = options.constant; + 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; + } } - compute(x, y) { - var sum = 0; + return tuples; + } + /** + * @ignore + * @param {{x:number,y:number}} tuple + * @param {Array} powers + * @return {Array} + */ + - for (var i = 0; i < x.length; i++) { - sum += x[i] * y[i]; - } + function calcCoefficients(tuple, powers) { + var X = tuple.slice(); + var Y = tuple.slice(); - return Math.tanh(this.alpha * sum + this.constant); + 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]); + } } + return solve(X, Y).to1DArray(); } - var sigmoidKernel = SigmoidKernel; - - const defaultOptions$b = { - sigma: 1, - degree: 1 - }; + function predict(x, powers, coefficients) { + let y = 0; - class ANOVAKernel { - constructor(options) { - options = Object.assign({}, defaultOptions$b, options); - this.sigma = options.sigma; - this.degree = options.degree; + for (let k = 0; k < powers.length; k++) { + y += coefficients[k] * Math.pow(x, powers[k]); } - compute(x, y) { - var sum = 0; - var len = Math.min(x.length, y.length); + return y; + } - 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); - } + function residualsMedian(residuals) { + residuals.sort((a, b) => a.residual - b.residual); + var l = residuals.length; + var half = Math.floor(l / 2); + return l % 2 === 0 ? residuals[half - 1] : residuals[half]; + } - return sum; + const toString$3 = Object.prototype.toString; + function isAnyArray$3(object) { + return toString$3.call(object).endsWith('Array]'); + } + + /** + * 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 errorCalculation(data, parameters, parameterizedFunction) { + let error = 0; + const func = parameterizedFunction(parameters); + + for (let i = 0; i < data.x.length; i++) { + error += Math.abs(data.y[i] - func(data.x[i])); } + return error; } - var anovaKernel = ANOVAKernel; + /** + * 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} + */ - const { - squaredEuclidean: squaredEuclidean$2 - } = euclidean$1; - const defaultOptions$c = { - sigma: 1 - }; + function gradientFunction(data, evaluatedData, params, gradientDifference, paramFunction) { + const n = params.length; + const m = data.x.length; + let ans = new Array(n); - class CauchyKernel { - constructor(options) { - options = Object.assign({}, defaultOptions$c, options); - this.sigma = options.sigma; - } + for (let param = 0; param < n; param++) { + ans[param] = new Array(m); + let auxParams = params.slice(); + auxParams[param] += gradientDifference; + let funcParam = paramFunction(auxParams); - compute(x, y) { - return 1 / (1 + squaredEuclidean$2(x, y) / (this.sigma * this.sigma)); + for (let point = 0; point < m; point++) { + ans[param][point] = evaluatedData[point] - funcParam(data.x[point]); + } } + return new 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} + */ - var cauchyKernel = CauchyKernel; - - const { - euclidean: euclidean$2 - } = euclidean$1; - const defaultOptions$d = { - sigma: 1 - }; - class ExponentialKernel { - constructor(options) { - options = Object.assign({}, defaultOptions$d, options); - this.sigma = options.sigma; - this.divisor = 2 * options.sigma * options.sigma; - } + function matrixFunction(data, evaluatedData) { + const m = data.x.length; + let ans = new Array(m); - compute(x, y) { - const distance = euclidean$2(x, y); - return Math.exp(-distance / this.divisor); + for (let point = 0; point < m; point++) { + ans[point] = [data.y[point] - evaluatedData[point]]; } + return new Matrix(ans); } + /** + * 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} + */ - var exponentialKernel = ExponentialKernel; - - 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]); - } + function step$1(data, params, damping, gradientDifference, parameterizedFunction) { + let value = damping * gradientDifference * gradientDifference; + let identity = Matrix.eye(params.length, params.length, value); + const func = parameterizedFunction(params); + let evaluatedData = new Float64Array(data.x.length); - return sum; + for (let i = 0; i < data.x.length; i++) { + evaluatedData[i] = func(data.x[i]); } + let gradientFunc = gradientFunction(data, evaluatedData, params, gradientDifference, parameterizedFunction); + let matrixFunc = matrixFunction(data, evaluatedData); + let inverseMatrix = inverse(identity.add(gradientFunc.mmul(gradientFunc.transpose()))); + params = new Matrix([params]); + params = params.sub(inverseMatrix.mmul(gradientFunc).mmul(matrixFunc).mul(gradientDifference).transpose()); + return params.to1DArray(); } - var histogramIntersectionKernel = HistogramIntersectionKernel; + /** + * 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}} + */ - const { - euclidean: euclidean$3 - } = euclidean$1; - const defaultOptions$e = { - sigma: 1 - }; + function levenbergMarquardt(data, parameterizedFunction, options = {}) { + let { + maxIterations = 100, + gradientDifference = 10e-2, + damping = 0, + errorTolerance = 10e-3, + minValues, + maxValues, + initialValues + } = options; - class LaplacianKernel { - constructor(options) { - options = Object.assign({}, defaultOptions$e, options); - this.sigma = options.sigma; + 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 (!isAnyArray$3(data.x) || data.x.length < 2 || !isAnyArray$3(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'); } - compute(x, y) { - const distance = euclidean$3(x, y); - return Math.exp(-distance / this.sigma); + let 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); + + if (maxValues.length !== minValues.length) { + throw new Error('minValues and maxValues must be the same size'); } - } + if (!isAnyArray$3(parameters)) { + throw new Error('initialValues must be an array'); + } - var laplacianKernel = LaplacianKernel; + let error = errorCalculation(data, parameters, parameterizedFunction); + let converged = error <= errorTolerance; + let iteration; - const { - squaredEuclidean: squaredEuclidean$3 - } = euclidean$1; - const defaultOptions$f = { - constant: 1 - }; + for (iteration = 0; iteration < maxIterations && !converged; iteration++) { + parameters = step$1(data, parameters, damping, gradientDifference, parameterizedFunction); - class MultiquadraticKernel { - constructor(options) { - options = Object.assign({}, defaultOptions$f, options); - this.constant = options.constant; - } + for (let k = 0; k < parLen; k++) { + parameters[k] = Math.min(Math.max(minValues[k], parameters[k]), maxValues[k]); + } - compute(x, y) { - return Math.sqrt(squaredEuclidean$3(x, y) + this.constant * this.constant); + error = errorCalculation(data, parameters, parameterizedFunction); + if (isNaN(error)) break; + converged = error <= errorTolerance; } + return { + parameterValues: parameters, + parameterError: error, + iterations: iteration + }; } - var multiquadraticKernel = MultiquadraticKernel; + /** + * Returns a new array based on extraction of specific indices of an array + * @private + * @param {Array} vector + * @param {Array} indices + */ + function selection(vector, indices) { + let u = []; //new Float64Array(indices.length); - const { - squaredEuclidean: squaredEuclidean$4 - } = euclidean$1; - const defaultOptions$g = { - constant: 1 - }; + for (let i = 0; i < indices.length; i++) { + u[i] = vector[indices[i]]; + } + + return u; + } + + /** + * + * @private + * @param {Array of arrays} collection + */ + function sortCollectionSet(collection) { + let objectCollection = collection.map((value, index) => { + let key = BigInt(0); + value.forEach(item => key |= BigInt(1) << BigInt(item)); + return { + value, + index, + key + }; + }).sort((a, b) => { + if (a.key - b.key < 0) return -1; + return 1; + }); + let sorted = []; + let indices = []; + let key; - class RationalQuadraticKernel { - constructor(options) { - options = Object.assign({}, defaultOptions$g, options); - this.constant = options.constant; - } + for (let set of objectCollection) { + if (set.key !== key) { + key = set.key; + indices.push([]); + sorted.push(set.value); + } - compute(x, y) { - const distance = squaredEuclidean$4(x, y); - return 1 - distance / (distance + this.constant); + indices[indices.length - 1].push(set.index); } + let result = { + values: sorted, + indices: indices + }; + return result; } - var rationalQuadraticKernel = RationalQuadraticKernel; + /** + * (Combinatorial Subspace Least Squares) - subfunction for the FC-NNLS + * @private + * @param {Matrix} XtX + * @param {Matrix} XtY + * @param {Array} Pset + * @param {Numbers} l + * @param {Numbers} p + */ - const { - Matrix: Matrix$1, - MatrixTransposeView: MatrixTransposeView$1 - } = Matrix; - const kernelType = { - gaussian: gaussianKernel, - rbf: gaussianKernel, - polynomial: polynomialKernel, - poly: polynomialKernel, - anova: anovaKernel, - cauchy: cauchyKernel, - exponential: exponentialKernel, - histogram: histogramIntersectionKernel, - min: histogramIntersectionKernel, - laplacian: laplacianKernel, - multiquadratic: multiquadraticKernel, - rational: rationalQuadraticKernel, - sigmoid: sigmoidKernel, - mlp: sigmoidKernel - }; + function cssls(XtX, XtY, Pset, l, p) { + // Solves the set of equation XtX*K = XtY for the variables in Pset + // if XtX (or XtX(vars,vars)) is singular, performs the svd and find pseudoinverse, otherwise (even if ill-conditioned) finds inverse with LU decomposition and solves the set of equation + // it is consistent with matlab results for ill-conditioned matrices (at least consistent with test 'ill-conditionned square X rank 2, Y 3x1' in cssls.test) + let K = Matrix.zeros(l, p); - class Kernel { - constructor(type, options) { - this.kernelType = type; - if (type === 'linear') return; + if (Pset === null) { + let choXtX = new CholeskyDecomposition(XtX); - if (typeof type === 'string') { - type = type.toLowerCase(); - var KernelConstructor = kernelType[type]; + if (choXtX.isPositiveDefinite() === true) { + K = choXtX.solve(XtY); + } else { + let luXtX = new LuDecomposition(XtX); - if (KernelConstructor) { - this.kernelFunction = new KernelConstructor(options); + if (luXtX.isSingular() === false) { + K = luXtX.solve(Matrix.eye(l)).mmul(XtY); } else { - throw new Error("unsupported kernel type: ".concat(type)); + K = solve(XtX, XtY, { + useSVD: true + }); } - } 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'); - } - } - - compute(inputs, landmarks) { - inputs = Matrix$1.checkMatrix(inputs); - - if (landmarks === undefined) { - landmarks = inputs; - } else { - landmarks = Matrix$1.checkMatrix(landmarks); } + } else { + let sortedPset = sortCollectionSet(Pset).values; + let sortedEset = sortCollectionSet(Pset).indices; - if (this.kernelType === 'linear') { - return inputs.mmul(new MatrixTransposeView$1(landmarks)); - } + if (sortedPset.length === 1 && sortedPset[0].length === 0 && sortedEset[0].length === p) { + return K; + } else if (sortedPset.length === 1 && sortedPset[0].length === l && sortedEset[0].length === p) { + let choXtX = new CholeskyDecomposition(XtX); - const kernelMatrix = new Matrix$1(inputs.rows, landmarks.rows); + if (choXtX.isPositiveDefinite() === true) { + K = choXtX.solve(XtY); + } else { + let luXtX = new LuDecomposition(XtX); - if (inputs === landmarks) { - // fast path, matrix is symmetric - for (let i = 0; i < inputs.rows; i++) { - for (let j = i; j < inputs.rows; j++) { - const value = this.kernelFunction.compute(inputs.getRow(i), inputs.getRow(j)); - kernelMatrix.set(i, j, value); - kernelMatrix.set(j, i, value); + if (luXtX.isSingular() === false) { + K = luXtX.solve(Matrix.eye(l)).mmul(XtY); + } else { + K = solve(XtX, XtY, { + useSVD: true + }); } } } else { - for (let i = 0; i < inputs.rows; i++) { - for (let j = 0; j < landmarks.rows; j++) { - kernelMatrix.set(i, j, this.kernelFunction.compute(inputs.getRow(i), landmarks.getRow(j))); + for (let k = 0; k < sortedPset.length; k++) { + let cols2Solve = sortedEset[k]; + let vars = sortedPset[k]; + let L; + let choXtX = new CholeskyDecomposition(XtX.selection(vars, vars)); + + if (choXtX.isPositiveDefinite() === true) { + L = choXtX.solve(XtY.selection(vars, cols2Solve)); + } else { + let luXtX = new LuDecomposition(XtX.selection(vars, vars)); + + if (luXtX.isSingular() === false) { + L = luXtX.solve(Matrix.eye(vars.length)).mmul(XtY.selection(vars, cols2Solve)); + } else { + L = solve(XtX.selection(vars, vars), XtY.selection(vars, cols2Solve), { + useSVD: true + }); + } + } + + for (let i = 0; i < L.rows; i++) { + for (let j = 0; j < L.columns; j++) { + K.set(vars[i], cols2Solve[j], L.get(i, j)); + } } } } - - return kernelMatrix; } + return K; } - var kernel = Kernel; + function initialisation(X, Y) { + let n = X.rows; + let l = X.columns; + let p = Y.columns; + let iter = 0; + if (Y.rows !== n) throw new Error('ERROR: matrix size not compatible'); + let W = Matrix.zeros(l, p); // precomputes part of pseudoinverse - class 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(); + let XtX = X.transpose().mmul(X); + let XtY = X.transpose().mmul(Y); + let K = cssls(XtX, XtY, null, l, p); // K is lxp + + let Pset = []; + + for (let j = 0; j < p; j++) { + Pset[j] = []; + + for (let i = 0; i < l; i++) { + if (K.get(i, j) > 0) { + Pset[j].push(i); + } else { + K.set(i, j, 0); + } //This is our initial solution, it's the solution found by overwriting the unconstrained least square solution - if (x === true) { - // loads the model - this.slope = y.slope; - this.intercept = y.intercept; - this.coefficients = y.coefficients; - } else { - // creates the model - checkArraySize(x, y); - theilSen(this, x, y); } } - toJSON() { - return { - name: 'TheilSenRegression', - slope: this.slope, - intercept: this.intercept - }; - } + let Fset = []; - _predict(input) { - return this.slope * input + this.intercept; + for (let j = 0; j < p; j++) { + if (Pset[j].length !== l) { + Fset.push(j); + } } - computeX(input) { - return (input - this.intercept) / this.slope; + let D = K.clone(); + return { + n, + l, + p, + iter, + W, + XtX, + XtY, + K, + Pset, + Fset, + D + }; + } + + /** + * Computes the set difference A\B + * @private + * @param {A} set A as an array + * @param {B} set B as an array + */ + function setDifference(A, B) { + let C = []; + + for (let i of A) { + if (!B.includes(i)) C.push(i); } - toString(precision) { - var result = 'f(x) = '; + return C; + } - if (this.slope) { - var xFactor = maybeToPrecision(this.slope, precision); - result += "".concat(Math.abs(xFactor - 1) < 1e-5 ? '' : "".concat(xFactor, " * "), "x"); + function optimality(iter, maxIter, XtX, XtY, Fset, Pset, W, K, l, p, D) { + if (iter === maxIter) { + throw new Error('Maximum number of iterations exceeded'); + } // Check solution for optimality - if (this.intercept) { - var absIntercept = Math.abs(this.intercept); - var operator = absIntercept === this.intercept ? '+' : '-'; - result += " ".concat(operator, " ").concat(maybeToPrecision(absIntercept, precision)); - } - } else { - result += maybeToPrecision(this.intercept, precision); - } - return result; + let V = XtY.subMatrixColumn(Fset).subtract(XtX.mmul(K.subMatrixColumn(Fset))); + + for (let j = 0; j < Fset.length; j++) { + W.setColumn(Fset[j], V.subMatrixColumn([j])); } - toLaTeX(precision) { - return this.toString(precision); + let Jset = []; + let fullSet = []; + + for (let i = 0; i < l; i++) { + fullSet.push(i); } - static load(json) { - if (json.name !== 'TheilSenRegression') { - throw new TypeError('not a Theil-Sen model'); - } + for (let j = 0; j < Fset.length; j++) { + let notPset = setDifference(fullSet, Pset[Fset[j]]); - return new TheilSenRegression(true, json); + if (notPset.length === 0) { + Jset.push(Fset[j]); + } else if (W.selection(notPset, [Fset[j]]).max() <= 0) { + Jset.push(Fset[j]); + } } - } - - function theilSen(regression, x, y) { - let len = x.length; - let slopes = new Array(len * len); - let count = 0; + Fset = setDifference(Fset, Jset); // For non-optimal solutions, add the appropriate variables to Pset - 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]); + if (Fset.length !== 0) { + for (let j = 0; j < Fset.length; j++) { + for (let i = 0; i < l; i++) { + if (Pset[Fset[j]].includes(i)) W.set(i, Fset[j], -Infinity); } + + Pset[Fset[j]].push(W.subMatrixColumn(Fset).maxColumnIndex(j)[0]); } - } - slopes.length = count; - let medianSlope = median(slopes); - let cuts = new Array(len); + for (let j = 0; j < Fset.length; j++) { + D.setColumn(Fset[j], K.getColumn(Fset[j])); + } + } - for (let i = 0; i < len; ++i) { - cuts[i] = y[i] - medianSlope * x[i]; + for (let j = 0; j < p; j++) { + Pset[j].sort((a, b) => a - b); } - regression.slope = medianSlope; - regression.intercept = median(cuts); - regression.coefficients = [regression.intercept, regression.slope]; + return { + Pset, + Fset, + W + }; } /** - * @class RobustPolynomialRegression - * @param {Array} x - * @param {Array} y - * @param {number} degree - polynomial degree + * Fast Combinatorial Non-negative Least Squares with multiple Right Hand Side + * @param {Matrix|number[][]} X + * @param {Matrix|number[][]} Y + * @param {object} [options={}] + * @param {number} [options.maxIterations] if empty maxIterations is set at 3 times the number of columns of X + * @returns {Matrix} K */ - class RobustPolynomialRegression extends BaseRegression { - constructor(x, y, degree) { - super(); + function fcnnls(X, Y, options = {}) { + X = Matrix.checkMatrix(X); + Y = Matrix.checkMatrix(Y); + let { + l, + p, + iter, + W, + XtX, + XtY, + K, + Pset, + Fset, + D + } = initialisation(X, Y); + const { + maxIterations = X.columns * 3 + } = options; // Active set algorithm for NNLS main loop - if (x === true) { - this.degree = y.degree; - this.powers = y.powers; - this.coefficients = y.coefficients; - } else { - checkArraySize(x, y); - robustPolynomial(this, x, y, degree); - } - } + while (Fset.length > 0) { + // Solves for the passive variables (uses subroutine below) + let L = cssls(XtX, XtY.subMatrixColumn(Fset), selection(Pset, Fset), l, Fset.length); - toJSON() { - return { - name: 'robustPolynomialRegression', - degree: this.degree, - powers: this.powers, - coefficients: this.coefficients - }; - } + for (let i = 0; i < l; i++) { + for (let j = 0; j < Fset.length; j++) { + K.set(i, Fset[j], L.get(i, j)); + } + } // Finds any infeasible solutions - _predict(x) { - return predict(x, this.powers, this.coefficients); - } - /** - * Display the formula - * @param {number} precision - precision for the numbers - * @return {string} - */ + let infeasIndex = []; - toString(precision) { - return this._toFormula(precision, false); - } - /** - * Display the formula in LaTeX format - * @param {number} precision - precision for the numbers - * @return {string} - */ + for (let j = 0; j < Fset.length; j++) { + for (let i = 0; i < l; i++) { + if (L.get(i, j) < 0) { + infeasIndex.push(j); + break; + } + } + } + let Hset = selection(Fset, infeasIndex); // Makes infeasible solutions feasible (standard NNLS inner loop) - toLaTeX(precision) { - return this._toFormula(precision, true); - } + if (Hset.length > 0) { + let m = Hset.length; + let alpha = Matrix.ones(l, m); - _toFormula(precision, isLaTeX) { - let sup = '^'; - let closeSup = ''; - let times = ' * '; + while (m > 0 && iter < maxIterations) { + iter++; + alpha.mul(Infinity); // Finds indices of negative variables in passive set - if (isLaTeX) { - sup = '^{'; - closeSup = '}'; - times = ''; - } + let hRowColIdx = [[], []]; // Indexes work in pairs, each pair reprensents a single element, first array is row index, second array is column index - let fn = ''; - let str = ''; + let negRowColIdx = [[], []]; // Same as before - for (let k = 0; k < this.coefficients.length; k++) { - str = ''; + for (let j = 0; j < m; j++) { + for (let i = 0; i < Pset[Hset[j]].length; i++) { + if (K.get(Pset[Hset[j]][i], Hset[j]) < 0) { + hRowColIdx[0].push(Pset[Hset[j]][i]); // i + + hRowColIdx[1].push(j); + negRowColIdx[0].push(Pset[Hset[j]][i]); // i + + negRowColIdx[1].push(Hset[j]); + } // Compared to matlab, here we keep the row/column indexing (we are not taking the linear indexing) - if (this.coefficients[k] !== 0) { - if (this.powers[k] === 0) { - str = maybeToPrecision(this.coefficients[k], precision); - } else { - if (this.powers[k] === 1) { - str = "".concat(maybeToPrecision(this.coefficients[k], precision) + times, "x"); - } else { - str = "".concat(maybeToPrecision(this.coefficients[k], precision) + times, "x").concat(sup).concat(this.powers[k]).concat(closeSup); } } - if (this.coefficients[k] > 0 && k !== this.coefficients.length - 1) { - str = " + ".concat(str); - } else if (k !== this.coefficients.length - 1) { - str = " ".concat(str); + for (let k = 0; k < hRowColIdx[0].length; k++) { + // could be hRowColIdx[1].length as well + alpha.set(hRowColIdx[0][k], hRowColIdx[1][k], D.get(negRowColIdx[0][k], negRowColIdx[1][k]) / (D.get(negRowColIdx[0][k], negRowColIdx[1][k]) - K.get(negRowColIdx[0][k], negRowColIdx[1][k]))); } - } - - fn = str + fn; - } - - if (fn.charAt(0) === '+') { - fn = fn.slice(1); - } - return "f(x) = ".concat(fn); - } + let alphaMin = []; + let minIdx = []; - static load(json) { - if (json.name !== 'robustPolynomialRegression') { - throw new TypeError('not a RobustPolynomialRegression model'); - } + for (let j = 0; j < m; j++) { + alphaMin[j] = alpha.minColumn(j); + minIdx[j] = alpha.minColumnIndex(j)[0]; + } - return new RobustPolynomialRegression(true, json); - } + alphaMin = Matrix.rowVector(alphaMin); - } + for (let i = 0; i < l; i++) { + alpha.setSubMatrix(alphaMin, i, 0); + } - function robustPolynomial(regression, x, y, degree) { - let powers = Array(degree).fill(0).map((_, index) => index); - const tuples = getRandomTuples(x, y, degree); - var min; + let E = new Matrix(l, m); + E = D.subMatrixColumn(Hset).subtract(alpha.subMatrix(0, l - 1, 0, m - 1).mul(D.subMatrixColumn(Hset).subtract(K.subMatrixColumn(Hset)))); - for (var i = 0; i < tuples.length; i++) { - var tuple = tuples[i]; - var coefficients = calcCoefficients(tuple, powers); - var residuals = x.slice(); + for (let j = 0; j < m; j++) { + D.setColumn(Hset[j], E.subMatrixColumn([j])); + } - 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 - }; - } + let idx2zero = [minIdx, Hset]; - var median = residualsMedian(residuals); + for (let k = 0; k < m; k++) { + D.set(idx2zero[0][k], idx2zero[1][k], 0); + } - if (!min || median.residual < min.residual) { - min = median; - } - } + for (let j = 0; j < m; j++) { + Pset[Hset[j]].splice(Pset[Hset[j]].findIndex(item => item === minIdx[j]), 1); + } - regression.degree = degree; - regression.powers = powers; - regression.coefficients = min.coefficients; - } - /** - * @ignore - * @param {Array} x - * @param {Array} y - * @param {number} degree - * @return {Array<{x:number,y:number}>} - */ + L = cssls(XtX, XtY.subMatrixColumn(Hset), selection(Pset, Hset), l, m); + for (let j = 0; j < m; j++) { + K.setColumn(Hset[j], L.subMatrixColumn([j])); + } - function getRandomTuples(x, y, degree) { - var len = Math.floor(x.length / degree); - var tuples = new Array(len); + Hset = []; - for (var i = 0; i < x.length; i++) { - var pos = Math.floor(Math.random() * len); - var counter = 0; + for (let j = 0; j < K.columns; j++) { + for (let i = 0; i < l; i++) { + if (K.get(i, j) < 0) { + Hset.push(j); + break; + } + } + } - 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; + m = Hset.length; } } - if (counter === x.length) { - return tuples; - } + let newParam = optimality(iter, maxIterations, XtX, XtY, Fset, Pset, W, K, l, p, D); + Pset = newParam.Pset; + Fset = newParam.Fset; + W = newParam.W; } - return tuples; + return K; } + /** - * @ignore - * @param {{x:number,y:number}} tuple - * @param {Array} powers - * @return {Array} + * Fast Combinatorial Non-negative Least Squares with single Right Hand Side + * @param {Matrix|number[][]} X + * @param {number[]} y + * @param {object} [options={}] + * @param {boolean} [maxIterations] if true or empty maxIterations is set at 3 times the number of columns of X + * @returns {Array} k */ + function fcnnlsVector(X, y, options = {}) { + if (Array.isArray(y) === false) { + throw new TypeError('y must be a 1D Array'); + } - function calcCoefficients(tuple, powers) { - var X = tuple.slice(); - var Y = tuple.slice(); + let Y = Matrix.columnVector(y); + let K = fcnnls(X, Y, options); + let k = K.to1DArray(); + return k; + } - for (var i = 0; i < X.length; i++) { - Y[i] = [tuple[i].y]; - X[i] = new Array(powers.length); + var index$3 = /*#__PURE__*/Object.freeze({ + __proto__: null, + fcnnls: fcnnls, + fcnnlsVector: fcnnlsVector + }); - for (var j = 0; j < powers.length; j++) { - X[i][j] = Math.pow(tuple[i].x, powers[j]); - } + var binarySearch = 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"); } - return solve(X, Y).to1DArray(); - } + while (low <= high) { + // The naive `low + high >>> 1` could fail for array lengths > 2**31 + // because `>>>` converts its operands to int32. `low + (high - low >>> 1)` + // works for array lengths <= 2**32-1 which is also Javascript's max array + // length. + mid = low + (high - low >>> 1); + cmp = +comparator(haystack[mid], needle, mid, haystack); // Too low. - function predict(x, powers, coefficients) { - let y = 0; + 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. - for (let k = 0; k < powers.length; k++) { - y += coefficients[k] * Math.pow(x, powers[k]); - } - return y; - } + return ~low; + }; - function residualsMedian(residuals) { - residuals.sort((a, b) => a.residual - b.residual); - var l = residuals.length; - var half = Math.floor(l / 2); - return l % 2 === 0 ? residuals[half - 1] : residuals[half]; + function assertNumber(number) { + if (typeof number !== 'number') { + throw new TypeError('Expected a number'); + } } - /** - * 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 errorCalculation(data, parameters, parameterizedFunction) { - var error = 0; - const func = parameterizedFunction(parameters); + var ascending = (left, right) => { + assertNumber(left); + assertNumber(right); - for (var i = 0; i < data.x.length; i++) { - error += Math.abs(data.y[i] - func(data.x[i])); + if (Number.isNaN(left)) { + return -1; } - return error; - } + if (Number.isNaN(right)) { + return 1; + } - /** - * 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} - */ + return left - right; + }; - function gradientFunction(data, evaluatedData, params, gradientDifference, paramFunction) { - const n = params.length; - const m = data.x.length; - var ans = new Array(n); + var descending = (left, right) => { + assertNumber(left); + assertNumber(right); - for (var param = 0; param < n; param++) { - ans[param] = new Array(m); - var auxParams = params.concat(); - auxParams[param] += gradientDifference; - var funcParam = paramFunction(auxParams); + if (Number.isNaN(left)) { + return 1; + } - for (var point = 0; point < m; point++) { - ans[param][point] = evaluatedData[point] - funcParam(data.x[point]); - } + if (Number.isNaN(right)) { + return -1; } - return new 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} - */ + return right - left; + }; + var numSort = { + ascending: ascending, + descending: descending + }; - function matrixFunction(data, evaluatedData) { - const m = data.x.length; - var ans = new Array(m); + var index$4 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), numSort, { + 'default': numSort, + ascending: ascending, + descending: descending + })); - for (var point = 0; point < m; point++) { - ans[point] = [data.y[point] - evaluatedData[point]]; + 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(ascending); + function nextPrime(value) { + let index = binarySearch(primeNumbers, value, ascending); + + if (index < 0) { + index = ~index; } - return new Matrix(ans); + return primeNumbers[index]; } - /** - * 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 step$1(data, params, damping, gradientDifference, parameterizedFunction) { - var value = damping * gradientDifference * gradientDifference; - var identity = 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 = inverse(identity.add(gradientFunc.mmul(gradientFunc.transpose()))); - params = new Matrix([params]); - params = params.sub(inverseMatrix.mmul(gradientFunc).mmul(matrixFunc).mul(gradientDifference).transpose()); - return params.to1DArray(); - } + const FREE = 0; + const FULL = 1; + const REMOVED = 2; + const defaultInitialCapacity = 150; + const defaultMinLoadFactor = 1 / 6; + const defaultMaxLoadFactor = 2 / 3; + 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; + } - /** - * 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}} - */ + const initialCapacity = options.initialCapacity === undefined ? defaultInitialCapacity : options.initialCapacity; - 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 (initialCapacity < 0) { + throw new RangeError(`initial capacity must not be less than zero: ${initialCapacity}`); + } - 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'); - } + const minLoadFactor = options.minLoadFactor === undefined ? defaultMinLoadFactor : options.minLoadFactor; + const maxLoadFactor = options.maxLoadFactor === undefined ? defaultMaxLoadFactor : options.maxLoadFactor; - 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); + if (minLoadFactor < 0 || minLoadFactor >= 1) { + throw new RangeError(`invalid minLoadFactor: ${minLoadFactor}`); + } - if (maxValues.length !== minValues.length) { - throw new Error('minValues and maxValues must be the same size'); - } + if (maxLoadFactor <= 0 || maxLoadFactor >= 1) { + throw new RangeError(`invalid maxLoadFactor: ${maxLoadFactor}`); + } - if (!Array.isArray(parameters)) { - throw new Error('initialValues must be an array'); - } + if (minLoadFactor >= maxLoadFactor) { + throw new RangeError(`minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`); + } - var error = errorCalculation(data, parameters, parameterizedFunction); - var converged = error <= errorTolerance; + 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 - for (var iteration = 0; iteration < maxIterations && !converged; iteration++) { - parameters = step$1(data, parameters, damping, gradientDifference, parameterizedFunction); + capacity = capacity / maxLoadFactor | 0; + capacity = nextPrime(capacity); + if (capacity === 0) capacity = 1; + this.table = newArray$1(capacity); + this.values = newArray$1(capacity); + this.state = newArray$1(capacity); + this.minLoadFactor = minLoadFactor; - for (let k = 0; k < parLen; k++) { - parameters[k] = Math.min(Math.max(minValues[k], parameters[k]), maxValues[k]); + if (capacity === largestPrime) { + this.maxLoadFactor = 1; + } else { + this.maxLoadFactor = maxLoadFactor; } - error = errorCalculation(data, parameters, parameterizedFunction); - if (isNaN(error)) break; - converged = error <= errorTolerance; + this.distinct = 0; + this.freeEntries = capacity; + this.lowWaterMark = 0; + this.highWaterMark = chooseHighWaterMark(capacity, this.maxLoadFactor); } - return { - parameterValues: parameters, - parameterError: error, - iterations: iteration - }; - } - - /** - * Returns a new array based on extraction of specific indices of an array - * @private - * @param {Array} vector - * @param {Array} indices - */ - function selection(vector, indices) { - let u = []; //new Float64Array(indices.length); + clone() { + return new HashTable(this); + } - for (let i = 0; i < indices.length; i++) { - u[i] = vector[indices[i]]; + get size() { + return this.distinct; } - return u; - } + get(key) { + const i = this.indexOfKey(key); + if (i < 0) return 0; + return this.values[i]; + } - /** - * - * @private - * @param {Array of arrays} collection - */ - function sortCollectionSet(collection) { - let objectCollection = collection.map((value, index) => { - let key = BigInt(0); - value.forEach(item => key |= BigInt(1) << BigInt(item)); - return { - value, - index, - key - }; - }).sort((a, b) => { - if (a.key - b.key < 0) return -1; - return 1; - }); - let sorted = []; - let indices = []; - let key; + set(key, value) { + let i = this.indexOfInsertion(key); - for (let set of objectCollection) { - if (set.key !== key) { - key = set.key; - indices.push([]); - sorted.push(set.value); + if (i < 0) { + i = -i - 1; + this.values[i] = value; + return false; } - indices[indices.length - 1].push(set.index); - } + if (this.distinct > this.highWaterMark) { + const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor); + this.rehash(newCapacity); + return this.set(key, value); + } - let result = { - values: sorted, - indices: indices - }; - return result; - } + this.table[i] = key; + this.values[i] = value; + if (this.state[i] === FREE) this.freeEntries--; + this.state[i] = FULL; + this.distinct++; - /** - * (Combinatorial Subspace Least Squares) - subfunction for the FC-NNLS - * @private - * @param {Matrix} XtX - * @param {Matrix} XtY - * @param {Array} Pset - * @param {Numbers} l - * @param {Numbers} p - */ + if (this.freeEntries < 1) { + const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor); + this.rehash(newCapacity); + } - function cssls(XtX, XtY, Pset, l, p) { - // Solves the set of equation XtX*K = XtY for the variables in Pset - // if XtX (or XtX(vars,vars)) is singular, performs the svd and find pseudoinverse, otherwise (even if ill-conditioned) finds inverse with LU decomposition and solves the set of equation - // it is consistent with matlab results for ill-conditioned matrices (at least consistent with test 'ill-conditionned square X rank 2, Y 3x1' in cssls.test) - let K = Matrix.zeros(l, p); + return true; + } - if (Pset === null) { - let choXtX = new CholeskyDecomposition(XtX); + 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; + } - if (choXtX.isPositiveDefinite() === true) { - K = choXtX.solve(XtY); - } else { - let luXtX = new LuDecomposition(XtX); + 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; + } - if (luXtX.isSingular() === false) { - K = luXtX.solve(Matrix.eye(l)).mmul(XtY); - } else { - K = solve(XtX, XtY, { - useSVD: true - }); - } + maybeShrinkCapacity() { + if (this.distinct < this.lowWaterMark) { + const newCapacity = chooseShrinkCapacity(this.distinct, this.minLoadFactor, this.maxLoadFactor); + this.rehash(newCapacity); } - } else { - let sortedPset = sortCollectionSet(Pset).values; - let sortedEset = sortCollectionSet(Pset).indices; + } - if (sortedPset.length === 1 && sortedPset[0].length === 0 && sortedEset[0].length === p) { - return K; - } else if (sortedPset.length === 1 && sortedPset[0].length === l && sortedEset[0].length === p) { - let choXtX = new CholeskyDecomposition(XtX); + containsKey(key) { + return this.indexOfKey(key) >= 0; + } - if (choXtX.isPositiveDefinite() === true) { - K = choXtX.solve(XtY); - } else { - let luXtX = new LuDecomposition(XtX); + 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; - if (luXtX.isSingular() === false) { - K = luXtX.solve(Matrix.eye(l)).mmul(XtY); - } else { - K = solve(XtX, XtY, { - useSVD: true - }); - } - } - } else { - for (let k = 0; k < sortedPset.length; k++) { - let cols2Solve = sortedEset[k]; - let vars = sortedPset[k]; - let L; - let choXtX = new CholeskyDecomposition(XtX.selection(vars, vars)); + while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) { + i -= decrement; + if (i < 0) i += length; + } - if (choXtX.isPositiveDefinite() === true) { - L = choXtX.solve(XtY.selection(vars, cols2Solve)); - } else { - let luXtX = new LuDecomposition(XtX.selection(vars, vars)); + if (state[i] === FREE) return -1; + return i; + } - if (luXtX.isSingular() === false) { - L = luXtX.solve(Matrix.eye(vars.length)).mmul(XtY.selection(vars, cols2Solve)); - } else { - L = solve(XtX.selection(vars, vars), XtY.selection(vars, cols2Solve), { - useSVD: true - }); - } - } + containsValue(value) { + return this.indexOfValue(value) >= 0; + } - for (let i = 0; i < L.rows; i++) { - for (let j = 0; j < L.columns; j++) { - K.set(vars[i], cols2Solve[j], L.get(i, j)); - } - } + indexOfValue(value) { + const values = this.values; + const state = this.state; + + for (var i = 0; i < state.length; i++) { + if (state[i] === FULL && values[i] === value) { + return i; } } + + return -1; } - return K; - } + 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; - function initialisation(X, Y) { - let n = X.rows; - let l = X.columns; - let p = Y.columns; - let iter = 0; - if (Y.rows !== n) throw new Error('ERROR: matrix size not compatible'); - let W = Matrix.zeros(l, p); // precomputes part of pseudoinverse + while (state[i] === FULL && table[i] !== key) { + i -= decrement; + if (i < 0) i += length; + } - let XtX = X.transpose().mmul(X); - let XtY = X.transpose().mmul(Y); - let K = cssls(XtX, XtY, null, l, p); // K is lxp + if (state[i] === REMOVED) { + const j = i; - let Pset = []; + while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) { + i -= decrement; + if (i < 0) i += length; + } - for (let j = 0; j < p; j++) { - Pset[j] = []; + if (state[i] === FREE) i = j; + } - for (let i = 0; i < l; i++) { - if (K.get(i, j) > 0) { - Pset[j].push(i); - } else { - K.set(i, j, 0); - } //This is our initial solution, it's the solution found by overwriting the unconstrained least square solution + if (state[i] === FULL) { + return -i - 1; + } + return i; + } + + ensureCapacity(minCapacity) { + if (this.table.length < minCapacity) { + const newCapacity = nextPrime(minCapacity); + this.rehash(newCapacity); } } - let Fset = []; + 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$1(newCapacity); + const newValues = newArray$1(newCapacity); + const newState = newArray$1(newCapacity); + 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 (let j = 0; j < p; j++) { - if (Pset[j].length !== l) { - Fset.push(j); + 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; + } } } - let D = K.clone(); - return { - n, - l, - p, - iter, - W, - XtX, - XtY, - K, - Pset, - Fset, - D - }; - } + forEachKey(callback) { + for (var i = 0; i < this.state.length; i++) { + if (this.state[i] === FULL) { + if (!callback(this.table[i])) return false; + } + } - /** - * Computes the set difference A\B - * @private - * @param {A} set A as an array - * @param {B} set B as an array - */ - function setDifference(A, B) { - let C = []; + return true; + } - for (let i of A) { - if (!B.includes(i)) C.push(i); + 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; + } + + 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; } - return C; } - function optimality(iter, maxIter, XtX, XtY, Fset, Pset, W, K, l, p, D) { - if (iter === maxIter) { - throw new Error('Maximum number of iterations exceeded'); - } // Check solution for optimality + function chooseLowWaterMark(capacity, minLoad) { + return capacity * minLoad | 0; + } + function chooseHighWaterMark(capacity, maxLoad) { + return Math.min(capacity - 2, capacity * maxLoad | 0); + } - let V = XtY.subMatrixColumn(Fset).subtract(XtX.mmul(K.subMatrixColumn(Fset))); + function chooseGrowCapacity(size, minLoad, maxLoad) { + return nextPrime(Math.max(size + 1, 4 * size / (3 * minLoad + maxLoad) | 0)); + } - for (let j = 0; j < Fset.length; j++) { - W.setColumn(Fset[j], V.subMatrixColumn([j])); - } + function chooseShrinkCapacity(size, minLoad, maxLoad) { + return nextPrime(Math.max(size + 1, 4 * size / (minLoad + 3 * maxLoad) | 0)); + } - let Jset = []; - let fullSet = []; + function newArray$1(size) { + return Array(size).fill(0); + } - for (let i = 0; i < l; i++) { - fullSet.push(i); - } + class SparseMatrix { + constructor(rows, columns, options = {}) { + if (rows instanceof SparseMatrix) { + // clone + const other = rows; - for (let j = 0; j < Fset.length; j++) { - let notPset = setDifference(fullSet, Pset[Fset[j]]); + this._init(other.rows, other.columns, other.elements.clone(), other.threshold); - if (notPset.length === 0) { - Jset.push(Fset[j]); - } else if (W.selection(notPset, [Fset[j]]).max() <= 0) { - Jset.push(Fset[j]); + return; } - } - Fset = setDifference(Fset, Jset); // For non-optimal solutions, add the appropriate variables to Pset + if (Array.isArray(rows)) { + const matrix = rows; + rows = matrix.length; + options = columns || {}; + columns = matrix[0].length; - if (Fset.length !== 0) { - for (let j = 0; j < Fset.length; j++) { - for (let i = 0; i < l; i++) { - if (Pset[Fset[j]].includes(i)) W.set(i, Fset[j], -Infinity); - } + this._init(rows, columns, new HashTable(options), options.threshold); - Pset[Fset[j]].push(W.subMatrixColumn(Fset).maxColumnIndex(j)[0]); - } + 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; - for (let j = 0; j < Fset.length; j++) { - D.setColumn(Fset[j], K.getColumn(Fset[j])); + if (value !== 0) { + this.elements.set(i * columns + j, matrix[i][j]); + } + } + } + } else { + this._init(rows, columns, new HashTable(options), options.threshold); } } - for (let j = 0; j < p; j++) { - Pset[j].sort((a, b) => a - b); + _init(rows, columns, elements, threshold) { + this.rows = rows; + this.columns = columns; + this.elements = elements; + this.threshold = threshold || 0; } - return { - Pset, - Fset, - W - }; - } - - /** - * Fast Combinatorial Non-negative Least Squares with multiple Right Hand Side - * @param {Matrix|number[][]} X - * @param {Matrix|number[][]} Y - * @param {object} [options={}] - * @param {number} [options.maxIterations] if empty maxIterations is set at 3 times the number of columns of X - * @returns {Matrix} K - */ - - function fcnnls(X, Y) { - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - X = Matrix.checkMatrix(X); - Y = Matrix.checkMatrix(Y); - let { - l, - p, - iter, - W, - XtX, - XtY, - K, - Pset, - Fset, - D - } = initialisation(X, Y); - const { - maxIterations = X.columns * 3 - } = options; // Active set algorithm for NNLS main loop + static eye(rows = 1, columns = rows) { + const min = Math.min(rows, columns); + const matrix = new SparseMatrix(rows, columns, { + initialCapacity: min + }); - while (Fset.length > 0) { - // Solves for the passive variables (uses subroutine below) - let L = cssls(XtX, XtY.subMatrixColumn(Fset), selection(Pset, Fset), l, Fset.length); + for (var i = 0; i < min; i++) { + matrix.set(i, i, 1); + } - for (let i = 0; i < l; i++) { - for (let j = 0; j < Fset.length; j++) { - K.set(i, Fset[j], L.get(i, j)); - } - } // Finds any infeasible solutions + return matrix; + } + clone() { + return new SparseMatrix(this); + } - let infeasIndex = []; + to2DArray() { + const copy = new Array(this.rows); - for (let j = 0; j < Fset.length; j++) { - for (let i = 0; i < l; i++) { - if (L.get(i, j) < 0) { - infeasIndex.push(j); - break; - } + 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); } } - let Hset = selection(Fset, infeasIndex); // Makes infeasible solutions feasible (standard NNLS inner loop) + return copy; + } - if (Hset.length > 0) { - let m = Hset.length; - let alpha = Matrix.ones(l, m); + isSquare() { + return this.rows === this.columns; + } - while (m > 0 && iter < maxIterations) { - iter++; - alpha.mul(Infinity); // Finds indices of negative variables in passive set + isSymmetric() { + if (!this.isSquare()) return false; + var symmetric = true; + this.forEachNonZero((i, j, v) => { + if (this.get(j, i) !== v) { + symmetric = false; + return false; + } - let hRowColIdx = [[], []]; // Indexes work in pairs, each pair reprensents a single element, first array is row index, second array is column index + return v; + }); + return symmetric; + } + /** + * Search for the wither band in the main diagonals + * @return {number} + */ - let negRowColIdx = [[], []]; // Same as before - for (let j = 0; j < m; j++) { - for (let i = 0; i < Pset[Hset[j]].length; i++) { - if (K.get(Pset[Hset[j]][i], Hset[j]) < 0) { - hRowColIdx[0].push(Pset[Hset[j]][i]); // i + 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} + */ - hRowColIdx[1].push(j); - negRowColIdx[0].push(Pset[Hset[j]][i]); // i - negRowColIdx[1].push(Hset[j]); - } // Compared to matlab, here we keep the row/column indexing (we are not taking the linear indexing) + isBanded(width) { + let bandWidth = this.bandWidth(); + return bandWidth <= width; + } - } - } + get cardinality() { + return this.elements.size; + } - for (let k = 0; k < hRowColIdx[0].length; k++) { - // could be hRowColIdx[1].length as well - alpha.set(hRowColIdx[0][k], hRowColIdx[1][k], D.get(negRowColIdx[0][k], negRowColIdx[1][k]) / (D.get(negRowColIdx[0][k], negRowColIdx[1][k]) - K.get(negRowColIdx[0][k], negRowColIdx[1][k]))); - } + get size() { + return this.rows * this.columns; + } - let alphaMin = []; - let minIdx = []; + get(row, column) { + return this.elements.get(row * this.columns + column); + } - for (let j = 0; j < m; j++) { - alphaMin[j] = alpha.minColumn(j); - minIdx[j] = alpha.minColumnIndex(j)[0]; - } + set(row, column, value) { + if (this.threshold && Math.abs(value) < this.threshold) value = 0; - alphaMin = Matrix.rowVector(alphaMin); + if (value === 0) { + this.elements.remove(row * this.columns + column); + } else { + this.elements.set(row * this.columns + column, value); + } - for (let i = 0; i < l; i++) { - alpha.setSubMatrix(alphaMin, i, 0); - } + return this; + } - let E = new Matrix(l, m); - E = D.subMatrixColumn(Hset).subtract(alpha.subMatrix(0, l - 1, 0, m - 1).mul(D.subMatrixColumn(Hset).subtract(K.subMatrixColumn(Hset)))); + 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.'); + } - for (let j = 0; j < m; j++) { - D.setColumn(Hset[j], E.subMatrixColumn([j])); + 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); } - let idx2zero = [minIdx, Hset]; + return v2; + }); + return v1; + }); + return result; + } - for (let k = 0; k < m; k++) { - D.set(idx2zero[0][k], idx2zero[1][k], 0); - } + 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; + } - for (let j = 0; j < m; j++) { - Pset[Hset[j]].splice(Pset[Hset[j]].findIndex(item => item === minIdx[j]), 1); - } + 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 - L = cssls(XtX, XtY.subMatrixColumn(Hset), selection(Pset, Hset), l, m); + if (this.threshold && Math.abs(r) < this.threshold) r = 0; - for (let j = 0; j < m; j++) { - K.setColumn(Hset[j], L.subMatrixColumn([j])); + if (r !== value) { + if (r === 0) { + this.elements.remove(key, true); + } else { + this.elements.set(key, r); } + } - Hset = []; + return true; + }); + this.elements.maybeShrinkCapacity(); + return this; + } - for (let j = 0; j < K.columns; j++) { - for (let i = 0; i < l; i++) { - if (K.get(i, j) < 0) { - Hset.push(j); - break; - } - } - } + 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 + }; + } - m = Hset.length; - } + setThreshold(newThreshold) { + if (newThreshold !== 0 && newThreshold !== this.threshold) { + this.threshold = newThreshold; + this.forEachNonZero((i, j, v) => v); } - let newParam = optimality(iter, maxIterations, XtX, XtY, Fset, Pset, W, K, l, p, D); - Pset = newParam.Pset; - Fset = newParam.Fset; - W = newParam.W; + return this; + } + /** + * @return {SparseMatrix} - New transposed sparse matrix + */ + + + 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; + } + + } + SparseMatrix.prototype.klass = 'Matrix'; + SparseMatrix.identity = SparseMatrix.eye; + SparseMatrix.prototype.tensorProduct = SparseMatrix.prototype.kroneckerProduct; + /* + Add dynamically instance and static methods for mathematical operations + */ + + 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%(); +}) +`; + const operators = [// Arithmetic operators + ['+', 'add'], ['-', 'sub', 'subtract'], ['*', 'mul', 'multiply'], ['/', 'div', 'divide'], ['%', 'mod', 'modulus'], // Bitwise operators + ['&', 'and'], ['|', 'or'], ['^', 'xor'], ['<<', 'leftShift'], ['>>', 'signPropagatingRightShift'], ['>>>', 'rightShift', 'zeroFillRightShift']]; + + 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] + })); } - - return K; } - /** - * Fast Combinatorial Non-negative Least Squares with single Right Hand Side - * @param {Matrix|number[][]} X - * @param {number[]} y - * @param {object} [options={}] - * @param {boolean} [maxIterations] if true or empty maxIterations is set at 3 times the number of columns of X - * @returns {Array} k - */ + 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]); + }); - function fcnnlsVector(X, y) { - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + 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] + })); + } + } - if (Array.isArray(y) === false) { - throw new TypeError('y must be a 1D Array'); + function fillTemplateFunction(template, values) { + for (const i in values) { + template = template.replace(new RegExp(`%${i}%`, 'g'), values[i]); } - let Y = Matrix.columnVector(y); - let K = fcnnls(X, Y, options); - let k = K.to1DArray(); - return k; + return template; } + function additiveSymmetric(a, b) { + var i = 0; + var ii = a.length; + var d = 0; + for (; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]) * (a[i] + b[i]) / (a[i] * b[i]); + } - var index$2 = /*#__PURE__*/Object.freeze({ - __proto__: null, - fcnnls: fcnnls, - fcnnlsVector: fcnnlsVector - }); + return 2 * d; + } - var binarySearch = function binarySearch(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"); - } + function avg(a, b) { + var ii = a.length; + var max = 0; + var ans = 0; + var aux = 0; - while (low <= high) { - // The naive `low + high >>> 1` could fail for array lengths > 2**31 - // because `>>>` converts its operands to int32. `low + (high - low >>> 1)` - // works for array lengths <= 2**32-1 which is also Javascript's max array - // length. - mid = low + (high - low >>> 1); - cmp = +comparator(haystack[mid], needle, mid, haystack); // Too low. + for (var i = 0; i < ii; i++) { + aux = Math.abs(a[i] - b[i]); + ans += aux; - 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. + if (max < aux) { + max = aux; + } + } + return (max + ans) / 2; + } - return ~low; - }; + function bhattacharyya(a, b) { + var ii = a.length; + var ans = 0; - function assertNumber(number) { - if (typeof number !== 'number' || Number.isNaN(number)) { - throw new TypeError('Expected a number'); + for (var i = 0; i < ii; i++) { + ans += Math.sqrt(a[i] * b[i]); } + + return -Math.log(ans); } - var ascending = (left, right) => { - assertNumber(left); - assertNumber(right); - return left - right; - }; + function canberra(a, b) { + var ii = a.length; + var ans = 0; - var descending = (left, right) => { - assertNumber(left); - assertNumber(right); - return right - left; - }; + for (var i = 0; i < ii; i++) { + ans += Math.abs(a[i] - b[i]) / (a[i] + b[i]); + } - var numSort = { - ascending: ascending, - descending: descending - }; + return ans; + } - var index$3 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': numSort, - __moduleExports: numSort, - ascending: ascending, - descending: descending - }); + function chebyshev(a, b) { + var ii = a.length; + var max = 0; + var aux = 0; - 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(ascending); - function nextPrime(value) { - let index = binarySearch(primeNumbers, value, ascending); + for (var i = 0; i < ii; i++) { + aux = Math.abs(a[i] - b[i]); - if (index < 0) { - index = ~index; + if (max < aux) { + max = aux; + } } - return primeNumbers[index]; + return max; } - 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] : {}; + function clark(a, b) { + var i = 0; + var ii = a.length; + var d = 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; - } + for (; i < ii; i++) { + d += Math.sqrt((a[i] - b[i]) * (a[i] - b[i]) / ((a[i] + b[i]) * (a[i] + b[i]))); + } - const initialCapacity = options.initialCapacity === undefined ? defaultInitialCapacity : options.initialCapacity; + return 2 * d; + } - if (initialCapacity < 0) { - throw new RangeError("initial capacity must not be less than zero: ".concat(initialCapacity)); - } + function czekanowskiSimilarity(a, b) { + var up = 0; + var down = 0; - const minLoadFactor = options.minLoadFactor === undefined ? defaultMinLoadFactor : options.minLoadFactor; - const maxLoadFactor = options.maxLoadFactor === undefined ? defaultMaxLoadFactor : options.maxLoadFactor; + for (var i = 0; i < a.length; i++) { + up += Math.min(a[i], b[i]); + down += a[i] + b[i]; + } - if (minLoadFactor < 0 || minLoadFactor >= 1) { - throw new RangeError("invalid minLoadFactor: ".concat(minLoadFactor)); - } + return 2 * up / down; + } - if (maxLoadFactor <= 0 || maxLoadFactor >= 1) { - throw new RangeError("invalid maxLoadFactor: ".concat(maxLoadFactor)); - } + function czekanowskiDistance(a, b) { + return 1 - czekanowskiSimilarity(a, b); + } - if (minLoadFactor >= maxLoadFactor) { - throw new RangeError("minLoadFactor (".concat(minLoadFactor, ") must be smaller than maxLoadFactor (").concat(maxLoadFactor, ")")); - } + function dice(a, b) { + var ii = a.length; + var p = 0; + var q1 = 0; + var q2 = 0; - 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 + 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]); + } - capacity = capacity / maxLoadFactor | 0; - capacity = nextPrime(capacity); - if (capacity === 0) capacity = 1; - this.table = newArray$1(capacity); - this.values = newArray$1(capacity); - this.state = newArray$1(capacity); - this.minLoadFactor = minLoadFactor; + return q2 / (p + q1); + } - if (capacity === largestPrime) { - this.maxLoadFactor = 1; - } else { - this.maxLoadFactor = maxLoadFactor; - } + function divergence(a, b) { + var i = 0; + var ii = a.length; + var d = 0; - this.distinct = 0; - this.freeEntries = capacity; - this.lowWaterMark = 0; - this.highWaterMark = chooseHighWaterMark(capacity, this.maxLoadFactor); + for (; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]) / ((a[i] + b[i]) * (a[i] + b[i])); } - clone() { - return new HashTable(this); + return 2 * d; + } + + function fidelity(a, b) { + var ii = a.length; + var ans = 0; + + for (var i = 0; i < ii; i++) { + ans += Math.sqrt(a[i] * b[i]); } - get size() { - return this.distinct; - } + return ans; + } - get(key) { - const i = this.indexOfKey(key); - if (i < 0) return 0; - return this.values[i]; + function gower(a, b) { + var ii = a.length; + var ans = 0; + + for (var i = 0; i < ii; i++) { + ans += Math.abs(a[i] - b[i]); } - set(key, value) { - let i = this.indexOfInsertion(key); + return ans / ii; + } - if (i < 0) { - i = -i - 1; - this.values[i] = value; - return false; - } + function harmonicMean(a, b) { + var ii = a.length; + var ans = 0; - if (this.distinct > this.highWaterMark) { - const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor); - this.rehash(newCapacity); - return this.set(key, value); - } + for (var i = 0; i < ii; i++) { + ans += a[i] * b[i] / (a[i] + b[i]); + } - this.table[i] = key; - this.values[i] = value; - if (this.state[i] === FREE) this.freeEntries--; - this.state[i] = FULL; - this.distinct++; + return 2 * ans; + } - if (this.freeEntries < 1) { - const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor); - this.rehash(newCapacity); - } + function hellinger(a, b) { + var ii = a.length; + var ans = 0; - return true; + for (var i = 0; i < ii; i++) { + ans += Math.sqrt(a[i] * b[i]); } - 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; - } + return 2 * Math.sqrt(1 - ans); + } - 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; - } + function innerProduct(a, b) { + var ii = a.length; + var ans = 0; - maybeShrinkCapacity() { - if (this.distinct < this.lowWaterMark) { - const newCapacity = chooseShrinkCapacity(this.distinct, this.minLoadFactor, this.maxLoadFactor); - this.rehash(newCapacity); - } + for (var i = 0; i < ii; i++) { + ans += a[i] * b[i]; } - containsKey(key) { - return this.indexOfKey(key) >= 0; + return ans; + } + + function intersection(a, b) { + var ii = a.length; + var ans = 0; + + for (var i = 0; i < ii; i++) { + ans += Math.min(a[i], b[i]); } - 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; + return 1 - ans; + } - while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) { - i -= decrement; - if (i < 0) i += length; - } + function jaccard(a, b) { + var ii = a.length; + var p1 = 0; + var p2 = 0; + var q1 = 0; + var q2 = 0; - if (state[i] === FREE) return -1; - return i; + 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]); } - containsValue(value) { - return this.indexOfValue(value) >= 0; + return q2 / (p2 + q1 - p1); + } + + function jeffreys(a, b) { + var ii = a.length; + var ans = 0; + + for (var i = 0; i < ii; i++) { + ans += (a[i] - b[i]) * Math.log(a[i] / b[i]); } - indexOfValue(value) { - const values = this.values; - const state = this.state; + return ans; + } - for (var i = 0; i < state.length; i++) { - if (state[i] === FULL && values[i] === value) { - return i; - } - } + function jensenDifference(a, b) { + var ii = a.length; + var ans = 0; - return -1; + 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); } - 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; - - while (state[i] === FULL && table[i] !== key) { - i -= decrement; - if (i < 0) i += length; - } + return ans; + } - if (state[i] === REMOVED) { - const j = i; + function jensenShannon(a, b) { + var ii = a.length; + var p = 0; + var q = 0; - while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) { - i -= decrement; - if (i < 0) i += length; - } + 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])); + } - if (state[i] === FREE) i = j; - } + return (p + q) / 2; + } - if (state[i] === FULL) { - return -i - 1; - } + function kdivergence(a, b) { + var ii = a.length; + var ans = 0; - return i; + for (var i = 0; i < ii; i++) { + ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])); } - ensureCapacity(minCapacity) { - if (this.table.length < minCapacity) { - const newCapacity = nextPrime(minCapacity); - this.rehash(newCapacity); - } - } + return ans; + } - 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$1(newCapacity); - const newValues = newArray$1(newCapacity); - const newState = newArray$1(newCapacity); - 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; + function kulczynski(a, b) { + var ii = a.length; + var up = 0; + var down = 0; - 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; - } - } + for (var i = 0; i < ii; i++) { + up += Math.abs(a[i] - b[i]); + down += Math.min(a[i], b[i]); } - forEachKey(callback) { - for (var i = 0; i < this.state.length; i++) { - if (this.state[i] === FULL) { - if (!callback(this.table[i])) return false; - } - } + return up / down; + } - return true; + function kullbackLeibler(a, b) { + var ii = a.length; + var ans = 0; + + for (var i = 0; i < ii; i++) { + ans += a[i] * Math.log(a[i] / b[i]); } - forEachValue(callback) { - for (var i = 0; i < this.state.length; i++) { - if (this.state[i] === FULL) { - if (!callback(this.values[i])) return false; - } - } + return ans; + } - return true; + function kumarHassebrook(a, b) { + var ii = a.length; + var p = 0; + var p2 = 0; + var q2 = 0; + + for (var i = 0; i < ii; i++) { + p += a[i] * b[i]; + p2 += a[i] * a[i]; + q2 += b[i] * b[i]; } - 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 p / (p2 + q2 - p); + } - return true; + function kumarJohnson(a, b) { + var ii = a.length; + var 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; } - function chooseLowWaterMark(capacity, minLoad) { - return capacity * minLoad | 0; - } + function lorentzian(a, b) { + var ii = a.length; + var ans = 0; - function chooseHighWaterMark(capacity, maxLoad) { - return Math.min(capacity - 2, capacity * maxLoad | 0); - } + for (var i = 0; i < ii; i++) { + ans += Math.log(Math.abs(a[i] - b[i]) + 1); + } - function chooseGrowCapacity(size, minLoad, maxLoad) { - return nextPrime(Math.max(size + 1, 4 * size / (3 * minLoad + maxLoad) | 0)); + return ans; } - function chooseShrinkCapacity(size, minLoad, maxLoad) { - return nextPrime(Math.max(size + 1, 4 * size / (minLoad + 3 * maxLoad) | 0)); - } + function manhattan(a, b) { + var i = 0; + var ii = a.length; + var d = 0; - function newArray$1(size) { - return Array(size).fill(0); + for (; i < ii; i++) { + d += Math.abs(a[i] - b[i]); + } + + return d; } - class SparseMatrix { - constructor(rows, columns) { - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + function matusita(a, b) { + var ii = a.length; + var ans = 0; - if (rows instanceof SparseMatrix) { - // clone - const other = rows; + for (var i = 0; i < ii; i++) { + ans += Math.sqrt(a[i] * b[i]); + } - this._init(other.rows, other.columns, other.elements.clone(), other.threshold); + return Math.sqrt(2 - 2 * ans); + } - return; - } + function minkowski(a, b, p) { + var i = 0; + var ii = a.length; + var d = 0; - if (Array.isArray(rows)) { - const matrix = rows; - rows = matrix.length; - options = columns || {}; - columns = matrix[0].length; + for (; i < ii; i++) { + d += Math.pow(Math.abs(a[i] - b[i]), p); + } - this._init(rows, columns, new HashTable(options), options.threshold); + return Math.pow(d, 1 / p); + } - 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; + function motyka(a, b) { + var ii = a.length; + var up = 0; + var down = 0; - if (value !== 0) { - this.elements.set(i * columns + j, matrix[i][j]); - } - } - } - } else { - this._init(rows, columns, new HashTable(options), options.threshold); - } + for (var i = 0; i < ii; i++) { + up += Math.min(a[i], b[i]); + down += a[i] + b[i]; } - _init(rows, columns, elements, threshold) { - this.rows = rows; - this.columns = columns; - this.elements = elements; - this.threshold = threshold || 0; + return 1 - up / down; + } + + function neyman(a, b) { + var i = 0; + var ii = a.length; + var d = 0; + + for (; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]) / a[i]; } - 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 - }); + return d; + } - for (var i = 0; i < min; i++) { - matrix.set(i, i, 1); - } + function pearson(a, b) { + var i = 0; + var ii = a.length; + var d = 0; - return matrix; + for (; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]) / b[i]; } - clone() { - return new SparseMatrix(this); - } + return d; + } - to2DArray() { - const copy = new Array(this.rows); + function probabilisticSymmetric(a, b) { + var i = 0; + var ii = a.length; + var d = 0; - for (var i = 0; i < this.rows; i++) { - copy[i] = new Array(this.columns); + for (; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]) / (a[i] + b[i]); + } - for (var j = 0; j < this.columns; j++) { - copy[i][j] = this.get(i, j); - } - } + return 2 * d; + } - return copy; - } + function ruzicka(a, b) { + var ii = a.length; + var up = 0; + var down = 0; - isSquare() { - return this.rows === this.columns; + for (var i = 0; i < ii; i++) { + up += Math.min(a[i], b[i]); + down += Math.max(a[i], b[i]); } - 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 up / down; + } - return v; - }); - return symmetric; + function soergel(a, b) { + var ii = a.length; + var up = 0; + var down = 0; + + for (var i = 0; i < ii; i++) { + up += Math.abs(a[i] - b[i]); + down += Math.max(a[i], b[i]); } - /** - * Search for the wither band in the main diagonals - * @return {number} - */ + return up / down; + } - 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; + function sorensen(a, b) { + var ii = a.length; + var up = 0; + var down = 0; + + for (var i = 0; i < ii; i++) { + up += Math.abs(a[i] - b[i]); + down += a[i] + b[i]; } - /** - * Test if a matrix is consider banded using a threshold - * @param {number} width - * @return {boolean} - */ + return up / down; + } - isBanded(width) { - let bandWidth = this.bandWidth(); - return bandWidth <= width; - } + function squared(a, b) { + var i = 0; + var ii = a.length; + var d = 0; - get cardinality() { - return this.elements.size; + for (; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]) / (a[i] + b[i]); } - get size() { - return this.rows * this.columns; - } + return d; + } - get(row, column) { - return this.elements.get(row * this.columns + column); + function squaredChord(a, b) { + var ii = a.length; + var 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])); } - set(row, column, value) { - if (this.threshold && Math.abs(value) < this.threshold) value = 0; + return ans; + } - if (value === 0) { - this.elements.remove(row * this.columns + column); - } else { - this.elements.set(row * this.columns + column, value); - } + function taneja(a, b) { + var ii = a.length; + var ans = 0; - return this; + 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]))); } - 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.'); - } - - 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); - } + return ans; + } - return v2; - }); - return v1; - }); - return result; - } + function tanimoto(a, b, bitvector) { + if (bitvector) { + var inter = 0; + var union = 0; - 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; - } + for (var j = 0; j < a.length; j++) { + inter += a[j] && b[j]; + union += a[j] || b[j]; + } - 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 (union === 0) { + return 1; + } - if (this.threshold && Math.abs(r) < this.threshold) r = 0; + return inter / union; + } else { + var ii = a.length; + var p = 0; + var q = 0; + var m = 0; - if (r !== value) { - if (r === 0) { - this.elements.remove(key, true); - } else { - this.elements.set(key, r); - } - } + for (var i = 0; i < ii; i++) { + p += a[i]; + q += b[i]; + m += Math.min(a[i], b[i]); + } - return true; - }); - this.elements.maybeShrinkCapacity(); - return this; + return 1 - (p + q - 2 * m) / (p + q - m); } + } - 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 - }; - } + function tanimoto$1(a, b, bitvector) { + if (bitvector) { + return 1 - tanimoto(a, b, bitvector); + } else { + var ii = a.length; + var p = 0; + var q = 0; + var m = 0; - setThreshold(newThreshold) { - if (newThreshold !== 0 && newThreshold !== this.threshold) { - this.threshold = newThreshold; - this.forEachNonZero((i, j, v) => v); + for (var i = 0; i < ii; i++) { + p += a[i]; + q += b[i]; + m += Math.min(a[i], b[i]); } - return this; + return (p + q - 2 * m) / (p + q - m); } - /** - * @return {SparseMatrix} - New transposed sparse matrix - */ + } + function topsoe(a, b) { + var ii = a.length; + var ans = 0; - 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; + 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])); } + return ans; } - SparseMatrix.prototype.klass = 'Matrix'; - SparseMatrix.identity = SparseMatrix.eye; - SparseMatrix.prototype.tensorProduct = SparseMatrix.prototype.kroneckerProduct; - /* - 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 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']]; + function waveHedges(a, b) { + var ii = a.length; + var ans = 0; - 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["".concat(operator[i], "S")] = eval(fillTemplateFunction(inplaceOperatorScalar, { - name: "".concat(operator[i], "S"), - op: operator[0] - })); - SparseMatrix.prototype["".concat(operator[i], "M")] = eval(fillTemplateFunction(inplaceOperatorMatrix, { - name: "".concat(operator[i], "M"), - op: operator[0] - })); - SparseMatrix[operator[i]] = eval(fillTemplateFunction(staticOperator, { - name: operator[i] - })); + for (var i = 0; i < ii; i++) { + ans += 1 - Math.min(a[i], b[i]) / Math.max(a[i], b[i]); } + + return ans; } - 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]); + var distances = /*#__PURE__*/Object.freeze({ + __proto__: null, + euclidean: euclidean, + squaredEuclidean: squaredEuclidean, + additiveSymmetric: additiveSymmetric, + avg: avg, + bhattacharyya: bhattacharyya, + canberra: canberra, + chebyshev: chebyshev, + clark: clark, + czekanowski: czekanowskiDistance, + dice: dice, + divergence: divergence, + fidelity: fidelity, + gower: gower, + harmonicMean: harmonicMean, + hellinger: hellinger, + innerProduct: innerProduct, + intersection: intersection, + jaccard: jaccard, + jeffreys: jeffreys, + jensenDifference: jensenDifference, + jensenShannon: jensenShannon, + kdivergence: kdivergence, + kulczynski: kulczynski, + kullbackLeibler: kullbackLeibler, + kumarHassebrook: kumarHassebrook, + kumarJohnson: kumarJohnson, + lorentzian: lorentzian, + manhattan: manhattan, + matusita: matusita, + minkowski: minkowski, + motyka: motyka, + neyman: neyman, + pearson: pearson, + probabilisticSymmetric: probabilisticSymmetric, + ruzicka: ruzicka, + soergel: soergel, + sorensen: sorensen, + squared: squared, + squaredChord: squaredChord, + taneja: taneja, + tanimoto: tanimoto$1, + topsoe: topsoe, + waveHedges: waveHedges }); - 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] - })); - } - } - - function fillTemplateFunction(template, values) { - for (const i in values) { - template = template.replace(new RegExp("%".concat(i, "%"), 'g'), values[i]); - } + /** + * Function that creates the tree + * @param {Array>} spectrum + * @param {object} [options] + * @return {Tree|null} + * left and right have the same structure than the parent, + * or are null if they are leaves + */ - return template; + function createTree(spectrum, options = {}) { + var X = spectrum[0]; + const { + minWindow = 0.16, + threshold = 0.01, + from = X[0], + to = X[X.length - 1] + } = options; + return mainCreateTree(spectrum[0], spectrum[1], from, to, minWindow, threshold); } - function additiveSymmetric(a, b) { - var i = 0; - var ii = a.length; - var d = 0; + function mainCreateTree(X, Y, from, to, minWindow, threshold) { + if (to - from < minWindow) { + return null; + } // search first point - for (; i < ii; i++) { - d += (a[i] - b[i]) * (a[i] - b[i]) * (a[i] + b[i]) / (a[i] * b[i]); - } - return 2 * d; - } + var start = binarySearch(X, from, ascending); - function avg(a, b) { - var ii = a.length; - var max = 0; - var ans = 0; - var aux = 0; + if (start < 0) { + start = ~start; + } // stop at last point - for (var i = 0; i < ii; i++) { - aux = Math.abs(a[i] - b[i]); - ans += aux; - if (max < aux) { - max = aux; + var sum = 0; + var center = 0; + + for (var i = start; i < X.length; i++) { + if (X[i] >= to) { + break; } + + sum += Y[i]; + center += X[i] * Y[i]; } - return (max + ans) / 2; - } + if (sum < threshold) { + return null; + } - function bhattacharyya(a, b) { - var ii = a.length; - var ans = 0; + center /= sum; - for (var i = 0; i < ii; i++) { - ans += Math.sqrt(a[i] * b[i]); + if (center - from < 1e-6 || to - center < 1e-6) { + return null; } - return -Math.log(ans); + if (center - from < minWindow / 4) { + return mainCreateTree(X, Y, center, to, minWindow, threshold); + } else { + if (to - center < minWindow / 4) { + return mainCreateTree(X, Y, from, center, minWindow, threshold); + } else { + return new Tree(sum, center, mainCreateTree(X, Y, from, center, minWindow, threshold), mainCreateTree(X, Y, center, to, minWindow, threshold)); + } + } } - function canberra(a, b) { - var ii = a.length; - var ans = 0; - - for (var i = 0; i < ii; i++) { - ans += Math.abs(a[i] - b[i]) / (a[i] + b[i]); + class Tree { + constructor(sum, center, left, right) { + this.sum = sum; + this.center = center; + this.left = left; + this.right = right; } - return ans; } - function chebyshev(a, b) { - var ii = a.length; - var max = 0; - var aux = 0; + /** + * Similarity between two nodes + * @param {Tree|Array>} a - tree A node + * @param {Tree|Array>} b - tree B node + * @param {object} [options] + * @return {number} similarity measure between tree nodes + */ - for (var i = 0; i < ii; i++) { - aux = Math.abs(a[i] - b[i]); + function getSimilarity(a, b, options = {}) { + const { + alpha = 0.1, + beta = 0.33, + gamma = 0.001 + } = options; - if (max < aux) { - max = aux; - } + if (a === null || b === null) { + return 0; } - return max; - } - - function clark(a, b) { - var i = 0; - var ii = a.length; - var 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]))); + if (Array.isArray(a)) { + a = createTree(a); } - return 2 * d; - } - - 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]; + if (Array.isArray(b)) { + b = createTree(b); } - return 2 * up / down; + 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) * (getSimilarity(a.left, b.left, options) + getSimilarity(a.right, b.right, options)) / 2; } - function czekanowskiDistance(a, b) { - return 1 - czekanowskiSimilarity(a, b); + function treeSimilarity(A, B, options = {}) { + return getSimilarity(A, B, options); + } + function getFunction(options = {}) { + return (A, B) => getSimilarity(A, B, options); } - function dice(a, b) { + var index$5 = /*#__PURE__*/Object.freeze({ + __proto__: null, + treeSimilarity: treeSimilarity, + getFunction: getFunction, + createTree: createTree + }); + + function cosine(a, b) { var ii = a.length; var p = 0; - var q1 = 0; + var p2 = 0; var 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]); + p += a[i] * b[i]; + p2 += a[i] * a[i]; + q2 += b[i] * b[i]; } - return q2 / (p + q1); + return p / (Math.sqrt(p2) * Math.sqrt(q2)); } - function divergence(a, b) { - var i = 0; - var ii = a.length; - var 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; + function dice$1(a, b) { + return 1 - dice(a, b); } - function fidelity(a, b) { - var ii = a.length; - var ans = 0; - - for (var i = 0; i < ii; i++) { - ans += Math.sqrt(a[i] * b[i]); - } - - return ans; + function intersection$1(a, b) { + return 1 - intersection(a, b); } - function gower(a, b) { - var ii = a.length; - var ans = 0; + function jaccard$1(a, b) { + return 1 - jaccard(a, b); + } - for (var i = 0; i < ii; i++) { - ans += Math.abs(a[i] - b[i]); - } + function kulczynski$1(a, b) { + return 1 / kulczynski(a, b); + } - return ans / ii; + function motyka$1(a, b) { + return 1 - motyka(a, b); } - function harmonicMean(a, b) { - var ii = a.length; - var ans = 0; + function pearson$1(a, b) { + var avgA = mean(a); + var avgB = mean(b); + var newA = new Array(a.length); + var newB = new Array(b.length); - for (var i = 0; i < ii; i++) { - ans += a[i] * b[i] / (a[i] + b[i]); + for (var i = 0; i < newA.length; i++) { + newA[i] = a[i] - avgA; + newB[i] = b[i] - avgB; } - return 2 * ans; + return cosine(newA, newB); } - function hellinger(a, b) { - var ii = a.length; - var ans = 0; - - for (var i = 0; i < ii; i++) { - ans += Math.sqrt(a[i] * b[i]); - } - - return 2 * Math.sqrt(1 - ans); + function squaredChord$1(a, b) { + return 1 - squaredChord(a, b); } - function innerProduct(a, b) { - var ii = a.length; - var ans = 0; + var similarities = /*#__PURE__*/Object.freeze({ + __proto__: null, + tree: index$5, + cosine: cosine, + czekanowski: czekanowskiSimilarity, + dice: dice$1, + intersection: intersection$1, + jaccard: jaccard$1, + kulczynski: kulczynski$1, + motyka: motyka$1, + pearson: pearson$1, + squaredChord: squaredChord$1, + tanimoto: tanimoto + }); - for (var i = 0; i < ii; i++) { - ans += a[i] * b[i]; + var acc = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + + for (var i = 0; i < l; i++) { + result[i] = (pred.tn[i] + pred.tp[i]) / (l - 1); } - return ans; - } + return result; + }; // Error rate - function intersection(a, b) { - var ii = a.length; - var ans = 0; - for (var i = 0; i < ii; i++) { - ans += Math.min(a[i], b[i]); + var err = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + + for (var i = 0; i < l; i++) { + result[i] = pred.fn[i] + pred.fp[i] / (l - 1); } - return 1 - ans; - } + return result; + }; // False positive rate - function jaccard(a, b) { - var ii = a.length; - var p1 = 0; - var p2 = 0; - var q1 = 0; - var 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]); + var fpr = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + + for (var i = 0; i < l; i++) { + result[i] = pred.fp[i] / pred.nNeg; } - return q2 / (p2 + q1 - p1); - } + return result; + }; // True positive rate - function jeffreys(a, b) { - var ii = a.length; - var ans = 0; - for (var i = 0; i < ii; i++) { - ans += (a[i] - b[i]) * Math.log(a[i] / b[i]); + var tpr = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + + for (var i = 0; i < l; i++) { + result[i] = pred.tp[i] / pred.nPos; } - return ans; - } + return result; + }; // False negative rate - function jensenDifference(a, b) { - var ii = a.length; - var 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); + var fnr = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + + for (var i = 0; i < l; i++) { + result[i] = pred.fn[i] / pred.nPos; } - return ans; - } + return result; + }; // True negative rate - function jensenShannon(a, b) { - var ii = a.length; - var p = 0; - var 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])); + var tnr = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + + for (var i = 0; i < l; i++) { + result[i] = pred.tn[i] / pred.nNeg; } - return (p + q) / 2; - } + return result; + }; // Positive predictive value - function kdivergence(a, b) { - var ii = a.length; - var ans = 0; - for (var i = 0; i < ii; i++) { - ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])); + var ppv = 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 ? pred.tp[i] / (pred.fp[i] + pred.tp[i]) : 0; } - return ans; - } + return result; + }; // Negative predictive value - function kulczynski(a, b) { - var ii = a.length; - var up = 0; - var down = 0; - for (var i = 0; i < ii; i++) { - up += Math.abs(a[i] - b[i]); - down += Math.min(a[i], b[i]); + var npv = 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 ? pred.tn[i] / (pred.fn[i] + pred.tn[i]) : 0; } - return up / down; - } + return result; + }; // Prediction conditioned fallout - function kullbackLeibler(a, b) { - var ii = a.length; - var ans = 0; - for (var i = 0; i < ii; i++) { - ans += a[i] * Math.log(a[i] / b[i]); + var 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 ans; - } + return result; + }; // Prediction conditioned miss - function kumarHassebrook(a, b) { - var ii = a.length; - var p = 0; - var p2 = 0; - var q2 = 0; - for (var i = 0; i < ii; i++) { - p += a[i] * b[i]; - p2 += a[i] * a[i]; - q2 += b[i] * b[i]; + var 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 p / (p2 + q2 - p); - } + return result; + }; // Lift value - function kumarJohnson(a, b) { - var ii = a.length; - var 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)); + var lift = pred => { + const l = pred.cutoffs.length; + const 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 ans; - } + return result; + }; // Rate of positive predictions - function lorentzian(a, b) { - var ii = a.length; - var ans = 0; - for (var i = 0; i < ii; i++) { - ans += Math.log(Math.abs(a[i] - b[i]) + 1); + var rpp = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + + for (var i = 0; i < l; i++) { + result[i] = pred.nPosPred[i] / pred.nSamples; } - return ans; - } + return result; + }; // Rate of negative predictions - function manhattan(a, b) { - var i = 0; - var ii = a.length; - var d = 0; - for (; i < ii; i++) { - d += Math.abs(a[i] - b[i]); + var rnp = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + + for (var i = 0; i < l; i++) { + result[i] = pred.nNegPred[i] / pred.nSamples; } - return d; - } + return result; + }; // Threshold - function matusita(a, b) { - var ii = a.length; - var ans = 0; - for (var i = 0; i < ii; i++) { - ans += Math.sqrt(a[i] * b[i]); - } + var threshold = pred => { + const clone = pred.cutoffs.slice(); + clone[0] = clone[1]; // Remove the infinite value - return Math.sqrt(2 - 2 * ans); - } + return clone; + }; - function minkowski(a, b, p) { - var i = 0; - var ii = a.length; - var d = 0; + var measures = { + acc: acc, + err: err, + fpr: fpr, + tpr: tpr, + fnr: fnr, + tnr: tnr, + ppv: ppv, + npv: npv, + pcfall: pcfall, + pcmiss: pcmiss, + lift: lift, + rpp: rpp, + rnp: rnp, + threshold: threshold + }; - for (; i < ii; i++) { - d += Math.pow(Math.abs(a[i] - b[i]), p); - } + 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 || {}; - return Math.pow(d, 1 / p); - } + if (prediction.length !== target.length || prediction[0].length !== target[0].length) { + throw new Error('dimensions of prediction and target do not match'); + } - function motyka(a, b) { - var ii = a.length; - var up = 0; - var down = 0; + const rows = prediction.length; + const columns = prediction[0].length; + const isDistance = !options.max; + const predP = []; - for (var i = 0; i < ii; i++) { - up += Math.min(a[i], b[i]); - down += a[i] + b[i]; - } + 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] + }); + } + } + } - return 1 - up / down; - } + if (isDistance) { + predP.sort((a, b) => a.pred - b.pred); + } else { + predP.sort((a, b) => b.pred - a.pred); + } - function neyman(a, b) { - var i = 0; - var ii = a.length; - var d = 0; + 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; - for (; i < ii; i++) { - d += (a[i] - b[i]) * (a[i] - b[i]) / a[i]; - } + 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; + } - return d; - } + if (predP[i].targ) { + nPos++; + nTp++; + } else { + nNeg++; + nFp++; + } + } - function pearson(a, b) { - var i = 0; - var ii = a.length; - var d = 0; + 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 (; i < ii; i++) { - d += (a[i] - b[i]) * (a[i] - b[i]) / b[i]; + 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]; + } + + 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] + */ - return d; - } - function probabilisticSymmetric(a, b) { - var i = 0; - var ii = a.length; - var d = 0; + getMeasure(measure) { + if (typeof measure !== 'string') { + throw new Error('No measure specified'); + } - for (; i < ii; i++) { - d += (a[i] - b[i]) * (a[i] - b[i]) / (a[i] + b[i]); + if (!measures[measure]) { + throw new Error(`The specified measure (${measure}) does not exist`); + } + + return measures[measure](this); } + /** + * Returns the area under the ROC curve + */ - return 2 * d; - } - function ruzicka(a, b) { - var ii = a.length; - var up = 0; - var down = 0; + getAURC() { + const l = this.cutoffs.length; + const x = new Array(l); + const y = new Array(l); - for (var i = 0; i < ii; i++) { - up += Math.min(a[i], b[i]); - down += Math.max(a[i], b[i]); - } + for (var i = 0; i < l; i++) { + x[i] = this.fp[i] / this.nNeg; + y[i] = this.tp[i] / this.nPos; + } - return up / down; - } + var auc = 0; - function soergel(a, b) { - var ii = a.length; - var up = 0; - var down = 0; + for (i = 1; i < l; i++) { + auc += 0.5 * (x[i] - x[i - 1]) * (y[i] + y[i - 1]); + } - for (var i = 0; i < ii; i++) { - up += Math.abs(a[i] - b[i]); - down += Math.max(a[i], b[i]); + return auc; } + /** + * Returns the area under the DET curve + */ - return up / down; - } - function sorensen(a, b) { - var ii = a.length; - var up = 0; - var down = 0; + getAUDC() { + const l = this.cutoffs.length; + const x = new Array(l); + const y = new Array(l); - for (var i = 0; i < ii; i++) { - up += Math.abs(a[i] - b[i]); - down += a[i] + b[i]; - } + for (var i = 0; i < l; i++) { + x[i] = this.fn[i] / this.nPos; + y[i] = this.fp[i] / this.nNeg; + } - return up / down; - } + var auc = 0; - function squared(a, b) { - var i = 0; - var ii = a.length; - var d = 0; + for (i = 1; i < l; i++) { + auc += 0.5 * (x[i] + x[i - 1]) * (y[i] - y[i - 1]); + } - for (; i < ii; i++) { - d += (a[i] - b[i]) * (a[i] - b[i]) / (a[i] + b[i]); + return auc; } - return d; - } - - function squaredChord(a, b) { - var ii = a.length; - var ans = 0; + 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 - for (var i = 0; i < ii; i++) { - ans += (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i])); - } + 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; - return ans; - } + for (var i = cutLow, j = cutLength - 1; i <= cutHigh; i += interval) { + while (this.cutoffs[j] < i) j--; - function taneja(a, b) { - var ii = a.length; - var ans = 0; + 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); + } - 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 { + xLabels: xLabels, + interValues: interValues, + intraValues: intraValues, + interCumPercent: interCumPercent, + intraCumPercent: intraCumPercent + }; } - return ans; } - function tanimoto(a, b, bitvector) { - if (bitvector) { - var inter = 0; - var union = 0; + 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' + }; + var src$1 = Performance; - for (var j = 0; j < a.length; j++) { - inter += a[j] && b[j]; - union += a[j] || b[j]; - } + var defaultOptions$g = { + size: 1, + value: 0 + }; + /** + * Case when the entry is an array + * @param data + * @param options + * @returns {Array} + */ - if (union === 0) { - return 1; - } + function arrayCase(data, options) { + var len = data.length; + + if (typeof options.size === 'number') { + options.size = [options.size, options.size]; + } - return inter / union; - } else { - var ii = a.length; - var p = 0; - var q = 0; - var m = 0; + var cond = len + options.size[0] + options.size[1]; + var output; - for (var i = 0; i < ii; i++) { - p += a[i]; - q += b[i]; - m += Math.min(a[i], b[i]); + if (options.output) { + if (options.output.length !== cond) { + throw new RangeError('Wrong output size'); } - return 1 - (p + q - 2 * m) / (p + q - m); + output = options.output; + } else { + output = new Array(cond); } - } - function tanimoto$1(a, b, bitvector) { - if (bitvector) { - return 1 - tanimoto(a, b, bitvector); - } else { - var ii = a.length; - var p = 0; - var q = 0; - var m = 0; + var i; - for (var i = 0; i < ii; i++) { - p += a[i]; - q += b[i]; - m += Math.min(a[i], b[i]); + 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]; + } + } + } 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]; + } + } 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'); } - return (p + q - 2 * m) / (p + q - m); + 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]; + } + } 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; + } } + + return output; } + /** + * Case when the entry is a matrix + * @param data + * @param options + * @returns {Array} + */ - function topsoe(a, b) { - var ii = a.length; - var 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])); + 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]; } - return ans; + throw new Error('matrix not supported yet, sorry'); } + /** + * Pads and array + * @param {Array } data + * @param {object} options + */ - function waveHedges(a, b) { - var ii = a.length; - var ans = 0; - for (var i = 0; i < ii; i++) { - ans += 1 - Math.min(a[i], b[i]) / Math.max(a[i], b[i]); - } + function padArray(data, options) { + options = Object.assign({}, defaultOptions$g, options); - return ans; + 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'); + } } + var src$2 = padArray; + /** + * Factorial of a number + * @ignore + * @param n + * @return {number} + */ - var distances = /*#__PURE__*/Object.freeze({ - __proto__: null, - euclidean: euclidean, - squaredEuclidean: squaredEuclidean, - additiveSymmetric: additiveSymmetric, - avg: avg, - bhattacharyya: bhattacharyya, - canberra: canberra, - chebyshev: chebyshev, - clark: clark, - czekanowski: czekanowskiDistance, - dice: dice, - divergence: divergence, - fidelity: fidelity, - gower: gower, - harmonicMean: harmonicMean, - hellinger: hellinger, - innerProduct: innerProduct, - intersection: intersection, - jaccard: jaccard, - jeffreys: jeffreys, - jensenDifference: jensenDifference, - jensenShannon: jensenShannon, - kdivergence: kdivergence, - kulczynski: kulczynski, - kullbackLeibler: kullbackLeibler, - kumarHassebrook: kumarHassebrook, - kumarJohnson: kumarJohnson, - lorentzian: lorentzian, - manhattan: manhattan, - matusita: matusita, - minkowski: minkowski, - motyka: motyka, - neyman: neyman, - pearson: pearson, - probabilisticSymmetric: probabilisticSymmetric, - ruzicka: ruzicka, - soergel: soergel, - sorensen: sorensen, - squared: squared, - squaredChord: squaredChord, - taneja: taneja, - tanimoto: tanimoto$1, - topsoe: topsoe, - waveHedges: waveHedges - }); + function factorial(n) { + let r = 1; + + while (n > 0) r *= n--; + + return r; + } + const defaultOptions$h = { + windowSize: 5, + derivative: 1, + polynomial: 2, + pad: 'none', + padValue: 'replicate' + }; /** - * Function that creates the tree - * @param {Array>} spectrum - * @param {object} [options] - * @return {Tree|null} - * left and right have the same structure than the parent, - * or are null if they are leaves + * Savitzky-Golay filter + * @param {Array } data + * @param {number} h + * @param {Object} options + * @returns {Array} */ - function createTree(spectrum) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var X = spectrum[0]; - const { - minWindow = 0.16, - threshold = 0.01, - from = X[0], - to = X[X.length - 1] - } = options; - return mainCreateTree(spectrum[0], spectrum[1], from, to, minWindow, threshold); - } + function savitzkyGolay(data, h, options) { + options = Object.assign({}, defaultOptions$h, options); - function mainCreateTree(X, Y, from, to, minWindow, threshold) { - if (to - from < minWindow) { - return null; - } // search first point + 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'); + } - var start = binarySearch(X, from, ascending); + if (options.polynomial < 1 || !Number.isInteger(options.polynomial)) { + throw new RangeError('Polynomial should be a positive integer'); + } - if (start < 0) { - start = ~start; - } // stop at last point + let C, norm; + let step = Math.floor(options.windowSize / 2); + if (options.pad === 'pre') { + data = src$2(data, { + size: step, + value: options.padValue + }); + } - var sum = 0; - var center = 0; + let ans = new Array(data.length - 2 * step); - for (var i = start; i < X.length; i++) { - if (X[i] >= to) { - break; + 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 { + let J = Matrix.ones(options.windowSize, options.polynomial + 1); + let inic = -(options.windowSize - 1) / 2; - sum += Y[i]; - center += X[i] * Y[i]; - } + for (let i = 0; i < J.rows; i++) { + for (let j = 0; j < J.columns; j++) { + if (inic + 1 !== 0 || j !== 0) J.set(i, j, Math.pow(inic + i, j)); + } + } - if (sum < threshold) { - return null; + let Jtranspose = new MatrixTransposeView(J); + let Jinv = inverse(Jtranspose.mmul(J)); + C = Jinv.mmul(Jtranspose); + C = C.getRow(options.derivative); + norm = 1 / factorial(options.derivative); } - center /= sum; + let det = norm * Math.pow(h, options.derivative); - if (center - from < 1e-6 || to - center < 1e-6) { - return null; + for (let k = step; k < data.length - step; k++) { + let d = 0; + + for (let l = 0; l < C.length; l++) d += C[l] * data[l + k - step] / det; + + ans[k - step] = d; } - if (center - from < minWindow / 4) { - return mainCreateTree(X, Y, center, to, minWindow, threshold); - } else { - if (to - center < minWindow / 4) { - return mainCreateTree(X, Y, from, center, minWindow, threshold); - } else { - return new Tree(sum, center, mainCreateTree(X, Y, from, center, minWindow, threshold), mainCreateTree(X, Y, center, to, minWindow, threshold)); - } + if (options.pad === 'post') { + ans = src$2(ans, { + size: step, + value: options.padValue + }); } + + return ans; } - class Tree { - constructor(sum, center, left, right) { - this.sum = sum; - this.center = center; - this.left = left; - this.right = right; + // auxiliary file to create the 256 look at table elements + 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; } + var creator = ans; + /** - * Similarity between two nodes - * @param {Tree|Array>} a - tree A node - * @param {Tree|Array>} b - tree B node - * @param {object} [options] - * @return {number} similarity measure between tree nodes + * Count the number of true values in an array + * @param {Array} arr + * @return {number} */ - function getSimilarity(a, b) { - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - const { - alpha = 0.1, - beta = 0.33, - gamma = 0.001 - } = options; - - if (a === null || b === null) { - return 0; - } - if (Array.isArray(a)) { - a = createTree(a); - } + function count(arr) { + var c = 0; - if (Array.isArray(b)) { - b = createTree(b); + for (var i = 0; i < arr.length; i++) { + c += creator[arr[i] & 0xff] + creator[arr[i] >> 8 & 0xff] + creator[arr[i] >> 16 & 0xff] + creator[arr[i] >> 24 & 0xff]; } - 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) * (getSimilarity(a.left, b.left, options) + getSimilarity(a.right, b.right, options)) / 2; + return c; } + /** + * Logical AND operation + * @param {Array} arr1 + * @param {Array} arr2 + * @return {Array} + */ - function treeSimilarity(A, B) { - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - return getSimilarity(A, B, options); - } - function getFunction() { - let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - return (A, B) => getSimilarity(A, B, options); + + 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} + */ - var index$4 = /*#__PURE__*/Object.freeze({ - __proto__: null, - treeSimilarity: treeSimilarity, - getFunction: getFunction, - createTree: createTree - }); - function cosine(a, b) { - var ii = a.length; - var p = 0; - var p2 = 0; - var q2 = 0; + function or(arr1, arr2) { + var ans = new Array(arr1.length); - for (var i = 0; i < ii; i++) { - p += a[i] * b[i]; - p2 += a[i] * a[i]; - q2 += b[i] * b[i]; - } + for (var i = 0; i < arr1.length; i++) ans[i] = arr1[i] | arr2[i]; - return p / (Math.sqrt(p2) * Math.sqrt(q2)); + return ans; } + /** + * Logical XOR operation + * @param {Array} arr1 + * @param {Array} arr2 + * @return {Array} + */ - function dice$1(a, b) { - return 1 - dice(a, b); - } - function intersection$1(a, b) { - return 1 - intersection(a, b); + 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; } + /** + * Logical NOT operation + * @param {Array} arr + * @return {Array} + */ - function jaccard$1(a, b) { - return 1 - jaccard(a, b); + + function not(arr) { + var ans = new Array(arr.length); + + for (var i = 0; i < ans.length; i++) ans[i] = ~arr[i]; + + return ans; } + /** + * Gets the n value of array arr + * @param {Array} arr + * @param {number} n + * @return {boolean} + */ - function kulczynski$1(a, b) { - return 1 / kulczynski(a, b); + + 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); } + /** + * Sets the n value of array arr to the value val + * @param {Array} arr + * @param {number} n + * @param {boolean} val + * @return {Array} + */ - function motyka$1(a, b) { - return 1 - motyka(a, b); + + 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 pearson$1(a, b) { - var avgA = mean(a); - var avgB = 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; + 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; } - return cosine(newA, newB); + return str; } + /** + * Creates an array of numbers based on a string of bits + * @param {string} str + * @returns {Array} + */ - function squaredChord$1(a, b) { - return 1 - squaredChord(a, b); - } + 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; + } - var similarities = /*#__PURE__*/Object.freeze({ - __proto__: null, - tree: index$4, - cosine: cosine, - czekanowski: czekanowskiSimilarity, - dice: dice$1, - intersection: intersection$1, - jaccard: jaccard$1, - kulczynski: kulczynski$1, - motyka: motyka$1, - pearson: pearson$1, - squaredChord: squaredChord$1, - tanimoto: tanimoto - }); + return ans; + } + /** + * Translates an array of numbers to a hex string + * @param {Array} arr + * @returns {string} + */ - var acc = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = (pred.tn[i] + pred.tp[i]) / (l - 1); + 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 result; - }; // Error rate + return str; + } + /** + * Creates an array of numbers based on a hex string + * @param {string} str + * @returns {Array} + */ - var err = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); + function parseHexString(str) { + var len = str.length / 8; + var ans = new Array(len); - for (var i = 0; i < l; i++) { - result[i] = pred.fn[i] + pred.fp[i] / (l - 1); + for (var i = 0; i < len; i++) { + ans[i] = parseInt(str.substr(i * 8, 8), 16) | 0; } - return result; - }; // False positive rate + return ans; + } + /** + * Creates a human readable string of the array + * @param {Array} arr + * @returns {string} + */ - var fpr = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); + 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 i = 0; i < l; i++) { - result[i] = pred.fp[i] / pred.nNeg; + for (var j = 0; j < 32; j += 4) { + str += ' ' + binary.substr(i * 32 + j, 4); + } + + if (i < arr.length - 1) str += '\n'; } - return result; - }; // True positive rate + return str; + } + var src$3 = { + count: count, + and: and, + or: or, + xor: xor, + not: not, + getBit: getBit, + setBit: setBit, + toBinaryString: toBinaryString, + parseBinaryString: parseBinaryString, + toHexString: toHexString, + parseHexString: parseHexString, + toDebug: toDebug + }; - var tpr = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); + function SavitzkyGolay(data, h, options = {}) { + let { + windowSize = 9, + derivative = 0, + polynomial = 3 + } = options; - for (var i = 0; i < l; i++) { - result[i] = pred.tp[i] / pred.nPos; + if (windowSize % 2 === 0 || windowSize < 5 || !Number.isInteger(windowSize)) { + throw new RangeError('Invalid window size (should be odd and at least 5 integer number)'); } - return result; - }; // False negative rate - + if (windowSize > data.length) { + throw new RangeError(`Window size is higher than the data length ${windowSize}>${data.length}`); + } - var fnr = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); + if (derivative < 0 || !Number.isInteger(derivative)) { + throw new RangeError('Derivative should be a positive integer'); + } - for (var i = 0; i < l; i++) { - result[i] = pred.fn[i] / pred.nPos; + if (polynomial < 1 || !Number.isInteger(polynomial)) { + throw new RangeError('Polynomial should be a positive integer'); } - return result; - }; // True negative rate + if (polynomial >= 6) { + // eslint-disable-next-line no-console + 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'); + } + let half = Math.floor(windowSize / 2); + let np = data.length; + let ans = new Array(np); + let weights = fullWeights(windowSize, polynomial, derivative); + let hs = 0; + let constantH = true; - var tnr = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); + if (Array.isArray(h)) { + constantH = false; + } else { + hs = Math.pow(h, derivative); + } //For the borders - for (var i = 0; i < l; i++) { - result[i] = pred.tn[i] / pred.nNeg; - } - return result; - }; // Positive predictive value + for (let i = 0; i < half; i++) { + let wg1 = weights[half - i - 1]; + let wg2 = weights[half + i + 1]; + let d1 = 0; + let d2 = 0; + for (let l = 0; l < windowSize; l++) { + d1 += wg1[l] * data[l]; + d2 += wg2[l] * data[np - windowSize + l]; + } - var ppv = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); + if (constantH) { + ans[half - i - 1] = d1 / hs; + ans[np - half + i] = d2 / hs; + } else { + hs = getHs(h, half - i - 1, half, derivative); + ans[half - i - 1] = d1 / hs; + hs = getHs(h, np - half + i, half, derivative); + ans[np - half + i] = d2 / hs; + } + } //For the internal points - 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; - }; // Negative predictive value + let wg = weights[half]; + for (let i = windowSize; i <= np; i++) { + let d = 0; - var npv = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); + for (let l = 0; l < windowSize; l++) d += wg[l] * data[l + i - windowSize]; - 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; + if (!constantH) hs = getHs(h, i - half - 1, half, derivative); + ans[i - half - 1] = d / hs; } - return result; - }; // Prediction conditioned fallout - + return ans; + } - var pcfall = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); + function getHs(h, center, half, derivative) { + let hs = 0; + let count = 0; - 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; + for (let i = center - half; i < center + half; i++) { + if (i >= 0 && i < h.length - 1) { + hs += h[i + 1] - h[i]; + count++; + } } - return result; - }; // Prediction conditioned miss - + return Math.pow(hs / count, derivative); + } - var pcmiss = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); + function GramPoly(i, m, k, s) { + let Grampoly = 0; - 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; + 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; + } } - return result; - }; // Lift value - + return Grampoly; + } - var lift = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); + function GenFact(a, b) { + let gf = 1; - for (var i = 0; i < l; i++) { - result[i] = pred.nPosPred[i] !== 0 ? pred.tp[i] / pred.nPos / (pred.nPosPred[i] / pred.nSamples) : 0; + if (a >= b) { + for (let j = a - b + 1; j <= a; j++) { + gf *= j; + } } - return result; - }; // Rate of positive predictions - + return gf; + } - var rpp = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); + function Weight(i, t, m, n, s) { + let sum = 0; - for (var i = 0; i < l; i++) { - result[i] = pred.nPosPred[i] / pred.nSamples; + for (let 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 result; - }; // Rate of negative predictions + return sum; + } + /** + * + * @param m Number of points + * @param n Polynomial grade + * @param s Derivative + */ - var rnp = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); + function fullWeights(m, n, s) { + let weights = new Array(m); + let np = Math.floor(m / 2); - for (var i = 0; i < l; i++) { - result[i] = pred.nNegPred[i] / pred.nSamples; - } + for (let t = -np; t <= np; t++) { + weights[t + np] = new Array(m); - return result; - }; // Threshold + for (let 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 { - const clone = pred.cutoffs.slice(); - clone[0] = clone[1]; // Remove the infinite value + sum/=data.length; + console.log(sum+" "+max); + console.log(stat.array.standardDeviation(copy)); + console.log(Math.abs(stat.array.mean(copy))/stat.array.standardDeviation(copy)); + return sum; - return clone; - }; + } - var measures = { - acc: acc, - err: err, - fpr: fpr, - tpr: tpr, - fnr: fnr, - tnr: tnr, - ppv: ppv, - npv: npv, - pcfall: pcfall, - pcmiss: pcmiss, - lift: lift, - rpp: rpp, - rnp: rnp, - threshold: threshold - }; - 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'); - } + function guessWindowSize(data, h){ + console.log("entropy "+entropy(data,h,trendOptions)); + return 5; + } + */ - const rows = prediction.length; - const columns = prediction[0].length; - const isDistance = !options.max; - const predP = []; + /** + * Global spectra deconvolution + * @param {Array} x - Independent variable + * @param {Array} yIn - Dependent variable + * @param {object} [options] - Options object + * @param {object} [options.sgOptions] - Options object for Savitzky-Golay filter. See https://github.com/mljs/savitzky-golay-generalized#options + * @param {number} [options.sgOptions.windowSize = 9] - points to use in the approximations + * @param {number} [options.sgOptions.polynomial = 3] - degree of the polynomial to use in the approximations + * @param {number} [options.minMaxRatio = 0.00025] - Threshold to determine if a given peak should be considered as a noise + * @param {number} [options.broadRatio = 0.00] - If `broadRatio` is higher than 0, then all the peaks which second derivative + * smaller than `broadRatio * maxAbsSecondDerivative` will be marked with the soft mask equal to true. + * @param {number} [options.noiseLevel = 0] - Noise threshold in spectrum units + * @param {boolean} [options.maxCriteria = true] - Peaks are local maximum(true) or minimum(false) + * @param {boolean} [options.smoothY = true] - Select the peak intensities from a smoothed version of the independent variables + * @param {boolean} [options.realTopDetection = false] - Use a quadratic optimizations with the peak and its 3 closest neighbors + * to determine the true x,y values of the peak? + * @param {number} [options.heightFactor = 0] - Factor to multiply the calculated height (usually 2) + * @param {number} [options.derivativeThreshold = -1] - Filters based on the amplitude of the first derivative + * @return {Array} + */ - 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'); - } + function gsd(x, yIn, options = {}) { + let { + noiseLevel, + sgOptions = { + windowSize: 9, + polynomial: 3 + }, + smoothY = true, + heightFactor = 0, + broadRatio = 0.0, + maxCriteria = true, + minMaxRatio = 0.00025, + derivativeThreshold = -1, + realTopDetection = false + } = options; + const y = yIn.slice(); + let equalSpaced = isEqualSpaced(x); - 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] - }); - } - } - } + if (noiseLevel === undefined) { + noiseLevel = equalSpaced ? getNoiseLevel(y) : 0; + } - if (isDistance) { - predP.sort((a, b) => a.pred - b.pred); - } else { - predP.sort((a, b) => b.pred - a.pred); - } + const yCorrection = { + m: 1, + b: noiseLevel + }; - 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 (!maxCriteria) { + yCorrection.m = -1; + yCorrection.b *= -1; + } - 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; - } + for (let i = 0; i < y.length; i++) { + y[i] = yCorrection.m * y[i] - yCorrection.b; + } - if (predP[i].targ) { - nPos++; - nTp++; - } else { - nNeg++; - nFp++; - } + for (let i = 0; i < y.length; i++) { + if (y[i] < 0) { + y[i] = 0; } + } // If the max difference between delta x is less than 5%, then, + // we can assume it to be equally spaced variable - 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]; + let yData = y; + let dY, ddY; + const { + windowSize, + polynomial + } = sgOptions; + + if (equalSpaced) { + if (smoothY) { + yData = SavitzkyGolay(y, x[1] - x[0], { + windowSize, + polynomial, + derivative: 0 + }); } - this.nPos = nPos; - this.nNeg = nNeg; - this.nSamples = nPos + nNeg; + dY = SavitzkyGolay(y, x[1] - x[0], { + windowSize, + polynomial, + derivative: 1 + }); + ddY = SavitzkyGolay(y, x[1] - x[0], { + windowSize, + polynomial, + derivative: 2 + }); + } else { + if (smoothY) { + yData = SavitzkyGolay(y, x, { + windowSize, + polynomial, + derivative: 0 + }); + } + + dY = SavitzkyGolay(y, x, { + windowSize, + polynomial, + derivative: 1 + }); + ddY = SavitzkyGolay(y, x, { + windowSize, + polynomial, + derivative: 2 + }); } - /** - * 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] - */ + const xData = x; + const dX = x[1] - x[0]; + let maxDdy = 0; + let maxY = 0; - getMeasure(measure) { - if (typeof measure !== 'string') { - throw new Error('No measure specified'); + for (let i = 0; i < yData.length; i++) { + if (Math.abs(ddY[i]) > maxDdy) { + maxDdy = Math.abs(ddY[i]); } - if (!measures[measure]) { - throw new Error("The specified measure (".concat(measure, ") does not exist")); + if (Math.abs(yData[i]) > maxY) { + maxY = Math.abs(yData[i]); } - - return measures[measure](this); } - /** - * Returns the area under the ROC curve - */ + let lastMax = null; + let lastMin = null; + let minddY = new Array(yData.length - 2); + let intervalL = new Array(yData.length); + let intervalR = new Array(yData.length); + let broadMask = new Array(yData.length - 2); + let minddYLen = 0; + let intervalLLen = 0; + let intervalRLen = 0; + let broadMaskLen = 0; // By the intermediate value theorem We cannot find 2 consecutive maximum or minimum - getAURC() { - const l = this.cutoffs.length; - const x = new Array(l); - const y = new Array(l); + for (let i = 1; i < yData.length - 1; ++i) { + // filter based on derivativeThreshold + // console.log('pasa', y[i], dY[i], ddY[i]); + if (Math.abs(dY[i]) > derivativeThreshold) { + // Minimum in first derivative + if (dY[i] < dY[i - 1] && dY[i] <= dY[i + 1] || dY[i] <= dY[i - 1] && dY[i] < dY[i + 1]) { + lastMin = { + x: xData[i], + index: i + }; - for (var i = 0; i < l; i++) { - x[i] = this.fp[i] / this.nNeg; - y[i] = this.tp[i] / this.nPos; - } + if (dX > 0 && lastMax !== null) { + intervalL[intervalLLen++] = lastMax; + intervalR[intervalRLen++] = lastMin; + } + } // Maximum in first derivative - var auc = 0; - for (i = 1; i < l; i++) { - auc += 0.5 * (x[i] - x[i - 1]) * (y[i] + y[i - 1]); - } + if (dY[i] >= dY[i - 1] && dY[i] > dY[i + 1] || dY[i] > dY[i - 1] && dY[i] >= dY[i + 1]) { + lastMax = { + x: xData[i], + index: i + }; - return auc; - } - /** - * Returns the area under the DET curve - */ + if (dX < 0 && lastMin !== null) { + intervalL[intervalLLen++] = lastMax; + intervalR[intervalRLen++] = lastMin; + } + } + } // Minimum in second derivative - getAUDC() { - const l = this.cutoffs.length; - const x = new Array(l); - const y = new Array(l); + if (ddY[i] < ddY[i - 1] && ddY[i] < ddY[i + 1]) { + // TODO should we change this to have 3 arrays ? Huge overhead creating arrays + minddY[minddYLen++] = i; // ( [xData[i], yData[i], i] ); - for (var i = 0; i < l; i++) { - x[i] = this.fn[i] / this.nPos; - y[i] = this.fp[i] / this.nNeg; + broadMask[broadMaskLen++] = Math.abs(ddY[i]) <= broadRatio * maxDdy; } + } - var auc = 0; + minddY.length = minddYLen; + intervalL.length = intervalLLen; + intervalR.length = intervalRLen; + broadMask.length = broadMaskLen; + let signals = new Array(minddY.length); + let signalsLen = 0; + let lastK = -1; + let possible, frequency, distanceJ, minDistance, gettingCloser; - for (i = 1; i < l; i++) { - auc += 0.5 * (x[i] + x[i - 1]) * (y[i] - y[i - 1]); - } + for (let j = 0; j < minddY.length; ++j) { + frequency = xData[minddY[j]]; + possible = -1; + let k = lastK + 1; + minDistance = Number.MAX_VALUE; + distanceJ = 0; + gettingCloser = true; - return auc; - } + while (possible === -1 && k < intervalL.length && gettingCloser) { + distanceJ = Math.abs(frequency - (intervalL[k].x + intervalR[k].x) / 2); // Still getting closer? - 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 + if (distanceJ < minDistance) { + minDistance = distanceJ; + } else { + gettingCloser = false; + } - 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; + if (distanceJ < Math.abs(intervalL[k].x - intervalR[k].x) / 2) { + possible = k; + lastK = k; + } - for (var i = cutLow, j = cutLength - 1; i <= cutHigh; i += interval) { - while (this.cutoffs[j] < i) j--; + ++k; + } - 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); + if (possible !== -1) { + if (Math.abs(yData[minddY[j]]) > minMaxRatio * maxY) { + signals[signalsLen++] = { + index: minddY[j], + x: frequency, + y: (yData[minddY[j]] + yCorrection.b) / yCorrection.m, + width: Math.abs(intervalR[possible].x - intervalL[possible].x), + // widthCorrection + soft: broadMask[j] + }; + signals[signalsLen - 1].left = intervalL[possible]; + signals[signalsLen - 1].right = intervalR[possible]; + + if (heightFactor) { + let yLeft = yData[intervalL[possible].index]; + let yRight = yData[intervalR[possible].index]; + signals[signalsLen - 1].height = heightFactor * (signals[signalsLen - 1].y - (yLeft + yRight) / 2); + } + } } + } - return { - xLabels: xLabels, - interValues: interValues, - intraValues: intraValues, - interCumPercent: interCumPercent, - intraCumPercent: intraCumPercent - }; + signals.length = signalsLen; + + if (realTopDetection) { + determineRealTop(signals, xData, yData); + } // Correct the values to fit the original spectra data + + + for (let j = 0; j < signals.length; j++) { + signals[j].base = noiseLevel; } + signals.sort(function (a, b) { + return a.x - b.x; + }); + return signals; } - 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' - }; - var src$5 = Performance; + const isEqualSpaced = x => { + let tmp; + let maxDx = 0; + let minDx = Number.MAX_SAFE_INTEGER; - var defaultOptions$h = { - size: 1, - value: 0 + for (let i = 0; i < x.length - 1; ++i) { + tmp = Math.abs(x[i + 1] - x[i]); + + if (tmp < minDx) { + minDx = tmp; + } + + if (tmp > maxDx) { + maxDx = tmp; + } + } + + return (maxDx - minDx) / maxDx < 0.05; }; - /** - * Case when the entry is an array - * @param data - * @param options - * @returns {Array} - */ - function arrayCase(data, options) { - var len = data.length; + const getNoiseLevel = y => { + let mean = 0; + let stddev = 0; + let length = y.length; - if (typeof options.size === 'number') { - options.size = [options.size, options.size]; + for (let i = 0; i < length; ++i) { + mean += y[i]; } - var cond = len + options.size[0] + options.size[1]; - var output; + mean /= length; + let averageDeviations = new Array(length); - if (options.output) { - if (options.output.length !== cond) { - throw new RangeError('Wrong output size'); - } + for (let i = 0; i < length; ++i) { + averageDeviations[i] = Math.abs(y[i] - mean); + } - output = options.output; + averageDeviations.sort((a, b) => a - b); + + if (length % 2 === 1) { + stddev = averageDeviations[(length - 1) / 2] / 0.6745; } else { - output = new Array(cond); + stddev = 0.5 * (averageDeviations[length / 2] + averageDeviations[length / 2 - 1]) / 0.6745; } - var i; + return stddev; + }; - 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]]; + const determineRealTop = (peakList, x, y) => { + let alpha, beta, gamma, p, currentPoint; + + for (let j = 0; j < peakList.length; j++) { + currentPoint = peakList[j].index; // peakList[j][2]; + // The detected peak could be moved 1 or 2 units to left or right. + + if (y[currentPoint - 1] >= y[currentPoint - 2] && y[currentPoint - 1] >= y[currentPoint]) { + currentPoint--; + } else { + if (y[currentPoint + 1] >= y[currentPoint] && y[currentPoint + 1] >= y[currentPoint + 2]) { + currentPoint++; } else { - output[i] = data[(i - options.size[0]) % len]; + if (y[currentPoint - 2] >= y[currentPoint - 3] && y[currentPoint - 2] >= y[currentPoint - 1]) { + currentPoint -= 2; + } else { + if (y[currentPoint + 2] >= y[currentPoint + 1] && y[currentPoint + 2] >= y[currentPoint + 3]) { + currentPoint += 2; + } + } } - } - } 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]; - } - } 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'); - } + } // interpolation to a sin() function - 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]; - } - } 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; + + if (y[currentPoint - 1] > 0 && y[currentPoint + 1] > 0 && y[currentPoint] >= y[currentPoint - 1] && y[currentPoint] >= y[currentPoint + 1] && (y[currentPoint] !== y[currentPoint - 1] || y[currentPoint] !== y[currentPoint + 1])) { + alpha = 20 * Math.log10(y[currentPoint - 1]); + beta = 20 * Math.log10(y[currentPoint]); + gamma = 20 * Math.log10(y[currentPoint + 1]); + p = 0.5 * (alpha - gamma) / (alpha - 2 * beta + gamma); // console.log(alpha, beta, gamma, `p: ${p}`); + // console.log(x[currentPoint]+" "+tmp+" "+currentPoint); + + peakList[j].x = x[currentPoint] + (x[currentPoint] - x[currentPoint - 1]) * p; + peakList[j].y = y[currentPoint] - 0.25 * (y[currentPoint - 1] - y[currentPoint + 1]) * p; } } + }; - return output; + /** + * This function calculates the spectrum as a sum of gaussian functions. The Gaussian + * parameters are divided in 3 batches. 1st: centers; 2nd: height; 3th: std's; + * @param t Ordinate values + * @param p Gaussian parameters + * @param c Constant parameters(Not used) + * @returns {*} + */ + function sumOfGaussians(p) { + return function (t) { + let nL = p.length / 3; + let factor; + let rows = t.length; + let result = rows === undefined ? 0 : new Float64Array(rows).fill(0); + + for (let i = 0; i < nL; i++) { + factor = Math.pow(p[i + nL * 2], 2) * 2; + + if (rows === undefined) { + result += p[i + nL] * Math.exp(-Math.pow(t - p[i], 2) / factor); + } else { + for (let j = 0; j < rows; j++) { + result[j] += p[i + nL] * Math.exp(-Math.pow(t[j] - p[i], 2) / factor); + } + } + } + + return result; + }; } + /** - * Case when the entry is a matrix - * @param data - * @param options - * @returns {Array} + * + * @param xy A two column matrix containing the x and y data to be fitted + * @param group A set of initial lorentzian parameters to be optimized [center, heigth, half_width_at_half_height] + * @returns {Array} A set of final lorentzian parameters [center, heigth, hwhh*2] */ + function optimizeGaussianSum(xy, group, opts = {}) { + let t = xy[0]; + let yData = xy[1]; + let maxY = Math.max(...yData); + yData.forEach((x, i, arr) => arr[i] /= maxY); + let nL = group.length; + let pInit = new Float64Array(nL * 3); + let pMin = new Float64Array(nL * 3); + let pMax = new Float64Array(nL * 3); + let dt = Math.abs(t[0] - t[1]); + + for (let i = 0; i < nL; i++) { + pInit[i] = group[i].x; + pInit[i + nL] = group[i].y / maxY; + pInit[i + 2 * nL] = group[i].width; + pMin[i] = group[i].x - dt; + pMin[i + nL] = 0; + pMin[i + 2 * nL] = group[i].width / 4; + pMax[i] = group[i].x + dt; + pMax[i + nL] = group[i].y * 1.2 / maxY; + pMax[i + 2 * nL] = group[i].width * 4; + } + + let data = { + x: t, + y: yData + }; + let result = new Array(nL); + let lmOptions = { + damping: 1.5, + initialValues: pInit, + minValues: pMin, + maxValues: pMax, + gradientDifference: dt / 10000, + maxIterations: 100, + errorTolerance: 10e-5 + }; + opts = Object.assign({}, lmOptions, opts); + let pFit = levenbergMarquardt(data, sumOfGaussians, opts); - 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]; + for (let i = 0; i < nL; i++) { + result[i] = { + parameters: [pFit.parameterValues[i], pFit.parameterValues[i + nL] * maxY, pFit.parameterValues[i + nL * 2]], + error: pFit.parameterError + }; } - throw new Error('matrix not supported yet, sorry'); + return result; } + /** - * Pads and array - * @param {Array } data - * @param {object} options + * Single 3 parameter gaussian function + * @param t Ordinate values + * @param p Gaussian parameters [mean, height, std] + * @param c Constant parameters(Not used) + * @returns {*} */ + function singleGaussian(p) { + return function (t) { + let factor2 = p[2] * p[2] / 2; + let rows = t.length; + if (!rows) return p[1] * Math.exp(-(t - p[0]) * (t - p[0]) / factor2); + let result = new Float64Array(t.length); + for (let i = 0; i < t.length; i++) { + result[i] = p[1] * Math.exp(-(t[i] - p[0]) * (t[i] - p[0]) / factor2); + } - function padArray(data, options) { - options = Object.assign({}, defaultOptions$h, 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'); - } + return result; + }; } - var src$6 = padArray; + /** + * Fits a set of points to a gaussian bell. Returns the mean of the peak, the std and the height of the signal. + * @param data,[y] + * @returns {*[]} + */ + + function optimizeSingleGaussian(xy, peak, opts = {}) { + let t = xy[0]; + let yData = xy[1]; + let maxY = Math.max(...yData); + yData.forEach((x, i, arr) => arr[i] /= maxY); + let dt = Math.abs(t[0] - t[1]); + let pInit = new Float64Array([peak.x, 1, peak.width]); + let pMin = new Float64Array([peak.x - dt, 0, peak.width / 4]); + let pMax = new Float64Array([peak.x + dt, 1.25, peak.width * 4]); + let data = { + x: t, + y: yData + }; + let lmOptions = { + damping: 1.5, + initialValues: pInit, + minValues: pMin, + maxValues: pMax, + gradientDifference: dt / 10000, + maxIterations: 100, + errorTolerance: 10e-5 + }; + opts = Object.assign({}, lmOptions, opts); + let pFit = levenbergMarquardt(data, singleGaussian, opts); + return { + parameters: [pFit.parameterValues[0], pFit.parameterValues[1] * maxY, pFit.parameterValues[2]], + error: pFit.parameterError + }; + } + + /** + * This function calculates the spectrum as a sum of lorentzian functions. The Lorentzian + * parameters are divided in 3 batches. 1st: centers; 2nd: heights; 3th: widths; + * @param t Ordinate values + * @param p Lorentzian parameters + * @returns {*} + */ + function sumOfLorentzians(p) { + return function (t) { + let nL = p.length / 3; + let factor; + let p2; + let rows = t.length; + let result = rows === undefined ? 0 : new Float64Array(rows).fill(0); + + for (let i = 0; i < nL; i++) { + p2 = Math.pow(p[i + nL * 2] / 2, 2); + factor = p[i + nL] * p2; + + if (rows === undefined) { + result += factor / (Math.pow(t - p[i], 2) + p2); + } else { + for (let j = 0; j < rows; j++) { + result[j] += factor / (Math.pow(t[j] - p[i], 2) + p2); + } + } + } + + return result; + }; + } - const defaultOptions$i = { - windowSize: 5, - derivative: 1, - polynomial: 2, - pad: 'none', - padValue: 'replicate' - }; /** - * Savitzky-Golay filter - * @param {Array } data - * @param {number} h - * @param {Object} options - * @returns {Array} + * + * @param xy A two column matrix containing the x and y data to be fitted + * @param group A set of initial lorentzian parameters to be optimized [center, heigth, half_width_at_half_height] + * @returns {Array} A set of final lorentzian parameters [center, heigth, hwhh*2] */ - function savitzkyGolay(data, h, options) { - options = Object.assign({}, defaultOptions$i, options); + function optimizeLorentzianSum(xy, group, opts = {}) { + let t = xy[0]; + let yData = xy[1]; + let maxY = Math.max(...yData); + yData.forEach((x, i, arr) => arr[i] /= maxY); + let nL = group.length; + let pInit = new Float64Array(nL * 3); + let pMin = new Float64Array(nL * 3); + let pMax = new Float64Array(nL * 3); + let dt = Math.abs(t[0] - t[1]); + + for (let i = 0; i < nL; i++) { + pInit[i] = group[i].x; + pInit[i + nL] = 1; + pInit[i + 2 * nL] = group[i].width; + pMin[i] = group[i].x - dt; + pMin[i + nL] = 0; + pMin[i + 2 * nL] = group[i].width / 4; + pMax[i] = group[i].x + dt; + pMax[i + nL] = 1.5; + pMax[i + 2 * nL] = group[i].width * 4; + } + + let data = { + x: t, + y: yData + }; + let result = new Array(nL); + let lmOptions = { + damping: 1.5, + initialValues: pInit, + minValues: pMin, + maxValues: pMax, + gradientDifference: dt / 10000, + maxIterations: 100, + errorTolerance: 10e-5 + }; + opts = Object.assign({}, lmOptions, opts); + let pFit = levenbergMarquardt(data, sumOfLorentzians, opts); - 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)'); + for (let i = 0; i < nL; i++) { + result[i] = { + parameters: [pFit.parameterValues[i], pFit.parameterValues[i + nL] * maxY, pFit.parameterValues[i + nL * 2]], + error: pFit.parameterError + }; } - if (options.derivative < 0 || !Number.isInteger(options.derivative)) { - throw new RangeError('Derivative should be a positive integer'); - } + return result; + } - if (options.polynomial < 1 || !Number.isInteger(options.polynomial)) { - throw new RangeError('Polynomial should be a positive integer'); - } + /** + * Single 4 parameter lorentzian function + * @param t Ordinate values + * @param p Lorentzian parameters + * @param c Constant parameters(Not used) + * @returns {*} + */ + function singleLorentzian(p) { + return function (t) { + let factor = p[1] * Math.pow(p[2] / 2, 2); + let rows = t.length; + if (!rows) return factor / (Math.pow(t - p[0], 2) + Math.pow(p[2] / 2, 2)); + let result = new Float64Array(rows); - let C, norm; - let step = Math.floor(options.windowSize / 2); + for (let i = 0; i < rows; i++) { + result[i] = factor / (Math.pow(t[i] - p[0], 2) + Math.pow(p[2] / 2, 2)); + } - if (options.pad === 'pre') { - data = src$6(data, { - size: step, - value: options.padValue - }); - } + return result; + }; + } - let ans = new Array(data.length - 2 * step); + /** + * * Fits a set of points to a Lorentzian function. Returns the center of the peak, the width at half height, and the height of the signal. + * @param data,[y] + * @returns {*[]} + */ - 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 { - let J = Matrix.ones(options.windowSize, options.polynomial + 1); - let inic = -(options.windowSize - 1) / 2; + function optimizeSingleLorentzian(xy, peak, opts = {}) { + let t = xy[0]; + let yData = xy[1]; + let maxY = Math.max(...yData); + yData.forEach((x, i, arr) => arr[i] /= maxY); + let dt = Math.abs(t[0] - t[1]); + let pInit = new Float64Array([peak.x, 1, peak.width]); + let pMin = new Float64Array([peak.x - dt, 0.75, peak.width / 4]); + let pMax = new Float64Array([peak.x + dt, 1.25, peak.width * 4]); + let data = { + x: t, + y: yData + }; + let lmOptions = { + damping: 1.5, + initialValues: pInit, + minValues: pMin, + maxValues: pMax, + gradientDifference: dt / 10000, + maxIterations: 100, + errorTolerance: 10e-5 + }; + opts = Object.assign({}, lmOptions, opts); + let pFit = levenbergMarquardt(data, singleLorentzian, opts); + return { + parameters: [pFit.parameterValues[0], pFit.parameterValues[1] * maxY, pFit.parameterValues[2]], + error: pFit.parameterError + }; + } - for (let i = 0; i < J.rows; i++) { - for (let j = 0; j < J.columns; j++) { - if (inic + 1 !== 0 || j !== 0) J.set(i, j, Math.pow(inic + i, j)); - } + function optimizePeaks(peakList, x, y, options = {}) { + const { + functionName = 'gaussian', + factorWidth = 4, + optimizationOptions = { + damping: 1.5, + maxIterations: 100, + errorTolerance: 10e-5 } + } = options; + let lastIndex = [0]; + let groups = groupPeaks(peakList, factorWidth); + let result = []; + let factor = 1; - let Jtranspose = new MatrixTransposeView(J); - let Jinv = inverse(Jtranspose.mmul(J)); - C = Jinv.mmul(Jtranspose); - C = C.getRow(options.derivative); - norm = 1; - } + if (functionName === 'gaussian') { + factor = 1.17741; + } // From https://en.wikipedia.org/wiki/Gaussian_function#Properties - let det = norm * Math.pow(h, options.derivative); - for (let k = step; k < data.length - step; k++) { - let d = 0; + let sampling; - for (let l = 0; l < C.length; l++) d += C[l] * data[l + k - step] / det; + for (let i = 0; i < groups.length; i++) { + let peaks = groups[i].group; - ans[k - step] = d; - } + if (peaks.length > 1) { + // Multiple peaks + sampling = sampleFunction(groups[i].limits[0] - groups[i].limits[1], groups[i].limits[0] + groups[i].limits[1], x, y, lastIndex); - if (options.pad === 'post') { - ans = src$6(ans, { - size: step, - value: options.padValue - }); - } + if (sampling[0].length > 5) { + let optPeaks = []; - return ans; - } + if (functionName === 'gaussian') { + optPeaks = optimizeGaussianSum(sampling, peaks, optimizationOptions); + } else { + if (functionName === 'lorentzian') { + optPeaks = optimizeLorentzianSum(sampling, peaks, optimizationOptions); + } + } - // auxiliary file to create the 256 look at table elements - var ans = new Array(256); + for (let j = 0; j < optPeaks.length; j++) { + let { + parameters + } = optPeaks[j]; + result.push({ + x: parameters[0], + y: parameters[1], + width: parameters[2] * factor, + index: peaks[j].index + }); + } + } + } else { + // Single peak + peaks = peaks[0]; + sampling = sampleFunction(peaks.x - factorWidth * peaks.width, peaks.x + factorWidth * peaks.width, x, y, lastIndex); - for (var i = 0; i < 256; i++) { - var num = i; - var c = 0; + if (sampling[0].length > 5) { + let fitResult = []; - while (num) { - num = num & num - 1; - c++; + if (functionName === 'gaussian') { + fitResult = optimizeSingleGaussian([sampling[0], sampling[1]], peaks, optimizationOptions); + } else { + if (functionName === 'lorentzian') { + fitResult = optimizeSingleLorentzian([sampling[0], sampling[1]], peaks, optimizationOptions); + } + } + + let { + parameters + } = fitResult; + result.push({ + x: parameters[0], + y: parameters[1], + width: parameters[2] * factor, + index: peaks.index + }); // From https://en.wikipedia.org/wiki/Gaussian_function#Properties} + } + } } - ans[i] = c; + return result; } - var creator = ans; - - /** - * Count the number of true values in an array - * @param {Array} arr - * @return {number} - */ + function sampleFunction(from, to, x, y, lastIndex) { + let nbPoints = x.length; + let sampleX = []; + let sampleY = []; + let direction = Math.sign(x[1] - x[0]); // Direction of the derivative + if (direction === -1) { + lastIndex[0] = x.length - 1; + } - function count(arr) { - var c = 0; + let delta = Math.abs(to - from) / 2; + let mid = (from + to) / 2; + let stop = false; + let index = lastIndex[0]; - for (var i = 0; i < arr.length; i++) { - c += creator[arr[i] & 0xff] + creator[arr[i] >> 8 & 0xff] + creator[arr[i] >> 16 & 0xff] + creator[arr[i] >> 24 & 0xff]; + while (!stop && index < nbPoints && index >= 0) { + if (Math.abs(x[index] - mid) <= delta) { + sampleX.push(x[index]); + sampleY.push(y[index]); + index += direction; + } else { + // It is outside the range. + if (Math.sign(mid - x[index]) === 1) { + // We'll reach the mid going in the current direction + index += direction; + } else { + // There is not more peaks in the current range + stop = true; + } + } } - return c; + lastIndex[0] = index; + return [sampleX, sampleY]; } - /** - * Logical AND operation - * @param {Array} arr1 - * @param {Array} arr2 - * @return {Array} - */ + function groupPeaks(peakList, nL) { + let group = []; + let groups = []; + let limits = [peakList[0].x, nL * peakList[0].width]; + let upperLimit, lowerLimit; // Merge forward - function and(arr1, arr2) { - var ans = new Array(arr1.length); + for (let i = 0; i < peakList.length; i++) { + // If the 2 things overlaps + if (Math.abs(peakList[i].x - limits[0]) < nL * peakList[i].width + limits[1]) { + // Add the peak to the group + group.push(peakList[i]); // Update the group limits - for (var i = 0; i < arr1.length; i++) ans[i] = arr1[i] & arr2[i]; + upperLimit = limits[0] + limits[1]; - return ans; - } - /** - * Logical OR operation - * @param {Array} arr1 - * @param {Array} arr2 - * @return {Array} - */ + if (peakList[i].x + nL * peakList[i].width > upperLimit) { + upperLimit = peakList[i].x + nL * peakList[i].width; + } + lowerLimit = limits[0] - limits[1]; - function or(arr1, arr2) { - var ans = new Array(arr1.length); + if (peakList[i].x - nL * peakList[i].width < lowerLimit) { + lowerLimit = peakList[i].x - nL * peakList[i].width; + } - for (var i = 0; i < arr1.length; i++) ans[i] = arr1[i] | arr2[i]; + limits = [(upperLimit + lowerLimit) / 2, Math.abs(upperLimit - lowerLimit) / 2]; + } else { + groups.push({ + limits: limits, + group: group + }); // var optmimalPeak = fitSpectrum(group,limits,spectrum); - return ans; - } - /** - * Logical XOR operation - * @param {Array} arr1 - * @param {Array} arr2 - * @return {Array} - */ + group = [peakList[i]]; + limits = [peakList[i].x, nL * peakList[i].width]; + } + } + groups.push({ + limits: limits, + group: group + }); // Merge backward - function xor(arr1, arr2) { - var ans = new Array(arr1.length); + for (let i = groups.length - 2; i >= 0; i--) { + // The groups overlaps + if (Math.abs(groups[i].limits[0] - groups[i + 1].limits[0]) < (groups[i].limits[1] + groups[i + 1].limits[1]) / 2) { + for (let j = 0; j < groups[i + 1].group.length; j++) { + groups[i].group.push(groups[i + 1].group[j]); + } - for (var i = 0; i < arr1.length; i++) ans[i] = arr1[i] ^ arr2[i]; + upperLimit = groups[i].limits[0] + groups[i].limits[1]; - return ans; - } - /** - * Logical NOT operation - * @param {Array} arr - * @return {Array} - */ + if (groups[i + 1].limits[0] + groups[i + 1].limits[1] > upperLimit) { + upperLimit = groups[i + 1].limits[0] + groups[i + 1].limits[1]; + } + lowerLimit = groups[i].limits[0] - groups[i].limits[1]; - function not(arr) { - var ans = new Array(arr.length); + if (groups[i + 1].limits[0] - groups[i + 1].limits[1] < lowerLimit) { + lowerLimit = groups[i + 1].limits[0] - groups[i + 1].limits[1]; + } - for (var i = 0; i < ans.length; i++) ans[i] = ~arr[i]; + groups[i].limits = [(upperLimit + lowerLimit) / 2, Math.abs(upperLimit - lowerLimit) / 2]; + groups.splice(i + 1, 1); + } + } - return ans; + return groups; } + /** - * Gets the n value of array arr - * @param {Array} arr - * @param {number} n - * @return {boolean} + * This function try to join the peaks that seems to belong to a broad signal in a single broad peak. + * @param peakList + * @param options */ + function joinBroadPeaks(peakList, options = {}) { + let width = options.width; + let broadLines = []; // Optimize the possible broad lines - function getBit(arr, n) { - var index = n >> 5; // Same as Math.floor(n/32) + let max = 0; + let maxI = 0; + let count = 1; - 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} - */ + for (let i = peakList.length - 1; i >= 0; i--) { + if (peakList[i].soft) { + broadLines.push(peakList.splice(i, 1)[0]); + } + } // Push a feke peak - function setBit(arr, n, val) { - var index = n >> 5; // Same as Math.floor(n/32) + broadLines.push({ + x: Number.MAX_VALUE + }); + let candidates = [[broadLines[0].x, broadLines[0].y]]; + let indexes = [broadLines[0].index]; - 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} - */ + for (let i = 1; i < broadLines.length; i++) { + // console.log(broadLines[i-1].x+" "+broadLines[i].x); + if (Math.abs(broadLines[i - 1].x - broadLines[i].x) < width) { + candidates.push([broadLines[i].x, broadLines[i].y]); + if (broadLines[i].y > max) { + max = broadLines[i].y; + maxI = i; + } - function toBinaryString(arr) { - var str = ''; + indexes.push(broadLines[i].index); + count++; + } else { + if (count > 2) { + let fitted = optimizeSingleLorentzian(candidates, { + x: broadLines[maxI].x, + y: max, + width: Math.abs(candidates[0][0] - candidates[candidates.length - 1][0]) + }); + let { + parameters + } = fitted; + peakList.push({ + x: parameters[0], + y: parameters[1], + width: parameters[2], + index: Math.floor(indexes.reduce((a, b) => a + b, 0) / indexes.length), + soft: false + }); + } else { + // Put back the candidates to the signals list + indexes.forEach(index => { + peakList.push(broadLines[index]); + }); + } - for (var i = 0; i < arr.length; i++) { - var obj = (arr[i] >>> 0).toString(2); - str += '00000000000000000000000000000000'.substr(obj.length) + obj; + candidates = [[broadLines[i].x, broadLines[i].y]]; + indexes = [i]; + max = broadLines[i].y; + maxI = i; + count = 1; + } } - return str; + peakList.sort(function (a, b) { + return a.x - b.x; + }); + return peakList; } + /** - * Creates an array of numbers based on a string of bits - * @param {string} str - * @returns {Array} + * This method will allow to enlarge peaks and prevent overlap between peaks + * Because peaks may not be symmetric after we add 2 properties, from and to. + * @param {Array} peakList + * @param {object} [options={}] + * @param {number} [factor=2] + * @param {boolean} [overlap=false] by default we don't allow overlap + * @return {Array} peakList */ + function broadenPeaks(peakList, options = {}) { + const { + factor = 2, + overlap = false + } = options; + for (let peak of peakList) { + if (!peak.right || !peak.left) { + peak.from = peak.x - peak.width / 2 * factor; + peak.to = peak.x + peak.width / 2 * factor; + } else { + peak.from = peak.x - (peak.x - peak.left.x) * factor; + peak.to = peak.x + (peak.right.x - peak.x) * factor; + } + } - function parseBinaryString(str) { - var len = str.length / 32; - var ans = new Array(len); + if (!overlap) { + for (let i = 0; i < peakList.length - 1; i++) { + let peak = peakList[i]; + let nextPeak = peakList[i + 1]; - for (var i = 0; i < len; i++) { - ans[i] = parseInt(str.substr(i * 32, 32), 2) | 0; + if (peak.to > nextPeak.from) { + peak.to = nextPeak.from = (peak.to + nextPeak.from) / 2; + } + } } - return ans; + for (let peak of peakList) { + peak.width = peak.to - peak.from; + } + + return peakList; } - /** - * Translates an array of numbers to a hex string - * @param {Array} arr - * @returns {string} - */ + var index$6 = /*#__PURE__*/Object.freeze({ + __proto__: null, + gsd: gsd, + optimizePeaks: optimizePeaks, + joinBroadPeaks: joinBroadPeaks, + broadenPeaks: broadenPeaks + }); + + const toString$4 = Object.prototype.toString; + function isAnyArray$4(object) { + return toString$4.call(object).endsWith('Array]'); + } + + function min$1(input) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!isAnyArray$4(input)) { + throw new TypeError('input must be an array'); + } + + if (input.length === 0) { + throw new TypeError('input must not be empty'); + } - function toHexString(arr) { - var str = ''; + var _options$fromIndex = options.fromIndex, + fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex, + _options$toIndex = options.toIndex, + toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex; - for (var i = 0; i < arr.length; i++) { - var obj = (arr[i] >>> 0).toString(16); - str += '00000000'.substr(obj.length) + obj; + if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) { + throw new Error('fromIndex must be a positive integer smaller than length'); } - return str; - } - /** - * Creates an array of numbers based on a hex string - * @param {string} str - * @returns {Array} - */ - + if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) { + throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length'); + } - function parseHexString(str) { - var len = str.length / 8; - var ans = new Array(len); + var minValue = input[fromIndex]; - for (var i = 0; i < len; i++) { - ans[i] = parseInt(str.substr(i * 8, 8), 16) | 0; + for (var i = fromIndex + 1; i < toIndex; i++) { + if (input[i] < minValue) minValue = input[i]; } - return ans; + return minValue; } - /** - * Creates a human readable string of the array - * @param {Array} arr - * @returns {string} - */ + function max$1(input) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - function toDebug(arr) { - var binary = toBinaryString(arr); - var str = ''; + if (!isAnyArray$4(input)) { + throw new TypeError('input must be an array'); + } - for (var i = 0; i < arr.length; i++) { - str += '0000'.substr((i * 32).toString(16).length) + (i * 32).toString(16) + ':'; + if (input.length === 0) { + throw new TypeError('input must not be empty'); + } - for (var j = 0; j < 32; j += 4) { - str += ' ' + binary.substr(i * 32 + j, 4); - } + var _options$fromIndex = options.fromIndex, + fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex, + _options$toIndex = options.toIndex, + toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex; - if (i < arr.length - 1) str += '\n'; + if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) { + throw new Error('fromIndex must be a positive integer smaller than length'); } - return str; - } + if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) { + throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length'); + } - var src$7 = { - count: count, - and: and, - or: or, - xor: xor, - not: not, - getBit: getBit, - setBit: setBit, - toBinaryString: toBinaryString, - parseBinaryString: parseBinaryString, - toHexString: toHexString, - parseHexString: parseHexString, - toDebug: toDebug - }; + var maxValue = input[fromIndex]; - /** - * Computes the mode of the given values - * @param {Array} input - * @return {number} - */ + for (var i = fromIndex + 1; i < toIndex; i++) { + if (input[i] > maxValue) maxValue = input[i]; + } + + return maxValue; + } function mode$1(input) { - if (!src(input)) { + if (!isAnyArray$4(input)) { throw new TypeError('input must be an array'); } @@ -16320,23 +18975,69 @@ return maxValue; } - /** - * Computes the norm of the given values - * @param {Array} input - * @param {object} [options={}] - * @param {string} [options.algorithm='absolute'] absolute, sum or max - * @return {number} - */ + const toString$5 = Object.prototype.toString; + function isAnyArray$5(object) { + return toString$5.call(object).endsWith('Array]'); + } + + function max$2(input) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!isAnyArray$5(input)) { + throw new TypeError('input must be an array'); + } + + if (input.length === 0) { + throw new TypeError('input must not be empty'); + } + + var _options$fromIndex = options.fromIndex, + fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex, + _options$toIndex = options.toIndex, + toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex; + + if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) { + throw new Error('fromIndex must be a positive integer smaller than length'); + } + + if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) { + throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length'); + } + + var maxValue = input[fromIndex]; + + for (var i = fromIndex + 1; i < toIndex; i++) { + if (input[i] > maxValue) maxValue = input[i]; + } + + return maxValue; + } function norm$1(input) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _options$algorithm = options.algorithm, - algorithm = _options$algorithm === void 0 ? 'absolute' : _options$algorithm; + algorithm = _options$algorithm === void 0 ? 'absolute' : _options$algorithm, + _options$sumValue = options.sumValue, + sumValue = _options$sumValue === void 0 ? 1 : _options$sumValue, + _options$maxValue = options.maxValue, + maxValue = _options$maxValue === void 0 ? 1 : _options$maxValue; - if (!Array.isArray(input)) { + if (!isAnyArray$5(input)) { throw new Error('input must be an array'); } + var output; + + if (options.output !== undefined) { + if (!isAnyArray$5(options.output)) { + throw new TypeError('output option must be an array if specified'); + } + + output = options.output; + } else { + output = new Array(input.length); + } + if (input.length === 0) { throw new Error('input must not be empty'); } @@ -16344,29 +19045,39 @@ switch (algorithm.toLowerCase()) { case 'absolute': { - var absoluteSumValue = absoluteSum(input); + var absoluteSumValue = absoluteSum(input) / sumValue; if (absoluteSumValue === 0) return input.slice(0); - return input.map(function (element) { - return element / absoluteSumValue; - }); + + for (var i = 0; i < input.length; i++) { + output[i] = input[i] / absoluteSumValue; + } + + return output; } case 'max': { - var maxValue = max(input); - if (maxValue === 0) return input.slice(0); - return input.map(function (element) { - return element / maxValue; - }); + var currentMaxValue = max$2(input); + if (currentMaxValue === 0) return input.slice(0); + var factor = maxValue / currentMaxValue; + + for (var _i = 0; _i < input.length; _i++) { + output[_i] = input[_i] * factor; + } + + return output; } case 'sum': { - var sumValue = sum(input); - if (sumValue === 0) return input.slice(0); - return input.map(function (element) { - return element / sumValue; - }); + var sumFactor = sum(input) / sumValue; + if (sumFactor === 0) return input.slice(0); + + for (var _i2 = 0; _i2 < input.length; _i2++) { + output[_i2] = input[_i2] / sumFactor; + } + + return output; } default: @@ -16385,27 +19096,29 @@ } function _typeof(obj) { + "@babel/helpers - typeof"; + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function _typeof(obj) { + _typeof = function (obj) { return typeof obj; }; } else { - _typeof = function _typeof(obj) { + _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } 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} + /** + * 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} */ @@ -16413,12 +19126,12 @@ var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (_typeof(input) === 'object' && !src(input)) { + if (_typeof(input) === 'object' && !isAnyArray$4(input)) { options = input; input = []; } - if (!src(input)) { + if (!isAnyArray$4(input)) { throw new TypeError('input must be an array'); } @@ -16431,7 +19144,7 @@ size = _options$size === void 0 ? input.length : _options$size, step = _options.step; - if (size && step) { + if (size !== 0 && step) { throw new Error('step is defined by the array size'); } @@ -16448,7 +19161,8 @@ } if (Array.isArray(input)) { - input.length = 0; // only works with normal array + // only works with normal array + input.length = 0; for (var i = 0; i < size; i++) { input.push(from); @@ -16468,19 +19182,15 @@ return 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} - */ + const toString$6 = Object.prototype.toString; + function isAnyArray$6(object) { + return toString$6.call(object).endsWith('Array]'); + } function variance(values) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (!src(values)) { + if (!isAnyArray$6(values)) { throw new TypeError('input must be an array'); } @@ -16502,15 +19212,6 @@ } } - /** - * 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) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return Math.sqrt(variance(values, options)); @@ -16526,8 +19227,7 @@ * @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] : {}; + function mergeByCentroids(originalPoints, centroids, options = {}) { const { window = 0.01 } = options; @@ -16611,8 +19311,7 @@ * @return {number} */ - function covariance$1(points) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + function covariance$1(points, options = {}) { const { x, y @@ -16644,8 +19343,7 @@ * @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] : {}; + function maxMerge(points, options = {}) { const { x, y @@ -16699,8 +19397,7 @@ * @return {{index: number, value: number}} */ - function maxY(points) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + function maxY(points, options = {}) { const { x, y @@ -16755,14 +19452,13 @@ } if (index < 0) { - throw new Error("the value ".concat(value, " doesn't belongs to the abscissa value")); + throw new Error(`the value ${value} doesn't belongs to the abscissa value`); } return index; } - function sortX(points) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + function sortX(points, options = {}) { const { x, y @@ -16800,8 +19496,7 @@ * @param {object} [points={}] : Object of points contains property x (an array) and y (an array) * @return points */ - function uniqueX() { - let points = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + function uniqueX(points = {}) { const { x, y @@ -16844,8 +19539,7 @@ * @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] : {}; + function weightedMerge(points, options = {}) { const { x, y @@ -16888,6 +19582,140 @@ return merged; } + /** + * Normalize an array of zones: + * - ensure than from < to + * - merge overlapping zones + * + * The method will always check if from if lower than to and will swap if required. + * @param {Array} [zones=[]] + * @param {object} [options={}] + * @param {number} [options.from=Number.NEGATIVE_INFINITY] Specify min value of a zone + * @param {number} [options.to=Number.POSITIVE_INFINITY] Specify max value of a zone + */ + function normalize(zones = [], options = {}) { + if (zones.length === 0) return []; + let { + from = Number.NEGATIVE_INFINITY, + to = Number.POSITIVE_INFINITY + } = options; + if (from > to) [from, to] = [to, from]; + zones = JSON.parse(JSON.stringify(zones)).map(zone => zone.from > zone.to ? { + from: zone.to, + to: zone.from + } : zone); + zones = zones.sort((a, b) => { + if (a.from !== b.from) return a.from - b.from; + return a.to - b.to; + }); + zones.forEach(zone => { + if (from > zone.from) zone.from = from; + if (to < zone.to) zone.to = to; + }); + zones = zones.filter(zone => zone.from <= zone.to); + if (zones.length === 0) return []; + let currentZone = zones[0]; + let result = [currentZone]; + + for (let i = 1; i < zones.length; i++) { + let zone = zones[i]; + + if (zone.from <= currentZone.to) { + currentZone.to = zone.to; + } else { + currentZone = zone; + result.push(currentZone); + } + } + + return result; + } + + /** + * Convert an array of exclusions and keep only from / to + * + * The method will always check if from if lower than to and will swap if required. + * @param {Array} [exclusions=[]] + * @param {object} [options={}] + * @param {number} [options.from=Number.NEGATIVE_INFINITY] Specify min value of zones (after inversion) + * @param {number} [options.to=Number.POSITIVE_INFINITY] Specify max value of zones (after inversion) + */ + + function invert(exclusions = [], options = {}) { + let { + from = Number.NEGATIVE_INFINITY, + to = Number.POSITIVE_INFINITY + } = options; + if (from > to) [from, to] = [to, from]; + exclusions = normalize(exclusions, { + from, + to + }); + if (exclusions.length === 0) return [{ + from, + to + }]; + let zones = []; + + for (let i = 0; i < exclusions.length; i++) { + let exclusion = exclusions[i]; + let nextExclusion = exclusions[i + 1]; + + if (i === 0) { + if (exclusion.from > from) { + zones.push({ + from, + to: exclusion.from + }); + } + } + + if (i === exclusions.length - 1) { + if (exclusion.to < to) { + zones.push({ + from: exclusion.to, + to + }); + } + } else { + zones.push({ + from: exclusion.to, + to: nextExclusion.from + }); + } + } + + return zones; + } + + /** + * Add the number of points per zone to reach a specified total + * @param {Array} [zones=[]] + * @param {number} [numberOfPoints] Total number of points to distribute between zones + * @param {object} [options={}] + * @param {number} [options.from=Number.NEGATIVE_INFINITY] Specify min value of a zone + * @param {number} [options.to=Number.POSITIVE_INFINITY] Specify max value of a zone + */ + + function zonesWithPoints(zones, numberOfPoints, options = {}) { + if (zones.length === 0) return zones; + zones = normalize(zones, options); + const totalSize = zones.reduce((previous, current) => { + return previous + (current.to - current.from); + }, 0); + let unitsPerPoint = totalSize / numberOfPoints; + let currentTotal = 0; + + for (let i = 0; i < zones.length - 1; i++) { + let zone = zones[i]; + zone.numberOfPoints = Math.min(Math.round((zone.to - zone.from) / unitsPerPoint), numberOfPoints - currentTotal); + currentTotal += zone.numberOfPoints; + } + + zones[zones.length - 1].numberOfPoints = numberOfPoints - currentTotal; + return zones; + } + /** * Function that calculates the integral of the line between two * x-coordinates, given the slope and intercept of the line. @@ -16913,32 +19741,34 @@ */ 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 + let xLength = x.length; + let step = (to - from) / (numberOfPoints - 1); + let halfStep = step / 2; + let output = new Array(numberOfPoints); + let initialOriginalStep = x[1] - x[0]; + let lastOriginalStep = x[xLength - 1] - x[xLength - 2]; // Init main variables + + let min = from - halfStep; + let max = from + halfStep; + let previousX = Number.MIN_VALUE; + let previousY = 0; + let nextX = x[0] - initialOriginalStep; + let nextY = 0; + let currentValue = 0; + let slope = 0; + let intercept = 0; + let sumAtMin = 0; + let sumAtMax = 0; + let i = 0; // index of input + + let j = 0; // index of output function getSlope(x0, y0, x1, y1) { return (y1 - y0) / (x1 - x0); } + let add = 0; + main: while (true) { if (previousX <= min && min <= nextX) { add = integral(0, min - previousX, slope, previousY); @@ -16947,7 +19777,7 @@ while (nextX - max >= 0) { // no overlap with original point, just consume current value - var add = integral(0, max - previousX, slope, previousY); + add = integral(0, max - previousX, slope, previousY); sumAtMax = currentValue + add; output[j++] = (sumAtMax - sumAtMin) / step; @@ -16991,27 +19821,27 @@ * @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 + let xLength = x.length; + let step = (to - from) / (numberOfPoints - 1); + let halfStep = step / 2; + let lastStep = x[x.length - 1] - x[x.length - 2]; + let start = from - halfStep; + let output = new Array(numberOfPoints); // Init main variables + + let min = start; + let max = start + step; + let previousX = -Number.MAX_VALUE; + let previousY = 0; + let nextX = x[0]; + let nextY = y[0]; + let frontOutsideSpectra = 0; + let backOutsideSpectra = true; + let currentValue = 0; // for slot algorithm + + let currentPoints = 0; + let i = 1; // index of input + + let j = 0; // index of output main: while (true) { if (previousX >= nextX) throw new Error('x must be an increasing serie'); @@ -17062,79 +19892,6 @@ return output; } - function getZones(from, to, numberOfPoints) { - let exclusions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; - - if (from > to) { - [from, to] = [to, from]; - } // in exclusions from and to have to be defined - - - exclusions = exclusions.filter(exclusion => exclusion.from !== undefined && exclusion.to !== undefined); - exclusions = JSON.parse(JSON.stringify(exclusions)); // we ensure that from before to - - 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) - - 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; - } - } - - exclusions = exclusions.filter(exclusion => exclusion.from < exclusion.to); - - if (!exclusions || exclusions.length === 0) { - return [{ - from, - to, - numberOfPoints - }]; - } // need to deal with overlapping exclusions and out of bound exclusions - - - 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; - - if (currentNbPoints > 0) { - zones.push({ - from: currentFrom, - to: exclusion.from, - numberOfPoints: currentNbPoints - }); - } - - currentFrom = exclusion.to; - } - - if (numberOfPoints - totalPoints > 0) { - zones.push({ - from: currentFrom, - to: to, - numberOfPoints: numberOfPoints - totalPoints - }); - } - - return zones; - } - /** * Function that returns a Number array of equally spaced numberOfPoints * containing a representation of intensities of the spectra arguments x @@ -17151,6 +19908,7 @@ * 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. * + * If exclusions zone are present, zones are ignored ! * @param {object} [arrayXY={}] - object containing 2 properties x and y (both an array) * @param {object} [options={}] * @param {number} [options.from=x[0]] @@ -17158,12 +19916,11 @@ * @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 + * @param {Array} [options.zones=[]] array of from / to that should be kept * @return {object} new object with x / y array with the equally spaced data. */ - function equallySpaced() { - let arrayXY = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + function equallySpaced(arrayXY = {}, options = {}) { let { x, y @@ -17182,7 +19939,8 @@ to = x[xLength - 1], variant = 'smooth', numberOfPoints = 100, - exclusions = [] + exclusions = [], + zones = [] } = options; if (xLength !== y.length) { @@ -17205,7 +19963,17 @@ throw new RangeError("'numberOfPoints' option must be greater than 1"); } - let zones = getZones(from, to, numberOfPoints, exclusions); + if (zones.length === 0) { + zones = invert(exclusions, { + from, + to + }); + } + + zones = zonesWithPoints(zones, numberOfPoints, { + from, + to + }); let xResult = []; let yResult = []; @@ -17247,7 +20015,7 @@ throw new RangeError('the number of points must be at least 1'); } - var output = variant === 'slot' ? equallySpacedSlot(x, y, from, to, numberOfPoints) : equallySpacedSmooth(x, y, from, to, numberOfPoints); + let output = variant === 'slot' ? equallySpacedSlot(x, y, from, to, numberOfPoints) : equallySpacedSmooth(x, y, from, to, numberOfPoints); return { x: sequentialFill({ from, @@ -17258,9 +20026,7 @@ }; } - function getZones$1(from, to) { - let exclusions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; - + function getZones(from, to, exclusions = []) { if (from > to) { [from, to] = [to, from]; } // in exclusions from and to have to be defined @@ -17332,8 +20098,7 @@ * @return {{x: Array, y: Array}} */ - function filterX(points) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + function filterX(points, options = {}) { const { x, y @@ -17343,7 +20108,7 @@ to = x[x.length - 1], exclusions = [] } = options; - let zones = getZones$1(from, to, exclusions); + let zones = getZones(from, to, exclusions); let currentZoneIndex = 0; let newX = []; let newY = []; @@ -17378,8 +20143,8 @@ QrDecomposition: QrDecomposition$1 } = MatrixLib; const Array$1 = { - min, - max, + min: min$1, + max: max$1, median, mean, mode: mode$1, @@ -17405,17 +20170,18 @@ exports.Array = Array$1; exports.ArrayXY = ArrayXY; - exports.BitArray = src$7; + exports.BitArray = src$3; exports.CholeskyDecomposition = CholeskyDecomposition$1; - exports.ConfusionMatrix = src$1; - exports.CrossValidation = src$3; + exports.ConfusionMatrix = ConfusionMatrix; + exports.CrossValidation = index$2; exports.DecisionTreeClassifier = DecisionTreeClassifier; exports.DecisionTreeRegression = DecisionTreeRegression; exports.Distance = distances; exports.EVD = EVD; exports.ExponentialRegression = ExponentialRegression; - exports.FCNNLS = index$2; + exports.FCNNLS = index$3; exports.FNN = FeedForwardNeuralNetwork; + exports.GSD = index$6; exports.HClust = index; exports.HashTable = HashTable; exports.KMeans = kmeans; @@ -17427,9 +20193,11 @@ exports.MatrixLib = MatrixLib; exports.MultivariateLinearRegression = MultivariateLinearRegression; exports.NaiveBayes = index$1; + exports.OPLS = OPLS; + exports.OPLSNipals = OPLSNipals; exports.PCA = PCA; exports.PLS = PLS; - exports.Performance = src$5; + exports.Performance = src$1; exports.PolynomialRegression = PolynomialRegression; exports.PowerRegression = PowerRegression; exports.QrDecomposition = QrDecomposition$1; @@ -17437,7 +20205,7 @@ exports.RandomForestClassifier = RandomForestClassifier; exports.RandomForestRegression = RandomForestRegression; exports.RobustPolynomialRegression = RobustPolynomialRegression; - exports.SOM = src$4; + exports.SOM = src; exports.SVD = SVD; exports.Similarity = similarities; exports.SimpleLinearRegression = SimpleLinearRegression; @@ -17447,11 +20215,11 @@ exports.binarySearch = binarySearch; exports.distanceMatrix = distanceMatrix; exports.levenbergMarquardt = levenbergMarquardt; - exports.numSort = index$3; - exports.padArray = src$6; + exports.numSort = index$4; + exports.padArray = src$2; exports.savitzkyGolay = savitzkyGolay; Object.defineProperty(exports, '__esModule', { value: true }); -})); +}))); //# sourceMappingURL=ml.js.map diff --git a/dist/ml.js.map b/dist/ml.js.map index fab0bc2..964f990 100644 --- a/dist/ml.js.map +++ b/dist/ml.js.map @@ -1 +1 @@ -{"version":3,"file":"ml.js","sources":["../node_modules/is-any-array/src/index.js","../node_modules/ml-array-max/lib-es6/index.js","../node_modules/ml-array-min/lib-es6/index.js","../node_modules/ml-array-rescale/lib-es6/index.js","../node_modules/ml-matrix/src/util.js","../node_modules/ml-matrix/src/stat.js","../node_modules/ml-matrix/src/inspect.js","../node_modules/ml-matrix/src/mathOperations.js","../node_modules/ml-matrix/src/matrix.js","../node_modules/ml-matrix/src/views/base.js","../node_modules/ml-matrix/src/views/column.js","../node_modules/ml-matrix/src/views/columnSelection.js","../node_modules/ml-matrix/src/views/flipColumn.js","../node_modules/ml-matrix/src/views/flipRow.js","../node_modules/ml-matrix/src/views/row.js","../node_modules/ml-matrix/src/views/rowSelection.js","../node_modules/ml-matrix/src/views/selection.js","../node_modules/ml-matrix/src/views/sub.js","../node_modules/ml-matrix/src/views/transpose.js","../node_modules/ml-matrix/src/wrap/WrapperMatrix1D.js","../node_modules/ml-matrix/src/wrap/WrapperMatrix2D.js","../node_modules/ml-matrix/src/wrap/wrap.js","../node_modules/ml-matrix/src/dc/lu.js","../node_modules/ml-matrix/src/dc/util.js","../node_modules/ml-matrix/src/dc/qr.js","../node_modules/ml-matrix/src/dc/svd.js","../node_modules/ml-matrix/src/decompositions.js","../node_modules/ml-matrix/src/determinant.js","../node_modules/ml-matrix/src/linearDependencies.js","../node_modules/ml-matrix/src/pseudoInverse.js","../node_modules/ml-matrix/src/covariance.js","../node_modules/ml-matrix/src/correlation.js","../node_modules/ml-matrix/src/dc/evd.js","../node_modules/ml-matrix/src/dc/cholesky.js","../node_modules/ml-matrix/src/dc/nipals.js","../node_modules/ml-array-sum/lib-es6/index.js","../node_modules/ml-array-mean/lib-es6/index.js","../node_modules/ml-cart/src/utils.js","../node_modules/ml-cart/src/TreeNode.js","../node_modules/ml-cart/src/DecisionTreeClassifier.js","../node_modules/ml-cart/src/DecisionTreeRegression.js","../node_modules/random-js/dist/random-js.esm.js","../node_modules/ml-random-forest/src/utils.js","../node_modules/ml-random-forest/src/RandomForestBase.js","../node_modules/ml-random-forest/src/RandomForestClassifier.js","../node_modules/median-quickselect/lib/median-quickselect.min.js","../node_modules/ml-array-median/lib-es6/index.js","../node_modules/ml-random-forest/src/RandomForestRegression.js","../node_modules/ml-pca/src/pca.js","../node_modules/ml-distance-euclidean/lib-es6/euclidean.js","../node_modules/ml-distance-matrix/src/index.js","../node_modules/heap/lib/heap.js","../node_modules/heap/index.js","../node_modules/ml-hclust/src/Cluster.js","../node_modules/ml-hclust/src/agnes.js","../node_modules/ml-hclust/src/index.js","../node_modules/ml-nearest-vector/lib-es6/index.js","../node_modules/ml-kmeans/src/utils.js","../node_modules/ml-xsadd/lib-es6/xsadd.js","../node_modules/ml-random/lib-es6/choice.js","../node_modules/ml-random/lib-es6/index.js","../node_modules/ml-kmeans/src/initialization.js","../node_modules/ml-kmeans/src/KMeansResult.js","../node_modules/ml-kmeans/src/kmeans.js","../node_modules/ml-naivebayes/src/utils.js","../node_modules/ml-naivebayes/src/GaussianNB.js","../node_modules/ml-naivebayes/src/MultinomialNB.js","../node_modules/ml-knn/src/KDTree.js","../node_modules/ml-knn/src/index.js","../node_modules/ml-pls/src/utils.js","../node_modules/ml-pls/src/pls.js","../node_modules/ml-pls/src/kopls.js","../node_modules/ml-confusion-matrix/src/index.js","../node_modules/ml-combinations/src/index.js","../node_modules/ml-cross-validation/src/index.js","../node_modules/ml-fnn/FeedForwardNeuralNetwork.js","../node_modules/ml-som/src/node-square.js","../node_modules/ml-som/src/node-hexagonal.js","../node_modules/ml-som/src/index.js","../node_modules/ml-regression-base/src/maybeToPrecision.js","../node_modules/ml-regression-base/src/checkArrayLength.js","../node_modules/ml-regression-base/src/index.js","../node_modules/ml-regression-polynomial/src/index.js","../node_modules/ml-regression-simple-linear/src/index.js","../node_modules/ml-regression-exponential/src/index.js","../node_modules/ml-regression-power/src/index.js","../node_modules/ml-regression-multivariate-linear/src/index.js","../node_modules/ml-kernel-gaussian/gaussian-kernel.js","../node_modules/ml-kernel-polynomial/polynomial-kernel.js","../node_modules/ml-kernel-sigmoid/sigmoid-kernel.js","../node_modules/ml-kernel/src/kernels/anova-kernel.js","../node_modules/ml-kernel/src/kernels/cauchy-kernel.js","../node_modules/ml-kernel/src/kernels/exponential-kernel.js","../node_modules/ml-kernel/src/kernels/histogram-intersection-kernel.js","../node_modules/ml-kernel/src/kernels/laplacian-kernel.js","../node_modules/ml-kernel/src/kernels/multiquadratic-kernel.js","../node_modules/ml-kernel/src/kernels/rational-quadratic-kernel.js","../node_modules/ml-kernel/src/kernel.js","../node_modules/ml-regression-theil-sen/src/index.js","../node_modules/ml-regression-robust-polynomial/src/index.js","../node_modules/ml-levenberg-marquardt/src/errorCalculation.js","../node_modules/ml-levenberg-marquardt/src/step.js","../node_modules/ml-levenberg-marquardt/src/index.js","../node_modules/ml-fcnnls/src/util/selection.js","../node_modules/ml-fcnnls/src/util/sortCollectionSet.js","../node_modules/ml-fcnnls/src/cssls.js","../node_modules/ml-fcnnls/src/initialisation.js","../node_modules/ml-fcnnls/src/util/setDifference.js","../node_modules/ml-fcnnls/src/optimality.js","../node_modules/ml-fcnnls/src/fcnnls.js","../node_modules/ml-fcnnls/src/fcnnlsVector.js","../node_modules/binary-search/index.js","../node_modules/num-sort/index.js","../node_modules/ml-hash-table/src/primeFinder.js","../node_modules/ml-hash-table/src/HashTable.js","../node_modules/ml-sparse-matrix/src/index.js","../node_modules/ml-distance/src/distances/additiveSymmetric.js","../node_modules/ml-distance/src/distances/avg.js","../node_modules/ml-distance/src/distances/bhattacharyya.js","../node_modules/ml-distance/src/distances/canberra.js","../node_modules/ml-distance/src/distances/chebyshev.js","../node_modules/ml-distance/src/distances/clark.js","../node_modules/ml-distance/src/similarities/czekanowski.js","../node_modules/ml-distance/src/distances/czekanowski.js","../node_modules/ml-distance/src/distances/dice.js","../node_modules/ml-distance/src/distances/divergence.js","../node_modules/ml-distance/src/distances/fidelity.js","../node_modules/ml-distance/src/distances/gower.js","../node_modules/ml-distance/src/distances/harmonicMean.js","../node_modules/ml-distance/src/distances/hellinger.js","../node_modules/ml-distance/src/distances/innerProduct.js","../node_modules/ml-distance/src/distances/intersection.js","../node_modules/ml-distance/src/distances/jaccard.js","../node_modules/ml-distance/src/distances/jeffreys.js","../node_modules/ml-distance/src/distances/jensenDifference.js","../node_modules/ml-distance/src/distances/jensenShannon.js","../node_modules/ml-distance/src/distances/kdivergence.js","../node_modules/ml-distance/src/distances/kulczynski.js","../node_modules/ml-distance/src/distances/kullbackLeibler.js","../node_modules/ml-distance/src/distances/kumarHassebrook.js","../node_modules/ml-distance/src/distances/kumarJohnson.js","../node_modules/ml-distance/src/distances/lorentzian.js","../node_modules/ml-distance/src/distances/manhattan.js","../node_modules/ml-distance/src/distances/matusita.js","../node_modules/ml-distance/src/distances/minkowski.js","../node_modules/ml-distance/src/distances/motyka.js","../node_modules/ml-distance/src/distances/neyman.js","../node_modules/ml-distance/src/distances/pearson.js","../node_modules/ml-distance/src/distances/probabilisticSymmetric.js","../node_modules/ml-distance/src/distances/ruzicka.js","../node_modules/ml-distance/src/distances/soergel.js","../node_modules/ml-distance/src/distances/sorensen.js","../node_modules/ml-distance/src/distances/squared.js","../node_modules/ml-distance/src/distances/squaredChord.js","../node_modules/ml-distance/src/distances/taneja.js","../node_modules/ml-distance/src/similarities/tanimoto.js","../node_modules/ml-distance/src/distances/tanimoto.js","../node_modules/ml-distance/src/distances/topsoe.js","../node_modules/ml-distance/src/distances/waveHedges.js","../node_modules/ml-tree-similarity/src/createTree.js","../node_modules/ml-tree-similarity/src/getSimilarity.js","../node_modules/ml-tree-similarity/src/index.js","../node_modules/ml-distance/src/similarities/cosine.js","../node_modules/ml-distance/src/similarities/dice.js","../node_modules/ml-distance/src/similarities/intersection.js","../node_modules/ml-distance/src/similarities/jaccard.js","../node_modules/ml-distance/src/similarities/kulczynski.js","../node_modules/ml-distance/src/similarities/motyka.js","../node_modules/ml-distance/src/similarities/pearson.js","../node_modules/ml-distance/src/similarities/squaredChord.js","../node_modules/ml-performance/src/measures.js","../node_modules/ml-performance/src/index.js","../node_modules/ml-pad-array/src/index.js","../node_modules/ml-savitzky-golay/src/index.js","../node_modules/ml-bit-array/src/creator.js","../node_modules/ml-bit-array/src/index.js","../node_modules/ml-array-mode/lib-es6/index.js","../node_modules/ml-array-normed/lib-es6/index.js","../node_modules/ml-array-sequential-fill/lib-es6/index.js","../node_modules/ml-array-variance/lib-es6/index.js","../node_modules/ml-array-standard-deviation/lib-es6/index.js","../node_modules/ml-array-xy-centroids-merge/src/index.js","../node_modules/ml-arrayxy-closestx/src/index.js","../node_modules/ml-array-xy-covariance/src/index.js","../node_modules/ml-array-xy-max-merge/src/index.js","../node_modules/ml-array-xy-max-y/src/index.js","../node_modules/ml-array-xy-sort-x/src/index.js","../node_modules/ml-arrayxy-uniquex/src/index.js","../node_modules/ml-array-xy-weighted-merge/src/index.js","../node_modules/ml-array-xy-equally-spaced/src/integral.js","../node_modules/ml-array-xy-equally-spaced/src/equallySpacedSmooth.js","../node_modules/ml-array-xy-equally-spaced/src/equallySpacedSlot.js","../node_modules/ml-array-xy-equally-spaced/src/getZones.js","../node_modules/ml-array-xy-equally-spaced/src/index.js","../node_modules/ml-array-xy-filter-x/src/getZones.js","../node_modules/ml-array-xy-filter-x/src/index.js","../src/index.js"],"sourcesContent":["'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","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 maxValue = input[0];\n\n for (var i = 1; i < input.length; i++) {\n if (input[i] > maxValue) maxValue = input[i];\n }\n\n return maxValue;\n}\n\nexport default max;\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 minValue = input[0];\n\n for (var i = 1; i < input.length; i++) {\n if (input[i] < minValue) minValue = input[i];\n }\n\n return minValue;\n}\n\nexport default min;\n","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","/**\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 let 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 let 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 let 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 let 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 newArray(length, value = 0) {\n let array = [];\n for (let i = 0; i < length; i++) {\n array.push(value);\n }\n return array;\n}\n\nfunction checkNumber(name, value) {\n if (typeof value !== 'number') {\n throw new TypeError(`${name} must be a number`);\n }\n}\n","import { newArray } from './util';\n\nexport function sumByRow(matrix) {\n let sum = newArray(matrix.rows);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[i] += matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function sumByColumn(matrix) {\n let sum = newArray(matrix.columns);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[j] += matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function sumAll(matrix) {\n let v = 0;\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n v += matrix.get(i, j);\n }\n }\n return v;\n}\n\nexport function productByRow(matrix) {\n let sum = newArray(matrix.rows, 1);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[i] *= matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function productByColumn(matrix) {\n let sum = newArray(matrix.columns, 1);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[j] *= matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function productAll(matrix) {\n let v = 1;\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n v *= matrix.get(i, j);\n }\n }\n return v;\n}\n\nexport function varianceByRow(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const variance = [];\n\n for (let i = 0; i < rows; i++) {\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let j = 0; j < cols; j++) {\n x = matrix.get(i, j) - mean[i];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n variance.push((sum2 - (sum1 * sum1) / cols) / (cols - 1));\n } else {\n variance.push((sum2 - (sum1 * sum1) / cols) / cols);\n }\n }\n return variance;\n}\n\nexport function varianceByColumn(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const variance = [];\n\n for (let j = 0; j < cols; j++) {\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let i = 0; i < rows; i++) {\n x = matrix.get(i, j) - mean[j];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n variance.push((sum2 - (sum1 * sum1) / rows) / (rows - 1));\n } else {\n variance.push((sum2 - (sum1 * sum1) / rows) / rows);\n }\n }\n return variance;\n}\n\nexport function varianceAll(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const size = rows * cols;\n\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n x = matrix.get(i, j) - mean;\n sum1 += x;\n sum2 += x * x;\n }\n }\n if (unbiased) {\n return (sum2 - (sum1 * sum1) / size) / (size - 1);\n } else {\n return (sum2 - (sum1 * sum1) / size) / size;\n }\n}\n\nexport function centerByRow(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean[i]);\n }\n }\n}\n\nexport function centerByColumn(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean[j]);\n }\n }\n}\n\nexport function centerAll(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean);\n }\n }\n}\n\nexport function getScaleByRow(matrix) {\n const scale = [];\n for (let i = 0; i < matrix.rows; i++) {\n let sum = 0;\n for (let j = 0; j < matrix.columns; j++) {\n sum += Math.pow(matrix.get(i, j), 2) / (matrix.columns - 1);\n }\n scale.push(Math.sqrt(sum));\n }\n return scale;\n}\n\nexport function scaleByRow(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale[i]);\n }\n }\n}\n\nexport function getScaleByColumn(matrix) {\n const scale = [];\n for (let j = 0; j < matrix.columns; j++) {\n let sum = 0;\n for (let i = 0; i < matrix.rows; i++) {\n sum += Math.pow(matrix.get(i, j), 2) / (matrix.rows - 1);\n }\n scale.push(Math.sqrt(sum));\n }\n return scale;\n}\n\nexport function scaleByColumn(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale[j]);\n }\n }\n}\n\nexport function getScaleAll(matrix) {\n const divider = matrix.size - 1;\n let sum = 0;\n for (let j = 0; j < matrix.columns; j++) {\n for (let i = 0; i < matrix.rows; i++) {\n sum += Math.pow(matrix.get(i, j), 2) / divider;\n }\n }\n return Math.sqrt(sum);\n}\n\nexport function scaleAll(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale);\n }\n }\n}\n","export function inspectMatrix() {\n const indent = ' '.repeat(2);\n const indentData = ' '.repeat(4);\n return `${this.constructor.name} {\n${indent}[\n${indentData}${inspectData(this, indentData)}\n${indent}]\n${indent}rows: ${this.rows}\n${indent}columns: ${this.columns}\n}`;\n}\n\nconst maxRows = 15;\nconst maxColumns = 10;\nconst maxNumSize = 8;\n\nfunction inspectData(matrix, indent) {\n const { rows, columns } = matrix;\n const maxI = Math.min(rows, maxRows);\n const maxJ = Math.min(columns, maxColumns);\n const result = [];\n for (let i = 0; i < maxI; i++) {\n let line = [];\n for (let j = 0; j < maxJ; j++) {\n line.push(formatNumber(matrix.get(i, j)));\n }\n result.push(`${line.join(' ')}`);\n }\n if (maxJ !== columns) {\n result[result.length - 1] += ` ... ${columns - maxColumns} more columns`;\n }\n if (maxI !== rows) {\n result.push(`... ${rows - maxRows} more rows`);\n }\n return result.join(`\\n${indent}`);\n}\n\nfunction formatNumber(num) {\n const numStr = String(num);\n if (numStr.length <= maxNumSize) {\n return numStr.padEnd(maxNumSize, ' ');\n }\n const precise = num.toPrecision(maxNumSize - 2);\n if (precise.length <= maxNumSize) {\n return precise;\n }\n const exponential = num.toExponential(maxNumSize - 2);\n const eIndex = exponential.indexOf('e');\n const e = exponential.substring(eIndex);\n return exponential.substring(0, maxNumSize - e.length) + e;\n}\n","export function installMathOperations(AbstractMatrix, Matrix) {\n AbstractMatrix.prototype.add = function add(value) {\n if (typeof value === 'number') return this.addS(value);\n return this.addM(value);\n };\n\n AbstractMatrix.prototype.addS = function addS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.addM = function addM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.add = function add(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.add(value);\n };\n\n AbstractMatrix.prototype.sub = function sub(value) {\n if (typeof value === 'number') return this.subS(value);\n return this.subM(value);\n };\n\n AbstractMatrix.prototype.subS = function subS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.subM = function subM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.sub = function sub(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sub(value);\n };\n AbstractMatrix.prototype.subtract = AbstractMatrix.prototype.sub;\n AbstractMatrix.prototype.subtractS = AbstractMatrix.prototype.subS;\n AbstractMatrix.prototype.subtractM = AbstractMatrix.prototype.subM;\n AbstractMatrix.subtract = AbstractMatrix.sub;\n\n AbstractMatrix.prototype.mul = function mul(value) {\n if (typeof value === 'number') return this.mulS(value);\n return this.mulM(value);\n };\n\n AbstractMatrix.prototype.mulS = function mulS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.mulM = function mulM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.mul = function mul(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.mul(value);\n };\n AbstractMatrix.prototype.multiply = AbstractMatrix.prototype.mul;\n AbstractMatrix.prototype.multiplyS = AbstractMatrix.prototype.mulS;\n AbstractMatrix.prototype.multiplyM = AbstractMatrix.prototype.mulM;\n AbstractMatrix.multiply = AbstractMatrix.mul;\n\n AbstractMatrix.prototype.div = function div(value) {\n if (typeof value === 'number') return this.divS(value);\n return this.divM(value);\n };\n\n AbstractMatrix.prototype.divS = function divS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.divM = function divM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.div = function div(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.div(value);\n };\n AbstractMatrix.prototype.divide = AbstractMatrix.prototype.div;\n AbstractMatrix.prototype.divideS = AbstractMatrix.prototype.divS;\n AbstractMatrix.prototype.divideM = AbstractMatrix.prototype.divM;\n AbstractMatrix.divide = AbstractMatrix.div;\n\n AbstractMatrix.prototype.mod = function mod(value) {\n if (typeof value === 'number') return this.modS(value);\n return this.modM(value);\n };\n\n AbstractMatrix.prototype.modS = function modS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) % value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.modM = function modM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) % matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.mod = function mod(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.mod(value);\n };\n AbstractMatrix.prototype.modulus = AbstractMatrix.prototype.mod;\n AbstractMatrix.prototype.modulusS = AbstractMatrix.prototype.modS;\n AbstractMatrix.prototype.modulusM = AbstractMatrix.prototype.modM;\n AbstractMatrix.modulus = AbstractMatrix.mod;\n\n AbstractMatrix.prototype.and = function and(value) {\n if (typeof value === 'number') return this.andS(value);\n return this.andM(value);\n };\n\n AbstractMatrix.prototype.andS = function andS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) & value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.andM = function andM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) & matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.and = function and(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.and(value);\n };\n\n AbstractMatrix.prototype.or = function or(value) {\n if (typeof value === 'number') return this.orS(value);\n return this.orM(value);\n };\n\n AbstractMatrix.prototype.orS = function orS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) | value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.orM = function orM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) | matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.or = function or(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.or(value);\n };\n\n AbstractMatrix.prototype.xor = function xor(value) {\n if (typeof value === 'number') return this.xorS(value);\n return this.xorM(value);\n };\n\n AbstractMatrix.prototype.xorS = function xorS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) ^ value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.xorM = function xorM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) ^ matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.xor = function xor(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.xor(value);\n };\n\n AbstractMatrix.prototype.leftShift = function leftShift(value) {\n if (typeof value === 'number') return this.leftShiftS(value);\n return this.leftShiftM(value);\n };\n\n AbstractMatrix.prototype.leftShiftS = function leftShiftS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) << value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.leftShiftM = function leftShiftM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) << matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.leftShift = function leftShift(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.leftShift(value);\n };\n\n AbstractMatrix.prototype.signPropagatingRightShift = function signPropagatingRightShift(value) {\n if (typeof value === 'number') return this.signPropagatingRightShiftS(value);\n return this.signPropagatingRightShiftM(value);\n };\n\n AbstractMatrix.prototype.signPropagatingRightShiftS = function signPropagatingRightShiftS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) >> value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.signPropagatingRightShiftM = function signPropagatingRightShiftM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) >> matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.signPropagatingRightShift = function signPropagatingRightShift(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.signPropagatingRightShift(value);\n };\n\n AbstractMatrix.prototype.rightShift = function rightShift(value) {\n if (typeof value === 'number') return this.rightShiftS(value);\n return this.rightShiftM(value);\n };\n\n AbstractMatrix.prototype.rightShiftS = function rightShiftS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) >>> value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.rightShiftM = function rightShiftM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) >>> matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.rightShift = function rightShift(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.rightShift(value);\n };\n AbstractMatrix.prototype.zeroFillRightShift = AbstractMatrix.prototype.rightShift;\n AbstractMatrix.prototype.zeroFillRightShiftS = AbstractMatrix.prototype.rightShiftS;\n AbstractMatrix.prototype.zeroFillRightShiftM = AbstractMatrix.prototype.rightShiftM;\n AbstractMatrix.zeroFillRightShift = AbstractMatrix.rightShift;\n\n AbstractMatrix.prototype.not = function not() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, ~(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.not = function not(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.not();\n };\n\n AbstractMatrix.prototype.abs = function abs() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.abs(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.abs = function abs(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.abs();\n };\n\n AbstractMatrix.prototype.acos = function acos() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.acos(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.acos = function acos(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.acos();\n };\n\n AbstractMatrix.prototype.acosh = function acosh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.acosh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.acosh = function acosh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.acosh();\n };\n\n AbstractMatrix.prototype.asin = function asin() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.asin(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.asin = function asin(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.asin();\n };\n\n AbstractMatrix.prototype.asinh = function asinh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.asinh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.asinh = function asinh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.asinh();\n };\n\n AbstractMatrix.prototype.atan = function atan() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.atan(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.atan = function atan(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.atan();\n };\n\n AbstractMatrix.prototype.atanh = function atanh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.atanh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.atanh = function atanh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.atanh();\n };\n\n AbstractMatrix.prototype.cbrt = function cbrt() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.cbrt(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.cbrt = function cbrt(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.cbrt();\n };\n\n AbstractMatrix.prototype.ceil = function ceil() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.ceil(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.ceil = function ceil(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.ceil();\n };\n\n AbstractMatrix.prototype.clz32 = function clz32() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.clz32(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.clz32 = function clz32(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.clz32();\n };\n\n AbstractMatrix.prototype.cos = function cos() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.cos(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.cos = function cos(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.cos();\n };\n\n AbstractMatrix.prototype.cosh = function cosh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.cosh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.cosh = function cosh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.cosh();\n };\n\n AbstractMatrix.prototype.exp = function exp() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.exp(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.exp = function exp(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.exp();\n };\n\n AbstractMatrix.prototype.expm1 = function expm1() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.expm1(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.expm1 = function expm1(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.expm1();\n };\n\n AbstractMatrix.prototype.floor = function floor() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.floor(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.floor = function floor(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.floor();\n };\n\n AbstractMatrix.prototype.fround = function fround() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.fround(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.fround = function fround(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.fround();\n };\n\n AbstractMatrix.prototype.log = function log() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.log(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.log = function log(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.log();\n };\n\n AbstractMatrix.prototype.log1p = function log1p() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.log1p(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.log1p = function log1p(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.log1p();\n };\n\n AbstractMatrix.prototype.log10 = function log10() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.log10(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.log10 = function log10(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.log10();\n };\n\n AbstractMatrix.prototype.log2 = function log2() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.log2(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.log2 = function log2(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.log2();\n };\n\n AbstractMatrix.prototype.round = function round() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.round(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.round = function round(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.round();\n };\n\n AbstractMatrix.prototype.sign = function sign() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.sign(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.sign = function sign(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sign();\n };\n\n AbstractMatrix.prototype.sin = function sin() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.sin(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.sin = function sin(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sin();\n };\n\n AbstractMatrix.prototype.sinh = function sinh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.sinh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.sinh = function sinh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sinh();\n };\n\n AbstractMatrix.prototype.sqrt = function sqrt() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.sqrt(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.sqrt = function sqrt(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sqrt();\n };\n\n AbstractMatrix.prototype.tan = function tan() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.tan(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.tan = function tan(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.tan();\n };\n\n AbstractMatrix.prototype.tanh = function tanh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.tanh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.tanh = function tanh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.tanh();\n };\n\n AbstractMatrix.prototype.trunc = function trunc() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.trunc(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.trunc = function trunc(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.trunc();\n };\n\n AbstractMatrix.pow = function pow(matrix, arg0) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.pow(arg0);\n };\n\n AbstractMatrix.prototype.pow = function pow(value) {\n if (typeof value === 'number') return this.powS(value);\n return this.powM(value);\n };\n\n AbstractMatrix.prototype.powS = function powS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.pow(this.get(i, j), value));\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.powM = function powM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.pow(this.get(i, j), matrix.get(i, j)));\n }\n }\n return this;\n };\n}\n","import rescale from 'ml-array-rescale';\n\nimport {\n checkRowVector,\n checkRowIndex,\n checkColumnIndex,\n checkColumnVector,\n checkRange,\n checkIndices,\n} from './util';\nimport {\n sumByRow,\n sumByColumn,\n sumAll,\n productByRow,\n productByColumn,\n productAll,\n varianceByRow,\n varianceByColumn,\n varianceAll,\n centerByRow,\n centerByColumn,\n centerAll,\n scaleByRow,\n scaleByColumn,\n scaleAll,\n getScaleByRow,\n getScaleByColumn,\n getScaleAll,\n} from './stat';\nimport { inspectMatrix } from './inspect';\nimport { installMathOperations } from './mathOperations';\n\nexport class AbstractMatrix {\n static from1DArray(newRows, newColumns, newData) {\n let length = newRows * newColumns;\n if (length !== newData.length) {\n throw new RangeError('data length does not match given dimensions');\n }\n let newMatrix = new Matrix(newRows, newColumns);\n for (let row = 0; row < newRows; row++) {\n for (let column = 0; column < newColumns; column++) {\n newMatrix.set(row, column, newData[row * newColumns + column]);\n }\n }\n return newMatrix;\n }\n\n static rowVector(newData) {\n let vector = new Matrix(1, newData.length);\n for (let i = 0; i < newData.length; i++) {\n vector.set(0, i, newData[i]);\n }\n return vector;\n }\n\n static columnVector(newData) {\n let vector = new Matrix(newData.length, 1);\n for (let i = 0; i < newData.length; i++) {\n vector.set(i, 0, newData[i]);\n }\n return vector;\n }\n\n static zeros(rows, columns) {\n return new Matrix(rows, columns);\n }\n\n static ones(rows, columns) {\n return new Matrix(rows, columns).fill(1);\n }\n\n static rand(rows, columns, options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { random = Math.random } = options;\n let matrix = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n matrix.set(i, j, random());\n }\n }\n return matrix;\n }\n\n static randInt(rows, columns, options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1000, random = Math.random } = options;\n if (!Number.isInteger(min)) throw new TypeError('min must be an integer');\n if (!Number.isInteger(max)) throw new TypeError('max must be an integer');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let interval = max - min;\n let matrix = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n let value = min + Math.round(random() * interval);\n matrix.set(i, j, value);\n }\n }\n return matrix;\n }\n\n static eye(rows, columns, value) {\n if (columns === undefined) columns = rows;\n if (value === undefined) value = 1;\n let min = Math.min(rows, columns);\n let matrix = this.zeros(rows, columns);\n for (let i = 0; i < min; i++) {\n matrix.set(i, i, value);\n }\n return matrix;\n }\n\n static diag(data, rows, columns) {\n let l = data.length;\n if (rows === undefined) rows = l;\n if (columns === undefined) columns = rows;\n let min = Math.min(l, rows, columns);\n let matrix = this.zeros(rows, columns);\n for (let i = 0; i < min; i++) {\n matrix.set(i, i, data[i]);\n }\n return matrix;\n }\n\n static min(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n let rows = matrix1.rows;\n let columns = matrix1.columns;\n let result = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let 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 static max(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n let rows = matrix1.rows;\n let columns = matrix1.columns;\n let result = new this(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let 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 static checkMatrix(value) {\n return AbstractMatrix.isMatrix(value) ? value : new Matrix(value);\n }\n\n static isMatrix(value) {\n return value != null && value.klass === 'Matrix';\n }\n\n get size() {\n return this.rows * this.columns;\n }\n\n apply(callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('callback must be a function');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n callback.call(this, i, j);\n }\n }\n return this;\n }\n\n to1DArray() {\n let array = [];\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n array.push(this.get(i, j));\n }\n }\n return array;\n }\n\n to2DArray() {\n let copy = [];\n for (let i = 0; i < this.rows; i++) {\n copy.push([]);\n for (let j = 0; j < this.columns; j++) {\n copy[i].push(this.get(i, j));\n }\n }\n return copy;\n }\n\n toJSON() {\n return this.to2DArray();\n }\n\n isRowVector() {\n return this.rows === 1;\n }\n\n isColumnVector() {\n return this.columns === 1;\n }\n\n isVector() {\n return this.rows === 1 || this.columns === 1;\n }\n\n isSquare() {\n return this.rows === this.columns;\n }\n\n isSymmetric() {\n if (this.isSquare()) {\n for (let i = 0; i < this.rows; i++) {\n for (let 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 isEchelonForm() {\n let i = 0;\n let j = 0;\n let previousColumn = -1;\n let isEchelonForm = true;\n let checked = false;\n while (i < this.rows && isEchelonForm) {\n j = 0;\n checked = false;\n while (j < this.columns && checked === false) {\n if (this.get(i, j) === 0) {\n j++;\n } else if (this.get(i, j) === 1 && j > previousColumn) {\n checked = true;\n previousColumn = j;\n } else {\n isEchelonForm = false;\n checked = true;\n }\n }\n i++;\n }\n return isEchelonForm;\n }\n\n isReducedEchelonForm() {\n let i = 0;\n let j = 0;\n let previousColumn = -1;\n let isReducedEchelonForm = true;\n let checked = false;\n while (i < this.rows && isReducedEchelonForm) {\n j = 0;\n checked = false;\n while (j < this.columns && checked === false) {\n if (this.get(i, j) === 0) {\n j++;\n } else if (this.get(i, j) === 1 && j > previousColumn) {\n checked = true;\n previousColumn = j;\n } else {\n isReducedEchelonForm = false;\n checked = true;\n }\n }\n for (let k = j + 1; k < this.rows; k++) {\n if (this.get(i, k) !== 0) {\n isReducedEchelonForm = false;\n }\n }\n i++;\n }\n return isReducedEchelonForm;\n }\n\n echelonForm() {\n let result = this.clone();\n let h = 0;\n let k = 0;\n while (h < result.rows && k < result.columns) {\n let iMax = h;\n for (let i = h; i < result.rows; i++) {\n if (result.get(i, k) > result.get(iMax, k)) {\n iMax = i;\n }\n }\n if (result.get(iMax, k) === 0) {\n k++;\n } else {\n result.swapRows(h, iMax);\n let tmp = result.get(h, k);\n for (let j = k; j < result.columns; j++) {\n result.set(h, j, result.get(h, j) / tmp);\n }\n for (let i = h + 1; i < result.rows; i++) {\n let factor = result.get(i, k) / result.get(h, k);\n result.set(i, k, 0);\n for (let j = k + 1; j < result.columns; j++) {\n result.set(i, j, result.get(i, j) - result.get(h, j) * factor);\n }\n }\n h++;\n k++;\n }\n }\n return result;\n }\n\n reducedEchelonForm() {\n let result = this.echelonForm();\n let m = result.columns;\n let n = result.rows;\n let h = n - 1;\n while (h >= 0) {\n if (result.maxRow(h) === 0) {\n h--;\n } else {\n let p = 0;\n let pivot = false;\n while (p < n && pivot === false) {\n if (result.get(h, p) === 1) {\n pivot = true;\n } else {\n p++;\n }\n }\n for (let i = 0; i < h; i++) {\n let factor = result.get(i, p);\n for (let j = p; j < m; j++) {\n let tmp = result.get(i, j) - factor * result.get(h, j);\n result.set(i, j, tmp);\n }\n }\n h--;\n }\n }\n return result;\n }\n\n set() {\n throw new Error('set method is unimplemented');\n }\n\n get() {\n throw new Error('get method is unimplemented');\n }\n\n repeat(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { rows = 1, columns = 1 } = options;\n if (!Number.isInteger(rows) || rows <= 0) {\n throw new TypeError('rows must be a positive integer');\n }\n if (!Number.isInteger(columns) || columns <= 0) {\n throw new TypeError('columns must be a positive integer');\n }\n let matrix = new Matrix(this.rows * rows, this.columns * columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\n }\n }\n return matrix;\n }\n\n fill(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, value);\n }\n }\n return this;\n }\n\n neg() {\n return this.mulS(-1);\n }\n\n getRow(index) {\n checkRowIndex(this, index);\n let row = [];\n for (let i = 0; i < this.columns; i++) {\n row.push(this.get(index, i));\n }\n return row;\n }\n\n getRowVector(index) {\n return Matrix.rowVector(this.getRow(index));\n }\n\n setRow(index, array) {\n checkRowIndex(this, index);\n array = checkRowVector(this, array);\n for (let i = 0; i < this.columns; i++) {\n this.set(index, i, array[i]);\n }\n return this;\n }\n\n swapRows(row1, row2) {\n checkRowIndex(this, row1);\n checkRowIndex(this, row2);\n for (let i = 0; i < this.columns; i++) {\n let 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 getColumn(index) {\n checkColumnIndex(this, index);\n let column = [];\n for (let i = 0; i < this.rows; i++) {\n column.push(this.get(i, index));\n }\n return column;\n }\n\n getColumnVector(index) {\n return Matrix.columnVector(this.getColumn(index));\n }\n\n setColumn(index, array) {\n checkColumnIndex(this, index);\n array = checkColumnVector(this, array);\n for (let i = 0; i < this.rows; i++) {\n this.set(i, index, array[i]);\n }\n return this;\n }\n\n swapColumns(column1, column2) {\n checkColumnIndex(this, column1);\n checkColumnIndex(this, column2);\n for (let i = 0; i < this.rows; i++) {\n let 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 addRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 subRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 mulRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 divRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 addColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 subColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 mulColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 divColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 mulRow(index, value) {\n checkRowIndex(this, index);\n for (let i = 0; i < this.columns; i++) {\n this.set(index, i, this.get(index, i) * value);\n }\n return this;\n }\n\n mulColumn(index, value) {\n checkColumnIndex(this, index);\n for (let i = 0; i < this.rows; i++) {\n this.set(i, index, this.get(i, index) * value);\n }\n return this;\n }\n\n max() {\n let v = this.get(0, 0);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 maxIndex() {\n let v = this.get(0, 0);\n let idx = [0, 0];\n for (let i = 0; i < this.rows; i++) {\n for (let 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 min() {\n let v = this.get(0, 0);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 minIndex() {\n let v = this.get(0, 0);\n let idx = [0, 0];\n for (let i = 0; i < this.rows; i++) {\n for (let 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 maxRow(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n for (let 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 maxRowIndex(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n let idx = [row, 0];\n for (let 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 minRow(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n for (let 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 minRowIndex(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n let idx = [row, 0];\n for (let 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 maxColumn(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n for (let 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 maxColumnIndex(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n let idx = [0, column];\n for (let 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 minColumn(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n for (let 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 minColumnIndex(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n let idx = [0, column];\n for (let 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 diag() {\n let min = Math.min(this.rows, this.columns);\n let diag = [];\n for (let i = 0; i < min; i++) {\n diag.push(this.get(i, i));\n }\n return diag;\n }\n\n norm(type = 'frobenius') {\n let result = 0;\n if (type === 'max') {\n return this.max();\n } else if (type === 'frobenius') {\n for (let i = 0; i < this.rows; i++) {\n for (let 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 cumulativeSum() {\n let sum = 0;\n for (let i = 0; i < this.rows; i++) {\n for (let 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 dot(vector2) {\n if (AbstractMatrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\n let vector1 = this.to1DArray();\n if (vector1.length !== vector2.length) {\n throw new RangeError('vectors do not have the same size');\n }\n let dot = 0;\n for (let i = 0; i < vector1.length; i++) {\n dot += vector1[i] * vector2[i];\n }\n return dot;\n }\n\n mmul(other) {\n other = Matrix.checkMatrix(other);\n\n let m = this.rows;\n let n = this.columns;\n let p = other.columns;\n\n let result = new Matrix(m, p);\n\n let Bcolj = new Float64Array(n);\n for (let j = 0; j < p; j++) {\n for (let k = 0; k < n; k++) {\n Bcolj[k] = other.get(k, j);\n }\n\n for (let i = 0; i < m; i++) {\n let s = 0;\n for (let 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 other = Matrix.checkMatrix(other);\n let result = new Matrix(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 other = Matrix.checkMatrix(other);\n let result = new Matrix(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 mmulStrassen(y) {\n y = Matrix.checkMatrix(y);\n let x = this.clone();\n let r1 = x.rows;\n let c1 = x.columns;\n let r2 = y.rows;\n let c2 = y.columns;\n if (c1 !== r2) {\n // eslint-disable-next-line no-console\n console.warn(\n `Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`,\n );\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 let r = mat.rows;\n let c = mat.columns;\n if (r === rows && c === cols) {\n return mat;\n } else {\n let resultat = AbstractMatrix.zeros(rows, cols);\n resultat = resultat.setSubMatrix(mat, 0, 0);\n return resultat;\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 let r = Math.max(r1, r2);\n let 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 let halfRows = parseInt(a.rows / 2, 10);\n let halfCols = parseInt(a.columns / 2, 10);\n // Subdivide input matrices.\n let a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n let b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n\n let a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\n let b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\n\n let a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\n let b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\n\n let a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\n let b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\n\n // Compute intermediate values.\n let m1 = blockMult(\n AbstractMatrix.add(a11, a22),\n AbstractMatrix.add(b11, b22),\n halfRows,\n halfCols,\n );\n let m2 = blockMult(AbstractMatrix.add(a21, a22), b11, halfRows, halfCols);\n let m3 = blockMult(a11, AbstractMatrix.sub(b12, b22), halfRows, halfCols);\n let m4 = blockMult(a22, AbstractMatrix.sub(b21, b11), halfRows, halfCols);\n let m5 = blockMult(AbstractMatrix.add(a11, a12), b22, halfRows, halfCols);\n let m6 = blockMult(\n AbstractMatrix.sub(a21, a11),\n AbstractMatrix.add(b11, b12),\n halfRows,\n halfCols,\n );\n let m7 = blockMult(\n AbstractMatrix.sub(a12, a22),\n AbstractMatrix.add(b21, b22),\n halfRows,\n halfCols,\n );\n\n // Combine intermediate values into the output.\n let c11 = AbstractMatrix.add(m1, m4);\n c11.sub(m5);\n c11.add(m7);\n let c12 = AbstractMatrix.add(m3, m5);\n let c21 = AbstractMatrix.add(m2, m4);\n let c22 = AbstractMatrix.sub(m1, m2);\n c22.add(m3);\n c22.add(m6);\n\n // Crop output to the desired size (undo dynamic padding).\n let resultat = AbstractMatrix.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 scaleRows(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1 } = options;\n if (!Number.isFinite(min)) throw new TypeError('min must be a number');\n if (!Number.isFinite(max)) throw new TypeError('max must be a number');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let i = 0; i < this.rows; i++) {\n const row = this.getRow(i);\n rescale(row, { min, max, output: row });\n newMatrix.setRow(i, row);\n }\n return newMatrix;\n }\n\n scaleColumns(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1 } = options;\n if (!Number.isFinite(min)) throw new TypeError('min must be a number');\n if (!Number.isFinite(max)) throw new TypeError('max must be a number');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let i = 0; i < this.columns; i++) {\n const column = this.getColumn(i);\n rescale(column, {\n min: min,\n max: max,\n output: column,\n });\n newMatrix.setColumn(i, column);\n }\n return newMatrix;\n }\n\n flipRows() {\n const middle = Math.ceil(this.columns / 2);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < middle; j++) {\n let first = this.get(i, j);\n let last = this.get(i, this.columns - 1 - j);\n this.set(i, j, last);\n this.set(i, this.columns - 1 - j, first);\n }\n }\n return this;\n }\n\n flipColumns() {\n const middle = Math.ceil(this.rows / 2);\n for (let j = 0; j < this.columns; j++) {\n for (let i = 0; i < middle; i++) {\n let first = this.get(i, j);\n let last = this.get(this.rows - 1 - i, j);\n this.set(i, j, last);\n this.set(this.rows - 1 - i, j, first);\n }\n }\n return this;\n }\n\n kroneckerProduct(other) {\n other = Matrix.checkMatrix(other);\n\n let m = this.rows;\n let n = this.columns;\n let p = other.rows;\n let q = other.columns;\n\n let result = new Matrix(m * p, n * q);\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n for (let k = 0; k < p; k++) {\n for (let l = 0; l < q; l++) {\n result.set(p * i + k, q * j + l, this.get(i, j) * other.get(k, l));\n }\n }\n }\n }\n return result;\n }\n\n transpose() {\n let result = new Matrix(this.columns, this.rows);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n result.set(j, i, this.get(i, j));\n }\n }\n return result;\n }\n\n sortRows(compareFunction = compareNumbers) {\n for (let i = 0; i < this.rows; i++) {\n this.setRow(i, this.getRow(i).sort(compareFunction));\n }\n return this;\n }\n\n sortColumns(compareFunction = compareNumbers) {\n for (let i = 0; i < this.columns; i++) {\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\n }\n return this;\n }\n\n subMatrix(startRow, endRow, startColumn, endColumn) {\n checkRange(this, startRow, endRow, startColumn, endColumn);\n let newMatrix = new Matrix(\n endRow - startRow + 1,\n endColumn - startColumn + 1,\n );\n for (let i = startRow; i <= endRow; i++) {\n for (let j = startColumn; j <= endColumn; j++) {\n newMatrix.set(i - startRow, j - startColumn, this.get(i, j));\n }\n }\n return newMatrix;\n }\n\n subMatrixRow(indices, startColumn, endColumn) {\n if (startColumn === undefined) startColumn = 0;\n if (endColumn === undefined) endColumn = this.columns - 1;\n if (\n startColumn > endColumn ||\n startColumn < 0 ||\n startColumn >= this.columns ||\n endColumn < 0 ||\n endColumn >= this.columns\n ) {\n throw new RangeError('Argument out of range');\n }\n\n let newMatrix = new Matrix(indices.length, endColumn - startColumn + 1);\n for (let i = 0; i < indices.length; i++) {\n for (let 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 subMatrixColumn(indices, startRow, endRow) {\n if (startRow === undefined) startRow = 0;\n if (endRow === undefined) endRow = this.rows - 1;\n if (\n startRow > endRow ||\n startRow < 0 ||\n startRow >= this.rows ||\n endRow < 0 ||\n endRow >= this.rows\n ) {\n throw new RangeError('Argument out of range');\n }\n\n let newMatrix = new Matrix(endRow - startRow + 1, indices.length);\n for (let i = 0; i < indices.length; i++) {\n for (let 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 setSubMatrix(matrix, startRow, startColumn) {\n matrix = Matrix.checkMatrix(matrix);\n let endRow = startRow + matrix.rows - 1;\n let endColumn = startColumn + matrix.columns - 1;\n checkRange(this, startRow, endRow, startColumn, endColumn);\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n this.set(startRow + i, startColumn + j, matrix.get(i, j));\n }\n }\n return this;\n }\n\n selection(rowIndices, columnIndices) {\n let indices = checkIndices(this, rowIndices, columnIndices);\n let newMatrix = new Matrix(rowIndices.length, columnIndices.length);\n for (let i = 0; i < indices.row.length; i++) {\n let rowIndex = indices.row[i];\n for (let j = 0; j < indices.column.length; j++) {\n let columnIndex = indices.column[j];\n newMatrix.set(i, j, this.get(rowIndex, columnIndex));\n }\n }\n return newMatrix;\n }\n\n trace() {\n let min = Math.min(this.rows, this.columns);\n let trace = 0;\n for (let i = 0; i < min; i++) {\n trace += this.get(i, i);\n }\n return trace;\n }\n\n clone() {\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let row = 0; row < this.rows; row++) {\n for (let column = 0; column < this.columns; column++) {\n newMatrix.set(row, column, this.get(row, column));\n }\n }\n return newMatrix;\n }\n\n sum(by) {\n switch (by) {\n case 'row':\n return sumByRow(this);\n case 'column':\n return sumByColumn(this);\n case undefined:\n return sumAll(this);\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n product(by) {\n switch (by) {\n case 'row':\n return productByRow(this);\n case 'column':\n return productByColumn(this);\n case undefined:\n return productAll(this);\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n mean(by) {\n const sum = this.sum(by);\n switch (by) {\n case 'row': {\n for (let i = 0; i < this.rows; i++) {\n sum[i] /= this.columns;\n }\n return sum;\n }\n case 'column': {\n for (let i = 0; i < this.columns; i++) {\n sum[i] /= this.rows;\n }\n return sum;\n }\n case undefined:\n return sum / this.size;\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n variance(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { unbiased = true, mean = this.mean(by) } = options;\n if (typeof unbiased !== 'boolean') {\n throw new TypeError('unbiased must be a boolean');\n }\n switch (by) {\n case 'row': {\n if (!Array.isArray(mean)) {\n throw new TypeError('mean must be an array');\n }\n return varianceByRow(this, unbiased, mean);\n }\n case 'column': {\n if (!Array.isArray(mean)) {\n throw new TypeError('mean must be an array');\n }\n return varianceByColumn(this, unbiased, mean);\n }\n case undefined: {\n if (typeof mean !== 'number') {\n throw new TypeError('mean must be a number');\n }\n return varianceAll(this, unbiased, mean);\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n standardDeviation(by, options) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n const variance = this.variance(by, options);\n if (by === undefined) {\n return Math.sqrt(variance);\n } else {\n for (let i = 0; i < variance.length; i++) {\n variance[i] = Math.sqrt(variance[i]);\n }\n return variance;\n }\n }\n\n center(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { center = this.mean(by) } = options;\n switch (by) {\n case 'row': {\n if (!Array.isArray(center)) {\n throw new TypeError('center must be an array');\n }\n centerByRow(this, center);\n return this;\n }\n case 'column': {\n if (!Array.isArray(center)) {\n throw new TypeError('center must be an array');\n }\n centerByColumn(this, center);\n return this;\n }\n case undefined: {\n if (typeof center !== 'number') {\n throw new TypeError('center must be a number');\n }\n centerAll(this, center);\n return this;\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n scale(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n let scale = options.scale;\n switch (by) {\n case 'row': {\n if (scale === undefined) {\n scale = getScaleByRow(this);\n } else if (!Array.isArray(scale)) {\n throw new TypeError('scale must be an array');\n }\n scaleByRow(this, scale);\n return this;\n }\n case 'column': {\n if (scale === undefined) {\n scale = getScaleByColumn(this);\n } else if (!Array.isArray(scale)) {\n throw new TypeError('scale must be an array');\n }\n scaleByColumn(this, scale);\n return this;\n }\n case undefined: {\n if (scale === undefined) {\n scale = getScaleAll(this);\n } else if (typeof scale !== 'number') {\n throw new TypeError('scale must be a number');\n }\n scaleAll(this, scale);\n return this;\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n}\n\nAbstractMatrix.prototype.klass = 'Matrix';\nif (typeof Symbol !== 'undefined') {\n AbstractMatrix.prototype[\n Symbol.for('nodejs.util.inspect.custom')\n ] = inspectMatrix;\n}\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\n// Synonyms\nAbstractMatrix.random = AbstractMatrix.rand;\nAbstractMatrix.randomInt = AbstractMatrix.randInt;\nAbstractMatrix.diagonal = AbstractMatrix.diag;\nAbstractMatrix.prototype.diagonal = AbstractMatrix.prototype.diag;\nAbstractMatrix.identity = AbstractMatrix.eye;\nAbstractMatrix.prototype.negate = AbstractMatrix.prototype.neg;\nAbstractMatrix.prototype.tensorProduct =\n AbstractMatrix.prototype.kroneckerProduct;\n\nexport default class Matrix extends AbstractMatrix {\n constructor(nRows, nColumns) {\n super();\n if (Matrix.isMatrix(nRows)) {\n return nRows.clone();\n } else if (Number.isInteger(nRows) && nRows > 0) {\n // Create an empty matrix\n this.data = [];\n if (Number.isInteger(nColumns) && nColumns > 0) {\n for (let i = 0; i < nRows; i++) {\n this.data.push(new Float64Array(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 arrayData = nRows;\n nRows = arrayData.length;\n nColumns = arrayData[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 this.data = [];\n for (let i = 0; i < nRows; i++) {\n if (arrayData[i].length !== nColumns) {\n throw new RangeError('Inconsistent array dimensions');\n }\n this.data.push(Float64Array.from(arrayData[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.data[rowIndex][columnIndex] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.data[rowIndex][columnIndex];\n }\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.data.splice(index, 1);\n this.rows -= 1;\n return this;\n }\n\n addRow(index, array) {\n if (array === undefined) {\n array = index;\n index = this.rows;\n }\n checkRowIndex(this, index, true);\n array = Float64Array.from(checkRowVector(this, array, true));\n this.data.splice(index, 0, array);\n this.rows += 1;\n return this;\n }\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 (let i = 0; i < this.rows; i++) {\n const newRow = new Float64Array(this.columns - 1);\n for (let j = 0; j < index; j++) {\n newRow[j] = this.data[i][j];\n }\n for (let j = index + 1; j < this.columns; j++) {\n newRow[j - 1] = this.data[i][j];\n }\n this.data[i] = newRow;\n }\n this.columns -= 1;\n return this;\n }\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 (let i = 0; i < this.rows; i++) {\n const newRow = new Float64Array(this.columns + 1);\n let j = 0;\n for (; j < index; j++) {\n newRow[j] = this.data[i][j];\n }\n newRow[j++] = array[i];\n for (; j < this.columns + 1; j++) {\n newRow[j] = this.data[i][j - 1];\n }\n this.data[i] = newRow;\n }\n this.columns += 1;\n return this;\n }\n}\n\ninstallMathOperations(AbstractMatrix, Matrix);\n","import { AbstractMatrix } 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","import { checkColumnIndex } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixColumnView extends BaseView {\n constructor(matrix, column) {\n checkColumnIndex(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","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 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 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 { checkRowIndex } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixRowView extends BaseView {\n constructor(matrix, row) {\n checkRowIndex(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","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 { checkIndices } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixSelectionView extends BaseView {\n constructor(matrix, rowIndices, columnIndices) {\n let 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","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","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 { AbstractMatrix } from '../matrix';\n\nexport default class WrapperMatrix1D extends AbstractMatrix {\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 let index = this._calculateIndex(rowIndex, columnIndex);\n this.data[index] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n let 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","import { AbstractMatrix } from '../matrix';\n\nexport default class WrapperMatrix2D extends AbstractMatrix {\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","import WrapperMatrix1D from './WrapperMatrix1D';\nimport WrapperMatrix2D from './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","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nexport default class LuDecomposition {\n constructor(matrix) {\n matrix = WrapperMatrix2D.checkMatrix(matrix);\n\n let lu = matrix.clone();\n let rows = lu.rows;\n let columns = lu.columns;\n let pivotVector = new Float64Array(rows);\n let pivotSign = 1;\n let i, j, k, p, s, t, v;\n let LUcolj, kmax;\n\n for (i = 0; i < rows; i++) {\n pivotVector[i] = i;\n }\n\n LUcolj = new Float64Array(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 isSingular() {\n let data = this.LU;\n let col = data.columns;\n for (let j = 0; j < col; j++) {\n if (data.get(j, j) === 0) {\n return true;\n }\n }\n return false;\n }\n\n solve(value) {\n value = Matrix.checkMatrix(value);\n\n let lu = this.LU;\n let 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 let count = value.columns;\n let X = value.subMatrixRow(this.pivotVector, 0, count - 1);\n let columns = lu.columns;\n let 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.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));\n }\n }\n }\n for (k = columns - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X.set(k, j, X.get(k, j) / lu.get(k, k));\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));\n }\n }\n }\n return X;\n }\n\n get determinant() {\n let data = this.LU;\n if (!data.isSquare()) {\n throw new Error('Matrix must be square');\n }\n let determinant = this.pivotSign;\n let col = data.columns;\n for (let j = 0; j < col; j++) {\n determinant *= data.get(j, j);\n }\n return determinant;\n }\n\n get lowerTriangularMatrix() {\n let data = this.LU;\n let rows = data.rows;\n let columns = data.columns;\n let X = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n if (i > j) {\n X.set(i, j, data.get(i, j));\n } else if (i === j) {\n X.set(i, j, 1);\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get upperTriangularMatrix() {\n let data = this.LU;\n let rows = data.rows;\n let columns = data.columns;\n let X = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n if (i <= j) {\n X.set(i, j, data.get(i, j));\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get pivotPermutationVector() {\n return Array.from(this.pivotVector);\n }\n}\n","export function hypotenuse(a, b) {\n let 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","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\n\nexport default class QrDecomposition {\n constructor(value) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n let qr = value.clone();\n let m = value.rows;\n let n = value.columns;\n let rdiag = new Float64Array(n);\n let i, j, k, s;\n\n for (k = 0; k < n; k++) {\n let 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 solve(value) {\n value = Matrix.checkMatrix(value);\n\n let qr = this.QR;\n let 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 let count = value.columns;\n let X = value.clone();\n let n = qr.columns;\n let 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.get(i, k) * X.get(i, j);\n }\n s = -s / qr.get(k, k);\n for (i = k; i < m; i++) {\n X.set(i, j, X.get(i, j) + s * qr.get(i, k));\n }\n }\n }\n for (k = n - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X.set(k, j, X.get(k, j) / this.Rdiag[k]);\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X.set(i, j, X.get(i, j) - X.get(k, j) * qr.get(i, k));\n }\n }\n }\n\n return X.subMatrix(0, n - 1, 0, count - 1);\n }\n\n isFullRank() {\n let columns = this.QR.columns;\n for (let i = 0; i < columns; i++) {\n if (this.Rdiag[i] === 0) {\n return false;\n }\n }\n return true;\n }\n\n get upperTriangularMatrix() {\n let qr = this.QR;\n let n = qr.columns;\n let X = new Matrix(n, n);\n let i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n if (i < j) {\n X.set(i, j, qr.get(i, j));\n } else if (i === j) {\n X.set(i, j, this.Rdiag[i]);\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get orthogonalMatrix() {\n let qr = this.QR;\n let rows = qr.rows;\n let columns = qr.columns;\n let X = new Matrix(rows, columns);\n let i, j, k, s;\n\n for (k = columns - 1; k >= 0; k--) {\n for (i = 0; i < rows; i++) {\n X.set(i, k, 0);\n }\n X.set(k, k, 1);\n for (j = k; j < columns; j++) {\n if (qr.get(k, k) !== 0) {\n s = 0;\n for (i = k; i < rows; i++) {\n s += qr.get(i, k) * X.get(i, j);\n }\n\n s = -s / qr.get(k, k);\n\n for (i = k; i < rows; i++) {\n X.set(i, j, X.get(i, j) + s * qr.get(i, k));\n }\n }\n }\n }\n return X;\n }\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\n\nexport default class SingularValueDecomposition {\n constructor(value, options = {}) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n let m = value.rows;\n let n = value.columns;\n\n const {\n computeLeftSingularVectors = true,\n computeRightSingularVectors = true,\n autoTranspose = false,\n } = options;\n\n let wantu = Boolean(computeLeftSingularVectors);\n let wantv = Boolean(computeRightSingularVectors);\n\n let swapped = false;\n let 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 let aux = wantu;\n wantu = wantv;\n wantv = aux;\n }\n } else {\n a = value.clone();\n }\n\n let nu = Math.min(m, n);\n let ni = Math.min(m + 1, n);\n let s = new Float64Array(ni);\n let U = new Matrix(m, nu);\n let V = new Matrix(n, n);\n\n let e = new Float64Array(n);\n let work = new Float64Array(m);\n\n let si = new Float64Array(ni);\n for (let i = 0; i < ni; i++) si[i] = i;\n\n let nct = Math.min(m - 1, n);\n let nrt = Math.max(0, Math.min(n - 2, m));\n let 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.get(i, k));\n }\n if (s[k] !== 0) {\n if (a.get(k, k) < 0) {\n s[k] = -s[k];\n }\n for (let i = k; i < m; i++) {\n a.set(i, k, a.get(i, k) / s[k]);\n }\n a.set(k, k, a.get(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.get(i, k) * a.get(i, j);\n }\n t = -t / a.get(k, k);\n for (let i = k; i < m; i++) {\n a.set(i, j, a.get(i, j) + t * a.get(i, k));\n }\n }\n e[j] = a.get(k, j);\n }\n\n if (wantu && k < nct) {\n for (let i = k; i < m; i++) {\n U.set(i, k, a.get(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.get(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.set(i, j, a.get(i, j) + t * work[i]);\n }\n }\n }\n if (wantv) {\n for (let i = k + 1; i < n; i++) {\n V.set(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.get(nct, nct);\n }\n if (m < p) {\n s[p - 1] = 0;\n }\n if (nrt + 1 < p) {\n e[nrt] = a.get(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.set(i, j, 0);\n }\n U.set(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.get(i, k) * U.get(i, j);\n }\n t = -t / U.get(k, k);\n for (let i = k; i < m; i++) {\n U.set(i, j, U.get(i, j) + t * U.get(i, k));\n }\n }\n for (let i = k; i < m; i++) {\n U.set(i, k, -U.get(i, k));\n }\n U.set(k, k, 1 + U.get(k, k));\n for (let i = 0; i < k - 1; i++) {\n U.set(i, k, 0);\n }\n } else {\n for (let i = 0; i < m; i++) {\n U.set(i, k, 0);\n }\n U.set(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.get(i, k) * V.get(i, j);\n }\n t = -t / V.get(k + 1, k);\n for (let i = k + 1; i < n; i++) {\n V.set(i, j, V.get(i, j) + t * V.get(i, k));\n }\n }\n }\n for (let i = 0; i < n; i++) {\n V.set(i, k, 0);\n }\n V.set(k, k, 1);\n }\n }\n\n let pp = p - 1;\n let iter = 0;\n let 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.get(i, j) + sn * V.get(i, p - 1);\n V.set(i, p - 1, -sn * V.get(i, j) + cs * V.get(i, p - 1));\n V.set(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.get(i, j) + sn * U.get(i, k - 1);\n U.set(i, k - 1, -sn * U.get(i, j) + cs * U.get(i, k - 1));\n U.set(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.get(i, j) + sn * V.get(i, j + 1);\n V.set(i, j + 1, -sn * V.get(i, j) + cs * V.get(i, j + 1));\n V.set(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.get(i, j) + sn * U.get(i, j + 1);\n U.set(i, j + 1, -sn * U.get(i, j) + cs * U.get(i, j + 1));\n U.set(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.set(i, k, -V.get(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.get(i, k + 1);\n V.set(i, k + 1, V.get(i, k));\n V.set(i, k, t);\n }\n }\n if (wantu && k < m - 1) {\n for (let i = 0; i < m; i++) {\n t = U.get(i, k + 1);\n U.set(i, k + 1, U.get(i, k));\n U.set(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 let 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 solve(value) {\n let Y = value;\n let e = this.threshold;\n let scols = this.s.length;\n let Ls = Matrix.zeros(scols, scols);\n\n for (let i = 0; i < scols; i++) {\n if (Math.abs(this.s[i]) <= e) {\n Ls.set(i, i, 0);\n } else {\n Ls.set(i, i, 1 / this.s[i]);\n }\n }\n\n let U = this.U;\n let V = this.rightSingularVectors;\n\n let VL = V.mmul(Ls);\n let vrows = V.rows;\n let urows = U.rows;\n let 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.get(i, k) * U.get(j, k);\n }\n VLU.set(i, j, sum);\n }\n }\n\n return VLU.mmul(Y);\n }\n\n solveForDiagonal(value) {\n return this.solve(Matrix.diag(value));\n }\n\n inverse() {\n let V = this.V;\n let e = this.threshold;\n let vrows = V.rows;\n let vcols = V.columns;\n let 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.set(i, j, V.get(i, j) / this.s[j]);\n }\n }\n }\n\n let U = this.U;\n\n let urows = U.rows;\n let ucols = U.columns;\n let 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.get(i, k) * U.get(j, k);\n }\n Y.set(i, j, sum);\n }\n }\n\n return Y;\n }\n\n get condition() {\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\n }\n\n get norm2() {\n return this.s[0];\n }\n\n get rank() {\n let tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON;\n let r = 0;\n let s = this.s;\n for (let i = 0, ii = s.length; i < ii; i++) {\n if (s[i] > tol) {\n r++;\n }\n }\n return r;\n }\n\n get diagonal() {\n return Array.from(this.s);\n }\n\n get threshold() {\n return (Number.EPSILON / 2) * Math.max(this.m, this.n) * this.s[0];\n }\n\n get leftSingularVectors() {\n return this.U;\n }\n\n get rightSingularVectors() {\n return this.V;\n }\n\n get diagonalMatrix() {\n return Matrix.diag(this.s);\n }\n}\n","import LuDecomposition from './dc/lu';\nimport QrDecomposition from './dc/qr';\nimport SingularValueDecomposition from './dc/svd';\nimport Matrix from './matrix';\nimport WrapperMatrix2D from './wrap/WrapperMatrix2D';\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\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","import Matrix from './matrix';\nimport LuDecomposition from './dc/lu';\nimport MatrixSelectionView from './views/selection';\n\nexport function determinant(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (matrix.isSquare()) {\n let a, b, c, d;\n if (matrix.columns === 2) {\n // 2 x 2 matrix\n a = matrix.get(0, 0);\n b = matrix.get(0, 1);\n c = matrix.get(1, 0);\n d = matrix.get(1, 1);\n\n return a * d - b * c;\n } else if (matrix.columns === 3) {\n // 3 x 3 matrix\n let subMatrix0, subMatrix1, subMatrix2;\n subMatrix0 = new MatrixSelectionView(matrix, [1, 2], [1, 2]);\n subMatrix1 = new MatrixSelectionView(matrix, [1, 2], [0, 2]);\n subMatrix2 = new MatrixSelectionView(matrix, [1, 2], [0, 1]);\n a = matrix.get(0, 0);\n b = matrix.get(0, 1);\n c = matrix.get(0, 2);\n\n return (\n a * determinant(subMatrix0) -\n b * determinant(subMatrix1) +\n c * determinant(subMatrix2)\n );\n } else {\n // general purpose determinant using the LU decomposition\n return new LuDecomposition(matrix).determinant;\n }\n } else {\n throw Error('determinant can only be calculated for a square matrix');\n }\n}\n","import Matrix from './matrix';\nimport SingularValueDecomposition from './dc/svd';\n\nfunction xrange(n, exception) {\n let range = [];\n for (let i = 0; i < n; i++) {\n if (i !== exception) {\n range.push(i);\n }\n }\n return range;\n}\n\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 let returnArray = matrix.addRow(index, [0]);\n for (let 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\nexport function linearDependencies(matrix, options = {}) {\n const { thresholdValue = 10e-10, thresholdError = 10e-10 } = options;\n matrix = Matrix.checkMatrix(matrix);\n\n let n = matrix.rows;\n let results = new Matrix(n, n);\n\n for (let i = 0; i < n; i++) {\n let b = Matrix.columnVector(matrix.getRow(i));\n let Abis = matrix.subMatrixRow(xrange(n, i)).transpose();\n let svd = new SingularValueDecomposition(Abis);\n let x = svd.solve(b);\n let error = Matrix.sub(b, Abis.mmul(x))\n .abs()\n .max();\n results.setRow(\n i,\n dependenciesOneRow(error, x, i, thresholdValue, thresholdError),\n );\n }\n return results;\n}\n","import SVD from './dc/svd';\nimport Matrix from './matrix';\n\nexport function pseudoInverse(matrix, threshold = Number.EPSILON) {\n matrix = Matrix.checkMatrix(matrix);\n let svdSolution = new SVD(matrix, { autoTranspose: true });\n\n let U = svdSolution.leftSingularVectors;\n let V = svdSolution.rightSingularVectors;\n let s = svdSolution.diagonal;\n\n for (let 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 return V.mmul(Matrix.diag(s).mmul(U.transpose()));\n}\n","import Matrix from './matrix';\n\nexport function covariance(xMatrix, yMatrix = xMatrix, options = {}) {\n xMatrix = Matrix.checkMatrix(xMatrix);\n let yIsSame = false;\n if (\n typeof yMatrix === 'object' &&\n !Matrix.isMatrix(yMatrix) &&\n !Array.isArray(yMatrix)\n ) {\n options = yMatrix;\n yMatrix = xMatrix;\n yIsSame = true;\n } else {\n yMatrix = Matrix.checkMatrix(yMatrix);\n }\n if (xMatrix.rows !== yMatrix.rows) {\n throw new TypeError('Both matrices must have the same number of rows');\n }\n const { center = true } = options;\n if (center) {\n xMatrix = xMatrix.center('column');\n if (!yIsSame) {\n yMatrix = yMatrix.center('column');\n }\n }\n const cov = xMatrix.transpose().mmul(yMatrix);\n for (let i = 0; i < cov.rows; i++) {\n for (let j = 0; j < cov.columns; j++) {\n cov.set(i, j, cov.get(i, j) * (1 / (xMatrix.rows - 1)));\n }\n }\n return cov;\n}\n","import Matrix from './matrix';\n\nexport function correlation(xMatrix, yMatrix = xMatrix, options = {}) {\n xMatrix = Matrix.checkMatrix(xMatrix);\n let yIsSame = false;\n if (\n typeof yMatrix === 'object' &&\n !Matrix.isMatrix(yMatrix) &&\n !Array.isArray(yMatrix)\n ) {\n options = yMatrix;\n yMatrix = xMatrix;\n yIsSame = true;\n } else {\n yMatrix = Matrix.checkMatrix(yMatrix);\n }\n if (xMatrix.rows !== yMatrix.rows) {\n throw new TypeError('Both matrices must have the same number of rows');\n }\n\n const { center = true, scale = true } = options;\n if (center) {\n xMatrix.center('column');\n if (!yIsSame) {\n yMatrix.center('column');\n }\n }\n if (scale) {\n xMatrix.scale('column');\n if (!yIsSame) {\n yMatrix.scale('column');\n }\n }\n\n const sdx = xMatrix.standardDeviation('column', { unbiased: true });\n const sdy = yIsSame\n ? sdx\n : yMatrix.standardDeviation('column', { unbiased: true });\n\n const corr = xMatrix.transpose().mmul(yMatrix);\n for (let i = 0; i < corr.rows; i++) {\n for (let j = 0; j < corr.columns; j++) {\n corr.set(\n i,\n j,\n corr.get(i, j) * (1 / (sdx[i] * sdy[j])) * (1 / (xMatrix.rows - 1)),\n );\n }\n }\n return corr;\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\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 let n = matrix.columns;\n let V = new Matrix(n, n);\n let d = new Float64Array(n);\n let e = new Float64Array(n);\n let value = matrix;\n let i, j;\n\n let 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.set(i, j, value.get(i, j));\n }\n }\n tred2(n, e, d, V);\n tql2(n, e, d, V);\n } else {\n let H = new Matrix(n, n);\n let ort = new Float64Array(n);\n for (j = 0; j < n; j++) {\n for (i = 0; i < n; i++) {\n H.set(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 get realEigenvalues() {\n return Array.from(this.d);\n }\n\n get imaginaryEigenvalues() {\n return Array.from(this.e);\n }\n\n get eigenvectorMatrix() {\n return this.V;\n }\n\n get diagonalMatrix() {\n let n = this.n;\n let e = this.e;\n let d = this.d;\n let X = new Matrix(n, n);\n let i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n X.set(i, j, 0);\n }\n X.set(i, i, d[i]);\n if (e[i] > 0) {\n X.set(i, i + 1, e[i]);\n } else if (e[i] < 0) {\n X.set(i, i - 1, e[i]);\n }\n }\n return X;\n }\n}\n\nfunction tred2(n, e, d, V) {\n let f, g, h, i, j, k, hh, scale;\n\n for (j = 0; j < n; j++) {\n d[j] = V.get(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.get(i - 1, j);\n V.set(i, j, 0);\n V.set(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.set(j, i, f);\n g = e[j] + V.get(j, j) * f;\n for (k = j + 1; k <= i - 1; k++) {\n g += V.get(k, j) * d[k];\n e[k] += V.get(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.set(k, j, V.get(k, j) - (f * e[k] + g * d[k]));\n }\n d[j] = V.get(i - 1, j);\n V.set(i, j, 0);\n }\n }\n d[i] = h;\n }\n\n for (i = 0; i < n - 1; i++) {\n V.set(n - 1, i, V.get(i, i));\n V.set(i, i, 1);\n h = d[i + 1];\n if (h !== 0) {\n for (k = 0; k <= i; k++) {\n d[k] = V.get(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.get(k, i + 1) * V.get(k, j);\n }\n for (k = 0; k <= i; k++) {\n V.set(k, j, V.get(k, j) - g * d[k]);\n }\n }\n }\n\n for (k = 0; k <= i; k++) {\n V.set(k, i + 1, 0);\n }\n }\n\n for (j = 0; j < n; j++) {\n d[j] = V.get(n - 1, j);\n V.set(n - 1, j, 0);\n }\n\n V.set(n - 1, n - 1, 1);\n e[0] = 0;\n}\n\nfunction tql2(n, e, d, V) {\n let 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 let f = 0;\n let tst1 = 0;\n let 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.get(k, i + 1);\n V.set(k, i + 1, s * V.get(k, i) + c * h);\n V.set(k, i, c * V.get(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.get(j, i);\n V.set(j, i, V.get(j, k));\n V.set(j, k, p);\n }\n }\n }\n}\n\nfunction orthes(n, H, ort, V) {\n let low = 0;\n let high = n - 1;\n let f, g, h, i, j, m;\n let 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.get(i, m - 1));\n }\n\n if (scale !== 0) {\n h = 0;\n for (i = high; i >= m; i--) {\n ort[i] = H.get(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.get(i, j);\n }\n\n f = f / h;\n for (i = m; i <= high; i++) {\n H.set(i, j, H.get(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.get(i, j);\n }\n\n f = f / h;\n for (j = m; j <= high; j++) {\n H.set(i, j, H.get(i, j) - f * ort[j]);\n }\n }\n\n ort[m] = scale * ort[m];\n H.set(m, m - 1, scale * g);\n }\n }\n\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V.set(i, j, i === j ? 1 : 0);\n }\n }\n\n for (m = high - 1; m >= low + 1; m--) {\n if (H.get(m, m - 1) !== 0) {\n for (i = m + 1; i <= high; i++) {\n ort[i] = H.get(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.get(i, j);\n }\n\n g = g / ort[m] / H.get(m, m - 1);\n for (i = m; i <= high; i++) {\n V.set(i, j, V.get(i, j) + g * ort[i]);\n }\n }\n }\n }\n}\n\nfunction hqr2(nn, e, d, V, H) {\n let n = nn - 1;\n let low = 0;\n let high = nn - 1;\n let eps = Number.EPSILON;\n let exshift = 0;\n let norm = 0;\n let p = 0;\n let q = 0;\n let r = 0;\n let s = 0;\n let z = 0;\n let iter = 0;\n let i, j, k, l, m, t, w, x, y;\n let ra, sa, vr, vi;\n let notlast, cdivres;\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n d[i] = H.get(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.get(i, j));\n }\n }\n\n while (n >= low) {\n l = n;\n while (l > low) {\n s = Math.abs(H.get(l - 1, l - 1)) + Math.abs(H.get(l, l));\n if (s === 0) {\n s = norm;\n }\n if (Math.abs(H.get(l, l - 1)) < eps * s) {\n break;\n }\n l--;\n }\n\n if (l === n) {\n H.set(n, n, H.get(n, n) + exshift);\n d[n] = H.get(n, n);\n e[n] = 0;\n n--;\n iter = 0;\n } else if (l === n - 1) {\n w = H.get(n, n - 1) * H.get(n - 1, n);\n p = (H.get(n - 1, n - 1) - H.get(n, n)) / 2;\n q = p * p + w;\n z = Math.sqrt(Math.abs(q));\n H.set(n, n, H.get(n, n) + exshift);\n H.set(n - 1, n - 1, H.get(n - 1, n - 1) + exshift);\n x = H.get(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.get(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.get(n - 1, j);\n H.set(n - 1, j, q * z + p * H.get(n, j));\n H.set(n, j, q * H.get(n, j) - p * z);\n }\n\n for (i = 0; i <= n; i++) {\n z = H.get(i, n - 1);\n H.set(i, n - 1, q * z + p * H.get(i, n));\n H.set(i, n, q * H.get(i, n) - p * z);\n }\n\n for (i = low; i <= high; i++) {\n z = V.get(i, n - 1);\n V.set(i, n - 1, q * z + p * V.get(i, n));\n V.set(i, n, q * V.get(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.get(n, n);\n y = 0;\n w = 0;\n if (l < n) {\n y = H.get(n - 1, n - 1);\n w = H.get(n, n - 1) * H.get(n - 1, n);\n }\n\n if (iter === 10) {\n exshift += x;\n for (i = low; i <= n; i++) {\n H.set(i, i, H.get(i, i) - x);\n }\n s = Math.abs(H.get(n, n - 1)) + Math.abs(H.get(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.set(i, i, H.get(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.get(m, m);\n r = x - z;\n s = y - z;\n p = (r * s - w) / H.get(m + 1, m) + H.get(m, m + 1);\n q = H.get(m + 1, m + 1) - z - r - s;\n r = H.get(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.get(m, m - 1)) * (Math.abs(q) + Math.abs(r)) <\n eps *\n (Math.abs(p) *\n (Math.abs(H.get(m - 1, m - 1)) +\n Math.abs(z) +\n Math.abs(H.get(m + 1, m + 1))))\n ) {\n break;\n }\n m--;\n }\n\n for (i = m + 2; i <= n; i++) {\n H.set(i, i - 2, 0);\n if (i > m + 2) {\n H.set(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.get(k, k - 1);\n q = H.get(k + 1, k - 1);\n r = notlast ? H.get(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.set(k, k - 1, -s * x);\n } else if (l !== m) {\n H.set(k, k - 1, -H.get(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.get(k, j) + q * H.get(k + 1, j);\n if (notlast) {\n p = p + r * H.get(k + 2, j);\n H.set(k + 2, j, H.get(k + 2, j) - p * z);\n }\n\n H.set(k, j, H.get(k, j) - p * x);\n H.set(k + 1, j, H.get(k + 1, j) - p * y);\n }\n\n for (i = 0; i <= Math.min(n, k + 3); i++) {\n p = x * H.get(i, k) + y * H.get(i, k + 1);\n if (notlast) {\n p = p + z * H.get(i, k + 2);\n H.set(i, k + 2, H.get(i, k + 2) - p * r);\n }\n\n H.set(i, k, H.get(i, k) - p);\n H.set(i, k + 1, H.get(i, k + 1) - p * q);\n }\n\n for (i = low; i <= high; i++) {\n p = x * V.get(i, k) + y * V.get(i, k + 1);\n if (notlast) {\n p = p + z * V.get(i, k + 2);\n V.set(i, k + 2, V.get(i, k + 2) - p * r);\n }\n\n V.set(i, k, V.get(i, k) - p);\n V.set(i, k + 1, V.get(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.set(n, n, 1);\n for (i = n - 1; i >= 0; i--) {\n w = H.get(i, i) - p;\n r = 0;\n for (j = l; j <= n; j++) {\n r = r + H.get(i, j) * H.get(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.set(i, n, w !== 0 ? -r / w : -r / (eps * norm));\n } else {\n x = H.get(i, i + 1);\n y = H.get(i + 1, i);\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\n t = (x * s - z * r) / q;\n H.set(i, n, t);\n H.set(\n i + 1,\n n,\n Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z,\n );\n }\n\n t = Math.abs(H.get(i, n));\n if (eps * t * t > 1) {\n for (j = i; j <= n; j++) {\n H.set(j, n, H.get(j, n) / t);\n }\n }\n }\n }\n } else if (q < 0) {\n l = n - 1;\n\n if (Math.abs(H.get(n, n - 1)) > Math.abs(H.get(n - 1, n))) {\n H.set(n - 1, n - 1, q / H.get(n, n - 1));\n H.set(n - 1, n, -(H.get(n, n) - p) / H.get(n, n - 1));\n } else {\n cdivres = cdiv(0, -H.get(n - 1, n), H.get(n - 1, n - 1) - p, q);\n H.set(n - 1, n - 1, cdivres[0]);\n H.set(n - 1, n, cdivres[1]);\n }\n\n H.set(n, n - 1, 0);\n H.set(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.get(i, j) * H.get(j, n - 1);\n sa = sa + H.get(i, j) * H.get(j, n);\n }\n\n w = H.get(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.set(i, n - 1, cdivres[0]);\n H.set(i, n, cdivres[1]);\n } else {\n x = H.get(i, i + 1);\n y = H.get(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.set(i, n - 1, cdivres[0]);\n H.set(i, n, cdivres[1]);\n if (Math.abs(x) > Math.abs(z) + Math.abs(q)) {\n H.set(\n i + 1,\n n - 1,\n (-ra - w * H.get(i, n - 1) + q * H.get(i, n)) / x,\n );\n H.set(\n i + 1,\n n,\n (-sa - w * H.get(i, n) - q * H.get(i, n - 1)) / x,\n );\n } else {\n cdivres = cdiv(\n -r - y * H.get(i, n - 1),\n -s - y * H.get(i, n),\n z,\n q,\n );\n H.set(i + 1, n - 1, cdivres[0]);\n H.set(i + 1, n, cdivres[1]);\n }\n }\n\n t = Math.max(Math.abs(H.get(i, n - 1)), Math.abs(H.get(i, n)));\n if (eps * t * t > 1) {\n for (j = i; j <= n; j++) {\n H.set(j, n - 1, H.get(j, n - 1) / t);\n H.set(j, n, H.get(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.set(i, j, H.get(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.get(i, k) * H.get(k, j);\n }\n V.set(i, j, z);\n }\n }\n}\n\nfunction cdiv(xr, xi, yr, yi) {\n let 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","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\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 let a = value;\n let dimension = a.rows;\n let l = new Matrix(dimension, dimension);\n let positiveDefinite = true;\n let i, j, k;\n\n for (j = 0; j < dimension; j++) {\n let d = 0;\n for (k = 0; k < j; k++) {\n let s = 0;\n for (i = 0; i < k; i++) {\n s += l.get(k, i) * l.get(j, i);\n }\n s = (a.get(j, k) - s) / l.get(k, k);\n l.set(j, k, s);\n d = d + s * s;\n }\n\n d = a.get(j, j) - d;\n\n positiveDefinite &= d > 0;\n l.set(j, j, Math.sqrt(Math.max(d, 0)));\n for (k = j + 1; k < dimension; k++) {\n l.set(j, k, 0);\n }\n }\n\n this.L = l;\n this.positiveDefinite = Boolean(positiveDefinite);\n }\n\n isPositiveDefinite() {\n return this.positiveDefinite;\n }\n\n solve(value) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n let l = this.L;\n let dimension = l.rows;\n\n if (value.rows !== dimension) {\n throw new Error('Matrix dimensions do not match');\n }\n if (this.isPositiveDefinite() === false) {\n throw new Error('Matrix is not positive definite');\n }\n\n let count = value.columns;\n let B = value.clone();\n let 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.set(k, j, B.get(k, j) - B.get(i, j) * l.get(k, i));\n }\n B.set(k, j, B.get(k, j) / l.get(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.set(k, j, B.get(k, j) - B.get(i, j) * l.get(i, k));\n }\n B.set(k, j, B.get(k, j) / l.get(k, k));\n }\n }\n\n return B;\n }\n\n get lowerTriangularMatrix() {\n return this.L;\n }\n}\n","import WrapperMatrix2D from '../wrap/WrapperMatrix2D';\nimport Matrix from '../matrix';\n\nexport default class nipals {\n constructor(X, options = {}) {\n X = WrapperMatrix2D.checkMatrix(X);\n let { Y } = options;\n const {\n scaleScores = false,\n maxIterations = 1000,\n terminationCriteria = 1e-10,\n } = options;\n\n let u;\n if (Y) {\n if (Array.isArray(Y) && typeof Y[0] === 'number') {\n Y = Matrix.columnVector(Y);\n } else {\n Y = WrapperMatrix2D.checkMatrix(Y);\n }\n if (!Y.isColumnVector() || Y.rows !== X.rows) {\n throw new Error('Y must be a column vector of length X.rows');\n }\n u = Y;\n } else {\n u = X.getColumnVector(0);\n }\n\n let diff = 1;\n let t, q, w, tOld;\n\n for (\n let counter = 0;\n counter < maxIterations && diff > terminationCriteria;\n counter++\n ) {\n w = X.transpose()\n .mmul(u)\n .div(\n u\n .transpose()\n .mmul(u)\n .get(0, 0),\n );\n w = w.div(w.norm());\n\n t = X.mmul(w).div(\n w\n .transpose()\n .mmul(w)\n .get(0, 0),\n );\n\n if (counter > 0) {\n diff = t\n .clone()\n .sub(tOld)\n .pow(2)\n .sum();\n }\n tOld = t.clone();\n\n if (Y) {\n q = Y.transpose()\n .mmul(t)\n .div(\n t\n .transpose()\n .mmul(t)\n .get(0, 0),\n );\n q = q.div(q.norm());\n\n u = Y.mmul(q).div(\n q\n .transpose()\n .mmul(q)\n .get(0, 0),\n );\n } else {\n u = t;\n }\n }\n\n if (Y) {\n let p = X.transpose()\n .mmul(t)\n .div(\n t\n .transpose()\n .mmul(t)\n .get(0, 0),\n );\n p = p.div(p.norm());\n let xResidual = X.clone().sub(t.clone().mmul(p.transpose()));\n let residual = u\n .transpose()\n .mmul(t)\n .div(\n t\n .transpose()\n .mmul(t)\n .get(0, 0),\n );\n let yResidual = Y.clone().sub(\n t\n .clone()\n .mulS(residual.get(0, 0))\n .mmul(q.transpose()),\n );\n\n this.t = t;\n this.p = p.transpose();\n this.w = w.transpose();\n this.q = q;\n this.u = u;\n this.s = t.transpose().mmul(t);\n this.xResidual = xResidual;\n this.yResidual = yResidual;\n this.betas = residual;\n } else {\n this.w = w.transpose();\n this.s = t\n .transpose()\n .mmul(t)\n .sqrt();\n if (scaleScores) {\n this.t = t.clone().div(this.s.get(0, 0));\n } else {\n this.t = t;\n }\n this.xResidual = X.sub(t.mmul(w.transpose()));\n }\n }\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 sum(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 sumValue = 0;\n\n for (var i = 0; i < input.length; i++) {\n sumValue += input[i];\n }\n\n return sumValue;\n}\n\nexport default sum;\n","import sum from 'ml-array-sum';\n\n/**\n * Computes the mean of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction mean(input) {\n return sum(input) / input.length;\n}\n\nexport default mean;\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 let counts = new Array(numberOfClasses).fill(0);\n for (let 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 let probabilities = toDiscreteDistribution(\n array,\n getNumberOfClasses(array),\n ).getRow(0);\n\n let sum = 0.0;\n for (let 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\n .filter(function(val, i, arr) {\n return arr.indexOf(val) === i;\n })\n .map((val) => val + 1)\n .reduce((a, b) => Math.max(a, b));\n}\n\n/**\n * @private\n * Calculates the Gini Gain of an array of predictions and those predictions splitted by a feature.\n * @param {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 let splitsImpurity = 0.0;\n let splits = ['greater', 'lesser'];\n\n for (let i = 0; i < splits.length; ++i) {\n let currentSplit = splitted[splits[i]];\n splitsImpurity +=\n (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 let l = array.length;\n\n let m = meanArray(array);\n let error = 0.0;\n\n for (let i = 0; i < l; ++i) {\n let currentElement = array[i];\n error += (currentElement - m) * (currentElement - m);\n }\n\n return error;\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 let error = 0.0;\n let splits = ['greater', 'lesser'];\n\n for (let i = 0; i < splits.length; ++i) {\n let 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 let lesserX = [];\n let greaterX = [];\n let lesserY = [];\n let greaterY = [];\n\n for (let i = 0; i < X.rows; ++i) {\n if (X.get(i, column) < value) {\n lesserX.push(X.getRow(i));\n lesserY.push(y[i]);\n } else {\n greaterX.push(X.getRow(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(\n `Error on zip: the size of a: ${a.length} is different from b: ${b.length}`,\n );\n }\n\n let ret = new Array(a.length);\n for (let 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 mean from 'ml-array-mean';\n\nimport * as Utils from './utils';\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 * @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 // Depending in the node tree class, we set the variables to check information gain (to classify)\n // or error (for regression)\n\n let bestGain = this.kind === 'classifier' ? -Infinity : Infinity;\n let check = this.kind === 'classifier' ? (a, b) => a > b : (a, b) => a < b;\n\n let maxColumn;\n let maxValue;\n\n for (let i = 0; i < XTranspose.rows; ++i) {\n let currentFeature = XTranspose.getRow(i);\n let splitValues = this.featureSplit(currentFeature, y);\n for (let j = 0; j < splitValues.length; ++j) {\n let currentSplitVal = splitValues[j];\n let splitted = this.split(currentFeature, y, currentSplitVal);\n\n let 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 split(x, y, splitValue) {\n let lesser = [];\n let greater = [];\n\n for (let 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 let splitValues = [];\n let arr = Utils.zip(x, y);\n arr.sort(function(a, b) {\n return a[0] - b[0];\n });\n\n for (let i = 1; i < arr.length; ++i) {\n if (arr[i - 1][1] !== arr[i][1]) {\n splitValues.push(\n splitFunctions[this.splitFunction](arr[i - 1][0], arr[i][0]),\n );\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(\n y,\n Utils.getNumberOfClasses(y),\n );\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 let XTranspose = X.transpose();\n let split = this.bestSplit(XTranspose, y);\n\n this.splitValue = split.maxValue;\n this.splitColumn = split.maxColumn;\n this.gain = split.maxGain;\n\n let splittedMatrix = Utils.matrixSplitter(\n X,\n y,\n this.splitColumn,\n this.splitValue,\n );\n\n if (\n currentDepth < this.maxDepth &&\n (this.gain > 0.01 && this.gain !== parentGain) &&\n (splittedMatrix.lesserX.length > 0 && splittedMatrix.greaterX.length > 0)\n ) {\n this.left = new TreeNode(this);\n this.right = new TreeNode(this);\n\n let lesserX = new Matrix(splittedMatrix.lesserX);\n let greaterX = new Matrix(splittedMatrix.greaterX);\n\n this.left.train(\n lesserX,\n splittedMatrix.lesserY,\n currentDepth + 1,\n this.gain,\n );\n this.right.train(\n greaterX,\n splittedMatrix.greaterY,\n currentDepth + 1,\n this.gain,\n );\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 =\n node.distribution.constructor === Array\n ? 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';\n\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 * 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 let predictions = new Array(toPredict.rows);\n\n for (let i = 0; i < toPredict.rows; ++i) {\n predictions[i] = this.root\n .classify(toPredict.getRow(i))\n .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';\n\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 * 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 (\n typeof trainingSet[0] !== 'undefined' &&\n trainingSet[0].length === undefined\n ) {\n trainingSet = Matrix.columnVector(trainingSet);\n } else {\n trainingSet = Matrix.checkMatrix(trainingSet);\n }\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 (\n typeof toPredict[0] !== 'undefined' &&\n toPredict[0].length === undefined\n ) {\n toPredict = Matrix.columnVector(toPredict);\n }\n toPredict = Matrix.checkMatrix(toPredict);\n\n let predictions = new Array(toPredict.rows);\n for (let 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","const SMALLEST_UNSAFE_INTEGER = 0x20000000000000;\r\nconst LARGEST_SAFE_INTEGER = SMALLEST_UNSAFE_INTEGER - 1;\r\nconst UINT32_MAX = -1 >>> 0;\r\nconst UINT32_SIZE = UINT32_MAX + 1;\r\nconst INT32_SIZE = UINT32_SIZE / 2;\r\nconst INT32_MAX = INT32_SIZE - 1;\r\nconst UINT21_SIZE = 1 << 21;\r\nconst UINT21_MAX = UINT21_SIZE - 1;\n\n/**\r\n * Returns a value within [-0x80000000, 0x7fffffff]\r\n */\r\nfunction int32(engine) {\r\n return engine.next() | 0;\r\n}\n\nfunction add(distribution, addend) {\r\n if (addend === 0) {\r\n return distribution;\r\n }\r\n else {\r\n return engine => distribution(engine) + addend;\r\n }\r\n}\n\n/**\r\n * Returns a value within [-0x20000000000000, 0x1fffffffffffff]\r\n */\r\nfunction int53(engine) {\r\n const high = engine.next() | 0;\r\n const low = engine.next() >>> 0;\r\n return ((high & UINT21_MAX) * UINT32_SIZE +\r\n low +\r\n (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0));\r\n}\n\n/**\r\n * Returns a value within [-0x20000000000000, 0x20000000000000]\r\n */\r\nfunction int53Full(engine) {\r\n while (true) {\r\n const high = engine.next() | 0;\r\n if (high & 0x400000) {\r\n if ((high & 0x7fffff) === 0x400000 && (engine.next() | 0) === 0) {\r\n return SMALLEST_UNSAFE_INTEGER;\r\n }\r\n }\r\n else {\r\n const low = engine.next() >>> 0;\r\n return ((high & UINT21_MAX) * UINT32_SIZE +\r\n low +\r\n (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0));\r\n }\r\n }\r\n}\n\n/**\r\n * Returns a value within [0, 0xffffffff]\r\n */\r\nfunction uint32(engine) {\r\n return engine.next() >>> 0;\r\n}\n\n/**\r\n * Returns a value within [0, 0x1fffffffffffff]\r\n */\r\nfunction uint53(engine) {\r\n const high = engine.next() & UINT21_MAX;\r\n const low = engine.next() >>> 0;\r\n return high * UINT32_SIZE + low;\r\n}\n\n/**\r\n * Returns a value within [0, 0x20000000000000]\r\n */\r\nfunction uint53Full(engine) {\r\n while (true) {\r\n const high = engine.next() | 0;\r\n if (high & UINT21_SIZE) {\r\n if ((high & UINT21_MAX) === 0 && (engine.next() | 0) === 0) {\r\n return SMALLEST_UNSAFE_INTEGER;\r\n }\r\n }\r\n else {\r\n const low = engine.next() >>> 0;\r\n return (high & UINT21_MAX) * UINT32_SIZE + low;\r\n }\r\n }\r\n}\n\nfunction isPowerOfTwoMinusOne(value) {\r\n return ((value + 1) & value) === 0;\r\n}\r\nfunction bitmask(masking) {\r\n return (engine) => engine.next() & masking;\r\n}\r\nfunction downscaleToLoopCheckedRange(range) {\r\n const extendedRange = range + 1;\r\n const maximum = extendedRange * Math.floor(UINT32_SIZE / extendedRange);\r\n return engine => {\r\n let value = 0;\r\n do {\r\n value = engine.next() >>> 0;\r\n } while (value >= maximum);\r\n return value % extendedRange;\r\n };\r\n}\r\nfunction downscaleToRange(range) {\r\n if (isPowerOfTwoMinusOne(range)) {\r\n return bitmask(range);\r\n }\r\n else {\r\n return downscaleToLoopCheckedRange(range);\r\n }\r\n}\r\nfunction isEvenlyDivisibleByMaxInt32(value) {\r\n return (value | 0) === 0;\r\n}\r\nfunction upscaleWithHighMasking(masking) {\r\n return engine => {\r\n const high = engine.next() & masking;\r\n const low = engine.next() >>> 0;\r\n return high * UINT32_SIZE + low;\r\n };\r\n}\r\nfunction upscaleToLoopCheckedRange(extendedRange) {\r\n const maximum = extendedRange * Math.floor(SMALLEST_UNSAFE_INTEGER / extendedRange);\r\n return engine => {\r\n let ret = 0;\r\n do {\r\n const high = engine.next() & UINT21_MAX;\r\n const low = engine.next() >>> 0;\r\n ret = high * UINT32_SIZE + low;\r\n } while (ret >= maximum);\r\n return ret % extendedRange;\r\n };\r\n}\r\nfunction upscaleWithinU53(range) {\r\n const extendedRange = range + 1;\r\n if (isEvenlyDivisibleByMaxInt32(extendedRange)) {\r\n const highRange = ((extendedRange / UINT32_SIZE) | 0) - 1;\r\n if (isPowerOfTwoMinusOne(highRange)) {\r\n return upscaleWithHighMasking(highRange);\r\n }\r\n }\r\n return upscaleToLoopCheckedRange(extendedRange);\r\n}\r\nfunction upscaleWithinI53AndLoopCheck(min, max) {\r\n return engine => {\r\n let ret = 0;\r\n do {\r\n const high = engine.next() | 0;\r\n const low = engine.next() >>> 0;\r\n ret =\r\n (high & UINT21_MAX) * UINT32_SIZE +\r\n low +\r\n (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0);\r\n } while (ret < min || ret > max);\r\n return ret;\r\n };\r\n}\r\n/**\r\n * Returns a Distribution to return a value within [min, max]\r\n * @param min The minimum integer value, inclusive. No less than -0x20000000000000.\r\n * @param max The maximum integer value, inclusive. No greater than 0x20000000000000.\r\n */\r\nfunction integer(min, max) {\r\n min = Math.floor(min);\r\n max = Math.floor(max);\r\n if (min < -SMALLEST_UNSAFE_INTEGER || !isFinite(min)) {\r\n throw new RangeError(`Expected min to be at least ${-SMALLEST_UNSAFE_INTEGER}`);\r\n }\r\n else if (max > SMALLEST_UNSAFE_INTEGER || !isFinite(max)) {\r\n throw new RangeError(`Expected max to be at most ${SMALLEST_UNSAFE_INTEGER}`);\r\n }\r\n const range = max - min;\r\n if (range <= 0 || !isFinite(range)) {\r\n return () => min;\r\n }\r\n else if (range === UINT32_MAX) {\r\n if (min === 0) {\r\n return uint32;\r\n }\r\n else {\r\n return add(int32, min + INT32_SIZE);\r\n }\r\n }\r\n else if (range < UINT32_MAX) {\r\n return add(downscaleToRange(range), min);\r\n }\r\n else if (range === LARGEST_SAFE_INTEGER) {\r\n return add(uint53, min);\r\n }\r\n else if (range < LARGEST_SAFE_INTEGER) {\r\n return add(upscaleWithinU53(range), min);\r\n }\r\n else if (max - 1 - min === LARGEST_SAFE_INTEGER) {\r\n return add(uint53Full, min);\r\n }\r\n else if (min === -SMALLEST_UNSAFE_INTEGER &&\r\n max === SMALLEST_UNSAFE_INTEGER) {\r\n return int53Full;\r\n }\r\n else if (min === -SMALLEST_UNSAFE_INTEGER && max === LARGEST_SAFE_INTEGER) {\r\n return int53;\r\n }\r\n else if (min === -LARGEST_SAFE_INTEGER && max === SMALLEST_UNSAFE_INTEGER) {\r\n return add(int53, 1);\r\n }\r\n else if (max === SMALLEST_UNSAFE_INTEGER) {\r\n return add(upscaleWithinI53AndLoopCheck(min - 1, max - 1), 1);\r\n }\r\n else {\r\n return upscaleWithinI53AndLoopCheck(min, max);\r\n }\r\n}\n\nfunction isLeastBitTrue(engine) {\r\n return (engine.next() & 1) === 1;\r\n}\r\nfunction lessThan(distribution, value) {\r\n return engine => distribution(engine) < value;\r\n}\r\nfunction probability(percentage) {\r\n if (percentage <= 0) {\r\n return () => false;\r\n }\r\n else if (percentage >= 1) {\r\n return () => true;\r\n }\r\n else {\r\n const scaled = percentage * UINT32_SIZE;\r\n if (scaled % 1 === 0) {\r\n return lessThan(int32, (scaled - INT32_SIZE) | 0);\r\n }\r\n else {\r\n return lessThan(uint53, Math.round(percentage * SMALLEST_UNSAFE_INTEGER));\r\n }\r\n }\r\n}\r\nfunction bool(numerator, denominator) {\r\n if (denominator == null) {\r\n if (numerator == null) {\r\n return isLeastBitTrue;\r\n }\r\n return probability(numerator);\r\n }\r\n else {\r\n if (numerator <= 0) {\r\n return () => false;\r\n }\r\n else if (numerator >= denominator) {\r\n return () => true;\r\n }\r\n return lessThan(integer(0, denominator - 1), numerator);\r\n }\r\n}\n\n/**\r\n * Returns a Distribution that returns a random `Date` within the inclusive\r\n * range of [`start`, `end`].\r\n * @param start The minimum `Date`\r\n * @param end The maximum `Date`\r\n */\r\nfunction date(start, end) {\r\n const distribution = integer(+start, +end);\r\n return engine => new Date(distribution(engine));\r\n}\n\n/**\r\n * Returns a Distribution to return a value within [1, sideCount]\r\n * @param sideCount The number of sides of the die\r\n */\r\nfunction die(sideCount) {\r\n return integer(1, sideCount);\r\n}\n\n/**\r\n * Returns a distribution that returns an array of length `dieCount` of values\r\n * within [1, `sideCount`]\r\n * @param sideCount The number of sides of each die\r\n * @param dieCount The number of dice\r\n */\r\nfunction dice(sideCount, dieCount) {\r\n const distribution = die(sideCount);\r\n return engine => {\r\n const result = [];\r\n for (let i = 0; i < dieCount; ++i) {\r\n result.push(distribution(engine));\r\n }\r\n return result;\r\n };\r\n}\n\n// tslint:disable:unified-signatures\r\n// has 2**x chars, for faster uniform distribution\r\nconst DEFAULT_STRING_POOL = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-\";\r\nfunction string(pool = DEFAULT_STRING_POOL) {\r\n const poolLength = pool.length;\r\n if (!poolLength) {\r\n throw new Error(\"Expected pool not to be an empty string\");\r\n }\r\n const distribution = integer(0, poolLength - 1);\r\n return (engine, length) => {\r\n let result = \"\";\r\n for (let i = 0; i < length; ++i) {\r\n const j = distribution(engine);\r\n result += pool.charAt(j);\r\n }\r\n return result;\r\n };\r\n}\n\nconst LOWER_HEX_POOL = \"0123456789abcdef\";\r\nconst lowerHex = string(LOWER_HEX_POOL);\r\nconst upperHex = string(LOWER_HEX_POOL.toUpperCase());\r\n/**\r\n * Returns a Distribution that returns a random string comprised of numbers\r\n * or the characters `abcdef` (or `ABCDEF`) of length `length`.\r\n * @param length Length of the result string\r\n * @param uppercase Whether the string should use `ABCDEF` instead of `abcdef`\r\n */\r\nfunction hex(uppercase) {\r\n if (uppercase) {\r\n return upperHex;\r\n }\r\n else {\r\n return lowerHex;\r\n }\r\n}\n\nfunction convertSliceArgument(value, length) {\r\n if (value < 0) {\r\n return Math.max(value + length, 0);\r\n }\r\n else {\r\n return Math.min(value, length);\r\n }\r\n}\n\nfunction toInteger(value) {\r\n const num = +value;\r\n if (num < 0) {\r\n return Math.ceil(num);\r\n }\r\n else {\r\n return Math.floor(num);\r\n }\r\n}\n\n/**\r\n * Returns a random value within the provided `source` within the sliced\r\n * bounds of `begin` and `end`.\r\n * @param source an array of items to pick from\r\n * @param begin the beginning slice index (defaults to `0`)\r\n * @param end the ending slice index (defaults to `source.length`)\r\n */\r\nfunction pick(engine, source, begin, end) {\r\n const length = source.length;\r\n if (length === 0) {\r\n throw new RangeError(\"Cannot pick from an empty array\");\r\n }\r\n const start = begin == null ? 0 : convertSliceArgument(toInteger(begin), length);\r\n const finish = end === void 0 ? length : convertSliceArgument(toInteger(end), length);\r\n if (start >= finish) {\r\n throw new RangeError(`Cannot pick between bounds ${start} and ${finish}`);\r\n }\r\n const distribution = integer(start, finish - 1);\r\n return source[distribution(engine)];\r\n}\n\nfunction multiply(distribution, multiplier) {\r\n if (multiplier === 1) {\r\n return distribution;\r\n }\r\n else if (multiplier === 0) {\r\n return () => 0;\r\n }\r\n else {\r\n return engine => distribution(engine) * multiplier;\r\n }\r\n}\n\n/**\r\n * Returns a floating-point value within [0.0, 1.0)\r\n */\r\nfunction realZeroToOneExclusive(engine) {\r\n return uint53(engine) / SMALLEST_UNSAFE_INTEGER;\r\n}\n\n/**\r\n * Returns a floating-point value within [0.0, 1.0]\r\n */\r\nfunction realZeroToOneInclusive(engine) {\r\n return uint53Full(engine) / SMALLEST_UNSAFE_INTEGER;\r\n}\n\n/**\r\n * Returns a floating-point value within [min, max) or [min, max]\r\n * @param min The minimum floating-point value, inclusive.\r\n * @param max The maximum floating-point value.\r\n * @param inclusive If true, `max` will be inclusive.\r\n */\r\nfunction real(min, max, inclusive = false) {\r\n if (!isFinite(min)) {\r\n throw new RangeError(\"Expected min to be a finite number\");\r\n }\r\n else if (!isFinite(max)) {\r\n throw new RangeError(\"Expected max to be a finite number\");\r\n }\r\n return add(multiply(inclusive ? realZeroToOneInclusive : realZeroToOneExclusive, max - min), min);\r\n}\n\nconst sliceArray = Array.prototype.slice;\n\n/**\r\n * Shuffles an array in-place\r\n * @param engine The Engine to use when choosing random values\r\n * @param array The array to shuffle\r\n * @param downTo minimum index to shuffle. Only used internally.\r\n */\r\nfunction shuffle(engine, array, downTo = 0) {\r\n const length = array.length;\r\n if (length) {\r\n for (let i = (length - 1) >>> 0; i > downTo; --i) {\r\n const distribution = integer(0, i);\r\n const j = distribution(engine);\r\n if (i !== j) {\r\n const tmp = array[i];\r\n array[i] = array[j];\r\n array[j] = tmp;\r\n }\r\n }\r\n }\r\n return array;\r\n}\n\n/**\r\n * From the population array, produce an array with sampleSize elements that\r\n * are randomly chosen without repeats.\r\n * @param engine The Engine to use when choosing random values\r\n * @param population An array that has items to choose a sample from\r\n * @param sampleSize The size of the result array\r\n */\r\nfunction sample(engine, population, sampleSize) {\r\n if (sampleSize < 0 ||\r\n sampleSize > population.length ||\r\n !isFinite(sampleSize)) {\r\n throw new RangeError(\"Expected sampleSize to be within 0 and the length of the population\");\r\n }\r\n if (sampleSize === 0) {\r\n return [];\r\n }\r\n const clone = sliceArray.call(population);\r\n const length = clone.length;\r\n if (length === sampleSize) {\r\n return shuffle(engine, clone, 0);\r\n }\r\n const tailLength = length - sampleSize;\r\n return shuffle(engine, clone, tailLength - 1).slice(tailLength);\r\n}\n\nconst stringRepeat = (() => {\r\n try {\r\n if (\"x\".repeat(3) === \"xxx\") {\r\n return (pattern, count) => pattern.repeat(count);\r\n }\r\n }\r\n catch (_) {\r\n // nothing to do here\r\n }\r\n return (pattern, count) => {\r\n let result = \"\";\r\n while (count > 0) {\r\n if (count & 1) {\r\n result += pattern;\r\n }\r\n count >>= 1;\r\n pattern += pattern;\r\n }\r\n return result;\r\n };\r\n})();\n\nfunction zeroPad(text, zeroCount) {\r\n return stringRepeat(\"0\", zeroCount - text.length) + text;\r\n}\r\n/**\r\n * Returns a Universally Unique Identifier Version 4.\r\n *\r\n * See http://en.wikipedia.org/wiki/Universally_unique_identifier\r\n */\r\nfunction uuid4(engine) {\r\n const a = engine.next() >>> 0;\r\n const b = engine.next() | 0;\r\n const c = engine.next() | 0;\r\n const d = engine.next() >>> 0;\r\n return (zeroPad(a.toString(16), 8) +\r\n \"-\" +\r\n zeroPad((b & 0xffff).toString(16), 4) +\r\n \"-\" +\r\n zeroPad((((b >> 4) & 0x0fff) | 0x4000).toString(16), 4) +\r\n \"-\" +\r\n zeroPad(((c & 0x3fff) | 0x8000).toString(16), 4) +\r\n \"-\" +\r\n zeroPad(((c >> 4) & 0xffff).toString(16), 4) +\r\n zeroPad(d.toString(16), 8));\r\n}\n\n/**\r\n * An int32-producing Engine that uses `Math.random()`\r\n */\r\nconst nativeMath = {\r\n next() {\r\n return (Math.random() * UINT32_SIZE) | 0;\r\n }\r\n};\n\n// tslint:disable:unified-signatures\r\n/**\r\n * A wrapper around an Engine that provides easy-to-use methods for\r\n * producing values based on known distributions\r\n */\r\nclass Random {\r\n /**\r\n * Creates a new Random wrapper\r\n * @param engine The engine to use (defaults to a `Math.random`-based implementation)\r\n */\r\n constructor(engine = nativeMath) {\r\n this.engine = engine;\r\n }\r\n /**\r\n * Returns a value within [-0x80000000, 0x7fffffff]\r\n */\r\n int32() {\r\n return int32(this.engine);\r\n }\r\n /**\r\n * Returns a value within [0, 0xffffffff]\r\n */\r\n uint32() {\r\n return uint32(this.engine);\r\n }\r\n /**\r\n * Returns a value within [0, 0x1fffffffffffff]\r\n */\r\n uint53() {\r\n return uint53(this.engine);\r\n }\r\n /**\r\n * Returns a value within [0, 0x20000000000000]\r\n */\r\n uint53Full() {\r\n return uint53Full(this.engine);\r\n }\r\n /**\r\n * Returns a value within [-0x20000000000000, 0x1fffffffffffff]\r\n */\r\n int53() {\r\n return int53(this.engine);\r\n }\r\n /**\r\n * Returns a value within [-0x20000000000000, 0x20000000000000]\r\n */\r\n int53Full() {\r\n return int53Full(this.engine);\r\n }\r\n /**\r\n * Returns a value within [min, max]\r\n * @param min The minimum integer value, inclusive. No less than -0x20000000000000.\r\n * @param max The maximum integer value, inclusive. No greater than 0x20000000000000.\r\n */\r\n integer(min, max) {\r\n return integer(min, max)(this.engine);\r\n }\r\n /**\r\n * Returns a floating-point value within [0.0, 1.0]\r\n */\r\n realZeroToOneInclusive() {\r\n return realZeroToOneInclusive(this.engine);\r\n }\r\n /**\r\n * Returns a floating-point value within [0.0, 1.0)\r\n */\r\n realZeroToOneExclusive() {\r\n return realZeroToOneExclusive(this.engine);\r\n }\r\n /**\r\n * Returns a floating-point value within [min, max) or [min, max]\r\n * @param min The minimum floating-point value, inclusive.\r\n * @param max The maximum floating-point value.\r\n * @param inclusive If true, `max` will be inclusive.\r\n */\r\n real(min, max, inclusive = false) {\r\n return real(min, max, inclusive)(this.engine);\r\n }\r\n bool(numerator, denominator) {\r\n return bool(numerator, denominator)(this.engine);\r\n }\r\n /**\r\n * Return a random value within the provided `source` within the sliced\r\n * bounds of `begin` and `end`.\r\n * @param source an array of items to pick from\r\n * @param begin the beginning slice index (defaults to `0`)\r\n * @param end the ending slice index (defaults to `source.length`)\r\n */\r\n pick(source, begin, end) {\r\n return pick(this.engine, source, begin, end);\r\n }\r\n /**\r\n * Shuffles an array in-place\r\n * @param array The array to shuffle\r\n */\r\n shuffle(array) {\r\n return shuffle(this.engine, array);\r\n }\r\n /**\r\n * From the population array, returns an array with sampleSize elements that\r\n * are randomly chosen without repeats.\r\n * @param population An array that has items to choose a sample from\r\n * @param sampleSize The size of the result array\r\n */\r\n sample(population, sampleSize) {\r\n return sample(this.engine, population, sampleSize);\r\n }\r\n /**\r\n * Returns a value within [1, sideCount]\r\n * @param sideCount The number of sides of the die\r\n */\r\n die(sideCount) {\r\n return die(sideCount)(this.engine);\r\n }\r\n /**\r\n * Returns an array of length `dieCount` of values within [1, sideCount]\r\n * @param sideCount The number of sides of each die\r\n * @param dieCount The number of dice\r\n */\r\n dice(sideCount, dieCount) {\r\n return dice(sideCount, dieCount)(this.engine);\r\n }\r\n /**\r\n * Returns a Universally Unique Identifier Version 4.\r\n *\r\n * See http://en.wikipedia.org/wiki/Universally_unique_identifier\r\n */\r\n uuid4() {\r\n return uuid4(this.engine);\r\n }\r\n string(length, pool) {\r\n return string(pool)(this.engine, length);\r\n }\r\n /**\r\n * Returns a random string comprised of numbers or the characters `abcdef`\r\n * (or `ABCDEF`) of length `length`.\r\n * @param length Length of the result string\r\n * @param uppercase Whether the string should use `ABCDEF` instead of `abcdef`\r\n */\r\n hex(length, uppercase) {\r\n return hex(uppercase)(this.engine, length);\r\n }\r\n /**\r\n * Returns a random `Date` within the inclusive range of [`start`, `end`].\r\n * @param start The minimum `Date`\r\n * @param end The maximum `Date`\r\n */\r\n date(start, end) {\r\n return date(start, end)(this.engine);\r\n }\r\n}\n\n/**\r\n * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array\r\n */\r\nconst I32Array = (() => {\r\n try {\r\n const buffer = new ArrayBuffer(4);\r\n const view = new Int32Array(buffer);\r\n view[0] = INT32_SIZE;\r\n if (view[0] === -INT32_SIZE) {\r\n return Int32Array;\r\n }\r\n }\r\n catch (_) {\r\n // nothing to do here\r\n }\r\n return Array;\r\n})();\n\nlet data = null;\r\nconst COUNT = 128;\r\nlet index = COUNT;\r\n/**\r\n * An Engine that relies on the globally-available `crypto.getRandomValues`,\r\n * which is typically available in modern browsers.\r\n *\r\n * See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues\r\n *\r\n * If unavailable or otherwise non-functioning, then `browserCrypto` will\r\n * likely `throw` on the first call to `next()`.\r\n */\r\nconst browserCrypto = {\r\n next() {\r\n if (index >= COUNT) {\r\n if (data === null) {\r\n data = new I32Array(COUNT);\r\n }\r\n crypto.getRandomValues(data);\r\n index = 0;\r\n }\r\n return data[index++] | 0;\r\n }\r\n};\n\n/**\r\n * Returns an array of random int32 values, based on current time\r\n * and a random number engine\r\n *\r\n * @param engine an Engine to pull random values from, default `nativeMath`\r\n * @param length the length of the Array, minimum 1, default 16\r\n */\r\nfunction createEntropy(engine = nativeMath, length = 16) {\r\n const array = [];\r\n array.push(new Date().getTime() | 0);\r\n for (let i = 1; i < length; ++i) {\r\n array[i] = engine.next() | 0;\r\n }\r\n return array;\r\n}\n\n/**\r\n * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul\r\n */\r\nconst imul = (() => {\r\n try {\r\n if (Math.imul(UINT32_MAX, 5) === -5) {\r\n return Math.imul;\r\n }\r\n }\r\n catch (_) {\r\n // nothing to do here\r\n }\r\n const UINT16_MAX = 0xffff;\r\n return (a, b) => {\r\n const ah = (a >>> 16) & UINT16_MAX;\r\n const al = a & UINT16_MAX;\r\n const bh = (b >>> 16) & UINT16_MAX;\r\n const bl = b & UINT16_MAX;\r\n // the shift by 0 fixes the sign on the high part\r\n // the final |0 converts the unsigned value into a signed value\r\n return (al * bl + (((ah * bl + al * bh) << 16) >>> 0)) | 0;\r\n };\r\n})();\n\nconst ARRAY_SIZE = 624;\r\nconst ARRAY_MAX = ARRAY_SIZE - 1;\r\nconst M = 397;\r\nconst ARRAY_SIZE_MINUS_M = ARRAY_SIZE - M;\r\nconst A = 0x9908b0df;\r\n/**\r\n * An Engine that is a pseudorandom number generator using the Mersenne\r\n * Twister algorithm based on the prime 2**19937 − 1\r\n *\r\n * See http://en.wikipedia.org/wiki/Mersenne_twister\r\n */\r\nclass MersenneTwister19937 {\r\n /**\r\n * MersenneTwister19937 should not be instantiated directly.\r\n * Instead, use the static methods `seed`, `seedWithArray`, or `autoSeed`.\r\n */\r\n constructor() {\r\n this.data = new I32Array(ARRAY_SIZE);\r\n this.index = 0; // integer within [0, 624]\r\n this.uses = 0;\r\n }\r\n /**\r\n * Returns a MersenneTwister19937 seeded with an initial int32 value\r\n * @param initial the initial seed value\r\n */\r\n static seed(initial) {\r\n return new MersenneTwister19937().seed(initial);\r\n }\r\n /**\r\n * Returns a MersenneTwister19937 seeded with zero or more int32 values\r\n * @param source A series of int32 values\r\n */\r\n static seedWithArray(source) {\r\n return new MersenneTwister19937().seedWithArray(source);\r\n }\r\n /**\r\n * Returns a MersenneTwister19937 seeded with the current time and\r\n * a series of natively-generated random values\r\n */\r\n static autoSeed() {\r\n return MersenneTwister19937.seedWithArray(createEntropy());\r\n }\r\n /**\r\n * Returns the next int32 value of the sequence\r\n */\r\n next() {\r\n if ((this.index | 0) >= ARRAY_SIZE) {\r\n refreshData(this.data);\r\n this.index = 0;\r\n }\r\n const value = this.data[this.index];\r\n this.index = (this.index + 1) | 0;\r\n this.uses += 1;\r\n return temper(value) | 0;\r\n }\r\n /**\r\n * Returns the number of times that the Engine has been used.\r\n *\r\n * This can be provided to an unused MersenneTwister19937 with the same\r\n * seed, bringing it to the exact point that was left off.\r\n */\r\n getUseCount() {\r\n return this.uses;\r\n }\r\n /**\r\n * Discards one or more items from the engine\r\n * @param count The count of items to discard\r\n */\r\n discard(count) {\r\n if (count <= 0) {\r\n return this;\r\n }\r\n this.uses += count;\r\n if ((this.index | 0) >= ARRAY_SIZE) {\r\n refreshData(this.data);\r\n this.index = 0;\r\n }\r\n while (count + this.index > ARRAY_SIZE) {\r\n count -= ARRAY_SIZE - this.index;\r\n refreshData(this.data);\r\n this.index = 0;\r\n }\r\n this.index = (this.index + count) | 0;\r\n return this;\r\n }\r\n seed(initial) {\r\n let previous = 0;\r\n this.data[0] = previous = initial | 0;\r\n for (let i = 1; i < ARRAY_SIZE; i = (i + 1) | 0) {\r\n this.data[i] = previous =\r\n (imul(previous ^ (previous >>> 30), 0x6c078965) + i) | 0;\r\n }\r\n this.index = ARRAY_SIZE;\r\n this.uses = 0;\r\n return this;\r\n }\r\n seedWithArray(source) {\r\n this.seed(0x012bd6aa);\r\n seedWithArray(this.data, source);\r\n return this;\r\n }\r\n}\r\nfunction refreshData(data) {\r\n let k = 0;\r\n let tmp = 0;\r\n for (; (k | 0) < ARRAY_SIZE_MINUS_M; k = (k + 1) | 0) {\r\n tmp = (data[k] & INT32_SIZE) | (data[(k + 1) | 0] & INT32_MAX);\r\n data[k] = data[(k + M) | 0] ^ (tmp >>> 1) ^ (tmp & 0x1 ? A : 0);\r\n }\r\n for (; (k | 0) < ARRAY_MAX; k = (k + 1) | 0) {\r\n tmp = (data[k] & INT32_SIZE) | (data[(k + 1) | 0] & INT32_MAX);\r\n data[k] =\r\n data[(k - ARRAY_SIZE_MINUS_M) | 0] ^ (tmp >>> 1) ^ (tmp & 0x1 ? A : 0);\r\n }\r\n tmp = (data[ARRAY_MAX] & INT32_SIZE) | (data[0] & INT32_MAX);\r\n data[ARRAY_MAX] = data[M - 1] ^ (tmp >>> 1) ^ (tmp & 0x1 ? A : 0);\r\n}\r\nfunction temper(value) {\r\n value ^= value >>> 11;\r\n value ^= (value << 7) & 0x9d2c5680;\r\n value ^= (value << 15) & 0xefc60000;\r\n return value ^ (value >>> 18);\r\n}\r\nfunction seedWithArray(data, source) {\r\n let i = 1;\r\n let j = 0;\r\n const sourceLength = source.length;\r\n let k = Math.max(sourceLength, ARRAY_SIZE) | 0;\r\n let previous = data[0] | 0;\r\n for (; (k | 0) > 0; --k) {\r\n data[i] = previous =\r\n ((data[i] ^ imul(previous ^ (previous >>> 30), 0x0019660d)) +\r\n (source[j] | 0) +\r\n (j | 0)) |\r\n 0;\r\n i = (i + 1) | 0;\r\n ++j;\r\n if ((i | 0) > ARRAY_MAX) {\r\n data[0] = data[ARRAY_MAX];\r\n i = 1;\r\n }\r\n if (j >= sourceLength) {\r\n j = 0;\r\n }\r\n }\r\n for (k = ARRAY_MAX; (k | 0) > 0; --k) {\r\n data[i] = previous =\r\n ((data[i] ^ imul(previous ^ (previous >>> 30), 0x5d588b65)) - i) | 0;\r\n i = (i + 1) | 0;\r\n if ((i | 0) > ARRAY_MAX) {\r\n data[0] = data[ARRAY_MAX];\r\n i = 1;\r\n }\r\n }\r\n data[0] = INT32_SIZE;\r\n}\n\nlet data$1 = null;\r\nconst COUNT$1 = 128;\r\nlet index$1 = COUNT$1;\r\n/**\r\n * An Engine that relies on the node-available\r\n * `require('crypto').randomBytes`, which has been available since 0.58.\r\n *\r\n * See https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback\r\n *\r\n * If unavailable or otherwise non-functioning, then `nodeCrypto` will\r\n * likely `throw` on the first call to `next()`.\r\n */\r\nconst nodeCrypto = {\r\n next() {\r\n if (index$1 >= COUNT$1) {\r\n data$1 = new Int32Array(new Int8Array(require(\"crypto\").randomBytes(4 * COUNT$1)).buffer);\r\n index$1 = 0;\r\n }\r\n return data$1[index$1++] | 0;\r\n }\r\n};\n\n/**\r\n * Returns a Distribution to random value within the provided `source`\r\n * within the sliced bounds of `begin` and `end`.\r\n * @param source an array of items to pick from\r\n * @param begin the beginning slice index (defaults to `0`)\r\n * @param end the ending slice index (defaults to `source.length`)\r\n */\r\nfunction picker(source, begin, end) {\r\n const clone = sliceArray.call(source, begin, end);\r\n if (clone.length === 0) {\r\n throw new RangeError(`Cannot pick from a source with no items`);\r\n }\r\n const distribution = integer(0, clone.length - 1);\r\n return engine => clone[distribution(engine)];\r\n}\n\nexport { Random, browserCrypto, nativeMath, MersenneTwister19937, nodeCrypto, bool, date, dice, die, hex, int32, int53, int53Full, integer, pick, picker, real, realZeroToOneExclusive, realZeroToOneInclusive, sample, shuffle, string, uint32, uint53, uint53Full, uuid4, createEntropy };\n//# sourceMappingURL=random-js.esm.js.map\n","import * as 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(\n trainingSet,\n trainingValue,\n seed,\n) {\n let engine;\n let distribution = Random.integer(0, trainingSet.rows - 1);\n if (seed === undefined) {\n engine = Random.MersenneTwister19937.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = Random.MersenneTwister19937.seed(seed);\n } else {\n throw new RangeError(\n `Expected seed must be undefined or integer not ${seed}`,\n );\n }\n\n let Xr = new Array(trainingSet.rows);\n let yr = new Array(trainingSet.rows);\n\n for (let i = 0; i < trainingSet.rows; ++i) {\n let index = distribution(engine);\n Xr[i] = trainingSet.getRow(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 'N should be less or equal to the number of columns of X',\n );\n }\n\n let distribution = Random.integer(0, trainingSet.columns - 1);\n let engine;\n if (seed === undefined) {\n engine = Random.MersenneTwister19937.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = Random.MersenneTwister19937.seed(seed);\n } else {\n throw new RangeError(\n `Expected seed must be undefined or integer not ${seed}`,\n );\n }\n\n let toRet = new Matrix(trainingSet.rows, n);\n\n let usedIndex;\n let index;\n if (replacement) {\n usedIndex = new Array(n);\n for (let i = 0; i < n; ++i) {\n 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 (let 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 {\n Matrix,\n WrapperMatrix2D,\n MatrixTransposeView,\n MatrixColumnSelectionView,\n} 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 let 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(\n `The maxFeatures parameter should be less than ${trainingSet.columns}`,\n );\n } else {\n this.n = this.maxFeatures;\n }\n } else {\n throw new RangeError(\n `Cannot process the maxFeatures parameter ${this.maxFeatures}`,\n );\n }\n\n let Estimator;\n if (this.isClassifier) {\n 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 (let i = 0; i < this.nEstimators; ++i) {\n let res = this.useSampleBagging\n ? Utils.examplesBaggingWithReplacement(\n trainingSet,\n trainingValues,\n this.seed,\n )\n : { X: trainingSet, y: trainingValues };\n let X = res.X;\n let 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 let predictionValues = new Array(this.nEstimators);\n toPredict = Matrix.checkMatrix(toPredict);\n for (let i = 0; i < this.nEstimators; ++i) {\n let X = new MatrixColumnSelectionView(toPredict, this.indexes[i]); // get features for estimator\n predictionValues[i] = this.estimators[i].predict(X);\n }\n\n predictionValues = new MatrixTransposeView(\n new WrapperMatrix2D(predictionValues),\n );\n let predictions = new Array(predictionValues.rows);\n for (let 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 let 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\n .sort(\n (a, b) =>\n arr.filter((v) => v === a).length - arr.filter((v) => v === b).length,\n )\n .pop();\n}\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","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","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 (\n !(\n options.selectionMethod === 'mean' ||\n options.selectionMethod === 'median'\n )\n ) {\n throw new RangeError(\n `Unsupported selection method ${options.selectionMethod}`,\n );\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 let 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","import { Matrix, MatrixTransposeView, EVD, SVD, NIPALS } from 'ml-matrix';\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 {string} [options.method='SVD'] - select which method to use: SVD (default), covarianceMatrirx or NIPALS.\n * @param {number} [options.nCompNIPALS=2] - number of components to be computed with NIPALS.\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 * @param {boolean} [options.ignoreZeroVariance=false] - ignore columns with zero variance if `scale` is `true`.\n * */\nexport class 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 this.R = model.R;\n this.excludedFeatures = model.excludedFeatures || [];\n return;\n }\n\n dataset = new Matrix(dataset);\n\n const {\n isCovarianceMatrix = false,\n method = 'SVD',\n nCompNIPALS = 2,\n center = true,\n scale = false,\n ignoreZeroVariance = false,\n } = options;\n\n this.center = center;\n this.scale = scale;\n this.means = null;\n this.stdevs = null;\n this.excludedFeatures = [];\n\n if (isCovarianceMatrix) {\n // User provided a covariance matrix instead of dataset.\n this._computeFromCovarianceMatrix(dataset);\n return;\n }\n\n this._adjust(dataset, ignoreZeroVariance);\n switch (method) {\n case 'covarianceMatrix': {\n // User provided a dataset but wants us to compute and use the covariance matrix.\n const covarianceMatrix = new MatrixTransposeView(dataset)\n .mmul(dataset)\n .div(dataset.rows - 1);\n this._computeFromCovarianceMatrix(covarianceMatrix);\n break;\n }\n case 'NIPALS': {\n this._computeWithNIPALS(dataset, nCompNIPALS);\n break;\n }\n case 'SVD': {\n const 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 = [];\n for (const singularValue of singularValues) {\n eigenvalues.push((singularValue * singularValue) / (dataset.rows - 1));\n }\n this.S = eigenvalues;\n break;\n }\n default: {\n throw new Error(`unknown method: ${method}`);\n }\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 (typeof model.name !== 'string') {\n throw new TypeError('model must have a name property');\n }\n if (model.name !== 'PCA') {\n throw new RangeError(`invalid model: ${model.name}`);\n }\n return new PCA(true, model);\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 { nComponents = this.U.columns } = options;\n dataset = new Matrix(dataset);\n if (this.center) {\n dataset.subRowVector(this.means);\n if (this.scale) {\n for (let i of this.excludedFeatures) {\n dataset.removeColumn(i);\n }\n dataset.divRowVector(this.stdevs);\n }\n }\n var predictions = dataset.mmul(this.U);\n return predictions.subMatrix(0, predictions.rows - 1, 0, nComponents - 1);\n }\n\n /**\n * Calculates the inverse PCA transform\n * @param {Matrix} dataset\n * @return {Matrix} dataset projected in the PCA space\n */\n invert(dataset) {\n dataset = Matrix.checkMatrix(dataset);\n\n var inverse = dataset.mmul(this.U.transpose());\n\n if (this.center) {\n if (this.scale) {\n inverse.mulRowVector(this.stdevs);\n }\n inverse.addRowVector(this.means);\n }\n\n return inverse;\n }\n\n\n /**\n * Returns the proportion of variance for each component\n * @return {[number]}\n */\n getExplainedVariance() {\n var sum = 0;\n for (const s of this.S) {\n sum += s;\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 excludedFeatures: this.excludedFeatures,\n };\n }\n\n _adjust(dataset, ignoreZeroVariance) {\n if (this.center) {\n const mean = dataset.mean('column');\n const stdevs = this.scale\n ? dataset.standardDeviation('column', { mean })\n : null;\n this.means = mean;\n dataset.subRowVector(mean);\n if (this.scale) {\n for (let i = 0; i < stdevs.length; i++) {\n if (stdevs[i] === 0) {\n if (ignoreZeroVariance) {\n dataset.removeColumn(i);\n stdevs.splice(i, 1);\n this.excludedFeatures.push(i);\n i--;\n } else {\n throw new RangeError(\n `Cannot scale the dataset (standard deviation is zero at index ${i}`,\n );\n }\n }\n }\n this.stdevs = stdevs;\n dataset.divRowVector(stdevs);\n }\n }\n }\n\n _computeFromCovarianceMatrix(dataset) {\n const evd = new EVD(dataset, { assumeSymmetric: true });\n this.U = evd.eigenvectorMatrix;\n this.U.flipRows();\n this.S = evd.realEigenvalues;\n this.S.reverse();\n }\n\n _computeWithNIPALS(dataset, nCompNIPALS) {\n this.U = new Matrix(nCompNIPALS, dataset.columns);\n this.S = [];\n\n let x = dataset;\n for (let i = 0; i < nCompNIPALS; i++) {\n let dc = new NIPALS(x);\n\n this.U.setRow(i, dc.w.transpose());\n this.S.push(Math.pow(dc.s.get(0, 0), 2));\n\n x = dc.xResidual;\n }\n this.U = this.U.transpose(); // to be compatible with API\n }\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","/**\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 distance/similarity matrix. The matrix is square and has a size equal to the length of\n * the data array\n */\nexport default function distanceMatrix(data, distanceFn) {\n const result = getMatrix(data.length);\n\n // Compute upper distance matrix\n for (let i = 0; i < data.length; i++) {\n for (let j = 0; j <= i; j++) {\n result[i][j] = distanceFn(data[i], data[j]);\n result[j][i] = result[i][j];\n }\n }\n\n return result;\n}\n\nfunction getMatrix(size) {\n const matrix = [];\n for (let i = 0; i < size; i++) {\n const row = [];\n matrix.push(row);\n for (let j = 0; j < size; j++) {\n row.push(0);\n }\n }\n return matrix;\n}\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","module.exports = require('./lib/heap');\n","import Heap from 'heap';\n\nexport default class Cluster {\n constructor() {\n this.children = [];\n this.height = 0;\n this.size = 1;\n this.index = -1;\n this.isLeaf = false;\n }\n\n /**\n * Creates an array of clusters where the maximum height is smaller than the threshold\n * @param {number} threshold\n * @return {Array}\n */\n cut(threshold) {\n if (typeof threshold !== 'number') {\n throw new TypeError('threshold must be a number');\n }\n if (threshold < 0) {\n throw new RangeError('threshold must be a positive number');\n }\n let list = [this];\n const ans = [];\n while (list.length > 0) {\n const aux = list.shift();\n if (threshold >= aux.height) {\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 `groups` number of clusters.\n * @param {number} groups - Them number of children the first level of the tree should have.\n * @return {Cluster}\n */\n group(groups) {\n if (!Number.isInteger(groups) || groups < 1) {\n throw new RangeError('groups must be a positive integer');\n }\n\n const heap = new Heap((a, b) => {\n return b.height - a.height;\n });\n\n heap.push(this);\n\n while (heap.size() < groups) {\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.height = this.height;\n\n return root;\n }\n\n /**\n * Traverses the tree depth-first and calls the provided callback with each individual node\n * @param {function} cb - The callback to be called on each node encounter\n */\n traverse(cb) {\n function visit(root, callback) {\n callback(root);\n if (root.children) {\n for (const child of root.children) {\n visit(child, callback);\n }\n }\n }\n visit(this, cb);\n }\n\n /**\n * Returns a list of indices for all the leaves of this cluster.\n * The list is ordered in such a way that a dendrogram could be drawn without crossing branches.\n * @returns {Array}\n */\n indices() {\n const result = [];\n this.traverse((cluster) => {\n if (cluster.isLeaf) {\n result.push(cluster.index);\n }\n });\n return result;\n }\n}\n","import { euclidean } from 'ml-distance-euclidean';\nimport getDistanceMatrix from 'ml-distance-matrix';\nimport { Matrix } from 'ml-matrix';\n\nimport Cluster from './Cluster';\n\nfunction singleLink(dKI, dKJ) {\n return Math.min(dKI, dKJ);\n}\n\nfunction completeLink(dKI, dKJ) {\n return Math.max(dKI, dKJ);\n}\n\nfunction averageLink(dKI, dKJ, dIJ, ni, nj) {\n const ai = ni / (ni + nj);\n const aj = nj / (ni + nj);\n return ai * dKI + aj * dKJ;\n}\n\nfunction weightedAverageLink(dKI, dKJ) {\n return (dKI + dKJ) / 2;\n}\n\nfunction centroidLink(dKI, dKJ, dIJ, ni, nj) {\n const ai = ni / (ni + nj);\n const aj = nj / (ni + nj);\n const b = -(ni * nj) / (ni + nj) ** 2;\n return ai * dKI + aj * dKJ + b * dIJ;\n}\n\nfunction medianLink(dKI, dKJ, dIJ) {\n return dKI / 2 + dKJ / 2 - dIJ / 4;\n}\n\nfunction wardLink(dKI, dKJ, dIJ, ni, nj, nk) {\n const ai = (ni + nk) / (ni + nj + nk);\n const aj = (nj + nk) / (ni + nj + nk);\n const b = -nk / (ni + nj + nk);\n return ai * dKI + aj * dKJ + b * dIJ;\n}\n\nfunction wardLink2(dKI, dKJ, dIJ, ni, nj, nk) {\n const ai = (ni + nk) / (ni + nj + nk);\n const aj = (nj + nk) / (ni + nj + nk);\n const b = -nk / (ni + nj + nk);\n return Math.sqrt(ai * dKI * dKI + aj * dKJ * dKJ + b * dIJ * dIJ);\n}\n\n/**\n * Continuously merge nodes that have the least dissimilarity\n * @param {Array>} data - Array of points to be clustered\n * @param {object} [options]\n * @param {Function} [options.distanceFunction]\n * @param {string} [options.method] - Default: `'complete'`\n * @param {boolean} [options.isDistanceMatrix] - Is the input already a distance matrix?\n * @constructor\n */\nexport function agnes(data, options = {}) {\n const {\n distanceFunction = euclidean,\n method = 'complete',\n isDistanceMatrix = false,\n } = options;\n\n let updateFunc;\n if (!isDistanceMatrix) {\n data = getDistanceMatrix(data, distanceFunction);\n }\n let distanceMatrix = new Matrix(data);\n const numLeaves = distanceMatrix.rows;\n\n // allows to use a string or a given function\n if (typeof method === 'string') {\n switch (method.toLowerCase()) {\n case 'single':\n updateFunc = singleLink;\n break;\n case 'complete':\n updateFunc = completeLink;\n break;\n case 'average':\n case 'upgma':\n updateFunc = averageLink;\n break;\n case 'wpgma':\n updateFunc = weightedAverageLink;\n break;\n case 'centroid':\n case 'upgmc':\n updateFunc = centroidLink;\n break;\n case 'median':\n case 'wpgmc':\n updateFunc = medianLink;\n break;\n case 'ward':\n updateFunc = wardLink;\n break;\n case 'ward2':\n updateFunc = wardLink2;\n break;\n default:\n throw new RangeError(`unknown clustering method: ${method}`);\n }\n } else if (typeof method !== 'function') {\n throw new TypeError('method must be a string or function');\n }\n\n let clusters = [];\n for (let i = 0; i < numLeaves; i++) {\n const cluster = new Cluster();\n cluster.isLeaf = true;\n cluster.index = i;\n clusters.push(cluster);\n }\n\n for (let n = 0; n < numLeaves - 1; n++) {\n const [row, column, distance] = getSmallestDistance(distanceMatrix);\n const cluster1 = clusters[row];\n const cluster2 = clusters[column];\n const newCluster = new Cluster();\n newCluster.size = cluster1.size + cluster2.size;\n newCluster.children.push(cluster1, cluster2);\n newCluster.height = distance;\n\n const newClusters = [newCluster];\n const newDistanceMatrix = new Matrix(\n distanceMatrix.rows - 1,\n distanceMatrix.rows - 1,\n );\n const previous = (newIndex) =>\n getPreviousIndex(newIndex, Math.min(row, column), Math.max(row, column));\n\n for (let i = 1; i < newDistanceMatrix.rows; i++) {\n const prevI = previous(i);\n const prevICluster = clusters[prevI];\n newClusters.push(prevICluster);\n for (let j = 0; j < i; j++) {\n if (j === 0) {\n const dKI = distanceMatrix.get(row, prevI);\n const dKJ = distanceMatrix.get(prevI, column);\n const val = updateFunc(\n dKI,\n dKJ,\n distance,\n cluster1.size,\n cluster2.size,\n prevICluster.size,\n );\n newDistanceMatrix.set(i, j, val);\n newDistanceMatrix.set(j, i, val);\n } else {\n // Just copy distance from previous matrix\n const val = distanceMatrix.get(prevI, previous(j));\n newDistanceMatrix.set(i, j, val);\n newDistanceMatrix.set(j, i, val);\n }\n }\n }\n\n clusters = newClusters;\n distanceMatrix = newDistanceMatrix;\n }\n\n return clusters[0];\n}\n\nfunction getSmallestDistance(distance) {\n let smallest = Infinity;\n let smallestI = 0;\n let smallestJ = 0;\n for (let i = 1; i < distance.rows; i++) {\n for (let j = 0; j < i; j++) {\n if (distance.get(i, j) < smallest) {\n smallest = distance.get(i, j);\n smallestI = i;\n smallestJ = j;\n }\n }\n }\n return [smallestI, smallestJ, smallest];\n}\n\nfunction getPreviousIndex(newIndex, prev1, prev2) {\n newIndex -= 1;\n if (newIndex >= prev1) newIndex++;\n if (newIndex >= prev2) newIndex++;\n return newIndex;\n}\n","export * from './agnes';\n// export * from './diana';\n// export * from './birch';\n// export * './cure';\n// export * from './chameleon';\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","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","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","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.rows;\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.getRow(firstCenterIdx));\n\n // Init closest distances\n let closestDistSquared = new Matrix(1, X.rows);\n for (let i = 0; i < X.rows; i++) {\n closestDistSquared.set(0, i, squaredEuclidean(X.getRow(i), centers[0]));\n }\n let cumSumClosestDistSquared = [cumSum(closestDistSquared.getRow(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.columns));\n const distanceToCandidates = euclideanDistances(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.getRow(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.getRow(bestCandidate);\n closestDistSquared = bestDistSquared;\n cumSumClosestDistSquared = [cumSum(closestDistSquared.getRow(0))];\n probabilities = Matrix.mul(\n closestDistSquared,\n 1 / cumSumClosestDistSquared[0][nSamples - 1]\n );\n }\n return centers;\n}\n\nfunction euclideanDistances(A, B) {\n const result = new Matrix(A.rows, B.rows);\n for (let i = 0; i < A.rows; i++) {\n for (let j = 0; j < B.rows; 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 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';\n\nimport { separateClasses } from './utils';\n\nexport class GaussianNB {\n /**\n * Constructor for the Gaussian Naive Bayes classifier, the parameters here is just for loading purposes.\n * @constructor\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);\n\n if (trainingSet.rows !== trainingLabels.length) {\n throw new RangeError(\n 'the size of the training set and the training labels must be the same.'\n );\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 = separatedClasses[i].mean('column');\n var std = separatedClasses[i].standardDeviation('column', {\n mean: means\n });\n\n var logPriorProbability = Math.log(\n separatedClasses[i].rows / trainingSet.rows\n );\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] = [\n 1 / (C1 * currentStd),\n -2 * currentStd * currentStd\n ];\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 dataset = Matrix.checkMatrix(dataset);\n if (dataset.rows === this.calculateProbabilities[0].length) {\n throw new RangeError(\n 'the dataset must have the same features as the training set'\n );\n }\n\n var predictions = new Array(dataset.rows);\n\n for (var i = 0; i < predictions.length; ++i) {\n predictions[i] = getCurrentClass(\n dataset.getRow(i),\n this.means,\n this.calculateProbabilities\n );\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(\n 'The current model is not a Multinomial Naive Bayes, current model:',\n model.name\n );\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(\n currentCase[j - 1],\n mean[i][j - 1],\n classes[i][j][0],\n classes[i][j][1]\n );\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';\n\nimport { separateClasses } from './utils';\n\nexport class MultinomialNB {\n /**\n * Constructor for Multinomial Naive Bayes, the model parameter is for load purposes.\n * @constructor\n * @param {object} model - for load purposes.\n */\n constructor(model) {\n if (model) {\n this.conditionalProbability = Matrix.checkMatrix(\n model.conditionalProbability\n );\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(\n 'the size of the training set and the training labels must be the same.'\n );\n }\n\n var separateClass = separateClasses(trainingSet, trainingLabels);\n\n this.priorProbability = new Matrix(separateClass.length, 1);\n\n for (var i = 0; i < separateClass.length; ++i) {\n this.priorProbability.set(i, 0, Math.log(\n separateClass[i].rows / trainingSet.rows\n ));\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(\n i,\n Matrix.rowVector(classValues\n .sum('column'))\n .add(1)\n .div(divisor)\n .apply(matrixLog)\n );\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 const v = Matrix.columnVector(this.conditionalProbability\n .clone()\n .mulRowVector(currentElement)\n .sum('row'));\n predictions[i] = v\n .add(this.priorProbability)\n .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.set(i, j, Math.log(this.get(i, j)));\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(function (e) {\n return -e[1];\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, linearDistance, otherChild, 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 (\n bestNodes.size() < maxNodes ||\n Math.abs(linearDistance) < bestNodes.peek()[1]\n ) {\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 {\n // 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 { euclidean as euclideanDistance } from 'ml-distance-euclidean';\n\nimport KDTree from './KDTree';\n\nexport default class KNN {\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 { distance = euclideanDistance, k = classes.size + 1 } = 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(\n 'a custom distance function was used to create the model. Please provide it again'\n );\n }\n if (model.isEuclidean && distance !== euclideanDistance) {\n throw new Error(\n 'the model was created with the default distance function. Do not load it with another one'\n );\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 (\n Array.isArray(dataset[0]) &&\n typeof dataset[0][0] === 'number'\n ) {\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","import Matrix from 'ml-matrix';\n\n/**\n * @private\n * Function that given vector, returns its 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.set(i, j, this.get(i, j) ** 2);\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 = dataset.mean('column');\n var std = dataset.standardDeviation('column', { mean: means, unbiased: 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';\n\nimport * as Utils from './utils';\n\n/**\n * @class PLS\n */\nexport class PLS {\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 = trainingSet.mean('column');\n this.stdDevX = trainingSet.standardDeviation('column', { mean: this.meanX, unbiased: true });\n this.meanY = trainingValues.mean('column');\n this.stdDevY = trainingValues.standardDeviation('column', { mean: this.meanY, unbiased: true });\n\n if (this.scale) {\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.rows - 1, trainingSet.columns);\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().mul(trainingSet));\n var uIndex = maxSumColIndex(trainingValues.clone().mul(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).get(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).get(0, 0);\n var b = num.div(den).get(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.set(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).get(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 Matrix.rowVector(data.sum('column')).maxIndex()[0];\n}\n","import { Matrix, SingularValueDecomposition, inverse } from 'ml-matrix';\n\nimport { initializeMatrices } from './utils';\n\n/**\n * @class KOPLS\n */\nexport class KOPLS {\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 Array(this.orthogonalComp + 1);\n for (let i = 0; i < this.orthogonalComp + 1; i++) {\n kernelX[i] = new Array(this.orthogonalComp + 1);\n }\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.get(i, j) === Infinity) {\n this.set(i, j, 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.get(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 var KTestTrain = this.kernel.compute(toPredict, this.trainingSet);\n\n var temp = KTestTrain;\n KTestTrain = new Array(this.orthogonalComp + 1);\n for (let i = 0; i < this.orthogonalComp + 1; i++) {\n KTestTrain[i] = new Array(this.orthogonalComp + 1);\n }\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 * 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';\nconst defaultOptions = {\n mode: 'index'\n};\n\nmodule.exports = function *(M, N, options) {\n options = Object.assign({}, defaultOptions, options);\n var a = new Array(N);\n var c = new Array(M);\n var b = new Array(N);\n var p = new Array(N + 2);\n var x, y, z;\n\n // init a and b\n for (var i = 0; i < N; i++) {\n a[i] = i;\n if (i < N - M) b[i] = 0;\n else b[i] = 1;\n }\n\n // init c\n for (i = 0; i < M; i++) {\n c[i] = N - M + i;\n }\n\n // init p\n for (i = 0; i < p.length; i++) {\n if (i === 0) p[i] = N + 1;\n else if (i <= N - M) p[i] = 0;\n else if (i <= N) p[i] = i - N + M;\n else p[i] = -2;\n }\n\n function twiddle() {\n var i, j, k;\n j = 1;\n while (p[j] <= 0) {\n j++;\n }\n if (p[j - 1] === 0) {\n for (i = j - 1; i !== 1; i--) {\n p[i] = -1;\n }\n p[j] = 0;\n x = z = 0;\n p[1] = 1;\n y = j - 1;\n } else {\n if (j > 1) {\n p[j - 1] = 0;\n }\n do {\n j++;\n }\n while (p[j] > 0);\n k = j - 1;\n i = j;\n while (p[i] === 0) {\n p[i++] = -1;\n }\n if (p[i] === -1) {\n p[i] = p[k];\n z = p[k] - 1;\n x = i - 1;\n y = k - 1;\n p[k] = -1;\n } else {\n if (i === p[0]) {\n return 0;\n } else {\n p[j] = p[i];\n z = p[i] - 1;\n p[i] = 0;\n x = j - 1;\n y = i - 1;\n }\n }\n }\n return 1;\n }\n\n if (options.mode === 'index') {\n yield c.slice();\n while (twiddle()) {\n c[z] = a[x];\n yield c.slice();\n }\n } else if (options.mode === 'mask') {\n yield b.slice();\n while (twiddle()) {\n b[x] = 1;\n b[y] = 0;\n yield b.slice();\n }\n } else {\n throw new Error('Invalid mode');\n }\n};\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","'use strict';\n\nvar mlMatrix = require('ml-matrix');\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\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.set(i, j, actFunction(this.get(i, j)));\n };\n this.derivate = function (i, j) {\n this.set(i, j, derFunction(this.get(i, j)));\n };\n\n if (options.model) {\n // load model\n this.W = mlMatrix.Matrix.checkMatrix(options.W);\n this.b = mlMatrix.Matrix.checkMatrix(options.b);\n } else {\n // default constructor\n this.W = mlMatrix.Matrix.rand(this.inputSize, this.outputSize);\n this.b = mlMatrix.Matrix.zeros(1, this.outputSize);\n\n this.W.apply(function (i, j) {\n this.set(i, j, this.get(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.transpose().mmul(delta);\n this.db = mlMatrix.Matrix.rowVector(delta.sum('column'));\n\n var aCopy = a.clone();\n return delta.mmul(this.W.transpose()).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\nclass OutputLayer extends Layer {\n constructor(options) {\n super(options);\n\n this.activationFunction = function (i, j) {\n this.set(i, j, Math.exp(this.get(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\nclass FeedForwardNeuralNetworks {\n /**\n * Create a new Feedforward 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 = mlMatrix.Matrix.checkMatrix(features);\n this.dicts = dictOutputs(labels);\n\n var inputSize = features.columns;\n var outputSize = Object.keys(this.dicts.inputs).length;\n\n if (!this.model) {\n this.buildNetwork(inputSize, outputSize);\n }\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 input = this.model[i].forward(input);\n }\n\n // get probabilities\n return input.divColumnVector(input.sum('row'));\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.rows; ++i) {\n probabilities.set(i, this.dicts.inputs[labels[i]], probabilities.get(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 = mlMatrix.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\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 = FeedForwardNeuralNetworks;\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;","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 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;","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 = [];\n for (let i = 0; i < x.length; i++) {\n y.push(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 (n * xY - xSum * ySum) /\n 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: Math.sqrt(rmsd / n)\n };\n }\n}\n","import BaseRegression, {\n checkArrayLength,\n maybeToPrecision\n} from 'ml-regression-base';\nimport { Matrix, MatrixTransposeView, 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 =\n `${maybeToPrecision(this.coefficients[k], precision) + times}x`;\n } else {\n str =\n `${maybeToPrecision(this.coefficients[k], precision) +\n times\n }x${\n sup\n }${this.powers[k]\n }${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.set(i, k, 1);\n } else {\n F.set(i, k, Math.pow(x[i], powers[k]));\n }\n }\n }\n\n const FT = new MatrixTransposeView(F);\n const A = FT.mmul(F);\n const B = FT.mmul(new MatrixTransposeView(Y));\n\n pr.degree = degree - 1;\n pr.powers = powers;\n pr.coefficients = solve(A, B).to1DArray();\n}\n","import BaseRegression, {\n checkArrayLength,\n maybeToPrecision\n} 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 !== 0) {\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, {\n checkArrayLength,\n maybeToPrecision\n} 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 (\n `f(x) = ${\n maybeToPrecision(this.B, precision)\n } * e^(${\n maybeToPrecision(this.A, precision)\n } * x)`\n );\n }\n\n toLaTeX(precision) {\n if (this.A >= 0) {\n return (\n `f(x) = ${\n maybeToPrecision(this.B, precision)\n }e^{${\n maybeToPrecision(this.A, precision)\n }x}`\n );\n } else {\n return (\n `f(x) = \\\\frac{${\n maybeToPrecision(this.B, precision)\n }}{e^{${\n maybeToPrecision(-this.A, precision)\n }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, {\n checkArrayLength,\n maybeToPrecision\n} 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) {\n // 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(\n this.A,\n precision\n )} * x^${maybeToPrecision(this.B, precision)}`;\n }\n\n toLaTeX(precision) {\n let latex = '';\n if (this.B >= 0) {\n latex = `f(x) = ${maybeToPrecision(\n this.A,\n precision\n )}x^{${maybeToPrecision(this.B, precision)}}`;\n } else {\n latex = `f(x) = \\\\frac{${maybeToPrecision(\n this.A,\n precision\n )}}{x^{${maybeToPrecision(-this.B, precision)}}}`;\n }\n latex = latex.replace(/e([+-]?[0-9]+)/g, 'e^{$1}');\n return latex;\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, pseudoInverse } from 'ml-matrix';\n\nexport default class MultivariateLinearRegression {\n constructor(x, y, options = {}) {\n const { intercept = true, statistics = true } = options;\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 y = new Matrix(y);\n if (intercept) {\n x.addColumn(new Array(x.rows).fill(1));\n }\n let xt = x.transpose();\n const xx = xt\n .mmul(x);\n const xy = xt\n .mmul(y);\n const invxx = new SVD(xx)\n .inverse();\n const beta = xy\n .transpose()\n .mmul(invxx)\n .transpose();\n this.weights = beta.to2DArray();\n this.inputs = x.columns;\n this.outputs = y.columns;\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 = y.clone().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.rows - x.columns);\n this.stdError = Math.sqrt(variance);\n this.stdErrorMatrix = pseudoInverse(xx).mul(variance);\n this.stdErrors = this.stdErrorMatrix\n .diagonal()\n .map((d) => Math.sqrt(d));\n this.tStats = this.weights.map((d, i) =>\n (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 } else if (Matrix.isMatrix(x)) {\n const y = new Matrix(x.rows, this.outputs);\n for (let i = 0; i < x.rows; i++) {\n y.setRow(i, this._predict(x.getRow(i)));\n }\n return y;\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","'use strict';\n\nconst { squaredEuclidean } = require('ml-distance-euclidean');\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 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 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 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(\n Math.exp(\n -this.sigma *\n Math.pow(Math.pow(x[i - 1], i) - Math.pow(y[i - 1], i), 2)\n ),\n this.degree\n );\n }\n return sum;\n }\n}\n\nmodule.exports = ANOVAKernel;\n","'use strict';\n\nconst { squaredEuclidean } = require('ml-distance-euclidean');\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');\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');\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 { Matrix, MatrixTransposeView } = require('ml-matrix');\nconst GaussianKernel = require('ml-kernel-gaussian');\nconst PolynomialKernel = require('ml-kernel-polynomial');\nconst SigmoidKernel = require('ml-kernel-sigmoid');\n\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');\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(\n 'first argument must be a valid kernel type or instance'\n );\n }\n }\n\n compute(inputs, landmarks) {\n inputs = Matrix.checkMatrix(inputs);\n if (landmarks === undefined) {\n landmarks = inputs;\n } else {\n landmarks = Matrix.checkMatrix(landmarks);\n }\n if (this.kernelType === 'linear') {\n return inputs.mmul(new MatrixTransposeView(landmarks));\n }\n\n const kernelMatrix = new Matrix(inputs.rows, landmarks.rows);\n if (inputs === landmarks) {\n // fast path, matrix is symmetric\n for (let i = 0; i < inputs.rows; i++) {\n for (let j = i; j < inputs.rows; j++) {\n const value = this.kernelFunction.compute(\n inputs.getRow(i),\n inputs.getRow(j)\n );\n kernelMatrix.set(i, j, value);\n kernelMatrix.set(j, i, value);\n }\n }\n } else {\n for (let i = 0; i < inputs.rows; i++) {\n for (let j = 0; j < landmarks.rows; j++) {\n kernelMatrix.set(\n i,\n j,\n this.kernelFunction.compute(inputs.getRow(i), landmarks.getRow(j))\n );\n }\n }\n }\n return kernelMatrix;\n }\n}\n\nmodule.exports = Kernel;\n","import BaseRegression, {\n checkArrayLength,\n maybeToPrecision\n} from 'ml-regression-base';\nimport median from 'ml-array-median';\n\nexport default class TheilSenRegression extends BaseRegression {\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 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 +=\n ` ${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, {\n checkArrayLength,\n maybeToPrecision\n} from 'ml-regression-base';\nimport { solve } from 'ml-matrix';\n\n/**\n * @class RobustPolynomialRegression\n * @param {Array} x\n * @param {Array} y\n * @param {number} degree - polynomial degree\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 /**\n * Display the formula\n * @param {number} precision - precision for the numbers\n * @return {string}\n */\n toString(precision) {\n return this._toFormula(precision, false);\n }\n\n /**\n * Display the formula in LaTeX format\n * @param {number} precision - precision for the numbers\n * @return {string}\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) +\n times}x`;\n } else {\n str = `${maybeToPrecision(this.coefficients[k], precision) +\n 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 = Array(degree)\n .fill(0)\n .map((_, index) => index);\n\n const tuples = getRandomTuples(x, y, degree);\n\n var min;\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 {\n x: x[i],\n y: y[i]\n }\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 return l % 2 === 0 ? residuals[half - 1] : residuals[half];\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 */\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","/**\n * Returns a new array based on extraction of specific indices of an array\n * @private\n * @param {Array} vector\n * @param {Array} indices\n */\nexport default function selection(vector, indices) {\n let u = []; //new Float64Array(indices.length);\n for (let i = 0; i < indices.length; i++) {\n u[i] = vector[indices[i]];\n }\n return u;\n}\n","/**\n *\n * @private\n * @param {Array of arrays} collection\n */\nexport default function sortCollectionSet(collection) {\n let objectCollection = collection\n .map((value, index) => {\n let key = BigInt(0);\n value.forEach((item) => (key |= BigInt(1) << BigInt(item)));\n return { value, index, key };\n })\n .sort((a, b) => {\n if (a.key - b.key < 0) return -1;\n return 1;\n });\n\n let sorted = [];\n let indices = [];\n\n let key;\n for (let set of objectCollection) {\n if (set.key !== key) {\n key = set.key;\n indices.push([]);\n sorted.push(set.value);\n }\n indices[indices.length - 1].push(set.index);\n }\n\n let result = {\n values: sorted,\n indices: indices,\n };\n return result;\n}\n","import {\n Matrix,\n LuDecomposition,\n solve,\n CholeskyDecomposition,\n} from 'ml-matrix';\n\nimport sortCollectionSet from './util/sortCollectionSet';\n\n/**\n * (Combinatorial Subspace Least Squares) - subfunction for the FC-NNLS\n * @private\n * @param {Matrix} XtX\n * @param {Matrix} XtY\n * @param {Array} Pset\n * @param {Numbers} l\n * @param {Numbers} p\n */\nexport default function cssls(XtX, XtY, Pset, l, p) {\n // Solves the set of equation XtX*K = XtY for the variables in Pset\n // if XtX (or XtX(vars,vars)) is singular, performs the svd and find pseudoinverse, otherwise (even if ill-conditioned) finds inverse with LU decomposition and solves the set of equation\n // it is consistent with matlab results for ill-conditioned matrices (at least consistent with test 'ill-conditionned square X rank 2, Y 3x1' in cssls.test)\n\n let K = Matrix.zeros(l, p);\n if (Pset === null) {\n let choXtX = new CholeskyDecomposition(XtX);\n if (choXtX.isPositiveDefinite() === true) {\n K = choXtX.solve(XtY);\n } else {\n let luXtX = new LuDecomposition(XtX);\n if (luXtX.isSingular() === false) {\n K = luXtX.solve(Matrix.eye(l)).mmul(XtY);\n } else {\n K = solve(XtX, XtY, { useSVD: true });\n }\n }\n } else {\n let sortedPset = sortCollectionSet(Pset).values;\n let sortedEset = sortCollectionSet(Pset).indices;\n if (\n sortedPset.length === 1 &&\n sortedPset[0].length === 0 &&\n sortedEset[0].length === p\n ) {\n return K;\n } else if (\n sortedPset.length === 1 &&\n sortedPset[0].length === l &&\n sortedEset[0].length === p\n ) {\n let choXtX = new CholeskyDecomposition(XtX);\n if (choXtX.isPositiveDefinite() === true) {\n K = choXtX.solve(XtY);\n } else {\n let luXtX = new LuDecomposition(XtX);\n if (luXtX.isSingular() === false) {\n K = luXtX.solve(Matrix.eye(l)).mmul(XtY);\n } else {\n K = solve(XtX, XtY, { useSVD: true });\n }\n }\n } else {\n for (let k = 0; k < sortedPset.length; k++) {\n let cols2Solve = sortedEset[k];\n let vars = sortedPset[k];\n let L;\n let choXtX = new CholeskyDecomposition(XtX.selection(vars, vars));\n if (choXtX.isPositiveDefinite() === true) {\n L = choXtX.solve(XtY.selection(vars, cols2Solve));\n } else {\n let luXtX = new LuDecomposition(XtX.selection(vars, vars));\n if (luXtX.isSingular() === false) {\n L = luXtX\n .solve(Matrix.eye(vars.length))\n .mmul(XtY.selection(vars, cols2Solve));\n } else {\n L = solve(\n XtX.selection(vars, vars),\n XtY.selection(vars, cols2Solve),\n { useSVD: true },\n );\n }\n }\n for (let i = 0; i < L.rows; i++) {\n for (let j = 0; j < L.columns; j++) {\n K.set(vars[i], cols2Solve[j], L.get(i, j));\n }\n }\n }\n }\n }\n return K;\n}\n","import { Matrix } from 'ml-matrix';\n\nimport cssls from './cssls';\n\nexport default function initialisation(X, Y) {\n let n = X.rows;\n let l = X.columns;\n let p = Y.columns;\n let iter = 0;\n\n if (Y.rows !== n) throw new Error('ERROR: matrix size not compatible');\n\n let W = Matrix.zeros(l, p);\n\n // precomputes part of pseudoinverse\n let XtX = X.transpose().mmul(X);\n let XtY = X.transpose().mmul(Y);\n\n let K = cssls(XtX, XtY, null, l, p); // K is lxp\n let Pset = [];\n for (let j = 0; j < p; j++) {\n Pset[j] = [];\n for (let i = 0; i < l; i++) {\n if (K.get(i, j) > 0) {\n Pset[j].push(i);\n } else {\n K.set(i, j, 0);\n } //This is our initial solution, it's the solution found by overwriting the unconstrained least square solution\n }\n }\n let Fset = [];\n for (let j = 0; j < p; j++) {\n if (Pset[j].length !== l) {\n Fset.push(j);\n }\n }\n\n let D = K.clone();\n\n return { n, l, p, iter, W, XtX, XtY, K, Pset, Fset, D };\n}\n","/**\n * Computes the set difference A\\B\n * @private\n * @param {A} set A as an array\n * @param {B} set B as an array\n */\nexport default function setDifference(A, B) {\n let C = [];\n for (let i of A) {\n if (!B.includes(i)) C.push(i);\n }\n return C;\n}\n","import setDifference from './util/setDifference';\n\n// Makes sure the solution has converged\nexport default function optimality(\n iter,\n maxIter,\n XtX,\n XtY,\n Fset,\n Pset,\n W,\n K,\n l,\n p,\n D,\n) {\n if (iter === maxIter) {\n throw new Error('Maximum number of iterations exceeded');\n }\n\n // Check solution for optimality\n let V = XtY.subMatrixColumn(Fset).subtract(XtX.mmul(K.subMatrixColumn(Fset)));\n for (let j = 0; j < Fset.length; j++) {\n W.setColumn(Fset[j], V.subMatrixColumn([j]));\n }\n let Jset = [];\n let fullSet = [];\n for (let i = 0; i < l; i++) {\n fullSet.push(i);\n }\n for (let j = 0; j < Fset.length; j++) {\n let notPset = setDifference(fullSet, Pset[Fset[j]]);\n if (notPset.length === 0) {\n Jset.push(Fset[j]);\n } else if (W.selection(notPset, [Fset[j]]).max() <= 0) {\n Jset.push(Fset[j]);\n }\n }\n Fset = setDifference(Fset, Jset);\n\n // For non-optimal solutions, add the appropriate variables to Pset\n if (Fset.length !== 0) {\n for (let j = 0; j < Fset.length; j++) {\n for (let i = 0; i < l; i++) {\n if (Pset[Fset[j]].includes(i)) W.set(i, Fset[j], -Infinity);\n }\n Pset[Fset[j]].push(W.subMatrixColumn(Fset).maxColumnIndex(j)[0]);\n }\n for (let j = 0; j < Fset.length; j++) {\n D.setColumn(Fset[j], K.getColumn(Fset[j]));\n }\n }\n for (let j = 0; j < p; j++) {\n Pset[j].sort((a, b) => a - b);\n }\n return { Pset, Fset, W };\n}\n","import { Matrix } from 'ml-matrix';\n\nimport selection from './util/selection';\nimport cssls from './cssls';\nimport initialisation from './initialisation';\nimport optimality from './optimality';\n\n/**\n * Fast Combinatorial Non-negative Least Squares with multiple Right Hand Side\n * @param {Matrix|number[][]} X\n * @param {Matrix|number[][]} Y\n * @param {object} [options={}]\n * @param {number} [options.maxIterations] if empty maxIterations is set at 3 times the number of columns of X\n * @returns {Matrix} K\n */\nexport default function fcnnls(X, Y, options = {}) {\n X = Matrix.checkMatrix(X);\n Y = Matrix.checkMatrix(Y);\n let { l, p, iter, W, XtX, XtY, K, Pset, Fset, D } = initialisation(X, Y);\n const { maxIterations = X.columns * 3 } = options;\n\n // Active set algorithm for NNLS main loop\n while (Fset.length > 0) {\n // Solves for the passive variables (uses subroutine below)\n let L = cssls(\n XtX,\n XtY.subMatrixColumn(Fset),\n selection(Pset, Fset),\n l,\n Fset.length,\n );\n for (let i = 0; i < l; i++) {\n for (let j = 0; j < Fset.length; j++) {\n K.set(i, Fset[j], L.get(i, j));\n }\n }\n\n // Finds any infeasible solutions\n let infeasIndex = [];\n for (let j = 0; j < Fset.length; j++) {\n for (let i = 0; i < l; i++) {\n if (L.get(i, j) < 0) {\n infeasIndex.push(j);\n break;\n }\n }\n }\n let Hset = selection(Fset, infeasIndex);\n\n // Makes infeasible solutions feasible (standard NNLS inner loop)\n if (Hset.length > 0) {\n let m = Hset.length;\n let alpha = Matrix.ones(l, m);\n\n while (m > 0 && iter < maxIterations) {\n iter++;\n\n alpha.mul(Infinity);\n\n // Finds indices of negative variables in passive set\n let hRowColIdx = [[], []]; // Indexes work in pairs, each pair reprensents a single element, first array is row index, second array is column index\n let negRowColIdx = [[], []]; // Same as before\n for (let j = 0; j < m; j++) {\n for (let i = 0; i < Pset[Hset[j]].length; i++) {\n if (K.get(Pset[Hset[j]][i], Hset[j]) < 0) {\n hRowColIdx[0].push(Pset[Hset[j]][i]); // i\n hRowColIdx[1].push(j);\n negRowColIdx[0].push(Pset[Hset[j]][i]); // i\n negRowColIdx[1].push(Hset[j]);\n } // Compared to matlab, here we keep the row/column indexing (we are not taking the linear indexing)\n }\n }\n\n for (let k = 0; k < hRowColIdx[0].length; k++) {\n // could be hRowColIdx[1].length as well\n alpha.set(\n hRowColIdx[0][k],\n hRowColIdx[1][k],\n D.get(negRowColIdx[0][k], negRowColIdx[1][k]) /\n (D.get(negRowColIdx[0][k], negRowColIdx[1][k]) -\n K.get(negRowColIdx[0][k], negRowColIdx[1][k])),\n );\n }\n\n let alphaMin = [];\n let minIdx = [];\n for (let j = 0; j < m; j++) {\n alphaMin[j] = alpha.minColumn(j);\n minIdx[j] = alpha.minColumnIndex(j)[0];\n }\n\n alphaMin = Matrix.rowVector(alphaMin);\n for (let i = 0; i < l; i++) {\n alpha.setSubMatrix(alphaMin, i, 0);\n }\n\n let E = new Matrix(l, m);\n E = D.subMatrixColumn(Hset).subtract(\n alpha\n .subMatrix(0, l - 1, 0, m - 1)\n .mul(D.subMatrixColumn(Hset).subtract(K.subMatrixColumn(Hset))),\n );\n for (let j = 0; j < m; j++) {\n D.setColumn(Hset[j], E.subMatrixColumn([j]));\n }\n\n let idx2zero = [minIdx, Hset];\n for (let k = 0; k < m; k++) {\n D.set(idx2zero[0][k], idx2zero[1][k], 0);\n }\n\n for (let j = 0; j < m; j++) {\n Pset[Hset[j]].splice(\n Pset[Hset[j]].findIndex((item) => item === minIdx[j]),\n 1,\n );\n }\n\n L = cssls(XtX, XtY.subMatrixColumn(Hset), selection(Pset, Hset), l, m);\n for (let j = 0; j < m; j++) {\n K.setColumn(Hset[j], L.subMatrixColumn([j]));\n }\n\n Hset = [];\n for (let j = 0; j < K.columns; j++) {\n for (let i = 0; i < l; i++) {\n if (K.get(i, j) < 0) {\n Hset.push(j);\n\n break;\n }\n }\n }\n m = Hset.length;\n }\n }\n\n let newParam = optimality(\n iter,\n maxIterations,\n XtX,\n XtY,\n Fset,\n Pset,\n W,\n K,\n l,\n p,\n D,\n );\n Pset = newParam.Pset;\n Fset = newParam.Fset;\n W = newParam.W;\n }\n\n return K;\n}\n","import { Matrix } from 'ml-matrix';\n\nimport fcnnls from './fcnnls';\n\n/**\n * Fast Combinatorial Non-negative Least Squares with single Right Hand Side\n * @param {Matrix|number[][]} X\n * @param {number[]} y\n * @param {object} [options={}]\n * @param {boolean} [maxIterations] if true or empty maxIterations is set at 3 times the number of columns of X\n * @returns {Array} k\n */\nexport default function fcnnlsVector(X, y, options = {}) {\n if (Array.isArray(y) === false) {\n throw new TypeError('y must be a 1D Array');\n }\n let Y = Matrix.columnVector(y);\n let K = fcnnls(X, Y, options);\n let k = K.to1DArray();\n return k;\n}\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 // The naive `low + high >>> 1` could fail for array lengths > 2**31\n // because `>>>` converts its operands to int32. `low + (high - low >>> 1)`\n // works for array lengths <= 2**32-1 which is also Javascript's max array\n // length.\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';\n\nfunction assertNumber(number) {\n\tif (typeof number !== 'number' || Number.isNaN(number)) {\n\t\tthrow new TypeError('Expected a number');\n\t}\n}\n\nexports.ascending = (left, right) => {\n\tassertNumber(left);\n\tassertNumber(right);\n\treturn left - right;\n};\n\nexports.descending = (left, right) => {\n\tassertNumber(left);\n\tassertNumber(right);\n\treturn right - left;\n};\n","import binarySearch from 'binary-search';\nimport { ascending } from 'num-sort';\n\nexport const largestPrime = 0x7fffffff;\n\nconst primeNumbers = [\n // chunk #0\n largestPrime, // 2^31-1\n\n // chunk #1\n 5,\n 11,\n 23,\n 47,\n 97,\n 197,\n 397,\n 797,\n 1597,\n 3203,\n 6421,\n 12853,\n 25717,\n 51437,\n 102877,\n 205759,\n 411527,\n 823117,\n 1646237,\n 3292489,\n 6584983,\n 13169977,\n 26339969,\n 52679969,\n 105359939,\n 210719881,\n 421439783,\n 842879579,\n 1685759167,\n\n // chunk #2\n 433,\n 877,\n 1759,\n 3527,\n 7057,\n 14143,\n 28289,\n 56591,\n 113189,\n 226379,\n 452759,\n 905551,\n 1811107,\n 3622219,\n 7244441,\n 14488931,\n 28977863,\n 57955739,\n 115911563,\n 231823147,\n 463646329,\n 927292699,\n 1854585413,\n\n // chunk #3\n 953,\n 1907,\n 3821,\n 7643,\n 15287,\n 30577,\n 61169,\n 122347,\n 244703,\n 489407,\n 978821,\n 1957651,\n 3915341,\n 7830701,\n 15661423,\n 31322867,\n 62645741,\n 125291483,\n 250582987,\n 501165979,\n 1002331963,\n 2004663929,\n\n // chunk #4\n 1039,\n 2081,\n 4177,\n 8363,\n 16729,\n 33461,\n 66923,\n 133853,\n 267713,\n 535481,\n 1070981,\n 2141977,\n 4283963,\n 8567929,\n 17135863,\n 34271747,\n 68543509,\n 137087021,\n 274174111,\n 548348231,\n 1096696463,\n\n // chunk #5\n 31,\n 67,\n 137,\n 277,\n 557,\n 1117,\n 2237,\n 4481,\n 8963,\n 17929,\n 35863,\n 71741,\n 143483,\n 286973,\n 573953,\n 1147921,\n 2295859,\n 4591721,\n 9183457,\n 18366923,\n 36733847,\n 73467739,\n 146935499,\n 293871013,\n 587742049,\n 1175484103,\n\n // chunk #6\n 599,\n 1201,\n 2411,\n 4831,\n 9677,\n 19373,\n 38747,\n 77509,\n 155027,\n 310081,\n 620171,\n 1240361,\n 2480729,\n 4961459,\n 9922933,\n 19845871,\n 39691759,\n 79383533,\n 158767069,\n 317534141,\n 635068283,\n 1270136683,\n\n // chunk #7\n 311,\n 631,\n 1277,\n 2557,\n 5119,\n 10243,\n 20507,\n 41017,\n 82037,\n 164089,\n 328213,\n 656429,\n 1312867,\n 2625761,\n 5251529,\n 10503061,\n 21006137,\n 42012281,\n 84024581,\n 168049163,\n 336098327,\n 672196673,\n 1344393353,\n\n // chunk #8\n 3,\n 7,\n 17,\n 37,\n 79,\n 163,\n 331,\n 673,\n 1361,\n 2729,\n 5471,\n 10949,\n 21911,\n 43853,\n 87719,\n 175447,\n 350899,\n 701819,\n 1403641,\n 2807303,\n 5614657,\n 11229331,\n 22458671,\n 44917381,\n 89834777,\n 179669557,\n 359339171,\n 718678369,\n 1437356741,\n\n // chunk #9\n 43,\n 89,\n 179,\n 359,\n 719,\n 1439,\n 2879,\n 5779,\n 11579,\n 23159,\n 46327,\n 92657,\n 185323,\n 370661,\n 741337,\n 1482707,\n 2965421,\n 5930887,\n 11861791,\n 23723597,\n 47447201,\n 94894427,\n 189788857,\n 379577741,\n 759155483,\n 1518310967,\n\n // chunk #10\n 379,\n 761,\n 1523,\n 3049,\n 6101,\n 12203,\n 24407,\n 48817,\n 97649,\n 195311,\n 390647,\n 781301,\n 1562611,\n 3125257,\n 6250537,\n 12501169,\n 25002389,\n 50004791,\n 100009607,\n 200019221,\n 400038451,\n 800076929,\n 1600153859,\n\n // chunk #11\n 13,\n 29,\n 59,\n 127,\n 257,\n 521,\n 1049,\n 2099,\n 4201,\n 8419,\n 16843,\n 33703,\n 67409,\n 134837,\n 269683,\n 539389,\n 1078787,\n 2157587,\n 4315183,\n 8630387,\n 17260781,\n 34521589,\n 69043189,\n 138086407,\n 276172823,\n 552345671,\n 1104691373,\n\n // chunk #12\n 19,\n 41,\n 83,\n 167,\n 337,\n 677,\n 1361,\n 2729,\n 5471,\n 10949,\n 21911,\n 43853,\n 87719,\n 175447,\n 350899,\n 701819,\n 1403641,\n 2807303,\n 5614657,\n 11229331,\n 22458671,\n 44917381,\n 89834777,\n 179669557,\n 359339171,\n 718678369,\n 1437356741,\n\n // chunk #13\n 53,\n 107,\n 223,\n 449,\n 907,\n 1823,\n 3659,\n 7321,\n 14653,\n 29311,\n 58631,\n 117269,\n 234539,\n 469099,\n 938207,\n 1876417,\n 3752839,\n 7505681,\n 15011389,\n 30022781,\n 60045577,\n 120091177,\n 240182359,\n 480364727,\n 960729461,\n 1921458943\n];\n\nprimeNumbers.sort(ascending);\n\nexport function nextPrime(value) {\n let index = binarySearch(primeNumbers, value, ascending);\n if (index < 0) {\n index = ~index;\n }\n return primeNumbers[index];\n}\n","import { largestPrime, nextPrime } from './primeFinder';\n\nconst FREE = 0;\nconst FULL = 1;\nconst REMOVED = 2;\n\nconst defaultInitialCapacity = 150;\nconst defaultMinLoadFactor = 1 / 6;\nconst defaultMaxLoadFactor = 2 / 3;\n\nexport default class 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 =\n options.initialCapacity === undefined\n ? defaultInitialCapacity\n : options.initialCapacity;\n if (initialCapacity < 0) {\n throw new RangeError(\n `initial capacity must not be less than zero: ${initialCapacity}`\n );\n }\n\n const minLoadFactor =\n options.minLoadFactor === undefined\n ? defaultMinLoadFactor\n : options.minLoadFactor;\n const maxLoadFactor =\n options.maxLoadFactor === undefined\n ? defaultMaxLoadFactor\n : 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(\n `minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`\n );\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);\n this.values = newArray(capacity);\n this.state = newArray(capacity);\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(\n this.distinct + 1,\n this.minLoadFactor,\n this.maxLoadFactor\n );\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(\n this.distinct + 1,\n this.minLoadFactor,\n this.maxLoadFactor\n );\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(\n this.distinct,\n this.minLoadFactor,\n this.maxLoadFactor\n );\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 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);\n const newValues = newArray(newCapacity);\n const newState = newArray(newCapacity);\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\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(\n Math.max(size + 1, ((4 * size) / (3 * minLoad + maxLoad)) | 0)\n );\n}\n\nfunction chooseShrinkCapacity(size, minLoad, maxLoad) {\n return nextPrime(\n Math.max(size + 1, ((4 * size) / (minLoad + 3 * maxLoad)) | 0)\n );\n}\n\nfunction newArray(size) {\n return Array(size).fill(0);\n}\n","import HashTable from 'ml-hash-table';\n\nexport class SparseMatrix {\n constructor(rows, columns, options = {}) {\n if (rows instanceof SparseMatrix) {\n // clone\n const other = rows;\n this._init(\n other.rows,\n other.columns,\n other.elements.clone(),\n other.threshold\n );\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(\n 'Number of columns of left matrix are not equal to number of rows of right matrix.'\n );\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, {\n initialCapacity: this.cardinality\n });\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(\n fillTemplateFunction(inplaceOperator, {\n name: operator[i],\n op: operator[0]\n })\n );\n SparseMatrix.prototype[`${operator[i]}S`] = eval(\n fillTemplateFunction(inplaceOperatorScalar, {\n name: `${operator[i]}S`,\n op: operator[0]\n })\n );\n SparseMatrix.prototype[`${operator[i]}M`] = eval(\n fillTemplateFunction(inplaceOperatorMatrix, {\n name: `${operator[i]}M`,\n op: operator[0]\n })\n );\n\n SparseMatrix[operator[i]] = eval(\n fillTemplateFunction(staticOperator, { name: operator[i] })\n );\n }\n}\n\nvar methods = [['~', 'not']];\n\n[\n 'abs',\n 'acos',\n 'acosh',\n 'asin',\n 'asinh',\n 'atan',\n 'atanh',\n 'cbrt',\n 'ceil',\n 'clz32',\n 'cos',\n 'cosh',\n 'exp',\n 'expm1',\n 'floor',\n 'fround',\n 'log',\n 'log1p',\n 'log10',\n 'log2',\n 'round',\n 'sign',\n 'sin',\n 'sinh',\n 'sqrt',\n 'tan',\n 'tanh',\n '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(\n fillTemplateFunction(inplaceMethod, {\n name: method[i],\n method: method[0]\n })\n );\n SparseMatrix[method[i]] = eval(\n fillTemplateFunction(staticMethod, { name: method[i] })\n );\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","export default function additiveSymmetric(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function avg(a, b) {\n var ii = a.length;\n var max = 0;\n var ans = 0;\n var 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","export default function bhattacharyya(a, b) {\n var ii = a.length;\n var 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","export default function canberra(a, b) {\n var ii = a.length;\n var 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","export default function chebyshev(a, b) {\n var ii = a.length;\n var max = 0;\n var 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","export default function clark(a, b) {\n var i = 0;\n var ii = a.length;\n var d = 0;\n for (; i < ii; i++) {\n d += Math.sqrt(\n ((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i]))\n );\n }\n return 2 * d;\n}\n","export default 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","import czekanowskiSimilarity from '../similarities/czekanowski';\n\nexport default function czekanowskiDistance(a, b) {\n return 1 - czekanowskiSimilarity(a, b);\n}\n","export default function dice(a, b) {\n var ii = a.length;\n var p = 0;\n var q1 = 0;\n var 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","export default function divergence(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function fidelity(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return ans;\n}\n","export default function gower(a, b) {\n var ii = a.length;\n var 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","export default function harmonicMean(a, b) {\n var ii = a.length;\n var 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","export default function hellinger(a, b) {\n var ii = a.length;\n var 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","export default function innerProduct(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans += a[i] * b[i];\n }\n return ans;\n}\n","export default function intersection(a, b) {\n var ii = a.length;\n var 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","export default function jaccard(a, b) {\n var ii = a.length;\n var p1 = 0;\n var p2 = 0;\n var q1 = 0;\n var 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","export default function jeffreys(a, b) {\n var ii = a.length;\n var 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","export default function jensenDifference(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n (a[i] * Math.log(a[i]) + b[i] * Math.log(b[i])) / 2 -\n ((a[i] + b[i]) / 2) * Math.log((a[i] + b[i]) / 2);\n }\n return ans;\n}\n","export default function jensenShannon(a, b) {\n var ii = a.length;\n var p = 0;\n var 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","export default function kdivergence(a, b) {\n var ii = a.length;\n var 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","export default function kulczynski(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function kullbackLeibler(a, b) {\n var ii = a.length;\n var 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","export default function kumarHassebrook(a, b) {\n var ii = a.length;\n var p = 0;\n var p2 = 0;\n var 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","export default function kumarJohnson(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n 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","export default function lorentzian(a, b) {\n var ii = a.length;\n var 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","export default function manhattan(a, b) {\n var i = 0;\n var ii = a.length;\n var d = 0;\n for (; i < ii; i++) {\n d += Math.abs(a[i] - b[i]);\n }\n return d;\n}\n","export default function matusita(a, b) {\n var ii = a.length;\n var 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","export default function minkowski(a, b, p) {\n var i = 0;\n var ii = a.length;\n var 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","export default function motyka(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function neyman(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function pearson(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function probabilisticSymmetric(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function ruzicka(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function soergel(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function sorensen(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function squared(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function squaredChord(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i]));\n }\n return ans;\n}\n","export default function taneja(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n ((a[i] + b[i]) / 2) *\n Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i])));\n }\n return ans;\n}\n","export default function tanimoto(a, b, bitvector) {\n if (bitvector) {\n var inter = 0;\n var 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 }\n return inter / union;\n } else {\n var ii = a.length;\n var p = 0;\n var q = 0;\n var 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","import tanimotoS from '../similarities/tanimoto';\n\nexport default function tanimoto(a, b, bitvector) {\n if (bitvector) {\n return 1 - tanimotoS(a, b, bitvector);\n } else {\n var ii = a.length;\n var p = 0;\n var q = 0;\n var 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","export default function topsoe(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n a[i] * Math.log((2 * a[i]) / (a[i] + b[i])) +\n b[i] * Math.log((2 * b[i]) / (a[i] + b[i]));\n }\n return ans;\n}\n","export default function waveHedges(a, b) {\n var ii = a.length;\n var 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","import binarySearch from 'binary-search';\nimport { ascending } from 'num-sort';\n\n/**\n * Function that creates the tree\n * @param {Array>} spectrum\n * @param {object} [options]\n * @return {Tree|null}\n * left and right have the same structure than the parent,\n * or are null if they are leaves\n */\nexport function createTree(spectrum, options = {}) {\n var X = spectrum[0];\n const {\n minWindow = 0.16,\n threshold = 0.01,\n from = X[0],\n to = X[X.length - 1]\n } = options;\n\n return mainCreateTree(\n spectrum[0],\n spectrum[1],\n from,\n to,\n minWindow,\n threshold\n );\n}\n\nfunction mainCreateTree(X, Y, from, to, minWindow, threshold) {\n if (to - from < minWindow) {\n return null;\n }\n\n // search first point\n var start = binarySearch(X, from, ascending);\n if (start < 0) {\n start = ~start;\n }\n\n // stop at last point\n var sum = 0;\n var center = 0;\n for (var i = start; i < X.length; i++) {\n if (X[i] >= to) {\n break;\n }\n sum += Y[i];\n center += X[i] * Y[i];\n }\n\n if (sum < threshold) {\n return null;\n }\n\n center /= sum;\n if (center - from < 1e-6 || to - center < 1e-6) {\n return null;\n }\n if (center - from < minWindow / 4) {\n return mainCreateTree(X, Y, center, to, minWindow, threshold);\n } else {\n if (to - center < minWindow / 4) {\n return mainCreateTree(X, Y, from, center, minWindow, threshold);\n } else {\n return new Tree(\n sum,\n center,\n mainCreateTree(X, Y, from, center, minWindow, threshold),\n mainCreateTree(X, Y, center, to, minWindow, threshold)\n );\n }\n }\n}\n\nclass Tree {\n constructor(sum, center, left, right) {\n this.sum = sum;\n this.center = center;\n this.left = left;\n this.right = right;\n }\n}\n","import { createTree } from './createTree';\n\n/**\n * Similarity between two nodes\n * @param {Tree|Array>} a - tree A node\n * @param {Tree|Array>} b - tree B node\n * @param {object} [options]\n * @return {number} similarity measure between tree nodes\n */\nexport function getSimilarity(a, b, options = {}) {\n const { alpha = 0.1, beta = 0.33, gamma = 0.001 } = options;\n\n if (a === null || b === null) {\n return 0;\n }\n if (Array.isArray(a)) {\n a = createTree(a);\n }\n if (Array.isArray(b)) {\n b = createTree(b);\n }\n\n var C =\n (alpha * Math.min(a.sum, b.sum)) / Math.max(a.sum, b.sum) +\n (1 - alpha) * Math.exp(-gamma * Math.abs(a.center - b.center));\n\n return (\n beta * C +\n ((1 - beta) *\n (getSimilarity(a.left, b.left, options) +\n getSimilarity(a.right, b.right, options))) /\n 2\n );\n}\n","import { getSimilarity } from './getSimilarity';\n\nexport { createTree } from './createTree';\n\nexport function treeSimilarity(A, B, options = {}) {\n return getSimilarity(A, B, options);\n}\n\nexport function getFunction(options = {}) {\n return (A, B) => getSimilarity(A, B, options);\n}\n","export default function cosine(a, b) {\n var ii = a.length;\n var p = 0;\n var p2 = 0;\n var 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","import diceD from '../distances/dice';\n\nexport default function dice(a, b) {\n return 1 - diceD(a, b);\n}\n","import intersectionD from '../distances/intersection';\n\nexport default function intersection(a, b) {\n return 1 - intersectionD(a, b);\n}\n","import jaccardD from '../distances/jaccard';\n\nexport default function jaccard(a, b) {\n return 1 - jaccardD(a, b);\n}\n","import kulczynskiD from '../distances/kulczynski';\n\nexport default function kulczynski(a, b) {\n return 1 / kulczynskiD(a, b);\n}\n","import motykaD from '../distances/motyka';\n\nexport default function motyka(a, b) {\n return 1 - motykaD(a, b);\n}\n","import mean from 'ml-array-mean';\n\nimport cosine from './cosine';\n\nexport default function pearson(a, b) {\n var avgA = mean(a);\n var avgB = mean(b);\n\n var newA = new Array(a.length);\n var newB = new Array(b.length);\n for (var i = 0; i < newA.length; i++) {\n newA[i] = a[i] - avgA;\n newB[i] = b[i] - avgB;\n }\n\n return cosine(newA, newB);\n}\n","import squaredChordD from '../distances/squaredChord';\n\nexport default function squaredChord(a, b) {\n return 1 - squaredChordD(a, b);\n}\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\nconst measures = require('./measures');\n\nclass Performance {\n /**\n *\n * @param prediction - The prediction matrix\n * @param target - The target matrix (values: truthy for same class, falsy for different class)\n * @param options\n *\n * @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)\n * @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)\n */\n constructor(prediction, target, options) {\n options = options || {};\n if (prediction.length !== target.length || prediction[0].length !== target[0].length) {\n throw new Error('dimensions of prediction and target do not match');\n }\n const rows = prediction.length;\n const columns = prediction[0].length;\n const isDistance = !options.max;\n\n const predP = [];\n\n if (options.all) {\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n predP.push({\n pred: prediction[i][j],\n targ: target[i][j]\n });\n }\n }\n } else {\n if (rows < 3 || rows !== columns) {\n throw new Error('When \"all\" option is false, the prediction matrix must be square and have at least 3 columns');\n }\n for (var i = 0; i < rows - 1; i++) {\n for (var j = i + 1; j < columns; j++) {\n predP.push({\n pred: prediction[i][j],\n targ: target[i][j]\n });\n }\n }\n }\n\n if (isDistance) {\n predP.sort((a, b) => 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\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\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 }\n output = options.output;\n } else {\n output = new Array(cond);\n }\n\n var i;\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 } else if (options.value === 'replicate') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0]) output[i] = data[0];\n else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];\n else output[i] = data[len - 1];\n }\n } else if (options.value === 'symmetric') {\n if (options.size[0] > len || options.size[1] > len) {\n throw new RangeError(\n 'expanded value should not be bigger than the data length'\n );\n }\n for (i = 0; i < cond; i++) {\n if (i < options.size[0]) output[i] = data[options.size[0] - 1 - i];\n else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];\n else output[i] = data[2 * len + options.size[0] - i - 1];\n }\n } else {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0]) output[i] = options.value;\n else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];\n else 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 }\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 = Object.assign({}, defaultOptions, options);\n if (Array.isArray(data)) {\n if (Array.isArray(data[0])) return matrixCase(data, options);\n else return arrayCase(data, options);\n } else {\n throw new TypeError('data should be an array');\n }\n}\n\nmodule.exports = padArray;\n","import { Matrix, MatrixTransposeView, inverse } from 'ml-matrix';\nimport padArray from 'ml-pad-array';\n\nconst 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 */\nexport default function savitzkyGolay(data, h, options) {\n options = Object.assign({}, defaultOptions, options);\n if (\n options.windowSize % 2 === 0 ||\n options.windowSize < 5 ||\n !Number.isInteger(options.windowSize)\n ) {\n throw new RangeError(\n 'Invalid window size (should be odd and at least 5 integer number)',\n );\n }\n if (options.derivative < 0 || !Number.isInteger(options.derivative)) {\n throw new RangeError('Derivative should be a positive integer');\n }\n if (options.polynomial < 1 || !Number.isInteger(options.polynomial)) {\n throw new RangeError('Polynomial should be a positive integer');\n }\n\n let C, norm;\n let step = Math.floor(options.windowSize / 2);\n\n if (options.pad === 'pre') {\n data = padArray(data, { size: step, value: options.padValue });\n }\n\n let ans = new Array(data.length - 2 * step);\n\n if (\n options.windowSize === 5 &&\n options.polynomial === 2 &&\n (options.derivative === 1 || options.derivative === 2)\n ) {\n if (options.derivative === 1) {\n C = [-2, -1, 0, 1, 2];\n norm = 10;\n } else {\n C = [2, -1, -2, -1, 2];\n norm = 7;\n }\n } else {\n let J = Matrix.ones(options.windowSize, options.polynomial + 1);\n let inic = -(options.windowSize - 1) / 2;\n for (let i = 0; i < J.rows; i++) {\n for (let j = 0; j < J.columns; j++) {\n if (inic + 1 !== 0 || j !== 0) J.set(i, j, Math.pow(inic + i, j));\n }\n }\n let Jtranspose = new MatrixTransposeView(J);\n let Jinv = inverse(Jtranspose.mmul(J));\n C = Jinv.mmul(Jtranspose);\n C = C.getRow(options.derivative);\n norm = 1;\n }\n let det = norm * Math.pow(h, options.derivative);\n for (let k = step; k < data.length - step; k++) {\n let d = 0;\n for (let l = 0; l < C.length; l++) 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","// 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\nvar eightBits = require('./creator');\n\n/**\n * Count the number of true values in an array\n * @param {Array} arr\n * @return {number}\n */\nfunction count(arr) {\n var c = 0;\n for (var i = 0; i < arr.length; i++) {\n c += eightBits[arr[i] & 0xff] + eightBits[(arr[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","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","import max from 'ml-array-max';\nimport sum from 'ml-array-sum';\n\n/**\n * Computes the norm of the given values\n * @param {Array} input\n * @param {object} [options={}]\n * @param {string} [options.algorithm='absolute'] absolute, sum or max\n * @return {number}\n */\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 {\n var absoluteSumValue = absoluteSum(input);\n if (absoluteSumValue === 0) return input.slice(0);\n return input.map(function (element) {\n return element / absoluteSumValue;\n });\n }\n\n case 'max':\n {\n var maxValue = max(input);\n if (maxValue === 0) return input.slice(0);\n return input.map(function (element) {\n return element / maxValue;\n });\n }\n\n case 'sum':\n {\n var sumValue = sum(input);\n if (sumValue === 0) return input.slice(0);\n return input.map(function (element) {\n return element / sumValue;\n });\n }\n\n default:\n throw new Error(\"norm: unknown algorithm: \".concat(algorithm));\n }\n}\n\nfunction absoluteSum(input) {\n var sumValue = 0;\n\n for (var i = 0; i < input.length; i++) {\n sumValue += Math.abs(input[i]);\n }\n\n return sumValue;\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 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","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 { ascending, descending } 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, descending);\n } else {\n index = binarySearch(x, target, ascending);\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","import mean from 'ml-array-mean';\n\n/**\n *\n * @param {object} points\n * @param {Array} points.x\n * @param {Array} points.y\n * @param {object} [options]\n * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n.\n * @return {number}\n */\nexport default function covariance(points, options = {}) {\n const { x, y } = points;\n const { unbiased = true } = options;\n\n const meanX = mean(x);\n const meanY = mean(y);\n\n var error = 0;\n\n for (let i = 0; i < x.length; i++) {\n error += (x[i] - meanX) * (y[i] - meanY);\n }\n\n if (unbiased) {\n return error / (x.length - 1);\n } else {\n return error / x.length;\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 { ascending, descending } 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, descending);\n } else {\n index = binarySearch(x, value, ascending);\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","/**\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 if (numberOfPoints < 2) {\n throw new RangeError(\"'numberOfPoints' option must be greater than 1\");\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 = xResult.concat(zoneResult.x);\n yResult = yResult.concat(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, 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","import { DecisionTreeClassifier, DecisionTreeRegression } from 'ml-cart';\nimport {\n RandomForestClassifier,\n RandomForestRegression\n} from 'ml-random-forest';\n\n// Try to keep this list in the same structure as the README.\n\n// Unsupervised learning\nexport { PCA } from 'ml-pca';\nimport * as HClust from 'ml-hclust';\nexport { HClust };\nexport { default as KMeans } from 'ml-kmeans';\n\n// Supervised learning\nimport * as NaiveBayes from 'ml-naivebayes';\nexport { NaiveBayes };\nexport { default as KNN } from 'ml-knn';\nexport { PLS, KOPLS } from 'ml-pls';\nexport { default as CrossValidation } from 'ml-cross-validation';\nexport { default as ConfusionMatrix } from 'ml-confusion-matrix';\nexport { DecisionTreeClassifier };\nexport { RandomForestClassifier };\n\n// Artificial neural networks\nexport { default as FNN } from 'ml-fnn';\nexport { default as SOM } from 'ml-som';\n\n// Regression\nexport {\n SimpleLinearRegression,\n PolynomialRegression,\n MultivariateLinearRegression,\n PowerRegression,\n ExponentialRegression,\n TheilSenRegression,\n RobustPolynomialRegression\n} from 'ml-regression';\nexport { DecisionTreeRegression };\nexport { RandomForestRegression };\n\n// Optimization\nexport { default as levenbergMarquardt } from 'ml-levenberg-marquardt';\nimport * as FCNNLS from 'ml-fcnnls';\nexport { FCNNLS };\n\n// Math\nimport * as MatrixLib from 'ml-matrix';\nconst {\n Matrix,\n SVD,\n EVD,\n CholeskyDecomposition,\n LuDecomposition,\n QrDecomposition\n} = MatrixLib;\nexport {\n MatrixLib,\n Matrix,\n SVD,\n EVD,\n CholeskyDecomposition,\n LuDecomposition,\n QrDecomposition\n};\n\nexport { SparseMatrix } from 'ml-sparse-matrix';\nexport { default as Kernel } from 'ml-kernel';\nimport { distance, similarity } from 'ml-distance';\nexport { distance as Distance, similarity as Similarity };\nexport { default as distanceMatrix } from 'ml-distance-matrix';\nexport { default as XSadd } from 'ml-xsadd';\n\n// Statistics\nexport { default as Performance } from 'ml-performance';\n\n// Data preprocessing\nexport { default as savitzkyGolay } from 'ml-savitzky-golay';\n\n// Utility\nexport { default as BitArray } from 'ml-bit-array';\nexport { default as HashTable } from 'ml-hash-table';\nexport { default as padArray } from 'ml-pad-array';\nexport { default as binarySearch } from 'binary-search';\nimport * as numSort from 'num-sort';\nexport { numSort };\nexport { default as Random } from 'ml-random';\n\nimport min from 'ml-array-min';\nimport max from 'ml-array-max';\nimport median from 'ml-array-median';\nimport mean from 'ml-array-mean';\nimport mode from 'ml-array-mode';\nimport normed from 'ml-array-normed';\nimport rescale from 'ml-array-rescale';\nimport sequentialFill from 'ml-array-sequential-fill';\nimport sum from 'ml-array-sum';\nimport standardDeviation from 'ml-array-standard-deviation';\nimport variance from 'ml-array-variance';\nexport const Array = {\n min,\n max,\n median,\n mean,\n mode,\n normed,\n rescale,\n sequentialFill,\n standardDeviation,\n sum,\n variance\n};\n\nimport centroidsMerge from 'ml-array-xy-centroids-merge';\nimport closestX from 'ml-arrayxy-closestx';\nimport covariance from 'ml-array-xy-covariance';\nimport maxMerge from 'ml-array-xy-max-merge';\nimport maxY from 'ml-array-xy-max-y';\nimport sortX from 'ml-array-xy-sort-x';\nimport uniqueX from 'ml-arrayxy-uniquex';\nimport weightedMerge from 'ml-array-xy-weighted-merge';\nimport equallySpaced from 'ml-array-xy-equally-spaced';\nimport filterX from 'ml-array-xy-filter-x';\nexport const ArrayXY = {\n centroidsMerge,\n closestX,\n covariance,\n maxMerge,\n maxY,\n sortX,\n uniqueX,\n weightedMerge,\n equallySpaced,\n filterX\n};\n"],"names":["toString","Object","prototype","isAnyArray","object","call","endsWith","max","input","isArray","TypeError","length","maxValue","i","min","minValue","rescale","options","arguments","undefined","output","Array","currentMin","currentMax","RangeError","_options$min","autoMinMax","_options$max","factor","checkRowIndex","matrix","index","outer","rows","checkColumnIndex","columns","checkRowVector","vector","to1DArray","checkColumnVector","checkIndices","rowIndices","columnIndices","row","checkRowIndices","column","checkColumnIndices","rowOut","some","r","from","columnOut","c","checkRange","startRow","endRow","startColumn","endColumn","checkNumber","newArray","value","array","push","name","sumByRow","sum","j","get","sumByColumn","sumAll","v","productByRow","productByColumn","productAll","varianceByRow","unbiased","mean","cols","variance","sum1","sum2","x","varianceByColumn","varianceAll","size","centerByRow","set","centerByColumn","centerAll","getScaleByRow","scale","Math","pow","sqrt","scaleByRow","getScaleByColumn","scaleByColumn","getScaleAll","divider","scaleAll","inspectMatrix","indent","repeat","indentData","constructor","inspectData","maxRows","maxColumns","maxNumSize","maxI","maxJ","result","line","formatNumber","join","num","numStr","String","padEnd","precise","toPrecision","exponential","toExponential","eIndex","indexOf","e","substring","installMathOperations","AbstractMatrix","Matrix","add","addS","addM","checkMatrix","newMatrix","sub","subS","subM","subtract","subtractS","subtractM","mul","mulS","mulM","multiply","multiplyS","multiplyM","div","divS","divM","divide","divideS","divideM","mod","modS","modM","modulus","modulusS","modulusM","and","andS","andM","or","orS","orM","xor","xorS","xorM","leftShift","leftShiftS","leftShiftM","signPropagatingRightShift","signPropagatingRightShiftS","signPropagatingRightShiftM","rightShift","rightShiftS","rightShiftM","zeroFillRightShift","zeroFillRightShiftS","zeroFillRightShiftM","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","tan","tanh","trunc","arg0","powS","powM","from1DArray","newRows","newColumns","newData","rowVector","columnVector","zeros","ones","fill","rand","random","randInt","Number","isInteger","interval","eye","diag","data","l","matrix1","matrix2","isMatrix","klass","apply","callback","to2DArray","copy","toJSON","isRowVector","isColumnVector","isVector","isSquare","isSymmetric","isEchelonForm","previousColumn","checked","isReducedEchelonForm","k","echelonForm","clone","h","iMax","swapRows","tmp","reducedEchelonForm","m","n","maxRow","p","pivot","Error","setSubMatrix","neg","getRow","getRowVector","setRow","row1","row2","temp","getColumn","getColumnVector","setColumn","swapColumns","column1","column2","addRowVector","subRowVector","mulRowVector","divRowVector","addColumnVector","subColumnVector","mulColumnVector","divColumnVector","mulRow","mulColumn","maxIndex","idx","minIndex","maxRowIndex","minRow","minRowIndex","maxColumn","maxColumnIndex","minColumn","minColumnIndex","norm","type","cumulativeSum","dot","vector2","vector1","mmul","other","Bcolj","Float64Array","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","y","r1","c1","r2","c2","console","warn","embed","mat","resultat","blockMult","a","b","halfRows","parseInt","halfCols","subMatrix","scaleRows","isFinite","scaleColumns","flipRows","middle","first","last","flipColumns","kroneckerProduct","q","transpose","sortRows","compareFunction","compareNumbers","sort","sortColumns","subMatrixRow","indices","subMatrixColumn","selection","rowIndex","columnIndex","trace","by","product","standardDeviation","center","Symbol","for","randomInt","diagonal","identity","negate","tensorProduct","nRows","nColumns","arrayData","removeRow","splice","addRow","removeColumn","newRow","addColumn","BaseView","MatrixColumnView","MatrixColumnSelectionView","MatrixFlipColumnView","MatrixFlipRowView","MatrixRowView","MatrixRowSelectionView","MatrixSelectionView","MatrixSubView","MatrixTransposeView","WrapperMatrix1D","_calculateIndex","WrapperMatrix2D","wrap","LuDecomposition","lu","pivotVector","pivotSign","t","LUcolj","kmax","LU","isSingular","col","solve","count","X","determinant","lowerTriangularMatrix","upperTriangularMatrix","pivotPermutationVector","hypotenuse","QrDecomposition","qr","rdiag","nrm","QR","Rdiag","isFullRank","orthogonalMatrix","SingularValueDecomposition","computeLeftSingularVectors","computeRightSingularVectors","autoTranspose","wantu","Boolean","wantv","swapped","aux","nu","ni","U","V","work","si","nct","nrt","mrc","pp","eps","EPSILON","kase","alpha","MIN_VALUE","isNaN","ks","f","cs","sn","sp","spm1","epm1","sk","ek","shift","g","iter","Y","threshold","scols","Ls","rightSingularVectors","VL","vrows","urows","VLU","solveForDiagonal","inverse","vcols","ucols","condition","norm2","rank","tol","ii","leftSingularVectors","diagonalMatrix","useSVD","leftHandSide","rightHandSide","d","subMatrix0","subMatrix1","subMatrix2","xrange","exception","range","dependenciesOneRow","error","thresholdValue","thresholdError","returnArray","linearDependencies","results","Abis","svd","pseudoInverse","svdSolution","SVD","covariance","xMatrix","yMatrix","yIsSame","cov","correlation","sdx","sdy","corr","EigenvalueDecomposition","assumeSymmetric","tred2","tql2","H","ort","orthes","hqr2","realEigenvalues","imaginaryEigenvalues","eigenvectorMatrix","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","L","isPositiveDefinite","B","nipals","scaleScores","maxIterations","terminationCriteria","u","diff","tOld","counter","xResidual","residual","yResidual","betas","sumValue","toDiscreteDistribution","numberOfClasses","counts","giniImpurity","probabilities","getNumberOfClasses","filter","val","arr","map","reduce","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","Infinity","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","load","DecisionTreeRegression","trainingValues","SMALLEST_UNSAFE_INTEGER","LARGEST_SAFE_INTEGER","UINT32_MAX","UINT32_SIZE","INT32_SIZE","INT32_MAX","UINT21_SIZE","UINT21_MAX","int32","engine","next","addend","int53","int53Full","uint32","uint53","uint53Full","isPowerOfTwoMinusOne","bitmask","masking","downscaleToLoopCheckedRange","extendedRange","maximum","downscaleToRange","isEvenlyDivisibleByMaxInt32","upscaleWithHighMasking","upscaleToLoopCheckedRange","upscaleWithinU53","highRange","upscaleWithinI53AndLoopCheck","integer","DEFAULT_STRING_POOL","string","pool","poolLength","charAt","LOWER_HEX_POOL","lowerHex","upperHex","toUpperCase","stringRepeat","pattern","_","nativeMath","I32Array","buffer","ArrayBuffer","view","Int32Array","createEntropy","Date","getTime","imul","UINT16_MAX","ah","al","bh","bl","ARRAY_SIZE","ARRAY_MAX","M","ARRAY_SIZE_MINUS_M","A","MersenneTwister19937","uses","seed","initial","seedWithArray","source","autoSeed","refreshData","temper","getUseCount","discard","previous","sourceLength","checkFloat","examplesBaggingWithReplacement","trainingValue","Random","Xr","featureBagging","replacement","toRet","usedIndex","Set","has","RandomForestBase","maxFeatures","nEstimators","treeOptions","isClassifier","indexes","useSampleBagging","Estimator","DTClassifier","DTRegression","estimators","est","res","values","predictionValues","RandomForestClassifier","baseModel","mode","pop","_ref","module","exports","window","median","quickSelectMedian","slice","selectionMethods","arrayMean","arrayMedian","selectionMethod","RandomForestRegression","PCA","dataset","means","stdevs","S","R","excludedFeatures","isCovarianceMatrix","method","nCompNIPALS","ignoreZeroVariance","_computeFromCovarianceMatrix","_adjust","covarianceMatrix","_computeWithNIPALS","singularValues","eigenvalues","singularValue","nComponents","invert","getExplainedVariance","getCumulativeVariance","explained","getEigenvectors","getEigenvalues","getStandardDeviations","getLoadings","evd","EVD","reverse","dc","NIPALS","squaredEuclidean","euclidean","distanceMatrix","distanceFn","getMatrix","Heap","defaultCmp","heapify","heappop","heappush","heappushpop","heapreplace","insort","nlargest","nsmallest","updateItem","_siftdown","_siftup","lo","hi","cmp","mid","concat","item","lastelt","returnitem","_i","_j","_len","_ref1","_results","_results1","pos","elem","los","startpos","newitem","parent","parentpos","childpos","endpos","rightpos","replace","pushpop","nodes","peek","contains","clear","empty","heap","toArray","insert","top","front","factory","this","require$$0","Cluster","children","height","isLeaf","cut","list","ans","group","groups","forEach","child","traverse","cb","visit","cluster","singleLink","dKI","dKJ","completeLink","averageLink","dIJ","nj","ai","aj","weightedAverageLink","centroidLink","medianLink","wardLink","nk","wardLink2","agnes","distanceFunction","isDistanceMatrix","updateFunc","getDistanceMatrix","numLeaves","toLowerCase","clusters","distance","getSmallestDistance","cluster1","cluster2","newCluster","newClusters","newDistanceMatrix","newIndex","getPreviousIndex","prevI","prevICluster","smallest","smallestI","smallestJ","prev1","prev2","nearestVector","listVectors","similarityFunction","vectorIndex","maxSim","sim","minDist","MAX_VALUE","dist","calculateDistanceMatrix","updateClusterID","centers","clusterID","updateCenters","prevCenters","K","nDim","centersLen","dim","id","hasConverged","oldCenters","tolerance","LOOP","FLOAT_MUL","sh1","sh2","sh3","multiply_uint32","nlo","nhi","XSadd","now","state","Uint32Array","init","getFloat","bind","getUint32","nextState","periodCertification","PROB_TOLERANCE","randomChoice","valuesArr","cumSum","getArray","randomIndex","seedOrRandom","xsadd","XSAdd","randomGenerator","choice","randomSample","mostDistant","maxDist","minDistCent","kmeanspp","nSamples","localTrials","firstCenterIdx","closestDistSquared","cumSumClosestDistSquared","candidateIdx","candidates","distanceToCandidates","euclideanDistances","bestCandidate","bestPot","bestDistSquared","newDistSquared","newPot","distanceSymbol","KMeansResult","centroids","converged","iterations","nearest","centroid","computeInformation","enrichedCentroids","withIterations","initialization","step","newCenters","kmeansGenerator","stepNumber","stepResult","kmeans","separateClasses","features","classes","totalPerClasses","separatedClasses","currentIndex","GaussianNB","reload","calculateProbabilities","C1","PI","std","logPriorProbability","currentStd","getCurrentClass","modelName","currentCase","maxProbability","predictedClass","currentProbability","calculateLogProbability","C2","MultinomialNB","conditionalProbability","priorProbability","separateClass","classValues","total","divisor","matrixLog","Node","obj","KDTree","points","metric","dimensions","restoreParent","buildTree","toJSONImpl","point","maxNodes","maxDistance","bestNodes","BinaryHeap","nearestSearch","ownDistance","linearPoint","bestChild","linearDistance","otherChild","saveNode","content","src","dest","depth","scoreFunction","element","bubbleUp","end","sinkDown","parentN","elemScore","child2N","child1N","swap","child1","child1Score","child2","child2Score","KNN","labels","kdTree","isEuclidean","euclideanDistance","getSinglePrediction","knn","nearestPoints","pointsPerClass","maxPoints","lastElement","currentClass","currentPoints","pow2array","initializeMatrices","PLS","meanX","stdDevX","meanY","stdDevY","PBQ","R2X","scaleMethod","latentVectors","rx","cx","ry","cy","ssqXcal","sumOfSquaresY","T","P","Q","W","transposeX","transposeY","tIndex","maxSumColIndex","uIndex","t1","den","pnorm","ssqYcal","E","F","KOPLS","YLoadingMat","SigmaPow","YScoreMat","predScoreMat","YOrthLoadingVec","YOrthEigen","YOrthScoreMat","toNorm","TURegressionCoeff","kernelX","kernel","orthogonalComp","predictiveComp","predictiveComponents","orthogonalComponents","compute","Identity","Sigma","YOrthScoreNorm","TpiPrime","CoTemp","SoTemp","toiPrime","ITo","lastScoreMat","lastTpPrime","KTestTrain","YOrthScoreVector","scoreMatPrime","p1","p2","p3","prediction","predYOrthVectors","ConfusionMatrix","fromLabels","actual","predicted","distinctLabels","actualIdx","predictedIdx","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","N","twiddle","CV","leaveOneOut","Classifier","classifierOptions","leavePOut","distinct","getDistinct","confusionMatrix","initMatrix","gen","combinations","allIdx","testIdx","trainIdx","validateWithCallback","validate","kFold","current","folds","randi","testFeatures","trainFeatures","testLabels","trainLabels","getTrainTest","classifier","predictedLabels","updateConfusionMatrix","logistic","expELU","param","softExponential","softExponentialPrime","ACTIVATION_FUNCTIONS","activation","derivate","arctan","softsign","relu","softplus","bent","sinusoid","sinc","gaussian","Layer","inputSize","outputSize","regularization","epsilon","activationParam","selectedFunction","params","actFunction","derFunction","activationFunction","mlMatrix","forward","backpropagation","delta","dW","db","aCopy","update","OutputLayer","FeedForwardNeuralNetworks","hiddenLayers","learningRate","dicts","layers","keys","buildNetwork","dictOutputs","inputs","propagate","outputs","NodeSquare","weights","som","neighbors","adjustWeights","target","influence","getDistance","otherNode","getDistanceTorus","distX","distY","gridDim","getNeighbors","xy","torus","getPos","bestNeighbor","direction","dist1","dist2","simA","simB","getPosition","NodeHexagonal","hX","getDistanceHexagonal","distZ","fields","randomizer","squareEuclidean","gridType","SOM","hasOwnProperty","numWeights","converters","getConverters","extractor","creator","nodeType","hx","distanceMethod","getMaxDistance","done","times","findBMU","adjust","iterationCount","startLearningRate","mapRadius","algorithmMethod","_initNodes","loadModel","eval","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","self","_predict","getQuantizationError","fit","getFit","normalizers","denormalizers","getNormalizer","getDenormalizer","minMax","normalizer","denormalizer","zero","one","maybeToPrecision","digits","checkArraySize","BaseRegression","new","toLaTeX","score","y2","xSum","ySum","chi2","rmsd","xSquared","ySquared","xY","PolynomialRegression","degree","powers","coefficients","checkArrayLength","regress","precision","_toFormula","isLaTeX","sup","closeSup","fn","str","json","pr","FT","SimpleLinearRegression","slope","intercept","computeX","xFactor","absIntercept","operator","slr","numerator","ExponentialRegression","er","yl","linear","PowerRegression","newInputs","latex","xl","MultivariateLinearRegression","statistics","xt","xx","invxx","beta","fittedValues","residuals","ri","stdError","stdErrorMatrix","stdErrors","tStats","summary","regressionStatistics","standardError","observations","variables","tStat","sigma","GaussianKernel","constant","PolynomialKernel","SigmoidKernel","ANOVAKernel","len","CauchyKernel","ExponentialKernel","HistogramIntersectionKernel","LaplacianKernel","MultiquadraticKernel","RationalQuadraticKernel","kernelType","rbf","polynomial","poly","anova","cauchy","histogram","HistogramKernel","laplacian","multiquadratic","rational","RationalKernel","sigmoid","mlp","Kernel","KernelConstructor","kernelFunction","landmarks","kernelMatrix","TheilSenRegression","theilSen","slopes","medianSlope","cuts","RobustPolynomialRegression","robustPolynomial","tuples","getRandomTuples","tuple","calcCoefficients","residualsMedian","half","errorCalculation","parameters","parameterizedFunction","func","gradientFunction","evaluatedData","gradientDifference","paramFunction","auxParams","funcParam","matrixFunction","damping","gradientFunc","matrixFunc","inverseMatrix","levenbergMarquardt","errorTolerance","minValues","maxValues","initialValues","parLen","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","iteration","parameterValues","parameterError","sortCollectionSet","collection","objectCollection","key","BigInt","sorted","cssls","XtX","XtY","Pset","choXtX","luXtX","sortedPset","sortedEset","cols2Solve","vars","initialisation","Fset","D","setDifference","C","includes","optimality","maxIter","Jset","fullSet","notPset","fcnnls","infeasIndex","Hset","hRowColIdx","negRowColIdx","alphaMin","minIdx","idx2zero","findIndex","newParam","fcnnlsVector","haystack","needle","comparator","assertNumber","number","largestPrime","primeNumbers","ascending","nextPrime","binarySearch","FREE","FULL","REMOVED","defaultInitialCapacity","defaultMinLoadFactor","defaultMaxLoadFactor","HashTable","table","minLoadFactor","maxLoadFactor","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","SparseMatrix","_init","elements","symmetric","forEachNonZero","bandWidth","isBanded","width","cardinality","v1","v2","getNonZeros","setThreshold","newThreshold","trans","inplaceOperator","inplaceOperatorScalar","inplaceOperatorMatrix","staticOperator","inplaceMethod","staticMethod","operators","fillTemplateFunction","op","methods","mathMethod","template","RegExp","additiveSymmetric","avg","bhattacharyya","canberra","chebyshev","clark","czekanowskiSimilarity","up","down","czekanowskiDistance","dice","q1","q2","divergence","fidelity","gower","harmonicMean","hellinger","innerProduct","intersection","jaccard","jeffreys","jensenDifference","jensenShannon","kdivergence","kulczynski","kullbackLeibler","kumarHassebrook","kumarJohnson","lorentzian","manhattan","matusita","minkowski","motyka","neyman","pearson","probabilisticSymmetric","ruzicka","soergel","sorensen","squared","squaredChord","taneja","tanimoto","bitvector","inter","union","tanimotoS","topsoe","waveHedges","createTree","spectrum","minWindow","to","mainCreateTree","start","getSimilarity","gamma","treeSimilarity","getFunction","cosine","diceD","intersectionD","jaccardD","kulczynskiD","motykaD","avgA","avgB","newA","newB","squaredChordD","pred","cutoffs","tn","tp","fp","nNeg","nPos","nPosPred","nNegPred","Performance","isDistance","predP","all","targ","currentPred","nTp","nFp","getMeasure","measure","measures","getAURC","auc","getAUDC","getDistribution","cutLength","cutLow","cutHigh","xLabels","interValues","intraValues","interCumPercent","intraCumPercent","nTP","currentTP","nFP","currentFP","thisTP","thisFP","names","acc","err","fpr","tpr","fnr","tnr","ppv","npv","pcfall","pcmiss","lift","rpp","rnp","arrayCase","cond","matrixCase","padArray","windowSize","derivative","pad","padValue","savitzkyGolay","J","inic","Jtranspose","Jinv","det","eightBits","arr1","arr2","getBit","mask","setBit","toBinaryString","substr","parseBinaryString","toHexString","parseHexString","toDebug","binary","maxCount","_options$algorithm","algorithm","absoluteSumValue","absoluteSum","_typeof","iterator","sequentialFill","_options","_options$from","_options$to","_options$size","_options$unbiased","_options$mean","sqrError","mergeByCentroids","originalPoints","mergedPoints","originalIndex","mergedIndex","closestX","descending","maxMerge","groupWidth","merged","maxAbscissa","maxY","calculateIndex","sortX","sortFunc","grouped","response","uniqueX","weightedMerge","weightedAbscissa","integral","x0","x1","equallySpacedSmooth","numberOfPoints","xLength","halfStep","initialOriginalStep","lastOriginalStep","previousX","previousY","nextX","nextY","currentValue","sumAtMin","sumAtMax","getSlope","y0","y1","main","equallySpacedSlot","lastStep","frontOutsideSpectra","backOutsideSpectra","getZones","exclusions","exclusion","JSON","parse","stringify","toRemove","unitsPerPoint","zones","currentFrom","totalPoints","currentNbPoints","equallySpaced","arrayXY","variant","xResult","yResult","zone","zoneResult","processZone","filterX","currentZoneIndex","newX","newY","position","MatrixLib","normed","ArrayXY","centroidsMerge"],"mappings":";;;;;;;;;;;;EAEA,MAAMA,QAAQ,GAAGC,MAAM,CAACC,SAAP,CAAiBF,QAAlC;;EAEA,SAASG,UAAT,CAAoBC,MAApB,EAA4B;EAC1B,SAAOJ,QAAQ,CAACK,IAAT,CAAcD,MAAd,EAAsBE,QAAtB,CAA+B,QAA/B,CAAP;EACD;;EAED,OAAc,GAAGH,UAAjB;;ECNA;;;;;;EAMA,SAASI,GAAT,CAAaC,KAAb,EAAoB;EAClB,MAAI,CAACC,GAAO,CAACD,KAAD,CAAZ,EAAqB;EACnB,UAAM,IAAIE,SAAJ,CAAc,wBAAd,CAAN;EACD;;EAED,MAAIF,KAAK,CAACG,MAAN,KAAiB,CAArB,EAAwB;EACtB,UAAM,IAAID,SAAJ,CAAc,yBAAd,CAAN;EACD;;EAED,MAAIE,QAAQ,GAAGJ,KA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MANmB;EAOnBh1D,EAAAA,OAPmB;EAQnBkwD,EAAAA,cARmB;EASnBh4C,EAAAA,iBATmB;EAUnBjV,EAAAA,GAVmB;EAWnBa,EAAAA;EAXmB,CAAd;AAcP,QAUamxD,OAAO,GAAG;EACrBC,kBAAAA,gBADqB;EAErBnE,EAAAA,QAFqB;EAGrBpwC,cAAAA,YAHqB;EAIrBswC,EAAAA,QAJqB;EAKrBI,EAAAA,IALqB;EAMrBE,EAAAA,KANqB;EAOrBI,EAAAA,OAPqB;EAQrBC,EAAAA,aARqB;EASrBsC,EAAAA,aATqB;EAUrBQ,EAAAA;EAVqB,CAAhB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"ml.js","sources":["../node_modules/ml-array-rescale/node_modules/is-any-array/src/index.js","../node_modules/ml-array-rescale/node_modules/ml-array-max/lib-es6/index.js","../node_modules/ml-array-rescale/node_modules/ml-array-min/lib-es6/index.js","../node_modules/ml-array-rescale/lib-es6/index.js","../node_modules/ml-matrix/src/inspect.js","../node_modules/ml-matrix/src/mathOperations.js","../node_modules/ml-matrix/src/util.js","../node_modules/ml-matrix/src/stat.js","../node_modules/ml-matrix/src/matrix.js","../node_modules/ml-matrix/src/views/base.js","../node_modules/ml-matrix/src/views/column.js","../node_modules/ml-matrix/src/views/columnSelection.js","../node_modules/ml-matrix/src/views/flipColumn.js","../node_modules/ml-matrix/src/views/flipRow.js","../node_modules/ml-matrix/src/views/row.js","../node_modules/ml-matrix/src/views/rowSelection.js","../node_modules/ml-matrix/src/views/selection.js","../node_modules/ml-matrix/src/views/sub.js","../node_modules/ml-matrix/src/views/transpose.js","../node_modules/ml-matrix/src/wrap/WrapperMatrix1D.js","../node_modules/ml-matrix/src/wrap/WrapperMatrix2D.js","../node_modules/ml-matrix/src/wrap/wrap.js","../node_modules/ml-matrix/src/dc/lu.js","../node_modules/ml-matrix/src/dc/util.js","../node_modules/ml-matrix/src/dc/qr.js","../node_modules/ml-matrix/src/dc/svd.js","../node_modules/ml-matrix/src/decompositions.js","../node_modules/ml-matrix/src/determinant.js","../node_modules/ml-matrix/src/linearDependencies.js","../node_modules/ml-matrix/src/pseudoInverse.js","../node_modules/ml-matrix/src/covariance.js","../node_modules/ml-matrix/src/correlation.js","../node_modules/ml-matrix/src/dc/evd.js","../node_modules/ml-matrix/src/dc/cholesky.js","../node_modules/ml-matrix/src/dc/nipals.js","../node_modules/ml-array-sum/node_modules/is-any-array/src/index.js","../node_modules/ml-array-sum/lib-es6/index.js","../node_modules/ml-array-mean/lib-es6/index.js","../node_modules/ml-cart/src/utils.js","../node_modules/ml-cart/src/TreeNode.js","../node_modules/ml-cart/src/DecisionTreeClassifier.js","../node_modules/ml-cart/src/DecisionTreeRegression.js","../node_modules/random-js/dist/random-js.esm.js","../node_modules/ml-random-forest/src/utils.js","../node_modules/ml-random-forest/src/RandomForestBase.js","../node_modules/ml-random-forest/src/RandomForestClassifier.js","../node_modules/ml-array-median/node_modules/is-any-array/src/index.js","../node_modules/median-quickselect/lib/median-quickselect.min.js","../node_modules/ml-array-median/lib-es6/index.js","../node_modules/ml-random-forest/src/RandomForestRegression.js","../node_modules/ml-pca/src/pca.js","../node_modules/ml-distance-euclidean/lib-es6/euclidean.js","../node_modules/ml-distance-matrix/src/index.js","../node_modules/heap/lib/heap.js","../node_modules/heap/index.js","../node_modules/ml-hclust/src/Cluster.js","../node_modules/ml-hclust/src/agnes.js","../node_modules/ml-hclust/src/index.js","../node_modules/ml-nearest-vector/lib-es6/index.js","../node_modules/ml-kmeans/src/utils.js","../node_modules/ml-xsadd/lib-es6/xsadd.js","../node_modules/ml-random/lib-es6/choice.js","../node_modules/ml-random/lib-es6/index.js","../node_modules/ml-kmeans/src/initialization.js","../node_modules/ml-kmeans/src/KMeansResult.js","../node_modules/ml-kmeans/src/kmeans.js","../node_modules/ml-naivebayes/src/utils.js","../node_modules/ml-naivebayes/src/GaussianNB.js","../node_modules/ml-naivebayes/src/MultinomialNB.js","../node_modules/ml-knn/src/KDTree.js","../node_modules/ml-knn/src/index.js","../node_modules/ml-pls/src/util/utils.js","../node_modules/ml-pls/src/PLS.js","../node_modules/ml-pls/src/KOPLS.js","../node_modules/ml-confusion-matrix/src/index.js","../node_modules/ml-combinations/lib/index.js","../node_modules/ml-cross-validation/src/getFolds.js","../node_modules/ml-cross-validation/src/sampleAClass.js","../node_modules/ml-cross-validation/src/index.js","../node_modules/ml-pls/src/OPLSNipals.js","../node_modules/ml-pls/src/util/tss.js","../node_modules/ml-pls/src/OPLS.js","../node_modules/ml-fnn/FeedForwardNeuralNetwork.js","../node_modules/ml-som/src/node-square.js","../node_modules/ml-som/src/node-hexagonal.js","../node_modules/ml-som/src/index.js","../node_modules/ml-regression-base/src/maybeToPrecision.js","../node_modules/ml-regression-base/src/checkArrayLength.js","../node_modules/ml-regression-base/src/index.js","../node_modules/ml-regression-polynomial/src/index.js","../node_modules/ml-regression-simple-linear/src/index.js","../node_modules/ml-regression-exponential/src/index.js","../node_modules/ml-regression-power/src/index.js","../node_modules/ml-regression-multivariate-linear/src/index.js","../node_modules/ml-kernel-gaussian/gaussian-kernel.js","../node_modules/ml-kernel-polynomial/polynomial-kernel.js","../node_modules/ml-kernel-sigmoid/sigmoid-kernel.js","../node_modules/ml-kernel/src/kernels/anova-kernel.js","../node_modules/ml-kernel/src/kernels/cauchy-kernel.js","../node_modules/ml-kernel/src/kernels/exponential-kernel.js","../node_modules/ml-kernel/src/kernels/histogram-intersection-kernel.js","../node_modules/ml-kernel/src/kernels/laplacian-kernel.js","../node_modules/ml-kernel/src/kernels/multiquadratic-kernel.js","../node_modules/ml-kernel/src/kernels/rational-quadratic-kernel.js","../node_modules/ml-kernel/src/kernel.js","../node_modules/ml-regression-theil-sen/src/index.js","../node_modules/ml-regression-robust-polynomial/src/index.js","../node_modules/ml-levenberg-marquardt/node_modules/is-any-array/src/index.js","../node_modules/ml-levenberg-marquardt/src/errorCalculation.js","../node_modules/ml-levenberg-marquardt/src/step.js","../node_modules/ml-levenberg-marquardt/src/index.js","../node_modules/ml-fcnnls/src/util/selection.js","../node_modules/ml-fcnnls/src/util/sortCollectionSet.js","../node_modules/ml-fcnnls/src/cssls.js","../node_modules/ml-fcnnls/src/initialisation.js","../node_modules/ml-fcnnls/src/util/setDifference.js","../node_modules/ml-fcnnls/src/optimality.js","../node_modules/ml-fcnnls/src/fcnnls.js","../node_modules/ml-fcnnls/src/fcnnlsVector.js","../node_modules/binary-search/index.js","../node_modules/num-sort/index.js","../node_modules/ml-hash-table/src/primeFinder.js","../node_modules/ml-hash-table/src/HashTable.js","../node_modules/ml-sparse-matrix/src/index.js","../node_modules/ml-distance/src/distances/additiveSymmetric.js","../node_modules/ml-distance/src/distances/avg.js","../node_modules/ml-distance/src/distances/bhattacharyya.js","../node_modules/ml-distance/src/distances/canberra.js","../node_modules/ml-distance/src/distances/chebyshev.js","../node_modules/ml-distance/src/distances/clark.js","../node_modules/ml-distance/src/similarities/czekanowski.js","../node_modules/ml-distance/src/distances/czekanowski.js","../node_modules/ml-distance/src/distances/dice.js","../node_modules/ml-distance/src/distances/divergence.js","../node_modules/ml-distance/src/distances/fidelity.js","../node_modules/ml-distance/src/distances/gower.js","../node_modules/ml-distance/src/distances/harmonicMean.js","../node_modules/ml-distance/src/distances/hellinger.js","../node_modules/ml-distance/src/distances/innerProduct.js","../node_modules/ml-distance/src/distances/intersection.js","../node_modules/ml-distance/src/distances/jaccard.js","../node_modules/ml-distance/src/distances/jeffreys.js","../node_modules/ml-distance/src/distances/jensenDifference.js","../node_modules/ml-distance/src/distances/jensenShannon.js","../node_modules/ml-distance/src/distances/kdivergence.js","../node_modules/ml-distance/src/distances/kulczynski.js","../node_modules/ml-distance/src/distances/kullbackLeibler.js","../node_modules/ml-distance/src/distances/kumarHassebrook.js","../node_modules/ml-distance/src/distances/kumarJohnson.js","../node_modules/ml-distance/src/distances/lorentzian.js","../node_modules/ml-distance/src/distances/manhattan.js","../node_modules/ml-distance/src/distances/matusita.js","../node_modules/ml-distance/src/distances/minkowski.js","../node_modules/ml-distance/src/distances/motyka.js","../node_modules/ml-distance/src/distances/neyman.js","../node_modules/ml-distance/src/distances/pearson.js","../node_modules/ml-distance/src/distances/probabilisticSymmetric.js","../node_modules/ml-distance/src/distances/ruzicka.js","../node_modules/ml-distance/src/distances/soergel.js","../node_modules/ml-distance/src/distances/sorensen.js","../node_modules/ml-distance/src/distances/squared.js","../node_modules/ml-distance/src/distances/squaredChord.js","../node_modules/ml-distance/src/distances/taneja.js","../node_modules/ml-distance/src/similarities/tanimoto.js","../node_modules/ml-distance/src/distances/tanimoto.js","../node_modules/ml-distance/src/distances/topsoe.js","../node_modules/ml-distance/src/distances/waveHedges.js","../node_modules/ml-tree-similarity/src/createTree.js","../node_modules/ml-tree-similarity/src/getSimilarity.js","../node_modules/ml-tree-similarity/src/index.js","../node_modules/ml-distance/src/similarities/cosine.js","../node_modules/ml-distance/src/similarities/dice.js","../node_modules/ml-distance/src/similarities/intersection.js","../node_modules/ml-distance/src/similarities/jaccard.js","../node_modules/ml-distance/src/similarities/kulczynski.js","../node_modules/ml-distance/src/similarities/motyka.js","../node_modules/ml-distance/src/similarities/pearson.js","../node_modules/ml-distance/src/similarities/squaredChord.js","../node_modules/ml-performance/src/measures.js","../node_modules/ml-performance/src/index.js","../node_modules/ml-pad-array/src/index.js","../node_modules/ml-savitzky-golay/src/index.js","../node_modules/ml-bit-array/src/creator.js","../node_modules/ml-bit-array/src/index.js","../node_modules/ml-gsd/node_modules/ml-savitzky-golay-generalized/src/index.js","../node_modules/ml-gsd/src/gsd.js","../node_modules/ml-optimize-lorentzian/src/sumOfGaussians.js","../node_modules/ml-optimize-lorentzian/src/optimizeGaussianSum.js","../node_modules/ml-optimize-lorentzian/src/singleGaussian.js","../node_modules/ml-optimize-lorentzian/src/optimizeSingleGaussian.js","../node_modules/ml-optimize-lorentzian/src/sumOfLorentzians.js","../node_modules/ml-optimize-lorentzian/src/optimizeLorentzianSum.js","../node_modules/ml-optimize-lorentzian/src/singleLorentzian.js","../node_modules/ml-optimize-lorentzian/src/optimizeSingleLorentzian.js","../node_modules/ml-gsd/src/post/optimizePeaks.js","../node_modules/ml-gsd/src/post/joinBroadPeaks.js","../node_modules/ml-gsd/src/post/broadenPeaks.js","../node_modules/is-any-array/src/index.js","../node_modules/ml-array-min/lib-es6/index.js","../node_modules/ml-array-max/lib-es6/index.js","../node_modules/ml-array-mode/lib-es6/index.js","../node_modules/ml-array-normed/node_modules/is-any-array/src/index.js","../node_modules/ml-array-normed/node_modules/ml-array-max/lib-es6/index.js","../node_modules/ml-array-normed/lib-es6/index.js","../node_modules/ml-array-sequential-fill/lib-es6/index.js","../node_modules/ml-array-variance/node_modules/is-any-array/src/index.js","../node_modules/ml-array-variance/lib-es6/index.js","../node_modules/ml-array-standard-deviation/lib-es6/index.js","../node_modules/ml-array-xy-centroids-merge/src/index.js","../node_modules/ml-arrayxy-closestx/src/index.js","../node_modules/ml-array-xy-covariance/src/index.js","../node_modules/ml-array-xy-max-merge/src/index.js","../node_modules/ml-array-xy-max-y/src/index.js","../node_modules/ml-array-xy-sort-x/src/index.js","../node_modules/ml-arrayxy-uniquex/src/index.js","../node_modules/ml-array-xy-weighted-merge/src/index.js","../node_modules/ml-zones/src/normalize.js","../node_modules/ml-zones/src/invert.js","../node_modules/ml-zones/src/zonesWithPoints.js","../node_modules/ml-array-xy-equally-spaced/src/integral.js","../node_modules/ml-array-xy-equally-spaced/src/equallySpacedSmooth.js","../node_modules/ml-array-xy-equally-spaced/src/equallySpacedSlot.js","../node_modules/ml-array-xy-equally-spaced/src/index.js","../node_modules/ml-array-xy-filter-x/src/getZones.js","../node_modules/ml-array-xy-filter-x/src/index.js","../src/index.js"],"sourcesContent":["const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n","import isArray from 'is-any-array';\n\nfunction max(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 }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var _options$fromIndex = options.fromIndex,\n fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,\n _options$toIndex = options.toIndex,\n toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;\n\n if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {\n throw new Error('fromIndex must be a positive integer smaller than length');\n }\n\n if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {\n throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');\n }\n\n var maxValue = input[fromIndex];\n\n for (var i = fromIndex + 1; i < toIndex; i++) {\n if (input[i] > maxValue) maxValue = input[i];\n }\n\n return maxValue;\n}\n\nexport default max;\n","import isArray from 'is-any-array';\n\nfunction min(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 }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var _options$fromIndex = options.fromIndex,\n fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,\n _options$toIndex = options.toIndex,\n toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;\n\n if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {\n throw new Error('fromIndex must be a positive integer smaller than length');\n }\n\n if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {\n throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');\n }\n\n var minValue = input[fromIndex];\n\n for (var i = fromIndex + 1; i < toIndex; i++) {\n if (input[i] < minValue) minValue = input[i];\n }\n\n return minValue;\n}\n\nexport default min;\n","import isArray from 'is-any-array';\nimport max from 'ml-array-max';\nimport min from 'ml-array-min';\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","const indent = ' '.repeat(2);\nconst indentData = ' '.repeat(4);\n\nexport function inspectMatrix() {\n return inspectMatrixWithOptions(this);\n}\n\nexport function inspectMatrixWithOptions(matrix, options = {}) {\n const { maxRows = 15, maxColumns = 10, maxNumSize = 8 } = options;\n return `${matrix.constructor.name} {\n${indent}[\n${indentData}${inspectData(matrix, maxRows, maxColumns, maxNumSize)}\n${indent}]\n${indent}rows: ${matrix.rows}\n${indent}columns: ${matrix.columns}\n}`;\n}\n\nfunction inspectData(matrix, maxRows, maxColumns, maxNumSize) {\n const { rows, columns } = matrix;\n const maxI = Math.min(rows, maxRows);\n const maxJ = Math.min(columns, maxColumns);\n const result = [];\n for (let i = 0; i < maxI; i++) {\n let line = [];\n for (let j = 0; j < maxJ; j++) {\n line.push(formatNumber(matrix.get(i, j), maxNumSize));\n }\n result.push(`${line.join(' ')}`);\n }\n if (maxJ !== columns) {\n result[result.length - 1] += ` ... ${columns - maxColumns} more columns`;\n }\n if (maxI !== rows) {\n result.push(`... ${rows - maxRows} more rows`);\n }\n return result.join(`\\n${indentData}`);\n}\n\nfunction formatNumber(num, maxNumSize) {\n const numStr = String(num);\n if (numStr.length <= maxNumSize) {\n return numStr.padEnd(maxNumSize, ' ');\n }\n const precise = num.toPrecision(maxNumSize - 2);\n if (precise.length <= maxNumSize) {\n return precise;\n }\n const exponential = num.toExponential(maxNumSize - 2);\n const eIndex = exponential.indexOf('e');\n const e = exponential.slice(eIndex);\n return exponential.slice(0, maxNumSize - e.length) + e;\n}\n","export function installMathOperations(AbstractMatrix, Matrix) {\r\n AbstractMatrix.prototype.add = function add(value) {\r\n if (typeof value === 'number') return this.addS(value);\r\n return this.addM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.addS = function addS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) + value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.addM = function addM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) + matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.add = function add(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.add(value);\r\n };\r\n\r\n AbstractMatrix.prototype.sub = function sub(value) {\r\n if (typeof value === 'number') return this.subS(value);\r\n return this.subM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.subS = function subS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) - value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.subM = function subM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) - matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.sub = function sub(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.sub(value);\r\n };\r\n AbstractMatrix.prototype.subtract = AbstractMatrix.prototype.sub;\r\n AbstractMatrix.prototype.subtractS = AbstractMatrix.prototype.subS;\r\n AbstractMatrix.prototype.subtractM = AbstractMatrix.prototype.subM;\r\n AbstractMatrix.subtract = AbstractMatrix.sub;\r\n\r\n AbstractMatrix.prototype.mul = function mul(value) {\r\n if (typeof value === 'number') return this.mulS(value);\r\n return this.mulM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.mulS = function mulS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) * value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.mulM = function mulM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) * matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.mul = function mul(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.mul(value);\r\n };\r\n AbstractMatrix.prototype.multiply = AbstractMatrix.prototype.mul;\r\n AbstractMatrix.prototype.multiplyS = AbstractMatrix.prototype.mulS;\r\n AbstractMatrix.prototype.multiplyM = AbstractMatrix.prototype.mulM;\r\n AbstractMatrix.multiply = AbstractMatrix.mul;\r\n\r\n AbstractMatrix.prototype.div = function div(value) {\r\n if (typeof value === 'number') return this.divS(value);\r\n return this.divM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.divS = function divS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) / value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.divM = function divM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) / matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.div = function div(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.div(value);\r\n };\r\n AbstractMatrix.prototype.divide = AbstractMatrix.prototype.div;\r\n AbstractMatrix.prototype.divideS = AbstractMatrix.prototype.divS;\r\n AbstractMatrix.prototype.divideM = AbstractMatrix.prototype.divM;\r\n AbstractMatrix.divide = AbstractMatrix.div;\r\n\r\n AbstractMatrix.prototype.mod = function mod(value) {\r\n if (typeof value === 'number') return this.modS(value);\r\n return this.modM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.modS = function modS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) % value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.modM = function modM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) % matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.mod = function mod(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.mod(value);\r\n };\r\n AbstractMatrix.prototype.modulus = AbstractMatrix.prototype.mod;\r\n AbstractMatrix.prototype.modulusS = AbstractMatrix.prototype.modS;\r\n AbstractMatrix.prototype.modulusM = AbstractMatrix.prototype.modM;\r\n AbstractMatrix.modulus = AbstractMatrix.mod;\r\n\r\n AbstractMatrix.prototype.and = function and(value) {\r\n if (typeof value === 'number') return this.andS(value);\r\n return this.andM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.andS = function andS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) & value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.andM = function andM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) & matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.and = function and(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.and(value);\r\n };\r\n\r\n AbstractMatrix.prototype.or = function or(value) {\r\n if (typeof value === 'number') return this.orS(value);\r\n return this.orM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.orS = function orS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) | value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.orM = function orM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) | matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.or = function or(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.or(value);\r\n };\r\n\r\n AbstractMatrix.prototype.xor = function xor(value) {\r\n if (typeof value === 'number') return this.xorS(value);\r\n return this.xorM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.xorS = function xorS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) ^ value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.xorM = function xorM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) ^ matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.xor = function xor(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.xor(value);\r\n };\r\n\r\n AbstractMatrix.prototype.leftShift = function leftShift(value) {\r\n if (typeof value === 'number') return this.leftShiftS(value);\r\n return this.leftShiftM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.leftShiftS = function leftShiftS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) << value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.leftShiftM = function leftShiftM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) << matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.leftShift = function leftShift(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.leftShift(value);\r\n };\r\n\r\n AbstractMatrix.prototype.signPropagatingRightShift = function signPropagatingRightShift(value) {\r\n if (typeof value === 'number') return this.signPropagatingRightShiftS(value);\r\n return this.signPropagatingRightShiftM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.signPropagatingRightShiftS = function signPropagatingRightShiftS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) >> value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.signPropagatingRightShiftM = function signPropagatingRightShiftM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) >> matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.signPropagatingRightShift = function signPropagatingRightShift(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.signPropagatingRightShift(value);\r\n };\r\n\r\n AbstractMatrix.prototype.rightShift = function rightShift(value) {\r\n if (typeof value === 'number') return this.rightShiftS(value);\r\n return this.rightShiftM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.rightShiftS = function rightShiftS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) >>> value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.rightShiftM = function rightShiftM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) >>> matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.rightShift = function rightShift(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.rightShift(value);\r\n };\r\n AbstractMatrix.prototype.zeroFillRightShift = AbstractMatrix.prototype.rightShift;\r\n AbstractMatrix.prototype.zeroFillRightShiftS = AbstractMatrix.prototype.rightShiftS;\r\n AbstractMatrix.prototype.zeroFillRightShiftM = AbstractMatrix.prototype.rightShiftM;\r\n AbstractMatrix.zeroFillRightShift = AbstractMatrix.rightShift;\r\n\r\n AbstractMatrix.prototype.not = function not() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, ~(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.not = function not(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.not();\r\n };\r\n\r\n AbstractMatrix.prototype.abs = function abs() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.abs(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.abs = function abs(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.abs();\r\n };\r\n\r\n AbstractMatrix.prototype.acos = function acos() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.acos(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.acos = function acos(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.acos();\r\n };\r\n\r\n AbstractMatrix.prototype.acosh = function acosh() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.acosh(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.acosh = function acosh(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.acosh();\r\n };\r\n\r\n AbstractMatrix.prototype.asin = function asin() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.asin(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.asin = function asin(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.asin();\r\n };\r\n\r\n AbstractMatrix.prototype.asinh = function asinh() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.asinh(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.asinh = function asinh(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.asinh();\r\n };\r\n\r\n AbstractMatrix.prototype.atan = function atan() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.atan(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.atan = function atan(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.atan();\r\n };\r\n\r\n AbstractMatrix.prototype.atanh = function atanh() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.atanh(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.atanh = function atanh(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.atanh();\r\n };\r\n\r\n AbstractMatrix.prototype.cbrt = function cbrt() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.cbrt(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.cbrt = function cbrt(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.cbrt();\r\n };\r\n\r\n AbstractMatrix.prototype.ceil = function ceil() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.ceil(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.ceil = function ceil(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.ceil();\r\n };\r\n\r\n AbstractMatrix.prototype.clz32 = function clz32() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.clz32(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.clz32 = function clz32(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.clz32();\r\n };\r\n\r\n AbstractMatrix.prototype.cos = function cos() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.cos(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.cos = function cos(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.cos();\r\n };\r\n\r\n AbstractMatrix.prototype.cosh = function cosh() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.cosh(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.cosh = function cosh(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.cosh();\r\n };\r\n\r\n AbstractMatrix.prototype.exp = function exp() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.exp(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.exp = function exp(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.exp();\r\n };\r\n\r\n AbstractMatrix.prototype.expm1 = function expm1() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.expm1(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.expm1 = function expm1(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.expm1();\r\n };\r\n\r\n AbstractMatrix.prototype.floor = function floor() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.floor(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.floor = function floor(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.floor();\r\n };\r\n\r\n AbstractMatrix.prototype.fround = function fround() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.fround(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.fround = function fround(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.fround();\r\n };\r\n\r\n AbstractMatrix.prototype.log = function log() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.log(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.log = function log(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.log();\r\n };\r\n\r\n AbstractMatrix.prototype.log1p = function log1p() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.log1p(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.log1p = function log1p(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.log1p();\r\n };\r\n\r\n AbstractMatrix.prototype.log10 = function log10() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.log10(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.log10 = function log10(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.log10();\r\n };\r\n\r\n AbstractMatrix.prototype.log2 = function log2() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.log2(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.log2 = function log2(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.log2();\r\n };\r\n\r\n AbstractMatrix.prototype.round = function round() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.round(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.round = function round(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.round();\r\n };\r\n\r\n AbstractMatrix.prototype.sign = function sign() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.sign(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.sign = function sign(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.sign();\r\n };\r\n\r\n AbstractMatrix.prototype.sin = function sin() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.sin(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.sin = function sin(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.sin();\r\n };\r\n\r\n AbstractMatrix.prototype.sinh = function sinh() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.sinh(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.sinh = function sinh(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.sinh();\r\n };\r\n\r\n AbstractMatrix.prototype.sqrt = function sqrt() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.sqrt(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.sqrt = function sqrt(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.sqrt();\r\n };\r\n\r\n AbstractMatrix.prototype.tan = function tan() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.tan(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.tan = function tan(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.tan();\r\n };\r\n\r\n AbstractMatrix.prototype.tanh = function tanh() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.tanh(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.tanh = function tanh(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.tanh();\r\n };\r\n\r\n AbstractMatrix.prototype.trunc = function trunc() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.trunc(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.trunc = function trunc(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.trunc();\r\n };\r\n\r\n AbstractMatrix.pow = function pow(matrix, arg0) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.pow(arg0);\r\n };\r\n\r\n AbstractMatrix.prototype.pow = function pow(value) {\r\n if (typeof value === 'number') return this.powS(value);\r\n return this.powM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.powS = function powS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.pow(this.get(i, j), value));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.powM = function powM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.pow(this.get(i, j), matrix.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n}\r\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 let 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 let 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 let 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 let 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 newArray(length, value = 0) {\n let array = [];\n for (let i = 0; i < length; i++) {\n array.push(value);\n }\n return array;\n}\n\nfunction checkNumber(name, value) {\n if (typeof value !== 'number') {\n throw new TypeError(`${name} must be a number`);\n }\n}\n","import { newArray } from './util';\n\nexport function sumByRow(matrix) {\n let sum = newArray(matrix.rows);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[i] += matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function sumByColumn(matrix) {\n let sum = newArray(matrix.columns);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[j] += matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function sumAll(matrix) {\n let v = 0;\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n v += matrix.get(i, j);\n }\n }\n return v;\n}\n\nexport function productByRow(matrix) {\n let sum = newArray(matrix.rows, 1);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[i] *= matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function productByColumn(matrix) {\n let sum = newArray(matrix.columns, 1);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[j] *= matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function productAll(matrix) {\n let v = 1;\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n v *= matrix.get(i, j);\n }\n }\n return v;\n}\n\nexport function varianceByRow(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const variance = [];\n\n for (let i = 0; i < rows; i++) {\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let j = 0; j < cols; j++) {\n x = matrix.get(i, j) - mean[i];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n variance.push((sum2 - (sum1 * sum1) / cols) / (cols - 1));\n } else {\n variance.push((sum2 - (sum1 * sum1) / cols) / cols);\n }\n }\n return variance;\n}\n\nexport function varianceByColumn(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const variance = [];\n\n for (let j = 0; j < cols; j++) {\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let i = 0; i < rows; i++) {\n x = matrix.get(i, j) - mean[j];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n variance.push((sum2 - (sum1 * sum1) / rows) / (rows - 1));\n } else {\n variance.push((sum2 - (sum1 * sum1) / rows) / rows);\n }\n }\n return variance;\n}\n\nexport function varianceAll(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const size = rows * cols;\n\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n x = matrix.get(i, j) - mean;\n sum1 += x;\n sum2 += x * x;\n }\n }\n if (unbiased) {\n return (sum2 - (sum1 * sum1) / size) / (size - 1);\n } else {\n return (sum2 - (sum1 * sum1) / size) / size;\n }\n}\n\nexport function centerByRow(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean[i]);\n }\n }\n}\n\nexport function centerByColumn(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean[j]);\n }\n }\n}\n\nexport function centerAll(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean);\n }\n }\n}\n\nexport function getScaleByRow(matrix) {\n const scale = [];\n for (let i = 0; i < matrix.rows; i++) {\n let sum = 0;\n for (let j = 0; j < matrix.columns; j++) {\n sum += Math.pow(matrix.get(i, j), 2) / (matrix.columns - 1);\n }\n scale.push(Math.sqrt(sum));\n }\n return scale;\n}\n\nexport function scaleByRow(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale[i]);\n }\n }\n}\n\nexport function getScaleByColumn(matrix) {\n const scale = [];\n for (let j = 0; j < matrix.columns; j++) {\n let sum = 0;\n for (let i = 0; i < matrix.rows; i++) {\n sum += Math.pow(matrix.get(i, j), 2) / (matrix.rows - 1);\n }\n scale.push(Math.sqrt(sum));\n }\n return scale;\n}\n\nexport function scaleByColumn(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale[j]);\n }\n }\n}\n\nexport function getScaleAll(matrix) {\n const divider = matrix.size - 1;\n let sum = 0;\n for (let j = 0; j < matrix.columns; j++) {\n for (let i = 0; i < matrix.rows; i++) {\n sum += Math.pow(matrix.get(i, j), 2) / divider;\n }\n }\n return Math.sqrt(sum);\n}\n\nexport function scaleAll(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale);\n }\n }\n}\n","import rescale from 'ml-array-rescale';\n\nimport { inspectMatrix, inspectMatrixWithOptions } from './inspect';\nimport { installMathOperations } from './mathOperations';\nimport {\n sumByRow,\n sumByColumn,\n sumAll,\n productByRow,\n productByColumn,\n productAll,\n varianceByRow,\n varianceByColumn,\n varianceAll,\n centerByRow,\n centerByColumn,\n centerAll,\n scaleByRow,\n scaleByColumn,\n scaleAll,\n getScaleByRow,\n getScaleByColumn,\n getScaleAll,\n} from './stat';\nimport {\n checkRowVector,\n checkRowIndex,\n checkColumnIndex,\n checkColumnVector,\n checkRange,\n checkIndices,\n} from './util';\n\nexport class AbstractMatrix {\n static from1DArray(newRows, newColumns, newData) {\n let length = newRows * newColumns;\n if (length !== newData.length) {\n throw new RangeError('data length does not match given dimensions');\n }\n let newMatrix = new Matrix(newRows, newColumns);\n for (let row = 0; row < newRows; row++) {\n for (let column = 0; column < newColumns; column++) {\n newMatrix.set(row, column, newData[row * newColumns + column]);\n }\n }\n return newMatrix;\n }\n\n static rowVector(newData) {\n let vector = new Matrix(1, newData.length);\n for (let i = 0; i < newData.length; i++) {\n vector.set(0, i, newData[i]);\n }\n return vector;\n }\n\n static columnVector(newData) {\n let vector = new Matrix(newData.length, 1);\n for (let i = 0; i < newData.length; i++) {\n vector.set(i, 0, newData[i]);\n }\n return vector;\n }\n\n static zeros(rows, columns) {\n return new Matrix(rows, columns);\n }\n\n static ones(rows, columns) {\n return new Matrix(rows, columns).fill(1);\n }\n\n static rand(rows, columns, options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { random = Math.random } = options;\n let matrix = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n matrix.set(i, j, random());\n }\n }\n return matrix;\n }\n\n static randInt(rows, columns, options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1000, random = Math.random } = options;\n if (!Number.isInteger(min)) throw new TypeError('min must be an integer');\n if (!Number.isInteger(max)) throw new TypeError('max must be an integer');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let interval = max - min;\n let matrix = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n let value = min + Math.round(random() * interval);\n matrix.set(i, j, value);\n }\n }\n return matrix;\n }\n\n static eye(rows, columns, value) {\n if (columns === undefined) columns = rows;\n if (value === undefined) value = 1;\n let min = Math.min(rows, columns);\n let matrix = this.zeros(rows, columns);\n for (let i = 0; i < min; i++) {\n matrix.set(i, i, value);\n }\n return matrix;\n }\n\n static diag(data, rows, columns) {\n let l = data.length;\n if (rows === undefined) rows = l;\n if (columns === undefined) columns = rows;\n let min = Math.min(l, rows, columns);\n let matrix = this.zeros(rows, columns);\n for (let i = 0; i < min; i++) {\n matrix.set(i, i, data[i]);\n }\n return matrix;\n }\n\n static min(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n let rows = matrix1.rows;\n let columns = matrix1.columns;\n let result = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let 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 static max(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n let rows = matrix1.rows;\n let columns = matrix1.columns;\n let result = new this(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let 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 static checkMatrix(value) {\n return AbstractMatrix.isMatrix(value) ? value : new Matrix(value);\n }\n\n static isMatrix(value) {\n return value != null && value.klass === 'Matrix';\n }\n\n get size() {\n return this.rows * this.columns;\n }\n\n apply(callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('callback must be a function');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n callback.call(this, i, j);\n }\n }\n return this;\n }\n\n to1DArray() {\n let array = [];\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n array.push(this.get(i, j));\n }\n }\n return array;\n }\n\n to2DArray() {\n let copy = [];\n for (let i = 0; i < this.rows; i++) {\n copy.push([]);\n for (let j = 0; j < this.columns; j++) {\n copy[i].push(this.get(i, j));\n }\n }\n return copy;\n }\n\n toJSON() {\n return this.to2DArray();\n }\n\n isRowVector() {\n return this.rows === 1;\n }\n\n isColumnVector() {\n return this.columns === 1;\n }\n\n isVector() {\n return this.rows === 1 || this.columns === 1;\n }\n\n isSquare() {\n return this.rows === this.columns;\n }\n\n isSymmetric() {\n if (this.isSquare()) {\n for (let i = 0; i < this.rows; i++) {\n for (let 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 isEchelonForm() {\n let i = 0;\n let j = 0;\n let previousColumn = -1;\n let isEchelonForm = true;\n let checked = false;\n while (i < this.rows && isEchelonForm) {\n j = 0;\n checked = false;\n while (j < this.columns && checked === false) {\n if (this.get(i, j) === 0) {\n j++;\n } else if (this.get(i, j) === 1 && j > previousColumn) {\n checked = true;\n previousColumn = j;\n } else {\n isEchelonForm = false;\n checked = true;\n }\n }\n i++;\n }\n return isEchelonForm;\n }\n\n isReducedEchelonForm() {\n let i = 0;\n let j = 0;\n let previousColumn = -1;\n let isReducedEchelonForm = true;\n let checked = false;\n while (i < this.rows && isReducedEchelonForm) {\n j = 0;\n checked = false;\n while (j < this.columns && checked === false) {\n if (this.get(i, j) === 0) {\n j++;\n } else if (this.get(i, j) === 1 && j > previousColumn) {\n checked = true;\n previousColumn = j;\n } else {\n isReducedEchelonForm = false;\n checked = true;\n }\n }\n for (let k = j + 1; k < this.rows; k++) {\n if (this.get(i, k) !== 0) {\n isReducedEchelonForm = false;\n }\n }\n i++;\n }\n return isReducedEchelonForm;\n }\n\n echelonForm() {\n let result = this.clone();\n let h = 0;\n let k = 0;\n while (h < result.rows && k < result.columns) {\n let iMax = h;\n for (let i = h; i < result.rows; i++) {\n if (result.get(i, k) > result.get(iMax, k)) {\n iMax = i;\n }\n }\n if (result.get(iMax, k) === 0) {\n k++;\n } else {\n result.swapRows(h, iMax);\n let tmp = result.get(h, k);\n for (let j = k; j < result.columns; j++) {\n result.set(h, j, result.get(h, j) / tmp);\n }\n for (let i = h + 1; i < result.rows; i++) {\n let factor = result.get(i, k) / result.get(h, k);\n result.set(i, k, 0);\n for (let j = k + 1; j < result.columns; j++) {\n result.set(i, j, result.get(i, j) - result.get(h, j) * factor);\n }\n }\n h++;\n k++;\n }\n }\n return result;\n }\n\n reducedEchelonForm() {\n let result = this.echelonForm();\n let m = result.columns;\n let n = result.rows;\n let h = n - 1;\n while (h >= 0) {\n if (result.maxRow(h) === 0) {\n h--;\n } else {\n let p = 0;\n let pivot = false;\n while (p < n && pivot === false) {\n if (result.get(h, p) === 1) {\n pivot = true;\n } else {\n p++;\n }\n }\n for (let i = 0; i < h; i++) {\n let factor = result.get(i, p);\n for (let j = p; j < m; j++) {\n let tmp = result.get(i, j) - factor * result.get(h, j);\n result.set(i, j, tmp);\n }\n }\n h--;\n }\n }\n return result;\n }\n\n set() {\n throw new Error('set method is unimplemented');\n }\n\n get() {\n throw new Error('get method is unimplemented');\n }\n\n repeat(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { rows = 1, columns = 1 } = options;\n if (!Number.isInteger(rows) || rows <= 0) {\n throw new TypeError('rows must be a positive integer');\n }\n if (!Number.isInteger(columns) || columns <= 0) {\n throw new TypeError('columns must be a positive integer');\n }\n let matrix = new Matrix(this.rows * rows, this.columns * columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\n }\n }\n return matrix;\n }\n\n fill(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, value);\n }\n }\n return this;\n }\n\n neg() {\n return this.mulS(-1);\n }\n\n getRow(index) {\n checkRowIndex(this, index);\n let row = [];\n for (let i = 0; i < this.columns; i++) {\n row.push(this.get(index, i));\n }\n return row;\n }\n\n getRowVector(index) {\n return Matrix.rowVector(this.getRow(index));\n }\n\n setRow(index, array) {\n checkRowIndex(this, index);\n array = checkRowVector(this, array);\n for (let i = 0; i < this.columns; i++) {\n this.set(index, i, array[i]);\n }\n return this;\n }\n\n swapRows(row1, row2) {\n checkRowIndex(this, row1);\n checkRowIndex(this, row2);\n for (let i = 0; i < this.columns; i++) {\n let 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 getColumn(index) {\n checkColumnIndex(this, index);\n let column = [];\n for (let i = 0; i < this.rows; i++) {\n column.push(this.get(i, index));\n }\n return column;\n }\n\n getColumnVector(index) {\n return Matrix.columnVector(this.getColumn(index));\n }\n\n setColumn(index, array) {\n checkColumnIndex(this, index);\n array = checkColumnVector(this, array);\n for (let i = 0; i < this.rows; i++) {\n this.set(i, index, array[i]);\n }\n return this;\n }\n\n swapColumns(column1, column2) {\n checkColumnIndex(this, column1);\n checkColumnIndex(this, column2);\n for (let i = 0; i < this.rows; i++) {\n let 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 addRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 subRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 mulRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 divRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 addColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 subColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 mulColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 divColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 mulRow(index, value) {\n checkRowIndex(this, index);\n for (let i = 0; i < this.columns; i++) {\n this.set(index, i, this.get(index, i) * value);\n }\n return this;\n }\n\n mulColumn(index, value) {\n checkColumnIndex(this, index);\n for (let i = 0; i < this.rows; i++) {\n this.set(i, index, this.get(i, index) * value);\n }\n return this;\n }\n\n max() {\n let v = this.get(0, 0);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 maxIndex() {\n let v = this.get(0, 0);\n let idx = [0, 0];\n for (let i = 0; i < this.rows; i++) {\n for (let 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 min() {\n let v = this.get(0, 0);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 minIndex() {\n let v = this.get(0, 0);\n let idx = [0, 0];\n for (let i = 0; i < this.rows; i++) {\n for (let 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 maxRow(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n for (let 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 maxRowIndex(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n let idx = [row, 0];\n for (let 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 minRow(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n for (let 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 minRowIndex(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n let idx = [row, 0];\n for (let 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 maxColumn(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n for (let 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 maxColumnIndex(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n let idx = [0, column];\n for (let 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 minColumn(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n for (let 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 minColumnIndex(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n let idx = [0, column];\n for (let 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 diag() {\n let min = Math.min(this.rows, this.columns);\n let diag = [];\n for (let i = 0; i < min; i++) {\n diag.push(this.get(i, i));\n }\n return diag;\n }\n\n norm(type = 'frobenius') {\n let result = 0;\n if (type === 'max') {\n return this.max();\n } else if (type === 'frobenius') {\n for (let i = 0; i < this.rows; i++) {\n for (let 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 cumulativeSum() {\n let sum = 0;\n for (let i = 0; i < this.rows; i++) {\n for (let 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 dot(vector2) {\n if (AbstractMatrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\n let vector1 = this.to1DArray();\n if (vector1.length !== vector2.length) {\n throw new RangeError('vectors do not have the same size');\n }\n let dot = 0;\n for (let i = 0; i < vector1.length; i++) {\n dot += vector1[i] * vector2[i];\n }\n return dot;\n }\n\n mmul(other) {\n other = Matrix.checkMatrix(other);\n\n let m = this.rows;\n let n = this.columns;\n let p = other.columns;\n\n let result = new Matrix(m, p);\n\n let Bcolj = new Float64Array(n);\n for (let j = 0; j < p; j++) {\n for (let k = 0; k < n; k++) {\n Bcolj[k] = other.get(k, j);\n }\n\n for (let i = 0; i < m; i++) {\n let s = 0;\n for (let 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 other = Matrix.checkMatrix(other);\n let result = new Matrix(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 other = Matrix.checkMatrix(other);\n let result = new Matrix(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 mmulStrassen(y) {\n y = Matrix.checkMatrix(y);\n let x = this.clone();\n let r1 = x.rows;\n let c1 = x.columns;\n let r2 = y.rows;\n let c2 = y.columns;\n if (c1 !== r2) {\n // eslint-disable-next-line no-console\n console.warn(\n `Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`,\n );\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 let r = mat.rows;\n let c = mat.columns;\n if (r === rows && c === cols) {\n return mat;\n } else {\n let resultat = AbstractMatrix.zeros(rows, cols);\n resultat = resultat.setSubMatrix(mat, 0, 0);\n return resultat;\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 let r = Math.max(r1, r2);\n let 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 let halfRows = parseInt(a.rows / 2, 10);\n let halfCols = parseInt(a.columns / 2, 10);\n // Subdivide input matrices.\n let a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n let b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n\n let a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\n let b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\n\n let a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\n let b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\n\n let a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\n let b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\n\n // Compute intermediate values.\n let m1 = blockMult(\n AbstractMatrix.add(a11, a22),\n AbstractMatrix.add(b11, b22),\n halfRows,\n halfCols,\n );\n let m2 = blockMult(AbstractMatrix.add(a21, a22), b11, halfRows, halfCols);\n let m3 = blockMult(a11, AbstractMatrix.sub(b12, b22), halfRows, halfCols);\n let m4 = blockMult(a22, AbstractMatrix.sub(b21, b11), halfRows, halfCols);\n let m5 = blockMult(AbstractMatrix.add(a11, a12), b22, halfRows, halfCols);\n let m6 = blockMult(\n AbstractMatrix.sub(a21, a11),\n AbstractMatrix.add(b11, b12),\n halfRows,\n halfCols,\n );\n let m7 = blockMult(\n AbstractMatrix.sub(a12, a22),\n AbstractMatrix.add(b21, b22),\n halfRows,\n halfCols,\n );\n\n // Combine intermediate values into the output.\n let c11 = AbstractMatrix.add(m1, m4);\n c11.sub(m5);\n c11.add(m7);\n let c12 = AbstractMatrix.add(m3, m5);\n let c21 = AbstractMatrix.add(m2, m4);\n let c22 = AbstractMatrix.sub(m1, m2);\n c22.add(m3);\n c22.add(m6);\n\n // Crop output to the desired size (undo dynamic padding).\n let resultat = AbstractMatrix.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 scaleRows(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1 } = options;\n if (!Number.isFinite(min)) throw new TypeError('min must be a number');\n if (!Number.isFinite(max)) throw new TypeError('max must be a number');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let i = 0; i < this.rows; i++) {\n const row = this.getRow(i);\n rescale(row, { min, max, output: row });\n newMatrix.setRow(i, row);\n }\n return newMatrix;\n }\n\n scaleColumns(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1 } = options;\n if (!Number.isFinite(min)) throw new TypeError('min must be a number');\n if (!Number.isFinite(max)) throw new TypeError('max must be a number');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let i = 0; i < this.columns; i++) {\n const column = this.getColumn(i);\n rescale(column, {\n min: min,\n max: max,\n output: column,\n });\n newMatrix.setColumn(i, column);\n }\n return newMatrix;\n }\n\n flipRows() {\n const middle = Math.ceil(this.columns / 2);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < middle; j++) {\n let first = this.get(i, j);\n let last = this.get(i, this.columns - 1 - j);\n this.set(i, j, last);\n this.set(i, this.columns - 1 - j, first);\n }\n }\n return this;\n }\n\n flipColumns() {\n const middle = Math.ceil(this.rows / 2);\n for (let j = 0; j < this.columns; j++) {\n for (let i = 0; i < middle; i++) {\n let first = this.get(i, j);\n let last = this.get(this.rows - 1 - i, j);\n this.set(i, j, last);\n this.set(this.rows - 1 - i, j, first);\n }\n }\n return this;\n }\n\n kroneckerProduct(other) {\n other = Matrix.checkMatrix(other);\n\n let m = this.rows;\n let n = this.columns;\n let p = other.rows;\n let q = other.columns;\n\n let result = new Matrix(m * p, n * q);\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n for (let k = 0; k < p; k++) {\n for (let l = 0; l < q; l++) {\n result.set(p * i + k, q * j + l, this.get(i, j) * other.get(k, l));\n }\n }\n }\n }\n return result;\n }\n\n transpose() {\n let result = new Matrix(this.columns, this.rows);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n result.set(j, i, this.get(i, j));\n }\n }\n return result;\n }\n\n sortRows(compareFunction = compareNumbers) {\n for (let i = 0; i < this.rows; i++) {\n this.setRow(i, this.getRow(i).sort(compareFunction));\n }\n return this;\n }\n\n sortColumns(compareFunction = compareNumbers) {\n for (let i = 0; i < this.columns; i++) {\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\n }\n return this;\n }\n\n subMatrix(startRow, endRow, startColumn, endColumn) {\n checkRange(this, startRow, endRow, startColumn, endColumn);\n let newMatrix = new Matrix(\n endRow - startRow + 1,\n endColumn - startColumn + 1,\n );\n for (let i = startRow; i <= endRow; i++) {\n for (let j = startColumn; j <= endColumn; j++) {\n newMatrix.set(i - startRow, j - startColumn, this.get(i, j));\n }\n }\n return newMatrix;\n }\n\n subMatrixRow(indices, startColumn, endColumn) {\n if (startColumn === undefined) startColumn = 0;\n if (endColumn === undefined) endColumn = this.columns - 1;\n if (\n startColumn > endColumn ||\n startColumn < 0 ||\n startColumn >= this.columns ||\n endColumn < 0 ||\n endColumn >= this.columns\n ) {\n throw new RangeError('Argument out of range');\n }\n\n let newMatrix = new Matrix(indices.length, endColumn - startColumn + 1);\n for (let i = 0; i < indices.length; i++) {\n for (let 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 subMatrixColumn(indices, startRow, endRow) {\n if (startRow === undefined) startRow = 0;\n if (endRow === undefined) endRow = this.rows - 1;\n if (\n startRow > endRow ||\n startRow < 0 ||\n startRow >= this.rows ||\n endRow < 0 ||\n endRow >= this.rows\n ) {\n throw new RangeError('Argument out of range');\n }\n\n let newMatrix = new Matrix(endRow - startRow + 1, indices.length);\n for (let i = 0; i < indices.length; i++) {\n for (let 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 setSubMatrix(matrix, startRow, startColumn) {\n matrix = Matrix.checkMatrix(matrix);\n let endRow = startRow + matrix.rows - 1;\n let endColumn = startColumn + matrix.columns - 1;\n checkRange(this, startRow, endRow, startColumn, endColumn);\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n this.set(startRow + i, startColumn + j, matrix.get(i, j));\n }\n }\n return this;\n }\n\n selection(rowIndices, columnIndices) {\n let indices = checkIndices(this, rowIndices, columnIndices);\n let newMatrix = new Matrix(rowIndices.length, columnIndices.length);\n for (let i = 0; i < indices.row.length; i++) {\n let rowIndex = indices.row[i];\n for (let j = 0; j < indices.column.length; j++) {\n let columnIndex = indices.column[j];\n newMatrix.set(i, j, this.get(rowIndex, columnIndex));\n }\n }\n return newMatrix;\n }\n\n trace() {\n let min = Math.min(this.rows, this.columns);\n let trace = 0;\n for (let i = 0; i < min; i++) {\n trace += this.get(i, i);\n }\n return trace;\n }\n\n clone() {\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let row = 0; row < this.rows; row++) {\n for (let column = 0; column < this.columns; column++) {\n newMatrix.set(row, column, this.get(row, column));\n }\n }\n return newMatrix;\n }\n\n sum(by) {\n switch (by) {\n case 'row':\n return sumByRow(this);\n case 'column':\n return sumByColumn(this);\n case undefined:\n return sumAll(this);\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n product(by) {\n switch (by) {\n case 'row':\n return productByRow(this);\n case 'column':\n return productByColumn(this);\n case undefined:\n return productAll(this);\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n mean(by) {\n const sum = this.sum(by);\n switch (by) {\n case 'row': {\n for (let i = 0; i < this.rows; i++) {\n sum[i] /= this.columns;\n }\n return sum;\n }\n case 'column': {\n for (let i = 0; i < this.columns; i++) {\n sum[i] /= this.rows;\n }\n return sum;\n }\n case undefined:\n return sum / this.size;\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n variance(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { unbiased = true, mean = this.mean(by) } = options;\n if (typeof unbiased !== 'boolean') {\n throw new TypeError('unbiased must be a boolean');\n }\n switch (by) {\n case 'row': {\n if (!Array.isArray(mean)) {\n throw new TypeError('mean must be an array');\n }\n return varianceByRow(this, unbiased, mean);\n }\n case 'column': {\n if (!Array.isArray(mean)) {\n throw new TypeError('mean must be an array');\n }\n return varianceByColumn(this, unbiased, mean);\n }\n case undefined: {\n if (typeof mean !== 'number') {\n throw new TypeError('mean must be a number');\n }\n return varianceAll(this, unbiased, mean);\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n standardDeviation(by, options) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n const variance = this.variance(by, options);\n if (by === undefined) {\n return Math.sqrt(variance);\n } else {\n for (let i = 0; i < variance.length; i++) {\n variance[i] = Math.sqrt(variance[i]);\n }\n return variance;\n }\n }\n\n center(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { center = this.mean(by) } = options;\n switch (by) {\n case 'row': {\n if (!Array.isArray(center)) {\n throw new TypeError('center must be an array');\n }\n centerByRow(this, center);\n return this;\n }\n case 'column': {\n if (!Array.isArray(center)) {\n throw new TypeError('center must be an array');\n }\n centerByColumn(this, center);\n return this;\n }\n case undefined: {\n if (typeof center !== 'number') {\n throw new TypeError('center must be a number');\n }\n centerAll(this, center);\n return this;\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n scale(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n let scale = options.scale;\n switch (by) {\n case 'row': {\n if (scale === undefined) {\n scale = getScaleByRow(this);\n } else if (!Array.isArray(scale)) {\n throw new TypeError('scale must be an array');\n }\n scaleByRow(this, scale);\n return this;\n }\n case 'column': {\n if (scale === undefined) {\n scale = getScaleByColumn(this);\n } else if (!Array.isArray(scale)) {\n throw new TypeError('scale must be an array');\n }\n scaleByColumn(this, scale);\n return this;\n }\n case undefined: {\n if (scale === undefined) {\n scale = getScaleAll(this);\n } else if (typeof scale !== 'number') {\n throw new TypeError('scale must be a number');\n }\n scaleAll(this, scale);\n return this;\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n toString(options) {\n return inspectMatrixWithOptions(this, options);\n }\n}\n\nAbstractMatrix.prototype.klass = 'Matrix';\nif (typeof Symbol !== 'undefined') {\n AbstractMatrix.prototype[\n Symbol.for('nodejs.util.inspect.custom')\n ] = inspectMatrix;\n}\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\n// Synonyms\nAbstractMatrix.random = AbstractMatrix.rand;\nAbstractMatrix.randomInt = AbstractMatrix.randInt;\nAbstractMatrix.diagonal = AbstractMatrix.diag;\nAbstractMatrix.prototype.diagonal = AbstractMatrix.prototype.diag;\nAbstractMatrix.identity = AbstractMatrix.eye;\nAbstractMatrix.prototype.negate = AbstractMatrix.prototype.neg;\nAbstractMatrix.prototype.tensorProduct =\n AbstractMatrix.prototype.kroneckerProduct;\n\nexport default class Matrix extends AbstractMatrix {\n constructor(nRows, nColumns) {\n super();\n if (Matrix.isMatrix(nRows)) {\n return nRows.clone();\n } else if (Number.isInteger(nRows) && nRows > 0) {\n // Create an empty matrix\n this.data = [];\n if (Number.isInteger(nColumns) && nColumns > 0) {\n for (let i = 0; i < nRows; i++) {\n this.data.push(new Float64Array(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 arrayData = nRows;\n nRows = arrayData.length;\n nColumns = arrayData[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 this.data = [];\n for (let i = 0; i < nRows; i++) {\n if (arrayData[i].length !== nColumns) {\n throw new RangeError('Inconsistent array dimensions');\n }\n this.data.push(Float64Array.from(arrayData[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.data[rowIndex][columnIndex] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.data[rowIndex][columnIndex];\n }\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.data.splice(index, 1);\n this.rows -= 1;\n return this;\n }\n\n addRow(index, array) {\n if (array === undefined) {\n array = index;\n index = this.rows;\n }\n checkRowIndex(this, index, true);\n array = Float64Array.from(checkRowVector(this, array, true));\n this.data.splice(index, 0, array);\n this.rows += 1;\n return this;\n }\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 (let i = 0; i < this.rows; i++) {\n const newRow = new Float64Array(this.columns - 1);\n for (let j = 0; j < index; j++) {\n newRow[j] = this.data[i][j];\n }\n for (let j = index + 1; j < this.columns; j++) {\n newRow[j - 1] = this.data[i][j];\n }\n this.data[i] = newRow;\n }\n this.columns -= 1;\n return this;\n }\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 (let i = 0; i < this.rows; i++) {\n const newRow = new Float64Array(this.columns + 1);\n let j = 0;\n for (; j < index; j++) {\n newRow[j] = this.data[i][j];\n }\n newRow[j++] = array[i];\n for (; j < this.columns + 1; j++) {\n newRow[j] = this.data[i][j - 1];\n }\n this.data[i] = newRow;\n }\n this.columns += 1;\n return this;\n }\n}\n\ninstallMathOperations(AbstractMatrix, Matrix);\n","import { AbstractMatrix } 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","import { checkColumnIndex } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixColumnView extends BaseView {\n constructor(matrix, column) {\n checkColumnIndex(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","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","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","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","import { checkRowIndex } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixRowView extends BaseView {\n constructor(matrix, row) {\n checkRowIndex(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","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","import { checkIndices } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixSelectionView extends BaseView {\n constructor(matrix, rowIndices, columnIndices) {\n let 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","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","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","import { AbstractMatrix } from '../matrix';\n\nexport default class WrapperMatrix1D extends AbstractMatrix {\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 let index = this._calculateIndex(rowIndex, columnIndex);\n this.data[index] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n let 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","import { AbstractMatrix } from '../matrix';\n\nexport default class WrapperMatrix2D extends AbstractMatrix {\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","import WrapperMatrix1D from './WrapperMatrix1D';\nimport WrapperMatrix2D from './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","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nexport default class LuDecomposition {\n constructor(matrix) {\n matrix = WrapperMatrix2D.checkMatrix(matrix);\n\n let lu = matrix.clone();\n let rows = lu.rows;\n let columns = lu.columns;\n let pivotVector = new Float64Array(rows);\n let pivotSign = 1;\n let i, j, k, p, s, t, v;\n let LUcolj, kmax;\n\n for (i = 0; i < rows; i++) {\n pivotVector[i] = i;\n }\n\n LUcolj = new Float64Array(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 isSingular() {\n let data = this.LU;\n let col = data.columns;\n for (let j = 0; j < col; j++) {\n if (data.get(j, j) === 0) {\n return true;\n }\n }\n return false;\n }\n\n solve(value) {\n value = Matrix.checkMatrix(value);\n\n let lu = this.LU;\n let 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 let count = value.columns;\n let X = value.subMatrixRow(this.pivotVector, 0, count - 1);\n let columns = lu.columns;\n let 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.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));\n }\n }\n }\n for (k = columns - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X.set(k, j, X.get(k, j) / lu.get(k, k));\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));\n }\n }\n }\n return X;\n }\n\n get determinant() {\n let data = this.LU;\n if (!data.isSquare()) {\n throw new Error('Matrix must be square');\n }\n let determinant = this.pivotSign;\n let col = data.columns;\n for (let j = 0; j < col; j++) {\n determinant *= data.get(j, j);\n }\n return determinant;\n }\n\n get lowerTriangularMatrix() {\n let data = this.LU;\n let rows = data.rows;\n let columns = data.columns;\n let X = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n if (i > j) {\n X.set(i, j, data.get(i, j));\n } else if (i === j) {\n X.set(i, j, 1);\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get upperTriangularMatrix() {\n let data = this.LU;\n let rows = data.rows;\n let columns = data.columns;\n let X = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n if (i <= j) {\n X.set(i, j, data.get(i, j));\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get pivotPermutationVector() {\n return Array.from(this.pivotVector);\n }\n}\n","export function hypotenuse(a, b) {\n let 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","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\n\nexport default class QrDecomposition {\n constructor(value) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n let qr = value.clone();\n let m = value.rows;\n let n = value.columns;\n let rdiag = new Float64Array(n);\n let i, j, k, s;\n\n for (k = 0; k < n; k++) {\n let 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 solve(value) {\n value = Matrix.checkMatrix(value);\n\n let qr = this.QR;\n let 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 let count = value.columns;\n let X = value.clone();\n let n = qr.columns;\n let 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.get(i, k) * X.get(i, j);\n }\n s = -s / qr.get(k, k);\n for (i = k; i < m; i++) {\n X.set(i, j, X.get(i, j) + s * qr.get(i, k));\n }\n }\n }\n for (k = n - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X.set(k, j, X.get(k, j) / this.Rdiag[k]);\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X.set(i, j, X.get(i, j) - X.get(k, j) * qr.get(i, k));\n }\n }\n }\n\n return X.subMatrix(0, n - 1, 0, count - 1);\n }\n\n isFullRank() {\n let columns = this.QR.columns;\n for (let i = 0; i < columns; i++) {\n if (this.Rdiag[i] === 0) {\n return false;\n }\n }\n return true;\n }\n\n get upperTriangularMatrix() {\n let qr = this.QR;\n let n = qr.columns;\n let X = new Matrix(n, n);\n let i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n if (i < j) {\n X.set(i, j, qr.get(i, j));\n } else if (i === j) {\n X.set(i, j, this.Rdiag[i]);\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get orthogonalMatrix() {\n let qr = this.QR;\n let rows = qr.rows;\n let columns = qr.columns;\n let X = new Matrix(rows, columns);\n let i, j, k, s;\n\n for (k = columns - 1; k >= 0; k--) {\n for (i = 0; i < rows; i++) {\n X.set(i, k, 0);\n }\n X.set(k, k, 1);\n for (j = k; j < columns; j++) {\n if (qr.get(k, k) !== 0) {\n s = 0;\n for (i = k; i < rows; i++) {\n s += qr.get(i, k) * X.get(i, j);\n }\n\n s = -s / qr.get(k, k);\n\n for (i = k; i < rows; i++) {\n X.set(i, j, X.get(i, j) + s * qr.get(i, k));\n }\n }\n }\n }\n return X;\n }\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\n\nexport default class SingularValueDecomposition {\n constructor(value, options = {}) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n let m = value.rows;\n let n = value.columns;\n\n const {\n computeLeftSingularVectors = true,\n computeRightSingularVectors = true,\n autoTranspose = false,\n } = options;\n\n let wantu = Boolean(computeLeftSingularVectors);\n let wantv = Boolean(computeRightSingularVectors);\n\n let swapped = false;\n let 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 let aux = wantu;\n wantu = wantv;\n wantv = aux;\n }\n } else {\n a = value.clone();\n }\n\n let nu = Math.min(m, n);\n let ni = Math.min(m + 1, n);\n let s = new Float64Array(ni);\n let U = new Matrix(m, nu);\n let V = new Matrix(n, n);\n\n let e = new Float64Array(n);\n let work = new Float64Array(m);\n\n let si = new Float64Array(ni);\n for (let i = 0; i < ni; i++) si[i] = i;\n\n let nct = Math.min(m - 1, n);\n let nrt = Math.max(0, Math.min(n - 2, m));\n let 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.get(i, k));\n }\n if (s[k] !== 0) {\n if (a.get(k, k) < 0) {\n s[k] = -s[k];\n }\n for (let i = k; i < m; i++) {\n a.set(i, k, a.get(i, k) / s[k]);\n }\n a.set(k, k, a.get(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.get(i, k) * a.get(i, j);\n }\n t = -t / a.get(k, k);\n for (let i = k; i < m; i++) {\n a.set(i, j, a.get(i, j) + t * a.get(i, k));\n }\n }\n e[j] = a.get(k, j);\n }\n\n if (wantu && k < nct) {\n for (let i = k; i < m; i++) {\n U.set(i, k, a.get(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.get(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.set(i, j, a.get(i, j) + t * work[i]);\n }\n }\n }\n if (wantv) {\n for (let i = k + 1; i < n; i++) {\n V.set(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.get(nct, nct);\n }\n if (m < p) {\n s[p - 1] = 0;\n }\n if (nrt + 1 < p) {\n e[nrt] = a.get(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.set(i, j, 0);\n }\n U.set(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.get(i, k) * U.get(i, j);\n }\n t = -t / U.get(k, k);\n for (let i = k; i < m; i++) {\n U.set(i, j, U.get(i, j) + t * U.get(i, k));\n }\n }\n for (let i = k; i < m; i++) {\n U.set(i, k, -U.get(i, k));\n }\n U.set(k, k, 1 + U.get(k, k));\n for (let i = 0; i < k - 1; i++) {\n U.set(i, k, 0);\n }\n } else {\n for (let i = 0; i < m; i++) {\n U.set(i, k, 0);\n }\n U.set(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.get(i, k) * V.get(i, j);\n }\n t = -t / V.get(k + 1, k);\n for (let i = k + 1; i < n; i++) {\n V.set(i, j, V.get(i, j) + t * V.get(i, k));\n }\n }\n }\n for (let i = 0; i < n; i++) {\n V.set(i, k, 0);\n }\n V.set(k, k, 1);\n }\n }\n\n let pp = p - 1;\n let iter = 0;\n let 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.get(i, j) + sn * V.get(i, p - 1);\n V.set(i, p - 1, -sn * V.get(i, j) + cs * V.get(i, p - 1));\n V.set(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.get(i, j) + sn * U.get(i, k - 1);\n U.set(i, k - 1, -sn * U.get(i, j) + cs * U.get(i, k - 1));\n U.set(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.get(i, j) + sn * V.get(i, j + 1);\n V.set(i, j + 1, -sn * V.get(i, j) + cs * V.get(i, j + 1));\n V.set(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.get(i, j) + sn * U.get(i, j + 1);\n U.set(i, j + 1, -sn * U.get(i, j) + cs * U.get(i, j + 1));\n U.set(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.set(i, k, -V.get(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.get(i, k + 1);\n V.set(i, k + 1, V.get(i, k));\n V.set(i, k, t);\n }\n }\n if (wantu && k < m - 1) {\n for (let i = 0; i < m; i++) {\n t = U.get(i, k + 1);\n U.set(i, k + 1, U.get(i, k));\n U.set(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 let 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 solve(value) {\n let Y = value;\n let e = this.threshold;\n let scols = this.s.length;\n let Ls = Matrix.zeros(scols, scols);\n\n for (let i = 0; i < scols; i++) {\n if (Math.abs(this.s[i]) <= e) {\n Ls.set(i, i, 0);\n } else {\n Ls.set(i, i, 1 / this.s[i]);\n }\n }\n\n let U = this.U;\n let V = this.rightSingularVectors;\n\n let VL = V.mmul(Ls);\n let vrows = V.rows;\n let urows = U.rows;\n let 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.get(i, k) * U.get(j, k);\n }\n VLU.set(i, j, sum);\n }\n }\n\n return VLU.mmul(Y);\n }\n\n solveForDiagonal(value) {\n return this.solve(Matrix.diag(value));\n }\n\n inverse() {\n let V = this.V;\n let e = this.threshold;\n let vrows = V.rows;\n let vcols = V.columns;\n let 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.set(i, j, V.get(i, j) / this.s[j]);\n }\n }\n }\n\n let U = this.U;\n\n let urows = U.rows;\n let ucols = U.columns;\n let 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.get(i, k) * U.get(j, k);\n }\n Y.set(i, j, sum);\n }\n }\n\n return Y;\n }\n\n get condition() {\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\n }\n\n get norm2() {\n return this.s[0];\n }\n\n get rank() {\n let tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON;\n let r = 0;\n let s = this.s;\n for (let i = 0, ii = s.length; i < ii; i++) {\n if (s[i] > tol) {\n r++;\n }\n }\n return r;\n }\n\n get diagonal() {\n return Array.from(this.s);\n }\n\n get threshold() {\n return (Number.EPSILON / 2) * Math.max(this.m, this.n) * this.s[0];\n }\n\n get leftSingularVectors() {\n return this.U;\n }\n\n get rightSingularVectors() {\n return this.V;\n }\n\n get diagonalMatrix() {\n return Matrix.diag(this.s);\n }\n}\n","import LuDecomposition from './dc/lu';\nimport QrDecomposition from './dc/qr';\nimport SingularValueDecomposition from './dc/svd';\nimport Matrix from './matrix';\nimport WrapperMatrix2D from './wrap/WrapperMatrix2D';\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\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","import LuDecomposition from './dc/lu';\nimport Matrix from './matrix';\nimport MatrixSelectionView from './views/selection';\n\nexport function determinant(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (matrix.isSquare()) {\n let a, b, c, d;\n if (matrix.columns === 2) {\n // 2 x 2 matrix\n a = matrix.get(0, 0);\n b = matrix.get(0, 1);\n c = matrix.get(1, 0);\n d = matrix.get(1, 1);\n\n return a * d - b * c;\n } else if (matrix.columns === 3) {\n // 3 x 3 matrix\n let subMatrix0, subMatrix1, subMatrix2;\n subMatrix0 = new MatrixSelectionView(matrix, [1, 2], [1, 2]);\n subMatrix1 = new MatrixSelectionView(matrix, [1, 2], [0, 2]);\n subMatrix2 = new MatrixSelectionView(matrix, [1, 2], [0, 1]);\n a = matrix.get(0, 0);\n b = matrix.get(0, 1);\n c = matrix.get(0, 2);\n\n return (\n a * determinant(subMatrix0) -\n b * determinant(subMatrix1) +\n c * determinant(subMatrix2)\n );\n } else {\n // general purpose determinant using the LU decomposition\n return new LuDecomposition(matrix).determinant;\n }\n } else {\n throw Error('determinant can only be calculated for a square matrix');\n }\n}\n","import SingularValueDecomposition from './dc/svd';\nimport Matrix from './matrix';\n\nfunction xrange(n, exception) {\n let range = [];\n for (let i = 0; i < n; i++) {\n if (i !== exception) {\n range.push(i);\n }\n }\n return range;\n}\n\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 let returnArray = matrix.addRow(index, [0]);\n for (let 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\nexport function linearDependencies(matrix, options = {}) {\n const { thresholdValue = 10e-10, thresholdError = 10e-10 } = options;\n matrix = Matrix.checkMatrix(matrix);\n\n let n = matrix.rows;\n let results = new Matrix(n, n);\n\n for (let i = 0; i < n; i++) {\n let b = Matrix.columnVector(matrix.getRow(i));\n let Abis = matrix.subMatrixRow(xrange(n, i)).transpose();\n let svd = new SingularValueDecomposition(Abis);\n let x = svd.solve(b);\n let error = Matrix.sub(b, Abis.mmul(x)).abs().max();\n results.setRow(\n i,\n dependenciesOneRow(error, x, i, thresholdValue, thresholdError),\n );\n }\n return results;\n}\n","import SVD from './dc/svd';\nimport Matrix from './matrix';\n\nexport function pseudoInverse(matrix, threshold = Number.EPSILON) {\n matrix = Matrix.checkMatrix(matrix);\n let svdSolution = new SVD(matrix, { autoTranspose: true });\n\n let U = svdSolution.leftSingularVectors;\n let V = svdSolution.rightSingularVectors;\n let s = svdSolution.diagonal;\n\n for (let 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 return V.mmul(Matrix.diag(s).mmul(U.transpose()));\n}\n","import Matrix from './matrix';\n\nexport function covariance(xMatrix, yMatrix = xMatrix, options = {}) {\n xMatrix = new Matrix(xMatrix);\n let yIsSame = false;\n if (\n typeof yMatrix === 'object' &&\n !Matrix.isMatrix(yMatrix) &&\n !Array.isArray(yMatrix)\n ) {\n options = yMatrix;\n yMatrix = xMatrix;\n yIsSame = true;\n } else {\n yMatrix = new Matrix(yMatrix);\n }\n if (xMatrix.rows !== yMatrix.rows) {\n throw new TypeError('Both matrices must have the same number of rows');\n }\n const { center = true } = options;\n if (center) {\n xMatrix = xMatrix.center('column');\n if (!yIsSame) {\n yMatrix = yMatrix.center('column');\n }\n }\n const cov = xMatrix.transpose().mmul(yMatrix);\n for (let i = 0; i < cov.rows; i++) {\n for (let j = 0; j < cov.columns; j++) {\n cov.set(i, j, cov.get(i, j) * (1 / (xMatrix.rows - 1)));\n }\n }\n return cov;\n}\n","import Matrix from './matrix';\n\nexport function correlation(xMatrix, yMatrix = xMatrix, options = {}) {\n xMatrix = new Matrix(xMatrix);\n let yIsSame = false;\n if (\n typeof yMatrix === 'object' &&\n !Matrix.isMatrix(yMatrix) &&\n !Array.isArray(yMatrix)\n ) {\n options = yMatrix;\n yMatrix = xMatrix;\n yIsSame = true;\n } else {\n yMatrix = new Matrix(yMatrix);\n }\n if (xMatrix.rows !== yMatrix.rows) {\n throw new TypeError('Both matrices must have the same number of rows');\n }\n\n const { center = true, scale = true } = options;\n if (center) {\n xMatrix.center('column');\n if (!yIsSame) {\n yMatrix.center('column');\n }\n }\n if (scale) {\n xMatrix.scale('column');\n if (!yIsSame) {\n yMatrix.scale('column');\n }\n }\n\n const sdx = xMatrix.standardDeviation('column', { unbiased: true });\n const sdy = yIsSame\n ? sdx\n : yMatrix.standardDeviation('column', { unbiased: true });\n\n const corr = xMatrix.transpose().mmul(yMatrix);\n for (let i = 0; i < corr.rows; i++) {\n for (let j = 0; j < corr.columns; j++) {\n corr.set(\n i,\n j,\n corr.get(i, j) * (1 / (sdx[i] * sdy[j])) * (1 / (xMatrix.rows - 1)),\n );\n }\n }\n return corr;\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\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 let n = matrix.columns;\n let V = new Matrix(n, n);\n let d = new Float64Array(n);\n let e = new Float64Array(n);\n let value = matrix;\n let i, j;\n\n let 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.set(i, j, value.get(i, j));\n }\n }\n tred2(n, e, d, V);\n tql2(n, e, d, V);\n } else {\n let H = new Matrix(n, n);\n let ort = new Float64Array(n);\n for (j = 0; j < n; j++) {\n for (i = 0; i < n; i++) {\n H.set(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 get realEigenvalues() {\n return Array.from(this.d);\n }\n\n get imaginaryEigenvalues() {\n return Array.from(this.e);\n }\n\n get eigenvectorMatrix() {\n return this.V;\n }\n\n get diagonalMatrix() {\n let n = this.n;\n let e = this.e;\n let d = this.d;\n let X = new Matrix(n, n);\n let i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n X.set(i, j, 0);\n }\n X.set(i, i, d[i]);\n if (e[i] > 0) {\n X.set(i, i + 1, e[i]);\n } else if (e[i] < 0) {\n X.set(i, i - 1, e[i]);\n }\n }\n return X;\n }\n}\n\nfunction tred2(n, e, d, V) {\n let f, g, h, i, j, k, hh, scale;\n\n for (j = 0; j < n; j++) {\n d[j] = V.get(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.get(i - 1, j);\n V.set(i, j, 0);\n V.set(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.set(j, i, f);\n g = e[j] + V.get(j, j) * f;\n for (k = j + 1; k <= i - 1; k++) {\n g += V.get(k, j) * d[k];\n e[k] += V.get(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.set(k, j, V.get(k, j) - (f * e[k] + g * d[k]));\n }\n d[j] = V.get(i - 1, j);\n V.set(i, j, 0);\n }\n }\n d[i] = h;\n }\n\n for (i = 0; i < n - 1; i++) {\n V.set(n - 1, i, V.get(i, i));\n V.set(i, i, 1);\n h = d[i + 1];\n if (h !== 0) {\n for (k = 0; k <= i; k++) {\n d[k] = V.get(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.get(k, i + 1) * V.get(k, j);\n }\n for (k = 0; k <= i; k++) {\n V.set(k, j, V.get(k, j) - g * d[k]);\n }\n }\n }\n\n for (k = 0; k <= i; k++) {\n V.set(k, i + 1, 0);\n }\n }\n\n for (j = 0; j < n; j++) {\n d[j] = V.get(n - 1, j);\n V.set(n - 1, j, 0);\n }\n\n V.set(n - 1, n - 1, 1);\n e[0] = 0;\n}\n\nfunction tql2(n, e, d, V) {\n let 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 let f = 0;\n let tst1 = 0;\n let 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.get(k, i + 1);\n V.set(k, i + 1, s * V.get(k, i) + c * h);\n V.set(k, i, c * V.get(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.get(j, i);\n V.set(j, i, V.get(j, k));\n V.set(j, k, p);\n }\n }\n }\n}\n\nfunction orthes(n, H, ort, V) {\n let low = 0;\n let high = n - 1;\n let f, g, h, i, j, m;\n let 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.get(i, m - 1));\n }\n\n if (scale !== 0) {\n h = 0;\n for (i = high; i >= m; i--) {\n ort[i] = H.get(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.get(i, j);\n }\n\n f = f / h;\n for (i = m; i <= high; i++) {\n H.set(i, j, H.get(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.get(i, j);\n }\n\n f = f / h;\n for (j = m; j <= high; j++) {\n H.set(i, j, H.get(i, j) - f * ort[j]);\n }\n }\n\n ort[m] = scale * ort[m];\n H.set(m, m - 1, scale * g);\n }\n }\n\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V.set(i, j, i === j ? 1 : 0);\n }\n }\n\n for (m = high - 1; m >= low + 1; m--) {\n if (H.get(m, m - 1) !== 0) {\n for (i = m + 1; i <= high; i++) {\n ort[i] = H.get(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.get(i, j);\n }\n\n g = g / ort[m] / H.get(m, m - 1);\n for (i = m; i <= high; i++) {\n V.set(i, j, V.get(i, j) + g * ort[i]);\n }\n }\n }\n }\n}\n\nfunction hqr2(nn, e, d, V, H) {\n let n = nn - 1;\n let low = 0;\n let high = nn - 1;\n let eps = Number.EPSILON;\n let exshift = 0;\n let norm = 0;\n let p = 0;\n let q = 0;\n let r = 0;\n let s = 0;\n let z = 0;\n let iter = 0;\n let i, j, k, l, m, t, w, x, y;\n let ra, sa, vr, vi;\n let notlast, cdivres;\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n d[i] = H.get(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.get(i, j));\n }\n }\n\n while (n >= low) {\n l = n;\n while (l > low) {\n s = Math.abs(H.get(l - 1, l - 1)) + Math.abs(H.get(l, l));\n if (s === 0) {\n s = norm;\n }\n if (Math.abs(H.get(l, l - 1)) < eps * s) {\n break;\n }\n l--;\n }\n\n if (l === n) {\n H.set(n, n, H.get(n, n) + exshift);\n d[n] = H.get(n, n);\n e[n] = 0;\n n--;\n iter = 0;\n } else if (l === n - 1) {\n w = H.get(n, n - 1) * H.get(n - 1, n);\n p = (H.get(n - 1, n - 1) - H.get(n, n)) / 2;\n q = p * p + w;\n z = Math.sqrt(Math.abs(q));\n H.set(n, n, H.get(n, n) + exshift);\n H.set(n - 1, n - 1, H.get(n - 1, n - 1) + exshift);\n x = H.get(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.get(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.get(n - 1, j);\n H.set(n - 1, j, q * z + p * H.get(n, j));\n H.set(n, j, q * H.get(n, j) - p * z);\n }\n\n for (i = 0; i <= n; i++) {\n z = H.get(i, n - 1);\n H.set(i, n - 1, q * z + p * H.get(i, n));\n H.set(i, n, q * H.get(i, n) - p * z);\n }\n\n for (i = low; i <= high; i++) {\n z = V.get(i, n - 1);\n V.set(i, n - 1, q * z + p * V.get(i, n));\n V.set(i, n, q * V.get(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.get(n, n);\n y = 0;\n w = 0;\n if (l < n) {\n y = H.get(n - 1, n - 1);\n w = H.get(n, n - 1) * H.get(n - 1, n);\n }\n\n if (iter === 10) {\n exshift += x;\n for (i = low; i <= n; i++) {\n H.set(i, i, H.get(i, i) - x);\n }\n s = Math.abs(H.get(n, n - 1)) + Math.abs(H.get(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.set(i, i, H.get(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.get(m, m);\n r = x - z;\n s = y - z;\n p = (r * s - w) / H.get(m + 1, m) + H.get(m, m + 1);\n q = H.get(m + 1, m + 1) - z - r - s;\n r = H.get(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.get(m, m - 1)) * (Math.abs(q) + Math.abs(r)) <\n eps *\n (Math.abs(p) *\n (Math.abs(H.get(m - 1, m - 1)) +\n Math.abs(z) +\n Math.abs(H.get(m + 1, m + 1))))\n ) {\n break;\n }\n m--;\n }\n\n for (i = m + 2; i <= n; i++) {\n H.set(i, i - 2, 0);\n if (i > m + 2) {\n H.set(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.get(k, k - 1);\n q = H.get(k + 1, k - 1);\n r = notlast ? H.get(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.set(k, k - 1, -s * x);\n } else if (l !== m) {\n H.set(k, k - 1, -H.get(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.get(k, j) + q * H.get(k + 1, j);\n if (notlast) {\n p = p + r * H.get(k + 2, j);\n H.set(k + 2, j, H.get(k + 2, j) - p * z);\n }\n\n H.set(k, j, H.get(k, j) - p * x);\n H.set(k + 1, j, H.get(k + 1, j) - p * y);\n }\n\n for (i = 0; i <= Math.min(n, k + 3); i++) {\n p = x * H.get(i, k) + y * H.get(i, k + 1);\n if (notlast) {\n p = p + z * H.get(i, k + 2);\n H.set(i, k + 2, H.get(i, k + 2) - p * r);\n }\n\n H.set(i, k, H.get(i, k) - p);\n H.set(i, k + 1, H.get(i, k + 1) - p * q);\n }\n\n for (i = low; i <= high; i++) {\n p = x * V.get(i, k) + y * V.get(i, k + 1);\n if (notlast) {\n p = p + z * V.get(i, k + 2);\n V.set(i, k + 2, V.get(i, k + 2) - p * r);\n }\n\n V.set(i, k, V.get(i, k) - p);\n V.set(i, k + 1, V.get(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.set(n, n, 1);\n for (i = n - 1; i >= 0; i--) {\n w = H.get(i, i) - p;\n r = 0;\n for (j = l; j <= n; j++) {\n r = r + H.get(i, j) * H.get(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.set(i, n, w !== 0 ? -r / w : -r / (eps * norm));\n } else {\n x = H.get(i, i + 1);\n y = H.get(i + 1, i);\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\n t = (x * s - z * r) / q;\n H.set(i, n, t);\n H.set(\n i + 1,\n n,\n Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z,\n );\n }\n\n t = Math.abs(H.get(i, n));\n if (eps * t * t > 1) {\n for (j = i; j <= n; j++) {\n H.set(j, n, H.get(j, n) / t);\n }\n }\n }\n }\n } else if (q < 0) {\n l = n - 1;\n\n if (Math.abs(H.get(n, n - 1)) > Math.abs(H.get(n - 1, n))) {\n H.set(n - 1, n - 1, q / H.get(n, n - 1));\n H.set(n - 1, n, -(H.get(n, n) - p) / H.get(n, n - 1));\n } else {\n cdivres = cdiv(0, -H.get(n - 1, n), H.get(n - 1, n - 1) - p, q);\n H.set(n - 1, n - 1, cdivres[0]);\n H.set(n - 1, n, cdivres[1]);\n }\n\n H.set(n, n - 1, 0);\n H.set(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.get(i, j) * H.get(j, n - 1);\n sa = sa + H.get(i, j) * H.get(j, n);\n }\n\n w = H.get(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.set(i, n - 1, cdivres[0]);\n H.set(i, n, cdivres[1]);\n } else {\n x = H.get(i, i + 1);\n y = H.get(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.set(i, n - 1, cdivres[0]);\n H.set(i, n, cdivres[1]);\n if (Math.abs(x) > Math.abs(z) + Math.abs(q)) {\n H.set(\n i + 1,\n n - 1,\n (-ra - w * H.get(i, n - 1) + q * H.get(i, n)) / x,\n );\n H.set(\n i + 1,\n n,\n (-sa - w * H.get(i, n) - q * H.get(i, n - 1)) / x,\n );\n } else {\n cdivres = cdiv(\n -r - y * H.get(i, n - 1),\n -s - y * H.get(i, n),\n z,\n q,\n );\n H.set(i + 1, n - 1, cdivres[0]);\n H.set(i + 1, n, cdivres[1]);\n }\n }\n\n t = Math.max(Math.abs(H.get(i, n - 1)), Math.abs(H.get(i, n)));\n if (eps * t * t > 1) {\n for (j = i; j <= n; j++) {\n H.set(j, n - 1, H.get(j, n - 1) / t);\n H.set(j, n, H.get(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.set(i, j, H.get(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.get(i, k) * H.get(k, j);\n }\n V.set(i, j, z);\n }\n }\n}\n\nfunction cdiv(xr, xi, yr, yi) {\n let 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","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\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 let a = value;\n let dimension = a.rows;\n let l = new Matrix(dimension, dimension);\n let positiveDefinite = true;\n let i, j, k;\n\n for (j = 0; j < dimension; j++) {\n let d = 0;\n for (k = 0; k < j; k++) {\n let s = 0;\n for (i = 0; i < k; i++) {\n s += l.get(k, i) * l.get(j, i);\n }\n s = (a.get(j, k) - s) / l.get(k, k);\n l.set(j, k, s);\n d = d + s * s;\n }\n\n d = a.get(j, j) - d;\n\n positiveDefinite &= d > 0;\n l.set(j, j, Math.sqrt(Math.max(d, 0)));\n for (k = j + 1; k < dimension; k++) {\n l.set(j, k, 0);\n }\n }\n\n this.L = l;\n this.positiveDefinite = Boolean(positiveDefinite);\n }\n\n isPositiveDefinite() {\n return this.positiveDefinite;\n }\n\n solve(value) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n let l = this.L;\n let dimension = l.rows;\n\n if (value.rows !== dimension) {\n throw new Error('Matrix dimensions do not match');\n }\n if (this.isPositiveDefinite() === false) {\n throw new Error('Matrix is not positive definite');\n }\n\n let count = value.columns;\n let B = value.clone();\n let 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.set(k, j, B.get(k, j) - B.get(i, j) * l.get(k, i));\n }\n B.set(k, j, B.get(k, j) / l.get(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.set(k, j, B.get(k, j) - B.get(i, j) * l.get(i, k));\n }\n B.set(k, j, B.get(k, j) / l.get(k, k));\n }\n }\n\n return B;\n }\n\n get lowerTriangularMatrix() {\n return this.L;\n }\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nexport default class nipals {\n constructor(X, options = {}) {\n X = WrapperMatrix2D.checkMatrix(X);\n let { Y } = options;\n const {\n scaleScores = false,\n maxIterations = 1000,\n terminationCriteria = 1e-10,\n } = options;\n\n let u;\n if (Y) {\n if (Array.isArray(Y) && typeof Y[0] === 'number') {\n Y = Matrix.columnVector(Y);\n } else {\n Y = WrapperMatrix2D.checkMatrix(Y);\n }\n if (!Y.isColumnVector() || Y.rows !== X.rows) {\n throw new Error('Y must be a column vector of length X.rows');\n }\n u = Y;\n } else {\n u = X.getColumnVector(0);\n }\n\n let diff = 1;\n let t, q, w, tOld;\n\n for (\n let counter = 0;\n counter < maxIterations && diff > terminationCriteria;\n counter++\n ) {\n w = X.transpose().mmul(u).div(u.transpose().mmul(u).get(0, 0));\n w = w.div(w.norm());\n\n t = X.mmul(w).div(w.transpose().mmul(w).get(0, 0));\n\n if (counter > 0) {\n diff = t.clone().sub(tOld).pow(2).sum();\n }\n tOld = t.clone();\n\n if (Y) {\n q = Y.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));\n q = q.div(q.norm());\n\n u = Y.mmul(q).div(q.transpose().mmul(q).get(0, 0));\n } else {\n u = t;\n }\n }\n\n if (Y) {\n let p = X.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));\n p = p.div(p.norm());\n let xResidual = X.clone().sub(t.clone().mmul(p.transpose()));\n let residual = u.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));\n let yResidual = Y.clone().sub(\n t.clone().mulS(residual.get(0, 0)).mmul(q.transpose()),\n );\n\n this.t = t;\n this.p = p.transpose();\n this.w = w.transpose();\n this.q = q;\n this.u = u;\n this.s = t.transpose().mmul(t);\n this.xResidual = xResidual;\n this.yResidual = yResidual;\n this.betas = residual;\n } else {\n this.w = w.transpose();\n this.s = t.transpose().mmul(t).sqrt();\n if (scaleScores) {\n this.t = t.clone().div(this.s.get(0, 0));\n } else {\n this.t = t;\n }\n this.xResidual = X.sub(t.mmul(w.transpose()));\n }\n }\n}\n","const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n","import isArray from 'is-any-array';\n\nfunction sum(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 sumValue = 0;\n\n for (var i = 0; i < input.length; i++) {\n sumValue += input[i];\n }\n\n return sumValue;\n}\n\nexport default sum;\n","import sum from 'ml-array-sum';\n\nfunction mean(input) {\n return sum(input) / input.length;\n}\n\nexport default mean;\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 let counts = new Array(numberOfClasses).fill(0);\n for (let 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 let probabilities = toDiscreteDistribution(\n array,\n getNumberOfClasses(array),\n ).getRow(0);\n\n let sum = 0.0;\n for (let 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\n .filter(function(val, i, arr) {\n return arr.indexOf(val) === i;\n })\n .map((val) => val + 1)\n .reduce((a, b) => Math.max(a, b));\n}\n\n/**\n * @private\n * Calculates the Gini Gain of an array of predictions and those predictions splitted by a feature.\n * @param {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 let splitsImpurity = 0.0;\n let splits = ['greater', 'lesser'];\n\n for (let i = 0; i < splits.length; ++i) {\n let currentSplit = splitted[splits[i]];\n splitsImpurity +=\n (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 let l = array.length;\n\n let m = meanArray(array);\n let error = 0.0;\n\n for (let i = 0; i < l; ++i) {\n let currentElement = array[i];\n error += (currentElement - m) * (currentElement - m);\n }\n\n return error;\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 let error = 0.0;\n let splits = ['greater', 'lesser'];\n\n for (let i = 0; i < splits.length; ++i) {\n let 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 let lesserX = [];\n let greaterX = [];\n let lesserY = [];\n let greaterY = [];\n\n for (let i = 0; i < X.rows; ++i) {\n if (X.get(i, column) < value) {\n lesserX.push(X.getRow(i));\n lesserY.push(y[i]);\n } else {\n greaterX.push(X.getRow(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(\n `Error on zip: the size of a: ${a.length} is different from b: ${b.length}`,\n );\n }\n\n let ret = new Array(a.length);\n for (let 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 mean from 'ml-array-mean';\n\nimport * as Utils from './utils';\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 * @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 // Depending in the node tree class, we set the variables to check information gain (to classify)\n // or error (for regression)\n\n let bestGain = this.kind === 'classifier' ? -Infinity : Infinity;\n let check = this.kind === 'classifier' ? (a, b) => a > b : (a, b) => a < b;\n\n let maxColumn;\n let maxValue;\n\n for (let i = 0; i < XTranspose.rows; ++i) {\n let currentFeature = XTranspose.getRow(i);\n let splitValues = this.featureSplit(currentFeature, y);\n for (let j = 0; j < splitValues.length; ++j) {\n let currentSplitVal = splitValues[j];\n let splitted = this.split(currentFeature, y, currentSplitVal);\n\n let 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 split(x, y, splitValue) {\n let lesser = [];\n let greater = [];\n\n for (let 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 let splitValues = [];\n let arr = Utils.zip(x, y);\n arr.sort(function(a, b) {\n return a[0] - b[0];\n });\n\n for (let i = 1; i < arr.length; ++i) {\n if (arr[i - 1][1] !== arr[i][1]) {\n splitValues.push(\n splitFunctions[this.splitFunction](arr[i - 1][0], arr[i][0]),\n );\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(\n y,\n Utils.getNumberOfClasses(y),\n );\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 let XTranspose = X.transpose();\n let split = this.bestSplit(XTranspose, y);\n\n this.splitValue = split.maxValue;\n this.splitColumn = split.maxColumn;\n this.gain = split.maxGain;\n\n let splittedMatrix = Utils.matrixSplitter(\n X,\n y,\n this.splitColumn,\n this.splitValue,\n );\n\n if (\n currentDepth < this.maxDepth &&\n (this.gain > 0.01 && this.gain !== parentGain) &&\n (splittedMatrix.lesserX.length > 0 && splittedMatrix.greaterX.length > 0)\n ) {\n this.left = new TreeNode(this);\n this.right = new TreeNode(this);\n\n let lesserX = new Matrix(splittedMatrix.lesserX);\n let greaterX = new Matrix(splittedMatrix.greaterX);\n\n this.left.train(\n lesserX,\n splittedMatrix.lesserY,\n currentDepth + 1,\n this.gain,\n );\n this.right.train(\n greaterX,\n splittedMatrix.greaterY,\n currentDepth + 1,\n this.gain,\n );\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 =\n node.distribution.constructor === Array\n ? 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';\n\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 * 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 let predictions = new Array(toPredict.rows);\n\n for (let i = 0; i < toPredict.rows; ++i) {\n predictions[i] = this.root\n .classify(toPredict.getRow(i))\n .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';\n\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 * 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 (\n typeof trainingSet[0] !== 'undefined' &&\n trainingSet[0].length === undefined\n ) {\n trainingSet = Matrix.columnVector(trainingSet);\n } else {\n trainingSet = Matrix.checkMatrix(trainingSet);\n }\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 (\n typeof toPredict[0] !== 'undefined' &&\n toPredict[0].length === undefined\n ) {\n toPredict = Matrix.columnVector(toPredict);\n }\n toPredict = Matrix.checkMatrix(toPredict);\n\n let predictions = new Array(toPredict.rows);\n for (let 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","const SMALLEST_UNSAFE_INTEGER = 0x20000000000000;\r\nconst LARGEST_SAFE_INTEGER = SMALLEST_UNSAFE_INTEGER - 1;\r\nconst UINT32_MAX = -1 >>> 0;\r\nconst UINT32_SIZE = UINT32_MAX + 1;\r\nconst INT32_SIZE = UINT32_SIZE / 2;\r\nconst INT32_MAX = INT32_SIZE - 1;\r\nconst UINT21_SIZE = 1 << 21;\r\nconst UINT21_MAX = UINT21_SIZE - 1;\n\n/**\r\n * Returns a value within [-0x80000000, 0x7fffffff]\r\n */\r\nfunction int32(engine) {\r\n return engine.next() | 0;\r\n}\n\nfunction add(distribution, addend) {\r\n if (addend === 0) {\r\n return distribution;\r\n }\r\n else {\r\n return engine => distribution(engine) + addend;\r\n }\r\n}\n\n/**\r\n * Returns a value within [-0x20000000000000, 0x1fffffffffffff]\r\n */\r\nfunction int53(engine) {\r\n const high = engine.next() | 0;\r\n const low = engine.next() >>> 0;\r\n return ((high & UINT21_MAX) * UINT32_SIZE +\r\n low +\r\n (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0));\r\n}\n\n/**\r\n * Returns a value within [-0x20000000000000, 0x20000000000000]\r\n */\r\nfunction int53Full(engine) {\r\n while (true) {\r\n const high = engine.next() | 0;\r\n if (high & 0x400000) {\r\n if ((high & 0x7fffff) === 0x400000 && (engine.next() | 0) === 0) {\r\n return SMALLEST_UNSAFE_INTEGER;\r\n }\r\n }\r\n else {\r\n const low = engine.next() >>> 0;\r\n return ((high & UINT21_MAX) * UINT32_SIZE +\r\n low +\r\n (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0));\r\n }\r\n }\r\n}\n\n/**\r\n * Returns a value within [0, 0xffffffff]\r\n */\r\nfunction uint32(engine) {\r\n return engine.next() >>> 0;\r\n}\n\n/**\r\n * Returns a value within [0, 0x1fffffffffffff]\r\n */\r\nfunction uint53(engine) {\r\n const high = engine.next() & UINT21_MAX;\r\n const low = engine.next() >>> 0;\r\n return high * UINT32_SIZE + low;\r\n}\n\n/**\r\n * Returns a value within [0, 0x20000000000000]\r\n */\r\nfunction uint53Full(engine) {\r\n while (true) {\r\n const high = engine.next() | 0;\r\n if (high & UINT21_SIZE) {\r\n if ((high & UINT21_MAX) === 0 && (engine.next() | 0) === 0) {\r\n return SMALLEST_UNSAFE_INTEGER;\r\n }\r\n }\r\n else {\r\n const low = engine.next() >>> 0;\r\n return (high & UINT21_MAX) * UINT32_SIZE + low;\r\n }\r\n }\r\n}\n\nfunction isPowerOfTwoMinusOne(value) {\r\n return ((value + 1) & value) === 0;\r\n}\r\nfunction bitmask(masking) {\r\n return (engine) => engine.next() & masking;\r\n}\r\nfunction downscaleToLoopCheckedRange(range) {\r\n const extendedRange = range + 1;\r\n const maximum = extendedRange * Math.floor(UINT32_SIZE / extendedRange);\r\n return engine => {\r\n let value = 0;\r\n do {\r\n value = engine.next() >>> 0;\r\n } while (value >= maximum);\r\n return value % extendedRange;\r\n };\r\n}\r\nfunction downscaleToRange(range) {\r\n if (isPowerOfTwoMinusOne(range)) {\r\n return bitmask(range);\r\n }\r\n else {\r\n return downscaleToLoopCheckedRange(range);\r\n }\r\n}\r\nfunction isEvenlyDivisibleByMaxInt32(value) {\r\n return (value | 0) === 0;\r\n}\r\nfunction upscaleWithHighMasking(masking) {\r\n return engine => {\r\n const high = engine.next() & masking;\r\n const low = engine.next() >>> 0;\r\n return high * UINT32_SIZE + low;\r\n };\r\n}\r\nfunction upscaleToLoopCheckedRange(extendedRange) {\r\n const maximum = extendedRange * Math.floor(SMALLEST_UNSAFE_INTEGER / extendedRange);\r\n return engine => {\r\n let ret = 0;\r\n do {\r\n const high = engine.next() & UINT21_MAX;\r\n const low = engine.next() >>> 0;\r\n ret = high * UINT32_SIZE + low;\r\n } while (ret >= maximum);\r\n return ret % extendedRange;\r\n };\r\n}\r\nfunction upscaleWithinU53(range) {\r\n const extendedRange = range + 1;\r\n if (isEvenlyDivisibleByMaxInt32(extendedRange)) {\r\n const highRange = ((extendedRange / UINT32_SIZE) | 0) - 1;\r\n if (isPowerOfTwoMinusOne(highRange)) {\r\n return upscaleWithHighMasking(highRange);\r\n }\r\n }\r\n return upscaleToLoopCheckedRange(extendedRange);\r\n}\r\nfunction upscaleWithinI53AndLoopCheck(min, max) {\r\n return engine => {\r\n let ret = 0;\r\n do {\r\n const high = engine.next() | 0;\r\n const low = engine.next() >>> 0;\r\n ret =\r\n (high & UINT21_MAX) * UINT32_SIZE +\r\n low +\r\n (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0);\r\n } while (ret < min || ret > max);\r\n return ret;\r\n };\r\n}\r\n/**\r\n * Returns a Distribution to return a value within [min, max]\r\n * @param min The minimum integer value, inclusive. No less than -0x20000000000000.\r\n * @param max The maximum integer value, inclusive. No greater than 0x20000000000000.\r\n */\r\nfunction integer(min, max) {\r\n min = Math.floor(min);\r\n max = Math.floor(max);\r\n if (min < -SMALLEST_UNSAFE_INTEGER || !isFinite(min)) {\r\n throw new RangeError(`Expected min to be at least ${-SMALLEST_UNSAFE_INTEGER}`);\r\n }\r\n else if (max > SMALLEST_UNSAFE_INTEGER || !isFinite(max)) {\r\n throw new RangeError(`Expected max to be at most ${SMALLEST_UNSAFE_INTEGER}`);\r\n }\r\n const range = max - min;\r\n if (range <= 0 || !isFinite(range)) {\r\n return () => min;\r\n }\r\n else if (range === UINT32_MAX) {\r\n if (min === 0) {\r\n return uint32;\r\n }\r\n else {\r\n return add(int32, min + INT32_SIZE);\r\n }\r\n }\r\n else if (range < UINT32_MAX) {\r\n return add(downscaleToRange(range), min);\r\n }\r\n else if (range === LARGEST_SAFE_INTEGER) {\r\n return add(uint53, min);\r\n }\r\n else if (range < LARGEST_SAFE_INTEGER) {\r\n return add(upscaleWithinU53(range), min);\r\n }\r\n else if (max - 1 - min === LARGEST_SAFE_INTEGER) {\r\n return add(uint53Full, min);\r\n }\r\n else if (min === -SMALLEST_UNSAFE_INTEGER &&\r\n max === SMALLEST_UNSAFE_INTEGER) {\r\n return int53Full;\r\n }\r\n else if (min === -SMALLEST_UNSAFE_INTEGER && max === LARGEST_SAFE_INTEGER) {\r\n return int53;\r\n }\r\n else if (min === -LARGEST_SAFE_INTEGER && max === SMALLEST_UNSAFE_INTEGER) {\r\n return add(int53, 1);\r\n }\r\n else if (max === SMALLEST_UNSAFE_INTEGER) {\r\n return add(upscaleWithinI53AndLoopCheck(min - 1, max - 1), 1);\r\n }\r\n else {\r\n return upscaleWithinI53AndLoopCheck(min, max);\r\n }\r\n}\n\nfunction isLeastBitTrue(engine) {\r\n return (engine.next() & 1) === 1;\r\n}\r\nfunction lessThan(distribution, value) {\r\n return engine => distribution(engine) < value;\r\n}\r\nfunction probability(percentage) {\r\n if (percentage <= 0) {\r\n return () => false;\r\n }\r\n else if (percentage >= 1) {\r\n return () => true;\r\n }\r\n else {\r\n const scaled = percentage * UINT32_SIZE;\r\n if (scaled % 1 === 0) {\r\n return lessThan(int32, (scaled - INT32_SIZE) | 0);\r\n }\r\n else {\r\n return lessThan(uint53, Math.round(percentage * SMALLEST_UNSAFE_INTEGER));\r\n }\r\n }\r\n}\r\nfunction bool(numerator, denominator) {\r\n if (denominator == null) {\r\n if (numerator == null) {\r\n return isLeastBitTrue;\r\n }\r\n return probability(numerator);\r\n }\r\n else {\r\n if (numerator <= 0) {\r\n return () => false;\r\n }\r\n else if (numerator >= denominator) {\r\n return () => true;\r\n }\r\n return lessThan(integer(0, denominator - 1), numerator);\r\n }\r\n}\n\n/**\r\n * Returns a Distribution that returns a random `Date` within the inclusive\r\n * range of [`start`, `end`].\r\n * @param start The minimum `Date`\r\n * @param end The maximum `Date`\r\n */\r\nfunction date(start, end) {\r\n const distribution = integer(+start, +end);\r\n return engine => new Date(distribution(engine));\r\n}\n\n/**\r\n * Returns a Distribution to return a value within [1, sideCount]\r\n * @param sideCount The number of sides of the die\r\n */\r\nfunction die(sideCount) {\r\n return integer(1, sideCount);\r\n}\n\n/**\r\n * Returns a distribution that returns an array of length `dieCount` of values\r\n * within [1, `sideCount`]\r\n * @param sideCount The number of sides of each die\r\n * @param dieCount The number of dice\r\n */\r\nfunction dice(sideCount, dieCount) {\r\n const distribution = die(sideCount);\r\n return engine => {\r\n const result = [];\r\n for (let i = 0; i < dieCount; ++i) {\r\n result.push(distribution(engine));\r\n }\r\n return result;\r\n };\r\n}\n\n// tslint:disable:unified-signatures\r\n// has 2**x chars, for faster uniform distribution\r\nconst DEFAULT_STRING_POOL = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-\";\r\nfunction string(pool = DEFAULT_STRING_POOL) {\r\n const poolLength = pool.length;\r\n if (!poolLength) {\r\n throw new Error(\"Expected pool not to be an empty string\");\r\n }\r\n const distribution = integer(0, poolLength - 1);\r\n return (engine, length) => {\r\n let result = \"\";\r\n for (let i = 0; i < length; ++i) {\r\n const j = distribution(engine);\r\n result += pool.charAt(j);\r\n }\r\n return result;\r\n };\r\n}\n\nconst LOWER_HEX_POOL = \"0123456789abcdef\";\r\nconst lowerHex = string(LOWER_HEX_POOL);\r\nconst upperHex = string(LOWER_HEX_POOL.toUpperCase());\r\n/**\r\n * Returns a Distribution that returns a random string comprised of numbers\r\n * or the characters `abcdef` (or `ABCDEF`) of length `length`.\r\n * @param length Length of the result string\r\n * @param uppercase Whether the string should use `ABCDEF` instead of `abcdef`\r\n */\r\nfunction hex(uppercase) {\r\n if (uppercase) {\r\n return upperHex;\r\n }\r\n else {\r\n return lowerHex;\r\n }\r\n}\n\nfunction convertSliceArgument(value, length) {\r\n if (value < 0) {\r\n return Math.max(value + length, 0);\r\n }\r\n else {\r\n return Math.min(value, length);\r\n }\r\n}\n\nfunction toInteger(value) {\r\n const num = +value;\r\n if (num < 0) {\r\n return Math.ceil(num);\r\n }\r\n else {\r\n return Math.floor(num);\r\n }\r\n}\n\n/**\r\n * Returns a random value within the provided `source` within the sliced\r\n * bounds of `begin` and `end`.\r\n * @param source an array of items to pick from\r\n * @param begin the beginning slice index (defaults to `0`)\r\n * @param end the ending slice index (defaults to `source.length`)\r\n */\r\nfunction pick(engine, source, begin, end) {\r\n const length = source.length;\r\n if (length === 0) {\r\n throw new RangeError(\"Cannot pick from an empty array\");\r\n }\r\n const start = begin == null ? 0 : convertSliceArgument(toInteger(begin), length);\r\n const finish = end === void 0 ? length : convertSliceArgument(toInteger(end), length);\r\n if (start >= finish) {\r\n throw new RangeError(`Cannot pick between bounds ${start} and ${finish}`);\r\n }\r\n const distribution = integer(start, finish - 1);\r\n return source[distribution(engine)];\r\n}\n\nfunction multiply(distribution, multiplier) {\r\n if (multiplier === 1) {\r\n return distribution;\r\n }\r\n else if (multiplier === 0) {\r\n return () => 0;\r\n }\r\n else {\r\n return engine => distribution(engine) * multiplier;\r\n }\r\n}\n\n/**\r\n * Returns a floating-point value within [0.0, 1.0)\r\n */\r\nfunction realZeroToOneExclusive(engine) {\r\n return uint53(engine) / SMALLEST_UNSAFE_INTEGER;\r\n}\n\n/**\r\n * Returns a floating-point value within [0.0, 1.0]\r\n */\r\nfunction realZeroToOneInclusive(engine) {\r\n return uint53Full(engine) / SMALLEST_UNSAFE_INTEGER;\r\n}\n\n/**\r\n * Returns a floating-point value within [min, max) or [min, max]\r\n * @param min The minimum floating-point value, inclusive.\r\n * @param max The maximum floating-point value.\r\n * @param inclusive If true, `max` will be inclusive.\r\n */\r\nfunction real(min, max, inclusive = false) {\r\n if (!isFinite(min)) {\r\n throw new RangeError(\"Expected min to be a finite number\");\r\n }\r\n else if (!isFinite(max)) {\r\n throw new RangeError(\"Expected max to be a finite number\");\r\n }\r\n return add(multiply(inclusive ? realZeroToOneInclusive : realZeroToOneExclusive, max - min), min);\r\n}\n\nconst sliceArray = Array.prototype.slice;\n\n/**\r\n * Shuffles an array in-place\r\n * @param engine The Engine to use when choosing random values\r\n * @param array The array to shuffle\r\n * @param downTo minimum index to shuffle. Only used internally.\r\n */\r\nfunction shuffle(engine, array, downTo = 0) {\r\n const length = array.length;\r\n if (length) {\r\n for (let i = (length - 1) >>> 0; i > downTo; --i) {\r\n const distribution = integer(0, i);\r\n const j = distribution(engine);\r\n if (i !== j) {\r\n const tmp = array[i];\r\n array[i] = array[j];\r\n array[j] = tmp;\r\n }\r\n }\r\n }\r\n return array;\r\n}\n\n/**\r\n * From the population array, produce an array with sampleSize elements that\r\n * are randomly chosen without repeats.\r\n * @param engine The Engine to use when choosing random values\r\n * @param population An array that has items to choose a sample from\r\n * @param sampleSize The size of the result array\r\n */\r\nfunction sample(engine, population, sampleSize) {\r\n if (sampleSize < 0 ||\r\n sampleSize > population.length ||\r\n !isFinite(sampleSize)) {\r\n throw new RangeError(\"Expected sampleSize to be within 0 and the length of the population\");\r\n }\r\n if (sampleSize === 0) {\r\n return [];\r\n }\r\n const clone = sliceArray.call(population);\r\n const length = clone.length;\r\n if (length === sampleSize) {\r\n return shuffle(engine, clone, 0);\r\n }\r\n const tailLength = length - sampleSize;\r\n return shuffle(engine, clone, tailLength - 1).slice(tailLength);\r\n}\n\nconst stringRepeat = (() => {\r\n try {\r\n if (\"x\".repeat(3) === \"xxx\") {\r\n return (pattern, count) => pattern.repeat(count);\r\n }\r\n }\r\n catch (_) {\r\n // nothing to do here\r\n }\r\n return (pattern, count) => {\r\n let result = \"\";\r\n while (count > 0) {\r\n if (count & 1) {\r\n result += pattern;\r\n }\r\n count >>= 1;\r\n pattern += pattern;\r\n }\r\n return result;\r\n };\r\n})();\n\nfunction zeroPad(text, zeroCount) {\r\n return stringRepeat(\"0\", zeroCount - text.length) + text;\r\n}\r\n/**\r\n * Returns a Universally Unique Identifier Version 4.\r\n *\r\n * See http://en.wikipedia.org/wiki/Universally_unique_identifier\r\n */\r\nfunction uuid4(engine) {\r\n const a = engine.next() >>> 0;\r\n const b = engine.next() | 0;\r\n const c = engine.next() | 0;\r\n const d = engine.next() >>> 0;\r\n return (zeroPad(a.toString(16), 8) +\r\n \"-\" +\r\n zeroPad((b & 0xffff).toString(16), 4) +\r\n \"-\" +\r\n zeroPad((((b >> 4) & 0x0fff) | 0x4000).toString(16), 4) +\r\n \"-\" +\r\n zeroPad(((c & 0x3fff) | 0x8000).toString(16), 4) +\r\n \"-\" +\r\n zeroPad(((c >> 4) & 0xffff).toString(16), 4) +\r\n zeroPad(d.toString(16), 8));\r\n}\n\n/**\r\n * An int32-producing Engine that uses `Math.random()`\r\n */\r\nconst nativeMath = {\r\n next() {\r\n return (Math.random() * UINT32_SIZE) | 0;\r\n }\r\n};\n\n// tslint:disable:unified-signatures\r\n/**\r\n * A wrapper around an Engine that provides easy-to-use methods for\r\n * producing values based on known distributions\r\n */\r\nclass Random {\r\n /**\r\n * Creates a new Random wrapper\r\n * @param engine The engine to use (defaults to a `Math.random`-based implementation)\r\n */\r\n constructor(engine = nativeMath) {\r\n this.engine = engine;\r\n }\r\n /**\r\n * Returns a value within [-0x80000000, 0x7fffffff]\r\n */\r\n int32() {\r\n return int32(this.engine);\r\n }\r\n /**\r\n * Returns a value within [0, 0xffffffff]\r\n */\r\n uint32() {\r\n return uint32(this.engine);\r\n }\r\n /**\r\n * Returns a value within [0, 0x1fffffffffffff]\r\n */\r\n uint53() {\r\n return uint53(this.engine);\r\n }\r\n /**\r\n * Returns a value within [0, 0x20000000000000]\r\n */\r\n uint53Full() {\r\n return uint53Full(this.engine);\r\n }\r\n /**\r\n * Returns a value within [-0x20000000000000, 0x1fffffffffffff]\r\n */\r\n int53() {\r\n return int53(this.engine);\r\n }\r\n /**\r\n * Returns a value within [-0x20000000000000, 0x20000000000000]\r\n */\r\n int53Full() {\r\n return int53Full(this.engine);\r\n }\r\n /**\r\n * Returns a value within [min, max]\r\n * @param min The minimum integer value, inclusive. No less than -0x20000000000000.\r\n * @param max The maximum integer value, inclusive. No greater than 0x20000000000000.\r\n */\r\n integer(min, max) {\r\n return integer(min, max)(this.engine);\r\n }\r\n /**\r\n * Returns a floating-point value within [0.0, 1.0]\r\n */\r\n realZeroToOneInclusive() {\r\n return realZeroToOneInclusive(this.engine);\r\n }\r\n /**\r\n * Returns a floating-point value within [0.0, 1.0)\r\n */\r\n realZeroToOneExclusive() {\r\n return realZeroToOneExclusive(this.engine);\r\n }\r\n /**\r\n * Returns a floating-point value within [min, max) or [min, max]\r\n * @param min The minimum floating-point value, inclusive.\r\n * @param max The maximum floating-point value.\r\n * @param inclusive If true, `max` will be inclusive.\r\n */\r\n real(min, max, inclusive = false) {\r\n return real(min, max, inclusive)(this.engine);\r\n }\r\n bool(numerator, denominator) {\r\n return bool(numerator, denominator)(this.engine);\r\n }\r\n /**\r\n * Return a random value within the provided `source` within the sliced\r\n * bounds of `begin` and `end`.\r\n * @param source an array of items to pick from\r\n * @param begin the beginning slice index (defaults to `0`)\r\n * @param end the ending slice index (defaults to `source.length`)\r\n */\r\n pick(source, begin, end) {\r\n return pick(this.engine, source, begin, end);\r\n }\r\n /**\r\n * Shuffles an array in-place\r\n * @param array The array to shuffle\r\n */\r\n shuffle(array) {\r\n return shuffle(this.engine, array);\r\n }\r\n /**\r\n * From the population array, returns an array with sampleSize elements that\r\n * are randomly chosen without repeats.\r\n * @param population An array that has items to choose a sample from\r\n * @param sampleSize The size of the result array\r\n */\r\n sample(population, sampleSize) {\r\n return sample(this.engine, population, sampleSize);\r\n }\r\n /**\r\n * Returns a value within [1, sideCount]\r\n * @param sideCount The number of sides of the die\r\n */\r\n die(sideCount) {\r\n return die(sideCount)(this.engine);\r\n }\r\n /**\r\n * Returns an array of length `dieCount` of values within [1, sideCount]\r\n * @param sideCount The number of sides of each die\r\n * @param dieCount The number of dice\r\n */\r\n dice(sideCount, dieCount) {\r\n return dice(sideCount, dieCount)(this.engine);\r\n }\r\n /**\r\n * Returns a Universally Unique Identifier Version 4.\r\n *\r\n * See http://en.wikipedia.org/wiki/Universally_unique_identifier\r\n */\r\n uuid4() {\r\n return uuid4(this.engine);\r\n }\r\n string(length, pool) {\r\n return string(pool)(this.engine, length);\r\n }\r\n /**\r\n * Returns a random string comprised of numbers or the characters `abcdef`\r\n * (or `ABCDEF`) of length `length`.\r\n * @param length Length of the result string\r\n * @param uppercase Whether the string should use `ABCDEF` instead of `abcdef`\r\n */\r\n hex(length, uppercase) {\r\n return hex(uppercase)(this.engine, length);\r\n }\r\n /**\r\n * Returns a random `Date` within the inclusive range of [`start`, `end`].\r\n * @param start The minimum `Date`\r\n * @param end The maximum `Date`\r\n */\r\n date(start, end) {\r\n return date(start, end)(this.engine);\r\n }\r\n}\n\n/**\r\n * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array\r\n */\r\nconst I32Array = (() => {\r\n try {\r\n const buffer = new ArrayBuffer(4);\r\n const view = new Int32Array(buffer);\r\n view[0] = INT32_SIZE;\r\n if (view[0] === -INT32_SIZE) {\r\n return Int32Array;\r\n }\r\n }\r\n catch (_) {\r\n // nothing to do here\r\n }\r\n return Array;\r\n})();\n\nlet data = null;\r\nconst COUNT = 128;\r\nlet index = COUNT;\r\n/**\r\n * An Engine that relies on the globally-available `crypto.getRandomValues`,\r\n * which is typically available in modern browsers.\r\n *\r\n * See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues\r\n *\r\n * If unavailable or otherwise non-functioning, then `browserCrypto` will\r\n * likely `throw` on the first call to `next()`.\r\n */\r\nconst browserCrypto = {\r\n next() {\r\n if (index >= COUNT) {\r\n if (data === null) {\r\n data = new I32Array(COUNT);\r\n }\r\n crypto.getRandomValues(data);\r\n index = 0;\r\n }\r\n return data[index++] | 0;\r\n }\r\n};\n\n/**\r\n * Returns an array of random int32 values, based on current time\r\n * and a random number engine\r\n *\r\n * @param engine an Engine to pull random values from, default `nativeMath`\r\n * @param length the length of the Array, minimum 1, default 16\r\n */\r\nfunction createEntropy(engine = nativeMath, length = 16) {\r\n const array = [];\r\n array.push(new Date().getTime() | 0);\r\n for (let i = 1; i < length; ++i) {\r\n array[i] = engine.next() | 0;\r\n }\r\n return array;\r\n}\n\n/**\r\n * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul\r\n */\r\nconst imul = (() => {\r\n try {\r\n if (Math.imul(UINT32_MAX, 5) === -5) {\r\n return Math.imul;\r\n }\r\n }\r\n catch (_) {\r\n // nothing to do here\r\n }\r\n const UINT16_MAX = 0xffff;\r\n return (a, b) => {\r\n const ah = (a >>> 16) & UINT16_MAX;\r\n const al = a & UINT16_MAX;\r\n const bh = (b >>> 16) & UINT16_MAX;\r\n const bl = b & UINT16_MAX;\r\n // the shift by 0 fixes the sign on the high part\r\n // the final |0 converts the unsigned value into a signed value\r\n return (al * bl + (((ah * bl + al * bh) << 16) >>> 0)) | 0;\r\n };\r\n})();\n\nconst ARRAY_SIZE = 624;\r\nconst ARRAY_MAX = ARRAY_SIZE - 1;\r\nconst M = 397;\r\nconst ARRAY_SIZE_MINUS_M = ARRAY_SIZE - M;\r\nconst A = 0x9908b0df;\r\n/**\r\n * An Engine that is a pseudorandom number generator using the Mersenne\r\n * Twister algorithm based on the prime 2**19937 − 1\r\n *\r\n * See http://en.wikipedia.org/wiki/Mersenne_twister\r\n */\r\nclass MersenneTwister19937 {\r\n /**\r\n * MersenneTwister19937 should not be instantiated directly.\r\n * Instead, use the static methods `seed`, `seedWithArray`, or `autoSeed`.\r\n */\r\n constructor() {\r\n this.data = new I32Array(ARRAY_SIZE);\r\n this.index = 0; // integer within [0, 624]\r\n this.uses = 0;\r\n }\r\n /**\r\n * Returns a MersenneTwister19937 seeded with an initial int32 value\r\n * @param initial the initial seed value\r\n */\r\n static seed(initial) {\r\n return new MersenneTwister19937().seed(initial);\r\n }\r\n /**\r\n * Returns a MersenneTwister19937 seeded with zero or more int32 values\r\n * @param source A series of int32 values\r\n */\r\n static seedWithArray(source) {\r\n return new MersenneTwister19937().seedWithArray(source);\r\n }\r\n /**\r\n * Returns a MersenneTwister19937 seeded with the current time and\r\n * a series of natively-generated random values\r\n */\r\n static autoSeed() {\r\n return MersenneTwister19937.seedWithArray(createEntropy());\r\n }\r\n /**\r\n * Returns the next int32 value of the sequence\r\n */\r\n next() {\r\n if ((this.index | 0) >= ARRAY_SIZE) {\r\n refreshData(this.data);\r\n this.index = 0;\r\n }\r\n const value = this.data[this.index];\r\n this.index = (this.index + 1) | 0;\r\n this.uses += 1;\r\n return temper(value) | 0;\r\n }\r\n /**\r\n * Returns the number of times that the Engine has been used.\r\n *\r\n * This can be provided to an unused MersenneTwister19937 with the same\r\n * seed, bringing it to the exact point that was left off.\r\n */\r\n getUseCount() {\r\n return this.uses;\r\n }\r\n /**\r\n * Discards one or more items from the engine\r\n * @param count The count of items to discard\r\n */\r\n discard(count) {\r\n if (count <= 0) {\r\n return this;\r\n }\r\n this.uses += count;\r\n if ((this.index | 0) >= ARRAY_SIZE) {\r\n refreshData(this.data);\r\n this.index = 0;\r\n }\r\n while (count + this.index > ARRAY_SIZE) {\r\n count -= ARRAY_SIZE - this.index;\r\n refreshData(this.data);\r\n this.index = 0;\r\n }\r\n this.index = (this.index + count) | 0;\r\n return this;\r\n }\r\n seed(initial) {\r\n let previous = 0;\r\n this.data[0] = previous = initial | 0;\r\n for (let i = 1; i < ARRAY_SIZE; i = (i + 1) | 0) {\r\n this.data[i] = previous =\r\n (imul(previous ^ (previous >>> 30), 0x6c078965) + i) | 0;\r\n }\r\n this.index = ARRAY_SIZE;\r\n this.uses = 0;\r\n return this;\r\n }\r\n seedWithArray(source) {\r\n this.seed(0x012bd6aa);\r\n seedWithArray(this.data, source);\r\n return this;\r\n }\r\n}\r\nfunction refreshData(data) {\r\n let k = 0;\r\n let tmp = 0;\r\n for (; (k | 0) < ARRAY_SIZE_MINUS_M; k = (k + 1) | 0) {\r\n tmp = (data[k] & INT32_SIZE) | (data[(k + 1) | 0] & INT32_MAX);\r\n data[k] = data[(k + M) | 0] ^ (tmp >>> 1) ^ (tmp & 0x1 ? A : 0);\r\n }\r\n for (; (k | 0) < ARRAY_MAX; k = (k + 1) | 0) {\r\n tmp = (data[k] & INT32_SIZE) | (data[(k + 1) | 0] & INT32_MAX);\r\n data[k] =\r\n data[(k - ARRAY_SIZE_MINUS_M) | 0] ^ (tmp >>> 1) ^ (tmp & 0x1 ? A : 0);\r\n }\r\n tmp = (data[ARRAY_MAX] & INT32_SIZE) | (data[0] & INT32_MAX);\r\n data[ARRAY_MAX] = data[M - 1] ^ (tmp >>> 1) ^ (tmp & 0x1 ? A : 0);\r\n}\r\nfunction temper(value) {\r\n value ^= value >>> 11;\r\n value ^= (value << 7) & 0x9d2c5680;\r\n value ^= (value << 15) & 0xefc60000;\r\n return value ^ (value >>> 18);\r\n}\r\nfunction seedWithArray(data, source) {\r\n let i = 1;\r\n let j = 0;\r\n const sourceLength = source.length;\r\n let k = Math.max(sourceLength, ARRAY_SIZE) | 0;\r\n let previous = data[0] | 0;\r\n for (; (k | 0) > 0; --k) {\r\n data[i] = previous =\r\n ((data[i] ^ imul(previous ^ (previous >>> 30), 0x0019660d)) +\r\n (source[j] | 0) +\r\n (j | 0)) |\r\n 0;\r\n i = (i + 1) | 0;\r\n ++j;\r\n if ((i | 0) > ARRAY_MAX) {\r\n data[0] = data[ARRAY_MAX];\r\n i = 1;\r\n }\r\n if (j >= sourceLength) {\r\n j = 0;\r\n }\r\n }\r\n for (k = ARRAY_MAX; (k | 0) > 0; --k) {\r\n data[i] = previous =\r\n ((data[i] ^ imul(previous ^ (previous >>> 30), 0x5d588b65)) - i) | 0;\r\n i = (i + 1) | 0;\r\n if ((i | 0) > ARRAY_MAX) {\r\n data[0] = data[ARRAY_MAX];\r\n i = 1;\r\n }\r\n }\r\n data[0] = INT32_SIZE;\r\n}\n\nlet data$1 = null;\r\nconst COUNT$1 = 128;\r\nlet index$1 = COUNT$1;\r\n/**\r\n * An Engine that relies on the node-available\r\n * `require('crypto').randomBytes`, which has been available since 0.58.\r\n *\r\n * See https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback\r\n *\r\n * If unavailable or otherwise non-functioning, then `nodeCrypto` will\r\n * likely `throw` on the first call to `next()`.\r\n */\r\nconst nodeCrypto = {\r\n next() {\r\n if (index$1 >= COUNT$1) {\r\n data$1 = new Int32Array(new Int8Array(require(\"crypto\").randomBytes(4 * COUNT$1)).buffer);\r\n index$1 = 0;\r\n }\r\n return data$1[index$1++] | 0;\r\n }\r\n};\n\n/**\r\n * Returns a Distribution to random value within the provided `source`\r\n * within the sliced bounds of `begin` and `end`.\r\n * @param source an array of items to pick from\r\n * @param begin the beginning slice index (defaults to `0`)\r\n * @param end the ending slice index (defaults to `source.length`)\r\n */\r\nfunction picker(source, begin, end) {\r\n const clone = sliceArray.call(source, begin, end);\r\n if (clone.length === 0) {\r\n throw new RangeError(`Cannot pick from a source with no items`);\r\n }\r\n const distribution = integer(0, clone.length - 1);\r\n return engine => clone[distribution(engine)];\r\n}\n\nexport { Random, browserCrypto, nativeMath, MersenneTwister19937, nodeCrypto, bool, date, dice, die, hex, int32, int53, int53Full, integer, pick, picker, real, realZeroToOneExclusive, realZeroToOneInclusive, sample, shuffle, string, uint32, uint53, uint53Full, uuid4, createEntropy };\n//# sourceMappingURL=random-js.esm.js.map\n","import * as 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(\n trainingSet,\n trainingValue,\n seed,\n) {\n let engine;\n let distribution = Random.integer(0, trainingSet.rows - 1);\n if (seed === undefined) {\n engine = Random.MersenneTwister19937.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = Random.MersenneTwister19937.seed(seed);\n } else {\n throw new RangeError(\n `Expected seed must be undefined or integer not ${seed}`,\n );\n }\n\n let Xr = new Array(trainingSet.rows);\n let yr = new Array(trainingSet.rows);\n\n for (let i = 0; i < trainingSet.rows; ++i) {\n let index = distribution(engine);\n Xr[i] = trainingSet.getRow(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 'N should be less or equal to the number of columns of X',\n );\n }\n\n let distribution = Random.integer(0, trainingSet.columns - 1);\n let engine;\n if (seed === undefined) {\n engine = Random.MersenneTwister19937.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = Random.MersenneTwister19937.seed(seed);\n } else {\n throw new RangeError(\n `Expected seed must be undefined or integer not ${seed}`,\n );\n }\n\n let toRet = new Matrix(trainingSet.rows, n);\n\n let usedIndex;\n let index;\n if (replacement) {\n usedIndex = new Array(n);\n for (let i = 0; i < n; ++i) {\n 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 (let 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 {\n Matrix,\n WrapperMatrix2D,\n MatrixTransposeView,\n MatrixColumnSelectionView,\n} 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 let 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(\n `The maxFeatures parameter should be less than ${trainingSet.columns}`,\n );\n } else {\n this.n = this.maxFeatures;\n }\n } else {\n throw new RangeError(\n `Cannot process the maxFeatures parameter ${this.maxFeatures}`,\n );\n }\n\n let Estimator;\n if (this.isClassifier) {\n 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 (let i = 0; i < this.nEstimators; ++i) {\n let res = this.useSampleBagging\n ? Utils.examplesBaggingWithReplacement(\n trainingSet,\n trainingValues,\n this.seed,\n )\n : { X: trainingSet, y: trainingValues };\n let X = res.X;\n let 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 let predictionValues = new Array(this.nEstimators);\n toPredict = Matrix.checkMatrix(toPredict);\n for (let i = 0; i < this.nEstimators; ++i) {\n let X = new MatrixColumnSelectionView(toPredict, this.indexes[i]); // get features for estimator\n predictionValues[i] = this.estimators[i].predict(X);\n }\n\n predictionValues = new MatrixTransposeView(\n new WrapperMatrix2D(predictionValues),\n );\n let predictions = new Array(predictionValues.rows);\n for (let 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 let 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\n .sort(\n (a, b) =>\n arr.filter((v) => v === a).length - arr.filter((v) => v === b).length,\n )\n .pop();\n}\n","const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\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","import isArray from 'is-any-array';\nimport quickSelectMedian from 'median-quickselect';\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","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 (\n !(\n options.selectionMethod === 'mean' ||\n options.selectionMethod === 'median'\n )\n ) {\n throw new RangeError(\n `Unsupported selection method ${options.selectionMethod}`,\n );\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 let 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","import { Matrix, MatrixTransposeView, EVD, SVD, NIPALS } from 'ml-matrix';\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 {string} [options.method='SVD'] - select which method to use: SVD (default), covarianceMatrirx or NIPALS.\n * @param {number} [options.nCompNIPALS=2] - number of components to be computed with NIPALS.\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 * @param {boolean} [options.ignoreZeroVariance=false] - ignore columns with zero variance if `scale` is `true`.\n * */\nexport class 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 this.R = model.R;\n this.excludedFeatures = model.excludedFeatures || [];\n return;\n }\n\n dataset = new Matrix(dataset);\n\n const {\n isCovarianceMatrix = false,\n method = 'SVD',\n nCompNIPALS = 2,\n center = true,\n scale = false,\n ignoreZeroVariance = false,\n } = options;\n\n this.center = center;\n this.scale = scale;\n this.means = null;\n this.stdevs = null;\n this.excludedFeatures = [];\n\n if (isCovarianceMatrix) {\n // User provided a covariance matrix instead of dataset.\n this._computeFromCovarianceMatrix(dataset);\n return;\n }\n\n this._adjust(dataset, ignoreZeroVariance);\n switch (method) {\n case 'covarianceMatrix': {\n // User provided a dataset but wants us to compute and use the covariance matrix.\n const covarianceMatrix = new MatrixTransposeView(dataset)\n .mmul(dataset)\n .div(dataset.rows - 1);\n this._computeFromCovarianceMatrix(covarianceMatrix);\n break;\n }\n case 'NIPALS': {\n this._computeWithNIPALS(dataset, nCompNIPALS);\n break;\n }\n case 'SVD': {\n const 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 = [];\n for (const singularValue of singularValues) {\n eigenvalues.push((singularValue * singularValue) / (dataset.rows - 1));\n }\n this.S = eigenvalues;\n break;\n }\n default: {\n throw new Error(`unknown method: ${method}`);\n }\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 (typeof model.name !== 'string') {\n throw new TypeError('model must have a name property');\n }\n if (model.name !== 'PCA') {\n throw new RangeError(`invalid model: ${model.name}`);\n }\n return new PCA(true, model);\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 { nComponents = this.U.columns } = options;\n dataset = new Matrix(dataset);\n if (this.center) {\n dataset.subRowVector(this.means);\n if (this.scale) {\n for (let i of this.excludedFeatures) {\n dataset.removeColumn(i);\n }\n dataset.divRowVector(this.stdevs);\n }\n }\n var predictions = dataset.mmul(this.U);\n return predictions.subMatrix(0, predictions.rows - 1, 0, nComponents - 1);\n }\n\n /**\n * Calculates the inverse PCA transform\n * @param {Matrix} dataset\n * @return {Matrix} dataset projected in the PCA space\n */\n invert(dataset) {\n dataset = Matrix.checkMatrix(dataset);\n\n var inverse = dataset.mmul(this.U.transpose());\n\n if (this.center) {\n if (this.scale) {\n inverse.mulRowVector(this.stdevs);\n }\n inverse.addRowVector(this.means);\n }\n\n return inverse;\n }\n\n\n /**\n * Returns the proportion of variance for each component\n * @return {[number]}\n */\n getExplainedVariance() {\n var sum = 0;\n for (const s of this.S) {\n sum += s;\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 excludedFeatures: this.excludedFeatures,\n };\n }\n\n _adjust(dataset, ignoreZeroVariance) {\n if (this.center) {\n const mean = dataset.mean('column');\n const stdevs = this.scale\n ? dataset.standardDeviation('column', { mean })\n : null;\n this.means = mean;\n dataset.subRowVector(mean);\n if (this.scale) {\n for (let i = 0; i < stdevs.length; i++) {\n if (stdevs[i] === 0) {\n if (ignoreZeroVariance) {\n dataset.removeColumn(i);\n stdevs.splice(i, 1);\n this.excludedFeatures.push(i);\n i--;\n } else {\n throw new RangeError(\n `Cannot scale the dataset (standard deviation is zero at index ${i}`,\n );\n }\n }\n }\n this.stdevs = stdevs;\n dataset.divRowVector(stdevs);\n }\n }\n }\n\n _computeFromCovarianceMatrix(dataset) {\n const evd = new EVD(dataset, { assumeSymmetric: true });\n this.U = evd.eigenvectorMatrix;\n this.U.flipRows();\n this.S = evd.realEigenvalues;\n this.S.reverse();\n }\n\n _computeWithNIPALS(dataset, nCompNIPALS) {\n this.U = new Matrix(nCompNIPALS, dataset.columns);\n this.S = [];\n\n let x = dataset;\n for (let i = 0; i < nCompNIPALS; i++) {\n let dc = new NIPALS(x);\n\n this.U.setRow(i, dc.w.transpose());\n this.S.push(Math.pow(dc.s.get(0, 0), 2));\n\n x = dc.xResidual;\n }\n this.U = this.U.transpose(); // to be compatible with API\n }\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","/**\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 distance/similarity matrix. The matrix is square and has a size equal to the length of\n * the data array\n */\nexport default function distanceMatrix(data, distanceFn) {\n const result = getMatrix(data.length);\n\n // Compute upper distance matrix\n for (let i = 0; i < data.length; i++) {\n for (let j = 0; j <= i; j++) {\n result[i][j] = distanceFn(data[i], data[j]);\n result[j][i] = result[i][j];\n }\n }\n\n return result;\n}\n\nfunction getMatrix(size) {\n const matrix = [];\n for (let i = 0; i < size; i++) {\n const row = [];\n matrix.push(row);\n for (let j = 0; j < size; j++) {\n row.push(0);\n }\n }\n return matrix;\n}\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","module.exports = require('./lib/heap');\n","import Heap from 'heap';\n\nexport default class Cluster {\n constructor() {\n this.children = [];\n this.height = 0;\n this.size = 1;\n this.index = -1;\n this.isLeaf = false;\n }\n\n /**\n * Creates an array of clusters where the maximum height is smaller than the threshold\n * @param {number} threshold\n * @return {Array}\n */\n cut(threshold) {\n if (typeof threshold !== 'number') {\n throw new TypeError('threshold must be a number');\n }\n if (threshold < 0) {\n throw new RangeError('threshold must be a positive number');\n }\n let list = [this];\n const ans = [];\n while (list.length > 0) {\n const aux = list.shift();\n if (threshold >= aux.height) {\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 `groups` number of clusters.\n * @param {number} groups - Them number of children the first level of the tree should have.\n * @return {Cluster}\n */\n group(groups) {\n if (!Number.isInteger(groups) || groups < 1) {\n throw new RangeError('groups must be a positive integer');\n }\n\n const heap = new Heap((a, b) => {\n return b.height - a.height;\n });\n\n heap.push(this);\n\n while (heap.size() < groups) {\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.height = this.height;\n\n return root;\n }\n\n /**\n * Traverses the tree depth-first and calls the provided callback with each individual node\n * @param {function} cb - The callback to be called on each node encounter\n */\n traverse(cb) {\n function visit(root, callback) {\n callback(root);\n if (root.children) {\n for (const child of root.children) {\n visit(child, callback);\n }\n }\n }\n visit(this, cb);\n }\n\n /**\n * Returns a list of indices for all the leaves of this cluster.\n * The list is ordered in such a way that a dendrogram could be drawn without crossing branches.\n * @returns {Array}\n */\n indices() {\n const result = [];\n this.traverse((cluster) => {\n if (cluster.isLeaf) {\n result.push(cluster.index);\n }\n });\n return result;\n }\n}\n","import { euclidean } from 'ml-distance-euclidean';\nimport getDistanceMatrix from 'ml-distance-matrix';\nimport { Matrix } from 'ml-matrix';\n\nimport Cluster from './Cluster';\n\nfunction singleLink(dKI, dKJ) {\n return Math.min(dKI, dKJ);\n}\n\nfunction completeLink(dKI, dKJ) {\n return Math.max(dKI, dKJ);\n}\n\nfunction averageLink(dKI, dKJ, dIJ, ni, nj) {\n const ai = ni / (ni + nj);\n const aj = nj / (ni + nj);\n return ai * dKI + aj * dKJ;\n}\n\nfunction weightedAverageLink(dKI, dKJ) {\n return (dKI + dKJ) / 2;\n}\n\nfunction centroidLink(dKI, dKJ, dIJ, ni, nj) {\n const ai = ni / (ni + nj);\n const aj = nj / (ni + nj);\n const b = -(ni * nj) / (ni + nj) ** 2;\n return ai * dKI + aj * dKJ + b * dIJ;\n}\n\nfunction medianLink(dKI, dKJ, dIJ) {\n return dKI / 2 + dKJ / 2 - dIJ / 4;\n}\n\nfunction wardLink(dKI, dKJ, dIJ, ni, nj, nk) {\n const ai = (ni + nk) / (ni + nj + nk);\n const aj = (nj + nk) / (ni + nj + nk);\n const b = -nk / (ni + nj + nk);\n return ai * dKI + aj * dKJ + b * dIJ;\n}\n\nfunction wardLink2(dKI, dKJ, dIJ, ni, nj, nk) {\n const ai = (ni + nk) / (ni + nj + nk);\n const aj = (nj + nk) / (ni + nj + nk);\n const b = -nk / (ni + nj + nk);\n return Math.sqrt(ai * dKI * dKI + aj * dKJ * dKJ + b * dIJ * dIJ);\n}\n\n/**\n * Continuously merge nodes that have the least dissimilarity\n * @param {Array>} data - Array of points to be clustered\n * @param {object} [options]\n * @param {Function} [options.distanceFunction]\n * @param {string} [options.method] - Default: `'complete'`\n * @param {boolean} [options.isDistanceMatrix] - Is the input already a distance matrix?\n * @constructor\n */\nexport function agnes(data, options = {}) {\n const {\n distanceFunction = euclidean,\n method = 'complete',\n isDistanceMatrix = false,\n } = options;\n\n let updateFunc;\n if (!isDistanceMatrix) {\n data = getDistanceMatrix(data, distanceFunction);\n }\n let distanceMatrix = new Matrix(data);\n const numLeaves = distanceMatrix.rows;\n\n // allows to use a string or a given function\n if (typeof method === 'string') {\n switch (method.toLowerCase()) {\n case 'single':\n updateFunc = singleLink;\n break;\n case 'complete':\n updateFunc = completeLink;\n break;\n case 'average':\n case 'upgma':\n updateFunc = averageLink;\n break;\n case 'wpgma':\n updateFunc = weightedAverageLink;\n break;\n case 'centroid':\n case 'upgmc':\n updateFunc = centroidLink;\n break;\n case 'median':\n case 'wpgmc':\n updateFunc = medianLink;\n break;\n case 'ward':\n updateFunc = wardLink;\n break;\n case 'ward2':\n updateFunc = wardLink2;\n break;\n default:\n throw new RangeError(`unknown clustering method: ${method}`);\n }\n } else if (typeof method !== 'function') {\n throw new TypeError('method must be a string or function');\n }\n\n let clusters = [];\n for (let i = 0; i < numLeaves; i++) {\n const cluster = new Cluster();\n cluster.isLeaf = true;\n cluster.index = i;\n clusters.push(cluster);\n }\n\n for (let n = 0; n < numLeaves - 1; n++) {\n const [row, column, distance] = getSmallestDistance(distanceMatrix);\n const cluster1 = clusters[row];\n const cluster2 = clusters[column];\n const newCluster = new Cluster();\n newCluster.size = cluster1.size + cluster2.size;\n newCluster.children.push(cluster1, cluster2);\n newCluster.height = distance;\n\n const newClusters = [newCluster];\n const newDistanceMatrix = new Matrix(\n distanceMatrix.rows - 1,\n distanceMatrix.rows - 1,\n );\n const previous = (newIndex) =>\n getPreviousIndex(newIndex, Math.min(row, column), Math.max(row, column));\n\n for (let i = 1; i < newDistanceMatrix.rows; i++) {\n const prevI = previous(i);\n const prevICluster = clusters[prevI];\n newClusters.push(prevICluster);\n for (let j = 0; j < i; j++) {\n if (j === 0) {\n const dKI = distanceMatrix.get(row, prevI);\n const dKJ = distanceMatrix.get(prevI, column);\n const val = updateFunc(\n dKI,\n dKJ,\n distance,\n cluster1.size,\n cluster2.size,\n prevICluster.size,\n );\n newDistanceMatrix.set(i, j, val);\n newDistanceMatrix.set(j, i, val);\n } else {\n // Just copy distance from previous matrix\n const val = distanceMatrix.get(prevI, previous(j));\n newDistanceMatrix.set(i, j, val);\n newDistanceMatrix.set(j, i, val);\n }\n }\n }\n\n clusters = newClusters;\n distanceMatrix = newDistanceMatrix;\n }\n\n return clusters[0];\n}\n\nfunction getSmallestDistance(distance) {\n let smallest = Infinity;\n let smallestI = 0;\n let smallestJ = 0;\n for (let i = 1; i < distance.rows; i++) {\n for (let j = 0; j < i; j++) {\n if (distance.get(i, j) < smallest) {\n smallest = distance.get(i, j);\n smallestI = i;\n smallestJ = j;\n }\n }\n }\n return [smallestI, smallestJ, smallest];\n}\n\nfunction getPreviousIndex(newIndex, prev1, prev2) {\n newIndex -= 1;\n if (newIndex >= prev1) newIndex++;\n if (newIndex >= prev2) newIndex++;\n return newIndex;\n}\n","export * from './agnes';\n// export * from './diana';\n// export * from './birch';\n// export * './cure';\n// export * from './chameleon';\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","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","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","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.rows;\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.getRow(firstCenterIdx));\n\n // Init closest distances\n let closestDistSquared = new Matrix(1, X.rows);\n for (let i = 0; i < X.rows; i++) {\n closestDistSquared.set(0, i, squaredEuclidean(X.getRow(i), centers[0]));\n }\n let cumSumClosestDistSquared = [cumSum(closestDistSquared.getRow(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.columns));\n const distanceToCandidates = euclideanDistances(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.getRow(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.getRow(bestCandidate);\n closestDistSquared = bestDistSquared;\n cumSumClosestDistSquared = [cumSum(closestDistSquared.getRow(0))];\n probabilities = Matrix.mul(\n closestDistSquared,\n 1 / cumSumClosestDistSquared[0][nSamples - 1]\n );\n }\n return centers;\n}\n\nfunction euclideanDistances(A, B) {\n const result = new Matrix(A.rows, B.rows);\n for (let i = 0; i < A.rows; i++) {\n for (let j = 0; j < B.rows; 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 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';\n\nimport { separateClasses } from './utils';\n\nexport class GaussianNB {\n /**\n * Constructor for the Gaussian Naive Bayes classifier, the parameters here is just for loading purposes.\n * @constructor\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);\n\n if (trainingSet.rows !== trainingLabels.length) {\n throw new RangeError(\n 'the size of the training set and the training labels must be the same.'\n );\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 = separatedClasses[i].mean('column');\n var std = separatedClasses[i].standardDeviation('column', {\n mean: means\n });\n\n var logPriorProbability = Math.log(\n separatedClasses[i].rows / trainingSet.rows\n );\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] = [\n 1 / (C1 * currentStd),\n -2 * currentStd * currentStd\n ];\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 dataset = Matrix.checkMatrix(dataset);\n if (dataset.rows === this.calculateProbabilities[0].length) {\n throw new RangeError(\n 'the dataset must have the same features as the training set'\n );\n }\n\n var predictions = new Array(dataset.rows);\n\n for (var i = 0; i < predictions.length; ++i) {\n predictions[i] = getCurrentClass(\n dataset.getRow(i),\n this.means,\n this.calculateProbabilities\n );\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(\n 'The current model is not a Multinomial Naive Bayes, current model:',\n model.name\n );\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(\n currentCase[j - 1],\n mean[i][j - 1],\n classes[i][j][0],\n classes[i][j][1]\n );\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';\n\nimport { separateClasses } from './utils';\n\nexport class MultinomialNB {\n /**\n * Constructor for Multinomial Naive Bayes, the model parameter is for load purposes.\n * @constructor\n * @param {object} model - for load purposes.\n */\n constructor(model) {\n if (model) {\n this.conditionalProbability = Matrix.checkMatrix(\n model.conditionalProbability\n );\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(\n 'the size of the training set and the training labels must be the same.'\n );\n }\n\n var separateClass = separateClasses(trainingSet, trainingLabels);\n\n this.priorProbability = new Matrix(separateClass.length, 1);\n\n for (var i = 0; i < separateClass.length; ++i) {\n this.priorProbability.set(i, 0, Math.log(\n separateClass[i].rows / trainingSet.rows\n ));\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(\n i,\n Matrix.rowVector(classValues\n .sum('column'))\n .add(1)\n .div(divisor)\n .apply(matrixLog)\n );\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 const v = Matrix.columnVector(this.conditionalProbability\n .clone()\n .mulRowVector(currentElement)\n .sum('row'));\n predictions[i] = v\n .add(this.priorProbability)\n .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.set(i, j, Math.log(this.get(i, j)));\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(function (e) {\n return -e[1];\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, linearDistance, otherChild, 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 (\n bestNodes.size() < maxNodes ||\n Math.abs(linearDistance) < bestNodes.peek()[1]\n ) {\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 {\n // 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 { euclidean as euclideanDistance } from 'ml-distance-euclidean';\n\nimport KDTree from './KDTree';\n\nexport default class KNN {\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 { distance = euclideanDistance, k = classes.size + 1 } = 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(\n 'a custom distance function was used to create the model. Please provide it again'\n );\n }\n if (model.isEuclidean && distance !== euclideanDistance) {\n throw new Error(\n 'the model was created with the default distance function. Do not load it with another one'\n );\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 (\n Array.isArray(dataset[0]) &&\n typeof dataset[0][0] === 'number'\n ) {\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","import Matrix from 'ml-matrix';\n\n/**\n * @private\n * Function that given vector, returns its norm\n * @param {Vector} X\n * @return {number} Norm of the vector\n */\nexport function norm(X) {\n return Math.sqrt(\n X.clone()\n .apply(pow2array)\n .sum(),\n );\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.set(i, j, this.get(i, j) ** 2);\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 let means = dataset.mean('column');\n let std = dataset.standardDeviation('column', {\n mean: means,\n unbiased: true,\n });\n let 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 (let i = 0; i < array.length; ++i) {\n for (let j = 0; j < array[i].length; ++j) {\n let elem = array[i][j];\n array[i][j] = elem !== null ? new Matrix(array[i][j]) : undefined;\n }\n }\n } else {\n for (let 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';\n\nimport * as Utils from './util/utils';\n\n/**\n * @class PLS\n */\nexport class PLS {\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 let { tolerance = 1e-5, scale = true } = 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(\n 'The number of X rows must be equal to the number of Y rows',\n );\n }\n\n this.meanX = trainingSet.mean('column');\n this.stdDevX = trainingSet.standardDeviation('column', {\n mean: this.meanX,\n unbiased: true,\n });\n this.meanY = trainingValues.mean('column');\n this.stdDevY = trainingValues.standardDeviation('column', {\n mean: this.meanY,\n unbiased: true,\n });\n\n if (this.scale) {\n trainingSet = trainingSet\n .clone()\n .subRowVector(this.meanX)\n .divRowVector(this.stdDevX);\n trainingValues = trainingValues\n .clone()\n .subRowVector(this.meanY)\n .divRowVector(this.stdDevY);\n }\n\n if (this.latentVectors === undefined) {\n this.latentVectors = Math.min(trainingSet.rows - 1, trainingSet.columns);\n }\n\n let rx = trainingSet.rows;\n let cx = trainingSet.columns;\n let ry = trainingValues.rows;\n let cy = trainingValues.columns;\n\n let ssqXcal = trainingSet\n .clone()\n .mul(trainingSet)\n .sum(); // for the r²\n let sumOfSquaresY = trainingValues\n .clone()\n .mul(trainingValues)\n .sum();\n\n let tolerance = this.tolerance;\n let n = this.latentVectors;\n let T = Matrix.zeros(rx, n);\n let P = Matrix.zeros(cx, n);\n let U = Matrix.zeros(ry, n);\n let Q = Matrix.zeros(cy, n);\n let B = Matrix.zeros(n, n);\n let W = P.clone();\n let k = 0;\n let t;\n let w;\n let q;\n let p;\n\n while (Utils.norm(trainingValues) > tolerance && k < n) {\n let transposeX = trainingSet.transpose();\n let transposeY = trainingValues.transpose();\n\n let tIndex = maxSumColIndex(trainingSet.clone().mul(trainingSet));\n let uIndex = maxSumColIndex(trainingValues.clone().mul(trainingValues));\n\n let t1 = trainingSet.getColumnVector(tIndex);\n let u = trainingValues.getColumnVector(uIndex);\n t = Matrix.zeros(rx, 1);\n\n while (Utils.norm(t1.clone().sub(t)) > tolerance) {\n w = transposeX.mmul(u);\n w.div(Utils.norm(w));\n t = t1;\n t1 = trainingSet.mmul(w);\n q = transposeY.mmul(t1);\n q.div(Utils.norm(q));\n u = trainingValues.mmul(q);\n }\n\n t = t1;\n let num = transposeX.mmul(t);\n let den = t\n .transpose()\n .mmul(t)\n .get(0, 0);\n p = num.div(den);\n let 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\n .transpose()\n .mmul(t)\n .get(0, 0);\n let b = num.div(den).get(0, 0);\n trainingSet.sub(t.mmul(p.transpose()));\n trainingValues.sub(\n t\n .clone()\n .mul(b)\n .mmul(q.transpose()),\n );\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.set(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 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\n .transpose()\n .mmul(t)\n .mmul(p.transpose().mmul(p))\n .div(ssqXcal)\n .get(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 let X = Matrix.checkMatrix(dataset);\n if (this.scale) {\n X = X.subRowVector(this.meanX).divRowVector(this.stdDevX);\n }\n let 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 Matrix.rowVector(data.sum('column')).maxIndex()[0];\n}\n","import { Matrix, SingularValueDecomposition, inverse } from 'ml-matrix';\n\nimport { initializeMatrices } from './util/utils';\n\n/**\n * @class KOPLS\n */\nexport class KOPLS {\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(\n model.TURegressionCoeff,\n false,\n );\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 let kernelX = this.kernel.compute(trainingSet);\n\n let Identity = Matrix.eye(kernelX.rows, kernelX.rows, 1);\n let temp = kernelX;\n kernelX = new Array(this.orthogonalComp + 1);\n for (let i = 0; i < this.orthogonalComp + 1; i++) {\n kernelX[i] = new Array(this.orthogonalComp + 1);\n }\n kernelX[0][0] = temp;\n\n let result = new SingularValueDecomposition(\n trainingValues\n .transpose()\n .mmul(kernelX[0][0])\n .mmul(trainingValues),\n {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: false,\n },\n );\n let YLoadingMat = result.leftSingularVectors;\n let Sigma = result.diagonalMatrix;\n\n YLoadingMat = YLoadingMat.subMatrix(\n 0,\n YLoadingMat.rows - 1,\n 0,\n this.predictiveComp - 1,\n );\n Sigma = Sigma.subMatrix(\n 0,\n this.predictiveComp - 1,\n 0,\n this.predictiveComp - 1,\n );\n\n let YScoreMat = trainingValues.mmul(YLoadingMat);\n\n let predScoreMat = new Array(this.orthogonalComp + 1);\n let TURegressionCoeff = new Array(this.orthogonalComp + 1);\n let YOrthScoreMat = new Array(this.orthogonalComp);\n let YOrthLoadingVec = new Array(this.orthogonalComp);\n let YOrthEigen = new Array(this.orthogonalComp);\n let YOrthScoreNorm = new Array(this.orthogonalComp);\n\n let SigmaPow = Matrix.pow(Sigma, -0.5);\n // to avoid errors, check infinity\n SigmaPow.apply(function(i, j) {\n if (this.get(i, j) === Infinity) {\n this.set(i, j, 0);\n }\n });\n\n for (let i = 0; i < this.orthogonalComp; ++i) {\n predScoreMat[i] = kernelX[0][i]\n .transpose()\n .mmul(YScoreMat)\n .mmul(SigmaPow);\n\n let TpiPrime = predScoreMat[i].transpose();\n TURegressionCoeff[i] = inverse(TpiPrime.mmul(predScoreMat[i]))\n .mmul(TpiPrime)\n .mmul(YScoreMat);\n\n result = new SingularValueDecomposition(\n TpiPrime.mmul(\n Matrix.sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime)),\n ).mmul(predScoreMat[i]),\n {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: false,\n },\n );\n let CoTemp = result.leftSingularVectors;\n let SoTemp = result.diagonalMatrix;\n\n YOrthLoadingVec[i] = CoTemp.subMatrix(0, CoTemp.rows - 1, 0, 0);\n YOrthEigen[i] = SoTemp.get(0, 0);\n\n YOrthScoreMat[i] = Matrix.sub(\n kernelX[i][i],\n predScoreMat[i].mmul(TpiPrime),\n )\n .mmul(predScoreMat[i])\n .mmul(YOrthLoadingVec[i])\n .mul(Math.pow(YOrthEigen[i], -0.5));\n\n let toiPrime = YOrthScoreMat[i].transpose();\n YOrthScoreNorm[i] = Matrix.sqrt(toiPrime.mmul(YOrthScoreMat[i]));\n\n YOrthScoreMat[i] = YOrthScoreMat[i].divRowVector(YOrthScoreNorm[i]);\n\n let ITo = Matrix.sub(\n Identity,\n YOrthScoreMat[i].mmul(YOrthScoreMat[i].transpose()),\n );\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 let lastScoreMat = (predScoreMat[this.orthogonalComp] = kernelX[0][\n this.orthogonalComp\n ]\n .transpose()\n .mmul(YScoreMat)\n .mmul(SigmaPow));\n\n let lastTpPrime = lastScoreMat.transpose();\n TURegressionCoeff[this.orthogonalComp] = inverse(\n lastTpPrime.mmul(lastScoreMat),\n )\n .mmul(lastTpPrime)\n .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 let KTestTrain = this.kernel.compute(toPredict, this.trainingSet);\n\n let temp = KTestTrain;\n KTestTrain = new Array(this.orthogonalComp + 1);\n for (let i = 0; i < this.orthogonalComp + 1; i++) {\n KTestTrain[i] = new Array(this.orthogonalComp + 1);\n }\n KTestTrain[0][0] = temp;\n\n let YOrthScoreVector = new Array(this.orthogonalComp);\n let predScoreMat = new Array(this.orthogonalComp);\n\n let i;\n for (i = 0; i < this.orthogonalComp; ++i) {\n predScoreMat[i] = KTestTrain[i][0]\n .mmul(this.YScoreMat)\n .mmul(this.SigmaPow);\n\n YOrthScoreVector[i] = Matrix.sub(\n KTestTrain[i][i],\n predScoreMat[i].mmul(this.predScoreMat[i].transpose()),\n )\n .mmul(this.predScoreMat[i])\n .mmul(this.YOrthLoadingVec[i])\n .mul(Math.pow(this.YOrthEigen[i], -0.5));\n\n YOrthScoreVector[i] = YOrthScoreVector[i].divRowVector(this.toNorm[i]);\n\n let scoreMatPrime = this.YOrthScoreMat[i].transpose();\n KTestTrain[i + 1][0] = Matrix.sub(\n KTestTrain[i][0],\n YOrthScoreVector[i]\n .mmul(scoreMatPrime)\n .mmul(this.kernelX[0][i].transpose()),\n );\n\n let p1 = Matrix.sub(\n KTestTrain[i][0],\n KTestTrain[i][i].mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime),\n );\n let p2 = YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[i][i]);\n let 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 let prediction = predScoreMat[i]\n .mmul(this.TURegressionCoeff[i])\n .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 * 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 */\nexport default class 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(\n 'Confusion matrix and labels should have the same length',\n );\n }\n this.labels = labels;\n this.matrix = matrix;\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 (let i = 0; i < this.matrix.length; i++) {\n for (let 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 let count = 0;\n for (let 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 let count = 0;\n for (let i = 0; i < this.matrix.length; i++) {\n for (let 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 let count = 0;\n for (let 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 let count = 0;\n for (let 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 (\n (2 * TP) /\n (2 * TP +\n this.getFalsePositiveCount(label) +\n this.getFalseNegativeCount(label))\n );\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 (\n (TP * TN - FP * FN) /\n Math.sqrt((TP + FP) * (TP + FN) * (TN + FP) * (TN + FN))\n );\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 (\n this.getTruePositiveRate(label) + this.getTrueNegativeRate(label) - 1\n );\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 (\n this.getPositivePredictiveValue(label) +\n this.getNegativePredictiveValue(label) -\n 1\n );\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 [this.getTruePositiveCount(label), this.getFalseNegativeCount(label)],\n [this.getFalsePositiveCount(label), this.getTrueNegativeCount(label)],\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 (let i = 0; i < this.matrix.length; i++) {\n for (let 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 * 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","(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 * get folds indexes\n * @param {Array} features\n * @param {Number} k - number of folds, a\n */\nexport function getFolds(features, k = 5) {\n let N = features.length;\n let allIdx = new Array(N);\n for (let i = 0; i < N; i++) {\n allIdx[i] = i;\n }\n\n let l = Math.floor(N / k);\n // create random k-folds\n let current = [];\n let folds = [];\n while (allIdx.length) {\n let 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 // we push the remaining to the last fold so that the total length is\n // preserved. Otherwise the Q2 will fail.\n if (current.length) current.forEach((e) => folds[k - 1].push(e));\n folds = folds.slice(0, k);\n\n let foldsIndex = folds.map((x, idx) => ({\n testIndex: x,\n trainIndex: [].concat(...folds.filter((el, idx2) => idx2 !== idx)),\n }));\n return foldsIndex;\n}\n","/**\n * A function to sample a dataset maintaining classes equilibrated\n * @param {Array} classVector - an array containing class or group information\n * @param {Number} fraction - a fraction of the class to sample\n * @return {Object} - an object with indexes\n */\n\nexport function sampleAClass(classVector, fraction) {\n // sort the vector\n let classVectorSorted = JSON.parse(JSON.stringify(classVector));\n let result = Array.from(Array(classVectorSorted.length).keys()).sort((a, b) =>\n classVectorSorted[a] < classVectorSorted[b]\n ? -1\n : (classVectorSorted[b] < classVectorSorted[a]) | 0,\n );\n classVectorSorted.sort((a, b) => (a < b ? -1 : (b < a) | 0));\n\n // counts the class elements\n let counts = {};\n classVectorSorted.forEach((x) => (counts[x] = (counts[x] || 0) + 1));\n\n // pick a few per class\n let indexOfSelected = [];\n\n Object.keys(counts).forEach((e, i) => {\n let shift = [];\n Object.values(counts).reduce((a, c, item) => (shift[item] = a + c), 0);\n\n let arr = [...Array(counts[e]).keys()];\n\n let r = [];\n for (let j = 0; j < Math.floor(counts[e] * fraction); j++) {\n let n = arr[Math.floor(Math.random() * arr.length)];\n r.push(n);\n let ind = arr.indexOf(n);\n arr.splice(ind, 1);\n }\n\n if (i === 0) {\n indexOfSelected = indexOfSelected.concat(r);\n } else {\n indexOfSelected = indexOfSelected.concat(r.map((x) => x + shift[i - 1]));\n }\n });\n\n // sort back the index\n let trainIndex = [];\n indexOfSelected.forEach((e) => trainIndex.push(result[e]));\n\n let testIndex = [];\n let mask = [];\n classVector.forEach((el, idx) => {\n if (trainIndex.includes(idx)) {\n mask.push(true);\n } else {\n mask.push(false);\n testIndex.push(idx);\n }\n });\n return { trainIndex, testIndex, mask };\n}\n","import ConfusionMatrix from 'ml-confusion-matrix';\nimport combinations from 'ml-combinations';\n\nimport { getFolds } from './getFolds.js';\n\nexport { sampleAClass } from './sampleAClass.js';\nexport { getFolds } from './getFolds.js';\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 */\n\nexport function leaveOneOut(Classifier, features, labels, classifierOptions) {\n if (typeof labels === 'function') {\n let callback = labels;\n labels = features;\n features = Classifier;\n return leavePOut(features, labels, 1, callback);\n }\n return leavePOut(Classifier, features, labels, classifierOptions, 1);\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 */\nexport function leavePOut(Classifier, features, labels, classifierOptions, p) {\n let callback;\n if (typeof classifierOptions === 'function') {\n 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 let N = features.length;\n let gen = combinations(p, N);\n let allIdx = new Array(N);\n for (let i = 0; i < N; i++) {\n allIdx[i] = i;\n }\n for (const testIdx of gen) {\n let 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(\n features,\n labels,\n testIdx,\n trainIdx,\n confusionMatrix,\n distinct,\n callback,\n );\n } else {\n validate(\n Classifier,\n features,\n labels,\n classifierOptions,\n testIdx,\n trainIdx,\n confusionMatrix,\n 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 */\nexport function kFold(Classifier, features, labels, classifierOptions, k) {\n let callback;\n if (typeof classifierOptions === 'function') {\n 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\n let folds = getFolds(features, k);\n\n for (let i = 0; i < folds.length; i++) {\n let testIdx = folds[i].testIndex;\n let trainIdx = folds[i].trainIndex;\n\n if (callback) {\n validateWithCallback(\n features,\n labels,\n testIdx,\n trainIdx,\n confusionMatrix,\n distinct,\n callback,\n );\n } else {\n validate(\n Classifier,\n features,\n labels,\n classifierOptions,\n testIdx,\n trainIdx,\n confusionMatrix,\n distinct,\n );\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 let 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(\n Classifier,\n features,\n labels,\n classifierOptions,\n testIdx,\n trainIdx,\n confusionMatrix,\n distinct,\n) {\n const { testFeatures, trainFeatures, testLabels, trainLabels } = getTrainTest(\n features,\n labels,\n testIdx,\n trainIdx,\n );\n\n let 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 let predictedLabels = classifier.predict(testFeatures);\n updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct);\n}\n\nfunction validateWithCallback(\n features,\n labels,\n testIdx,\n trainIdx,\n confusionMatrix,\n distinct,\n callback,\n) {\n const { testFeatures, trainFeatures, testLabels, trainLabels } = getTrainTest(\n features,\n labels,\n testIdx,\n trainIdx,\n );\n const predictedLabels = callback(trainFeatures, trainLabels, testFeatures);\n updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct);\n}\n\nfunction updateConfusionMatrix(\n confusionMatrix,\n testLabels,\n predictedLabels,\n distinct,\n) {\n for (let 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\nexport function 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","import Matrix from 'ml-matrix';\n\nimport { norm } from './util/utils.js';\n\n/**\n * OPLS loop\n * @param {Array} x a matrix with features\n * @param {Array} y an array of labels (dependent variable)\n * @param {Object} options an object with options\n * @return {Object} an object with model (filteredX: err,\n loadingsXOrtho: pOrtho,\n scoresXOrtho: tOrtho,\n weightsXOrtho: wOrtho,\n weightsPred: w,\n loadingsXpred: p,\n scoresXpred: t,\n loadingsY:)\n */\nexport function OPLSNipals(x, y, options = {}) {\n const { numberOSC = 100 } = options;\n\n let X = Matrix.checkMatrix(x);\n let Y = Matrix.checkMatrix(y);\n\n let u = Y.getColumnVector(0);\n\n let diff = 1;\n let t, c, w, uNew;\n for (let i = 0; i < numberOSC && diff > 1e-10; i++) {\n w = u\n .transpose()\n .mmul(X)\n .div(\n u\n .transpose()\n .mmul(u)\n .get(0, 0),\n );\n w = w.transpose().div(norm(w));\n\n t = X.mmul(w).div(\n w\n .transpose()\n .mmul(w)\n .get(0, 0),\n ); // t_h paso 3\n\n // calc loading\n c = t\n .transpose()\n .mmul(Y)\n .div(\n t\n .transpose()\n .mmul(t)\n .get(0, 0),\n );\n\n // calc new u and compare with one in previus iteration (stop criterion)\n uNew = Y.mmul(c.transpose());\n uNew = uNew.div(\n c\n .transpose()\n .mmul(c)\n .get(0, 0),\n );\n\n if (i > 0) {\n diff =\n uNew\n .clone()\n .sub(u)\n .pow(2)\n .sum() /\n uNew\n .clone()\n .pow(2)\n .sum();\n }\n\n u = uNew.clone();\n }\n\n // calc loadings\n let p = t\n .transpose()\n .mmul(X)\n .div(\n t\n .transpose()\n .mmul(t)\n .get(0, 0),\n );\n\n let wOrtho = p.clone().sub(\n w\n .transpose()\n .mmul(p.transpose())\n .div(\n w\n .transpose()\n .mmul(w)\n .get(0, 0),\n )\n .mmul(w.transpose()),\n );\n wOrtho.div(norm(wOrtho));\n\n // orthogonal scores\n let tOrtho = X.mmul(wOrtho.transpose()).div(\n wOrtho.mmul(wOrtho.transpose()).get(0, 0),\n );\n\n // orthogonal loadings\n let pOrtho = tOrtho\n .transpose()\n .mmul(X)\n .div(\n tOrtho\n .transpose()\n .mmul(tOrtho)\n .get(0, 0),\n );\n\n // filtered data\n let err = X.clone().sub(tOrtho.mmul(pOrtho));\n return {\n filteredX: err,\n weightsXOrtho: wOrtho,\n loadingsXOrtho: pOrtho,\n scoresXOrtho: tOrtho,\n weightsXPred: w,\n loadingsXpred: p,\n scoresXpred: t,\n loadingsY: c,\n };\n}\n","import { Matrix } from 'ml-matrix';\n\n/**\n * Get total sum of square\n * @param {Array} x an array\n * @return {Number} - the sum of the squares\n */\nexport function tss(x) {\n return Matrix.mul(x, x).sum();\n}\n","import { Matrix, NIPALS } from 'ml-matrix';\nimport ConfusionMatrix from 'ml-confusion-matrix';\nimport { getFolds } from 'ml-cross-validation';\n\nimport { OPLSNipals } from './OPLSNipals.js';\nimport { tss } from './util/tss.js';\n\n/**\n * Creates new OPLS (orthogonal partial latent structures) from features and labels.\n * @param {Matrix} data - matrix containing data (X).\n * @param {Array} labels - 1D Array containing metadata (Y).\n * @param {Object} [options]\n * @param {number} [options.nComp = 3] - number of latent structures computed.\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 * @param {Array} [options.cvFolds = []] - allows to provide folds as 2D array for testing purpose.\n * */\n\nexport class OPLS {\n constructor(data, labels, options = {}) {\n if (data === true) {\n const opls = options;\n this.center = opls.center;\n this.scale = opls.scale;\n this.means = opls.means;\n this.meansY = opls.meansY;\n this.stdevs = opls.stdevs;\n this.stdevs = opls.stdevsY;\n this.model = opls.model;\n this.tCV = opls.tCV;\n this.tOrthCV = opls.tOrthCV;\n this.yHatCV = opls.yHatCV;\n this.mode = opls.mode;\n return;\n }\n\n let features = data.clone();\n // set default values\n // cvFolds allows to define folds for testing purpose\n const { nComp = 3, center = true, scale = true, cvFolds = [] } = options;\n\n let group;\n if (typeof labels[0] === 'number') {\n // numeric labels: OPLS regression is used\n this.mode = 'regression';\n group = Matrix.from1DArray(labels.length, 1, labels);\n } else if (typeof labels[0] === 'string') {\n // non-numeric labels: OPLS-DA is used\n this.mode = 'discriminantAnalysis';\n group = labels;\n throw new Error('discriminant analysis is not yet supported');\n }\n\n // check types of features and labels\n if (features.constructor.name !== 'Matrix') {\n throw new TypeError('features must be of class Matrix');\n }\n // getting center and scale the features (all)\n this.center = center;\n if (this.center) {\n this.means = features.mean('column');\n this.meansY = group.mean('column');\n } else {\n this.stdevs = null;\n }\n this.scale = scale;\n if (this.scale) {\n this.stdevs = features.standardDeviation('column');\n this.stdevsY = group.standardDeviation('column');\n } else {\n this.means = null;\n }\n\n // check and remove for features with sd = 0 TODO here\n // check opls.R line 70\n\n let folds;\n if (cvFolds.length > 0) {\n folds = cvFolds;\n } else {\n folds = getFolds(labels, 5);\n }\n\n let Q2 = [];\n this.model = [];\n\n this.tCV = [];\n this.tOrthCV = [];\n this.yHatCV = [];\n let oplsCV = [];\n\n let modelNC = [];\n\n // this code could be made more efficient by reverting the order of the loops\n // this is a legacy loop to be consistent with R code from MetaboMate package\n // this allows for having statistic (R2) from CV to decide wether to continue\n // with more latent structures\n let nc;\n for (nc = 0; nc < nComp; nc++) {\n let yHatk = new Matrix(group.rows, 1);\n let tPredk = new Matrix(group.rows, 1);\n let tOrthk = new Matrix(group.rows, 1);\n let oplsk = [];\n\n let f = 0;\n for (let fold of folds) {\n let trainTest = this._getTrainTest(features, group, fold);\n let testXk = trainTest.testFeatures;\n let Xk = trainTest.trainFeatures;\n let Yk = trainTest.trainLabels;\n\n // determine center and scale of training set\n let dataCenter = Xk.mean('column');\n let dataSD = Xk.standardDeviation('column');\n\n // center and scale training set\n if (center) {\n Xk.center('column');\n Yk.center('column');\n }\n\n if (scale) {\n Xk.scale('column');\n Yk.scale('column');\n }\n\n // perform opls\n if (nc === 0) {\n oplsk[f] = OPLSNipals(Xk, Yk);\n } else {\n oplsk[f] = OPLSNipals(oplsCV[nc - 1][f].filteredX, Yk);\n }\n // store model for next component\n oplsCV[nc] = oplsk;\n\n let plsCV = new NIPALS(oplsk[f].filteredX, { Y: Yk });\n\n // scaling the test dataset with respect to the train\n testXk.center('column', { center: dataCenter });\n testXk.scale('column', { scale: dataSD });\n\n let Eh = testXk;\n // removing the orthogonal components from PLS\n let scores;\n for (let idx = 0; idx < nc + 1; idx++) {\n scores = Eh.mmul(oplsCV[idx][f].weightsXOrtho.transpose()); // ok\n Eh.sub(scores.mmul(oplsCV[idx][f].loadingsXOrtho));\n }\n\n // prediction\n let tPred = Eh.mmul(plsCV.w.transpose());\n // this should be summed over ncomp (pls_prediction.R line 23)\n let yHat = tPred.mmul(plsCV.betas); // ok\n\n // adding all prediction from all folds\n for (let i = 0; i < fold.testIndex.length; i++) {\n yHatk.setRow(fold.testIndex[i], [yHat.get(i, 0)]);\n tPredk.setRow(fold.testIndex[i], [tPred.get(i, 0)]);\n tOrthk.setRow(fold.testIndex[i], [scores.get(i, 0)]);\n }\n f++;\n } // end of loop over folds\n\n this.tCV.push(tPredk);\n this.tOrthCV.push(tOrthk);\n this.yHatCV.push(yHatk);\n\n // calculate Q2y for all the prediction (all folds)\n // ROC for DA is not implemented (check opls.R line 183) TODO\n if (this.mode === 'regression') {\n let tssy = tss(group.center('column').scale('column'));\n let press = tss(group.clone().sub(yHatk));\n let Q2y = 1 - press / tssy;\n Q2.push(Q2y);\n } else if (this.mode === 'discriminantAnalysis') {\n throw new Error('discriminant analysis is not yet supported');\n }\n\n // calculate the R2y for the complete data\n if (nc === 0) {\n modelNC = this._predictAll(features, group);\n } else {\n modelNC = this._predictAll(\n modelNC.xRes,\n group,\n (options = { scale: false, center: false }),\n );\n }\n\n // adding the predictive statistics from CV\n modelNC.Q2y = Q2;\n // store the model for each component\n this.model.push(modelNC);\n // console.warn(`OPLS iteration over # of Components: ${nc + 1}`);\n } // end of loop over nc\n\n // store scores from CV\n let tCV = this.tCV;\n let tOrthCV = this.tOrthCV;\n\n let m = this.model[nc - 1];\n let XOrth = m.XOrth;\n let FeaturesCS = features.center('column').scale('column');\n let labelsCS = group.center('column').scale('column');\n let Xres = FeaturesCS.clone().sub(XOrth);\n let plsCall = new NIPALS(Xres, { Y: labelsCS });\n let E = Xres.clone().sub(plsCall.t.mmul(plsCall.p));\n\n let R2x = this.model.map((x) => x.R2x);\n let R2y = this.model.map((x) => x.R2y);\n\n this.output = {\n Q2y: Q2,\n R2x,\n R2y,\n tPred: m.plsC.t,\n pPred: m.plsC.p,\n wPred: m.plsC.w,\n betasPred: m.plsC.betas,\n Qpc: m.plsC.q,\n tCV,\n tOrthCV,\n tOrth: m.tOrth,\n pOrth: m.pOrth,\n wOrth: m.wOrth,\n XOrth,\n yHat: m.totalPred,\n Yres: m.plsC.yResidual,\n E,\n };\n }\n\n /**\n * get access to all the computed elements\n * Mainly for debug and testing\n * @return {Object} output object\n */\n getLogs() {\n return this.output;\n }\n\n getScores() {\n let scoresX = this.tCV.map((x) => x.to1DArray());\n let scoresY = this.tOrthCV.map((x) => x.to1DArray());\n return { scoresX, scoresY };\n }\n\n /**\n * Load an OPLS model from JSON\n * @param {Object} model\n * @return {OPLS}\n */\n static load(model) {\n if (typeof model.name !== 'string') {\n throw new TypeError('model must have a name property');\n }\n if (model.name !== 'OPLS') {\n throw new RangeError(`invalid model: ${model.name}`);\n }\n return new OPLS(true, [], model);\n }\n\n /**\n * Export the current model to a JSON object\n * @return {Object} model\n */\n toJSON() {\n return {\n name: 'OPLS',\n center: this.center,\n scale: this.scale,\n means: this.means,\n stdevs: this.stdevs,\n model: this.model,\n tCV: this.tCV,\n tOrthCV: this.tOrthCV,\n yHatCV: this.yHatCV,\n };\n }\n\n /**\n * Predict scores for new data\n * @param {Matrix} features - a matrix containing new data\n * @param {Object} [options]\n * @param {Array} [options.trueLabel] - an array with true values to compute confusion matrix\n * @param {Number} [options.nc] - the number of components to be used\n * @return {Object} - predictions\n */\n predict(newData, options = {}) {\n let { trueLabels = [], nc = 1 } = options;\n let labels = [];\n if (trueLabels.length > 0) {\n trueLabels = Matrix.from1DArray(trueLabels.length, 1, trueLabels);\n labels = trueLabels.clone();\n }\n\n let features = newData.clone();\n\n // scaling the test dataset with respect to the train\n if (this.center) {\n features.center('column', { center: this.means });\n if (labels.rows > 0 && this.mode === 'regression') {\n labels.center('column', { center: this.meansY });\n }\n }\n if (this.scale) {\n features.scale('column', { scale: this.stdevs });\n if (labels.rows > 0 && this.mode === 'regression') {\n labels.scale('column', { scale: this.stdevsY });\n }\n }\n\n let Eh = features.clone();\n // removing the orthogonal components from PLS\n let tOrth;\n let wOrth;\n let pOrth;\n let yHat;\n let tPred;\n\n for (let idx = 0; idx < nc; idx++) {\n wOrth = this.model[idx].wOrth.transpose();\n pOrth = this.model[idx].pOrth;\n tOrth = Eh.mmul(wOrth);\n Eh.sub(tOrth.mmul(pOrth));\n // prediction\n tPred = Eh.mmul(this.model[idx].plsC.w.transpose());\n // this should be summed over ncomp (pls_prediction.R line 23)\n yHat = tPred.mmul(this.model[idx].plsC.betas);\n }\n\n if (labels.rows > 0) {\n if (this.mode === 'regression') {\n let tssy = tss(labels);\n let press = tss(labels.clone().sub(yHat));\n let Q2y = 1 - press / tssy;\n\n return { tPred, tOrth, yHat, Q2y };\n } else if (this.mode === 'discriminantAnalysis') {\n let confusionMatrix = [];\n confusionMatrix = ConfusionMatrix.fromLabels(\n trueLabels.to1DArray(),\n yHat.to1DArray(),\n );\n\n return { tPred, tOrth, yHat, confusionMatrix };\n }\n } else {\n return { tPred, tOrth, yHat };\n }\n }\n\n _predictAll(features, labels, options = {}) {\n // cannot use the global this.center here\n // since it is used in the NC loop and\n // centering and scaling should only be\n // performed once\n const { center = true, scale = true } = options;\n\n if (center) {\n features.center('column');\n labels.center('column');\n }\n\n if (scale) {\n features.scale('column');\n labels.scale('column');\n // reevaluate tssy and tssx after scaling\n // must be global because re-used for next nc iteration\n // tssx is only evaluate the first time\n this.tssy = tss(labels);\n this.tssx = tss(features);\n }\n\n let oplsC = OPLSNipals(features, labels);\n let plsC = new NIPALS(oplsC.filteredX, { Y: labels });\n\n let tPred = oplsC.filteredX.mmul(plsC.w.transpose());\n let yHat = tPred.mmul(plsC.betas);\n\n let rss = tss(labels.clone().sub(yHat));\n let R2y = 1 - rss / this.tssy;\n\n let xEx = plsC.t.mmul(plsC.p);\n let rssx = tss(xEx);\n let R2x = rssx / this.tssx;\n\n return {\n R2y,\n R2x,\n xRes: oplsC.filteredX,\n tOrth: oplsC.scoresXOrtho,\n pOrth: oplsC.loadingsXOrtho,\n wOrth: oplsC.weightsXOrtho,\n tPred: tPred,\n totalPred: yHat,\n XOrth: oplsC.scoresXOrtho.mmul(oplsC.loadingsXOrtho),\n oplsC,\n plsC,\n };\n }\n /**\n *\n * @param {*} X - dataset matrix object\n * @param {*} group - labels matrix object\n * @param {*} index - train and test index (output from getFold())\n */\n _getTrainTest(X, group, index) {\n let testFeatures = new Matrix(index.testIndex.length, X.columns);\n let testLabels = new Matrix(index.testIndex.length, 1);\n index.testIndex.forEach((el, idx) => {\n testFeatures.setRow(idx, X.getRow(el));\n testLabels.setRow(idx, group.getRow(el));\n });\n\n let trainFeatures = new Matrix(index.trainIndex.length, X.columns);\n let trainLabels = new Matrix(index.trainIndex.length, 1);\n index.trainIndex.forEach((el, idx) => {\n trainFeatures.setRow(idx, X.getRow(el));\n trainLabels.setRow(idx, group.getRow(el));\n });\n\n return {\n trainFeatures,\n testFeatures,\n trainLabels,\n testLabels,\n };\n }\n}\n","'use strict';\n\nvar mlMatrix = require('ml-matrix');\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\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.set(i, j, actFunction(this.get(i, j)));\n };\n this.derivate = function (i, j) {\n this.set(i, j, derFunction(this.get(i, j)));\n };\n\n if (options.model) {\n // load model\n this.W = mlMatrix.Matrix.checkMatrix(options.W);\n this.b = mlMatrix.Matrix.checkMatrix(options.b);\n } else {\n // default constructor\n this.W = mlMatrix.Matrix.rand(this.inputSize, this.outputSize);\n this.b = mlMatrix.Matrix.zeros(1, this.outputSize);\n\n this.W.apply(function (i, j) {\n this.set(i, j, this.get(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.transpose().mmul(delta);\n this.db = mlMatrix.Matrix.rowVector(delta.sum('column'));\n\n var aCopy = a.clone();\n return delta.mmul(this.W.transpose()).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\nclass OutputLayer extends Layer {\n constructor(options) {\n super(options);\n\n this.activationFunction = function (i, j) {\n this.set(i, j, Math.exp(this.get(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\nclass FeedForwardNeuralNetworks {\n /**\n * Create a new Feedforward 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 = mlMatrix.Matrix.checkMatrix(features);\n this.dicts = dictOutputs(labels);\n\n var inputSize = features.columns;\n var outputSize = Object.keys(this.dicts.inputs).length;\n\n if (!this.model) {\n this.buildNetwork(inputSize, outputSize);\n }\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 input = this.model[i].forward(input);\n }\n\n // get probabilities\n return input.divColumnVector(input.sum('row'));\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.rows; ++i) {\n probabilities.set(i, this.dicts.inputs[labels[i]], probabilities.get(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 = mlMatrix.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\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 = FeedForwardNeuralNetworks;\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;","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 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;","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 = [];\n for (let i = 0; i < x.length; i++) {\n y.push(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 (n * xY - xSum * ySum) /\n 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: Math.sqrt(rmsd / n)\n };\n }\n}\n","import BaseRegression, {\n checkArrayLength,\n maybeToPrecision\n} from 'ml-regression-base';\nimport { Matrix, MatrixTransposeView, 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 =\n `${maybeToPrecision(this.coefficients[k], precision) + times}x`;\n } else {\n str =\n `${maybeToPrecision(this.coefficients[k], precision) +\n times\n }x${\n sup\n }${this.powers[k]\n }${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.set(i, k, 1);\n } else {\n F.set(i, k, Math.pow(x[i], powers[k]));\n }\n }\n }\n\n const FT = new MatrixTransposeView(F);\n const A = FT.mmul(F);\n const B = FT.mmul(new MatrixTransposeView(Y));\n\n pr.degree = degree - 1;\n pr.powers = powers;\n pr.coefficients = solve(A, B).to1DArray();\n}\n","import BaseRegression, {\n checkArrayLength,\n maybeToPrecision\n} 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 !== 0) {\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, {\n checkArrayLength,\n maybeToPrecision\n} 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 (\n `f(x) = ${\n maybeToPrecision(this.B, precision)\n } * e^(${\n maybeToPrecision(this.A, precision)\n } * x)`\n );\n }\n\n toLaTeX(precision) {\n if (this.A >= 0) {\n return (\n `f(x) = ${\n maybeToPrecision(this.B, precision)\n }e^{${\n maybeToPrecision(this.A, precision)\n }x}`\n );\n } else {\n return (\n `f(x) = \\\\frac{${\n maybeToPrecision(this.B, precision)\n }}{e^{${\n maybeToPrecision(-this.A, precision)\n }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, {\n checkArrayLength,\n maybeToPrecision\n} 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) {\n // 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(\n this.A,\n precision\n )} * x^${maybeToPrecision(this.B, precision)}`;\n }\n\n toLaTeX(precision) {\n let latex = '';\n if (this.B >= 0) {\n latex = `f(x) = ${maybeToPrecision(\n this.A,\n precision\n )}x^{${maybeToPrecision(this.B, precision)}}`;\n } else {\n latex = `f(x) = \\\\frac{${maybeToPrecision(\n this.A,\n precision\n )}}{x^{${maybeToPrecision(-this.B, precision)}}}`;\n }\n latex = latex.replace(/e([+-]?[0-9]+)/g, 'e^{$1}');\n return latex;\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, pseudoInverse } from 'ml-matrix';\n\nexport default class MultivariateLinearRegression {\n constructor(x, y, options = {}) {\n const { intercept = true, statistics = true } = options;\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 y = new Matrix(y);\n if (intercept) {\n x.addColumn(new Array(x.rows).fill(1));\n }\n let xt = x.transpose();\n const xx = xt\n .mmul(x);\n const xy = xt\n .mmul(y);\n const invxx = new SVD(xx)\n .inverse();\n const beta = xy\n .transpose()\n .mmul(invxx)\n .transpose();\n this.weights = beta.to2DArray();\n this.inputs = x.columns;\n this.outputs = y.columns;\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 = y.clone().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.rows - x.columns);\n this.stdError = Math.sqrt(variance);\n this.stdErrorMatrix = pseudoInverse(xx).mul(variance);\n this.stdErrors = this.stdErrorMatrix\n .diagonal()\n .map((d) => Math.sqrt(d));\n this.tStats = this.weights.map((d, i) =>\n (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 } else if (Matrix.isMatrix(x)) {\n const y = new Matrix(x.rows, this.outputs);\n for (let i = 0; i < x.rows; i++) {\n y.setRow(i, this._predict(x.getRow(i)));\n }\n return y;\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","'use strict';\n\nconst { squaredEuclidean } = require('ml-distance-euclidean');\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 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 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 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(\n Math.exp(\n -this.sigma *\n Math.pow(Math.pow(x[i - 1], i) - Math.pow(y[i - 1], i), 2)\n ),\n this.degree\n );\n }\n return sum;\n }\n}\n\nmodule.exports = ANOVAKernel;\n","'use strict';\n\nconst { squaredEuclidean } = require('ml-distance-euclidean');\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');\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');\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 { Matrix, MatrixTransposeView } = require('ml-matrix');\nconst GaussianKernel = require('ml-kernel-gaussian');\nconst PolynomialKernel = require('ml-kernel-polynomial');\nconst SigmoidKernel = require('ml-kernel-sigmoid');\n\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');\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(\n 'first argument must be a valid kernel type or instance'\n );\n }\n }\n\n compute(inputs, landmarks) {\n inputs = Matrix.checkMatrix(inputs);\n if (landmarks === undefined) {\n landmarks = inputs;\n } else {\n landmarks = Matrix.checkMatrix(landmarks);\n }\n if (this.kernelType === 'linear') {\n return inputs.mmul(new MatrixTransposeView(landmarks));\n }\n\n const kernelMatrix = new Matrix(inputs.rows, landmarks.rows);\n if (inputs === landmarks) {\n // fast path, matrix is symmetric\n for (let i = 0; i < inputs.rows; i++) {\n for (let j = i; j < inputs.rows; j++) {\n const value = this.kernelFunction.compute(\n inputs.getRow(i),\n inputs.getRow(j)\n );\n kernelMatrix.set(i, j, value);\n kernelMatrix.set(j, i, value);\n }\n }\n } else {\n for (let i = 0; i < inputs.rows; i++) {\n for (let j = 0; j < landmarks.rows; j++) {\n kernelMatrix.set(\n i,\n j,\n this.kernelFunction.compute(inputs.getRow(i), landmarks.getRow(j))\n );\n }\n }\n }\n return kernelMatrix;\n }\n}\n\nmodule.exports = Kernel;\n","import BaseRegression, {\n checkArrayLength,\n maybeToPrecision\n} from 'ml-regression-base';\nimport median from 'ml-array-median';\n\nexport default class TheilSenRegression extends BaseRegression {\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 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 +=\n ` ${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, {\n checkArrayLength,\n maybeToPrecision\n} from 'ml-regression-base';\nimport { solve } from 'ml-matrix';\n\n/**\n * @class RobustPolynomialRegression\n * @param {Array} x\n * @param {Array} y\n * @param {number} degree - polynomial degree\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 /**\n * Display the formula\n * @param {number} precision - precision for the numbers\n * @return {string}\n */\n toString(precision) {\n return this._toFormula(precision, false);\n }\n\n /**\n * Display the formula in LaTeX format\n * @param {number} precision - precision for the numbers\n * @return {string}\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) +\n times}x`;\n } else {\n str = `${maybeToPrecision(this.coefficients[k], precision) +\n 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 = Array(degree)\n .fill(0)\n .map((_, index) => index);\n\n const tuples = getRandomTuples(x, y, degree);\n\n var min;\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 {\n x: x[i],\n y: y[i]\n }\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 return l % 2 === 0 ? residuals[half - 1] : residuals[half];\n}\n","const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\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 */\nexport default function errorCalculation(\n data,\n parameters,\n parameterizedFunction,\n) {\n let error = 0;\n const func = parameterizedFunction(parameters);\n\n for (let 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 let ans = new Array(n);\n\n for (let param = 0; param < n; param++) {\n ans[param] = new Array(m);\n let auxParams = params.slice();\n auxParams[param] += gradientDifference;\n let funcParam = paramFunction(auxParams);\n\n for (let 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 let ans = new Array(m);\n\n for (let 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 let value = damping * gradientDifference * gradientDifference;\n let identity = Matrix.eye(params.length, params.length, value);\n\n const func = parameterizedFunction(params);\n\n let evaluatedData = new Float64Array(data.x.length);\n for (let i = 0; i < data.x.length; i++) {\n evaluatedData[i] = func(data.x[i]);\n }\n\n let gradientFunc = gradientFunction(\n data,\n evaluatedData,\n params,\n gradientDifference,\n parameterizedFunction,\n );\n let matrixFunc = matrixFunction(data, evaluatedData);\n let 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 isArray from 'is-any-array';\n\nimport 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 !isArray(data.x) ||\n data.x.length < 2 ||\n !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 let 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 (!isArray(parameters)) {\n throw new Error('initialValues must be an array');\n }\n\n let error = errorCalculation(data, parameters, parameterizedFunction);\n\n let converged = error <= errorTolerance;\n\n let iteration;\n for (iteration = 0; iteration < maxIterations && !converged; iteration++) {\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","/**\n * Returns a new array based on extraction of specific indices of an array\n * @private\n * @param {Array} vector\n * @param {Array} indices\n */\nexport default function selection(vector, indices) {\n let u = []; //new Float64Array(indices.length);\n for (let i = 0; i < indices.length; i++) {\n u[i] = vector[indices[i]];\n }\n return u;\n}\n","/**\n *\n * @private\n * @param {Array of arrays} collection\n */\nexport default function sortCollectionSet(collection) {\n let objectCollection = collection\n .map((value, index) => {\n let key = BigInt(0);\n value.forEach((item) => (key |= BigInt(1) << BigInt(item)));\n return { value, index, key };\n })\n .sort((a, b) => {\n if (a.key - b.key < 0) return -1;\n return 1;\n });\n\n let sorted = [];\n let indices = [];\n\n let key;\n for (let set of objectCollection) {\n if (set.key !== key) {\n key = set.key;\n indices.push([]);\n sorted.push(set.value);\n }\n indices[indices.length - 1].push(set.index);\n }\n\n let result = {\n values: sorted,\n indices: indices,\n };\n return result;\n}\n","import {\n Matrix,\n LuDecomposition,\n solve,\n CholeskyDecomposition,\n} from 'ml-matrix';\n\nimport sortCollectionSet from './util/sortCollectionSet';\n\n/**\n * (Combinatorial Subspace Least Squares) - subfunction for the FC-NNLS\n * @private\n * @param {Matrix} XtX\n * @param {Matrix} XtY\n * @param {Array} Pset\n * @param {Numbers} l\n * @param {Numbers} p\n */\nexport default function cssls(XtX, XtY, Pset, l, p) {\n // Solves the set of equation XtX*K = XtY for the variables in Pset\n // if XtX (or XtX(vars,vars)) is singular, performs the svd and find pseudoinverse, otherwise (even if ill-conditioned) finds inverse with LU decomposition and solves the set of equation\n // it is consistent with matlab results for ill-conditioned matrices (at least consistent with test 'ill-conditionned square X rank 2, Y 3x1' in cssls.test)\n\n let K = Matrix.zeros(l, p);\n if (Pset === null) {\n let choXtX = new CholeskyDecomposition(XtX);\n if (choXtX.isPositiveDefinite() === true) {\n K = choXtX.solve(XtY);\n } else {\n let luXtX = new LuDecomposition(XtX);\n if (luXtX.isSingular() === false) {\n K = luXtX.solve(Matrix.eye(l)).mmul(XtY);\n } else {\n K = solve(XtX, XtY, { useSVD: true });\n }\n }\n } else {\n let sortedPset = sortCollectionSet(Pset).values;\n let sortedEset = sortCollectionSet(Pset).indices;\n if (\n sortedPset.length === 1 &&\n sortedPset[0].length === 0 &&\n sortedEset[0].length === p\n ) {\n return K;\n } else if (\n sortedPset.length === 1 &&\n sortedPset[0].length === l &&\n sortedEset[0].length === p\n ) {\n let choXtX = new CholeskyDecomposition(XtX);\n if (choXtX.isPositiveDefinite() === true) {\n K = choXtX.solve(XtY);\n } else {\n let luXtX = new LuDecomposition(XtX);\n if (luXtX.isSingular() === false) {\n K = luXtX.solve(Matrix.eye(l)).mmul(XtY);\n } else {\n K = solve(XtX, XtY, { useSVD: true });\n }\n }\n } else {\n for (let k = 0; k < sortedPset.length; k++) {\n let cols2Solve = sortedEset[k];\n let vars = sortedPset[k];\n let L;\n let choXtX = new CholeskyDecomposition(XtX.selection(vars, vars));\n if (choXtX.isPositiveDefinite() === true) {\n L = choXtX.solve(XtY.selection(vars, cols2Solve));\n } else {\n let luXtX = new LuDecomposition(XtX.selection(vars, vars));\n if (luXtX.isSingular() === false) {\n L = luXtX\n .solve(Matrix.eye(vars.length))\n .mmul(XtY.selection(vars, cols2Solve));\n } else {\n L = solve(\n XtX.selection(vars, vars),\n XtY.selection(vars, cols2Solve),\n { useSVD: true },\n );\n }\n }\n for (let i = 0; i < L.rows; i++) {\n for (let j = 0; j < L.columns; j++) {\n K.set(vars[i], cols2Solve[j], L.get(i, j));\n }\n }\n }\n }\n }\n return K;\n}\n","import { Matrix } from 'ml-matrix';\n\nimport cssls from './cssls';\n\nexport default function initialisation(X, Y) {\n let n = X.rows;\n let l = X.columns;\n let p = Y.columns;\n let iter = 0;\n\n if (Y.rows !== n) throw new Error('ERROR: matrix size not compatible');\n\n let W = Matrix.zeros(l, p);\n\n // precomputes part of pseudoinverse\n let XtX = X.transpose().mmul(X);\n let XtY = X.transpose().mmul(Y);\n\n let K = cssls(XtX, XtY, null, l, p); // K is lxp\n let Pset = [];\n for (let j = 0; j < p; j++) {\n Pset[j] = [];\n for (let i = 0; i < l; i++) {\n if (K.get(i, j) > 0) {\n Pset[j].push(i);\n } else {\n K.set(i, j, 0);\n } //This is our initial solution, it's the solution found by overwriting the unconstrained least square solution\n }\n }\n let Fset = [];\n for (let j = 0; j < p; j++) {\n if (Pset[j].length !== l) {\n Fset.push(j);\n }\n }\n\n let D = K.clone();\n\n return { n, l, p, iter, W, XtX, XtY, K, Pset, Fset, D };\n}\n","/**\n * Computes the set difference A\\B\n * @private\n * @param {A} set A as an array\n * @param {B} set B as an array\n */\nexport default function setDifference(A, B) {\n let C = [];\n for (let i of A) {\n if (!B.includes(i)) C.push(i);\n }\n return C;\n}\n","import setDifference from './util/setDifference';\n\n// Makes sure the solution has converged\nexport default function optimality(\n iter,\n maxIter,\n XtX,\n XtY,\n Fset,\n Pset,\n W,\n K,\n l,\n p,\n D,\n) {\n if (iter === maxIter) {\n throw new Error('Maximum number of iterations exceeded');\n }\n\n // Check solution for optimality\n let V = XtY.subMatrixColumn(Fset).subtract(XtX.mmul(K.subMatrixColumn(Fset)));\n for (let j = 0; j < Fset.length; j++) {\n W.setColumn(Fset[j], V.subMatrixColumn([j]));\n }\n let Jset = [];\n let fullSet = [];\n for (let i = 0; i < l; i++) {\n fullSet.push(i);\n }\n for (let j = 0; j < Fset.length; j++) {\n let notPset = setDifference(fullSet, Pset[Fset[j]]);\n if (notPset.length === 0) {\n Jset.push(Fset[j]);\n } else if (W.selection(notPset, [Fset[j]]).max() <= 0) {\n Jset.push(Fset[j]);\n }\n }\n Fset = setDifference(Fset, Jset);\n\n // For non-optimal solutions, add the appropriate variables to Pset\n if (Fset.length !== 0) {\n for (let j = 0; j < Fset.length; j++) {\n for (let i = 0; i < l; i++) {\n if (Pset[Fset[j]].includes(i)) W.set(i, Fset[j], -Infinity);\n }\n Pset[Fset[j]].push(W.subMatrixColumn(Fset).maxColumnIndex(j)[0]);\n }\n for (let j = 0; j < Fset.length; j++) {\n D.setColumn(Fset[j], K.getColumn(Fset[j]));\n }\n }\n for (let j = 0; j < p; j++) {\n Pset[j].sort((a, b) => a - b);\n }\n return { Pset, Fset, W };\n}\n","import { Matrix } from 'ml-matrix';\n\nimport selection from './util/selection';\nimport cssls from './cssls';\nimport initialisation from './initialisation';\nimport optimality from './optimality';\n\n/**\n * Fast Combinatorial Non-negative Least Squares with multiple Right Hand Side\n * @param {Matrix|number[][]} X\n * @param {Matrix|number[][]} Y\n * @param {object} [options={}]\n * @param {number} [options.maxIterations] if empty maxIterations is set at 3 times the number of columns of X\n * @returns {Matrix} K\n */\nexport default function fcnnls(X, Y, options = {}) {\n X = Matrix.checkMatrix(X);\n Y = Matrix.checkMatrix(Y);\n let { l, p, iter, W, XtX, XtY, K, Pset, Fset, D } = initialisation(X, Y);\n const { maxIterations = X.columns * 3 } = options;\n\n // Active set algorithm for NNLS main loop\n while (Fset.length > 0) {\n // Solves for the passive variables (uses subroutine below)\n let L = cssls(\n XtX,\n XtY.subMatrixColumn(Fset),\n selection(Pset, Fset),\n l,\n Fset.length,\n );\n for (let i = 0; i < l; i++) {\n for (let j = 0; j < Fset.length; j++) {\n K.set(i, Fset[j], L.get(i, j));\n }\n }\n\n // Finds any infeasible solutions\n let infeasIndex = [];\n for (let j = 0; j < Fset.length; j++) {\n for (let i = 0; i < l; i++) {\n if (L.get(i, j) < 0) {\n infeasIndex.push(j);\n break;\n }\n }\n }\n let Hset = selection(Fset, infeasIndex);\n\n // Makes infeasible solutions feasible (standard NNLS inner loop)\n if (Hset.length > 0) {\n let m = Hset.length;\n let alpha = Matrix.ones(l, m);\n\n while (m > 0 && iter < maxIterations) {\n iter++;\n\n alpha.mul(Infinity);\n\n // Finds indices of negative variables in passive set\n let hRowColIdx = [[], []]; // Indexes work in pairs, each pair reprensents a single element, first array is row index, second array is column index\n let negRowColIdx = [[], []]; // Same as before\n for (let j = 0; j < m; j++) {\n for (let i = 0; i < Pset[Hset[j]].length; i++) {\n if (K.get(Pset[Hset[j]][i], Hset[j]) < 0) {\n hRowColIdx[0].push(Pset[Hset[j]][i]); // i\n hRowColIdx[1].push(j);\n negRowColIdx[0].push(Pset[Hset[j]][i]); // i\n negRowColIdx[1].push(Hset[j]);\n } // Compared to matlab, here we keep the row/column indexing (we are not taking the linear indexing)\n }\n }\n\n for (let k = 0; k < hRowColIdx[0].length; k++) {\n // could be hRowColIdx[1].length as well\n alpha.set(\n hRowColIdx[0][k],\n hRowColIdx[1][k],\n D.get(negRowColIdx[0][k], negRowColIdx[1][k]) /\n (D.get(negRowColIdx[0][k], negRowColIdx[1][k]) -\n K.get(negRowColIdx[0][k], negRowColIdx[1][k])),\n );\n }\n\n let alphaMin = [];\n let minIdx = [];\n for (let j = 0; j < m; j++) {\n alphaMin[j] = alpha.minColumn(j);\n minIdx[j] = alpha.minColumnIndex(j)[0];\n }\n\n alphaMin = Matrix.rowVector(alphaMin);\n for (let i = 0; i < l; i++) {\n alpha.setSubMatrix(alphaMin, i, 0);\n }\n\n let E = new Matrix(l, m);\n E = D.subMatrixColumn(Hset).subtract(\n alpha\n .subMatrix(0, l - 1, 0, m - 1)\n .mul(D.subMatrixColumn(Hset).subtract(K.subMatrixColumn(Hset))),\n );\n for (let j = 0; j < m; j++) {\n D.setColumn(Hset[j], E.subMatrixColumn([j]));\n }\n\n let idx2zero = [minIdx, Hset];\n for (let k = 0; k < m; k++) {\n D.set(idx2zero[0][k], idx2zero[1][k], 0);\n }\n\n for (let j = 0; j < m; j++) {\n Pset[Hset[j]].splice(\n Pset[Hset[j]].findIndex((item) => item === minIdx[j]),\n 1,\n );\n }\n\n L = cssls(XtX, XtY.subMatrixColumn(Hset), selection(Pset, Hset), l, m);\n for (let j = 0; j < m; j++) {\n K.setColumn(Hset[j], L.subMatrixColumn([j]));\n }\n\n Hset = [];\n for (let j = 0; j < K.columns; j++) {\n for (let i = 0; i < l; i++) {\n if (K.get(i, j) < 0) {\n Hset.push(j);\n\n break;\n }\n }\n }\n m = Hset.length;\n }\n }\n\n let newParam = optimality(\n iter,\n maxIterations,\n XtX,\n XtY,\n Fset,\n Pset,\n W,\n K,\n l,\n p,\n D,\n );\n Pset = newParam.Pset;\n Fset = newParam.Fset;\n W = newParam.W;\n }\n\n return K;\n}\n","import { Matrix } from 'ml-matrix';\n\nimport fcnnls from './fcnnls';\n\n/**\n * Fast Combinatorial Non-negative Least Squares with single Right Hand Side\n * @param {Matrix|number[][]} X\n * @param {number[]} y\n * @param {object} [options={}]\n * @param {boolean} [maxIterations] if true or empty maxIterations is set at 3 times the number of columns of X\n * @returns {Array} k\n */\nexport default function fcnnlsVector(X, y, options = {}) {\n if (Array.isArray(y) === false) {\n throw new TypeError('y must be a 1D Array');\n }\n let Y = Matrix.columnVector(y);\n let K = fcnnls(X, Y, options);\n let k = K.to1DArray();\n return k;\n}\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 // The naive `low + high >>> 1` could fail for array lengths > 2**31\n // because `>>>` converts its operands to int32. `low + (high - low >>> 1)`\n // works for array lengths <= 2**32-1 which is also Javascript's max array\n // length.\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';\n\nfunction assertNumber(number) {\n\tif (typeof number !== 'number') {\n\t\tthrow new TypeError('Expected a number');\n\t}\n}\n\nexports.ascending = (left, right) => {\n\tassertNumber(left);\n\tassertNumber(right);\n\n\tif (Number.isNaN(left)) {\n\t\treturn -1;\n\t}\n\n\tif (Number.isNaN(right)) {\n\t\treturn 1;\n\t}\n\n\treturn left - right;\n};\n\nexports.descending = (left, right) => {\n\tassertNumber(left);\n\tassertNumber(right);\n\n\tif (Number.isNaN(left)) {\n\t\treturn 1;\n\t}\n\n\tif (Number.isNaN(right)) {\n\t\treturn -1;\n\t}\n\n\treturn right - left;\n};\n","import binarySearch from 'binary-search';\nimport { ascending } from 'num-sort';\n\nexport const largestPrime = 0x7fffffff;\n\nconst primeNumbers = [\n // chunk #0\n largestPrime, // 2^31-1\n\n // chunk #1\n 5,\n 11,\n 23,\n 47,\n 97,\n 197,\n 397,\n 797,\n 1597,\n 3203,\n 6421,\n 12853,\n 25717,\n 51437,\n 102877,\n 205759,\n 411527,\n 823117,\n 1646237,\n 3292489,\n 6584983,\n 13169977,\n 26339969,\n 52679969,\n 105359939,\n 210719881,\n 421439783,\n 842879579,\n 1685759167,\n\n // chunk #2\n 433,\n 877,\n 1759,\n 3527,\n 7057,\n 14143,\n 28289,\n 56591,\n 113189,\n 226379,\n 452759,\n 905551,\n 1811107,\n 3622219,\n 7244441,\n 14488931,\n 28977863,\n 57955739,\n 115911563,\n 231823147,\n 463646329,\n 927292699,\n 1854585413,\n\n // chunk #3\n 953,\n 1907,\n 3821,\n 7643,\n 15287,\n 30577,\n 61169,\n 122347,\n 244703,\n 489407,\n 978821,\n 1957651,\n 3915341,\n 7830701,\n 15661423,\n 31322867,\n 62645741,\n 125291483,\n 250582987,\n 501165979,\n 1002331963,\n 2004663929,\n\n // chunk #4\n 1039,\n 2081,\n 4177,\n 8363,\n 16729,\n 33461,\n 66923,\n 133853,\n 267713,\n 535481,\n 1070981,\n 2141977,\n 4283963,\n 8567929,\n 17135863,\n 34271747,\n 68543509,\n 137087021,\n 274174111,\n 548348231,\n 1096696463,\n\n // chunk #5\n 31,\n 67,\n 137,\n 277,\n 557,\n 1117,\n 2237,\n 4481,\n 8963,\n 17929,\n 35863,\n 71741,\n 143483,\n 286973,\n 573953,\n 1147921,\n 2295859,\n 4591721,\n 9183457,\n 18366923,\n 36733847,\n 73467739,\n 146935499,\n 293871013,\n 587742049,\n 1175484103,\n\n // chunk #6\n 599,\n 1201,\n 2411,\n 4831,\n 9677,\n 19373,\n 38747,\n 77509,\n 155027,\n 310081,\n 620171,\n 1240361,\n 2480729,\n 4961459,\n 9922933,\n 19845871,\n 39691759,\n 79383533,\n 158767069,\n 317534141,\n 635068283,\n 1270136683,\n\n // chunk #7\n 311,\n 631,\n 1277,\n 2557,\n 5119,\n 10243,\n 20507,\n 41017,\n 82037,\n 164089,\n 328213,\n 656429,\n 1312867,\n 2625761,\n 5251529,\n 10503061,\n 21006137,\n 42012281,\n 84024581,\n 168049163,\n 336098327,\n 672196673,\n 1344393353,\n\n // chunk #8\n 3,\n 7,\n 17,\n 37,\n 79,\n 163,\n 331,\n 673,\n 1361,\n 2729,\n 5471,\n 10949,\n 21911,\n 43853,\n 87719,\n 175447,\n 350899,\n 701819,\n 1403641,\n 2807303,\n 5614657,\n 11229331,\n 22458671,\n 44917381,\n 89834777,\n 179669557,\n 359339171,\n 718678369,\n 1437356741,\n\n // chunk #9\n 43,\n 89,\n 179,\n 359,\n 719,\n 1439,\n 2879,\n 5779,\n 11579,\n 23159,\n 46327,\n 92657,\n 185323,\n 370661,\n 741337,\n 1482707,\n 2965421,\n 5930887,\n 11861791,\n 23723597,\n 47447201,\n 94894427,\n 189788857,\n 379577741,\n 759155483,\n 1518310967,\n\n // chunk #10\n 379,\n 761,\n 1523,\n 3049,\n 6101,\n 12203,\n 24407,\n 48817,\n 97649,\n 195311,\n 390647,\n 781301,\n 1562611,\n 3125257,\n 6250537,\n 12501169,\n 25002389,\n 50004791,\n 100009607,\n 200019221,\n 400038451,\n 800076929,\n 1600153859,\n\n // chunk #11\n 13,\n 29,\n 59,\n 127,\n 257,\n 521,\n 1049,\n 2099,\n 4201,\n 8419,\n 16843,\n 33703,\n 67409,\n 134837,\n 269683,\n 539389,\n 1078787,\n 2157587,\n 4315183,\n 8630387,\n 17260781,\n 34521589,\n 69043189,\n 138086407,\n 276172823,\n 552345671,\n 1104691373,\n\n // chunk #12\n 19,\n 41,\n 83,\n 167,\n 337,\n 677,\n 1361,\n 2729,\n 5471,\n 10949,\n 21911,\n 43853,\n 87719,\n 175447,\n 350899,\n 701819,\n 1403641,\n 2807303,\n 5614657,\n 11229331,\n 22458671,\n 44917381,\n 89834777,\n 179669557,\n 359339171,\n 718678369,\n 1437356741,\n\n // chunk #13\n 53,\n 107,\n 223,\n 449,\n 907,\n 1823,\n 3659,\n 7321,\n 14653,\n 29311,\n 58631,\n 117269,\n 234539,\n 469099,\n 938207,\n 1876417,\n 3752839,\n 7505681,\n 15011389,\n 30022781,\n 60045577,\n 120091177,\n 240182359,\n 480364727,\n 960729461,\n 1921458943\n];\n\nprimeNumbers.sort(ascending);\n\nexport function nextPrime(value) {\n let index = binarySearch(primeNumbers, value, ascending);\n if (index < 0) {\n index = ~index;\n }\n return primeNumbers[index];\n}\n","import { largestPrime, nextPrime } from './primeFinder';\n\nconst FREE = 0;\nconst FULL = 1;\nconst REMOVED = 2;\n\nconst defaultInitialCapacity = 150;\nconst defaultMinLoadFactor = 1 / 6;\nconst defaultMaxLoadFactor = 2 / 3;\n\nexport default class 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 =\n options.initialCapacity === undefined\n ? defaultInitialCapacity\n : options.initialCapacity;\n if (initialCapacity < 0) {\n throw new RangeError(\n `initial capacity must not be less than zero: ${initialCapacity}`\n );\n }\n\n const minLoadFactor =\n options.minLoadFactor === undefined\n ? defaultMinLoadFactor\n : options.minLoadFactor;\n const maxLoadFactor =\n options.maxLoadFactor === undefined\n ? defaultMaxLoadFactor\n : 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(\n `minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`\n );\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);\n this.values = newArray(capacity);\n this.state = newArray(capacity);\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(\n this.distinct + 1,\n this.minLoadFactor,\n this.maxLoadFactor\n );\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(\n this.distinct + 1,\n this.minLoadFactor,\n this.maxLoadFactor\n );\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(\n this.distinct,\n this.minLoadFactor,\n this.maxLoadFactor\n );\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 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);\n const newValues = newArray(newCapacity);\n const newState = newArray(newCapacity);\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\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(\n Math.max(size + 1, ((4 * size) / (3 * minLoad + maxLoad)) | 0)\n );\n}\n\nfunction chooseShrinkCapacity(size, minLoad, maxLoad) {\n return nextPrime(\n Math.max(size + 1, ((4 * size) / (minLoad + 3 * maxLoad)) | 0)\n );\n}\n\nfunction newArray(size) {\n return Array(size).fill(0);\n}\n","import HashTable from 'ml-hash-table';\n\nexport class SparseMatrix {\n constructor(rows, columns, options = {}) {\n if (rows instanceof SparseMatrix) {\n // clone\n const other = rows;\n this._init(\n other.rows,\n other.columns,\n other.elements.clone(),\n other.threshold\n );\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(\n 'Number of columns of left matrix are not equal to number of rows of right matrix.'\n );\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, {\n initialCapacity: this.cardinality\n });\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(\n fillTemplateFunction(inplaceOperator, {\n name: operator[i],\n op: operator[0]\n })\n );\n SparseMatrix.prototype[`${operator[i]}S`] = eval(\n fillTemplateFunction(inplaceOperatorScalar, {\n name: `${operator[i]}S`,\n op: operator[0]\n })\n );\n SparseMatrix.prototype[`${operator[i]}M`] = eval(\n fillTemplateFunction(inplaceOperatorMatrix, {\n name: `${operator[i]}M`,\n op: operator[0]\n })\n );\n\n SparseMatrix[operator[i]] = eval(\n fillTemplateFunction(staticOperator, { name: operator[i] })\n );\n }\n}\n\nvar methods = [['~', 'not']];\n\n[\n 'abs',\n 'acos',\n 'acosh',\n 'asin',\n 'asinh',\n 'atan',\n 'atanh',\n 'cbrt',\n 'ceil',\n 'clz32',\n 'cos',\n 'cosh',\n 'exp',\n 'expm1',\n 'floor',\n 'fround',\n 'log',\n 'log1p',\n 'log10',\n 'log2',\n 'round',\n 'sign',\n 'sin',\n 'sinh',\n 'sqrt',\n 'tan',\n 'tanh',\n '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(\n fillTemplateFunction(inplaceMethod, {\n name: method[i],\n method: method[0]\n })\n );\n SparseMatrix[method[i]] = eval(\n fillTemplateFunction(staticMethod, { name: method[i] })\n );\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","export default function additiveSymmetric(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function avg(a, b) {\n var ii = a.length;\n var max = 0;\n var ans = 0;\n var 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","export default function bhattacharyya(a, b) {\n var ii = a.length;\n var 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","export default function canberra(a, b) {\n var ii = a.length;\n var 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","export default function chebyshev(a, b) {\n var ii = a.length;\n var max = 0;\n var 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","export default function clark(a, b) {\n var i = 0;\n var ii = a.length;\n var d = 0;\n for (; i < ii; i++) {\n d += Math.sqrt(\n ((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i]))\n );\n }\n return 2 * d;\n}\n","export default 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","import czekanowskiSimilarity from '../similarities/czekanowski';\n\nexport default function czekanowskiDistance(a, b) {\n return 1 - czekanowskiSimilarity(a, b);\n}\n","export default function dice(a, b) {\n var ii = a.length;\n var p = 0;\n var q1 = 0;\n var 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","export default function divergence(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function fidelity(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return ans;\n}\n","export default function gower(a, b) {\n var ii = a.length;\n var 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","export default function harmonicMean(a, b) {\n var ii = a.length;\n var 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","export default function hellinger(a, b) {\n var ii = a.length;\n var 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","export default function innerProduct(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans += a[i] * b[i];\n }\n return ans;\n}\n","export default function intersection(a, b) {\n var ii = a.length;\n var 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","export default function jaccard(a, b) {\n var ii = a.length;\n var p1 = 0;\n var p2 = 0;\n var q1 = 0;\n var 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","export default function jeffreys(a, b) {\n var ii = a.length;\n var 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","export default function jensenDifference(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n (a[i] * Math.log(a[i]) + b[i] * Math.log(b[i])) / 2 -\n ((a[i] + b[i]) / 2) * Math.log((a[i] + b[i]) / 2);\n }\n return ans;\n}\n","export default function jensenShannon(a, b) {\n var ii = a.length;\n var p = 0;\n var 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","export default function kdivergence(a, b) {\n var ii = a.length;\n var 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","export default function kulczynski(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function kullbackLeibler(a, b) {\n var ii = a.length;\n var 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","export default function kumarHassebrook(a, b) {\n var ii = a.length;\n var p = 0;\n var p2 = 0;\n var 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","export default function kumarJohnson(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n 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","export default function lorentzian(a, b) {\n var ii = a.length;\n var 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","export default function manhattan(a, b) {\n var i = 0;\n var ii = a.length;\n var d = 0;\n for (; i < ii; i++) {\n d += Math.abs(a[i] - b[i]);\n }\n return d;\n}\n","export default function matusita(a, b) {\n var ii = a.length;\n var 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","export default function minkowski(a, b, p) {\n var i = 0;\n var ii = a.length;\n var 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","export default function motyka(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function neyman(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function pearson(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function probabilisticSymmetric(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function ruzicka(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function soergel(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function sorensen(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function squared(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function squaredChord(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i]));\n }\n return ans;\n}\n","export default function taneja(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n ((a[i] + b[i]) / 2) *\n Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i])));\n }\n return ans;\n}\n","export default function tanimoto(a, b, bitvector) {\n if (bitvector) {\n var inter = 0;\n var 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 }\n return inter / union;\n } else {\n var ii = a.length;\n var p = 0;\n var q = 0;\n var 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","import tanimotoS from '../similarities/tanimoto';\n\nexport default function tanimoto(a, b, bitvector) {\n if (bitvector) {\n return 1 - tanimotoS(a, b, bitvector);\n } else {\n var ii = a.length;\n var p = 0;\n var q = 0;\n var 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","export default function topsoe(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n a[i] * Math.log((2 * a[i]) / (a[i] + b[i])) +\n b[i] * Math.log((2 * b[i]) / (a[i] + b[i]));\n }\n return ans;\n}\n","export default function waveHedges(a, b) {\n var ii = a.length;\n var 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","import binarySearch from 'binary-search';\nimport { ascending } from 'num-sort';\n\n/**\n * Function that creates the tree\n * @param {Array>} spectrum\n * @param {object} [options]\n * @return {Tree|null}\n * left and right have the same structure than the parent,\n * or are null if they are leaves\n */\nexport function createTree(spectrum, options = {}) {\n var X = spectrum[0];\n const {\n minWindow = 0.16,\n threshold = 0.01,\n from = X[0],\n to = X[X.length - 1]\n } = options;\n\n return mainCreateTree(\n spectrum[0],\n spectrum[1],\n from,\n to,\n minWindow,\n threshold\n );\n}\n\nfunction mainCreateTree(X, Y, from, to, minWindow, threshold) {\n if (to - from < minWindow) {\n return null;\n }\n\n // search first point\n var start = binarySearch(X, from, ascending);\n if (start < 0) {\n start = ~start;\n }\n\n // stop at last point\n var sum = 0;\n var center = 0;\n for (var i = start; i < X.length; i++) {\n if (X[i] >= to) {\n break;\n }\n sum += Y[i];\n center += X[i] * Y[i];\n }\n\n if (sum < threshold) {\n return null;\n }\n\n center /= sum;\n if (center - from < 1e-6 || to - center < 1e-6) {\n return null;\n }\n if (center - from < minWindow / 4) {\n return mainCreateTree(X, Y, center, to, minWindow, threshold);\n } else {\n if (to - center < minWindow / 4) {\n return mainCreateTree(X, Y, from, center, minWindow, threshold);\n } else {\n return new Tree(\n sum,\n center,\n mainCreateTree(X, Y, from, center, minWindow, threshold),\n mainCreateTree(X, Y, center, to, minWindow, threshold)\n );\n }\n }\n}\n\nclass Tree {\n constructor(sum, center, left, right) {\n this.sum = sum;\n this.center = center;\n this.left = left;\n this.right = right;\n }\n}\n","import { createTree } from './createTree';\n\n/**\n * Similarity between two nodes\n * @param {Tree|Array>} a - tree A node\n * @param {Tree|Array>} b - tree B node\n * @param {object} [options]\n * @return {number} similarity measure between tree nodes\n */\nexport function getSimilarity(a, b, options = {}) {\n const { alpha = 0.1, beta = 0.33, gamma = 0.001 } = options;\n\n if (a === null || b === null) {\n return 0;\n }\n if (Array.isArray(a)) {\n a = createTree(a);\n }\n if (Array.isArray(b)) {\n b = createTree(b);\n }\n\n var C =\n (alpha * Math.min(a.sum, b.sum)) / Math.max(a.sum, b.sum) +\n (1 - alpha) * Math.exp(-gamma * Math.abs(a.center - b.center));\n\n return (\n beta * C +\n ((1 - beta) *\n (getSimilarity(a.left, b.left, options) +\n getSimilarity(a.right, b.right, options))) /\n 2\n );\n}\n","import { getSimilarity } from './getSimilarity';\n\nexport { createTree } from './createTree';\n\nexport function treeSimilarity(A, B, options = {}) {\n return getSimilarity(A, B, options);\n}\n\nexport function getFunction(options = {}) {\n return (A, B) => getSimilarity(A, B, options);\n}\n","export default function cosine(a, b) {\n var ii = a.length;\n var p = 0;\n var p2 = 0;\n var 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","import diceD from '../distances/dice';\n\nexport default function dice(a, b) {\n return 1 - diceD(a, b);\n}\n","import intersectionD from '../distances/intersection';\n\nexport default function intersection(a, b) {\n return 1 - intersectionD(a, b);\n}\n","import jaccardD from '../distances/jaccard';\n\nexport default function jaccard(a, b) {\n return 1 - jaccardD(a, b);\n}\n","import kulczynskiD from '../distances/kulczynski';\n\nexport default function kulczynski(a, b) {\n return 1 / kulczynskiD(a, b);\n}\n","import motykaD from '../distances/motyka';\n\nexport default function motyka(a, b) {\n return 1 - motykaD(a, b);\n}\n","import mean from 'ml-array-mean';\n\nimport cosine from './cosine';\n\nexport default function pearson(a, b) {\n var avgA = mean(a);\n var avgB = mean(b);\n\n var newA = new Array(a.length);\n var newB = new Array(b.length);\n for (var i = 0; i < newA.length; i++) {\n newA[i] = a[i] - avgA;\n newB[i] = b[i] - avgB;\n }\n\n return cosine(newA, newB);\n}\n","import squaredChordD from '../distances/squaredChord';\n\nexport default function squaredChord(a, b) {\n return 1 - squaredChordD(a, b);\n}\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\nconst measures = require('./measures');\n\nclass Performance {\n /**\n *\n * @param prediction - The prediction matrix\n * @param target - The target matrix (values: truthy for same class, falsy for different class)\n * @param options\n *\n * @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)\n * @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)\n */\n constructor(prediction, target, options) {\n options = options || {};\n if (prediction.length !== target.length || prediction[0].length !== target[0].length) {\n throw new Error('dimensions of prediction and target do not match');\n }\n const rows = prediction.length;\n const columns = prediction[0].length;\n const isDistance = !options.max;\n\n const predP = [];\n\n if (options.all) {\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n predP.push({\n pred: prediction[i][j],\n targ: target[i][j]\n });\n }\n }\n } else {\n if (rows < 3 || rows !== columns) {\n throw new Error('When \"all\" option is false, the prediction matrix must be square and have at least 3 columns');\n }\n for (var i = 0; i < rows - 1; i++) {\n for (var j = i + 1; j < columns; j++) {\n predP.push({\n pred: prediction[i][j],\n targ: target[i][j]\n });\n }\n }\n }\n\n if (isDistance) {\n predP.sort((a, b) => 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\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\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 }\n output = options.output;\n } else {\n output = new Array(cond);\n }\n\n var i;\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 } else if (options.value === 'replicate') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0]) output[i] = data[0];\n else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];\n else output[i] = data[len - 1];\n }\n } else if (options.value === 'symmetric') {\n if (options.size[0] > len || options.size[1] > len) {\n throw new RangeError(\n 'expanded value should not be bigger than the data length'\n );\n }\n for (i = 0; i < cond; i++) {\n if (i < options.size[0]) output[i] = data[options.size[0] - 1 - i];\n else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];\n else output[i] = data[2 * len + options.size[0] - i - 1];\n }\n } else {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0]) output[i] = options.value;\n else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];\n else 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 }\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 = Object.assign({}, defaultOptions, options);\n if (Array.isArray(data)) {\n if (Array.isArray(data[0])) return matrixCase(data, options);\n else return arrayCase(data, options);\n } else {\n throw new TypeError('data should be an array');\n }\n}\n\nmodule.exports = padArray;\n","import { Matrix, MatrixTransposeView, inverse } from 'ml-matrix';\nimport padArray from 'ml-pad-array';\n\n/**\n * Factorial of a number\n * @ignore\n * @param n\n * @return {number}\n */\nfunction factorial(n) {\n let r = 1;\n while (n > 0) r *= n--;\n return r;\n}\n\nconst 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 */\nexport default function savitzkyGolay(data, h, options) {\n options = Object.assign({}, defaultOptions, options);\n if (\n options.windowSize % 2 === 0 ||\n options.windowSize < 5 ||\n !Number.isInteger(options.windowSize)\n ) {\n throw new RangeError(\n 'Invalid window size (should be odd and at least 5 integer number)',\n );\n }\n if (options.derivative < 0 || !Number.isInteger(options.derivative)) {\n throw new RangeError('Derivative should be a positive integer');\n }\n if (options.polynomial < 1 || !Number.isInteger(options.polynomial)) {\n throw new RangeError('Polynomial should be a positive integer');\n }\n\n let C, norm;\n let step = Math.floor(options.windowSize / 2);\n\n if (options.pad === 'pre') {\n data = padArray(data, { size: step, value: options.padValue });\n }\n\n let ans = new Array(data.length - 2 * step);\n\n if (\n options.windowSize === 5 &&\n options.polynomial === 2 &&\n (options.derivative === 1 || options.derivative === 2)\n ) {\n if (options.derivative === 1) {\n C = [-2, -1, 0, 1, 2];\n norm = 10;\n } else {\n C = [2, -1, -2, -1, 2];\n norm = 7;\n }\n } else {\n let J = Matrix.ones(options.windowSize, options.polynomial + 1);\n let inic = -(options.windowSize - 1) / 2;\n for (let i = 0; i < J.rows; i++) {\n for (let j = 0; j < J.columns; j++) {\n if (inic + 1 !== 0 || j !== 0) J.set(i, j, Math.pow(inic + i, j));\n }\n }\n let Jtranspose = new MatrixTransposeView(J);\n let Jinv = inverse(Jtranspose.mmul(J));\n C = Jinv.mmul(Jtranspose);\n C = C.getRow(options.derivative);\n norm = 1 / factorial(options.derivative);\n }\n let det = norm * Math.pow(h, options.derivative);\n for (let k = step; k < data.length - step; k++) {\n let d = 0;\n for (let l = 0; l < C.length; l++) 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","// 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\nvar eightBits = require('./creator');\n\n/**\n * Count the number of true values in an array\n * @param {Array} arr\n * @return {number}\n */\nfunction count(arr) {\n var c = 0;\n for (var i = 0; i < arr.length; i++) {\n c += eightBits[arr[i] & 0xff] + eightBits[(arr[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","export default function SavitzkyGolay(data, h, options = {}) {\n let { windowSize = 9, derivative = 0, polynomial = 3 } = options;\n\n if (windowSize % 2 === 0 || windowSize < 5 || !Number.isInteger(windowSize)) {\n throw new RangeError(\n 'Invalid window size (should be odd and at least 5 integer number)',\n );\n }\n if (windowSize > data.length) {\n throw new RangeError(\n `Window size is higher than the data length ${windowSize}>${data.length}`,\n );\n }\n if (derivative < 0 || !Number.isInteger(derivative)) {\n throw new RangeError('Derivative should be a positive integer');\n }\n if (polynomial < 1 || !Number.isInteger(polynomial)) {\n throw new RangeError('Polynomial should be a positive integer');\n }\n if (polynomial >= 6) {\n // eslint-disable-next-line no-console\n console.warn(\n '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 }\n\n let half = Math.floor(windowSize / 2);\n let np = data.length;\n let ans = new Array(np);\n let weights = fullWeights(windowSize, polynomial, derivative);\n let hs = 0;\n let constantH = true;\n if (Array.isArray(h)) {\n constantH = false;\n } else {\n hs = Math.pow(h, derivative);\n }\n\n //For the borders\n for (let i = 0; i < half; i++) {\n let wg1 = weights[half - i - 1];\n let wg2 = weights[half + i + 1];\n let d1 = 0;\n let d2 = 0;\n for (let l = 0; l < windowSize; l++) {\n d1 += wg1[l] * data[l];\n d2 += wg2[l] * data[np - windowSize + l];\n }\n if (constantH) {\n ans[half - i - 1] = d1 / hs;\n ans[np - half + i] = d2 / hs;\n } else {\n hs = getHs(h, half - i - 1, half, derivative);\n ans[half - i - 1] = d1 / hs;\n hs = getHs(h, np - half + i, half, derivative);\n ans[np - half + i] = d2 / hs;\n }\n }\n\n //For the internal points\n let wg = weights[half];\n for (let i = windowSize; i <= np; i++) {\n let d = 0;\n for (let l = 0; l < windowSize; l++) d += wg[l] * data[l + i - windowSize];\n if (!constantH) hs = getHs(h, i - half - 1, half, derivative);\n ans[i - half - 1] = d / hs;\n }\n return ans;\n}\n\nfunction getHs(h, center, half, derivative) {\n let hs = 0;\n let count = 0;\n for (let i = center - half; i < center + half; i++) {\n if (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 let Grampoly = 0;\n if (k > 0) {\n Grampoly =\n ((4 * k - 2) / (k * (2 * m - k + 1))) *\n (i * GramPoly(i, m, k - 1, s) + s * GramPoly(i, m, k - 1, s - 1)) -\n (((k - 1) * (2 * m + k)) / (k * (2 * m - k + 1))) *\n GramPoly(i, m, k - 2, s);\n } else {\n if (k === 0 && s === 0) {\n Grampoly = 1;\n } else {\n Grampoly = 0;\n }\n }\n return Grampoly;\n}\n\nfunction GenFact(a, b) {\n let gf = 1;\n if (a >= b) {\n for (let 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 let sum = 0;\n for (let k = 0; k <= n; k++) {\n //console.log(k);\n sum +=\n (2 * k + 1) *\n (GenFact(2 * m, k) / GenFact(2 * m + k + 1, k + 1)) *\n GramPoly(i, m, k, 0) *\n 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 let weights = new Array(m);\n let np = Math.floor(m / 2);\n for (let t = -np; t <= np; t++) {\n weights[t + np] = new Array(m);\n for (let 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} x - Independent variable\n * @param {Array} yIn - Dependent variable\n * @param {object} [options] - Options object\n * @param {object} [options.sgOptions] - Options object for Savitzky-Golay filter. See https://github.com/mljs/savitzky-golay-generalized#options\n * @param {number} [options.sgOptions.windowSize = 9] - points to use in the approximations\n * @param {number} [options.sgOptions.polynomial = 3] - degree of the polynomial to use in the approximations\n * @param {number} [options.minMaxRatio = 0.00025] - Threshold to determine if a given peak should be considered as a noise\n * @param {number} [options.broadRatio = 0.00] - If `broadRatio` is higher than 0, then all the peaks which second derivative\n * smaller than `broadRatio * maxAbsSecondDerivative` will be marked with the soft mask equal to true.\n * @param {number} [options.noiseLevel = 0] - Noise threshold in spectrum units\n * @param {boolean} [options.maxCriteria = true] - Peaks are local maximum(true) or minimum(false)\n * @param {boolean} [options.smoothY = true] - Select the peak intensities from a smoothed version of the independent variables\n * @param {boolean} [options.realTopDetection = false] - Use a quadratic optimizations with the peak and its 3 closest neighbors\n * to determine the true x,y values of the peak?\n * @param {number} [options.heightFactor = 0] - Factor to multiply the calculated height (usually 2)\n * @param {number} [options.derivativeThreshold = -1] - Filters based on the amplitude of the first derivative\n * @return {Array}\n */\nexport function gsd(x, yIn, options = {}) {\n let {\n noiseLevel,\n sgOptions = {\n windowSize: 9,\n polynomial: 3,\n },\n smoothY = true,\n heightFactor = 0,\n broadRatio = 0.0,\n maxCriteria = true,\n minMaxRatio = 0.00025,\n derivativeThreshold = -1,\n realTopDetection = false,\n } = options;\n\n const y = yIn.slice();\n let equalSpaced = isEqualSpaced(x);\n\n if (noiseLevel === undefined) {\n noiseLevel = equalSpaced ? getNoiseLevel(y) : 0;\n }\n\n const yCorrection = { m: 1, b: noiseLevel };\n\n if (!maxCriteria) {\n yCorrection.m = -1;\n yCorrection.b *= -1;\n }\n\n for (let i = 0; i < y.length; i++) {\n y[i] = yCorrection.m * y[i] - yCorrection.b;\n }\n\n for (let i = 0; i < y.length; i++) {\n if (y[i] < 0) {\n y[i] = 0;\n }\n }\n // If the max difference between delta x is less than 5%, then,\n // we can assume it to be equally spaced variable\n let yData = y;\n let dY, ddY;\n const { windowSize, polynomial } = sgOptions;\n\n if (equalSpaced) {\n if (smoothY) {\n yData = SG(y, x[1] - x[0], {\n windowSize,\n polynomial,\n derivative: 0,\n });\n }\n dY = SG(y, x[1] - x[0], {\n windowSize,\n polynomial,\n derivative: 1,\n });\n ddY = SG(y, x[1] - x[0], {\n windowSize,\n polynomial,\n derivative: 2,\n });\n } else {\n if (smoothY) {\n yData = SG(y, x, {\n windowSize,\n polynomial,\n derivative: 0,\n });\n }\n dY = SG(y, x, {\n windowSize,\n polynomial,\n derivative: 1,\n });\n ddY = SG(y, x, {\n windowSize,\n polynomial,\n derivative: 2,\n });\n }\n\n const xData = x;\n const dX = x[1] - x[0];\n let maxDdy = 0;\n let maxY = 0;\n for (let i = 0; i < yData.length; i++) {\n if (Math.abs(ddY[i]) > maxDdy) {\n maxDdy = Math.abs(ddY[i]);\n }\n if (Math.abs(yData[i]) > maxY) {\n maxY = Math.abs(yData[i]);\n }\n }\n\n let lastMax = null;\n let lastMin = null;\n let minddY = new Array(yData.length - 2);\n let intervalL = new Array(yData.length);\n let intervalR = new Array(yData.length);\n let broadMask = new Array(yData.length - 2);\n let minddYLen = 0;\n let intervalLLen = 0;\n let intervalRLen = 0;\n let broadMaskLen = 0;\n // By the intermediate value theorem We cannot find 2 consecutive maximum or minimum\n for (let i = 1; i < yData.length - 1; ++i) {\n // filter based on derivativeThreshold\n // console.log('pasa', y[i], dY[i], ddY[i]);\n if (Math.abs(dY[i]) > derivativeThreshold) {\n // Minimum in first derivative\n if (\n (dY[i] < dY[i - 1] && dY[i] <= dY[i + 1]) ||\n (dY[i] <= dY[i - 1] && dY[i] < dY[i + 1])\n ) {\n lastMin = {\n x: xData[i],\n index: i,\n };\n if (dX > 0 && lastMax !== null) {\n intervalL[intervalLLen++] = lastMax;\n intervalR[intervalRLen++] = lastMin;\n }\n }\n\n // Maximum in first derivative\n if (\n (dY[i] >= dY[i - 1] && dY[i] > dY[i + 1]) ||\n (dY[i] > dY[i - 1] && dY[i] >= dY[i + 1])\n ) {\n lastMax = {\n x: xData[i],\n index: i,\n };\n if (dX < 0 && lastMin !== null) {\n intervalL[intervalLLen++] = lastMax;\n intervalR[intervalRLen++] = lastMin;\n }\n }\n }\n\n // Minimum in second derivative\n if (ddY[i] < ddY[i - 1] && ddY[i] < ddY[i + 1]) {\n // TODO should we change this to have 3 arrays ? Huge overhead creating arrays\n minddY[minddYLen++] = i; // ( [xData[i], yData[i], i] );\n broadMask[broadMaskLen++] = Math.abs(ddY[i]) <= broadRatio * maxDdy;\n }\n }\n minddY.length = minddYLen;\n intervalL.length = intervalLLen;\n intervalR.length = intervalRLen;\n broadMask.length = broadMaskLen;\n\n let signals = new Array(minddY.length);\n let signalsLen = 0;\n let lastK = -1;\n let possible, frequency, distanceJ, minDistance, gettingCloser;\n for (let j = 0; j < minddY.length; ++j) {\n frequency = xData[minddY[j]];\n possible = -1;\n let k = lastK + 1;\n minDistance = Number.MAX_VALUE;\n distanceJ = 0;\n gettingCloser = true;\n while (possible === -1 && k < intervalL.length && gettingCloser) {\n distanceJ = Math.abs(frequency - (intervalL[k].x + intervalR[k].x) / 2);\n\n // Still getting closer?\n if (distanceJ < minDistance) {\n minDistance = distanceJ;\n } else {\n gettingCloser = false;\n }\n if (distanceJ < Math.abs(intervalL[k].x - intervalR[k].x) / 2) {\n possible = k;\n lastK = k;\n }\n ++k;\n }\n\n if (possible !== -1) {\n if (Math.abs(yData[minddY[j]]) > minMaxRatio * maxY) {\n signals[signalsLen++] = {\n index: minddY[j],\n x: frequency,\n y: (yData[minddY[j]] + yCorrection.b) / yCorrection.m,\n width: Math.abs(intervalR[possible].x - intervalL[possible].x), // widthCorrection\n soft: broadMask[j],\n };\n\n signals[signalsLen - 1].left = intervalL[possible];\n signals[signalsLen - 1].right = intervalR[possible];\n\n if (heightFactor) {\n let yLeft = yData[intervalL[possible].index];\n let yRight = yData[intervalR[possible].index];\n signals[signalsLen - 1].height =\n heightFactor * (signals[signalsLen - 1].y - (yLeft + yRight) / 2);\n }\n }\n }\n }\n signals.length = signalsLen;\n\n if (realTopDetection) {\n determineRealTop(signals, xData, yData);\n }\n\n // Correct the values to fit the original spectra data\n for (let j = 0; j < signals.length; j++) {\n signals[j].base = noiseLevel;\n }\n\n signals.sort(function (a, b) {\n return a.x - b.x;\n });\n\n return signals;\n}\n\nconst isEqualSpaced = (x) => {\n let tmp;\n let maxDx = 0;\n let minDx = Number.MAX_SAFE_INTEGER;\n for (let i = 0; i < x.length - 1; ++i) {\n tmp = Math.abs(x[i + 1] - x[i]);\n if (tmp < minDx) {\n minDx = tmp;\n }\n if (tmp > maxDx) {\n maxDx = tmp;\n }\n }\n return (maxDx - minDx) / maxDx < 0.05;\n};\n\nconst getNoiseLevel = (y) => {\n let mean = 0;\n\n let stddev = 0;\n let length = y.length;\n for (let i = 0; i < length; ++i) {\n mean += y[i];\n }\n mean /= length;\n let averageDeviations = new Array(length);\n for (let i = 0; i < length; ++i) {\n averageDeviations[i] = Math.abs(y[i] - mean);\n }\n averageDeviations.sort((a, b) => a - b);\n if (length % 2 === 1) {\n stddev = averageDeviations[(length - 1) / 2] / 0.6745;\n } else {\n stddev =\n (0.5 *\n (averageDeviations[length / 2] + averageDeviations[length / 2 - 1])) /\n 0.6745;\n }\n\n return stddev;\n};\n\nconst determineRealTop = (peakList, x, y) => {\n let alpha, beta, gamma, p, currentPoint;\n for (let j = 0; j < peakList.length; j++) {\n currentPoint = peakList[j].index; // peakList[j][2];\n // The detected peak could be moved 1 or 2 units to left or right.\n if (\n y[currentPoint - 1] >= y[currentPoint - 2] &&\n y[currentPoint - 1] >= y[currentPoint]\n ) {\n currentPoint--;\n } else {\n if (\n y[currentPoint + 1] >= y[currentPoint] &&\n y[currentPoint + 1] >= y[currentPoint + 2]\n ) {\n currentPoint++;\n } else {\n if (\n y[currentPoint - 2] >= y[currentPoint - 3] &&\n y[currentPoint - 2] >= y[currentPoint - 1]\n ) {\n currentPoint -= 2;\n } else {\n if (\n y[currentPoint + 2] >= y[currentPoint + 1] &&\n y[currentPoint + 2] >= y[currentPoint + 3]\n ) {\n currentPoint += 2;\n }\n }\n }\n }\n // interpolation to a sin() function\n if (\n y[currentPoint - 1] > 0 &&\n y[currentPoint + 1] > 0 &&\n y[currentPoint] >= y[currentPoint - 1] &&\n y[currentPoint] >= y[currentPoint + 1] &&\n (y[currentPoint] !== y[currentPoint - 1] ||\n y[currentPoint] !== y[currentPoint + 1])\n ) {\n alpha = 20 * Math.log10(y[currentPoint - 1]);\n beta = 20 * Math.log10(y[currentPoint]);\n gamma = 20 * Math.log10(y[currentPoint + 1]);\n p = (0.5 * (alpha - gamma)) / (alpha - 2 * beta + gamma);\n // console.log(alpha, beta, gamma, `p: ${p}`);\n // console.log(x[currentPoint]+\" \"+tmp+\" \"+currentPoint);\n peakList[j].x =\n x[currentPoint] + (x[currentPoint] - x[currentPoint - 1]) * p;\n peakList[j].y =\n y[currentPoint] -\n 0.25 * (y[currentPoint - 1] - y[currentPoint + 1]) * p;\n }\n }\n};\n","/**\n * This function calculates the spectrum as a sum of gaussian functions. The Gaussian\n * parameters are divided in 3 batches. 1st: centers; 2nd: height; 3th: std's;\n * @param t Ordinate values\n * @param p Gaussian parameters\n * @param c Constant parameters(Not used)\n * @returns {*}\n */\nexport function sumOfGaussians(p) {\n return function (t) {\n let nL = p.length / 3;\n let factor;\n let rows = t.length;\n let result = rows === undefined ? 0 : new Float64Array(rows).fill(0);\n for (let i = 0; i < nL; i++) {\n factor = Math.pow(p[i + nL * 2], 2) * 2;\n if (rows === undefined) {\n result += p[i + nL] * Math.exp(-Math.pow(t - p[i], 2) / factor);\n } else {\n for (let j = 0; j < rows; j++) {\n result[j] += p[i + nL] * Math.exp(-Math.pow(t[j] - p[i], 2) / factor);\n }\n }\n }\n return result;\n };\n}\n","import LM from 'ml-levenberg-marquardt';\n\nimport { sumOfGaussians } from './sumOfGaussians';\n\n/**\n *\n * @param xy A two column matrix containing the x and y data to be fitted\n * @param group A set of initial lorentzian parameters to be optimized [center, heigth, half_width_at_half_height]\n * @returns {Array} A set of final lorentzian parameters [center, heigth, hwhh*2]\n */\nexport function optimizeGaussianSum(xy, group, opts = {}) {\n let t = xy[0];\n let yData = xy[1];\n let maxY = Math.max(...yData);\n yData.forEach((x, i, arr) => (arr[i] /= maxY));\n let nL = group.length;\n let pInit = new Float64Array(nL * 3);\n let pMin = new Float64Array(nL * 3);\n let pMax = new Float64Array(nL * 3);\n let dt = Math.abs(t[0] - t[1]);\n\n for (let i = 0; i < nL; i++) {\n pInit[i] = group[i].x;\n pInit[i + nL] = group[i].y / maxY;\n pInit[i + 2 * nL] = group[i].width;\n\n pMin[i] = group[i].x - dt;\n pMin[i + nL] = 0;\n pMin[i + 2 * nL] = group[i].width / 4;\n\n pMax[i] = group[i].x + dt;\n pMax[i + nL] = (group[i].y * 1.2) / maxY;\n pMax[i + 2 * nL] = group[i].width * 4;\n }\n\n let data = {\n x: t,\n y: yData,\n };\n let result = new Array(nL);\n\n let lmOptions = {\n damping: 1.5,\n initialValues: pInit,\n minValues: pMin,\n maxValues: pMax,\n gradientDifference: dt / 10000,\n maxIterations: 100,\n errorTolerance: 10e-5,\n };\n\n opts = Object.assign({}, lmOptions, opts);\n\n let pFit = LM(data, sumOfGaussians, opts);\n for (let i = 0; i < nL; i++) {\n result[i] = {\n parameters: [\n pFit.parameterValues[i],\n pFit.parameterValues[i + nL] * maxY,\n pFit.parameterValues[i + nL * 2],\n ],\n error: pFit.parameterError,\n };\n }\n return result;\n}\n","/**\n * Single 3 parameter gaussian function\n * @param t Ordinate values\n * @param p Gaussian parameters [mean, height, std]\n * @param c Constant parameters(Not used)\n * @returns {*}\n */\n\nexport function singleGaussian(p) {\n return function (t) {\n let factor2 = (p[2] * p[2]) / 2;\n let rows = t.length;\n if (!rows) return p[1] * Math.exp((-(t - p[0]) * (t - p[0])) / factor2);\n let result = new Float64Array(t.length);\n for (let i = 0; i < t.length; i++) {\n result[i] = p[1] * Math.exp((-(t[i] - p[0]) * (t[i] - p[0])) / factor2);\n }\n return result;\n };\n}\n","import LM from 'ml-levenberg-marquardt';\n\nimport { singleGaussian } from './singleGaussian';\n\n/**\n * Fits a set of points to a gaussian bell. Returns the mean of the peak, the std and the height of the signal.\n * @param data,[y]\n * @returns {*[]}\n */\nexport function optimizeSingleGaussian(xy, peak, opts = {}) {\n let t = xy[0];\n let yData = xy[1];\n let maxY = Math.max(...yData);\n yData.forEach((x, i, arr) => (arr[i] /= maxY));\n let dt = Math.abs(t[0] - t[1]);\n let pInit = new Float64Array([peak.x, 1, peak.width]);\n let pMin = new Float64Array([peak.x - dt, 0, peak.width / 4]);\n let pMax = new Float64Array([peak.x + dt, 1.25, peak.width * 4]);\n\n let data = {\n x: t,\n y: yData,\n };\n\n let lmOptions = {\n damping: 1.5,\n initialValues: pInit,\n minValues: pMin,\n maxValues: pMax,\n gradientDifference: dt / 10000,\n maxIterations: 100,\n errorTolerance: 10e-5,\n };\n\n opts = Object.assign({}, lmOptions, opts);\n let pFit = LM(data, singleGaussian, opts);\n return {\n parameters: [\n pFit.parameterValues[0],\n pFit.parameterValues[1] * maxY,\n pFit.parameterValues[2],\n ],\n error: pFit.parameterError,\n };\n}\n","/**\n * This function calculates the spectrum as a sum of lorentzian functions. The Lorentzian\n * parameters are divided in 3 batches. 1st: centers; 2nd: heights; 3th: widths;\n * @param t Ordinate values\n * @param p Lorentzian parameters\n * @returns {*}\n */\n\nexport function sumOfLorentzians(p) {\n return function (t) {\n let nL = p.length / 3;\n let factor;\n let p2;\n let rows = t.length;\n let result = rows === undefined ? 0 : new Float64Array(rows).fill(0);\n for (let i = 0; i < nL; i++) {\n p2 = Math.pow(p[i + nL * 2] / 2, 2);\n factor = p[i + nL] * p2;\n if (rows === undefined) {\n result += factor / (Math.pow(t - p[i], 2) + p2);\n } else {\n for (let j = 0; j < rows; j++) {\n result[j] += factor / (Math.pow(t[j] - p[i], 2) + p2);\n }\n }\n }\n return result;\n };\n}\n","import LM from 'ml-levenberg-marquardt';\n\nimport { sumOfLorentzians } from './sumOfLorentzians';\n\n/**\n *\n * @param xy A two column matrix containing the x and y data to be fitted\n * @param group A set of initial lorentzian parameters to be optimized [center, heigth, half_width_at_half_height]\n * @returns {Array} A set of final lorentzian parameters [center, heigth, hwhh*2]\n */\nexport function optimizeLorentzianSum(xy, group, opts = {}) {\n let t = xy[0];\n let yData = xy[1];\n let maxY = Math.max(...yData);\n yData.forEach((x, i, arr) => (arr[i] /= maxY));\n\n let nL = group.length;\n let pInit = new Float64Array(nL * 3);\n let pMin = new Float64Array(nL * 3);\n let pMax = new Float64Array(nL * 3);\n let dt = Math.abs(t[0] - t[1]);\n\n for (let i = 0; i < nL; i++) {\n pInit[i] = group[i].x;\n pInit[i + nL] = 1;\n pInit[i + 2 * nL] = group[i].width;\n\n pMin[i] = group[i].x - dt;\n pMin[i + nL] = 0;\n pMin[i + 2 * nL] = group[i].width / 4;\n\n pMax[i] = group[i].x + dt;\n pMax[i + nL] = 1.5;\n pMax[i + 2 * nL] = group[i].width * 4;\n }\n\n let data = {\n x: t,\n y: yData,\n };\n\n let result = new Array(nL);\n\n let lmOptions = {\n damping: 1.5,\n initialValues: pInit,\n minValues: pMin,\n maxValues: pMax,\n gradientDifference: dt / 10000,\n maxIterations: 100,\n errorTolerance: 10e-5,\n };\n\n opts = Object.assign({}, lmOptions, opts);\n\n let pFit = LM(data, sumOfLorentzians, opts);\n for (let i = 0; i < nL; i++) {\n result[i] = {\n parameters: [\n pFit.parameterValues[i],\n pFit.parameterValues[i + nL] * maxY,\n pFit.parameterValues[i + nL * 2],\n ],\n error: pFit.parameterError,\n };\n }\n return result;\n}\n","/**\n * Single 4 parameter lorentzian function\n * @param t Ordinate values\n * @param p Lorentzian parameters\n * @param c Constant parameters(Not used)\n * @returns {*}\n */\n\nexport function singleLorentzian(p) {\n return function (t) {\n let factor = p[1] * Math.pow(p[2] / 2, 2);\n let rows = t.length;\n if (!rows) return factor / (Math.pow(t - p[0], 2) + Math.pow(p[2] / 2, 2));\n let result = new Float64Array(rows);\n for (let i = 0; i < rows; i++) {\n result[i] = factor / (Math.pow(t[i] - p[0], 2) + Math.pow(p[2] / 2, 2));\n }\n return result;\n };\n}\n","import LM from 'ml-levenberg-marquardt';\n\nimport { singleLorentzian } from './singleLorentzian';\n\n/**\n * * Fits a set of points to a Lorentzian function. Returns the center of the peak, the width at half height, and the height of the signal.\n * @param data,[y]\n * @returns {*[]}\n */\nexport function optimizeSingleLorentzian(xy, peak, opts = {}) {\n let t = xy[0];\n let yData = xy[1];\n let maxY = Math.max(...yData);\n yData.forEach((x, i, arr) => (arr[i] /= maxY));\n let dt = Math.abs(t[0] - t[1]);\n let pInit = new Float64Array([peak.x, 1, peak.width]);\n let pMin = new Float64Array([peak.x - dt, 0.75, peak.width / 4]);\n let pMax = new Float64Array([peak.x + dt, 1.25, peak.width * 4]);\n\n let data = {\n x: t,\n y: yData,\n };\n\n let lmOptions = {\n damping: 1.5,\n initialValues: pInit,\n minValues: pMin,\n maxValues: pMax,\n gradientDifference: dt / 10000,\n maxIterations: 100,\n errorTolerance: 10e-5,\n };\n opts = Object.assign({}, lmOptions, opts);\n let pFit = LM(data, singleLorentzian, opts);\n return {\n parameters: [\n pFit.parameterValues[0],\n pFit.parameterValues[1] * maxY,\n pFit.parameterValues[2],\n ],\n error: pFit.parameterError,\n };\n}\n","import {\n optimizeGaussianSum,\n optimizeLorentzianSum,\n optimizeSingleGaussian,\n optimizeSingleLorentzian,\n} from 'ml-optimize-lorentzian';\n\nexport function optimizePeaks(peakList, x, y, options = {}) {\n const {\n functionName = 'gaussian',\n factorWidth = 4,\n optimizationOptions = {\n damping: 1.5,\n maxIterations: 100,\n errorTolerance: 10e-5,\n },\n } = options;\n\n let lastIndex = [0];\n let groups = groupPeaks(peakList, factorWidth);\n let result = [];\n let factor = 1;\n if (functionName === 'gaussian') {\n factor = 1.17741;\n } // From https://en.wikipedia.org/wiki/Gaussian_function#Properties\n let sampling;\n for (let i = 0; i < groups.length; i++) {\n let peaks = groups[i].group;\n if (peaks.length > 1) {\n // Multiple peaks\n sampling = sampleFunction(\n groups[i].limits[0] - groups[i].limits[1],\n groups[i].limits[0] + groups[i].limits[1],\n x,\n y,\n lastIndex,\n );\n if (sampling[0].length > 5) {\n let optPeaks = [];\n if (functionName === 'gaussian') {\n optPeaks = optimizeGaussianSum(sampling, peaks, optimizationOptions);\n } else {\n if (functionName === 'lorentzian') {\n optPeaks = optimizeLorentzianSum(\n sampling,\n peaks,\n optimizationOptions,\n );\n }\n }\n\n for (let j = 0; j < optPeaks.length; j++) {\n let { parameters } = optPeaks[j];\n result.push({\n x: parameters[0],\n y: parameters[1],\n width: parameters[2] * factor,\n index: peaks[j].index,\n });\n }\n }\n } else {\n // Single peak\n peaks = peaks[0];\n sampling = sampleFunction(\n peaks.x - factorWidth * peaks.width,\n peaks.x + factorWidth * peaks.width,\n x,\n y,\n lastIndex,\n );\n\n if (sampling[0].length > 5) {\n let fitResult = [];\n if (functionName === 'gaussian') {\n fitResult = optimizeSingleGaussian(\n [sampling[0], sampling[1]],\n peaks,\n optimizationOptions,\n );\n } else {\n if (functionName === 'lorentzian') {\n fitResult = optimizeSingleLorentzian(\n [sampling[0], sampling[1]],\n peaks,\n optimizationOptions,\n );\n }\n }\n\n let { parameters } = fitResult;\n result.push({\n x: parameters[0],\n y: parameters[1],\n width: parameters[2] * factor,\n index: peaks.index,\n }); // From https://en.wikipedia.org/wiki/Gaussian_function#Properties}\n }\n }\n }\n return result;\n}\n\nfunction sampleFunction(from, to, x, y, lastIndex) {\n let nbPoints = x.length;\n let sampleX = [];\n let sampleY = [];\n let direction = Math.sign(x[1] - x[0]); // Direction of the derivative\n if (direction === -1) {\n lastIndex[0] = x.length - 1;\n }\n\n let delta = Math.abs(to - from) / 2;\n let mid = (from + to) / 2;\n let stop = false;\n let index = lastIndex[0];\n while (!stop && index < nbPoints && index >= 0) {\n if (Math.abs(x[index] - mid) <= delta) {\n sampleX.push(x[index]);\n sampleY.push(y[index]);\n index += direction;\n } else {\n // It is outside the range.\n if (Math.sign(mid - x[index]) === 1) {\n // We'll reach the mid going in the current direction\n index += direction;\n } else {\n // There is not more peaks in the current range\n stop = true;\n }\n }\n }\n lastIndex[0] = index;\n return [sampleX, sampleY];\n}\n\nfunction groupPeaks(peakList, nL) {\n let group = [];\n let groups = [];\n let limits = [peakList[0].x, nL * peakList[0].width];\n let upperLimit, lowerLimit;\n // Merge forward\n for (let i = 0; i < peakList.length; i++) {\n // If the 2 things overlaps\n if (\n Math.abs(peakList[i].x - limits[0]) <\n nL * peakList[i].width + limits[1]\n ) {\n // Add the peak to the group\n group.push(peakList[i]);\n // Update the group limits\n upperLimit = limits[0] + limits[1];\n if (peakList[i].x + nL * peakList[i].width > upperLimit) {\n upperLimit = peakList[i].x + nL * peakList[i].width;\n }\n lowerLimit = limits[0] - limits[1];\n if (peakList[i].x - nL * peakList[i].width < lowerLimit) {\n lowerLimit = peakList[i].x - nL * peakList[i].width;\n }\n limits = [\n (upperLimit + lowerLimit) / 2,\n Math.abs(upperLimit - lowerLimit) / 2,\n ];\n } else {\n groups.push({ limits: limits, group: group });\n // var optmimalPeak = fitSpectrum(group,limits,spectrum);\n group = [peakList[i]];\n limits = [peakList[i].x, nL * peakList[i].width];\n }\n }\n groups.push({ limits: limits, group: group });\n // Merge backward\n for (let i = groups.length - 2; i >= 0; i--) {\n // The groups overlaps\n if (\n Math.abs(groups[i].limits[0] - groups[i + 1].limits[0]) <\n (groups[i].limits[1] + groups[i + 1].limits[1]) / 2\n ) {\n for (let j = 0; j < groups[i + 1].group.length; j++) {\n groups[i].group.push(groups[i + 1].group[j]);\n }\n upperLimit = groups[i].limits[0] + groups[i].limits[1];\n if (groups[i + 1].limits[0] + groups[i + 1].limits[1] > upperLimit) {\n upperLimit = groups[i + 1].limits[0] + groups[i + 1].limits[1];\n }\n lowerLimit = groups[i].limits[0] - groups[i].limits[1];\n if (groups[i + 1].limits[0] - groups[i + 1].limits[1] < lowerLimit) {\n lowerLimit = groups[i + 1].limits[0] - groups[i + 1].limits[1];\n }\n\n groups[i].limits = [\n (upperLimit + lowerLimit) / 2,\n Math.abs(upperLimit - lowerLimit) / 2,\n ];\n\n groups.splice(i + 1, 1);\n }\n }\n return groups;\n}\n","import { optimizeSingleLorentzian } from 'ml-optimize-lorentzian';\n\n/**\n * This function try to join the peaks that seems to belong to a broad signal in a single broad peak.\n * @param peakList\n * @param options\n */\nexport function joinBroadPeaks(peakList, options = {}) {\n let width = options.width;\n let broadLines = [];\n // Optimize the possible broad lines\n let max = 0;\n\n let maxI = 0;\n\n let count = 1;\n for (let i = peakList.length - 1; i >= 0; i--) {\n if (peakList[i].soft) {\n broadLines.push(peakList.splice(i, 1)[0]);\n }\n }\n // Push a feke peak\n broadLines.push({ x: Number.MAX_VALUE });\n\n let candidates = [[broadLines[0].x, broadLines[0].y]];\n let indexes = [broadLines[0].index];\n\n for (let i = 1; i < broadLines.length; i++) {\n // console.log(broadLines[i-1].x+\" \"+broadLines[i].x);\n if (Math.abs(broadLines[i - 1].x - broadLines[i].x) < width) {\n candidates.push([broadLines[i].x, broadLines[i].y]);\n if (broadLines[i].y > max) {\n max = broadLines[i].y;\n maxI = i;\n }\n indexes.push(broadLines[i].index);\n count++;\n } else {\n if (count > 2) {\n let fitted = optimizeSingleLorentzian(candidates, {\n x: broadLines[maxI].x,\n y: max,\n width: Math.abs(\n candidates[0][0] - candidates[candidates.length - 1][0],\n ),\n });\n let { parameters } = fitted;\n peakList.push({\n x: parameters[0],\n y: parameters[1],\n width: parameters[2],\n index: Math.floor(\n indexes.reduce((a, b) => a + b, 0) / indexes.length,\n ),\n soft: false,\n });\n } else {\n // Put back the candidates to the signals list\n indexes.forEach((index) => {\n peakList.push(broadLines[index]);\n });\n }\n candidates = [[broadLines[i].x, broadLines[i].y]];\n indexes = [i];\n max = broadLines[i].y;\n maxI = i;\n count = 1;\n }\n }\n\n peakList.sort(function (a, b) {\n return a.x - b.x;\n });\n\n return peakList;\n}\n","/**\n * This method will allow to enlarge peaks and prevent overlap between peaks\n * Because peaks may not be symmetric after we add 2 properties, from and to.\n * @param {Array} peakList\n * @param {object} [options={}]\n * @param {number} [factor=2]\n * @param {boolean} [overlap=false] by default we don't allow overlap\n * @return {Array} peakList\n */\nexport function broadenPeaks(peakList, options = {}) {\n const { factor = 2, overlap = false } = options;\n\n for (let peak of peakList) {\n if (!peak.right || !peak.left) {\n peak.from = peak.x - (peak.width / 2) * factor;\n peak.to = peak.x + (peak.width / 2) * factor;\n } else {\n peak.from = peak.x - (peak.x - peak.left.x) * factor;\n peak.to = peak.x + (peak.right.x - peak.x) * factor;\n }\n }\n\n if (!overlap) {\n for (let i = 0; i < peakList.length - 1; i++) {\n let peak = peakList[i];\n let nextPeak = peakList[i + 1];\n if (peak.to > nextPeak.from) {\n peak.to = nextPeak.from = (peak.to + nextPeak.from) / 2;\n }\n }\n }\n\n for (let peak of peakList) {\n peak.width = peak.to - peak.from;\n }\n\n return peakList;\n}\n","const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n","import isArray from 'is-any-array';\n\nfunction min(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 }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var _options$fromIndex = options.fromIndex,\n fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,\n _options$toIndex = options.toIndex,\n toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;\n\n if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {\n throw new Error('fromIndex must be a positive integer smaller than length');\n }\n\n if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {\n throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');\n }\n\n var minValue = input[fromIndex];\n\n for (var i = fromIndex + 1; i < toIndex; i++) {\n if (input[i] < minValue) minValue = input[i];\n }\n\n return minValue;\n}\n\nexport default min;\n","import isArray from 'is-any-array';\n\nfunction max(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 }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var _options$fromIndex = options.fromIndex,\n fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,\n _options$toIndex = options.toIndex,\n toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;\n\n if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {\n throw new Error('fromIndex must be a positive integer smaller than length');\n }\n\n if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {\n throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');\n }\n\n var maxValue = input[fromIndex];\n\n for (var i = fromIndex + 1; i < toIndex; i++) {\n if (input[i] > maxValue) maxValue = input[i];\n }\n\n return maxValue;\n}\n\nexport default max;\n","import isArray from 'is-any-array';\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","const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n","import isArray from 'is-any-array';\n\nfunction max(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 }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var _options$fromIndex = options.fromIndex,\n fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,\n _options$toIndex = options.toIndex,\n toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;\n\n if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {\n throw new Error('fromIndex must be a positive integer smaller than length');\n }\n\n if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {\n throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');\n }\n\n var maxValue = input[fromIndex];\n\n for (var i = fromIndex + 1; i < toIndex; i++) {\n if (input[i] > maxValue) maxValue = input[i];\n }\n\n return maxValue;\n}\n\nexport default max;\n","import isArray from 'is-any-array';\nimport max from 'ml-array-max';\nimport sum from 'ml-array-sum';\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 _options$sumValue = options.sumValue,\n sumValue = _options$sumValue === void 0 ? 1 : _options$sumValue,\n _options$maxValue = options.maxValue,\n maxValue = _options$maxValue === void 0 ? 1 : _options$maxValue;\n\n if (!isArray(input)) {\n throw new Error('input must be an array');\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 if (input.length === 0) {\n throw new Error('input must not be empty');\n }\n\n switch (algorithm.toLowerCase()) {\n case 'absolute':\n {\n var absoluteSumValue = absoluteSum(input) / sumValue;\n if (absoluteSumValue === 0) return input.slice(0);\n\n for (var i = 0; i < input.length; i++) {\n output[i] = input[i] / absoluteSumValue;\n }\n\n return output;\n }\n\n case 'max':\n {\n var currentMaxValue = max(input);\n if (currentMaxValue === 0) return input.slice(0);\n var factor = maxValue / currentMaxValue;\n\n for (var _i = 0; _i < input.length; _i++) {\n output[_i] = input[_i] * factor;\n }\n\n return output;\n }\n\n case 'sum':\n {\n var sumFactor = sum(input) / sumValue;\n if (sumFactor === 0) return input.slice(0);\n\n for (var _i2 = 0; _i2 < input.length; _i2++) {\n output[_i2] = input[_i2] / sumFactor;\n }\n\n return output;\n }\n\n default:\n throw new Error(\"norm: unknown algorithm: \".concat(algorithm));\n }\n}\n\nfunction absoluteSum(input) {\n var sumValue = 0;\n\n for (var i = 0; i < input.length; i++) {\n sumValue += Math.abs(input[i]);\n }\n\n return sumValue;\n}\n\nexport default norm;\n","import isArray from 'is-any-array';\n\nfunction _typeof(obj) {\n \"@babel/helpers - typeof\";\n\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/**\r\n * Fill an array with sequential numbers\r\n * @param {Array} [input] - optional destination array (if not provided a new array will be created)\r\n * @param {object} [options={}]\r\n * @param {number} [options.from=0] - first value in the array\r\n * @param {number} [options.to=10] - last value in the array\r\n * @param {number} [options.size=input.length] - size of the array (if not provided calculated from step)\r\n * @param {number} [options.step] - if not provided calculated from size\r\n * @return {Array}\r\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 !== 0 && 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 // only works with normal array\n input.length = 0;\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","const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n","import isArray from 'is-any-array';\nimport arrayMean from 'ml-array-mean';\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","import variance from 'ml-array-variance';\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 { ascending, descending } 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, descending);\n } else {\n index = binarySearch(x, target, ascending);\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","import mean from 'ml-array-mean';\n\n/**\n *\n * @param {object} points\n * @param {Array} points.x\n * @param {Array} points.y\n * @param {object} [options]\n * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n.\n * @return {number}\n */\nexport default function covariance(points, options = {}) {\n const { x, y } = points;\n const { unbiased = true } = options;\n\n const meanX = mean(x);\n const meanY = mean(y);\n\n var error = 0;\n\n for (let i = 0; i < x.length; i++) {\n error += (x[i] - meanX) * (y[i] - meanY);\n }\n\n if (unbiased) {\n return error / (x.length - 1);\n } else {\n return error / x.length;\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 { ascending, descending } 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, descending);\n } else {\n index = binarySearch(x, value, ascending);\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","/**\n * Normalize an array of zones:\n * - ensure than from < to\n * - merge overlapping zones\n *\n * The method will always check if from if lower than to and will swap if required.\n * @param {Array} [zones=[]]\n * @param {object} [options={}]\n * @param {number} [options.from=Number.NEGATIVE_INFINITY] Specify min value of a zone\n * @param {number} [options.to=Number.POSITIVE_INFINITY] Specify max value of a zone\n */\n\nexport function normalize(zones = [], options = {}) {\n if (zones.length === 0) return [];\n let {\n from = Number.NEGATIVE_INFINITY,\n to = Number.POSITIVE_INFINITY,\n } = options;\n if (from > to) [from, to] = [to, from];\n\n zones = JSON.parse(JSON.stringify(zones)).map((zone) =>\n zone.from > zone.to ? { from: zone.to, to: zone.from } : zone,\n );\n zones = zones.sort((a, b) => {\n if (a.from !== b.from) return a.from - b.from;\n return a.to - b.to;\n });\n\n zones.forEach((zone) => {\n if (from > zone.from) zone.from = from;\n if (to < zone.to) zone.to = to;\n });\n\n zones = zones.filter((zone) => zone.from <= zone.to);\n if (zones.length === 0) return [];\n\n let currentZone = zones[0];\n let result = [currentZone];\n for (let i = 1; i < zones.length; i++) {\n let zone = zones[i];\n if (zone.from <= currentZone.to) {\n currentZone.to = zone.to;\n } else {\n currentZone = zone;\n result.push(currentZone);\n }\n }\n return result;\n}\n","import { normalize } from './normalize';\n\n/**\n * Convert an array of exclusions and keep only from / to\n *\n * The method will always check if from if lower than to and will swap if required.\n * @param {Array} [exclusions=[]]\n * @param {object} [options={}]\n * @param {number} [options.from=Number.NEGATIVE_INFINITY] Specify min value of zones (after inversion)\n * @param {number} [options.to=Number.POSITIVE_INFINITY] Specify max value of zones (after inversion)\n */\n\nexport function invert(exclusions = [], options = {}) {\n let {\n from = Number.NEGATIVE_INFINITY,\n to = Number.POSITIVE_INFINITY,\n } = options;\n if (from > to) [from, to] = [to, from];\n\n exclusions = normalize(exclusions, { from, to });\n if (exclusions.length === 0) return [{ from, to }];\n\n let zones = [];\n for (let i = 0; i < exclusions.length; i++) {\n let exclusion = exclusions[i];\n let nextExclusion = exclusions[i + 1];\n if (i === 0) {\n if (exclusion.from > from) {\n zones.push({ from, to: exclusion.from });\n }\n }\n if (i === exclusions.length - 1) {\n if (exclusion.to < to) {\n zones.push({ from: exclusion.to, to });\n }\n } else {\n zones.push({ from: exclusion.to, to: nextExclusion.from });\n }\n }\n\n return zones;\n}\n","import { normalize } from './normalize';\n\n/**\n * Add the number of points per zone to reach a specified total\n * @param {Array} [zones=[]]\n * @param {number} [numberOfPoints] Total number of points to distribute between zones\n * @param {object} [options={}]\n * @param {number} [options.from=Number.NEGATIVE_INFINITY] Specify min value of a zone\n * @param {number} [options.to=Number.POSITIVE_INFINITY] Specify max value of a zone\n */\n\nexport function zonesWithPoints(zones, numberOfPoints, options = {}) {\n if (zones.length === 0) return zones;\n zones = normalize(zones, options);\n\n const totalSize = zones.reduce((previous, current) => {\n return previous + (current.to - current.from);\n }, 0);\n\n let unitsPerPoint = totalSize / numberOfPoints;\n let currentTotal = 0;\n for (let i = 0; i < zones.length - 1; i++) {\n let zone = zones[i];\n zone.numberOfPoints = Math.min(\n Math.round((zone.to - zone.from) / unitsPerPoint),\n numberOfPoints - currentTotal,\n );\n currentTotal += zone.numberOfPoints;\n }\n\n zones[zones.length - 1].numberOfPoints = numberOfPoints - currentTotal;\n\n return zones;\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 {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 let xLength = x.length;\n\n let step = (to - from) / (numberOfPoints - 1);\n let halfStep = step / 2;\n\n let output = new Array(numberOfPoints);\n\n let initialOriginalStep = x[1] - x[0];\n let lastOriginalStep = x[xLength - 1] - x[xLength - 2];\n\n // Init main variables\n let min = from - halfStep;\n let max = from + halfStep;\n\n let previousX = Number.MIN_VALUE;\n let previousY = 0;\n let nextX = x[0] - initialOriginalStep;\n let nextY = 0;\n\n let currentValue = 0;\n let slope = 0;\n let intercept = 0;\n let sumAtMin = 0;\n let sumAtMax = 0;\n\n let i = 0; // index of input\n let j = 0; // index of output\n\n function getSlope(x0, y0, x1, y1) {\n return (y1 - y0) / (x1 - x0);\n }\n\n let add = 0;\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 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 let xLength = x.length;\n\n let step = (to - from) / (numberOfPoints - 1);\n let halfStep = step / 2;\n let lastStep = x[x.length - 1] - x[x.length - 2];\n\n let start = from - halfStep;\n let output = new Array(numberOfPoints);\n\n // Init main variables\n let min = start;\n let max = start + step;\n\n let previousX = -Number.MAX_VALUE;\n let previousY = 0;\n let nextX = x[0];\n let nextY = y[0];\n let frontOutsideSpectra = 0;\n let backOutsideSpectra = true;\n\n let currentValue = 0;\n\n // for slot algorithm\n let currentPoints = 0;\n\n let i = 1; // index of input\n let 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 sequentialFill from 'ml-array-sequential-fill';\nimport { zonesWithPoints, invert } from 'ml-zones';\n\nimport equallySpacedSmooth from './equallySpacedSmooth';\nimport equallySpacedSlot from './equallySpacedSlot';\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 * If exclusions zone are present, zones are ignored !\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 * @param {Array} [options.zones=[]] array of from / to that should be kept\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 zones = [],\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 if (numberOfPoints < 2) {\n throw new RangeError(\"'numberOfPoints' option must be greater than 1\");\n }\n\n if (zones.length === 0) {\n zones = invert(exclusions, { from, to });\n }\n\n zones = zonesWithPoints(zones, numberOfPoints, { from, to });\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\n xResult = xResult.concat(zoneResult.x);\n yResult = yResult.concat(zoneResult.y);\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 let 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, 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","import { DecisionTreeClassifier, DecisionTreeRegression } from \"ml-cart\";\nimport {\n RandomForestClassifier,\n RandomForestRegression\n} from \"ml-random-forest\";\n\n// Try to keep this list in the same structure as the README.\n\n// Unsupervised learning\nexport { PCA } from \"ml-pca\";\nimport * as HClust from \"ml-hclust\";\nexport { HClust };\nexport { default as KMeans } from \"ml-kmeans\";\n\n// Supervised learning\nimport * as NaiveBayes from \"ml-naivebayes\";\nexport { NaiveBayes };\nexport { default as KNN } from \"ml-knn\";\nexport { PLS, KOPLS, OPLS, OPLSNipals } from \"ml-pls\";\nimport * as CrossValidation from \"ml-cross-validation\";\nexport { CrossValidation };\nexport { default as ConfusionMatrix } from \"ml-confusion-matrix\";\nexport { DecisionTreeClassifier };\nexport { RandomForestClassifier };\n\n// Artificial neural networks\nexport { default as FNN } from \"ml-fnn\";\nexport { default as SOM } from \"ml-som\";\n\n// Regression\nexport {\n SimpleLinearRegression,\n PolynomialRegression,\n MultivariateLinearRegression,\n PowerRegression,\n ExponentialRegression,\n TheilSenRegression,\n RobustPolynomialRegression\n} from \"ml-regression\";\nexport { DecisionTreeRegression };\nexport { RandomForestRegression };\n\n// Optimization\nexport { default as levenbergMarquardt } from \"ml-levenberg-marquardt\";\nimport * as FCNNLS from \"ml-fcnnls\";\nexport { FCNNLS };\n\n// Math\nimport * as MatrixLib from \"ml-matrix\";\nconst {\n Matrix,\n SVD,\n EVD,\n CholeskyDecomposition,\n LuDecomposition,\n QrDecomposition\n} = MatrixLib;\nexport {\n MatrixLib,\n Matrix,\n SVD,\n EVD,\n CholeskyDecomposition,\n LuDecomposition,\n QrDecomposition\n};\n\nexport { SparseMatrix } from \"ml-sparse-matrix\";\nexport { default as Kernel } from \"ml-kernel\";\nimport { distance, similarity } from \"ml-distance\";\nexport { distance as Distance, similarity as Similarity };\nexport { default as distanceMatrix } from \"ml-distance-matrix\";\nexport { default as XSadd } from \"ml-xsadd\";\n\n// Statistics\nexport { default as Performance } from \"ml-performance\";\n\n// Data preprocessing\nexport { default as savitzkyGolay } from \"ml-savitzky-golay\";\n\n// Utility\nexport { default as BitArray } from \"ml-bit-array\";\nexport { default as HashTable } from \"ml-hash-table\";\nexport { default as padArray } from \"ml-pad-array\";\nexport { default as binarySearch } from \"binary-search\";\nimport * as numSort from \"num-sort\";\nexport { numSort };\nexport { default as Random } from \"ml-random\";\nimport * as GSD from 'ml-gsd';\nexport { GSD };\n\nimport min from \"ml-array-min\";\nimport max from \"ml-array-max\";\nimport median from \"ml-array-median\";\nimport mean from \"ml-array-mean\";\nimport mode from \"ml-array-mode\";\nimport normed from \"ml-array-normed\";\nimport rescale from \"ml-array-rescale\";\nimport sequentialFill from \"ml-array-sequential-fill\";\nimport sum from \"ml-array-sum\";\nimport standardDeviation from \"ml-array-standard-deviation\";\nimport variance from \"ml-array-variance\";\nexport const Array = {\n min,\n max,\n median,\n mean,\n mode,\n normed,\n rescale,\n sequentialFill,\n standardDeviation,\n sum,\n variance\n};\n\nimport centroidsMerge from \"ml-array-xy-centroids-merge\";\nimport closestX from \"ml-arrayxy-closestx\";\nimport covariance from \"ml-array-xy-covariance\";\nimport maxMerge from \"ml-array-xy-max-merge\";\nimport maxY from \"ml-array-xy-max-y\";\nimport sortX from \"ml-array-xy-sort-x\";\nimport uniqueX from \"ml-arrayxy-uniquex\";\nimport weightedMerge from \"ml-array-xy-weighted-merge\";\nimport equallySpaced from \"ml-array-xy-equally-spaced\";\nimport filterX from \"ml-array-xy-filter-x\";\nexport const ArrayXY = {\n centroidsMerge,\n closestX,\n covariance,\n maxMerge,\n maxY,\n sortX,\n uniqueX,\n weightedMerge,\n equallySpaced,\n filterX\n};\n"],"names":["toString","Object","prototype","isAnyArray","object","call","endsWith","max","input","options","arguments","length","undefined","isArray","TypeError","_options$fromIndex","fromIndex","_options$toIndex","toIndex","Number","isInteger","Error","maxValue","i","min","minValue","rescale","output","Array","currentMin","currentMax","RangeError","_options$min","autoMinMax","_options$max","factor","indent","repeat","indentData","inspectMatrix","inspectMatrixWithOptions","matrix","maxRows","maxColumns","maxNumSize","constructor","name","inspectData","rows","columns","maxI","Math","maxJ","result","line","j","push","formatNumber","get","join","num","numStr","String","padEnd","precise","toPrecision","exponential","toExponential","eIndex","indexOf","e","slice","installMathOperations","AbstractMatrix","Matrix","add","value","addS","addM","set","checkMatrix","newMatrix","sub","subS","subM","subtract","subtractS","subtractM","mul","mulS","mulM","multiply","multiplyS","multiplyM","div","divS","divM","divide","divideS","divideM","mod","modS","modM","modulus","modulusS","modulusM","and","andS","andM","or","orS","orM","xor","xorS","xorM","leftShift","leftShiftS","leftShiftM","signPropagatingRightShift","signPropagatingRightShiftS","signPropagatingRightShiftM","rightShift","rightShiftS","rightShiftM","zeroFillRightShift","zeroFillRightShiftS","zeroFillRightShiftM","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","pow","arg0","powS","powM","checkRowIndex","index","outer","checkColumnIndex","checkRowVector","vector","to1DArray","checkColumnVector","checkIndices","rowIndices","columnIndices","row","checkRowIndices","column","checkColumnIndices","rowOut","some","r","from","columnOut","c","checkRange","startRow","endRow","startColumn","endColumn","checkNumber","newArray","array","sumByRow","sum","sumByColumn","sumAll","v","productByRow","productByColumn","productAll","varianceByRow","unbiased","mean","cols","variance","sum1","sum2","x","varianceByColumn","varianceAll","size","centerByRow","centerByColumn","centerAll","getScaleByRow","scale","scaleByRow","getScaleByColumn","scaleByColumn","getScaleAll","divider","scaleAll","from1DArray","newRows","newColumns","newData","rowVector","columnVector","zeros","ones","fill","rand","random","randInt","interval","eye","diag","data","l","matrix1","matrix2","isMatrix","klass","apply","callback","to2DArray","copy","toJSON","isRowVector","isColumnVector","isVector","isSquare","isSymmetric","isEchelonForm","previousColumn","checked","isReducedEchelonForm","k","echelonForm","clone","h","iMax","swapRows","tmp","reducedEchelonForm","m","n","maxRow","p","pivot","setSubMatrix","neg","getRow","getRowVector","setRow","row1","row2","temp","getColumn","getColumnVector","setColumn","swapColumns","column1","column2","addRowVector","subRowVector","mulRowVector","divRowVector","addColumnVector","subColumnVector","mulColumnVector","divColumnVector","mulRow","mulColumn","maxIndex","idx","minIndex","maxRowIndex","minRow","minRowIndex","maxColumn","maxColumnIndex","minColumn","minColumnIndex","norm","type","cumulativeSum","dot","vector2","vector1","mmul","other","Bcolj","Float64Array","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","y","r1","c1","r2","c2","console","warn","embed","mat","resultat","blockMult","a","b","halfRows","parseInt","halfCols","subMatrix","scaleRows","isFinite","scaleColumns","flipRows","middle","first","last","flipColumns","kroneckerProduct","q","transpose","sortRows","compareFunction","compareNumbers","sort","sortColumns","subMatrixRow","indices","subMatrixColumn","selection","rowIndex","columnIndex","trace","by","product","standardDeviation","center","Symbol","for","randomInt","diagonal","identity","negate","tensorProduct","nRows","nColumns","arrayData","removeRow","splice","addRow","removeColumn","newRow","addColumn","BaseView","MatrixColumnView","MatrixColumnSelectionView","MatrixFlipColumnView","MatrixFlipRowView","MatrixRowView","MatrixRowSelectionView","MatrixSelectionView","MatrixSubView","MatrixTransposeView","WrapperMatrix1D","_calculateIndex","WrapperMatrix2D","wrap","LuDecomposition","lu","pivotVector","pivotSign","t","LUcolj","kmax","LU","isSingular","col","solve","count","X","determinant","lowerTriangularMatrix","upperTriangularMatrix","pivotPermutationVector","hypotenuse","QrDecomposition","qr","rdiag","nrm","QR","Rdiag","isFullRank","orthogonalMatrix","SingularValueDecomposition","computeLeftSingularVectors","computeRightSingularVectors","autoTranspose","wantu","Boolean","wantv","swapped","aux","nu","ni","U","V","work","si","nct","nrt","mrc","pp","eps","EPSILON","kase","alpha","MIN_VALUE","isNaN","ks","f","cs","sn","sp","spm1","epm1","sk","ek","shift","g","Y","threshold","scols","Ls","rightSingularVectors","VL","vrows","urows","VLU","solveForDiagonal","inverse","vcols","ucols","condition","norm2","rank","tol","ii","leftSingularVectors","diagonalMatrix","useSVD","leftHandSide","rightHandSide","d","subMatrix0","subMatrix1","subMatrix2","xrange","exception","range","dependenciesOneRow","error","thresholdValue","thresholdError","returnArray","linearDependencies","results","Abis","svd","pseudoInverse","svdSolution","SVD","covariance","xMatrix","yMatrix","yIsSame","cov","correlation","sdx","sdy","corr","EigenvalueDecomposition","assumeSymmetric","tred2","tql2","H","ort","orthes","hqr2","realEigenvalues","imaginaryEigenvalues","eigenvectorMatrix","hh","dl1","c3","el1","s2","tst1","low","high","nn","exshift","z","iter","w","ra","sa","vr","vi","notlast","cdivres","cdiv","xr","xi","yr","yi","CholeskyDecomposition","dimension","positiveDefinite","L","isPositiveDefinite","B","nipals","scaleScores","maxIterations","terminationCriteria","u","diff","tOld","counter","xResidual","residual","yResidual","betas","sumValue","toDiscreteDistribution","numberOfClasses","counts","giniImpurity","probabilities","getNumberOfClasses","filter","val","arr","map","reduce","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","Infinity","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","load","DecisionTreeRegression","trainingValues","checkFloat","examplesBaggingWithReplacement","trainingValue","seed","engine","Random","autoSeed","Xr","featureBagging","replacement","toRet","usedIndex","Set","has","RandomForestBase","maxFeatures","nEstimators","treeOptions","isClassifier","indexes","useSampleBagging","Estimator","DTClassifier","DTRegression","estimators","est","res","values","predictionValues","RandomForestClassifier","baseModel","mode","pop","_ref","module","exports","window","median","quickSelectMedian","selectionMethods","arrayMean","arrayMedian","selectionMethod","RandomForestRegression","PCA","dataset","means","stdevs","S","R","excludedFeatures","isCovarianceMatrix","method","nCompNIPALS","ignoreZeroVariance","_computeFromCovarianceMatrix","_adjust","covarianceMatrix","_computeWithNIPALS","singularValues","eigenvalues","singularValue","nComponents","invert","getExplainedVariance","getCumulativeVariance","explained","getEigenvectors","getEigenvalues","getStandardDeviations","getLoadings","evd","EVD","reverse","dc","NIPALS","squaredEuclidean","euclidean","distanceMatrix","distanceFn","getMatrix","Heap","defaultCmp","heapify","heappop","heappush","heappushpop","heapreplace","insort","nlargest","nsmallest","updateItem","_siftdown","_siftup","lo","hi","cmp","mid","concat","item","lastelt","returnitem","_i","_len","_ref1","_results","_results1","_j","pos","elem","los","startpos","newitem","parent","parentpos","childpos","endpos","rightpos","replace","pushpop","nodes","peek","contains","clear","empty","heap","toArray","insert","top","front","factory","this","require$$0","Cluster","children","height","isLeaf","cut","list","ans","group","groups","forEach","child","traverse","cb","visit","cluster","singleLink","dKI","dKJ","completeLink","averageLink","dIJ","nj","ai","aj","weightedAverageLink","centroidLink","medianLink","wardLink","nk","wardLink2","agnes","distanceFunction","isDistanceMatrix","updateFunc","getDistanceMatrix","numLeaves","toLowerCase","clusters","distance","getSmallestDistance","cluster1","cluster2","newCluster","newClusters","newDistanceMatrix","previous","newIndex","getPreviousIndex","prevI","prevICluster","smallest","smallestI","smallestJ","prev1","prev2","nearestVector","listVectors","similarityFunction","vectorIndex","maxSim","sim","minDist","MAX_VALUE","dist","calculateDistanceMatrix","updateClusterID","centers","clusterID","updateCenters","prevCenters","K","nDim","centersLen","dim","id","hasConverged","oldCenters","tolerance","LOOP","FLOAT_MUL","sh1","sh2","sh3","multiply_uint32","nlo","nhi","XSadd","Date","now","state","Uint32Array","init","getFloat","bind","getUint32","nextState","periodCertification","PROB_TOLERANCE","randomChoice","valuesArr","cumSum","getArray","randomIndex","seedOrRandom","xsadd","XSAdd","randomGenerator","choice","randomSample","mostDistant","maxDist","minDistCent","kmeanspp","nSamples","localTrials","firstCenterIdx","closestDistSquared","cumSumClosestDistSquared","candidateIdx","candidates","distanceToCandidates","euclideanDistances","bestCandidate","bestPot","bestDistSquared","newDistSquared","newPot","A","distanceSymbol","KMeansResult","centroids","converged","iterations","nearest","centroid","computeInformation","enrichedCentroids","withIterations","initialization","step","newCenters","kmeansGenerator","stepNumber","stepResult","kmeans","separateClasses","features","classes","totalPerClasses","separatedClasses","currentIndex","GaussianNB","reload","calculateProbabilities","C1","PI","std","logPriorProbability","currentStd","getCurrentClass","modelName","currentCase","maxProbability","predictedClass","currentProbability","calculateLogProbability","C2","MultinomialNB","conditionalProbability","priorProbability","separateClass","classValues","total","divisor","matrixLog","Node","obj","KDTree","points","metric","dimensions","restoreParent","buildTree","toJSONImpl","point","maxNodes","maxDistance","bestNodes","BinaryHeap","nearestSearch","ownDistance","linearPoint","bestChild","linearDistance","otherChild","saveNode","content","src","dest","depth","scoreFunction","element","bubbleUp","end","sinkDown","parentN","elemScore","child2N","child1N","swap","child1","child1Score","child2","child2Score","KNN","labels","kdTree","isEuclidean","euclideanDistance","getSinglePrediction","knn","nearestPoints","pointsPerClass","maxPoints","lastElement","currentClass","currentPoints","pow2array","initializeMatrices","PLS","meanX","stdDevX","meanY","stdDevY","PBQ","R2X","scaleMethod","latentVectors","rx","cx","ry","cy","ssqXcal","sumOfSquaresY","T","P","Q","W","transposeX","transposeY","tIndex","maxSumColIndex","uIndex","t1","den","pnorm","ssqYcal","E","F","KOPLS","YLoadingMat","SigmaPow","YScoreMat","predScoreMat","YOrthLoadingVec","YOrthEigen","YOrthScoreMat","toNorm","TURegressionCoeff","kernelX","kernel","orthogonalComp","predictiveComp","predictiveComponents","orthogonalComponents","compute","Identity","Sigma","YOrthScoreNorm","TpiPrime","CoTemp","SoTemp","toiPrime","ITo","lastScoreMat","lastTpPrime","KTestTrain","YOrthScoreVector","scoreMatPrime","p1","p2","p3","prediction","predYOrthVectors","ConfusionMatrix","fromLabels","actual","predicted","distinctLabels","actualIdx","predictedIdx","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","global","createCommonjsModule","fn","runtime","Op","hasOwn","hasOwnProperty","$Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","regeneratorRuntime","innerFn","outerFn","self","tryLocsList","protoGenerator","Generator","generator","create","context","Context","_invoke","makeInvokeMethod","tryCatch","arg","err","GenStateSuspendedStart","GenStateSuspendedYield","GenStateExecuting","GenStateCompleted","ContinueSentinel","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","getProto","getPrototypeOf","NativeIteratorPrototype","Gp","displayName","defineIteratorMethods","isGeneratorFunction","genFun","ctor","mark","setPrototypeOf","__proto__","awrap","__await","AsyncIterator","invoke","resolve","reject","record","Promise","then","unwrapped","previousPromise","enqueue","callInvokeWithMethodAndArg","async","next","done","doneResult","delegate","delegateResult","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","return","info","resultName","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","resetTryEntry","completion","reset","keys","key","iterable","iteratorMethod","skipTempReset","prev","charAt","stop","rootEntry","rootRecord","rval","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","thrown","delegateYield","Function","hadRuntime","getOwnPropertyNames","oldRuntime","runtimeModule","regenerator","_callee","M","N","twiddle","_callee$","_context","getFolds","allIdx","current","folds","randi","foldsIndex","testIndex","trainIndex","el","idx2","sampleAClass","classVector","fraction","classVectorSorted","JSON","parse","stringify","indexOfSelected","ind","mask","includes","leaveOneOut","Classifier","classifierOptions","leavePOut","distinct","getDistinct","confusionMatrix","initMatrix","gen","combinations","testIdx","trainIdx","validateWithCallback","validate","kFold","testFeatures","trainFeatures","testLabels","trainLabels","getTrainTest","classifier","predictedLabels","updateConfusionMatrix","OPLSNipals","numberOSC","uNew","wOrtho","tOrtho","pOrtho","filteredX","weightsXOrtho","loadingsXOrtho","scoresXOrtho","weightsXPred","loadingsXpred","scoresXpred","loadingsY","tss","OPLS","opls","meansY","stdevsY","tCV","tOrthCV","yHatCV","nComp","cvFolds","Q2","oplsCV","modelNC","nc","yHatk","tPredk","tOrthk","oplsk","fold","trainTest","_getTrainTest","testXk","Xk","Yk","dataCenter","dataSD","plsCV","Eh","scores","tPred","yHat","tssy","press","Q2y","_predictAll","xRes","XOrth","FeaturesCS","labelsCS","Xres","plsCall","R2x","R2y","plsC","pPred","wPred","betasPred","Qpc","tOrth","pOrth","wOrth","totalPred","Yres","getLogs","getScores","scoresX","scoresY","trueLabels","tssx","oplsC","rss","xEx","rssx","logistic","expELU","param","softExponential","softExponentialPrime","ACTIVATION_FUNCTIONS","activation","derivate","arctan","softsign","relu","softplus","bent","sinusoid","sinc","gaussian","Layer","inputSize","outputSize","regularization","epsilon","activationParam","selectedFunction","params","actFunction","derFunction","activationFunction","mlMatrix","forward","backpropagation","delta","dW","db","aCopy","update","OutputLayer","FeedForwardNeuralNetworks","hiddenLayers","learningRate","dicts","layers","buildNetwork","dictOutputs","inputs","propagate","outputs","NodeSquare","weights","som","neighbors","adjustWeights","target","influence","getDistance","otherNode","getDistanceTorus","distX","distY","gridDim","getNeighbors","xy","torus","getPos","bestNeighbor","direction","dist1","dist2","simA","simB","getPosition","NodeHexagonal","hX","getDistanceHexagonal","distZ","fields","randomizer","squareEuclidean","gridType","SOM","numWeights","converters","getConverters","extractor","creator","nodeType","hx","distanceMethod","getMaxDistance","times","findBMU","adjust","iterationCount","startLearningRate","mapRadius","algorithmMethod","_initNodes","loadModel","eval","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","_predict","getQuantizationError","fit","getFit","normalizers","denormalizers","getNormalizer","getDenormalizer","minMax","normalizer","denormalizer","zero","one","maybeToPrecision","digits","checkArraySize","BaseRegression","new","toLaTeX","score","y2","xSum","ySum","chi2","rmsd","xSquared","ySquared","xY","PolynomialRegression","degree","powers","coefficients","checkArrayLength","regress","precision","_toFormula","isLaTeX","sup","closeSup","str","json","pr","FT","SimpleLinearRegression","slope","intercept","computeX","xFactor","absIntercept","operator","slr","numerator","ExponentialRegression","er","yl","linear","PowerRegression","newInputs","latex","xl","MultivariateLinearRegression","statistics","xt","xx","invxx","beta","fittedValues","residuals","ri","stdError","stdErrorMatrix","stdErrors","tStats","summary","regressionStatistics","standardError","observations","variables","tStat","sigma","GaussianKernel","constant","PolynomialKernel","SigmoidKernel","ANOVAKernel","len","CauchyKernel","ExponentialKernel","HistogramIntersectionKernel","LaplacianKernel","MultiquadraticKernel","RationalQuadraticKernel","kernelType","rbf","polynomial","poly","anova","cauchy","histogram","HistogramKernel","laplacian","multiquadratic","rational","RationalKernel","sigmoid","mlp","Kernel","KernelConstructor","kernelFunction","landmarks","kernelMatrix","TheilSenRegression","theilSen","slopes","medianSlope","cuts","RobustPolynomialRegression","robustPolynomial","_","tuples","getRandomTuples","tuple","calcCoefficients","residualsMedian","half","errorCalculation","parameters","parameterizedFunction","func","gradientFunction","evaluatedData","gradientDifference","paramFunction","auxParams","funcParam","matrixFunction","damping","gradientFunc","matrixFunc","inverseMatrix","levenbergMarquardt","errorTolerance","minValues","maxValues","initialValues","parLen","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","iteration","parameterValues","parameterError","sortCollectionSet","collection","objectCollection","BigInt","sorted","cssls","XtX","XtY","Pset","choXtX","luXtX","sortedPset","sortedEset","cols2Solve","vars","initialisation","Fset","D","setDifference","C","optimality","maxIter","Jset","fullSet","notPset","fcnnls","infeasIndex","Hset","hRowColIdx","negRowColIdx","alphaMin","minIdx","idx2zero","findIndex","newParam","fcnnlsVector","haystack","needle","comparator","assertNumber","number","largestPrime","primeNumbers","ascending","nextPrime","binarySearch","FREE","FULL","REMOVED","defaultInitialCapacity","defaultMinLoadFactor","defaultMaxLoadFactor","HashTable","table","minLoadFactor","maxLoadFactor","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","SparseMatrix","_init","elements","symmetric","forEachNonZero","bandWidth","isBanded","width","cardinality","v1","v2","getNonZeros","setThreshold","newThreshold","trans","inplaceOperator","inplaceOperatorScalar","inplaceOperatorMatrix","staticOperator","inplaceMethod","staticMethod","operators","fillTemplateFunction","op","methods","mathMethod","template","RegExp","additiveSymmetric","avg","bhattacharyya","canberra","chebyshev","clark","czekanowskiSimilarity","up","down","czekanowskiDistance","dice","q1","q2","divergence","fidelity","gower","harmonicMean","hellinger","innerProduct","intersection","jaccard","jeffreys","jensenDifference","jensenShannon","kdivergence","kulczynski","kullbackLeibler","kumarHassebrook","kumarJohnson","lorentzian","manhattan","matusita","minkowski","motyka","neyman","pearson","probabilisticSymmetric","ruzicka","soergel","sorensen","squared","squaredChord","taneja","tanimoto","bitvector","inter","union","tanimotoS","topsoe","waveHedges","createTree","spectrum","minWindow","to","mainCreateTree","start","getSimilarity","gamma","treeSimilarity","getFunction","cosine","diceD","intersectionD","jaccardD","kulczynskiD","motykaD","avgA","avgB","newA","newB","squaredChordD","pred","cutoffs","tn","tp","fp","nNeg","nPos","nPosPred","nNegPred","Performance","isDistance","predP","all","targ","currentPred","nTp","nFp","getMeasure","measure","measures","getAURC","auc","getAUDC","getDistribution","cutLength","cutLow","cutHigh","xLabels","interValues","intraValues","interCumPercent","intraCumPercent","nTP","currentTP","nFP","currentFP","thisTP","thisFP","names","acc","fpr","tpr","fnr","tnr","ppv","npv","pcfall","pcmiss","lift","rpp","rnp","arrayCase","cond","matrixCase","padArray","factorial","windowSize","derivative","pad","padValue","savitzkyGolay","J","inic","Jtranspose","Jinv","det","eightBits","arr1","arr2","getBit","setBit","toBinaryString","substr","parseBinaryString","toHexString","parseHexString","toDebug","binary","SavitzkyGolay","np","fullWeights","hs","constantH","wg1","wg2","d1","d2","getHs","wg","GramPoly","Grampoly","GenFact","gf","Weight","gsd","yIn","noiseLevel","sgOptions","smoothY","heightFactor","broadRatio","maxCriteria","minMaxRatio","derivativeThreshold","realTopDetection","equalSpaced","isEqualSpaced","getNoiseLevel","yCorrection","yData","dY","ddY","SG","xData","dX","maxDdy","maxY","lastMax","lastMin","minddY","intervalL","intervalR","broadMask","minddYLen","intervalLLen","intervalRLen","broadMaskLen","signals","signalsLen","lastK","possible","frequency","distanceJ","minDistance","gettingCloser","soft","yLeft","yRight","determineRealTop","base","maxDx","minDx","stddev","averageDeviations","peakList","currentPoint","sumOfGaussians","nL","optimizeGaussianSum","opts","pInit","pMin","pMax","dt","lmOptions","pFit","LM","singleGaussian","factor2","optimizeSingleGaussian","peak","sumOfLorentzians","optimizeLorentzianSum","singleLorentzian","optimizeSingleLorentzian","optimizePeaks","functionName","factorWidth","optimizationOptions","lastIndex","groupPeaks","sampling","peaks","sampleFunction","limits","optPeaks","fitResult","nbPoints","sampleX","sampleY","upperLimit","lowerLimit","joinBroadPeaks","broadLines","fitted","broadenPeaks","overlap","nextPeak","maxCount","_options$algorithm","algorithm","_options$sumValue","_options$maxValue","absoluteSumValue","absoluteSum","currentMaxValue","sumFactor","_i2","_typeof","sequentialFill","_options","_options$from","_options$to","_options$size","_options$unbiased","_options$mean","sqrError","mergeByCentroids","originalPoints","mergedPoints","originalIndex","mergedIndex","closestX","descending","maxMerge","groupWidth","merged","maxAbscissa","calculateIndex","sortX","sortFunc","grouped","response","uniqueX","weightedMerge","weightedAbscissa","normalize","zones","NEGATIVE_INFINITY","POSITIVE_INFINITY","zone","currentZone","exclusions","exclusion","nextExclusion","zonesWithPoints","numberOfPoints","totalSize","unitsPerPoint","currentTotal","integral","x0","x1","equallySpacedSmooth","xLength","halfStep","initialOriginalStep","lastOriginalStep","previousX","previousY","nextX","nextY","currentValue","sumAtMin","sumAtMax","getSlope","y0","y1","main","equallySpacedSlot","lastStep","frontOutsideSpectra","backOutsideSpectra","equallySpaced","arrayXY","variant","xResult","yResult","zoneResult","processZone","getZones","currentFrom","filterX","currentZoneIndex","newX","newY","position","MatrixLib","normed","ArrayXY","centroidsMerge"],"mappings":";;;;;;;;;;;;EAAA,MAAMA,QAAQ,GAAGC,MAAM,CAACC,SAAP,CAAiBF,QAAlC;EAEe,SAASG,UAAT,CAAoBC,MAApB,EAA4B;EACzC,SAAOJ,QAAQ,CAACK,IAAT,CAAcD,MAAd,EAAsBE,QAAtB,CAA+B,QAA/B,CAAP;EACD;;ECFD,SAASC,GAAT,CAAaC,KAAb,EAAoB;EAClB,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EAKrBlG,EAAAA,IALqB;EAMrBuG,EAAAA,KANqB;EAOrBI,EAAAA,OAPqB;EAQrBC,EAAAA,aARqB;EASrBuC,EAAAA,aATqB;EAUrBS,EAAAA;EAVqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/dist/ml.min.js b/dist/ml.min.js index 875774c..58ae0db 100644 --- a/dist/ml.min.js +++ b/dist/ml.min.js @@ -1,4 +1,4 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).ML={})}(this,(function(exports){"use strict";const toString=Object.prototype.toString;function isAnyArray(t){return toString.call(t).endsWith("Array]")}var src=isAnyArray;function max(t){if(!src(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");for(var e=t[0],r=1;re&&(e=t[r]);return e}function min(t){if(!src(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");for(var e=t[0],r=1;r1&&void 0!==arguments[1]?arguments[1]:{};if(!src(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(!src(r.output))throw new TypeError("output option must be an array if specified");e=r.output}else e=new Array(t.length);var i=min(t),n=max(t);if(i===n)throw new RangeError("minimum and maximum input values are equal. Cannot rescale a constant array");var s=r.min,o=void 0===s?r.autoMinMax?i:0:s,a=r.max,h=void 0===a?r.autoMinMax?n:1:a;if(o>=h)throw new RangeError("min option must be smaller than max option");for(var l=(h-o)/(n-i),u=0;ui)throw new RangeError("Row index out of range")}function checkColumnIndex(t,e,r){let i=r?t.columns:t.columns-1;if(e<0||e>i)throw new RangeError("Column index out of range")}function checkRowVector(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 checkColumnVector(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 checkIndices(t,e,r){return{row:checkRowIndices(t,e),column:checkColumnIndices(t,r)}}function checkRowIndices(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 checkColumnIndices(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 checkRange(t,e,r,i,n){if(5!==arguments.length)throw new RangeError("expected 4 arguments");if(checkNumber("startRow",e),checkNumber("endRow",r),checkNumber("startColumn",i),checkNumber("endColumn",n),e>r||i>n||e<0||e>=t.rows||r<0||r>=t.rows||i<0||i>=t.columns||n<0||n>=t.columns)throw new RangeError("Submatrix indices are out of range")}function newArray(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=[];for(let i=0;i>t);return this},t.prototype.signPropagatingRightShiftM=function(t){if(t=e.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let e=0;e>t.get(e,r));return this},t.signPropagatingRightShift=function(t,r){return new e(t).signPropagatingRightShift(r)},t.prototype.rightShift=function(t){return"number"==typeof t?this.rightShiftS(t):this.rightShiftM(t)},t.prototype.rightShiftS=function(t){for(let e=0;e>>t);return this},t.prototype.rightShiftM=function(t){if(t=e.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let e=0;e>>t.get(e,r));return this},t.rightShift=function(t,r){return new e(t).rightShift(r)},t.prototype.zeroFillRightShift=t.prototype.rightShift,t.prototype.zeroFillRightShiftS=t.prototype.rightShiftS,t.prototype.zeroFillRightShiftM=t.prototype.rightShiftM,t.zeroFillRightShift=t.rightShift,t.prototype.not=function(){for(let t=0;t2&&void 0!==arguments[2]?arguments[2]:{};if("object"!=typeof r)throw new TypeError("options must be an object");const{random:i=Math.random}=r;let n=new Matrix(t,e);for(let r=0;r2&&void 0!==arguments[2]?arguments[2]:{};if("object"!=typeof r)throw new TypeError("options must be an object");const{min:i=0,max:n=1e3,random:s=Math.random}=r;if(!Number.isInteger(i))throw new TypeError("min must be an integer");if(!Number.isInteger(n))throw new TypeError("max must be an integer");if(i>=n)throw new RangeError("min must be smaller than max");let o=n-i,a=new Matrix(t,e);for(let r=0;rr?(n=!0,r=e):(i=!1,n=!0);t++}return i}isReducedEchelonForm(){let t=0,e=0,r=-1,i=!0,n=!1;for(;tr?(n=!0,r=e):(i=!1,n=!0);for(let r=e+1;rt.get(i,r)&&(i=n);if(0===t.get(i,r))r++;else{t.swapRows(e,i);let n=t.get(e,r);for(let i=r;i=0;)if(0===t.maxRow(i))i--;else{let n=0,s=!1;for(;n0&&void 0!==arguments[0]?arguments[0]:{};if("object"!=typeof t)throw new TypeError("options must be an object");const{rows:e=1,columns:r=1}=t;if(!Number.isInteger(e)||e<=0)throw new TypeError("rows must be a positive integer");if(!Number.isInteger(r)||r<=0)throw new TypeError("columns must be a positive integer");let i=new Matrix(this.rows*e,this.columns*r);for(let t=0;tt&&(t=this.get(e,r));return t}maxIndex(){let t=this.get(0,0),e=[0,0];for(let r=0;rt&&(t=this.get(r,i),e[0]=r,e[1]=i);return e}min(){let t=this.get(0,0);for(let e=0;ee&&(e=this.get(t,r));return e}maxRowIndex(t){checkRowIndex(this,t);let e=this.get(t,0),r=[t,0];for(let i=1;ie&&(e=this.get(t,i),r[1]=i);return r}minRow(t){checkRowIndex(this,t);let e=this.get(t,0);for(let r=1;re&&(e=this.get(r,t));return e}maxColumnIndex(t){checkColumnIndex(this,t);let e=this.get(0,t),r=[0,t];for(let i=1;ie&&(e=this.get(i,t),r[0]=i);return r}minColumn(t){checkColumnIndex(this,t);let e=this.get(0,t);for(let r=1;r0&&void 0!==arguments[0]?arguments[0]:"frobenius",e=0;if("max"===t)return this.max();if("frobenius"===t){for(let t=0;t0&&void 0!==arguments[0]?arguments[0]:{};if("object"!=typeof t)throw new TypeError("options must be an object");const{min:e=0,max:r=1}=t;if(!Number.isFinite(e))throw new TypeError("min must be a number");if(!Number.isFinite(r))throw new TypeError("max must be a number");if(e>=r)throw new RangeError("min must be smaller than max");let i=new Matrix(this.rows,this.columns);for(let t=0;t0&&void 0!==arguments[0]?arguments[0]:{};if("object"!=typeof t)throw new TypeError("options must be an object");const{min:e=0,max:r=1}=t;if(!Number.isFinite(e))throw new TypeError("min must be a number");if(!Number.isFinite(r))throw new TypeError("max must be a number");if(e>=r)throw new RangeError("min must be smaller than max");let i=new Matrix(this.rows,this.columns);for(let t=0;t0&&void 0!==arguments[0]?arguments[0]:compareNumbers;for(let e=0;e0&&void 0!==arguments[0]?arguments[0]:compareNumbers;for(let e=0;er||e<0||e>=this.columns||r<0||r>=this.columns)throw new RangeError("Argument out of range");let i=new Matrix(t.length,r-e+1);for(let n=0;n=this.rows)throw new RangeError("Row index out of range: ".concat(t[n]));i.set(n,s-e,this.get(t[n],s))}return i}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");let i=new Matrix(r-e+1,t.length);for(let n=0;n=this.columns)throw new RangeError("Column index out of range: ".concat(t[n]));i.set(s-e,n,this.get(s,t[n]))}return i}setSubMatrix(t,e,r){checkRange(this,e,e+(t=Matrix.checkMatrix(t)).rows-1,r,r+t.columns-1);for(let i=0;i1&&void 0!==arguments[1]?arguments[1]:{};if("object"==typeof t&&(e=t,t=void 0),"object"!=typeof e)throw new TypeError("options must be an object");const{unbiased:r=!0,mean:i=this.mean(t)}=e;if("boolean"!=typeof r)throw new TypeError("unbiased must be a boolean");switch(t){case"row":if(!Array.isArray(i))throw new TypeError("mean must be an array");return varianceByRow(this,r,i);case"column":if(!Array.isArray(i))throw new TypeError("mean must be an array");return varianceByColumn(this,r,i);case void 0:if("number"!=typeof i)throw new TypeError("mean must be a number");return varianceAll(this,r,i);default:throw new Error("invalid option: ".concat(t))}}standardDeviation(t,e){"object"==typeof t&&(e=t,t=void 0);const r=this.variance(t,e);if(void 0===t)return Math.sqrt(r);for(let t=0;t1&&void 0!==arguments[1]?arguments[1]:{};if("object"==typeof t&&(e=t,t=void 0),"object"!=typeof e)throw new TypeError("options must be an object");const{center:r=this.mean(t)}=e;switch(t){case"row":if(!Array.isArray(r))throw new TypeError("center must be an array");return centerByRow(this,r),this;case"column":if(!Array.isArray(r))throw new TypeError("center must be an array");return centerByColumn(this,r),this;case void 0:if("number"!=typeof r)throw new TypeError("center must be a number");return centerAll(this,r),this;default:throw new Error("invalid option: ".concat(t))}}scale(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("object"==typeof t&&(e=t,t=void 0),"object"!=typeof e)throw new TypeError("options must be an object");let r=e.scale;switch(t){case"row":if(void 0===r)r=getScaleByRow(this);else if(!Array.isArray(r))throw new TypeError("scale must be an array");return scaleByRow(this,r),this;case"column":if(void 0===r)r=getScaleByColumn(this);else if(!Array.isArray(r))throw new TypeError("scale must be an array");return scaleByColumn(this,r),this;case void 0:if(void 0===r)r=getScaleAll(this);else if("number"!=typeof r)throw new TypeError("scale must be a number");return scaleAll(this,r),this;default:throw new Error("invalid option: ".concat(t))}}}function compareNumbers(t,e){return t-e}AbstractMatrix.prototype.klass="Matrix","undefined"!=typeof Symbol&&(AbstractMatrix.prototype[Symbol.for("nodejs.util.inspect.custom")]=inspectMatrix),AbstractMatrix.random=AbstractMatrix.rand,AbstractMatrix.randomInt=AbstractMatrix.randInt,AbstractMatrix.diagonal=AbstractMatrix.diag,AbstractMatrix.prototype.diagonal=AbstractMatrix.prototype.diag,AbstractMatrix.identity=AbstractMatrix.eye,AbstractMatrix.prototype.negate=AbstractMatrix.prototype.neg,AbstractMatrix.prototype.tensorProduct=AbstractMatrix.prototype.kroneckerProduct;class Matrix extends AbstractMatrix{constructor(t,e){if(super(),Matrix.isMatrix(t))return t.clone();if(Number.isInteger(t)&&t>0){if(this.data=[],!(Number.isInteger(e)&&e>0))throw new TypeError("nColumns must be a positive integer");for(let 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){let i=this._calculateIndex(t,e);return this.data[i]=r,this}get(t,e){let r=this._calculateIndex(t,e);return this.data[r]}_calculateIndex(t,e){return t*this.columns+e}}class WrapperMatrix2D extends AbstractMatrix{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]}}function wrap(t,e){if(Array.isArray(t))return t[0]&&Array.isArray(t[0])?new WrapperMatrix2D(t):new WrapperMatrix1D(t,e);throw new Error("the argument is not an array")}class LuDecomposition{constructor(t){let e,r,i,n,s,o,a,h,l,u=(t=WrapperMatrix2D.checkMatrix(t)).clone(),c=u.rows,f=u.columns,m=new Float64Array(c),g=1;for(e=0;eMath.abs(h[n])&&(n=e);if(n!==r){for(i=0;i=0;n--){for(i=0;ie?i.set(n,e,t.get(n,e)):n===e?i.set(n,e,1):i.set(n,e,0);return i}get upperTriangularMatrix(){let t=this.LU,e=t.rows,r=t.columns,i=new Matrix(e,r);for(let n=0;nMath.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}class QrDecomposition{constructor(t){let e,r,i,n,s=(t=WrapperMatrix2D.checkMatrix(t)).clone(),o=t.rows,a=t.columns,h=new Float64Array(a);for(i=0;i=0;s--){for(n=0;n=0;r--){for(t=0;t1&&void 0!==arguments[1]?arguments[1]:{},r=(t=WrapperMatrix2D.checkMatrix(t)).rows,i=t.columns;const{computeLeftSingularVectors:n=!0,computeRightSingularVectors:s=!0,autoTranspose:o=!1}=e;let a,h=Boolean(n),l=Boolean(s),u=!1;if(r=0;t--)if(0!==m[t]){for(let e=t+1;e=0;t--){if(t0;){let t,e;for(t=b-2;t>=-1&&-1!==t;t--){const e=Number.MIN_VALUE+A*Math.abs(m[t]+Math.abs(m[t+1]));if(Math.abs(p[t])<=e||Number.isNaN(p[t])){p[t]=0;break}}if(t===b-2)e=4;else{let r;for(r=b-1;r>=t&&r!==t;r--){let e=(r!==b?Math.abs(p[r]):0)+(r!==t+1?Math.abs(p[r-1]):0);if(Math.abs(m[r])<=A*e){m[r]=0;break}}r===t?e=3:r===b-1?e=1:(e=2,t=r)}switch(t++,e){case 1:{let e=p[b-2];p[b-2]=0;for(let r=b-2;r>=t;r--){let n=hypotenuse(m[r],e),s=m[r]/n,o=e/n;if(m[r]=n,r!==t&&(e=-o*p[r-1],p[r-1]=s*p[r-1]),l)for(let t=0;t=m[t+1]);){let e=m[t];if(m[t]=m[t+1],m[t+1]=e,l&&te&&n.set(s,r,t.get(s,r)/this.s[r]);let s=this.U,o=s.rows,a=s.columns,h=new Matrix(r,o);for(let t=0;tt&&e++;return e}get diagonal(){return Array.from(this.s)}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return this.U}get rightSingularVectors(){return this.V}get diagonalMatrix(){return Matrix.diag(this.s)}}function inverse(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return t=WrapperMatrix2D.checkMatrix(t),e?new SingularValueDecomposition(t).inverse():solve(t,Matrix.eye(t.rows))}function solve(t,e){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=WrapperMatrix2D.checkMatrix(t),e=WrapperMatrix2D.checkMatrix(e),r?new SingularValueDecomposition(t).solve(e):t.isSquare()?new LuDecomposition(t).solve(e):new QrDecomposition(t).solve(e)}function determinant(t){if((t=Matrix.checkMatrix(t)).isSquare()){let e,r,i,n;if(2===t.columns)return e=t.get(0,0),r=t.get(0,1),i=t.get(1,0),e*(n=t.get(1,1))-r*i;if(3===t.columns){let n,s,o;return n=new MatrixSelectionView(t,[1,2],[1,2]),s=new MatrixSelectionView(t,[1,2],[0,2]),o=new MatrixSelectionView(t,[1,2],[0,1]),e=t.get(0,0),r=t.get(0,1),i=t.get(0,2),e*determinant(n)-r*determinant(s)+i*determinant(o)}return new LuDecomposition(t).determinant}throw Error("determinant can only be calculated for a square matrix")}function xrange(t,e){let r=[];for(let i=0;i3&&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);{let t=e.addRow(r,[0]);for(let e=0;e1&&void 0!==arguments[1]?arguments[1]:{};const{thresholdValue:r=1e-9,thresholdError:i=1e-9}=e;let n=(t=Matrix.checkMatrix(t)).rows,s=new Matrix(n,n);for(let e=0;e1&&void 0!==arguments[1]?arguments[1]:Number.EPSILON;t=Matrix.checkMatrix(t);let r=new SingularValueDecomposition(t,{autoTranspose:!0}),i=r.leftSingularVectors,n=r.rightSingularVectors,s=r.diagonal;for(let t=0;te?s[t]=1/s[t]:s[t]=0;return n.mmul(Matrix.diag(s).mmul(i.transpose()))}function covariance(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};t=Matrix.checkMatrix(t);let i=!1;if("object"!=typeof e||Matrix.isMatrix(e)||Array.isArray(e)?e=Matrix.checkMatrix(e):(r=e,e=t,i=!0),t.rows!==e.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:n=!0}=r;n&&(t=t.center("column"),i||(e=e.center("column")));const s=t.transpose().mmul(e);for(let e=0;e1&&void 0!==arguments[1]?arguments[1]:t,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};t=Matrix.checkMatrix(t);let i=!1;if("object"!=typeof e||Matrix.isMatrix(e)||Array.isArray(e)?e=Matrix.checkMatrix(e):(r=e,e=t,i=!0),t.rows!==e.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:n=!0,scale:s=!0}=r;n&&(t.center("column"),i||e.center("column")),s&&(t.scale("column"),i||e.scale("column"));const o=t.standardDeviation("column",{unbiased:!0}),a=i?o:e.standardDeviation("column",{unbiased:!0}),h=t.transpose().mmul(e);for(let e=0;e1&&void 0!==arguments[1]?arguments[1]:{};const{assumeSymmetric:r=!1}=e;if(!(t=WrapperMatrix2D.checkMatrix(t)).isSquare())throw new Error("Matrix is not a square matrix");let i,n,s=t.columns,o=new Matrix(s,s),a=new Float64Array(s),h=new Float64Array(s),l=t,u=!1;if(u=!!r||t.isSymmetric()){for(i=0;i0?s.set(t,t+1,i[t]):i[t]<0&&s.set(t,t-1,i[t])}return s}}function tred2(t,e,r,i){let n,s,o,a,h,l,u,c;for(h=0;h0;a--){for(c=0,o=0,l=0;l0&&(s=-s),e[a]=c*s,o-=n*s,r[a-1]=n-s,h=0;hl)do{for(n=r[l],f=hypotenuse(c=(r[l+1]-n)/(2*e[l]),1),c<0&&(f=-f),r[l]=e[l]/(c+f),r[l+1]=e[l]*(c+f),m=r[l+1],s=n-r[l],o=l+2;o=l;o--)for(p=d,d=g,M=x,n=g*e[o],s=g*c,f=hypotenuse(c,e[o]),e[o+1]=x*f,x=e[o]/f,c=(g=c/f)*r[o]-x*n,r[o+1]=s+x*(g*n+x*r[o]),h=0;hb*v);r[l]=r[l]+y,e[l]=0}for(o=0;o=l;a--)r[a]=e.get(a,l-1)/u,o+=r[a]*r[a];for(s=Math.sqrt(o),r[l]>0&&(s=-s),o-=r[l]*s,r[l]=r[l]-s,h=l;h=l;a--)n+=r[a]*e.get(a,h);for(n/=o,a=l;a<=c;a++)e.set(a,h,e.get(a,h)-n*r[a])}for(a=0;a<=c;a++){for(n=0,h=c;h>=l;h--)n+=r[h]*e.get(a,h);for(n/=o,h=l;h<=c;h++)e.set(a,h,e.get(a,h)-n*r[h])}r[l]=u*r[l],e.set(l,l-1,u*s)}}for(a=0;a=1;l--)if(0!==e.get(l,l-1)){for(a=l+1;a<=c;a++)r[a]=e.get(a,l-1);for(h=l;h<=c;h++){for(s=0,a=l;a<=c;a++)s+=r[a]*i.get(a,h);for(s=s/r[l]/e.get(l,l-1),a=l;a<=c;a++)i.set(a,h,i.get(a,h)+s*r[a])}}}function hqr2(t,e,r,i,n){let s,o,a,h,l,u,c,f,m,g,d,p,w,x,M,y=t-1,v=t-1,b=Number.EPSILON,S=0,A=0,E=0,R=0,k=0,C=0,T=0,N=0;for(s=0;sv)&&(r[s]=n.get(s,s),e[s]=0),o=Math.max(s-1,0);o=0;){for(h=y;h>0&&(0===(C=Math.abs(n.get(h-1,h-1))+Math.abs(n.get(h,h)))&&(C=A),!(Math.abs(n.get(h,h-1))=0){for(T=E>=0?E+T:E-T,r[y-1]=f+T,r[y]=r[y-1],0!==T&&(r[y]=f-c/T),e[y-1]=0,e[y]=0,E=(f=n.get(y,y-1))/(C=Math.abs(f)+Math.abs(T)),R=T/C,E/=k=Math.sqrt(E*E+R*R),R/=k,o=y-1;o0){for(C=Math.sqrt(C),m=h&&(E=((k=f-(T=n.get(l,l)))*(C=m-T)-c)/n.get(l+1,l)+n.get(l,l+1),R=n.get(l+1,l+1)-T-k-C,k=n.get(l+2,l+1),E/=C=Math.abs(E)+Math.abs(R)+Math.abs(k),R/=C,k/=C,l!==h)&&!(Math.abs(n.get(l,l-1))*(Math.abs(R)+Math.abs(k))l+2&&n.set(s,s-3,0);for(a=l;a<=y-1&&(x=a!==y-1,a!==l&&(E=n.get(a,a-1),R=n.get(a+1,a-1),k=x?n.get(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(C=Math.sqrt(E*E+R*R+k*k),E<0&&(C=-C),0!==C){for(a!==l?n.set(a,a-1,-C*f):h!==l&&n.set(a,a-1,-n.get(a,a-1)),f=(E+=C)/C,m=R/C,T=k/C,R/=E,k/=E,o=a;o=0;y--)if(E=r[y],0===(R=e[y]))for(h=y,n.set(y,y,1),s=y-1;s>=0;s--){for(c=n.get(s,s)-E,k=0,o=h;o<=y;o++)k+=n.get(s,o)*n.get(o,y);if(e[s]<0)T=c,C=k;else if(h=s,0===e[s]?n.set(s,y,0!==c?-k/c:-k/(b*A)):(f=n.get(s,s+1),m=n.get(s+1,s),u=(f*C-T*k)/(R=(r[s]-E)*(r[s]-E)+e[s]*e[s]),n.set(s,y,u),n.set(s+1,y,Math.abs(f)>Math.abs(T)?(-k-c*u)/f:(-C-m*u)/T)),b*(u=Math.abs(n.get(s,y)))*u>1)for(o=s;o<=y;o++)n.set(o,y,n.get(o,y)/u)}else if(R<0)for(h=y-1,Math.abs(n.get(y,y-1))>Math.abs(n.get(y-1,y))?(n.set(y-1,y-1,R/n.get(y,y-1)),n.set(y-1,y,-(n.get(y,y)-E)/n.get(y,y-1))):(M=cdiv(0,-n.get(y-1,y),n.get(y-1,y-1)-E,R),n.set(y-1,y-1,M[0]),n.set(y-1,y,M[1])),n.set(y,y-1,0),n.set(y,y,1),s=y-2;s>=0;s--){for(g=0,d=0,o=h;o<=y;o++)g+=n.get(s,o)*n.get(o,y-1),d+=n.get(s,o)*n.get(o,y);if(c=n.get(s,s)-E,e[s]<0)T=c,k=g,C=d;else if(h=s,0===e[s]?(M=cdiv(-g,-d,c,R),n.set(s,y-1,M[0]),n.set(s,y,M[1])):(f=n.get(s,s+1),m=n.get(s+1,s),p=(r[s]-E)*(r[s]-E)+e[s]*e[s]-R*R,w=2*(r[s]-E)*R,0===p&&0===w&&(p=b*A*(Math.abs(c)+Math.abs(R)+Math.abs(f)+Math.abs(m)+Math.abs(T))),M=cdiv(f*k-T*g+R*d,f*C-T*d-R*g,p,w),n.set(s,y-1,M[0]),n.set(s,y,M[1]),Math.abs(f)>Math.abs(T)+Math.abs(R)?(n.set(s+1,y-1,(-g-c*n.get(s,y-1)+R*n.get(s,y))/f),n.set(s+1,y,(-d-c*n.get(s,y)-R*n.get(s,y-1))/f)):(M=cdiv(-k-m*n.get(s,y-1),-C-m*n.get(s,y),T,R),n.set(s+1,y-1,M[0]),n.set(s+1,y,M[1]))),b*(u=Math.max(Math.abs(n.get(s,y-1)),Math.abs(n.get(s,y))))*u>1)for(o=s;o<=y;o++)n.set(o,y-1,n.get(o,y-1)/u),n.set(o,y,n.get(o,y)/u)}for(s=0;sv)for(o=s;o=0;o--)for(s=0;s<=v;s++){for(T=0,a=0;a<=Math.min(o,v);a++)T+=i.get(s,a)*n.get(a,o);i.set(s,o,T)}}}function cdiv(t,e,r,i){let n,s;return Math.abs(r)>Math.abs(i)?[(t+(n=i/r)*e)/(s=r+n*i),(e-n*t)/s]:[((n=r/i)*t+e)/(s=i+n*r),(n*e-t)/s]}class CholeskyDecomposition{constructor(t){if(!(t=WrapperMatrix2D.checkMatrix(t)).isSymmetric())throw new Error("Matrix is not symmetric");let e,r,i,n=t,s=n.rows,o=new Matrix(s,s),a=!0;for(r=0;r0,o.set(r,r,Math.sqrt(Math.max(t,0))),i=r+1;i=0;s--)for(n=0;n1&&void 0!==arguments[1]?arguments[1]:{};t=WrapperMatrix2D.checkMatrix(t);let{Y:r}=e;const{scaleScores:i=!1,maxIterations:n=1e3,terminationCriteria:s=1e-10}=e;let o;if(r){if(!(r=Array.isArray(r)&&"number"==typeof r[0]?Matrix.columnVector(r):WrapperMatrix2D.checkMatrix(r)).isColumnVector()||r.rows!==t.rows)throw new Error("Y must be a column vector of length X.rows");o=r}else o=t.getColumnVector(0);let a,h,l,u,c=1;for(let e=0;es;e++)l=(l=t.transpose().mmul(o).div(o.transpose().mmul(o).get(0,0))).div(l.norm()),a=t.mmul(l).div(l.transpose().mmul(l).get(0,0)),e>0&&(c=a.clone().sub(u).pow(2).sum()),u=a.clone(),r?(h=(h=r.transpose().mmul(a).div(a.transpose().mmul(a).get(0,0))).div(h.norm()),o=r.mmul(h).div(h.transpose().mmul(h).get(0,0))):o=a;if(r){let e=t.transpose().mmul(a).div(a.transpose().mmul(a).get(0,0));e=e.div(e.norm());let i=t.clone().sub(a.clone().mmul(e.transpose())),n=o.transpose().mmul(a).div(a.transpose().mmul(a).get(0,0)),s=r.clone().sub(a.clone().mulS(n.get(0,0)).mmul(h.transpose()));this.t=a,this.p=e.transpose(),this.w=l.transpose(),this.q=h,this.u=o,this.s=a.transpose().mmul(a),this.xResidual=i,this.yResidual=s,this.betas=n}else this.w=l.transpose(),this.s=a.transpose().mmul(a).sqrt(),this.t=i?a.clone().div(this.s.get(0,0)):a,this.xResidual=t.sub(a.mmul(l.transpose()))}}var MatrixLib=Object.freeze({__proto__:null,AbstractMatrix:AbstractMatrix,default:Matrix,Matrix:Matrix,wrap:wrap,WrapperMatrix1D:WrapperMatrix1D,WrapperMatrix2D:WrapperMatrix2D,solve:solve,inverse:inverse,determinant:determinant,linearDependencies:linearDependencies,pseudoInverse:pseudoInverse,covariance:covariance,correlation:correlation,SingularValueDecomposition:SingularValueDecomposition,SVD:SingularValueDecomposition,EigenvalueDecomposition:EigenvalueDecomposition,EVD:EigenvalueDecomposition,CholeskyDecomposition:CholeskyDecomposition,CHO:CholeskyDecomposition,LuDecomposition:LuDecomposition,LU:LuDecomposition,QrDecomposition:QrDecomposition,QR:QrDecomposition,Nipals:nipals,NIPALS:nipals,MatrixColumnView:MatrixColumnView,MatrixColumnSelectionView:MatrixColumnSelectionView,MatrixFlipColumnView:MatrixFlipColumnView,MatrixFlipRowView:MatrixFlipRowView,MatrixRowView:MatrixRowView,MatrixRowSelectionView:MatrixRowSelectionView,MatrixSelectionView:MatrixSelectionView,MatrixSubView:MatrixSubView,MatrixTransposeView:MatrixTransposeView});function sum(t){if(!src(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");for(var e=0,r=0;rt+1).reduce((t,e)=>Math.max(t,e))}function giniGain(t,e){let r=0,i=["greater","lesser"];for(let n=0;nt>e:(t,e)=>t.01&&this.gain!==i&&o.lesserX.length>0&&o.greaterX.length>0){this.left=new TreeNode(this),this.right=new TreeNode(this);let t=new Matrix(o.lesserX),e=new Matrix(o.greaterX);this.left.train(t,o.lesserY,r+1,this.gain),this.right.train(e,o.greaterY,r+1,this.gain)}else this.calculatePrediction(e)}classify(t){return this.right&&this.left?t[this.splitColumn]>>0,UINT32_SIZE=UINT32_MAX+1,INT32_SIZE=UINT32_SIZE/2,INT32_MAX=INT32_SIZE-1,UINT21_SIZE=1<<21,UINT21_MAX=UINT21_SIZE-1;function int32(t){return 0|t.next()}function add(t,e){return 0===e?t:r=>t(r)+e}function int53(t){const e=0|t.next(),r=t.next()>>>0;return(e&UINT21_MAX)*UINT32_SIZE+r+(e&UINT21_SIZE?-SMALLEST_UNSAFE_INTEGER:0)}function int53Full(t){for(;;){const e=0|t.next();if(!(4194304&e)){const r=t.next()>>>0;return(e&UINT21_MAX)*UINT32_SIZE+r+(e&UINT21_SIZE?-SMALLEST_UNSAFE_INTEGER:0)}if(4194304==(8388607&e)&&0==(0|t.next()))return SMALLEST_UNSAFE_INTEGER}}function uint32(t){return t.next()>>>0}function uint53(t){const e=t.next()&UINT21_MAX,r=t.next()>>>0;return e*UINT32_SIZE+r}function uint53Full(t){for(;;){const e=0|t.next();if(!(e&UINT21_SIZE)){const r=t.next()>>>0;return(e&UINT21_MAX)*UINT32_SIZE+r}if(0==(e&UINT21_MAX)&&0==(0|t.next()))return SMALLEST_UNSAFE_INTEGER}}function isPowerOfTwoMinusOne(t){return 0==(t+1&t)}function bitmask(t){return e=>e.next()&t}function downscaleToLoopCheckedRange(t){const e=t+1,r=e*Math.floor(UINT32_SIZE/e);return t=>{let i=0;do{i=t.next()>>>0}while(i>=r);return i%e}}function downscaleToRange(t){return isPowerOfTwoMinusOne(t)?bitmask(t):downscaleToLoopCheckedRange(t)}function isEvenlyDivisibleByMaxInt32(t){return 0==(0|t)}function upscaleWithHighMasking(t){return e=>{const r=e.next()&t,i=e.next()>>>0;return r*UINT32_SIZE+i}}function upscaleToLoopCheckedRange(t){const e=t*Math.floor(SMALLEST_UNSAFE_INTEGER/t);return r=>{let i=0;do{const t=r.next()&UINT21_MAX,e=r.next()>>>0;i=t*UINT32_SIZE+e}while(i>=e);return i%t}}function upscaleWithinU53(t){const e=t+1;if(isEvenlyDivisibleByMaxInt32(e)){const t=(e/UINT32_SIZE|0)-1;if(isPowerOfTwoMinusOne(t))return upscaleWithHighMasking(t)}return upscaleToLoopCheckedRange(e)}function upscaleWithinI53AndLoopCheck(t,e){return r=>{let i=0;do{const t=0|r.next(),e=r.next()>>>0;i=(t&UINT21_MAX)*UINT32_SIZE+e+(t&UINT21_SIZE?-SMALLEST_UNSAFE_INTEGER:0)}while(ie);return i}}function integer(t,e){if(t=Math.floor(t),e=Math.floor(e),t<-SMALLEST_UNSAFE_INTEGER||!isFinite(t))throw new RangeError("Expected min to be at least ".concat(-SMALLEST_UNSAFE_INTEGER));if(e>SMALLEST_UNSAFE_INTEGER||!isFinite(e))throw new RangeError("Expected max to be at most ".concat(SMALLEST_UNSAFE_INTEGER));const r=e-t;return r<=0||!isFinite(r)?()=>t:r===UINT32_MAX?0===t?uint32:add(int32,t+INT32_SIZE):r0&&void 0!==arguments[0]?arguments[0]:DEFAULT_STRING_POOL;const e=t.length;if(!e)throw new Error("Expected pool not to be an empty string");const r=integer(0,e-1);return(e,i)=>{let n="";for(let s=0;s{try{if("xxx"==="x".repeat(3))return(t,e)=>t.repeat(e)}catch(t){}return(t,e)=>{let r="";for(;e>0;)1&e&&(r+=t),e>>=1,t+=t;return r}})(),nativeMath={next:()=>Math.random()*UINT32_SIZE|0},I32Array=(()=>{try{const t=new ArrayBuffer(4),e=new Int32Array(t);if(e[0]=INT32_SIZE,e[0]===-INT32_SIZE)return Int32Array}catch(t){}return Array})();function createEntropy(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nativeMath,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16;const r=[];r.push(0|(new Date).getTime());for(let i=1;i{try{if(-5===Math.imul(UINT32_MAX,5))return Math.imul}catch(t){}return(t,e)=>{const r=65535&t,i=65535&e;return r*i+((t>>>16&65535)*i+r*(e>>>16&65535)<<16>>>0)|0}})(),ARRAY_SIZE=624,ARRAY_MAX=ARRAY_SIZE-1,M=397,ARRAY_SIZE_MINUS_M=ARRAY_SIZE-M,A=2567483615;class MersenneTwister19937{constructor(){this.data=new I32Array(ARRAY_SIZE),this.index=0,this.uses=0}static seed(t){return(new MersenneTwister19937).seed(t)}static seedWithArray(t){return(new MersenneTwister19937).seedWithArray(t)}static autoSeed(){return MersenneTwister19937.seedWithArray(createEntropy())}next(){(0|this.index)>=ARRAY_SIZE&&(refreshData(this.data),this.index=0);const t=this.data[this.index];return this.index=this.index+1|0,this.uses+=1,0|temper(t)}getUseCount(){return this.uses}discard(t){if(t<=0)return this;for(this.uses+=t,(0|this.index)>=ARRAY_SIZE&&(refreshData(this.data),this.index=0);t+this.index>ARRAY_SIZE;)t-=ARRAY_SIZE-this.index,refreshData(this.data),this.index=0;return this.index=this.index+t|0,this}seed(t){let e=0;this.data[0]=e=0|t;for(let t=1;t>>30,1812433253)+t|0;return this.index=ARRAY_SIZE,this.uses=0,this}seedWithArray(t){return this.seed(19650218),seedWithArray(this.data,t),this}}function refreshData(t){let e=0,r=0;for(;(0|e)>>1^(1&r?A:0);for(;(0|e)>>1^(1&r?A:0);r=t[ARRAY_MAX]&INT32_SIZE|t[0]&INT32_MAX,t[ARRAY_MAX]=t[M-1]^r>>>1^(1&r?A:0)}function temper(t){return t^=t>>>11,t^=t<<7&2636928640,(t^=t<<15&4022730752)^t>>>18}function seedWithArray(t,e){let r=1,i=0;const n=e.length;let s=0|Math.max(n,ARRAY_SIZE),o=0|t[0];for(;(0|s)>0;--s)t[r]=o=(t[r]^imul(o^o>>>30,1664525))+(0|e[i])+(0|i)|0,++i,(0|(r=r+1|0))>ARRAY_MAX&&(t[0]=t[ARRAY_MAX],r=1),i>=n&&(i=0);for(s=ARRAY_MAX;(0|s)>0;--s)t[r]=o=(t[r]^imul(o^o>>>30,1566083941))-r|0,(0|(r=r+1|0))>ARRAY_MAX&&(t[0]=t[ARRAY_MAX],r=1);t[0]=INT32_SIZE}function checkFloat(t){return t>0&&t<=1}function examplesBaggingWithReplacement(t,e,r){let i,n=integer(0,t.rows-1);if(void 0===r)i=MersenneTwister19937.autoSeed();else{if(!Number.isInteger(r))throw new RangeError("Expected seed must be undefined or integer not ".concat(r));i=MersenneTwister19937.seed(r)}let s=new Array(t.rows),o=new Array(t.rows);for(let r=0;rt.load(e))}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=Matrix.checkMatrix(t),this.maxFeatures=this.maxFeatures||t.columns,checkFloat(this.maxFeatures))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}let r;r=this.isClassifier?DecisionTreeClassifier:DecisionTreeRegression,this.estimators=new Array(this.nEstimators),this.indexes=new Array(this.nEstimators);for(let i=0;it.toJSON()),useSampleBagging:this.useSampleBagging}}}const defaultOptions$2={maxFeatures:1,replacement:!0,nEstimators:10,seed:42,useSampleBagging:!1};class RandomForestClassifier extends RandomForestBase{constructor(t,e){!0===t?super(!0,e.baseModel):((t=Object.assign({},defaultOptions$2,t)).isClassifier=!0,super(t))}selection(t){return mode(t)}toJSON(){return{baseModel:super.toJSON(),name:"RFClassifier"}}static load(t){if("RFClassifier"!==t.name)throw new RangeError("Invalid model: ".concat(t.name));return new RandomForestClassifier(!0,t)}}function mode(t){return t.sort((e,r)=>t.filter(t=>t===e).length-t.filter(t=>t===r).length).pop()}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(t,e){return t(e={exports:{}},e.exports),e.exports}var medianQuickselect_min=createCommonjsModule((function(t){!function(){function e(t){for(var e=0,n=t.length-1,s=void 0,o=void 0,a=void 0,h=i(e,n);;){if(n<=e)return t[h];if(n==e+1)return t[e]>t[n]&&r(t,e,n),t[h];for(t[s=i(e,n)]>t[n]&&r(t,s,n),t[e]>t[n]&&r(t,e,n),t[s]>t[e]&&r(t,s,e),r(t,s,e+1),o=e+1,a=n;;){do{o++}while(t[e]>t[o]);do{a--}while(t[a]>t[e]);if(a=h&&(n=a-1)}}var r=function(t,e,r){var i;return i=[t[r],t[e]],t[e]=i[0],t[r]=i[1],i},i=function(t,e){return~~((t+e)/2)};t.exports?t.exports=e:window.median=e}()}));function median(t){if(!src(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");return medianQuickselect_min(t.slice())}const selectionMethods={mean:mean,median:median},defaultOptions$3={maxFeatures:1,replacement:!1,nEstimators:10,treeOptions:{},selectionMethod:"mean",seed:42,useSampleBagging:!1};class RandomForestRegression extends RandomForestBase{constructor(t,e){if(!0===t)super(!0,e.baseModel),this.selectionMethod=e.selectionMethod;else{if("mean"!==(t=Object.assign({},defaultOptions$3,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 selectionMethods[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 RandomForestRegression(!0,t)}}class PCA{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};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=Matrix.checkMatrix(t.U),this.S=t.S,this.R=t.R,void(this.excludedFeatures=t.excludedFeatures||[])}t=new Matrix(t);const{isCovarianceMatrix:r=!1,method:i="SVD",nCompNIPALS:n=2,center:s=!0,scale:o=!1,ignoreZeroVariance:a=!1}=e;if(this.center=s,this.scale=o,this.means=null,this.stdevs=null,this.excludedFeatures=[],r)this._computeFromCovarianceMatrix(t);else switch(this._adjust(t,a),i){case"covarianceMatrix":{const e=new MatrixTransposeView(t).mmul(t).div(t.rows-1);this._computeFromCovarianceMatrix(e);break}case"NIPALS":this._computeWithNIPALS(t,n);break;case"SVD":{const e=new SingularValueDecomposition(t,{computeLeftSingularVectors:!1,computeRightSingularVectors:!0,autoTranspose:!0});this.U=e.rightSingularVectors;const r=e.diagonal,i=[];for(const e of r)i.push(e*e/(t.rows-1));this.S=i;break}default:throw new Error("unknown method: ".concat(i))}}static load(t){if("string"!=typeof t.name)throw new TypeError("model must have a name property");if("PCA"!==t.name)throw new RangeError("invalid model: ".concat(t.name));return new PCA(!0,t)}predict(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{nComponents:r=this.U.columns}=e;if(t=new Matrix(t),this.center&&(t.subRowVector(this.means),this.scale)){for(let e of this.excludedFeatures)t.removeColumn(e);t.divRowVector(this.stdevs)}var i=t.mmul(this.U);return i.subMatrix(0,i.rows-1,0,r-1)}invert(t){var e=(t=Matrix.checkMatrix(t)).mmul(this.U.transpose());return this.center&&(this.scale&&e.mulRowVector(this.stdevs),e.addRowVector(this.means)),e}getExplainedVariance(){var t=0;for(const e of this.S)t+=e;return this.S.map(e=>e/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,excludedFeatures:this.excludedFeatures}}_adjust(t,e){if(this.center){const r=t.mean("column"),i=this.scale?t.standardDeviation("column",{mean:r}):null;if(this.means=r,t.subRowVector(r),this.scale){for(let r=0;re?1:0},l=function(t,e,n,s,o){var a;if(null==n&&(n=0),null==o&&(o=r),n<0)throw new Error("lo must be non-negative");for(null==s&&(s=t.length);nr;0<=r?e++:e--)l.push(e);return l}.apply(this).reverse()).length;sd;0<=d?++f:--f)p.push(s(t,i));return p},g=function(t,e,i,n){var s,o,a;for(null==n&&(n=r),s=t[i];i>e&&n(s,o=t[a=i-1>>1])<0;)t[i]=o,i=a;return t[i]=s},d=function(t,e,i){var n,s,o,a,h;for(null==i&&(i=r),s=t.length,h=e,o=t[e],n=2*e+1;n0;){const i=e.shift();t>=i.height?r.push(i):e=e.concat(i.children)}return r}group(t){if(!Number.isInteger(t)||t<1)throw new RangeError("groups must be a positive integer");const e=new heap$1((t,e)=>e.height-t.height);for(e.push(this);e.size()e.push(t))}var i=new Cluster;return i.children=e.toArray(),i.height=this.height,i}traverse(t){!function t(e,r){if(r(e),e.children)for(const i of e.children)t(i,r)}(this,t)}indices(){const t=[];return this.traverse(e=>{e.isLeaf&&t.push(e.index)}),t}}function singleLink(t,e){return Math.min(t,e)}function completeLink(t,e){return Math.max(t,e)}function averageLink(t,e,r,i,n){return i/(i+n)*t+n/(i+n)*e}function weightedAverageLink(t,e){return(t+e)/2}function centroidLink(t,e,r,i,n){return i/(i+n)*t+n/(i+n)*e+-i*n/(i+n)**2*r}function medianLink(t,e,r){return t/2+e/2-r/4}function wardLink(t,e,r,i,n,s){return(i+s)/(i+n+s)*t+(n+s)/(i+n+s)*e+-s/(i+n+s)*r}function wardLink2(t,e,r,i,n,s){const o=(i+s)/(i+n+s),a=(n+s)/(i+n+s),h=-s/(i+n+s);return Math.sqrt(o*t*t+a*e*e+h*r*r)}function agnes(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{distanceFunction:r=euclidean,method:i="complete",isDistanceMatrix:n=!1}=e;let s;n||(t=distanceMatrix(t,r));let o=new Matrix(t);const a=o.rows;if("string"==typeof i)switch(i.toLowerCase()){case"single":s=singleLink;break;case"complete":s=completeLink;break;case"average":case"upgma":s=averageLink;break;case"wpgma":s=weightedAverageLink;break;case"centroid":case"upgmc":s=centroidLink;break;case"median":case"wpgmc":s=medianLink;break;case"ward":s=wardLink;break;case"ward2":s=wardLink2;break;default:throw new RangeError("unknown clustering method: ".concat(i))}else if("function"!=typeof i)throw new TypeError("method must be a string or function");let h=[];for(let t=0;tgetPreviousIndex(r,Math.min(t,e),Math.max(t,e));for(let a=1;a=e&&t++,t>=r&&t++,t}var index=Object.freeze({__proto__:null,agnes:agnes});const defaultOptions$4={distanceFunction:squaredEuclidean};function nearestVector(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:defaultOptions$4;const i=r.distanceFunction||defaultOptions$4.distanceFunction,n=r.similarityFunction||defaultOptions$4.similarityFunction;let s=-1;if("function"==typeof n){let r=Number.MIN_VALUE;for(let i=0;ir&&(r=o,s=i)}}else{if("function"!=typeof i)throw new Error("A similarity or distance function it's required");{let r=Number.MAX_VALUE;for(let n=0;ni)return!1;return!0}const LOOP=8,FLOAT_MUL=1/16777216,sh1=15,sh2=18,sh3=11;function multiply_uint32(t,e){const r=65535&(t>>>=0);return((t-r)*(e>>>=0)>>>0)+r*e>>>0}class XSadd{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)*FLOAT_MUL}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>>sh2,t^=this.state[3]<1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Math.random;const{size:i=1,replace:n=!1,probabilities:s}=e;let o,a;if(o="number"==typeof t?getArray(t):t.slice(),s){if(!n)throw new Error("choice with probabilities and no replacement is not implemented");if(s.length!==o.length)throw new Error("the length of probabilities option should be equal to the number of choices");a=[s[0]];for(let t=1;tPROB_TOLERANCE)throw new Error("probabilities should sum to 1, but instead sums to ".concat(a[a.length-1]))}if(!1===n&&i>o.length)throw new Error("size option is too large");const h=[];for(let t=0;tr[t];)t++;return t}return Math.floor(i*t)}class Random{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Math.random;if("number"==typeof t){const e=new XSadd(t);this.randomGenerator=e.random}else this.randomGenerator=t}choice(t,e){return randomChoice(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;r1){for(var o={dist:-1,index:-1},a=0;ao.dist&&(o.dist=r[s[0]][a],o.index=a);if(s[1]=o.index,e>2)for(var h=2;hl.dist&&(l=Object.assign({},c))}s[h]=l.index}}return s.map(e=>t[e])}function kmeanspp(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const i=(t=new Matrix(t)).rows,n=new Random(r.seed),s=[],o=r.localTrials||2+Math.floor(Math.log(e)),a=n.randInt(i);s.push(t.getRow(a));let h=new Matrix(1,t.rows);for(let e=0;et.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=kmeanspp(t,e,r);break;case"random":i=random(t,e,r.seed);break;case"mostDistant":i=mostDistant(t,e,calculateDistanceMatrix(t,r.distanceFunction),r.seed);break;default:throw new Error('Unknown initialization method: "'.concat(r.initialization,'"'))}0===r.maxIterations&&(r.maxIterations=Number.MAX_VALUE);var n=new Array(t.length);if(r.withIterations)return kmeansGenerator(i,t,n,e,r);for(var s,o=!1,a=0;!o&&ai&&(i=o,n=s)}return n}function calculateLogProbability(t,e,r,i){return t-=e,Math.log(r*Math.exp(t*t/i))}class MultinomialNB{constructor(t){t&&(this.conditionalProbability=Matrix.checkMatrix(t.conditionalProbability),this.priorProbability=Matrix.checkMatrix(t.priorProbability))}train(t,e){if((t=Matrix.checkMatrix(t)).rows!==e.length)throw new RangeError("the size of the training set and the training labels must be the same.");var r=separateClasses(t,e);this.priorProbability=new Matrix(r.length,1);for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:{};if(!isAnyArray(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");var r=e.fromIndex,n=void 0===r?0:r,i=e.toIndex,o=void 0===i?t.length:i;if(n<0||n>=t.length||!Number.isInteger(n))throw new Error("fromIndex must be a positive integer smaller than length");if(o<=n||o>t.length||!Number.isInteger(o))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var s=t[n],a=n+1;as&&(s=t[a]);return s}function min(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!isAnyArray(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");var r=e.fromIndex,n=void 0===r?0:r,i=e.toIndex,o=void 0===i?t.length:i;if(n<0||n>=t.length||!Number.isInteger(n))throw new Error("fromIndex must be a positive integer smaller than length");if(o<=n||o>t.length||!Number.isInteger(o))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var s=t[n],a=n+1;a1&&void 0!==arguments[1]?arguments[1]:{};if(!isAnyArray(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(!isAnyArray(r.output))throw new TypeError("output option must be an array if specified");e=r.output}else e=new Array(t.length);var n=min(t),i=max(t);if(n===i)throw new RangeError("minimum and maximum input values are equal. Cannot rescale a constant array");var o=r.min,s=void 0===o?r.autoMinMax?n:0:o,a=r.max,l=void 0===a?r.autoMinMax?i:1:a;if(s>=l)throw new RangeError("min option must be smaller than max option");for(var h=(l-s)/(i-n),u=0;u>t);return this},t.prototype.signPropagatingRightShiftM=function(t){if(t=e.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let e=0;e>t.get(e,r));return this},t.signPropagatingRightShift=function(t,r){return new e(t).signPropagatingRightShift(r)},t.prototype.rightShift=function(t){return"number"==typeof t?this.rightShiftS(t):this.rightShiftM(t)},t.prototype.rightShiftS=function(t){for(let e=0;e>>t);return this},t.prototype.rightShiftM=function(t){if(t=e.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let e=0;e>>t.get(e,r));return this},t.rightShift=function(t,r){return new e(t).rightShift(r)},t.prototype.zeroFillRightShift=t.prototype.rightShift,t.prototype.zeroFillRightShiftS=t.prototype.rightShiftS,t.prototype.zeroFillRightShiftM=t.prototype.rightShiftM,t.zeroFillRightShift=t.rightShift,t.prototype.not=function(){for(let t=0;tn)throw new RangeError("Row index out of range")}function checkColumnIndex(t,e,r){let n=r?t.columns:t.columns-1;if(e<0||e>n)throw new RangeError("Column index out of range")}function checkRowVector(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 checkColumnVector(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 checkIndices(t,e,r){return{row:checkRowIndices(t,e),column:checkColumnIndices(t,r)}}function checkRowIndices(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 checkColumnIndices(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 checkRange(t,e,r,n,i){if(5!==arguments.length)throw new RangeError("expected 4 arguments");if(checkNumber("startRow",e),checkNumber("endRow",r),checkNumber("startColumn",n),checkNumber("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 newArray(t,e=0){let r=[];for(let n=0;n=i)throw new RangeError("min must be smaller than max");let s=i-n,a=new Matrix(t,e);for(let r=0;rr?(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.get(n,r)&&(n=i);if(0===t.get(n,r))r++;else{t.swapRows(e,n);let i=t.get(e,r);for(let n=r;n=0;)if(0===t.maxRow(n))n--;else{let i=0,o=!1;for(;it&&(t=this.get(e,r));return t}maxIndex(){let t=this.get(0,0),e=[0,0];for(let r=0;rt&&(t=this.get(r,n),e[0]=r,e[1]=n);return e}min(){let t=this.get(0,0);for(let e=0;ee&&(e=this.get(t,r));return e}maxRowIndex(t){checkRowIndex(this,t);let e=this.get(t,0),r=[t,0];for(let n=1;ne&&(e=this.get(t,n),r[1]=n);return r}minRow(t){checkRowIndex(this,t);let e=this.get(t,0);for(let r=1;re&&(e=this.get(r,t));return e}maxColumnIndex(t){checkColumnIndex(this,t);let e=this.get(0,t),r=[0,t];for(let n=1;ne&&(e=this.get(n,t),r[0]=n);return r}minColumn(t){checkColumnIndex(this,t);let e=this.get(0,t);for(let r=1;r=r)throw new RangeError("min must be smaller than max");let n=new Matrix(this.rows,this.columns);for(let t=0;t=r)throw new RangeError("min must be smaller than max");let n=new Matrix(this.rows,this.columns);for(let t=0;tr||e<0||e>=this.columns||r<0||r>=this.columns)throw new RangeError("Argument out of range");let n=new Matrix(t.length,r-e+1);for(let i=0;i=this.rows)throw new RangeError("Row index out of range: "+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");let n=new Matrix(r-e+1,t.length);for(let i=0;i=this.columns)throw new RangeError("Column index out of range: "+t[i]);n.set(o-e,i,this.get(o,t[i]))}return n}setSubMatrix(t,e,r){checkRange(this,e,e+(t=Matrix.checkMatrix(t)).rows-1,r,r+t.columns-1);for(let n=0;n0){if(this.data=[],!(Number.isInteger(e)&&e>0))throw new TypeError("nColumns must be a positive integer");for(let r=0;rMath.abs(l[i])&&(i=e);if(i!==r){for(n=0;n=0;i--){for(n=0;ne?n.set(i,e,t.get(i,e)):i===e?n.set(i,e,1):n.set(i,e,0);return n}get upperTriangularMatrix(){let t=this.LU,e=t.rows,r=t.columns,n=new Matrix(e,r);for(let 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}class QrDecomposition{constructor(t){let e,r,n,i,o=(t=WrapperMatrix2D.checkMatrix(t)).clone(),s=t.rows,a=t.columns,l=new Float64Array(a);for(n=0;n=0;o--){for(i=0;i=0;r--){for(t=0;t=0;t--)if(0!==m[t]){for(let e=t+1;e=0;t--){if(t0;){let t,e;for(t=b-2;t>=-1&&-1!==t;t--){const e=Number.MIN_VALUE+A*Math.abs(m[t]+Math.abs(m[t+1]));if(Math.abs(d[t])<=e||Number.isNaN(d[t])){d[t]=0;break}}if(t===b-2)e=4;else{let r;for(r=b-1;r>=t&&r!==t;r--){let e=(r!==b?Math.abs(d[r]):0)+(r!==t+1?Math.abs(d[r-1]):0);if(Math.abs(m[r])<=A*e){m[r]=0;break}}r===t?e=3:r===b-1?e=1:(e=2,t=r)}switch(t++,e){case 1:{let e=d[b-2];d[b-2]=0;for(let r=b-2;r>=t;r--){let i=hypotenuse(m[r],e),o=m[r]/i,s=e/i;if(m[r]=i,r!==t&&(e=-s*d[r-1],d[r-1]=o*d[r-1]),h)for(let t=0;t=m[t+1]);){let e=m[t];if(m[t]=m[t+1],m[t+1]=e,h&&te&&i.set(o,r,t.get(o,r)/this.s[r]);let o=this.U,s=o.rows,a=o.columns,l=new Matrix(r,s);for(let t=0;tt&&e++;return e}get diagonal(){return Array.from(this.s)}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return this.U}get rightSingularVectors(){return this.V}get diagonalMatrix(){return Matrix.diag(this.s)}}function inverse(t,e=!1){return t=WrapperMatrix2D.checkMatrix(t),e?new SingularValueDecomposition(t).inverse():solve(t,Matrix.eye(t.rows))}function solve(t,e,r=!1){return t=WrapperMatrix2D.checkMatrix(t),e=WrapperMatrix2D.checkMatrix(e),r?new SingularValueDecomposition(t).solve(e):t.isSquare()?new LuDecomposition(t).solve(e):new QrDecomposition(t).solve(e)}function determinant(t){if((t=Matrix.checkMatrix(t)).isSquare()){let e,r,n,i;if(2===t.columns)return e=t.get(0,0),r=t.get(0,1),n=t.get(1,0),i=t.get(1,1),e*i-r*n;if(3===t.columns){let i,o,s;return i=new MatrixSelectionView(t,[1,2],[1,2]),o=new MatrixSelectionView(t,[1,2],[0,2]),s=new MatrixSelectionView(t,[1,2],[0,1]),e=t.get(0,0),r=t.get(0,1),n=t.get(0,2),e*determinant(i)-r*determinant(o)+n*determinant(s)}return new LuDecomposition(t).determinant}throw Error("determinant can only be calculated for a square matrix")}function xrange(t,e){let r=[];for(let n=0;ni)return new Array(e.rows+1).fill(0);{let t=e.addRow(r,[0]);for(let e=0;ee?o[t]=1/o[t]:o[t]=0;return i.mmul(Matrix.diag(o).mmul(n.transpose()))}function covariance(t,e=t,r={}){t=new Matrix(t);let n=!1;if("object"!=typeof e||Matrix.isMatrix(e)||Array.isArray(e)?e=new Matrix(e):(r=e,e=t,n=!0),t.rows!==e.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:i=!0}=r;i&&(t=t.center("column"),n||(e=e.center("column")));const o=t.transpose().mmul(e);for(let e=0;e0?o.set(t,t+1,n[t]):n[t]<0&&o.set(t,t-1,n[t])}return o}}function tred2(t,e,r,n){let i,o,s,a,l,h,u,c;for(l=0;l0;a--){for(c=0,s=0,h=0;h0&&(o=-o),e[a]=c*o,s-=i*o,r[a-1]=i-o,l=0;lh)do{for(i=r[h],c=(r[h+1]-i)/(2*e[h]),f=hypotenuse(c,1),c<0&&(f=-f),r[h]=e[h]/(c+f),r[h+1]=e[h]*(c+f),m=r[h+1],o=i-r[h],s=h+2;s=h;s--)for(d=p,p=g,x=y,i=g*e[s],o=g*c,f=hypotenuse(c,e[s]),e[s+1]=y*f,y=e[s]/f,g=c/f,c=g*r[s]-y*i,r[s+1]=o+y*(g*i+y*r[s]),l=0;lb*v);r[h]=r[h]+M,e[h]=0}for(s=0;s=h;a--)r[a]=e.get(a,h-1)/u,s+=r[a]*r[a];for(o=Math.sqrt(s),r[h]>0&&(o=-o),s-=r[h]*o,r[h]=r[h]-o,l=h;l=h;a--)i+=r[a]*e.get(a,l);for(i/=s,a=h;a<=c;a++)e.set(a,l,e.get(a,l)-i*r[a])}for(a=0;a<=c;a++){for(i=0,l=c;l>=h;l--)i+=r[l]*e.get(a,l);for(i/=s,l=h;l<=c;l++)e.set(a,l,e.get(a,l)-i*r[l])}r[h]=u*r[h],e.set(h,h-1,u*o)}}for(a=0;a=1;h--)if(0!==e.get(h,h-1)){for(a=h+1;a<=c;a++)r[a]=e.get(a,h-1);for(l=h;l<=c;l++){for(o=0,a=h;a<=c;a++)o+=r[a]*n.get(a,l);for(o=o/r[h]/e.get(h,h-1),a=h;a<=c;a++)n.set(a,l,n.get(a,l)+o*r[a])}}}function hqr2(t,e,r,n,i){let o,s,a,l,h,u,c,f,m,g,p,d,w,y,x,M=t-1,v=t-1,b=Number.EPSILON,S=0,A=0,E=0,R=0,k=0,N=0,T=0,C=0;for(o=0;ov)&&(r[o]=i.get(o,o),e[o]=0),s=Math.max(o-1,0);s=0;){for(l=M;l>0&&(N=Math.abs(i.get(l-1,l-1))+Math.abs(i.get(l,l)),0===N&&(N=A),!(Math.abs(i.get(l,l-1))=0){for(T=E>=0?E+T:E-T,r[M-1]=f+T,r[M]=r[M-1],0!==T&&(r[M]=f-c/T),e[M-1]=0,e[M]=0,f=i.get(M,M-1),N=Math.abs(f)+Math.abs(T),E=f/N,R=T/N,k=Math.sqrt(E*E+R*R),E/=k,R/=k,s=M-1;s0)){for(N=Math.sqrt(N),m=l&&(T=i.get(h,h),k=f-T,N=m-T,E=(k*N-c)/i.get(h+1,h)+i.get(h,h+1),R=i.get(h+1,h+1)-T-k-N,k=i.get(h+2,h+1),N=Math.abs(E)+Math.abs(R)+Math.abs(k),E/=N,R/=N,k/=N,h!==l)&&!(Math.abs(i.get(h,h-1))*(Math.abs(R)+Math.abs(k))h+2&&i.set(o,o-3,0);for(a=h;a<=M-1&&(y=a!==M-1,a!==h&&(E=i.get(a,a-1),R=i.get(a+1,a-1),k=y?i.get(a+2,a-1):0,f=Math.abs(E)+Math.abs(R)+Math.abs(k),0!==f&&(E/=f,R/=f,k/=f)),0!==f);a++)if(N=Math.sqrt(E*E+R*R+k*k),E<0&&(N=-N),0!==N){for(a!==h?i.set(a,a-1,-N*f):l!==h&&i.set(a,a-1,-i.get(a,a-1)),E+=N,f=E/N,m=R/N,T=k/N,R/=E,k/=E,s=a;s=0;M--)if(E=r[M],R=e[M],0===R)for(l=M,i.set(M,M,1),o=M-1;o>=0;o--){for(c=i.get(o,o)-E,k=0,s=l;s<=M;s++)k+=i.get(o,s)*i.get(s,M);if(e[o]<0)T=c,N=k;else if(l=o,0===e[o]?i.set(o,M,0!==c?-k/c:-k/(b*A)):(f=i.get(o,o+1),m=i.get(o+1,o),R=(r[o]-E)*(r[o]-E)+e[o]*e[o],u=(f*N-T*k)/R,i.set(o,M,u),i.set(o+1,M,Math.abs(f)>Math.abs(T)?(-k-c*u)/f:(-N-m*u)/T)),u=Math.abs(i.get(o,M)),b*u*u>1)for(s=o;s<=M;s++)i.set(s,M,i.get(s,M)/u)}else if(R<0)for(l=M-1,Math.abs(i.get(M,M-1))>Math.abs(i.get(M-1,M))?(i.set(M-1,M-1,R/i.get(M,M-1)),i.set(M-1,M,-(i.get(M,M)-E)/i.get(M,M-1))):(x=cdiv(0,-i.get(M-1,M),i.get(M-1,M-1)-E,R),i.set(M-1,M-1,x[0]),i.set(M-1,M,x[1])),i.set(M,M-1,0),i.set(M,M,1),o=M-2;o>=0;o--){for(g=0,p=0,s=l;s<=M;s++)g+=i.get(o,s)*i.get(s,M-1),p+=i.get(o,s)*i.get(s,M);if(c=i.get(o,o)-E,e[o]<0)T=c,k=g,N=p;else if(l=o,0===e[o]?(x=cdiv(-g,-p,c,R),i.set(o,M-1,x[0]),i.set(o,M,x[1])):(f=i.get(o,o+1),m=i.get(o+1,o),d=(r[o]-E)*(r[o]-E)+e[o]*e[o]-R*R,w=2*(r[o]-E)*R,0===d&&0===w&&(d=b*A*(Math.abs(c)+Math.abs(R)+Math.abs(f)+Math.abs(m)+Math.abs(T))),x=cdiv(f*k-T*g+R*p,f*N-T*p-R*g,d,w),i.set(o,M-1,x[0]),i.set(o,M,x[1]),Math.abs(f)>Math.abs(T)+Math.abs(R)?(i.set(o+1,M-1,(-g-c*i.get(o,M-1)+R*i.get(o,M))/f),i.set(o+1,M,(-p-c*i.get(o,M)-R*i.get(o,M-1))/f)):(x=cdiv(-k-m*i.get(o,M-1),-N-m*i.get(o,M),T,R),i.set(o+1,M-1,x[0]),i.set(o+1,M,x[1]))),u=Math.max(Math.abs(i.get(o,M-1)),Math.abs(i.get(o,M))),b*u*u>1)for(s=o;s<=M;s++)i.set(s,M-1,i.get(s,M-1)/u),i.set(s,M,i.get(s,M)/u)}for(o=0;ov)for(s=o;s=0;s--)for(o=0;o<=v;o++){for(T=0,a=0;a<=Math.min(s,v);a++)T+=n.get(o,a)*i.get(a,s);n.set(o,s,T)}}}function cdiv(t,e,r,n){let i,o;return Math.abs(r)>Math.abs(n)?(i=n/r,o=r+i*n,[(t+i*e)/o,(e-i*t)/o]):(i=r/n,o=n+i*r,[(i*t+e)/o,(i*e-t)/o])}class CholeskyDecomposition{constructor(t){if(!(t=WrapperMatrix2D.checkMatrix(t)).isSymmetric())throw new Error("Matrix is not symmetric");let e,r,n,i=t,o=i.rows,s=new Matrix(o,o),a=!0;for(r=0;r0,s.set(r,r,Math.sqrt(Math.max(t,0))),n=r+1;n=0;o--)for(i=0;io;e++)h=t.transpose().mmul(s).div(s.transpose().mmul(s).get(0,0)),h=h.div(h.norm()),a=t.mmul(h).div(h.transpose().mmul(h).get(0,0)),e>0&&(c=a.clone().sub(u).pow(2).sum()),u=a.clone(),r?(l=r.transpose().mmul(a).div(a.transpose().mmul(a).get(0,0)),l=l.div(l.norm()),s=r.mmul(l).div(l.transpose().mmul(l).get(0,0))):s=a;if(r){let e=t.transpose().mmul(a).div(a.transpose().mmul(a).get(0,0));e=e.div(e.norm());let n=t.clone().sub(a.clone().mmul(e.transpose())),i=s.transpose().mmul(a).div(a.transpose().mmul(a).get(0,0)),o=r.clone().sub(a.clone().mulS(i.get(0,0)).mmul(l.transpose()));this.t=a,this.p=e.transpose(),this.w=h.transpose(),this.q=l,this.u=s,this.s=a.transpose().mmul(a),this.xResidual=n,this.yResidual=o,this.betas=i}else this.w=h.transpose(),this.s=a.transpose().mmul(a).sqrt(),this.t=n?a.clone().div(this.s.get(0,0)):a,this.xResidual=t.sub(a.mmul(h.transpose()))}}var MatrixLib=Object.freeze({__proto__:null,AbstractMatrix:AbstractMatrix,default:Matrix,Matrix:Matrix,wrap:wrap,WrapperMatrix1D:WrapperMatrix1D,WrapperMatrix2D:WrapperMatrix2D,solve:solve,inverse:inverse,determinant:determinant,linearDependencies:linearDependencies,pseudoInverse:pseudoInverse,covariance:covariance,correlation:correlation,SingularValueDecomposition:SingularValueDecomposition,SVD:SingularValueDecomposition,EigenvalueDecomposition:EigenvalueDecomposition,EVD:EigenvalueDecomposition,CholeskyDecomposition:CholeskyDecomposition,CHO:CholeskyDecomposition,LuDecomposition:LuDecomposition,LU:LuDecomposition,QrDecomposition:QrDecomposition,QR:QrDecomposition,Nipals:nipals,NIPALS:nipals,MatrixColumnView:MatrixColumnView,MatrixColumnSelectionView:MatrixColumnSelectionView,MatrixFlipColumnView:MatrixFlipColumnView,MatrixFlipRowView:MatrixFlipRowView,MatrixRowView:MatrixRowView,MatrixRowSelectionView:MatrixRowSelectionView,MatrixSelectionView:MatrixSelectionView,MatrixSubView:MatrixSubView,MatrixTransposeView:MatrixTransposeView});const toString$1=Object.prototype.toString;function isAnyArray$1(t){return toString$1.call(t).endsWith("Array]")}function sum(t){if(!isAnyArray$1(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");for(var e=0,r=0;rt+1)).reduce(((t,e)=>Math.max(t,e)))}function giniGain(t,e){let r=0,n=["greater","lesser"];for(let i=0;it>e:(t,e)=>t.01&&this.gain!==n&&s.lesserX.length>0&&s.greaterX.length>0){this.left=new TreeNode(this),this.right=new TreeNode(this);let t=new Matrix(s.lesserX),e=new Matrix(s.greaterX);this.left.train(t,s.lesserY,r+1,this.gain),this.right.train(e,s.greaterY,r+1,this.gain)}else this.calculatePrediction(e)}classify(t){return this.right&&this.left?t[this.splitColumn]>>0,UINT32_SIZE=UINT32_MAX+1,INT32_SIZE=UINT32_SIZE/2,INT32_MAX=INT32_SIZE-1,UINT21_SIZE=1<<21,UINT21_MAX=UINT21_SIZE-1;function int32(t){return 0|t.next()}function add(t,e){return 0===e?t:r=>t(r)+e}function int53(t){const e=0|t.next(),r=t.next()>>>0;return(e&UINT21_MAX)*UINT32_SIZE+r+(e&UINT21_SIZE?-SMALLEST_UNSAFE_INTEGER:0)}function int53Full(t){for(;;){const e=0|t.next();if(!(4194304&e)){const r=t.next()>>>0;return(e&UINT21_MAX)*UINT32_SIZE+r+(e&UINT21_SIZE?-SMALLEST_UNSAFE_INTEGER:0)}if(4194304==(8388607&e)&&0==(0|t.next()))return SMALLEST_UNSAFE_INTEGER}}function uint32(t){return t.next()>>>0}function uint53(t){const e=t.next()&UINT21_MAX,r=t.next()>>>0;return e*UINT32_SIZE+r}function uint53Full(t){for(;;){const e=0|t.next();if(!(e&UINT21_SIZE)){const r=t.next()>>>0;return(e&UINT21_MAX)*UINT32_SIZE+r}if(0==(e&UINT21_MAX)&&0==(0|t.next()))return SMALLEST_UNSAFE_INTEGER}}function isPowerOfTwoMinusOne(t){return 0==(t+1&t)}function bitmask(t){return e=>e.next()&t}function downscaleToLoopCheckedRange(t){const e=t+1,r=e*Math.floor(UINT32_SIZE/e);return t=>{let n=0;do{n=t.next()>>>0}while(n>=r);return n%e}}function downscaleToRange(t){return isPowerOfTwoMinusOne(t)?bitmask(t):downscaleToLoopCheckedRange(t)}function isEvenlyDivisibleByMaxInt32(t){return 0==(0|t)}function upscaleWithHighMasking(t){return e=>{const r=e.next()&t,n=e.next()>>>0;return r*UINT32_SIZE+n}}function upscaleToLoopCheckedRange(t){const e=t*Math.floor(SMALLEST_UNSAFE_INTEGER/t);return r=>{let n=0;do{const t=r.next()&UINT21_MAX,e=r.next()>>>0;n=t*UINT32_SIZE+e}while(n>=e);return n%t}}function upscaleWithinU53(t){const e=t+1;if(isEvenlyDivisibleByMaxInt32(e)){const t=(e/UINT32_SIZE|0)-1;if(isPowerOfTwoMinusOne(t))return upscaleWithHighMasking(t)}return upscaleToLoopCheckedRange(e)}function upscaleWithinI53AndLoopCheck(t,e){return r=>{let n=0;do{const t=0|r.next(),e=r.next()>>>0;n=(t&UINT21_MAX)*UINT32_SIZE+e+(t&UINT21_SIZE?-SMALLEST_UNSAFE_INTEGER:0)}while(ne);return n}}function integer(t,e){if(t=Math.floor(t),e=Math.floor(e),t<-SMALLEST_UNSAFE_INTEGER||!isFinite(t))throw new RangeError("Expected min to be at least "+-SMALLEST_UNSAFE_INTEGER);if(e>SMALLEST_UNSAFE_INTEGER||!isFinite(e))throw new RangeError("Expected max to be at most "+SMALLEST_UNSAFE_INTEGER);const r=e-t;return r<=0||!isFinite(r)?()=>t:r===UINT32_MAX?0===t?uint32:add(int32,t+INT32_SIZE):r{let i="";for(let o=0;o{try{if("xxx"==="x".repeat(3))return(t,e)=>t.repeat(e)}catch(t){}return(t,e)=>{let r="";for(;e>0;)1&e&&(r+=t),e>>=1,t+=t;return r}})(),nativeMath={next:()=>Math.random()*UINT32_SIZE|0},I32Array=(()=>{try{const t=new ArrayBuffer(4),e=new Int32Array(t);if(e[0]=INT32_SIZE,e[0]===-INT32_SIZE)return Int32Array}catch(t){}return Array})();function createEntropy(t=nativeMath,e=16){const r=[];r.push(0|(new Date).getTime());for(let n=1;n{try{if(-5===Math.imul(UINT32_MAX,5))return Math.imul}catch(t){}const t=65535;return(e,r)=>{const n=e&t,i=r&t;return n*i+((e>>>16&t)*i+n*(r>>>16&t)<<16>>>0)|0}})(),ARRAY_SIZE=624,ARRAY_MAX=ARRAY_SIZE-1,M=397,ARRAY_SIZE_MINUS_M=ARRAY_SIZE-M,A=2567483615;class MersenneTwister19937{constructor(){this.data=new I32Array(ARRAY_SIZE),this.index=0,this.uses=0}static seed(t){return(new MersenneTwister19937).seed(t)}static seedWithArray(t){return(new MersenneTwister19937).seedWithArray(t)}static autoSeed(){return MersenneTwister19937.seedWithArray(createEntropy())}next(){(0|this.index)>=ARRAY_SIZE&&(refreshData(this.data),this.index=0);const t=this.data[this.index];return this.index=this.index+1|0,this.uses+=1,0|temper(t)}getUseCount(){return this.uses}discard(t){if(t<=0)return this;for(this.uses+=t,(0|this.index)>=ARRAY_SIZE&&(refreshData(this.data),this.index=0);t+this.index>ARRAY_SIZE;)t-=ARRAY_SIZE-this.index,refreshData(this.data),this.index=0;return this.index=this.index+t|0,this}seed(t){let e=0;this.data[0]=e=0|t;for(let t=1;t>>30,1812433253)+t|0;return this.index=ARRAY_SIZE,this.uses=0,this}seedWithArray(t){return this.seed(19650218),seedWithArray(this.data,t),this}}function refreshData(t){let e=0,r=0;for(;(0|e)>>1^(1&r?A:0);for(;(0|e)>>1^(1&r?A:0);r=t[ARRAY_MAX]&INT32_SIZE|t[0]&INT32_MAX,t[ARRAY_MAX]=t[M-1]^r>>>1^(1&r?A:0)}function temper(t){return t^=t>>>11,t^=t<<7&2636928640,(t^=t<<15&4022730752)^t>>>18}function seedWithArray(t,e){let r=1,n=0;const i=e.length;let o=0|Math.max(i,ARRAY_SIZE),s=0|t[0];for(;(0|o)>0;--o)t[r]=s=(t[r]^imul(s^s>>>30,1664525))+(0|e[n])+(0|n)|0,r=r+1|0,++n,(0|r)>ARRAY_MAX&&(t[0]=t[ARRAY_MAX],r=1),n>=i&&(n=0);for(o=ARRAY_MAX;(0|o)>0;--o)t[r]=s=(t[r]^imul(s^s>>>30,1566083941))-r|0,r=r+1|0,(0|r)>ARRAY_MAX&&(t[0]=t[ARRAY_MAX],r=1);t[0]=INT32_SIZE}function checkFloat(t){return t>0&&t<=1}function examplesBaggingWithReplacement(t,e,r){let n,i=integer(0,t.rows-1);if(void 0===r)n=MersenneTwister19937.autoSeed();else{if(!Number.isInteger(r))throw new RangeError("Expected seed must be undefined or integer not "+r);n=MersenneTwister19937.seed(r)}let o=new Array(t.rows),s=new Array(t.rows);for(let r=0;rt.load(e)))}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=Matrix.checkMatrix(t),this.maxFeatures=this.maxFeatures||t.columns,checkFloat(this.maxFeatures))this.n=Math.floor(t.columns*this.maxFeatures);else{if(!Number.isInteger(this.maxFeatures))throw new RangeError("Cannot process the maxFeatures parameter "+this.maxFeatures);if(this.maxFeatures>t.columns)throw new RangeError("The maxFeatures parameter should be less than "+t.columns);this.n=this.maxFeatures}let r;r=this.isClassifier?DecisionTreeClassifier:DecisionTreeRegression,this.estimators=new Array(this.nEstimators),this.indexes=new Array(this.nEstimators);for(let n=0;nt.toJSON())),useSampleBagging:this.useSampleBagging}}}const defaultOptions$2={maxFeatures:1,replacement:!0,nEstimators:10,seed:42,useSampleBagging:!1};class RandomForestClassifier extends RandomForestBase{constructor(t,e){!0===t?super(!0,e.baseModel):((t=Object.assign({},defaultOptions$2,t)).isClassifier=!0,super(t))}selection(t){return mode(t)}toJSON(){return{baseModel:super.toJSON(),name:"RFClassifier"}}static load(t){if("RFClassifier"!==t.name)throw new RangeError("Invalid model: "+t.name);return new RandomForestClassifier(!0,t)}}function mode(t){return t.sort(((e,r)=>t.filter((t=>t===e)).length-t.filter((t=>t===r)).length)).pop()}const toString$2=Object.prototype.toString;function isAnyArray$2(t){return toString$2.call(t).endsWith("Array]")}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(t,e,r){return t(r={path:e,exports:{},require:function(t,e){return commonjsRequire(t,null==e?r.path:e)}},r.exports),r.exports}function getAugmentedNamespace(t){if(t.__esModule)return t;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(t).forEach((function(r){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})})),e}function commonjsRequire(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}var medianQuickselect_min=createCommonjsModule((function(t){!function(){function e(t){for(var e=0,i=t.length-1,o=void 0,s=void 0,a=void 0,l=n(e,i);;){if(i<=e)return t[l];if(i==e+1)return t[e]>t[i]&&r(t,e,i),t[l];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=l&&(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 median(t){if(!isAnyArray$2(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");return medianQuickselect_min(t.slice())}const selectionMethods={mean:mean,median:median},defaultOptions$3={maxFeatures:1,replacement:!1,nEstimators:10,treeOptions:{},selectionMethod:"mean",seed:42,useSampleBagging:!1};class RandomForestRegression extends RandomForestBase{constructor(t,e){if(!0===t)super(!0,e.baseModel),this.selectionMethod=e.selectionMethod;else{if("mean"!==(t=Object.assign({},defaultOptions$3,t)).selectionMethod&&"median"!==t.selectionMethod)throw new RangeError("Unsupported selection method "+t.selectionMethod);t.isClassifier=!1,super(t),this.selectionMethod=t.selectionMethod}}selection(t){return selectionMethods[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: "+t.name);return new RandomForestRegression(!0,t)}}class PCA{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=Matrix.checkMatrix(t.U),this.S=t.S,this.R=t.R,void(this.excludedFeatures=t.excludedFeatures||[])}t=new Matrix(t);const{isCovarianceMatrix:r=!1,method:n="SVD",nCompNIPALS:i=2,center:o=!0,scale:s=!1,ignoreZeroVariance:a=!1}=e;if(this.center=o,this.scale=s,this.means=null,this.stdevs=null,this.excludedFeatures=[],r)this._computeFromCovarianceMatrix(t);else switch(this._adjust(t,a),n){case"covarianceMatrix":{const e=new MatrixTransposeView(t).mmul(t).div(t.rows-1);this._computeFromCovarianceMatrix(e);break}case"NIPALS":this._computeWithNIPALS(t,i);break;case"SVD":{const e=new SingularValueDecomposition(t,{computeLeftSingularVectors:!1,computeRightSingularVectors:!0,autoTranspose:!0});this.U=e.rightSingularVectors;const r=e.diagonal,n=[];for(const e of r)n.push(e*e/(t.rows-1));this.S=n;break}default:throw new Error("unknown method: "+n)}}static load(t){if("string"!=typeof t.name)throw new TypeError("model must have a name property");if("PCA"!==t.name)throw new RangeError("invalid model: "+t.name);return new PCA(!0,t)}predict(t,e={}){const{nComponents:r=this.U.columns}=e;if(t=new Matrix(t),this.center&&(t.subRowVector(this.means),this.scale)){for(let e of this.excludedFeatures)t.removeColumn(e);t.divRowVector(this.stdevs)}var n=t.mmul(this.U);return n.subMatrix(0,n.rows-1,0,r-1)}invert(t){var e=(t=Matrix.checkMatrix(t)).mmul(this.U.transpose());return this.center&&(this.scale&&e.mulRowVector(this.stdevs),e.addRowVector(this.means)),e}getExplainedVariance(){var t=0;for(const e of this.S)t+=e;return this.S.map((e=>e/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,excludedFeatures:this.excludedFeatures}}_adjust(t,e){if(this.center){const r=t.mean("column"),n=this.scale?t.standardDeviation("column",{mean:r}):null;if(this.means=r,t.subRowVector(r),this.scale){for(let r=0;re?1:0},h=function(t,e,i,o,s){var a;if(null==i&&(i=0),null==s&&(s=r),i<0)throw new Error("lo must be non-negative");for(null==o&&(o=t.length);ir;0<=r?e++:e--)h.push(e);return h}.apply(this).reverse()).length;op;0<=p?++f:--f)d.push(o(t,n));return d},g=function(t,e,n,i){var o,s,a;for(null==i&&(i=r),o=t[n];n>e&&i(o,s=t[a=n-1>>1])<0;)t[n]=s,n=a;return t[n]=o},p=function(t,e,n){var i,o,s,a,l;for(null==n&&(n=r),o=t.length,l=e,s=t[e],i=2*e+1;i0;){const n=e.shift();t>=n.height?r.push(n):e=e.concat(n.children)}return r}group(t){if(!Number.isInteger(t)||t<1)throw new RangeError("groups must be a positive integer");const e=new heap$1(((t,e)=>e.height-t.height));for(e.push(this);e.size()e.push(t)))}var n=new Cluster;return n.children=e.toArray(),n.height=this.height,n}traverse(t){!function t(e,r){if(r(e),e.children)for(const n of e.children)t(n,r)}(this,t)}indices(){const t=[];return this.traverse((e=>{e.isLeaf&&t.push(e.index)})),t}}function singleLink(t,e){return Math.min(t,e)}function completeLink(t,e){return Math.max(t,e)}function averageLink(t,e,r,n,i){return n/(n+i)*t+i/(n+i)*e}function weightedAverageLink(t,e){return(t+e)/2}function centroidLink(t,e,r,n,i){return n/(n+i)*t+i/(n+i)*e+-n*i/(n+i)**2*r}function medianLink(t,e,r){return t/2+e/2-r/4}function wardLink(t,e,r,n,i,o){return(n+o)/(n+i+o)*t+(i+o)/(n+i+o)*e+-o/(n+i+o)*r}function wardLink2(t,e,r,n,i,o){const s=(n+o)/(n+i+o),a=(i+o)/(n+i+o),l=-o/(n+i+o);return Math.sqrt(s*t*t+a*e*e+l*r*r)}function agnes(t,e={}){const{distanceFunction:r=euclidean,method:n="complete",isDistanceMatrix:i=!1}=e;let o;i||(t=distanceMatrix(t,r));let s=new Matrix(t);const a=s.rows;if("string"==typeof n)switch(n.toLowerCase()){case"single":o=singleLink;break;case"complete":o=completeLink;break;case"average":case"upgma":o=averageLink;break;case"wpgma":o=weightedAverageLink;break;case"centroid":case"upgmc":o=centroidLink;break;case"median":case"wpgmc":o=medianLink;break;case"ward":o=wardLink;break;case"ward2":o=wardLink2;break;default:throw new RangeError("unknown clustering method: "+n)}else if("function"!=typeof n)throw new TypeError("method must be a string or function");let l=[];for(let t=0;tgetPreviousIndex(r,Math.min(t,e),Math.max(t,e));for(let a=1;a=e&&t++,t>=r&&t++,t}var index=Object.freeze({__proto__:null,agnes:agnes});const defaultOptions$4={distanceFunction:squaredEuclidean};function nearestVector(t,e,r=defaultOptions$4){const n=r.distanceFunction||defaultOptions$4.distanceFunction,i=r.similarityFunction||defaultOptions$4.similarityFunction;let o=-1;if("function"==typeof i){let r=Number.MIN_VALUE;for(let n=0;nr&&(r=s,o=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}const LOOP=8,FLOAT_MUL=1/16777216,sh1=15,sh2=18,sh3=11;function multiply_uint32(t,e){const r=65535&(t>>>=0);return((t-r)*(e>>>=0)>>>0)+r*e>>>0}class XSadd{constructor(t=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)*FLOAT_MUL}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>>sh2,t^=this.state[3]<PROB_TOLERANCE)throw new Error("probabilities should sum to 1, but instead sums to "+a[a.length-1])}if(!1===i&&n>s.length)throw new Error("size option is too large");const l=[];for(let t=0;tr[t];)t++;return t}return Math.floor(n*t)}class Random{constructor(t=Math.random){if("number"==typeof t){const e=new XSadd(t);this.randomGenerator=e.random}else this.randomGenerator=t}choice(t,e){return randomChoice(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;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 l=2;lh.dist&&(h=Object.assign({},c))}o[l]=h.index}}return o.map((e=>t[e]))}function kmeanspp(t,e,r={}){const n=(t=new Matrix(t)).rows,i=new Random(r.seed),o=[],s=r.localTrials||2+Math.floor(Math.log(e)),a=i.randInt(n);o.push(t.getRow(a));let l=new Matrix(1,t.rows);for(let e=0;et.length||!Number.isInteger(e))throw new Error("K should be a positive integer smaller than the number of points");var n;if(Array.isArray(r.initialization)){if(r.initialization.length!==e)throw new Error("The initial centers should have the same length as K");n=r.initialization}else switch(r.initialization){case"kmeans++":n=kmeanspp(t,e,r);break;case"random":n=random(t,e,r.seed);break;case"mostDistant":n=mostDistant(t,e,calculateDistanceMatrix(t,r.distanceFunction),r.seed);break;default:throw new Error(`Unknown initialization method: "${r.initialization}"`)}0===r.maxIterations&&(r.maxIterations=Number.MAX_VALUE);var i=new Array(t.length);if(r.withIterations)return kmeansGenerator(n,t,i,e,r);for(var o,s=!1,a=0;!s&&an&&(n=s,i=o)}return i}function calculateLogProbability(t,e,r,n){return t-=e,Math.log(r*Math.exp(t*t/n))}class MultinomialNB{constructor(t){t&&(this.conditionalProbability=Matrix.checkMatrix(t.conditionalProbability),this.priorProbability=Matrix.checkMatrix(t.priorProbability))}train(t,e){if((t=Matrix.checkMatrix(t)).rows!==e.length)throw new RangeError("the size of the training set and the training labels must be the same.");var r=separateClasses(t,e);this.priorProbability=new Matrix(r.length,1);for(var n=0;n, 2012 * @author Ubilabs http://ubilabs.net, 2012 * @license MIT License - */function Node(t,e,r){this.obj=t,this.left=null,this.right=null,this.parent=r,this.dimension=e}class KDTree{constructor(t,e){if(Array.isArray(t)){this.dimensions=new Array(t[0].length);for(var r=0;re&&o.pop()}for(m=0;mt[i[n]]-e[i[n]]);const s=Math.floor(t.length/2),o=new Node(t[s],n,r);return o.left=buildTree(t.slice(0,s),e+1,o,i),o.right=buildTree(t.slice(s+1),e+1,o,i),o}function restoreParent(t){t.left&&(t.left.parent=t,restoreParent(t.left)),t.right&&(t.right.parent=t,restoreParent(t.right))}class BinaryHeap{constructor(t){this.content=[],this.scoreFunction=t}push(t){this.content.push(t),this.bubbleUp(this.content.length-1)}pop(){var t=this.content[0],e=this.content.pop();return this.content.length>0&&(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,i=this.content[r];if(!(this.scoreFunction(e)2&&void 0!==arguments[2]?arguments[2]:{};if(!0===t){const t=e;return this.kdTree=new KDTree(t.kdTree,r),this.k=t.k,this.classes=new Set(t.classes),void(this.isEuclidean=t.isEuclidean)}const i=new Set(e),{distance:n=euclidean,k:s=i.size+1}=r,o=new Array(t.length);for(var a=0;a1&&void 0!==arguments[1]?arguments[1]:euclidean;if("KNN"!==t.name)throw new Error("invalid model: ".concat(t.name));if(!t.isEuclidean&&e===euclidean)throw new Error("a custom distance function was used to create the model. Please provide it again");if(t.isEuclidean&&e!==euclidean)throw new Error("the model was created with the default distance function. Do not load it with another one");return new KNN(!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 getSinglePrediction(this,t);if(Array.isArray(t[0])&&"number"==typeof t[0][0]){const r=new Array(t.length);for(var e=0;es&&(n=l,s=u)}return n}function norm(t){return Math.sqrt(t.clone().apply(pow2array).sum())}function pow2array(t,e){this.set(t,e,this.get(t,e)**2)}function initializeMatrices(t,e){if(e)for(var r=0;rh&&ph;){var A=w.mmul(b);A.div(norm(A)),S=v,v=t.mmul(A);var E=x.mmul(v);E.div(norm(E)),b=e.mmul(E)}S=v;var R=w.mmul(S),k=S.transpose().mmul(S).get(0,0),C=R.div(k),T=norm(C);C.div(T),S.mul(T),A.mul(T),R=b.transpose().mmul(S),k=S.transpose().mmul(S).get(0,0);var N=R.div(k).get(0,0);t.sub(S.mmul(C.transpose())),e.sub(S.clone().mul(N).mmul(E.transpose())),u.setColumn(p,S),c.setColumn(p,C),f.setColumn(p,b),m.setColumn(p,E),d.setColumn(p,A),g.set(p,p,N),p++}p--,u=u.subMatrix(0,u.rows-1,0,p),c=c.subMatrix(0,c.rows-1,0,p),f=f.subMatrix(0,f.rows-1,0,p),m=m.subMatrix(0,m.rows-1,0,p),d=d.subMatrix(0,d.rows-1,0,p),g=g.subMatrix(0,p,0,p),this.ssqYcal=a,this.E=t,this.F=e,this.T=u,this.P=c,this.U=f,this.Q=m,this.W=d,this.B=g,this.PBQ=c.mmul(g).mmul(m.transpose()),this.R2X=S.transpose().mmul(S).mmul(C.transpose().mmul(C)).div(o).get(0,0)}predict(t){var e=Matrix.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: ".concat(t.name));return new PLS(!0,t)}}function maxSumColIndex(t){return Matrix.rowVector(t.sum("column")).maxIndex()[0]}class KOPLS{constructor(t,e){if(!0===t)this.trainingSet=new Matrix(e.trainingSet),this.YLoadingMat=new Matrix(e.YLoadingMat),this.SigmaPow=new Matrix(e.SigmaPow),this.YScoreMat=new Matrix(e.YScoreMat),this.predScoreMat=initializeMatrices(e.predScoreMat,!1),this.YOrthLoadingVec=initializeMatrices(e.YOrthLoadingVec,!1),this.YOrthEigen=e.YOrthEigen,this.YOrthScoreMat=initializeMatrices(e.YOrthScoreMat,!1),this.toNorm=initializeMatrices(e.toNorm,!1),this.TURegressionCoeff=initializeMatrices(e.TURegressionCoeff,!1),this.kernelX=initializeMatrices(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=Matrix.checkMatrix(t),e=Matrix.checkMatrix(e),this.trainingSet=t.clone();var r=this.kernel.compute(t),i=Matrix.eye(r.rows,r.rows,1),n=r;r=new Array(this.orthogonalComp+1);for(let t=0;t2&&void 0!==arguments[2]?arguments[2]:{};if(e.length!==t.length)throw new Error("predicted and actual must have the same length");r=i.labels?new Set(i.labels):new Set([...t,...e]),r=Array.from(r),i.sort&&r.sort(i.sort);const n=Array.from({length:r.length});for(let t=0;t=0&&o>=0&&n[s][o]++}return new ConfusionMatrix(n,r)}getMatrix(){return this.matrix}getLabels(){return this.labels}getTotalCount(){let t=0;for(var e=0;e1&&(l[e-1]=0);do{e++}while(l[e]>0);for(r=e-1,t=e;0===l[t];)l[t++]=-1;if(-1===l[t])l[t]=l[r],s=l[r]-1,i=t-1,n=r-1,l[r]=-1;else{if(t===l[0])return 0;l[e]=l[t],s=l[t]-1,l[t]=0,i=e-1,n=t-1}}return 1}if("index"===r.mode)for(yield a.slice();c();)a[s]=o[i],yield a.slice();else{if("mask"!==r.mode)throw new Error("Invalid mode");for(yield h.slice();c();)h[i]=1,h[n]=0,yield h.slice()}};const CV={};function check(t,e){if(t.length!==e.length)throw new Error("features and labels should have the same length")}function initMatrix(t,e){return new Array(t).fill(0).map(()=>new Array(e).fill(0))}function getDistinct(t){var e=new Set;for(let r=0;r=0;t--)c.splice(n[t],1);s?validateWithCallback(e,r,n,c,a,o,s):validate(t,e,r,i,n,c,a,o)}return new src$1(a,o)},CV.kFold=function(t,e,r,i,n){if("function"==typeof i){var s=i;n=r,r=e,e=t}check(e,r);const o=getDistinct(r),a=initMatrix(o.length,o.length);for(var h=e.length,l=new Array(h),u=0;u0?(Math.exp(e*t)-1)/e+e:t}function softExponentialPrime(t,e){return e<0?1/(1-e*(e+t)):Math.exp(e*t)}const ACTIVATION_FUNCTIONS={tanh:{activation:Math.tanh,derivate:t=>1-t*t},identity:{activation:t=>t,derivate:()=>1},logistic:{activation:logistic,derivate:t=>logistic(t)*(1-logistic(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:expELU,derivate:(t,e)=>t<0?expELU(t,e)+e:1},"soft-exponential":{activation:softExponential,derivate:softExponentialPrime}};class Layer{constructor(t){this.inputSize=t.inputSize,this.outputSize=t.outputSize,this.regularization=t.regularization,this.epsilon=t.epsilon,this.activation=t.activation,this.activationParam=t.activationParam;var e=ACTIVATION_FUNCTIONS[t.activation],r=e.activation.length,i=r>1?r=>e.activation(r,t.activationParam):e.activation,n=r>1?r=>e.derivate(r,t.activationParam):e.derivate;this.activationFunction=function(t,e){this.set(t,e,i(this.get(t,e)))},this.derivate=function(t,e){this.set(t,e,n(this.get(t,e)))},t.model?(this.W=Matrix.Matrix.checkMatrix(t.W),this.b=Matrix.Matrix.checkMatrix(t.b)):(this.W=Matrix.Matrix.rand(this.inputSize,this.outputSize),this.b=Matrix.Matrix.zeros(1,this.outputSize),this.W.apply((function(e,r){this.set(e,r,this.get(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.transpose().mmul(t),this.db=Matrix.Matrix.rowVector(t.sum("column"));var r=e.clone();return t.mmul(this.W.transpose()).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 Layer(t)}}class OutputLayer extends Layer{constructor(t){super(t),this.activationFunction=function(t,e){this.set(t,e,Math.exp(this.get(t,e)))}}static load(t){if("Layer"!==t.model)throw new RangeError("the current model is not a Layer model");return new OutputLayer(t)}}class FeedForwardNeuralNetworks{constructor(t){if((t=t||{}).model){this.hiddenLayers=t.hiddenLayers,this.iterations=t.iterations,this.learningRate=t.learningRate,this.regularization=t.regularization,this.dicts=t.dicts,this.activation=t.activation,this.activationParam=t.activationParam,this.model=new Array(t.layers.length);for(var e=0;e=0;--i){var s=i>0?this.model[i-1].a:t;n=this.model[i].backpropagation(n,s)}for(i=0;i0?e=this[t]-1:this.som.torus&&(e=this.som.gridDim[t]-1),void 0!==e)"x"===t?(r=e,i=this.y):(r=this.x,i=e),this.neighbors[t][0]=this.som.nodes[r][i];this[t]0&&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),i=new Array(e),n=0;n0?("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,i,n,s,o=Date.now(),a=this._findBestMatchingUnit(t),h=Date.now();this.times.findBMU+=h-o;var l=Math.floor(e),u=a.x-l,c=a.x+l,f=a.y-l,m=a.y+l;for(r=u;r<=c;r++){var g=r;for(r<0?g+=this.x:r>=this.x&&(g-=this.x),i=f;i<=m;i++){var d=i;i<0?d+=this.y:i>=this.y&&(d-=this.y),(n=a[this.distanceMethod](this.nodes[g][d]))0&&e!==this.coefficients.length-1?o=" + ".concat(o):e!==this.coefficients.length-1&&(o=" ".concat(o))),s=o+s;return"+"===s.charAt(0)&&(s=s.slice(1)),"f(x) = ".concat(s)}static load(t){if("polynomialRegression"!==t.name)throw new TypeError("not a polynomial regression model");return new PolynomialRegression(!0,t)}}function regress(t,e,r,i){const n=e.length;let s;if(Array.isArray(i))i=(s=i).length;else{i++,s=new Array(i);for(let t=0;t=0?"f(x) = ".concat(maybeToPrecision(this.B,t),"e^{").concat(maybeToPrecision(this.A,t),"x}"):"f(x) = \\frac{".concat(maybeToPrecision(this.B,t),"}{e^{").concat(maybeToPrecision(-this.A,t),"x}}")}static load(t){if("exponentialRegression"!==t.name)throw new TypeError("not a exponential regression model");return new ExponentialRegression(!0,t)}}function regress$2(t,e,r){const i=e.length,n=new Array(i);for(let t=0;t=0?"f(x) = ".concat(maybeToPrecision(this.A,t),"x^{").concat(maybeToPrecision(this.B,t),"}"):"f(x) = \\frac{".concat(maybeToPrecision(this.A,t),"}{x^{").concat(maybeToPrecision(-this.B,t),"}}")).replace(/e([+-]?[0-9]+)/g,"e^{$1}")}static load(t){if("powerRegression"!==t.name)throw new TypeError("not a power regression model");return new PowerRegression(!0,t)}}function regress$3(t,e,r){const i=e.length,n=new Array(i),s=new Array(i);for(let t=0;t2&&void 0!==arguments[2]?arguments[2]:{};const{intercept:i=!0,statistics:n=!0}=r;if(this.statistics=n,!0===t)this.weights=e.weights,this.inputs=e.inputs,this.outputs=e.outputs,this.intercept=e.intercept;else{t=new Matrix(t),e=new Matrix(e),i&&t.addColumn(new Array(t.rows).fill(1));let r=t.transpose();const s=r.mmul(t),o=r.mmul(e),a=new SingularValueDecomposition(s).inverse(),h=o.transpose().mmul(a).transpose();if(this.weights=h.to2DArray(),this.inputs=t.columns,this.outputs=e.columns,i&&this.inputs--,this.intercept=i,n){const r=t.mmul(h),i=e.clone().addM(r.neg()).to2DArray().map(t=>Math.pow(t[0],2)).reduce((t,e)=>t+e)/(e.rows-t.columns);this.stdError=Math.sqrt(i),this.stdErrorMatrix=pseudoInverse(s).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 MultivariateLinearRegression(!0,t)}}const{squaredEuclidean:squaredEuclidean$1}=euclidean$1,defaultOptions$8={sigma:1};class GaussianKernel{constructor(t){t=Object.assign({},defaultOptions$8,t),this.sigma=t.sigma,this.divisor=2*t.sigma*t.sigma}compute(t,e){const r=squaredEuclidean$1(t,e);return Math.exp(-r/this.divisor)}}var gaussianKernel=GaussianKernel;const defaultOptions$9={degree:1,constant:1,scale:1};class PolynomialKernel{constructor(t){t=Object.assign({},defaultOptions$9,t),this.degree=t.degree,this.constant=t.constant,this.scale=t.scale}compute(t,e){for(var r=0,i=0;i0&&e!==this.coefficients.length-1?o=" + ".concat(o):e!==this.coefficients.length-1&&(o=" ".concat(o))),s=o+s;return"+"===s.charAt(0)&&(s=s.slice(1)),"f(x) = ".concat(s)}static load(t){if("robustPolynomialRegression"!==t.name)throw new TypeError("not a RobustPolynomialRegression model");return new RobustPolynomialRegression(!0,t)}}function robustPolynomial(t,e,r,i){let n=Array(i).fill(0).map((t,e)=>e);const s=getRandomTuples(e,r,i);for(var o,a=0;at.residual-e.residual);var e=t.length,r=Math.floor(e/2);return e%2==0?t[r-1]:t[r]}function errorCalculation(t,e,r){var i=0;const n=r(e);for(var s=0;sa(t)),l=gradientFunction(t,h,e,i,n),u=matrixFunction(t,h),c=inverse(o.add(l.mmul(l.transpose())));return(e=(e=new Matrix([e])).sub(c.mmul(l).mmul(u).mul(i).transpose())).to1DArray()}function levenbergMarquardt(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{maxIterations:i=100,gradientDifference:n=.1,damping:s=0,errorTolerance:o=.01,minValues:a,maxValues:h,initialValues:l}=r;if(s<=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 u=l||new Array(e.length).fill(1);let c=u.length;if(h=h||new Array(c).fill(Number.MAX_SAFE_INTEGER),a=a||new Array(c).fill(Number.MIN_SAFE_INTEGER),h.length!==a.length)throw new Error("minValues and maxValues must be the same size");if(!Array.isArray(u))throw new Error("initialValues must be an array");for(var f=errorCalculation(t,u,e),m=f<=o,g=0;g{let r=BigInt(0);return t.forEach(t=>r|=BigInt(1)<t.key-e.key<0?-1:1),i=[],n=[];for(let t of r)t.key!==e&&(e=t.key,n.push([]),i.push(t.value)),n[n.length-1].push(t.index);return{values:i,indices:n}}function cssls(t,e,r,i,n){let s=Matrix.zeros(i,n);if(null===r){let r=new CholeskyDecomposition(t);if(!0===r.isPositiveDefinite())s=r.solve(e);else{let r=new LuDecomposition(t);s=!1===r.isSingular()?r.solve(Matrix.eye(i)).mmul(e):solve(t,e,{useSVD:!0})}}else{let o=sortCollectionSet(r).values,a=sortCollectionSet(r).indices;if(1===o.length&&0===o[0].length&&a[0].length===n)return s;if(1===o.length&&o[0].length===i&&a[0].length===n){let r=new CholeskyDecomposition(t);if(!0===r.isPositiveDefinite())s=r.solve(e);else{let r=new LuDecomposition(t);s=!1===r.isSingular()?r.solve(Matrix.eye(i)).mmul(e):solve(t,e,{useSVD:!0})}}else for(let r=0;r0?l[t].push(e):h.set(e,t,0)}let u=[];for(let t=0;tt-e);return{Pset:s,Fset:n,W:o}}function fcnnls(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};t=Matrix.checkMatrix(t),e=Matrix.checkMatrix(e);let{l:i,p:n,iter:s,W:o,XtX:a,XtY:h,K:l,Pset:u,Fset:c,D:f}=initialisation(t,e);const{maxIterations:m=3*t.columns}=r;for(;c.length>0;){let t=cssls(a,h.subMatrixColumn(c),selection(u,c),i,c.length);for(let e=0;e0){let e=r.length,n=Matrix.ones(i,e);for(;e>0&&se===g[t]),1);t=cssls(a,h.subMatrixColumn(r),selection(u,r),i,e);for(let i=0;i2&&void 0!==arguments[2]?arguments[2]:{};if(!1===Array.isArray(e))throw new TypeError("y must be a 1D Array");return fcnnls(t,Matrix.columnVector(e),r).to1DArray()}var index$2=Object.freeze({__proto__:null,fcnnls:fcnnls,fcnnlsVector:fcnnlsVector}),binarySearch=function(t,e,r,i,n){var s,o;if(void 0===i)i=0;else if((i|=0)<0||i>=t.length)throw new RangeError("invalid lower bound");if(void 0===n)n=t.length-1;else if((n|=0)=t.length)throw new RangeError("invalid upper bound");for(;i<=n;)if((o=+r(t[s=i+(n-i>>>1)],e,s,t))<0)i=s+1;else{if(!(o>0))return s;n=s-1}return~i};function assertNumber(t){if("number"!=typeof t||Number.isNaN(t))throw new TypeError("Expected a number")}var ascending=(t,e)=>(assertNumber(t),assertNumber(e),t-e),descending=(t,e)=>(assertNumber(t),assertNumber(e),e-t),numSort={ascending:ascending,descending:descending},index$3=Object.freeze({__proto__:null,default:numSort,__moduleExports:numSort,ascending:ascending,descending:descending});const largestPrime=2147483647,primeNumbers=[largestPrime,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,433,877,1759,3527,7057,14143,28289,56591,113189,226379,452759,905551,1811107,3622219,7244441,14488931,28977863,57955739,115911563,231823147,463646329,927292699,1854585413,953,1907,3821,7643,15287,30577,61169,122347,244703,489407,978821,1957651,3915341,7830701,15661423,31322867,62645741,125291483,250582987,501165979,1002331963,2004663929,1039,2081,4177,8363,16729,33461,66923,133853,267713,535481,1070981,2141977,4283963,8567929,17135863,34271747,68543509,137087021,274174111,548348231,1096696463,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,599,1201,2411,4831,9677,19373,38747,77509,155027,310081,620171,1240361,2480729,4961459,9922933,19845871,39691759,79383533,158767069,317534141,635068283,1270136683,311,631,1277,2557,5119,10243,20507,41017,82037,164089,328213,656429,1312867,2625761,5251529,10503061,21006137,42012281,84024581,168049163,336098327,672196673,1344393353,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,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,379,761,1523,3049,6101,12203,24407,48817,97649,195311,390647,781301,1562611,3125257,6250537,12501169,25002389,50004791,100009607,200019221,400038451,800076929,1600153859,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,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,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 nextPrime(t){let e=binarySearch(primeNumbers,t,ascending);return e<0&&(e=~e),primeNumbers[e]}primeNumbers.sort(ascending);const FREE=0,FULL=1,REMOVED=2,defaultInitialCapacity=150,defaultMinLoadFactor=1/6,defaultMaxLoadFactor=2/3;class HashTable{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(t instanceof HashTable)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?defaultInitialCapacity:t.initialCapacity;if(e<0)throw new RangeError("initial capacity must not be less than zero: ".concat(e));const r=void 0===t.minLoadFactor?defaultMinLoadFactor:t.minLoadFactor,i=void 0===t.maxLoadFactor?defaultMaxLoadFactor: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 n=e;0===(n=nextPrime(n=n/i|0))&&(n=1),this.table=newArray$1(n),this.values=newArray$1(n),this.state=newArray$1(n),this.minLoadFactor=r,this.maxLoadFactor=n===largestPrime?1:i,this.distinct=0,this.freeEntries=n,this.lowWaterMark=0,this.highWaterMark=chooseHighWaterMark(n,this.maxLoadFactor)}clone(){return new HashTable(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=chooseGrowCapacity(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]===FREE&&this.freeEntries--,this.state[r]=FULL,this.distinct++,this.freeEntries<1){const t=chooseGrowCapacity(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]=REMOVED,this.distinct--,e||this.maybeShrinkCapacity(),!0)}delete(t,e){const r=this.indexOfKey(t);return!(r<0)&&(this.state[r]=FREE,this.distinct--,e||this.maybeShrinkCapacity(),!0)}maybeShrinkCapacity(){if(this.distinct=0}indexOfKey(t){const e=this.table,r=this.state,i=this.table.length,n=2147483647&t;let s=n%i,o=n%(i-2);for(0===o&&(o=1);r[s]!==FREE&&(r[s]===REMOVED||e[s]!==t);)(s-=o)<0&&(s+=i);return r[s]===FREE?-1:s}containsValue(t){return this.indexOfValue(t)>=0}indexOfValue(t){const e=this.values,r=this.state;for(var i=0;i2&&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 o=t;t=o.length,r=e||{},e=o[0].length,this._init(t,e,new HashTable(r),r.threshold);for(var i=0;i0&&void 0!==arguments[0]?arguments[0]:1,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t;const r=Math.min(t,e),i=new SparseMatrix(t,e,{initialCapacity:r});for(var n=0;nthis.get(r,e)!==i?(t=!1,!1):i),t}bandWidth(){let t=this.columns,e=-1;return this.forEachNonZero((r,i,n)=>{let s=r-i;return t=Math.min(t,s),e=Math.max(e,s),n}),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,s,o)=>(r===t&&i.set(e,s,i.get(e,s)+n*o),o)),n)),i}kroneckerProduct(t){const e=this.rows,r=this.columns,i=t.rows,n=t.columns,s=new SparseMatrix(e*i,r*n,{initialCapacity:this.cardinality*t.cardinality});return this.forEachNonZero((e,r,o)=>(t.forEachNonZero((t,a,h)=>(s.set(i*e+t,n*r+a,o*h),h)),o)),s}forEachNonZero(t){return this.elements.forEachPair((e,r)=>{const i=e/this.columns|0,n=e%this.columns;let s=t(i,n,r);return!1!==s&&(this.threshold&&Math.abs(s)(e[n]=t,r[n]=s,i[n]=o,n++,o)),{rows:e,columns:r,values:i}}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,i)=>(t.set(r,e,i),i)),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;i1&&void 0!==arguments[1]?arguments[1]:{};var r=t[0];const{minWindow:i=.16,threshold:n=.01,from:s=r[0],to:o=r[r.length-1]}=e;return mainCreateTree(t[0],t[1],s,o,i,n)}function mainCreateTree(t,e,r,i,n,s){if(i-r=i);l++)a+=e[l],h+=t[l]*e[l];return a2&&void 0!==arguments[2]?arguments[2]:{};const{alpha:i=.1,beta:n=.33,gamma:s=.001}=r;return null===t||null===e?0:(Array.isArray(t)&&(t=createTree(t)),Array.isArray(e)&&(e=createTree(e)),n*(i*Math.min(t.sum,e.sum)/Math.max(t.sum,e.sum)+(1-i)*Math.exp(-s*Math.abs(t.center-e.center)))+(1-n)*(getSimilarity(t.left,e.left,r)+getSimilarity(t.right,e.right,r))/2)}function treeSimilarity(t,e){return getSimilarity(t,e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function getFunction(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return(e,r)=>getSimilarity(e,r,t)}var index$4=Object.freeze({__proto__:null,treeSimilarity:treeSimilarity,getFunction:getFunction,createTree:createTree});function cosine(t,e){for(var r=t.length,i=0,n=0,s=0,o=0;o{const e=t.cutoffs.length,r=new Array(e);for(var i=0;i{const e=t.cutoffs.length,r=new Array(e);for(var i=0;i{const e=t.cutoffs.length,r=new Array(e);for(var i=0;i{const e=t.cutoffs.length,r=new Array(e);for(var i=0;i{const e=t.cutoffs.length,r=new Array(e);for(var i=0;i{const e=t.cutoffs.length,r=new Array(e);for(var i=0;i{const e=t.cutoffs.length,r=new Array(e);for(var i=0;i{const e=t.cutoffs.length,r=new Array(e);for(var i=0;i{const e=t.cutoffs.length,r=new Array(e);for(var i=0;i{const e=t.cutoffs.length,r=new Array(e);for(var i=0;i{const e=t.cutoffs.length,r=new Array(e);for(var i=0;i{const e=t.cutoffs.length,r=new Array(e);for(var i=0;i{const e=t.cutoffs.length,r=new Array(e);for(var i=0;i{const e=t.cutoffs.slice();return e[0]=e[1],e},measures={acc:acc,err:err,fpr:fpr,tpr:tpr,fnr:fnr,tnr:tnr,ppv:ppv,npv:npv,pcfall:pcfall,pcmiss:pcmiss,lift:lift,rpp:rpp,rnp:rnp,threshold:threshold};class Performance{constructor(t,e,r){if(r=r||{},t.length!==e.length||t[0].length!==e[0].length)throw new Error("dimensions of prediction and target do not match");const i=t.length,n=t[0].length,s=!r.max,o=[];if(r.all)for(var a=0;at.pred-e.pred):o.sort((t,e)=>e.pred-t.pred);const l=this.cutoffs=[s?Number.MIN_VALUE:Number.MAX_VALUE],u=this.fp=[0],c=this.tp=[0];var f=0,m=0,g=o[0].pred,d=0,p=0;for(a=0;ar||e.size[1]>r)throw new RangeError("expanded value should not be bigger than the data length");for(n=0;n>8&255]+creator[t[r]>>16&255]+creator[t[r]>>24&255];return e}function and(t,e){for(var r=new Array(t.length),i=0;i>5]&r)}function setBit(t,e,r){var i=e>>5,n=1<<31-e%32;return t[i]=r?n|t[i]:~n&t[i],t}function toBinaryString(t){for(var e="",r=0;r>>0).toString(2);e+="00000000000000000000000000000000".substr(i.length)+i}return e}function parseBinaryString(t){for(var e=t.length/32,r=new Array(e),i=0;i>>0).toString(16);e+="00000000".substr(i.length)+i}return e}function parseHexString(t){for(var e=t.length/8,r=new Array(e),i=0;ir&&(r=i,e=t[s])}return e}function norm$1(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 i=absoluteSum(t);return 0===i?t.slice(0):t.map((function(t){return t/i}));case"max":var n=max(t);return 0===n?t.slice(0):t.map((function(t){return t/n}));case"sum":var s=sum(t);return 0===s?t.slice(0):t.map((function(t){return t/s}));default:throw new Error("norm: unknown algorithm: ".concat(r))}}function absoluteSum(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"!==_typeof(t)||src(t)||(e=t,t=[]),!src(t))throw new TypeError("input must be an array");var r=e,i=r.from,n=void 0===i?0:i,s=r.to,o=void 0===s?10:s,a=r.size,h=void 0===a?t.length:a,l=r.step;if(h&&l)throw new Error("step is defined by the array size");if(h||(h=l?Math.floor((o-n)/l)+1:o-n+1),!l&&h&&(l=(o-n)/(h-1)),Array.isArray(t)){t.length=0;for(var u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(!src(t))throw new TypeError("input must be an array");for(var r=e.unbiased,i=void 0===r||r,n=e.mean,s=void 0===n?mean(t):n,o=0,a=0;a1&&void 0!==arguments[1]?arguments[1]:{};return Math.sqrt(variance(t,e))}function mergeByCentroids(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{window:i=.01}=r;for(var n={x:e.slice(),y:new Array(e.length).fill(0)},s=0,o=0;s=0?{x:r[o],y:i[o]}:0!==(o=~o)&&Math.abs(r[o]-n)>.5||o===r.length?{x:r[o-1],y:i[o-1]}:{x:r[o],y:i[o]}}function covariance$1(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{x:r,y:i}=t,{unbiased:n=!0}=e,s=mean(r),o=mean(i);var a=0;for(let t=0;t1&&void 0!==arguments[1]?arguments[1]:{};const{x:r,y:i}=t,{groupWidth:n=.001}=e;for(var s={x:[],y:[]},o={x:[],y:[]},a=0,h=0;hn?(o.x.push(r[h]),o.y.push(i[h]),s.x.push(r[h]),s.y.push(i[h]),h++,a++):(i[h]>o.y[a-1]&&(o.x[a-1]=r[h],o.y[a-1]=i[h]),s.x[a-1]=r[h],s.y[a-1]+=i[h],h++);return s.x=o.x.slice(),s}function maxY(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{x:r,y:i}=t;let{from:n={index:0},to:s={index:r.length},reverse:o=!1}=e;void 0!==n.value&&void 0===n.index&&(n.index=calculateIndex(n.value,r,o)),void 0!==s.value&&void 0===s.index&&(s.index=calculateIndex(s.value,r,o));for(var a,h=Number.MIN_VALUE,l=n.index;l1&&void 0!==arguments[1]?arguments[1]:{};const{x:r,y:i}=t,{reverse:n=!1}=e;var s;s=n?(t,e)=>e.x-t.x:(t,e)=>t.x-e.x;for(var o=r.map((t,e)=>({x:t,y:i[e]})).sort(s),a={x:r.slice(),y:i.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 i=e[0],n=0;for(let t=1;t1&&void 0!==arguments[1]?arguments[1]:{};const{x:r,y:i}=t,{groupWidth:n=.001}=e;for(var s={x:[],y:[]},o={x:[],y:[]},a=0,h=0;hn?(o.x.push(r[h]*i[h]),o.y.push(i[h]),s.x.push(r[h]),s.y.push(i[h]),h++,a++):(o.x[a-1]+=r[h]*i[h],o.y[a-1]+=i[h],s.x[a-1]=r[h],s.y[a-1]+=i[h],h++);for(var l=0;l=0;){var A=integral(0,f-m,x,g);if(v=w+A,h[S++]=(v-y)/o,S===n)break t;c=f,f+=o,y=v}w+=integral(m,d,x,M),m=d,g=p,b=d)throw new Error("x must be an increasing serie");for(;m-f>0;){if(x&&(y++,x=!1),u[b]=y<=0?0:M/y,++b===n)break t;c=f,f+=o,M=0,y=0}m>c&&(M+=g,y++),(m===-Number.MAX_VALUE||w>1)&&y--,m=d,g=p,v3&&void 0!==arguments[3]?arguments[3]:[];t>e&&([t,e]=[e,t]),i=i.filter(t=>void 0!==t.from&&void 0!==t.to),(i=JSON.parse(JSON.stringify(i))).forEach(t=>{t.from>t.to&&([t.to,t.from]=[t.from,t.to])}),i.sort((t,e)=>t.from-e.from),i.forEach(r=>{r.frome&&(r.to=e)});for(let t=0;ti[t+1].from&&(i[t].to=i[t+1].from);if(!(i=i.filter(t=>t.fromt+=e.to-e.from,0),s=(e-t-n)/r,o=[],a=t,h=0;for(let t of i){let e=Math.round((t.from-a)/s);h+=e,e>0&&o.push({from:a,to:t.from,numberOfPoints:e}),a=t.to}return r-h>0&&o.push({from:a,to:e,numberOfPoints:r-h}),o}function equallySpaced(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{x:r,y:i}=t,n=r.length,s=!1;r.length>1&&r[0]>r[1]&&(r=r.slice().reverse(),i=i.slice().reverse(),s=!0);let{from:o=r[0],to:a=r[n-1],variant:h="smooth",numberOfPoints:l=100,exclusions:u=[]}=e;if(n!==i.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 a||isNaN(a))throw new RangeError("'to' option must be a number");if("number"!=typeof l||isNaN(l))throw new RangeError("'numberOfPoints' option must be a number");if(l<2)throw new RangeError("'numberOfPoints' option must be greater than 1");let c=getZones(o,a,l,u),f=[],m=[];for(let t of c){let e=processZone(r,i,t.from,t.to,t.numberOfPoints,h);f=f.concat(e.x),m=m.concat(e.y)}return s?o2&&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.from1&&void 0!==arguments[1]?arguments[1]:{};const{x:r,y:i}=t,{from:n=r[0],to:s=r[r.length-1],exclusions:o=[]}=e;let a=getZones$1(n,s,o),h=0,l=[],u=[],c=0;for(;c=a[h].from)l.push(r[c]),u.push(i[c]);else if(r[c]>a[h].to&&!a[++h])break;c++}return{x:l,y:u}}const{Matrix:Matrix$2,SVD:SVD,EVD:EVD,CholeskyDecomposition:CholeskyDecomposition$1,LuDecomposition:LuDecomposition$1,QrDecomposition:QrDecomposition$1}=MatrixLib,Array$1={min:min,max:max,median:median,mean:mean,mode:mode$1,normed:norm$1,rescale:rescale,sequentialFill:sequentialFill,standardDeviation:standardDeviation,sum:sum,variance:variance},ArrayXY={centroidsMerge:mergeByCentroids,closestX:closestX,covariance:covariance$1,maxMerge:maxMerge,maxY:maxY,sortX:sortX,uniqueX:uniqueX,weightedMerge:weightedMerge,equallySpaced:equallySpaced,filterX:filterX};exports.Array=Array$1,exports.ArrayXY=ArrayXY,exports.BitArray=src$7,exports.CholeskyDecomposition=CholeskyDecomposition$1,exports.ConfusionMatrix=src$1,exports.CrossValidation=src$3,exports.DecisionTreeClassifier=DecisionTreeClassifier,exports.DecisionTreeRegression=DecisionTreeRegression,exports.Distance=distances,exports.EVD=EVD,exports.ExponentialRegression=ExponentialRegression,exports.FCNNLS=index$2,exports.FNN=FeedForwardNeuralNetwork,exports.HClust=index,exports.HashTable=HashTable,exports.KMeans=kmeans,exports.KNN=KNN,exports.KOPLS=KOPLS,exports.Kernel=kernel,exports.LuDecomposition=LuDecomposition$1,exports.Matrix=Matrix$2,exports.MatrixLib=MatrixLib,exports.MultivariateLinearRegression=MultivariateLinearRegression,exports.NaiveBayes=index$1,exports.PCA=PCA,exports.PLS=PLS,exports.Performance=src$5,exports.PolynomialRegression=PolynomialRegression,exports.PowerRegression=PowerRegression,exports.QrDecomposition=QrDecomposition$1,exports.Random=Random,exports.RandomForestClassifier=RandomForestClassifier,exports.RandomForestRegression=RandomForestRegression,exports.RobustPolynomialRegression=RobustPolynomialRegression,exports.SOM=src$4,exports.SVD=SVD,exports.Similarity=similarities,exports.SimpleLinearRegression=SimpleLinearRegression,exports.SparseMatrix=SparseMatrix,exports.TheilSenRegression=TheilSenRegression,exports.XSadd=XSadd,exports.binarySearch=binarySearch,exports.distanceMatrix=distanceMatrix,exports.levenbergMarquardt=levenbergMarquardt,exports.numSort=index$3,exports.padArray=src$6,exports.savitzkyGolay=savitzkyGolay,Object.defineProperty(exports,"__esModule",{value:!0})})); + */function Node(t,e,r){this.obj=t,this.left=null,this.right=null,this.parent=r,this.dimension=e}class KDTree{constructor(t,e){if(Array.isArray(t)){this.dimensions=new Array(t[0].length);for(var r=0;re&&s.pop()}for(m=0;mt[n[i]]-e[n[i]]));const o=Math.floor(t.length/2),s=new Node(t[o],i,r);return s.left=buildTree(t.slice(0,o),e+1,s,n),s.right=buildTree(t.slice(o+1),e+1,s,n),s}function restoreParent(t){t.left&&(t.left.parent=t,restoreParent(t.left)),t.right&&(t.right.parent=t,restoreParent(t.right))}class BinaryHeap{constructor(t){this.content=[],this.scoreFunction=t}push(t){this.content.push(t),this.bubbleUp(this.content.length-1)}pop(){var t=this.content[0],e=this.content.pop();return this.content.length>0&&(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)o&&(i=h,o=u)}return i}function norm(t){return Math.sqrt(t.clone().apply(pow2array).sum())}function pow2array(t,e){this.set(t,e,this.get(t,e)**2)}function initializeMatrices(t,e){if(e)for(let e=0;ef&&Mf;)n=a.mmul(m),n.div(norm(n)),r=c,c=t.mmul(n),i=l.mmul(c),i.div(norm(i)),m=e.mmul(i);r=c;let v=a.mmul(r),b=r.transpose().mmul(r).get(0,0);o=v.div(b);let S=norm(o);o.div(S),r.mul(S),n.mul(S),v=m.transpose().mmul(r),b=r.transpose().mmul(r).get(0,0);let A=v.div(b).get(0,0);t.sub(r.mmul(o.transpose())),e.sub(r.clone().mul(A).mmul(i.transpose())),g.setColumn(M,r),p.setColumn(M,o),d.setColumn(M,m),w.setColumn(M,i),x.setColumn(M,n),y.set(M,M,A),M++}M--,g=g.subMatrix(0,g.rows-1,0,M),p=p.subMatrix(0,p.rows-1,0,M),d=d.subMatrix(0,d.rows-1,0,M),w=w.subMatrix(0,w.rows-1,0,M),x=x.subMatrix(0,x.rows-1,0,M),y=y.subMatrix(0,M,0,M),this.ssqYcal=c,this.E=t,this.F=e,this.T=g,this.P=p,this.U=d,this.Q=w,this.W=x,this.B=y,this.PBQ=p.mmul(y).mmul(w.transpose()),this.R2X=r.transpose().mmul(r).mmul(o.transpose().mmul(o)).div(u).get(0,0)}predict(t){let e=Matrix.checkMatrix(t);this.scale&&(e=e.subRowVector(this.meanX).divRowVector(this.stdDevX));let r=e.mmul(this.PBQ);return r=r.mulRowVector(this.stdDevY).addRowVector(this.meanY),r}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 PLS(!0,t)}}function maxSumColIndex(t){return Matrix.rowVector(t.sum("column")).maxIndex()[0]}class KOPLS{constructor(t,e){if(!0===t)this.trainingSet=new Matrix(e.trainingSet),this.YLoadingMat=new Matrix(e.YLoadingMat),this.SigmaPow=new Matrix(e.SigmaPow),this.YScoreMat=new Matrix(e.YScoreMat),this.predScoreMat=initializeMatrices(e.predScoreMat,!1),this.YOrthLoadingVec=initializeMatrices(e.YOrthLoadingVec,!1),this.YOrthEigen=e.YOrthEigen,this.YOrthScoreMat=initializeMatrices(e.YOrthScoreMat,!1),this.toNorm=initializeMatrices(e.toNorm,!1),this.TURegressionCoeff=initializeMatrices(e.TURegressionCoeff,!1),this.kernelX=initializeMatrices(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=Matrix.checkMatrix(t),e=Matrix.checkMatrix(e),this.trainingSet=t.clone();let r=this.kernel.compute(t),n=Matrix.eye(r.rows,r.rows,1),i=r;r=new Array(this.orthogonalComp+1);for(let t=0;t=0&&s>=0&&i[o][s]++}return new ConfusionMatrix(i,n)}getMatrix(){return this.matrix}getLabels(){return this.labels}getTotalCount(){let t=0;for(let e=0;e=0;--o){var s=this.tryEntries[o],a=s.completion;if("root"===s.tryLoc)return n("end");if(s.tryLoc<=this.prev){var l=i.call(s,"catchLoc"),h=i.call(s,"finallyLoc");if(l&&h){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),T(r),g}},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;T(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:I(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=r),g}}}function x(t,e,r,n){var i=e&&e.prototype instanceof v?e:v,o=Object.create(i.prototype),s=new C(n||[]);return o._invoke=R(t,r,s),o}function M(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}function v(){}function b(){}function S(){}function A(t){["next","throw","return"].forEach((function(e){t[e]=function(t){return this._invoke(e,t)}}))}function E(t){function e(r,n,o,s){var a=M(t[r],t,n);if("throw"!==a.type){var l=a.arg,h=l.value;return h&&"object"==typeof h&&i.call(h,"__await")?Promise.resolve(h.__await).then((function(t){e("next",t,o,s)}),(function(t){e("throw",t,o,s)})):Promise.resolve(h).then((function(t){l.value=t,o(l)}),s)}s(a.arg)}var r;function n(t,n){function i(){return new Promise((function(r,i){e(t,n,r,i)}))}return r=r?r.then(i,i):i()}this._invoke=n}function R(t,e,r){var n=u;return function(i,o){if(n===f)throw new Error("Generator is already running");if(n===m){if("throw"===i)throw o;return O()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var a=k(s,r);if(a){if(a===g)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===u)throw n=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=f;var l=M(t,e,r);if("normal"===l.type){if(n=r.done?m:c,l.arg===g)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(n=m,r.method="throw",r.arg=l.arg)}}}function k(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,k(t,e),"throw"===e.method))return g;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return g}var i=M(n,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,g;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,g):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,g)}function N(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 T(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function C(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(N,this),this.reset(!0)}function I(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,o=i&&n.regeneratorRuntime;n.regeneratorRuntime=void 0;var s=r;if(i)n.regeneratorRuntime=o;else try{delete n.regeneratorRuntime}catch(t){n.regeneratorRuntime=void 0}var a=s,l={mode:"index"};t.exports=a.mark((function t(e,r,n){var i,o,s,h,u,c,f,m,g;return a.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:for(g=function(){var t,e,r;for(e=1;h[e]<=0;)e++;if(0===h[e-1]){for(t=e-1;1!==t;t--)h[t]=-1;h[e]=0,u=f=0,h[1]=1,c=e-1}else{e>1&&(h[e-1]=0);do{e++}while(h[e]>0);for(r=e-1,t=e;0===h[t];)h[t++]=-1;if(-1===h[t])h[t]=h[r],f=h[r]-1,u=t-1,c=r-1,h[r]=-1;else{if(t===h[0])return 0;h[e]=h[t],f=h[t]-1,h[t]=0,u=e-1,c=t-1}}return 1},n=Object.assign({},l,n),i=new Array(r),o=new Array(e),s=new Array(r),h=new Array(r+2),m=0;ms[e-1].push(t))),s=s.slice(0,e),s.map(((t,e)=>({testIndex:t,trainIndex:[].concat(...s.filter(((t,r)=>r!==e)))})))}function sampleAClass(t,e){let r=JSON.parse(JSON.stringify(t)),n=Array.from(Array(r.length).keys()).sort(((t,e)=>r[t]ti[t]=(i[t]||0)+1));let o=[];Object.keys(i).forEach(((t,r)=>{let n=[];Object.values(i).reduce(((t,e,r)=>n[r]=t+e),0);let s=[...Array(i[t]).keys()],a=[];for(let r=0;rt+n[r-1])))}));let s=[];o.forEach((t=>s.push(n[t])));let a=[],l=[];return t.forEach(((t,e)=>{s.includes(e)?l.push(!0):(l.push(!1),a.push(e))})),{trainIndex:s,testIndex:a,mask:l}}function leaveOneOut(t,e,r,n){if("function"==typeof r){let n=r;return r=e,leavePOut(e=t,r,1,n)}return leavePOut(t,e,r,n,1)}function leavePOut(t,e,r,n,i){let o;"function"==typeof n&&(o=n,i=r,r=e,e=t),check(e,r);const s=getDistinct(r),a=initMatrix(s.length,s.length);let l=e.length,h=lib(i,l),u=new Array(l);for(let t=0;t=0;t--)l.splice(i[t],1);o?validateWithCallback(e,r,i,l,a,s,o):validate(t,e,r,n,i,l,a,s)}return new ConfusionMatrix(a,s)}function kFold(t,e,r,n,i){let o;"function"==typeof n&&(o=n,i=r,r=e,e=t),check(e,r);const s=getDistinct(r),a=initMatrix(s.length,s.length);let l=getFolds(e,i);for(let i=0;inew Array(e).fill(0)))}function getDistinct(t){let e=new Set;for(let r=0;r1e-10;t++)s=u.transpose().mmul(l).div(u.transpose().mmul(u).get(0,0)),s=s.transpose().div(norm(s)),i=l.mmul(s).div(s.transpose().mmul(s).get(0,0)),o=i.transpose().mmul(h).div(i.transpose().mmul(i).get(0,0)),a=h.mmul(o.transpose()),a=a.div(o.transpose().mmul(o).get(0,0)),t>0&&(c=a.clone().sub(u).pow(2).sum()/a.clone().pow(2).sum()),u=a.clone();let f=i.transpose().mmul(l).div(i.transpose().mmul(i).get(0,0)),m=f.clone().sub(s.transpose().mmul(f.transpose()).div(s.transpose().mmul(s).get(0,0)).mmul(s.transpose()));m.div(norm(m));let g=l.mmul(m.transpose()).div(m.mmul(m.transpose()).get(0,0)),p=g.transpose().mmul(l).div(g.transpose().mmul(g).get(0,0));return{filteredX:l.clone().sub(g.mmul(p)),weightsXOrtho:m,loadingsXOrtho:p,scoresXOrtho:g,weightsXPred:s,loadingsXpred:f,scoresXpred:i,loadingsY:o}}function tss(t){return Matrix.mul(t,t).sum()}class OPLS{constructor(t,e,r={}){if(!0===t){const t=r;return this.center=t.center,this.scale=t.scale,this.means=t.means,this.meansY=t.meansY,this.stdevs=t.stdevs,this.stdevs=t.stdevsY,this.model=t.model,this.tCV=t.tCV,this.tOrthCV=t.tOrthCV,this.yHatCV=t.yHatCV,void(this.mode=t.mode)}let n=t.clone();const{nComp:i=3,center:o=!0,scale:s=!0,cvFolds:a=[]}=r;let l,h;if("number"==typeof e[0])this.mode="regression",l=Matrix.from1DArray(e.length,1,e);else if("string"==typeof e[0])throw this.mode="discriminantAnalysis",l=e,new Error("discriminant analysis is not yet supported");if("Matrix"!==n.constructor.name)throw new TypeError("features must be of class Matrix");this.center=o,this.center?(this.means=n.mean("column"),this.meansY=l.mean("column")):this.stdevs=null,this.scale=s,this.scale?(this.stdevs=n.standardDeviation("column"),this.stdevsY=l.standardDeviation("column")):this.means=null,h=a.length>0?a:getFolds(e,5);let u=[];this.model=[],this.tCV=[],this.tOrthCV=[],this.yHatCV=[];let c,f=[],m=[];for(c=0;ct.R2x)),A=this.model.map((t=>t.R2y));this.output={Q2y:u,R2x:S,R2y:A,tPred:d.plsC.t,pPred:d.plsC.p,wPred:d.plsC.w,betasPred:d.plsC.betas,Qpc:d.plsC.q,tCV:g,tOrthCV:p,tOrth:d.tOrth,pOrth:d.pOrth,wOrth:d.wOrth,XOrth:w,yHat:d.totalPred,Yres:d.plsC.yResidual,E:b}}getLogs(){return this.output}getScores(){return{scoresX:this.tCV.map((t=>t.to1DArray())),scoresY:this.tOrthCV.map((t=>t.to1DArray()))}}static load(t){if("string"!=typeof t.name)throw new TypeError("model must have a name property");if("OPLS"!==t.name)throw new RangeError("invalid model: "+t.name);return new OPLS(!0,[],t)}toJSON(){return{name:"OPLS",center:this.center,scale:this.scale,means:this.means,stdevs:this.stdevs,model:this.model,tCV:this.tCV,tOrthCV:this.tOrthCV,yHatCV:this.yHatCV}}predict(t,e={}){let{trueLabels:r=[],nc:n=1}=e,i=[];r.length>0&&(r=Matrix.from1DArray(r.length,1,r),i=r.clone());let o=t.clone();this.center&&(o.center("column",{center:this.means}),i.rows>0&&"regression"===this.mode&&i.center("column",{center:this.meansY})),this.scale&&(o.scale("column",{scale:this.stdevs}),i.rows>0&&"regression"===this.mode&&i.scale("column",{scale:this.stdevsY}));let s,a,l,h,u,c=o.clone();for(let t=0;t0))return{tPred:u,tOrth:s,yHat:h};if("regression"===this.mode){let t=tss(i);return{tPred:u,tOrth:s,yHat:h,Q2y:1-tss(i.clone().sub(h))/t}}if("discriminantAnalysis"===this.mode){let t=[];return t=ConfusionMatrix.fromLabels(r.to1DArray(),h.to1DArray()),{tPred:u,tOrth:s,yHat:h,confusionMatrix:t}}}_predictAll(t,e,r={}){const{center:n=!0,scale:i=!0}=r;n&&(t.center("column"),e.center("column")),i&&(t.scale("column"),e.scale("column"),this.tssy=tss(e),this.tssx=tss(t));let o=OPLSNipals(t,e),s=new nipals(o.filteredX,{Y:e}),a=o.filteredX.mmul(s.w.transpose()),l=a.mmul(s.betas);return{R2y:1-tss(e.clone().sub(l))/this.tssy,R2x:tss(s.t.mmul(s.p))/this.tssx,xRes:o.filteredX,tOrth:o.scoresXOrtho,pOrth:o.loadingsXOrtho,wOrth:o.weightsXOrtho,tPred:a,totalPred:l,XOrth:o.scoresXOrtho.mmul(o.loadingsXOrtho),oplsC:o,plsC:s}}_getTrainTest(t,e,r){let n=new Matrix(r.testIndex.length,t.columns),i=new Matrix(r.testIndex.length,1);r.testIndex.forEach(((r,o)=>{n.setRow(o,t.getRow(r)),i.setRow(o,e.getRow(r))}));let o=new Matrix(r.trainIndex.length,t.columns),s=new Matrix(r.trainIndex.length,1);return r.trainIndex.forEach(((r,n)=>{o.setRow(n,t.getRow(r)),s.setRow(n,e.getRow(r))})),{trainFeatures:o,testFeatures:n,trainLabels:s,testLabels:i}}}var require$$0=getAugmentedNamespace(MatrixLib);function logistic(t){return 1/(1+Math.exp(-t))}function expELU(t,e){return t<0?e*(Math.exp(t)-1):t}function softExponential(t,e){return e<0?-Math.log(1-e*(t+e))/e:e>0?(Math.exp(e*t)-1)/e+e:t}function softExponentialPrime(t,e){return e<0?1/(1-e*(e+t)):Math.exp(e*t)}const ACTIVATION_FUNCTIONS={tanh:{activation:Math.tanh,derivate:t=>1-t*t},identity:{activation:t=>t,derivate:()=>1},logistic:{activation:logistic,derivate:t=>logistic(t)*(1-logistic(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:expELU,derivate:(t,e)=>t<0?expELU(t,e)+e:1},"soft-exponential":{activation:softExponential,derivate:softExponentialPrime}};class Layer{constructor(t){this.inputSize=t.inputSize,this.outputSize=t.outputSize,this.regularization=t.regularization,this.epsilon=t.epsilon,this.activation=t.activation,this.activationParam=t.activationParam;var e=ACTIVATION_FUNCTIONS[t.activation],r=e.activation.length,n=r>1?r=>e.activation(r,t.activationParam):e.activation,i=r>1?r=>e.derivate(r,t.activationParam):e.derivate;this.activationFunction=function(t,e){this.set(t,e,n(this.get(t,e)))},this.derivate=function(t,e){this.set(t,e,i(this.get(t,e)))},t.model?(this.W=require$$0.Matrix.checkMatrix(t.W),this.b=require$$0.Matrix.checkMatrix(t.b)):(this.W=require$$0.Matrix.rand(this.inputSize,this.outputSize),this.b=require$$0.Matrix.zeros(1,this.outputSize),this.W.apply((function(e,r){this.set(e,r,this.get(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.transpose().mmul(t),this.db=require$$0.Matrix.rowVector(t.sum("column"));var r=e.clone();return t.mmul(this.W.transpose()).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 Layer(t)}}class OutputLayer extends Layer{constructor(t){super(t),this.activationFunction=function(t,e){this.set(t,e,Math.exp(this.get(t,e)))}}static load(t){if("Layer"!==t.model)throw new RangeError("the current model is not a Layer model");return new OutputLayer(t)}}class FeedForwardNeuralNetworks{constructor(t){if((t=t||{}).model){this.hiddenLayers=t.hiddenLayers,this.iterations=t.iterations,this.learningRate=t.learningRate,this.regularization=t.regularization,this.dicts=t.dicts,this.activation=t.activation,this.activationParam=t.activationParam,this.model=new Array(t.layers.length);for(var e=0;e=0;--n){var o=n>0?this.model[n-1].a:t;i=this.model[n].backpropagation(i,o)}for(n=0;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]0&&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),l=Date.now();this.times.findBMU+=l-s;var h=Math.floor(e),u=a.x-h,c=a.x+h,f=a.y-h,m=a.y+h;for(r=u;r<=c;r++){var g=r;for(r<0?g+=this.x:r>=this.x&&(g-=this.x),n=f;n<=m;n++){var p=n;n<0?p+=this.y:n>=this.y&&(p-=this.y),(i=a[this.distanceMethod](this.nodes[g][p]))0&&e!==this.coefficients.length-1?s=" + "+s:e!==this.coefficients.length-1&&(s=" "+s)),o=s+o;return"+"===o.charAt(0)&&(o=o.slice(1)),"f(x) = "+o}static load(t){if("polynomialRegression"!==t.name)throw new TypeError("not a polynomial regression model");return new PolynomialRegression(!0,t)}}function regress(t,e,r,n){const i=e.length;let o;if(Array.isArray(n))o=n,n=o.length;else{n++,o=new Array(n);for(let t=0;t=0?`f(x) = ${maybeToPrecision(this.B,t)}e^{${maybeToPrecision(this.A,t)}x}`:`f(x) = \\frac{${maybeToPrecision(this.B,t)}}{e^{${maybeToPrecision(-this.A,t)}x}}`}static load(t){if("exponentialRegression"!==t.name)throw new TypeError("not a exponential regression model");return new ExponentialRegression(!0,t)}}function regress$2(t,e,r){const n=e.length,i=new Array(n);for(let t=0;t=0?`f(x) = ${maybeToPrecision(this.A,t)}x^{${maybeToPrecision(this.B,t)}}`:`f(x) = \\frac{${maybeToPrecision(this.A,t)}}{x^{${maybeToPrecision(-this.B,t)}}}`,e=e.replace(/e([+-]?[0-9]+)/g,"e^{$1}"),e}static load(t){if("powerRegression"!==t.name)throw new TypeError("not a power regression model");return new PowerRegression(!0,t)}}function regress$3(t,e,r){const n=e.length,i=new Array(n),o=new Array(n);for(let t=0;tMath.pow(t[0],2))).reduce(((t,e)=>t+e))/(e.rows-t.columns);this.stdError=Math.sqrt(n),this.stdErrorMatrix=pseudoInverse(o).mul(n),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 "+(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 MultivariateLinearRegression(!0,t)}}var require$$0$1=getAugmentedNamespace(euclidean$1);const{squaredEuclidean:squaredEuclidean$1}=require$$0$1,defaultOptions$7={sigma:1};class GaussianKernel{constructor(t){t=Object.assign({},defaultOptions$7,t),this.sigma=t.sigma,this.divisor=2*t.sigma*t.sigma}compute(t,e){const r=squaredEuclidean$1(t,e);return Math.exp(-r/this.divisor)}}var gaussianKernel=GaussianKernel;const defaultOptions$8={degree:1,constant:1,scale:1};class PolynomialKernel{constructor(t){t=Object.assign({},defaultOptions$8,t),this.degree=t.degree,this.constant=t.constant,this.scale=t.scale}compute(t,e){for(var r=0,n=0;n0&&e!==this.coefficients.length-1?s=" + "+s:e!==this.coefficients.length-1&&(s=" "+s)),o=s+o;return"+"===o.charAt(0)&&(o=o.slice(1)),"f(x) = "+o}static load(t){if("robustPolynomialRegression"!==t.name)throw new TypeError("not a RobustPolynomialRegression model");return new RobustPolynomialRegression(!0,t)}}function robustPolynomial(t,e,r,n){let i=Array(n).fill(0).map(((t,e)=>e));const o=getRandomTuples(e,r,n);for(var s,a=0;at.residual-e.residual));var e=t.length,r=Math.floor(e/2);return e%2==0?t[r-1]:t[r]}const toString$3=Object.prototype.toString;function isAnyArray$3(t){return toString$3.call(t).endsWith("Array]")}function errorCalculation(t,e,r){let n=0;const i=r(e);for(let e=0;e{let r=BigInt(0);return t.forEach((t=>r|=BigInt(1)<t.key-e.key<0?-1:1)),n=[],i=[];for(let t of r)t.key!==e&&(e=t.key,i.push([]),n.push(t.value)),i[i.length-1].push(t.index);return{values:n,indices:i}}function cssls(t,e,r,n,i){let o=Matrix.zeros(n,i);if(null===r){let r=new CholeskyDecomposition(t);if(!0===r.isPositiveDefinite())o=r.solve(e);else{let r=new LuDecomposition(t);o=!1===r.isSingular()?r.solve(Matrix.eye(n)).mmul(e):solve(t,e,{useSVD:!0})}}else{let s=sortCollectionSet(r).values,a=sortCollectionSet(r).indices;if(1===s.length&&0===s[0].length&&a[0].length===i)return o;if(1===s.length&&s[0].length===n&&a[0].length===i){let r=new CholeskyDecomposition(t);if(!0===r.isPositiveDefinite())o=r.solve(e);else{let r=new LuDecomposition(t);o=!1===r.isSingular()?r.solve(Matrix.eye(n)).mmul(e):solve(t,e,{useSVD:!0})}}else for(let r=0;r0?h[t].push(e):l.set(e,t,0)}let u=[];for(let t=0;tt-e));return{Pset:o,Fset:i,W:s}}function fcnnls(t,e,r={}){t=Matrix.checkMatrix(t),e=Matrix.checkMatrix(e);let{l:n,p:i,iter:o,W:s,XtX:a,XtY:l,K:h,Pset:u,Fset:c,D:f}=initialisation(t,e);const{maxIterations:m=3*t.columns}=r;for(;c.length>0;){let t=cssls(a,l.subMatrixColumn(c),selection(u,c),n,c.length);for(let e=0;e0){let e=r.length,i=Matrix.ones(n,e);for(;e>0&&oe===g[t])),1);t=cssls(a,l.subMatrixColumn(r),selection(u,r),n,e);for(let n=0;n=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 assertNumber(t){if("number"!=typeof t)throw new TypeError("Expected a number")}var ascending=(t,e)=>(assertNumber(t),assertNumber(e),Number.isNaN(t)?-1:Number.isNaN(e)?1:t-e),descending=(t,e)=>(assertNumber(t),assertNumber(e),Number.isNaN(t)?1:Number.isNaN(e)?-1:e-t),numSort={ascending:ascending,descending:descending},index$4=Object.freeze(Object.assign(Object.create(null),numSort,{default:numSort,ascending:ascending,descending:descending}));const largestPrime=2147483647,primeNumbers=[largestPrime,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,433,877,1759,3527,7057,14143,28289,56591,113189,226379,452759,905551,1811107,3622219,7244441,14488931,28977863,57955739,115911563,231823147,463646329,927292699,1854585413,953,1907,3821,7643,15287,30577,61169,122347,244703,489407,978821,1957651,3915341,7830701,15661423,31322867,62645741,125291483,250582987,501165979,1002331963,2004663929,1039,2081,4177,8363,16729,33461,66923,133853,267713,535481,1070981,2141977,4283963,8567929,17135863,34271747,68543509,137087021,274174111,548348231,1096696463,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,599,1201,2411,4831,9677,19373,38747,77509,155027,310081,620171,1240361,2480729,4961459,9922933,19845871,39691759,79383533,158767069,317534141,635068283,1270136683,311,631,1277,2557,5119,10243,20507,41017,82037,164089,328213,656429,1312867,2625761,5251529,10503061,21006137,42012281,84024581,168049163,336098327,672196673,1344393353,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,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,379,761,1523,3049,6101,12203,24407,48817,97649,195311,390647,781301,1562611,3125257,6250537,12501169,25002389,50004791,100009607,200019221,400038451,800076929,1600153859,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,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,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 nextPrime(t){let e=binarySearch(primeNumbers,t,ascending);return e<0&&(e=~e),primeNumbers[e]}primeNumbers.sort(ascending);const FREE=0,FULL=1,REMOVED=2,defaultInitialCapacity=150,defaultMinLoadFactor=1/6,defaultMaxLoadFactor=2/3;class HashTable{constructor(t={}){if(t instanceof HashTable)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?defaultInitialCapacity:t.initialCapacity;if(e<0)throw new RangeError("initial capacity must not be less than zero: "+e);const r=void 0===t.minLoadFactor?defaultMinLoadFactor:t.minLoadFactor,n=void 0===t.maxLoadFactor?defaultMaxLoadFactor:t.maxLoadFactor;if(r<0||r>=1)throw new RangeError("invalid minLoadFactor: "+r);if(n<=0||n>=1)throw new RangeError("invalid maxLoadFactor: "+n);if(r>=n)throw new RangeError(`minLoadFactor (${r}) must be smaller than maxLoadFactor (${n})`);let i=e;i=i/n|0,i=nextPrime(i),0===i&&(i=1),this.table=newArray$1(i),this.values=newArray$1(i),this.state=newArray$1(i),this.minLoadFactor=r,this.maxLoadFactor=i===largestPrime?1:n,this.distinct=0,this.freeEntries=i,this.lowWaterMark=0,this.highWaterMark=chooseHighWaterMark(i,this.maxLoadFactor)}clone(){return new HashTable(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=chooseGrowCapacity(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]===FREE&&this.freeEntries--,this.state[r]=FULL,this.distinct++,this.freeEntries<1){const t=chooseGrowCapacity(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]=REMOVED,this.distinct--,e||this.maybeShrinkCapacity(),!0)}delete(t,e){const r=this.indexOfKey(t);return!(r<0)&&(this.state[r]=FREE,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]!==FREE&&(r[o]===REMOVED||e[o]!==t);)o-=s,o<0&&(o+=n);return r[o]===FREE?-1:o}containsValue(t){return this.indexOfValue(t)>=0}indexOfValue(t){const e=this.values,r=this.state;for(var n=0;nthis.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,l)=>(o.set(n*e+t,i*r+a,s*l),l))),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;i=n);h++)a+=e[h],l+=t[h]*e[h];return agetSimilarity(e,r,t)}var index$5=Object.freeze({__proto__:null,treeSimilarity:treeSimilarity,getFunction:getFunction,createTree:createTree});function cosine(t,e){for(var r=t.length,n=0,i=0,o=0,s=0;s{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},measures={acc:acc,err:err,fpr:fpr,tpr:tpr,fnr:fnr,tnr:tnr,ppv:ppv,npv:npv,pcfall:pcfall,pcmiss:pcmiss,lift:lift,rpp:rpp,rnp:rnp,threshold:threshold};class Performance{constructor(t,e,r){if(r=r||{},t.length!==e.length||t[0].length!==e[0].length)throw new Error("dimensions of prediction and target do not match");const n=t.length,i=t[0].length,o=!r.max,s=[];if(r.all)for(var a=0;at.pred-e.pred)):s.sort(((t,e)=>e.pred-t.pred));const h=this.cutoffs=[o?Number.MIN_VALUE:Number.MAX_VALUE],u=this.fp=[0],c=this.tp=[0];var f=0,m=0,g=s[0].pred,p=0,d=0;for(a=0;ar||e.size[1]>r)throw new RangeError("expanded value should not be bigger than the data length");for(i=0;i0;)e*=t--;return e}const defaultOptions$h={windowSize:5,derivative:1,polynomial:2,pad:"none",padValue:"replicate"};function savitzkyGolay(t,e,r){if((r=Object.assign({},defaultOptions$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");let n,i,o=Math.floor(r.windowSize/2);"pre"===r.pad&&(t=src$2(t,{size:o,value:r.padValue}));let s=new Array(t.length-2*o);if(5!==r.windowSize||2!==r.polynomial||1!==r.derivative&&2!==r.derivative){let t=Matrix.ones(r.windowSize,r.polynomial+1),e=-(r.windowSize-1)/2;for(let r=0;r>8&255]+creator[t[r]>>16&255]+creator[t[r]>>24&255];return e}function and(t,e){for(var r=new Array(t.length),n=0;n>5]&r)}function setBit(t,e,r){var n=e>>5,i=1<<31-e%32;return t[n]=r?i|t[n]:~i&t[n],t}function toBinaryString(t){for(var e="",r=0;r>>0).toString(2);e+="00000000000000000000000000000000".substr(n.length)+n}return e}function parseBinaryString(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}function parseHexString(t){for(var e=t.length/8,r=new Array(e),n=0;nt.length)throw new RangeError(`Window size is higher than the data length ${n}>${t.length}`);if(i<0||!Number.isInteger(i))throw new RangeError("Derivative should be a positive integer");if(o<1||!Number.isInteger(o))throw new RangeError("Polynomial should be a positive integer");o>=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");let s=Math.floor(n/2),a=t.length,l=new Array(a),h=fullWeights(n,o,i),u=0,c=!0;Array.isArray(e)?c=!1:u=Math.pow(e,i);for(let r=0;r=0&&n0?(4*r-2)/(r*(2*e-r+1))*(t*GramPoly(t,e,r-1,n)+n*GramPoly(t,e,r-1,n-1))-(r-1)*(2*e+r)/(r*(2*e-r+1))*GramPoly(t,e,r-2,n):0===r&&0===n?1:0,i}function GenFact(t,e){let r=1;if(t>=e)for(let n=t-e+1;n<=t;n++)r*=n;return r}function Weight(t,e,r,n,i){let o=0;for(let s=0;s<=n;s++)o+=(2*s+1)*(GenFact(2*r,s)/GenFact(2*r+s+1,s+1))*GramPoly(t,r,s,0)*GramPoly(e,r,s,i);return o}function fullWeights(t,e,r){let n=new Array(t),i=Math.floor(t/2);for(let o=-i;o<=i;o++){n[o+i]=new Array(t);for(let t=-i;t<=i;t++)n[o+i][t+i]=Weight(t,o,i,e,r)}return n}function gsd(t,e,r={}){let{noiseLevel:n,sgOptions:i={windowSize:9,polynomial:3},smoothY:o=!0,heightFactor:s=0,broadRatio:a=0,maxCriteria:l=!0,minMaxRatio:h=25e-5,derivativeThreshold:u=-1,realTopDetection:c=!1}=r;const f=e.slice();let m=isEqualSpaced(t);void 0===n&&(n=m?getNoiseLevel(f):0);const g={m:1,b:n};l||(g.m=-1,g.b*=-1);for(let t=0;tb&&(b=Math.abs(d[t])),Math.abs(w[t])>S&&(S=Math.abs(w[t]));let A=null,E=null,R=new Array(w.length-2),k=new Array(w.length),N=new Array(w.length),T=new Array(w.length-2),C=0,I=0,O=0,L=0;for(let t=1;tu&&((p[t]0&&null!==A&&(k[I++]=A,N[O++]=E)),(p[t]>=p[t-1]&&p[t]>p[t+1]||p[t]>p[t-1]&&p[t]>=p[t+1])&&(A={x:M[t],index:t},v<0&&null!==E&&(k[I++]=A,N[O++]=E))),d[t]h*S&&(z[$++]={index:R[t],x:P,y:(w[R[t]]+g.b)/g.m,width:Math.abs(N[F].x-k[F].x),soft:T[t]},z[$-1].left=k[F],z[$-1].right=N[F],s)){let t=w[k[F].index],e=w[N[F].index];z[$-1].height=s*(z[$-1].y-(t+e)/2)}}z.length=$,c&&determineRealTop(z,M,w);for(let t=0;t{let e,r=0,n=Number.MAX_SAFE_INTEGER;for(let i=0;ir&&(r=e);return(r-n)/r<.05},getNoiseLevel=t=>{let e=0,r=0,n=t.length;for(let r=0;rt-e)),r=n%2==1?i[(n-1)/2]/.6745:.5*(i[n/2]+i[n/2-1])/.6745,r},determineRealTop=(t,e,r)=>{let n,i,o,s,a;for(let l=0;l=r[a-2]&&r[a-1]>=r[a]?a--:r[a+1]>=r[a]&&r[a+1]>=r[a+2]?a++:r[a-2]>=r[a-3]&&r[a-2]>=r[a-1]?a-=2:r[a+2]>=r[a+1]&&r[a+2]>=r[a+3]&&(a+=2),r[a-1]>0&&r[a+1]>0&&r[a]>=r[a-1]&&r[a]>=r[a+1]&&(r[a]!==r[a-1]||r[a]!==r[a+1])&&(n=20*Math.log10(r[a-1]),i=20*Math.log10(r[a]),o=20*Math.log10(r[a+1]),s=.5*(n-o)/(n-2*i+o),t[l].x=e[a]+(e[a]-e[a-1])*s,t[l].y=r[a]-.25*(r[a-1]-r[a+1])*s)};function sumOfGaussians(t){return function(e){let r,n=t.length/3,i=e.length,o=void 0===i?0:new Float64Array(i).fill(0);for(let s=0;sr[e]/=o));let s=e.length,a=new Float64Array(3*s),l=new Float64Array(3*s),h=new Float64Array(3*s),u=Math.abs(n[0]-n[1]);for(let t=0;tr[e]/=o));let s=Math.abs(n[0]-n[1]),a={damping:1.5,initialValues:new Float64Array([e.x,1,e.width]),minValues:new Float64Array([e.x-s,0,e.width/4]),maxValues:new Float64Array([e.x+s,1.25,4*e.width]),gradientDifference:s/1e4,maxIterations:100,errorTolerance:1e-4},l=levenbergMarquardt({x:n,y:i},singleGaussian,r=Object.assign({},a,r));return{parameters:[l.parameterValues[0],l.parameterValues[1]*o,l.parameterValues[2]],error:l.parameterError}}function sumOfLorentzians(t){return function(e){let r,n,i=t.length/3,o=e.length,s=void 0===o?0:new Float64Array(o).fill(0);for(let a=0;ar[e]/=o));let s=e.length,a=new Float64Array(3*s),l=new Float64Array(3*s),h=new Float64Array(3*s),u=Math.abs(n[0]-n[1]);for(let t=0;tr[e]/=o));let s=Math.abs(n[0]-n[1]),a={damping:1.5,initialValues:new Float64Array([e.x,1,e.width]),minValues:new Float64Array([e.x-s,.75,e.width/4]),maxValues:new Float64Array([e.x+s,1.25,4*e.width]),gradientDifference:s/1e4,maxIterations:100,errorTolerance:1e-4},l=levenbergMarquardt({x:n,y:i},singleLorentzian,r=Object.assign({},a,r));return{parameters:[l.parameterValues[0],l.parameterValues[1]*o,l.parameterValues[2]],error:l.parameterError}}function optimizePeaks(t,e,r,n={}){const{functionName:i="gaussian",factorWidth:o=4,optimizationOptions:s={damping:1.5,maxIterations:100,errorTolerance:1e-4}}=n;let a,l=[0],h=groupPeaks(t,o),u=[],c=1;"gaussian"===i&&(c=1.17741);for(let t=0;t1){if(a=sampleFunction(h[t].limits[0]-h[t].limits[1],h[t].limits[0]+h[t].limits[1],e,r,l),a[0].length>5){let t=[];"gaussian"===i?t=optimizeGaussianSum(a,n,s):"lorentzian"===i&&(t=optimizeLorentzianSum(a,n,s));for(let e=0;e5){let t=[];"gaussian"===i?t=optimizeSingleGaussian([a[0],a[1]],n,s):"lorentzian"===i&&(t=optimizeSingleLorentzian([a[0],a[1]],n,s));let{parameters:e}=t;u.push({x:e[0],y:e[1],width:e[2]*c,index:n.index})}}return u}function sampleFunction(t,e,r,n,i){let o=r.length,s=[],a=[],l=Math.sign(r[1]-r[0]);-1===l&&(i[0]=r.length-1);let h=Math.abs(e-t)/2,u=(t+e)/2,c=!1,f=i[0];for(;!c&&f=0;)Math.abs(r[f]-u)<=h?(s.push(r[f]),a.push(n[f]),f+=l):1===Math.sign(u-r[f])?f+=l:c=!0;return i[0]=f,[s,a]}function groupPeaks(t,e){let r,n,i=[],o=[],s=[t[0].x,e*t[0].width];for(let a=0;ar&&(r=t[a].x+e*t[a].width),n=s[0]-s[1],t[a].x-e*t[a].width=0;t--)if(Math.abs(o[t].limits[0]-o[t+1].limits[0])<(o[t].limits[1]+o[t+1].limits[1])/2){for(let e=0;er&&(r=o[t+1].limits[0]+o[t+1].limits[1]),n=o[t].limits[0]-o[t].limits[1],o[t+1].limits[0]-o[t+1].limits[1]=0;e--)t[e].soft&&n.push(t.splice(e,1)[0]);n.push({x:Number.MAX_VALUE});let a=[[n[0].x,n[0].y]],l=[n[0].index];for(let e=1;ei&&(i=n[e].y,o=e),l.push(n[e].index),s++;else{if(s>2){let e=optimizeSingleLorentzian(a,{x:n[o].x,y:i,width:Math.abs(a[0][0]-a[a.length-1][0])}),{parameters:r}=e;t.push({x:r[0],y:r[1],width:r[2],index:Math.floor(l.reduce(((t,e)=>t+e),0)/l.length),soft:!1})}else l.forEach((e=>{t.push(n[e])}));a=[[n[e].x,n[e].y]],l=[e],i=n[e].y,o=e,s=1}return t.sort((function(t,e){return t.x-e.x})),t}function broadenPeaks(t,e={}){const{factor:r=2,overlap:n=!1}=e;for(let e of t)e.right&&e.left?(e.from=e.x-(e.x-e.left.x)*r,e.to=e.x+(e.right.x-e.x)*r):(e.from=e.x-e.width/2*r,e.to=e.x+e.width/2*r);if(!n)for(let e=0;en.from&&(r.to=n.from=(r.to+n.from)/2)}for(let e of t)e.width=e.to-e.from;return t}var index$6=Object.freeze({__proto__:null,gsd:gsd,optimizePeaks:optimizePeaks,joinBroadPeaks:joinBroadPeaks,broadenPeaks:broadenPeaks});const toString$4=Object.prototype.toString;function isAnyArray$4(t){return toString$4.call(t).endsWith("Array]")}function min$1(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!isAnyArray$4(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");var r=e.fromIndex,n=void 0===r?0:r,i=e.toIndex,o=void 0===i?t.length:i;if(n<0||n>=t.length||!Number.isInteger(n))throw new Error("fromIndex must be a positive integer smaller than length");if(o<=n||o>t.length||!Number.isInteger(o))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var s=t[n],a=n+1;a1&&void 0!==arguments[1]?arguments[1]:{};if(!isAnyArray$4(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");var r=e.fromIndex,n=void 0===r?0:r,i=e.toIndex,o=void 0===i?t.length:i;if(n<0||n>=t.length||!Number.isInteger(n))throw new Error("fromIndex must be a positive integer smaller than length");if(o<=n||o>t.length||!Number.isInteger(o))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var s=t[n],a=n+1;as&&(s=t[a]);return s}function mode$1(t){if(!isAnyArray$4(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");for(var e=0,r=0,n=0,i={},o=0;or&&(r=n,e=t[o])}return e}const toString$5=Object.prototype.toString;function isAnyArray$5(t){return toString$5.call(t).endsWith("Array]")}function max$2(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!isAnyArray$5(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");var r=e.fromIndex,n=void 0===r?0:r,i=e.toIndex,o=void 0===i?t.length:i;if(n<0||n>=t.length||!Number.isInteger(n))throw new Error("fromIndex must be a positive integer smaller than length");if(o<=n||o>t.length||!Number.isInteger(o))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var s=t[n],a=n+1;as&&(s=t[a]);return s}function norm$1(t){var e,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.algorithm,i=void 0===n?"absolute":n,o=r.sumValue,s=void 0===o?1:o,a=r.maxValue,l=void 0===a?1:a;if(!isAnyArray$5(t))throw new Error("input must be an array");if(void 0!==r.output){if(!isAnyArray$5(r.output))throw new TypeError("output option must be an array if specified");e=r.output}else e=new Array(t.length);if(0===t.length)throw new Error("input must not be empty");switch(i.toLowerCase()){case"absolute":var h=absoluteSum(t)/s;if(0===h)return t.slice(0);for(var u=0;u0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("object"!==_typeof(t)||isAnyArray$4(t)||(e=t,t=[]),!isAnyArray$4(t))throw new TypeError("input must be an array");var r=e,n=r.from,i=void 0===n?0:n,o=r.to,s=void 0===o?10:o,a=r.size,l=void 0===a?t.length:a,h=r.step;if(0!==l&&h)throw new Error("step is defined by the array size");if(l||(l=h?Math.floor((s-i)/h)+1:s-i+1),!h&&l&&(h=(s-i)/(l-1)),Array.isArray(t)){t.length=0;for(var u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(!isAnyArray$6(t))throw new TypeError("input must be an array");for(var r=e.unbiased,n=void 0===r||r,i=e.mean,o=void 0===i?mean(t):i,s=0,a=0;a1&&void 0!==arguments[1]?arguments[1]:{};return Math.sqrt(variance(t,e))}function mergeByCentroids(t,e,r={}){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[s],y:n[s]}:(s=~s,0!==s&&Math.abs(r[s]-i)>.5||s===r.length?{x:r[s-1],y:n[s-1]}:{x:r[s],y:n[s]})}function covariance$1(t,e={}){const{x:r,y:n}=t,{unbiased:i=!0}=e,o=mean(r),s=mean(n);var a=0;for(let t=0;ti?(s.x.push(r[l]),s.y.push(n[l]),o.x.push(r[l]),o.y.push(n[l]),l++,a++):(n[l]>s.y[a-1]&&(s.x[a-1]=r[l],s.y[a-1]=n[l]),o.x[a-1]=r[l],o.y[a-1]+=n[l],l++);return o.x=s.x.slice(),o}function maxY(t,e={}){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=calculateIndex(i.value,r,s)),void 0!==o.value&&void 0===o.index&&(o.index=calculateIndex(o.value,r,s));for(var a,l=Number.MIN_VALUE,h=i.index;he.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()},l=0;li?(s.x.push(r[l]*n[l]),s.y.push(n[l]),o.x.push(r[l]),o.y.push(n[l]),l++,a++):(s.x[a-1]+=r[l]*n[l],s.y[a-1]+=n[l],o.x[a-1]=r[l],o.y[a-1]+=n[l],l++);for(var h=0;hn&&([r,n]=[n,r]),(t=(t=JSON.parse(JSON.stringify(t)).map((t=>t.from>t.to?{from:t.to,to:t.from}:t))).sort(((t,e)=>t.from!==e.from?t.from-e.from:t.to-e.to))).forEach((t=>{r>t.from&&(t.from=r),nt.from<=t.to))).length)return[];let i=t[0],o=[i];for(let e=1;en&&([r,n]=[n,r]),0===(t=normalize(t,{from:r,to:n})).length)return[{from:r,to:n}];let i=[];for(let e=0;er&&i.push({from:r,to:o.from}),e===t.length-1?o.tot+(e.to-e.from)),0)/e,i=0;for(let r=0;r=0;){if(A=integral(0,f-m,y,g),v=w+A,l[S++]=(v-M)/s,S===i)break t;c=f,f+=s,M=v}w+=integral(m,p,y,x),m=p,g=d,b=p)throw new Error("x must be an increasing serie");for(;m-f>0;){if(y&&(M++,y=!1),u[b]=M<=0?0:x/M,b++,b===i)break t;c=f,f+=s,x=0,M=0}m>c&&(x+=g,M++),(m===-Number.MAX_VALUE||w>1)&&M--,m=p,g=d,v1&&r[0]>r[1]&&(r=r.slice().reverse(),n=n.slice().reverse(),o=!0);let{from:s=r[0],to:a=r[i-1],variant:l="smooth",numberOfPoints:h=100,exclusions:u=[],zones:c=[]}=e;if(i!==n.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 a||isNaN(a))throw new RangeError("'to' option must be a number");if("number"!=typeof h||isNaN(h))throw new RangeError("'numberOfPoints' option must be a number");if(h<2)throw new RangeError("'numberOfPoints' option must be greater than 1");0===c.length&&(c=invert(u,{from:s,to:a})),c=zonesWithPoints(c,h,{from:s,to:a});let f=[],m=[];for(let t of c){let e=processZone(r,n,t.from,t.to,t.numberOfPoints,l);f=f.concat(e.x),m=m.concat(e.y)}return o?se&&([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[l].from)h.push(r[c]),u.push(n[c]);else if(r[c]>a[l].to&&(l++,!a[l]))break;c++}return{x:h,y:u}}const{Matrix:Matrix$2,SVD:SVD,EVD:EVD,CholeskyDecomposition:CholeskyDecomposition$1,LuDecomposition:LuDecomposition$1,QrDecomposition:QrDecomposition$1}=MatrixLib,Array$1={min:min$1,max:max$1,median:median,mean:mean,mode:mode$1,normed:norm$1,rescale:rescale,sequentialFill:sequentialFill,standardDeviation:standardDeviation,sum:sum,variance:variance},ArrayXY={centroidsMerge:mergeByCentroids,closestX:closestX,covariance:covariance$1,maxMerge:maxMerge,maxY:maxY,sortX:sortX,uniqueX:uniqueX,weightedMerge:weightedMerge,equallySpaced:equallySpaced,filterX:filterX};exports.Array=Array$1,exports.ArrayXY=ArrayXY,exports.BitArray=src$3,exports.CholeskyDecomposition=CholeskyDecomposition$1,exports.ConfusionMatrix=ConfusionMatrix,exports.CrossValidation=index$2,exports.DecisionTreeClassifier=DecisionTreeClassifier,exports.DecisionTreeRegression=DecisionTreeRegression,exports.Distance=distances,exports.EVD=EVD,exports.ExponentialRegression=ExponentialRegression,exports.FCNNLS=index$3,exports.FNN=FeedForwardNeuralNetwork,exports.GSD=index$6,exports.HClust=index,exports.HashTable=HashTable,exports.KMeans=kmeans,exports.KNN=KNN,exports.KOPLS=KOPLS,exports.Kernel=kernel,exports.LuDecomposition=LuDecomposition$1,exports.Matrix=Matrix$2,exports.MatrixLib=MatrixLib,exports.MultivariateLinearRegression=MultivariateLinearRegression,exports.NaiveBayes=index$1,exports.OPLS=OPLS,exports.OPLSNipals=OPLSNipals,exports.PCA=PCA,exports.PLS=PLS,exports.Performance=src$1,exports.PolynomialRegression=PolynomialRegression,exports.PowerRegression=PowerRegression,exports.QrDecomposition=QrDecomposition$1,exports.Random=Random,exports.RandomForestClassifier=RandomForestClassifier,exports.RandomForestRegression=RandomForestRegression,exports.RobustPolynomialRegression=RobustPolynomialRegression,exports.SOM=src,exports.SVD=SVD,exports.Similarity=similarities,exports.SimpleLinearRegression=SimpleLinearRegression,exports.SparseMatrix=SparseMatrix,exports.TheilSenRegression=TheilSenRegression,exports.XSadd=XSadd,exports.binarySearch=binarySearch,exports.distanceMatrix=distanceMatrix,exports.levenbergMarquardt=levenbergMarquardt,exports.numSort=index$4,exports.padArray=src$2,exports.savitzkyGolay=savitzkyGolay,Object.defineProperty(exports,"__esModule",{value:!0})})); //# sourceMappingURL=ml.min.js.map diff --git a/dist/ml.min.js.map b/dist/ml.min.js.map index 7d50fd8..cb45a49 100644 --- a/dist/ml.min.js.map +++ b/dist/ml.min.js.map @@ -1 +1 @@ -{"version":3,"file":"ml.min.js","sources":["../node_modules/is-any-array/src/index.js","../node_modules/ml-array-max/lib-es6/index.js","../node_modules/ml-array-min/lib-es6/index.js","../node_modules/ml-array-rescale/lib-es6/index.js","../node_modules/ml-matrix/src/util.js","../node_modules/ml-matrix/src/stat.js","../node_modules/ml-matrix/src/inspect.js","../node_modules/ml-matrix/src/mathOperations.js","../node_modules/ml-matrix/src/matrix.js","../node_modules/ml-matrix/src/views/base.js","../node_modules/ml-matrix/src/views/column.js","../node_modules/ml-matrix/src/views/columnSelection.js","../node_modules/ml-matrix/src/views/flipColumn.js","../node_modules/ml-matrix/src/views/flipRow.js","../node_modules/ml-matrix/src/views/row.js","../node_modules/ml-matrix/src/views/rowSelection.js","../node_modules/ml-matrix/src/views/selection.js","../node_modules/ml-matrix/src/views/sub.js","../node_modules/ml-matrix/src/views/transpose.js","../node_modules/ml-matrix/src/wrap/WrapperMatrix1D.js","../node_modules/ml-matrix/src/wrap/WrapperMatrix2D.js","../node_modules/ml-matrix/src/wrap/wrap.js","../node_modules/ml-matrix/src/dc/lu.js","../node_modules/ml-matrix/src/dc/util.js","../node_modules/ml-matrix/src/dc/qr.js","../node_modules/ml-matrix/src/dc/svd.js","../node_modules/ml-matrix/src/decompositions.js","../node_modules/ml-matrix/src/determinant.js","../node_modules/ml-matrix/src/linearDependencies.js","../node_modules/ml-matrix/src/pseudoInverse.js","../node_modules/ml-matrix/src/covariance.js","../node_modules/ml-matrix/src/correlation.js","../node_modules/ml-matrix/src/dc/evd.js","../node_modules/ml-matrix/src/dc/cholesky.js","../node_modules/ml-matrix/src/dc/nipals.js","../node_modules/ml-array-sum/lib-es6/index.js","../node_modules/ml-array-mean/lib-es6/index.js","../node_modules/ml-cart/src/utils.js","../node_modules/ml-cart/src/TreeNode.js","../node_modules/ml-cart/src/DecisionTreeClassifier.js","../node_modules/ml-cart/src/DecisionTreeRegression.js","../node_modules/random-js/dist/random-js.esm.js","../node_modules/ml-random-forest/src/utils.js","../node_modules/ml-random-forest/src/RandomForestBase.js","../node_modules/ml-random-forest/src/RandomForestClassifier.js","../node_modules/median-quickselect/lib/median-quickselect.min.js","../node_modules/ml-array-median/lib-es6/index.js","../node_modules/ml-random-forest/src/RandomForestRegression.js","../node_modules/ml-pca/src/pca.js","../node_modules/ml-distance-euclidean/lib-es6/euclidean.js","../node_modules/ml-distance-matrix/src/index.js","../node_modules/heap/lib/heap.js","../node_modules/heap/index.js","../node_modules/ml-hclust/src/Cluster.js","../node_modules/ml-hclust/src/agnes.js","../node_modules/ml-nearest-vector/lib-es6/index.js","../node_modules/ml-kmeans/src/utils.js","../node_modules/ml-xsadd/lib-es6/xsadd.js","../node_modules/ml-random/lib-es6/choice.js","../node_modules/ml-random/lib-es6/index.js","../node_modules/ml-kmeans/src/initialization.js","../node_modules/ml-kmeans/src/KMeansResult.js","../node_modules/ml-kmeans/src/kmeans.js","../node_modules/ml-naivebayes/src/utils.js","../node_modules/ml-naivebayes/src/GaussianNB.js","../node_modules/ml-naivebayes/src/MultinomialNB.js","../node_modules/ml-knn/src/KDTree.js","../node_modules/ml-knn/src/index.js","../node_modules/ml-pls/src/utils.js","../node_modules/ml-pls/src/pls.js","../node_modules/ml-pls/src/kopls.js","../node_modules/ml-confusion-matrix/src/index.js","../node_modules/ml-combinations/src/index.js","../node_modules/ml-cross-validation/src/index.js","../node_modules/ml-fnn/FeedForwardNeuralNetwork.js","../node_modules/ml-som/src/node-square.js","../node_modules/ml-som/src/node-hexagonal.js","../node_modules/ml-som/src/index.js","../node_modules/ml-regression-base/src/maybeToPrecision.js","../node_modules/ml-regression-base/src/checkArrayLength.js","../node_modules/ml-regression-base/src/index.js","../node_modules/ml-regression-polynomial/src/index.js","../node_modules/ml-regression-simple-linear/src/index.js","../node_modules/ml-regression-exponential/src/index.js","../node_modules/ml-regression-power/src/index.js","../node_modules/ml-regression-multivariate-linear/src/index.js","../node_modules/ml-kernel-gaussian/gaussian-kernel.js","../node_modules/ml-kernel-polynomial/polynomial-kernel.js","../node_modules/ml-kernel-sigmoid/sigmoid-kernel.js","../node_modules/ml-kernel/src/kernels/anova-kernel.js","../node_modules/ml-kernel/src/kernels/cauchy-kernel.js","../node_modules/ml-kernel/src/kernels/exponential-kernel.js","../node_modules/ml-kernel/src/kernels/histogram-intersection-kernel.js","../node_modules/ml-kernel/src/kernels/laplacian-kernel.js","../node_modules/ml-kernel/src/kernels/multiquadratic-kernel.js","../node_modules/ml-kernel/src/kernels/rational-quadratic-kernel.js","../node_modules/ml-kernel/src/kernel.js","../node_modules/ml-regression-theil-sen/src/index.js","../node_modules/ml-regression-robust-polynomial/src/index.js","../node_modules/ml-levenberg-marquardt/src/errorCalculation.js","../node_modules/ml-levenberg-marquardt/src/step.js","../node_modules/ml-levenberg-marquardt/src/index.js","../node_modules/ml-fcnnls/src/util/selection.js","../node_modules/ml-fcnnls/src/util/sortCollectionSet.js","../node_modules/ml-fcnnls/src/cssls.js","../node_modules/ml-fcnnls/src/initialisation.js","../node_modules/ml-fcnnls/src/util/setDifference.js","../node_modules/ml-fcnnls/src/optimality.js","../node_modules/ml-fcnnls/src/fcnnls.js","../node_modules/ml-fcnnls/src/fcnnlsVector.js","../node_modules/binary-search/index.js","../node_modules/num-sort/index.js","../node_modules/ml-hash-table/src/primeFinder.js","../node_modules/ml-hash-table/src/HashTable.js","../node_modules/ml-sparse-matrix/src/index.js","../node_modules/ml-distance/src/distances/additiveSymmetric.js","../node_modules/ml-distance/src/distances/avg.js","../node_modules/ml-distance/src/distances/bhattacharyya.js","../node_modules/ml-distance/src/distances/canberra.js","../node_modules/ml-distance/src/distances/chebyshev.js","../node_modules/ml-distance/src/distances/clark.js","../node_modules/ml-distance/src/similarities/czekanowski.js","../node_modules/ml-distance/src/distances/czekanowski.js","../node_modules/ml-distance/src/distances/dice.js","../node_modules/ml-distance/src/distances/divergence.js","../node_modules/ml-distance/src/distances/fidelity.js","../node_modules/ml-distance/src/distances/gower.js","../node_modules/ml-distance/src/distances/harmonicMean.js","../node_modules/ml-distance/src/distances/hellinger.js","../node_modules/ml-distance/src/distances/innerProduct.js","../node_modules/ml-distance/src/distances/intersection.js","../node_modules/ml-distance/src/distances/jaccard.js","../node_modules/ml-distance/src/distances/jeffreys.js","../node_modules/ml-distance/src/distances/jensenDifference.js","../node_modules/ml-distance/src/distances/jensenShannon.js","../node_modules/ml-distance/src/distances/kdivergence.js","../node_modules/ml-distance/src/distances/kulczynski.js","../node_modules/ml-distance/src/distances/kullbackLeibler.js","../node_modules/ml-distance/src/distances/kumarHassebrook.js","../node_modules/ml-distance/src/distances/kumarJohnson.js","../node_modules/ml-distance/src/distances/lorentzian.js","../node_modules/ml-distance/src/distances/manhattan.js","../node_modules/ml-distance/src/distances/matusita.js","../node_modules/ml-distance/src/distances/minkowski.js","../node_modules/ml-distance/src/distances/motyka.js","../node_modules/ml-distance/src/distances/neyman.js","../node_modules/ml-distance/src/distances/pearson.js","../node_modules/ml-distance/src/distances/probabilisticSymmetric.js","../node_modules/ml-distance/src/distances/ruzicka.js","../node_modules/ml-distance/src/distances/soergel.js","../node_modules/ml-distance/src/distances/sorensen.js","../node_modules/ml-distance/src/distances/squared.js","../node_modules/ml-distance/src/distances/squaredChord.js","../node_modules/ml-distance/src/distances/taneja.js","../node_modules/ml-distance/src/similarities/tanimoto.js","../node_modules/ml-distance/src/distances/tanimoto.js","../node_modules/ml-distance/src/distances/topsoe.js","../node_modules/ml-distance/src/distances/waveHedges.js","../node_modules/ml-tree-similarity/src/createTree.js","../node_modules/ml-tree-similarity/src/getSimilarity.js","../node_modules/ml-tree-similarity/src/index.js","../node_modules/ml-distance/src/similarities/cosine.js","../node_modules/ml-distance/src/similarities/dice.js","../node_modules/ml-distance/src/similarities/intersection.js","../node_modules/ml-distance/src/similarities/jaccard.js","../node_modules/ml-distance/src/similarities/kulczynski.js","../node_modules/ml-distance/src/similarities/motyka.js","../node_modules/ml-distance/src/similarities/pearson.js","../node_modules/ml-distance/src/similarities/squaredChord.js","../node_modules/ml-performance/src/measures.js","../node_modules/ml-performance/src/index.js","../node_modules/ml-pad-array/src/index.js","../node_modules/ml-savitzky-golay/src/index.js","../node_modules/ml-bit-array/src/creator.js","../node_modules/ml-bit-array/src/index.js","../node_modules/ml-array-mode/lib-es6/index.js","../node_modules/ml-array-normed/lib-es6/index.js","../node_modules/ml-array-sequential-fill/lib-es6/index.js","../node_modules/ml-array-variance/lib-es6/index.js","../node_modules/ml-array-standard-deviation/lib-es6/index.js","../node_modules/ml-array-xy-centroids-merge/src/index.js","../node_modules/ml-arrayxy-closestx/src/index.js","../node_modules/ml-array-xy-covariance/src/index.js","../node_modules/ml-array-xy-max-merge/src/index.js","../node_modules/ml-array-xy-max-y/src/index.js","../node_modules/ml-array-xy-sort-x/src/index.js","../node_modules/ml-arrayxy-uniquex/src/index.js","../node_modules/ml-array-xy-weighted-merge/src/index.js","../node_modules/ml-array-xy-equally-spaced/src/integral.js","../node_modules/ml-array-xy-equally-spaced/src/equallySpacedSmooth.js","../node_modules/ml-array-xy-equally-spaced/src/equallySpacedSlot.js","../node_modules/ml-array-xy-equally-spaced/src/getZones.js","../node_modules/ml-array-xy-equally-spaced/src/index.js","../node_modules/ml-array-xy-filter-x/src/getZones.js","../node_modules/ml-array-xy-filter-x/src/index.js","../src/index.js"],"sourcesContent":["'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","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 maxValue = input[0];\n\n for (var i = 1; i < input.length; i++) {\n if (input[i] > maxValue) maxValue = input[i];\n }\n\n return maxValue;\n}\n\nexport default max;\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 minValue = input[0];\n\n for (var i = 1; i < input.length; i++) {\n if (input[i] < minValue) minValue = input[i];\n }\n\n return minValue;\n}\n\nexport default min;\n","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","/**\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 let 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 let 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 let 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 let 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 newArray(length, value = 0) {\n let array = [];\n for (let i = 0; i < length; i++) {\n array.push(value);\n }\n return array;\n}\n\nfunction checkNumber(name, value) {\n if (typeof value !== 'number') {\n throw new TypeError(`${name} must be a number`);\n }\n}\n","import { newArray } from './util';\n\nexport function sumByRow(matrix) {\n let sum = newArray(matrix.rows);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[i] += matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function sumByColumn(matrix) {\n let sum = newArray(matrix.columns);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[j] += matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function sumAll(matrix) {\n let v = 0;\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n v += matrix.get(i, j);\n }\n }\n return v;\n}\n\nexport function productByRow(matrix) {\n let sum = newArray(matrix.rows, 1);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[i] *= matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function productByColumn(matrix) {\n let sum = newArray(matrix.columns, 1);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[j] *= matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function productAll(matrix) {\n let v = 1;\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n v *= matrix.get(i, j);\n }\n }\n return v;\n}\n\nexport function varianceByRow(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const variance = [];\n\n for (let i = 0; i < rows; i++) {\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let j = 0; j < cols; j++) {\n x = matrix.get(i, j) - mean[i];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n variance.push((sum2 - (sum1 * sum1) / cols) / (cols - 1));\n } else {\n variance.push((sum2 - (sum1 * sum1) / cols) / cols);\n }\n }\n return variance;\n}\n\nexport function varianceByColumn(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const variance = [];\n\n for (let j = 0; j < cols; j++) {\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let i = 0; i < rows; i++) {\n x = matrix.get(i, j) - mean[j];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n variance.push((sum2 - (sum1 * sum1) / rows) / (rows - 1));\n } else {\n variance.push((sum2 - (sum1 * sum1) / rows) / rows);\n }\n }\n return variance;\n}\n\nexport function varianceAll(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const size = rows * cols;\n\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n x = matrix.get(i, j) - mean;\n sum1 += x;\n sum2 += x * x;\n }\n }\n if (unbiased) {\n return (sum2 - (sum1 * sum1) / size) / (size - 1);\n } else {\n return (sum2 - (sum1 * sum1) / size) / size;\n }\n}\n\nexport function centerByRow(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean[i]);\n }\n }\n}\n\nexport function centerByColumn(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean[j]);\n }\n }\n}\n\nexport function centerAll(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean);\n }\n }\n}\n\nexport function getScaleByRow(matrix) {\n const scale = [];\n for (let i = 0; i < matrix.rows; i++) {\n let sum = 0;\n for (let j = 0; j < matrix.columns; j++) {\n sum += Math.pow(matrix.get(i, j), 2) / (matrix.columns - 1);\n }\n scale.push(Math.sqrt(sum));\n }\n return scale;\n}\n\nexport function scaleByRow(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale[i]);\n }\n }\n}\n\nexport function getScaleByColumn(matrix) {\n const scale = [];\n for (let j = 0; j < matrix.columns; j++) {\n let sum = 0;\n for (let i = 0; i < matrix.rows; i++) {\n sum += Math.pow(matrix.get(i, j), 2) / (matrix.rows - 1);\n }\n scale.push(Math.sqrt(sum));\n }\n return scale;\n}\n\nexport function scaleByColumn(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale[j]);\n }\n }\n}\n\nexport function getScaleAll(matrix) {\n const divider = matrix.size - 1;\n let sum = 0;\n for (let j = 0; j < matrix.columns; j++) {\n for (let i = 0; i < matrix.rows; i++) {\n sum += Math.pow(matrix.get(i, j), 2) / divider;\n }\n }\n return Math.sqrt(sum);\n}\n\nexport function scaleAll(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale);\n }\n }\n}\n","export function inspectMatrix() {\n const indent = ' '.repeat(2);\n const indentData = ' '.repeat(4);\n return `${this.constructor.name} {\n${indent}[\n${indentData}${inspectData(this, indentData)}\n${indent}]\n${indent}rows: ${this.rows}\n${indent}columns: ${this.columns}\n}`;\n}\n\nconst maxRows = 15;\nconst maxColumns = 10;\nconst maxNumSize = 8;\n\nfunction inspectData(matrix, indent) {\n const { rows, columns } = matrix;\n const maxI = Math.min(rows, maxRows);\n const maxJ = Math.min(columns, maxColumns);\n const result = [];\n for (let i = 0; i < maxI; i++) {\n let line = [];\n for (let j = 0; j < maxJ; j++) {\n line.push(formatNumber(matrix.get(i, j)));\n }\n result.push(`${line.join(' ')}`);\n }\n if (maxJ !== columns) {\n result[result.length - 1] += ` ... ${columns - maxColumns} more columns`;\n }\n if (maxI !== rows) {\n result.push(`... ${rows - maxRows} more rows`);\n }\n return result.join(`\\n${indent}`);\n}\n\nfunction formatNumber(num) {\n const numStr = String(num);\n if (numStr.length <= maxNumSize) {\n return numStr.padEnd(maxNumSize, ' ');\n }\n const precise = num.toPrecision(maxNumSize - 2);\n if (precise.length <= maxNumSize) {\n return precise;\n }\n const exponential = num.toExponential(maxNumSize - 2);\n const eIndex = exponential.indexOf('e');\n const e = exponential.substring(eIndex);\n return exponential.substring(0, maxNumSize - e.length) + e;\n}\n","export function installMathOperations(AbstractMatrix, Matrix) {\n AbstractMatrix.prototype.add = function add(value) {\n if (typeof value === 'number') return this.addS(value);\n return this.addM(value);\n };\n\n AbstractMatrix.prototype.addS = function addS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.addM = function addM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.add = function add(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.add(value);\n };\n\n AbstractMatrix.prototype.sub = function sub(value) {\n if (typeof value === 'number') return this.subS(value);\n return this.subM(value);\n };\n\n AbstractMatrix.prototype.subS = function subS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.subM = function subM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.sub = function sub(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sub(value);\n };\n AbstractMatrix.prototype.subtract = AbstractMatrix.prototype.sub;\n AbstractMatrix.prototype.subtractS = AbstractMatrix.prototype.subS;\n AbstractMatrix.prototype.subtractM = AbstractMatrix.prototype.subM;\n AbstractMatrix.subtract = AbstractMatrix.sub;\n\n AbstractMatrix.prototype.mul = function mul(value) {\n if (typeof value === 'number') return this.mulS(value);\n return this.mulM(value);\n };\n\n AbstractMatrix.prototype.mulS = function mulS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.mulM = function mulM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.mul = function mul(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.mul(value);\n };\n AbstractMatrix.prototype.multiply = AbstractMatrix.prototype.mul;\n AbstractMatrix.prototype.multiplyS = AbstractMatrix.prototype.mulS;\n AbstractMatrix.prototype.multiplyM = AbstractMatrix.prototype.mulM;\n AbstractMatrix.multiply = AbstractMatrix.mul;\n\n AbstractMatrix.prototype.div = function div(value) {\n if (typeof value === 'number') return this.divS(value);\n return this.divM(value);\n };\n\n AbstractMatrix.prototype.divS = function divS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.divM = function divM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.div = function div(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.div(value);\n };\n AbstractMatrix.prototype.divide = AbstractMatrix.prototype.div;\n AbstractMatrix.prototype.divideS = AbstractMatrix.prototype.divS;\n AbstractMatrix.prototype.divideM = AbstractMatrix.prototype.divM;\n AbstractMatrix.divide = AbstractMatrix.div;\n\n AbstractMatrix.prototype.mod = function mod(value) {\n if (typeof value === 'number') return this.modS(value);\n return this.modM(value);\n };\n\n AbstractMatrix.prototype.modS = function modS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) % value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.modM = function modM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) % matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.mod = function mod(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.mod(value);\n };\n AbstractMatrix.prototype.modulus = AbstractMatrix.prototype.mod;\n AbstractMatrix.prototype.modulusS = AbstractMatrix.prototype.modS;\n AbstractMatrix.prototype.modulusM = AbstractMatrix.prototype.modM;\n AbstractMatrix.modulus = AbstractMatrix.mod;\n\n AbstractMatrix.prototype.and = function and(value) {\n if (typeof value === 'number') return this.andS(value);\n return this.andM(value);\n };\n\n AbstractMatrix.prototype.andS = function andS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) & value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.andM = function andM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) & matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.and = function and(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.and(value);\n };\n\n AbstractMatrix.prototype.or = function or(value) {\n if (typeof value === 'number') return this.orS(value);\n return this.orM(value);\n };\n\n AbstractMatrix.prototype.orS = function orS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) | value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.orM = function orM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) | matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.or = function or(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.or(value);\n };\n\n AbstractMatrix.prototype.xor = function xor(value) {\n if (typeof value === 'number') return this.xorS(value);\n return this.xorM(value);\n };\n\n AbstractMatrix.prototype.xorS = function xorS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) ^ value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.xorM = function xorM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) ^ matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.xor = function xor(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.xor(value);\n };\n\n AbstractMatrix.prototype.leftShift = function leftShift(value) {\n if (typeof value === 'number') return this.leftShiftS(value);\n return this.leftShiftM(value);\n };\n\n AbstractMatrix.prototype.leftShiftS = function leftShiftS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) << value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.leftShiftM = function leftShiftM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) << matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.leftShift = function leftShift(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.leftShift(value);\n };\n\n AbstractMatrix.prototype.signPropagatingRightShift = function signPropagatingRightShift(value) {\n if (typeof value === 'number') return this.signPropagatingRightShiftS(value);\n return this.signPropagatingRightShiftM(value);\n };\n\n AbstractMatrix.prototype.signPropagatingRightShiftS = function signPropagatingRightShiftS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) >> value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.signPropagatingRightShiftM = function signPropagatingRightShiftM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) >> matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.signPropagatingRightShift = function signPropagatingRightShift(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.signPropagatingRightShift(value);\n };\n\n AbstractMatrix.prototype.rightShift = function rightShift(value) {\n if (typeof value === 'number') return this.rightShiftS(value);\n return this.rightShiftM(value);\n };\n\n AbstractMatrix.prototype.rightShiftS = function rightShiftS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) >>> value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.rightShiftM = function rightShiftM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) >>> matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.rightShift = function rightShift(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.rightShift(value);\n };\n AbstractMatrix.prototype.zeroFillRightShift = AbstractMatrix.prototype.rightShift;\n AbstractMatrix.prototype.zeroFillRightShiftS = AbstractMatrix.prototype.rightShiftS;\n AbstractMatrix.prototype.zeroFillRightShiftM = AbstractMatrix.prototype.rightShiftM;\n AbstractMatrix.zeroFillRightShift = AbstractMatrix.rightShift;\n\n AbstractMatrix.prototype.not = function not() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, ~(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.not = function not(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.not();\n };\n\n AbstractMatrix.prototype.abs = function abs() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.abs(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.abs = function abs(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.abs();\n };\n\n AbstractMatrix.prototype.acos = function acos() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.acos(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.acos = function acos(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.acos();\n };\n\n AbstractMatrix.prototype.acosh = function acosh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.acosh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.acosh = function acosh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.acosh();\n };\n\n AbstractMatrix.prototype.asin = function asin() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.asin(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.asin = function asin(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.asin();\n };\n\n AbstractMatrix.prototype.asinh = function asinh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.asinh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.asinh = function asinh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.asinh();\n };\n\n AbstractMatrix.prototype.atan = function atan() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.atan(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.atan = function atan(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.atan();\n };\n\n AbstractMatrix.prototype.atanh = function atanh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.atanh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.atanh = function atanh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.atanh();\n };\n\n AbstractMatrix.prototype.cbrt = function cbrt() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.cbrt(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.cbrt = function cbrt(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.cbrt();\n };\n\n AbstractMatrix.prototype.ceil = function ceil() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.ceil(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.ceil = function ceil(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.ceil();\n };\n\n AbstractMatrix.prototype.clz32 = function clz32() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.clz32(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.clz32 = function clz32(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.clz32();\n };\n\n AbstractMatrix.prototype.cos = function cos() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.cos(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.cos = function cos(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.cos();\n };\n\n AbstractMatrix.prototype.cosh = function cosh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.cosh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.cosh = function cosh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.cosh();\n };\n\n AbstractMatrix.prototype.exp = function exp() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.exp(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.exp = function exp(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.exp();\n };\n\n AbstractMatrix.prototype.expm1 = function expm1() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.expm1(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.expm1 = function expm1(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.expm1();\n };\n\n AbstractMatrix.prototype.floor = function floor() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.floor(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.floor = function floor(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.floor();\n };\n\n AbstractMatrix.prototype.fround = function fround() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.fround(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.fround = function fround(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.fround();\n };\n\n AbstractMatrix.prototype.log = function log() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.log(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.log = function log(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.log();\n };\n\n AbstractMatrix.prototype.log1p = function log1p() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.log1p(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.log1p = function log1p(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.log1p();\n };\n\n AbstractMatrix.prototype.log10 = function log10() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.log10(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.log10 = function log10(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.log10();\n };\n\n AbstractMatrix.prototype.log2 = function log2() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.log2(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.log2 = function log2(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.log2();\n };\n\n AbstractMatrix.prototype.round = function round() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.round(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.round = function round(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.round();\n };\n\n AbstractMatrix.prototype.sign = function sign() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.sign(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.sign = function sign(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sign();\n };\n\n AbstractMatrix.prototype.sin = function sin() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.sin(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.sin = function sin(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sin();\n };\n\n AbstractMatrix.prototype.sinh = function sinh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.sinh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.sinh = function sinh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sinh();\n };\n\n AbstractMatrix.prototype.sqrt = function sqrt() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.sqrt(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.sqrt = function sqrt(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sqrt();\n };\n\n AbstractMatrix.prototype.tan = function tan() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.tan(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.tan = function tan(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.tan();\n };\n\n AbstractMatrix.prototype.tanh = function tanh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.tanh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.tanh = function tanh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.tanh();\n };\n\n AbstractMatrix.prototype.trunc = function trunc() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.trunc(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.trunc = function trunc(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.trunc();\n };\n\n AbstractMatrix.pow = function pow(matrix, arg0) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.pow(arg0);\n };\n\n AbstractMatrix.prototype.pow = function pow(value) {\n if (typeof value === 'number') return this.powS(value);\n return this.powM(value);\n };\n\n AbstractMatrix.prototype.powS = function powS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.pow(this.get(i, j), value));\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.powM = function powM(matrix) {\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.pow(this.get(i, j), matrix.get(i, j)));\n }\n }\n return this;\n };\n}\n","import rescale from 'ml-array-rescale';\n\nimport {\n checkRowVector,\n checkRowIndex,\n checkColumnIndex,\n checkColumnVector,\n checkRange,\n checkIndices,\n} from './util';\nimport {\n sumByRow,\n sumByColumn,\n sumAll,\n productByRow,\n productByColumn,\n productAll,\n varianceByRow,\n varianceByColumn,\n varianceAll,\n centerByRow,\n centerByColumn,\n centerAll,\n scaleByRow,\n scaleByColumn,\n scaleAll,\n getScaleByRow,\n getScaleByColumn,\n getScaleAll,\n} from './stat';\nimport { inspectMatrix } from './inspect';\nimport { installMathOperations } from './mathOperations';\n\nexport class AbstractMatrix {\n static from1DArray(newRows, newColumns, newData) {\n let length = newRows * newColumns;\n if (length !== newData.length) {\n throw new RangeError('data length does not match given dimensions');\n }\n let newMatrix = new Matrix(newRows, newColumns);\n for (let row = 0; row < newRows; row++) {\n for (let column = 0; column < newColumns; column++) {\n newMatrix.set(row, column, newData[row * newColumns + column]);\n }\n }\n return newMatrix;\n }\n\n static rowVector(newData) {\n let vector = new Matrix(1, newData.length);\n for (let i = 0; i < newData.length; i++) {\n vector.set(0, i, newData[i]);\n }\n return vector;\n }\n\n static columnVector(newData) {\n let vector = new Matrix(newData.length, 1);\n for (let i = 0; i < newData.length; i++) {\n vector.set(i, 0, newData[i]);\n }\n return vector;\n }\n\n static zeros(rows, columns) {\n return new Matrix(rows, columns);\n }\n\n static ones(rows, columns) {\n return new Matrix(rows, columns).fill(1);\n }\n\n static rand(rows, columns, options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { random = Math.random } = options;\n let matrix = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n matrix.set(i, j, random());\n }\n }\n return matrix;\n }\n\n static randInt(rows, columns, options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1000, random = Math.random } = options;\n if (!Number.isInteger(min)) throw new TypeError('min must be an integer');\n if (!Number.isInteger(max)) throw new TypeError('max must be an integer');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let interval = max - min;\n let matrix = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n let value = min + Math.round(random() * interval);\n matrix.set(i, j, value);\n }\n }\n return matrix;\n }\n\n static eye(rows, columns, value) {\n if (columns === undefined) columns = rows;\n if (value === undefined) value = 1;\n let min = Math.min(rows, columns);\n let matrix = this.zeros(rows, columns);\n for (let i = 0; i < min; i++) {\n matrix.set(i, i, value);\n }\n return matrix;\n }\n\n static diag(data, rows, columns) {\n let l = data.length;\n if (rows === undefined) rows = l;\n if (columns === undefined) columns = rows;\n let min = Math.min(l, rows, columns);\n let matrix = this.zeros(rows, columns);\n for (let i = 0; i < min; i++) {\n matrix.set(i, i, data[i]);\n }\n return matrix;\n }\n\n static min(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n let rows = matrix1.rows;\n let columns = matrix1.columns;\n let result = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let 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 static max(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n let rows = matrix1.rows;\n let columns = matrix1.columns;\n let result = new this(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let 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 static checkMatrix(value) {\n return AbstractMatrix.isMatrix(value) ? value : new Matrix(value);\n }\n\n static isMatrix(value) {\n return value != null && value.klass === 'Matrix';\n }\n\n get size() {\n return this.rows * this.columns;\n }\n\n apply(callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('callback must be a function');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n callback.call(this, i, j);\n }\n }\n return this;\n }\n\n to1DArray() {\n let array = [];\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n array.push(this.get(i, j));\n }\n }\n return array;\n }\n\n to2DArray() {\n let copy = [];\n for (let i = 0; i < this.rows; i++) {\n copy.push([]);\n for (let j = 0; j < this.columns; j++) {\n copy[i].push(this.get(i, j));\n }\n }\n return copy;\n }\n\n toJSON() {\n return this.to2DArray();\n }\n\n isRowVector() {\n return this.rows === 1;\n }\n\n isColumnVector() {\n return this.columns === 1;\n }\n\n isVector() {\n return this.rows === 1 || this.columns === 1;\n }\n\n isSquare() {\n return this.rows === this.columns;\n }\n\n isSymmetric() {\n if (this.isSquare()) {\n for (let i = 0; i < this.rows; i++) {\n for (let 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 isEchelonForm() {\n let i = 0;\n let j = 0;\n let previousColumn = -1;\n let isEchelonForm = true;\n let checked = false;\n while (i < this.rows && isEchelonForm) {\n j = 0;\n checked = false;\n while (j < this.columns && checked === false) {\n if (this.get(i, j) === 0) {\n j++;\n } else if (this.get(i, j) === 1 && j > previousColumn) {\n checked = true;\n previousColumn = j;\n } else {\n isEchelonForm = false;\n checked = true;\n }\n }\n i++;\n }\n return isEchelonForm;\n }\n\n isReducedEchelonForm() {\n let i = 0;\n let j = 0;\n let previousColumn = -1;\n let isReducedEchelonForm = true;\n let checked = false;\n while (i < this.rows && isReducedEchelonForm) {\n j = 0;\n checked = false;\n while (j < this.columns && checked === false) {\n if (this.get(i, j) === 0) {\n j++;\n } else if (this.get(i, j) === 1 && j > previousColumn) {\n checked = true;\n previousColumn = j;\n } else {\n isReducedEchelonForm = false;\n checked = true;\n }\n }\n for (let k = j + 1; k < this.rows; k++) {\n if (this.get(i, k) !== 0) {\n isReducedEchelonForm = false;\n }\n }\n i++;\n }\n return isReducedEchelonForm;\n }\n\n echelonForm() {\n let result = this.clone();\n let h = 0;\n let k = 0;\n while (h < result.rows && k < result.columns) {\n let iMax = h;\n for (let i = h; i < result.rows; i++) {\n if (result.get(i, k) > result.get(iMax, k)) {\n iMax = i;\n }\n }\n if (result.get(iMax, k) === 0) {\n k++;\n } else {\n result.swapRows(h, iMax);\n let tmp = result.get(h, k);\n for (let j = k; j < result.columns; j++) {\n result.set(h, j, result.get(h, j) / tmp);\n }\n for (let i = h + 1; i < result.rows; i++) {\n let factor = result.get(i, k) / result.get(h, k);\n result.set(i, k, 0);\n for (let j = k + 1; j < result.columns; j++) {\n result.set(i, j, result.get(i, j) - result.get(h, j) * factor);\n }\n }\n h++;\n k++;\n }\n }\n return result;\n }\n\n reducedEchelonForm() {\n let result = this.echelonForm();\n let m = result.columns;\n let n = result.rows;\n let h = n - 1;\n while (h >= 0) {\n if (result.maxRow(h) === 0) {\n h--;\n } else {\n let p = 0;\n let pivot = false;\n while (p < n && pivot === false) {\n if (result.get(h, p) === 1) {\n pivot = true;\n } else {\n p++;\n }\n }\n for (let i = 0; i < h; i++) {\n let factor = result.get(i, p);\n for (let j = p; j < m; j++) {\n let tmp = result.get(i, j) - factor * result.get(h, j);\n result.set(i, j, tmp);\n }\n }\n h--;\n }\n }\n return result;\n }\n\n set() {\n throw new Error('set method is unimplemented');\n }\n\n get() {\n throw new Error('get method is unimplemented');\n }\n\n repeat(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { rows = 1, columns = 1 } = options;\n if (!Number.isInteger(rows) || rows <= 0) {\n throw new TypeError('rows must be a positive integer');\n }\n if (!Number.isInteger(columns) || columns <= 0) {\n throw new TypeError('columns must be a positive integer');\n }\n let matrix = new Matrix(this.rows * rows, this.columns * columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\n }\n }\n return matrix;\n }\n\n fill(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, value);\n }\n }\n return this;\n }\n\n neg() {\n return this.mulS(-1);\n }\n\n getRow(index) {\n checkRowIndex(this, index);\n let row = [];\n for (let i = 0; i < this.columns; i++) {\n row.push(this.get(index, i));\n }\n return row;\n }\n\n getRowVector(index) {\n return Matrix.rowVector(this.getRow(index));\n }\n\n setRow(index, array) {\n checkRowIndex(this, index);\n array = checkRowVector(this, array);\n for (let i = 0; i < this.columns; i++) {\n this.set(index, i, array[i]);\n }\n return this;\n }\n\n swapRows(row1, row2) {\n checkRowIndex(this, row1);\n checkRowIndex(this, row2);\n for (let i = 0; i < this.columns; i++) {\n let 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 getColumn(index) {\n checkColumnIndex(this, index);\n let column = [];\n for (let i = 0; i < this.rows; i++) {\n column.push(this.get(i, index));\n }\n return column;\n }\n\n getColumnVector(index) {\n return Matrix.columnVector(this.getColumn(index));\n }\n\n setColumn(index, array) {\n checkColumnIndex(this, index);\n array = checkColumnVector(this, array);\n for (let i = 0; i < this.rows; i++) {\n this.set(i, index, array[i]);\n }\n return this;\n }\n\n swapColumns(column1, column2) {\n checkColumnIndex(this, column1);\n checkColumnIndex(this, column2);\n for (let i = 0; i < this.rows; i++) {\n let 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 addRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 subRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 mulRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 divRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 addColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 subColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 mulColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 divColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 mulRow(index, value) {\n checkRowIndex(this, index);\n for (let i = 0; i < this.columns; i++) {\n this.set(index, i, this.get(index, i) * value);\n }\n return this;\n }\n\n mulColumn(index, value) {\n checkColumnIndex(this, index);\n for (let i = 0; i < this.rows; i++) {\n this.set(i, index, this.get(i, index) * value);\n }\n return this;\n }\n\n max() {\n let v = this.get(0, 0);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 maxIndex() {\n let v = this.get(0, 0);\n let idx = [0, 0];\n for (let i = 0; i < this.rows; i++) {\n for (let 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 min() {\n let v = this.get(0, 0);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 minIndex() {\n let v = this.get(0, 0);\n let idx = [0, 0];\n for (let i = 0; i < this.rows; i++) {\n for (let 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 maxRow(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n for (let 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 maxRowIndex(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n let idx = [row, 0];\n for (let 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 minRow(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n for (let 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 minRowIndex(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n let idx = [row, 0];\n for (let 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 maxColumn(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n for (let 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 maxColumnIndex(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n let idx = [0, column];\n for (let 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 minColumn(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n for (let 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 minColumnIndex(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n let idx = [0, column];\n for (let 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 diag() {\n let min = Math.min(this.rows, this.columns);\n let diag = [];\n for (let i = 0; i < min; i++) {\n diag.push(this.get(i, i));\n }\n return diag;\n }\n\n norm(type = 'frobenius') {\n let result = 0;\n if (type === 'max') {\n return this.max();\n } else if (type === 'frobenius') {\n for (let i = 0; i < this.rows; i++) {\n for (let 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 cumulativeSum() {\n let sum = 0;\n for (let i = 0; i < this.rows; i++) {\n for (let 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 dot(vector2) {\n if (AbstractMatrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\n let vector1 = this.to1DArray();\n if (vector1.length !== vector2.length) {\n throw new RangeError('vectors do not have the same size');\n }\n let dot = 0;\n for (let i = 0; i < vector1.length; i++) {\n dot += vector1[i] * vector2[i];\n }\n return dot;\n }\n\n mmul(other) {\n other = Matrix.checkMatrix(other);\n\n let m = this.rows;\n let n = this.columns;\n let p = other.columns;\n\n let result = new Matrix(m, p);\n\n let Bcolj = new Float64Array(n);\n for (let j = 0; j < p; j++) {\n for (let k = 0; k < n; k++) {\n Bcolj[k] = other.get(k, j);\n }\n\n for (let i = 0; i < m; i++) {\n let s = 0;\n for (let 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 other = Matrix.checkMatrix(other);\n let result = new Matrix(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 other = Matrix.checkMatrix(other);\n let result = new Matrix(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 mmulStrassen(y) {\n y = Matrix.checkMatrix(y);\n let x = this.clone();\n let r1 = x.rows;\n let c1 = x.columns;\n let r2 = y.rows;\n let c2 = y.columns;\n if (c1 !== r2) {\n // eslint-disable-next-line no-console\n console.warn(\n `Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`,\n );\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 let r = mat.rows;\n let c = mat.columns;\n if (r === rows && c === cols) {\n return mat;\n } else {\n let resultat = AbstractMatrix.zeros(rows, cols);\n resultat = resultat.setSubMatrix(mat, 0, 0);\n return resultat;\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 let r = Math.max(r1, r2);\n let 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 let halfRows = parseInt(a.rows / 2, 10);\n let halfCols = parseInt(a.columns / 2, 10);\n // Subdivide input matrices.\n let a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n let b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n\n let a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\n let b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\n\n let a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\n let b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\n\n let a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\n let b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\n\n // Compute intermediate values.\n let m1 = blockMult(\n AbstractMatrix.add(a11, a22),\n AbstractMatrix.add(b11, b22),\n halfRows,\n halfCols,\n );\n let m2 = blockMult(AbstractMatrix.add(a21, a22), b11, halfRows, halfCols);\n let m3 = blockMult(a11, AbstractMatrix.sub(b12, b22), halfRows, halfCols);\n let m4 = blockMult(a22, AbstractMatrix.sub(b21, b11), halfRows, halfCols);\n let m5 = blockMult(AbstractMatrix.add(a11, a12), b22, halfRows, halfCols);\n let m6 = blockMult(\n AbstractMatrix.sub(a21, a11),\n AbstractMatrix.add(b11, b12),\n halfRows,\n halfCols,\n );\n let m7 = blockMult(\n AbstractMatrix.sub(a12, a22),\n AbstractMatrix.add(b21, b22),\n halfRows,\n halfCols,\n );\n\n // Combine intermediate values into the output.\n let c11 = AbstractMatrix.add(m1, m4);\n c11.sub(m5);\n c11.add(m7);\n let c12 = AbstractMatrix.add(m3, m5);\n let c21 = AbstractMatrix.add(m2, m4);\n let c22 = AbstractMatrix.sub(m1, m2);\n c22.add(m3);\n c22.add(m6);\n\n // Crop output to the desired size (undo dynamic padding).\n let resultat = AbstractMatrix.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 scaleRows(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1 } = options;\n if (!Number.isFinite(min)) throw new TypeError('min must be a number');\n if (!Number.isFinite(max)) throw new TypeError('max must be a number');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let i = 0; i < this.rows; i++) {\n const row = this.getRow(i);\n rescale(row, { min, max, output: row });\n newMatrix.setRow(i, row);\n }\n return newMatrix;\n }\n\n scaleColumns(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1 } = options;\n if (!Number.isFinite(min)) throw new TypeError('min must be a number');\n if (!Number.isFinite(max)) throw new TypeError('max must be a number');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let i = 0; i < this.columns; i++) {\n const column = this.getColumn(i);\n rescale(column, {\n min: min,\n max: max,\n output: column,\n });\n newMatrix.setColumn(i, column);\n }\n return newMatrix;\n }\n\n flipRows() {\n const middle = Math.ceil(this.columns / 2);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < middle; j++) {\n let first = this.get(i, j);\n let last = this.get(i, this.columns - 1 - j);\n this.set(i, j, last);\n this.set(i, this.columns - 1 - j, first);\n }\n }\n return this;\n }\n\n flipColumns() {\n const middle = Math.ceil(this.rows / 2);\n for (let j = 0; j < this.columns; j++) {\n for (let i = 0; i < middle; i++) {\n let first = this.get(i, j);\n let last = this.get(this.rows - 1 - i, j);\n this.set(i, j, last);\n this.set(this.rows - 1 - i, j, first);\n }\n }\n return this;\n }\n\n kroneckerProduct(other) {\n other = Matrix.checkMatrix(other);\n\n let m = this.rows;\n let n = this.columns;\n let p = other.rows;\n let q = other.columns;\n\n let result = new Matrix(m * p, n * q);\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n for (let k = 0; k < p; k++) {\n for (let l = 0; l < q; l++) {\n result.set(p * i + k, q * j + l, this.get(i, j) * other.get(k, l));\n }\n }\n }\n }\n return result;\n }\n\n transpose() {\n let result = new Matrix(this.columns, this.rows);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n result.set(j, i, this.get(i, j));\n }\n }\n return result;\n }\n\n sortRows(compareFunction = compareNumbers) {\n for (let i = 0; i < this.rows; i++) {\n this.setRow(i, this.getRow(i).sort(compareFunction));\n }\n return this;\n }\n\n sortColumns(compareFunction = compareNumbers) {\n for (let i = 0; i < this.columns; i++) {\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\n }\n return this;\n }\n\n subMatrix(startRow, endRow, startColumn, endColumn) {\n checkRange(this, startRow, endRow, startColumn, endColumn);\n let newMatrix = new Matrix(\n endRow - startRow + 1,\n endColumn - startColumn + 1,\n );\n for (let i = startRow; i <= endRow; i++) {\n for (let j = startColumn; j <= endColumn; j++) {\n newMatrix.set(i - startRow, j - startColumn, this.get(i, j));\n }\n }\n return newMatrix;\n }\n\n subMatrixRow(indices, startColumn, endColumn) {\n if (startColumn === undefined) startColumn = 0;\n if (endColumn === undefined) endColumn = this.columns - 1;\n if (\n startColumn > endColumn ||\n startColumn < 0 ||\n startColumn >= this.columns ||\n endColumn < 0 ||\n endColumn >= this.columns\n ) {\n throw new RangeError('Argument out of range');\n }\n\n let newMatrix = new Matrix(indices.length, endColumn - startColumn + 1);\n for (let i = 0; i < indices.length; i++) {\n for (let 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 subMatrixColumn(indices, startRow, endRow) {\n if (startRow === undefined) startRow = 0;\n if (endRow === undefined) endRow = this.rows - 1;\n if (\n startRow > endRow ||\n startRow < 0 ||\n startRow >= this.rows ||\n endRow < 0 ||\n endRow >= this.rows\n ) {\n throw new RangeError('Argument out of range');\n }\n\n let newMatrix = new Matrix(endRow - startRow + 1, indices.length);\n for (let i = 0; i < indices.length; i++) {\n for (let 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 setSubMatrix(matrix, startRow, startColumn) {\n matrix = Matrix.checkMatrix(matrix);\n let endRow = startRow + matrix.rows - 1;\n let endColumn = startColumn + matrix.columns - 1;\n checkRange(this, startRow, endRow, startColumn, endColumn);\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n this.set(startRow + i, startColumn + j, matrix.get(i, j));\n }\n }\n return this;\n }\n\n selection(rowIndices, columnIndices) {\n let indices = checkIndices(this, rowIndices, columnIndices);\n let newMatrix = new Matrix(rowIndices.length, columnIndices.length);\n for (let i = 0; i < indices.row.length; i++) {\n let rowIndex = indices.row[i];\n for (let j = 0; j < indices.column.length; j++) {\n let columnIndex = indices.column[j];\n newMatrix.set(i, j, this.get(rowIndex, columnIndex));\n }\n }\n return newMatrix;\n }\n\n trace() {\n let min = Math.min(this.rows, this.columns);\n let trace = 0;\n for (let i = 0; i < min; i++) {\n trace += this.get(i, i);\n }\n return trace;\n }\n\n clone() {\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let row = 0; row < this.rows; row++) {\n for (let column = 0; column < this.columns; column++) {\n newMatrix.set(row, column, this.get(row, column));\n }\n }\n return newMatrix;\n }\n\n sum(by) {\n switch (by) {\n case 'row':\n return sumByRow(this);\n case 'column':\n return sumByColumn(this);\n case undefined:\n return sumAll(this);\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n product(by) {\n switch (by) {\n case 'row':\n return productByRow(this);\n case 'column':\n return productByColumn(this);\n case undefined:\n return productAll(this);\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n mean(by) {\n const sum = this.sum(by);\n switch (by) {\n case 'row': {\n for (let i = 0; i < this.rows; i++) {\n sum[i] /= this.columns;\n }\n return sum;\n }\n case 'column': {\n for (let i = 0; i < this.columns; i++) {\n sum[i] /= this.rows;\n }\n return sum;\n }\n case undefined:\n return sum / this.size;\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n variance(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { unbiased = true, mean = this.mean(by) } = options;\n if (typeof unbiased !== 'boolean') {\n throw new TypeError('unbiased must be a boolean');\n }\n switch (by) {\n case 'row': {\n if (!Array.isArray(mean)) {\n throw new TypeError('mean must be an array');\n }\n return varianceByRow(this, unbiased, mean);\n }\n case 'column': {\n if (!Array.isArray(mean)) {\n throw new TypeError('mean must be an array');\n }\n return varianceByColumn(this, unbiased, mean);\n }\n case undefined: {\n if (typeof mean !== 'number') {\n throw new TypeError('mean must be a number');\n }\n return varianceAll(this, unbiased, mean);\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n standardDeviation(by, options) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n const variance = this.variance(by, options);\n if (by === undefined) {\n return Math.sqrt(variance);\n } else {\n for (let i = 0; i < variance.length; i++) {\n variance[i] = Math.sqrt(variance[i]);\n }\n return variance;\n }\n }\n\n center(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { center = this.mean(by) } = options;\n switch (by) {\n case 'row': {\n if (!Array.isArray(center)) {\n throw new TypeError('center must be an array');\n }\n centerByRow(this, center);\n return this;\n }\n case 'column': {\n if (!Array.isArray(center)) {\n throw new TypeError('center must be an array');\n }\n centerByColumn(this, center);\n return this;\n }\n case undefined: {\n if (typeof center !== 'number') {\n throw new TypeError('center must be a number');\n }\n centerAll(this, center);\n return this;\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n scale(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n let scale = options.scale;\n switch (by) {\n case 'row': {\n if (scale === undefined) {\n scale = getScaleByRow(this);\n } else if (!Array.isArray(scale)) {\n throw new TypeError('scale must be an array');\n }\n scaleByRow(this, scale);\n return this;\n }\n case 'column': {\n if (scale === undefined) {\n scale = getScaleByColumn(this);\n } else if (!Array.isArray(scale)) {\n throw new TypeError('scale must be an array');\n }\n scaleByColumn(this, scale);\n return this;\n }\n case undefined: {\n if (scale === undefined) {\n scale = getScaleAll(this);\n } else if (typeof scale !== 'number') {\n throw new TypeError('scale must be a number');\n }\n scaleAll(this, scale);\n return this;\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n}\n\nAbstractMatrix.prototype.klass = 'Matrix';\nif (typeof Symbol !== 'undefined') {\n AbstractMatrix.prototype[\n Symbol.for('nodejs.util.inspect.custom')\n ] = inspectMatrix;\n}\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\n// Synonyms\nAbstractMatrix.random = AbstractMatrix.rand;\nAbstractMatrix.randomInt = AbstractMatrix.randInt;\nAbstractMatrix.diagonal = AbstractMatrix.diag;\nAbstractMatrix.prototype.diagonal = AbstractMatrix.prototype.diag;\nAbstractMatrix.identity = AbstractMatrix.eye;\nAbstractMatrix.prototype.negate = AbstractMatrix.prototype.neg;\nAbstractMatrix.prototype.tensorProduct =\n AbstractMatrix.prototype.kroneckerProduct;\n\nexport default class Matrix extends AbstractMatrix {\n constructor(nRows, nColumns) {\n super();\n if (Matrix.isMatrix(nRows)) {\n return nRows.clone();\n } else if (Number.isInteger(nRows) && nRows > 0) {\n // Create an empty matrix\n this.data = [];\n if (Number.isInteger(nColumns) && nColumns > 0) {\n for (let i = 0; i < nRows; i++) {\n this.data.push(new Float64Array(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 arrayData = nRows;\n nRows = arrayData.length;\n nColumns = arrayData[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 this.data = [];\n for (let i = 0; i < nRows; i++) {\n if (arrayData[i].length !== nColumns) {\n throw new RangeError('Inconsistent array dimensions');\n }\n this.data.push(Float64Array.from(arrayData[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.data[rowIndex][columnIndex] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.data[rowIndex][columnIndex];\n }\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.data.splice(index, 1);\n this.rows -= 1;\n return this;\n }\n\n addRow(index, array) {\n if (array === undefined) {\n array = index;\n index = this.rows;\n }\n checkRowIndex(this, index, true);\n array = Float64Array.from(checkRowVector(this, array, true));\n this.data.splice(index, 0, array);\n this.rows += 1;\n return this;\n }\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 (let i = 0; i < this.rows; i++) {\n const newRow = new Float64Array(this.columns - 1);\n for (let j = 0; j < index; j++) {\n newRow[j] = this.data[i][j];\n }\n for (let j = index + 1; j < this.columns; j++) {\n newRow[j - 1] = this.data[i][j];\n }\n this.data[i] = newRow;\n }\n this.columns -= 1;\n return this;\n }\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 (let i = 0; i < this.rows; i++) {\n const newRow = new Float64Array(this.columns + 1);\n let j = 0;\n for (; j < index; j++) {\n newRow[j] = this.data[i][j];\n }\n newRow[j++] = array[i];\n for (; j < this.columns + 1; j++) {\n newRow[j] = this.data[i][j - 1];\n }\n this.data[i] = newRow;\n }\n this.columns += 1;\n return this;\n }\n}\n\ninstallMathOperations(AbstractMatrix, Matrix);\n","import { AbstractMatrix } 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","import { checkColumnIndex } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixColumnView extends BaseView {\n constructor(matrix, column) {\n checkColumnIndex(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","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 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 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 { checkRowIndex } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixRowView extends BaseView {\n constructor(matrix, row) {\n checkRowIndex(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","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 { checkIndices } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixSelectionView extends BaseView {\n constructor(matrix, rowIndices, columnIndices) {\n let 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","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","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 { AbstractMatrix } from '../matrix';\n\nexport default class WrapperMatrix1D extends AbstractMatrix {\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 let index = this._calculateIndex(rowIndex, columnIndex);\n this.data[index] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n let 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","import { AbstractMatrix } from '../matrix';\n\nexport default class WrapperMatrix2D extends AbstractMatrix {\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","import WrapperMatrix1D from './WrapperMatrix1D';\nimport WrapperMatrix2D from './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","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nexport default class LuDecomposition {\n constructor(matrix) {\n matrix = WrapperMatrix2D.checkMatrix(matrix);\n\n let lu = matrix.clone();\n let rows = lu.rows;\n let columns = lu.columns;\n let pivotVector = new Float64Array(rows);\n let pivotSign = 1;\n let i, j, k, p, s, t, v;\n let LUcolj, kmax;\n\n for (i = 0; i < rows; i++) {\n pivotVector[i] = i;\n }\n\n LUcolj = new Float64Array(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 isSingular() {\n let data = this.LU;\n let col = data.columns;\n for (let j = 0; j < col; j++) {\n if (data.get(j, j) === 0) {\n return true;\n }\n }\n return false;\n }\n\n solve(value) {\n value = Matrix.checkMatrix(value);\n\n let lu = this.LU;\n let 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 let count = value.columns;\n let X = value.subMatrixRow(this.pivotVector, 0, count - 1);\n let columns = lu.columns;\n let 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.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));\n }\n }\n }\n for (k = columns - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X.set(k, j, X.get(k, j) / lu.get(k, k));\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));\n }\n }\n }\n return X;\n }\n\n get determinant() {\n let data = this.LU;\n if (!data.isSquare()) {\n throw new Error('Matrix must be square');\n }\n let determinant = this.pivotSign;\n let col = data.columns;\n for (let j = 0; j < col; j++) {\n determinant *= data.get(j, j);\n }\n return determinant;\n }\n\n get lowerTriangularMatrix() {\n let data = this.LU;\n let rows = data.rows;\n let columns = data.columns;\n let X = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n if (i > j) {\n X.set(i, j, data.get(i, j));\n } else if (i === j) {\n X.set(i, j, 1);\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get upperTriangularMatrix() {\n let data = this.LU;\n let rows = data.rows;\n let columns = data.columns;\n let X = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n if (i <= j) {\n X.set(i, j, data.get(i, j));\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get pivotPermutationVector() {\n return Array.from(this.pivotVector);\n }\n}\n","export function hypotenuse(a, b) {\n let 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","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\n\nexport default class QrDecomposition {\n constructor(value) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n let qr = value.clone();\n let m = value.rows;\n let n = value.columns;\n let rdiag = new Float64Array(n);\n let i, j, k, s;\n\n for (k = 0; k < n; k++) {\n let 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 solve(value) {\n value = Matrix.checkMatrix(value);\n\n let qr = this.QR;\n let 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 let count = value.columns;\n let X = value.clone();\n let n = qr.columns;\n let 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.get(i, k) * X.get(i, j);\n }\n s = -s / qr.get(k, k);\n for (i = k; i < m; i++) {\n X.set(i, j, X.get(i, j) + s * qr.get(i, k));\n }\n }\n }\n for (k = n - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X.set(k, j, X.get(k, j) / this.Rdiag[k]);\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X.set(i, j, X.get(i, j) - X.get(k, j) * qr.get(i, k));\n }\n }\n }\n\n return X.subMatrix(0, n - 1, 0, count - 1);\n }\n\n isFullRank() {\n let columns = this.QR.columns;\n for (let i = 0; i < columns; i++) {\n if (this.Rdiag[i] === 0) {\n return false;\n }\n }\n return true;\n }\n\n get upperTriangularMatrix() {\n let qr = this.QR;\n let n = qr.columns;\n let X = new Matrix(n, n);\n let i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n if (i < j) {\n X.set(i, j, qr.get(i, j));\n } else if (i === j) {\n X.set(i, j, this.Rdiag[i]);\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get orthogonalMatrix() {\n let qr = this.QR;\n let rows = qr.rows;\n let columns = qr.columns;\n let X = new Matrix(rows, columns);\n let i, j, k, s;\n\n for (k = columns - 1; k >= 0; k--) {\n for (i = 0; i < rows; i++) {\n X.set(i, k, 0);\n }\n X.set(k, k, 1);\n for (j = k; j < columns; j++) {\n if (qr.get(k, k) !== 0) {\n s = 0;\n for (i = k; i < rows; i++) {\n s += qr.get(i, k) * X.get(i, j);\n }\n\n s = -s / qr.get(k, k);\n\n for (i = k; i < rows; i++) {\n X.set(i, j, X.get(i, j) + s * qr.get(i, k));\n }\n }\n }\n }\n return X;\n }\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\n\nexport default class SingularValueDecomposition {\n constructor(value, options = {}) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n let m = value.rows;\n let n = value.columns;\n\n const {\n computeLeftSingularVectors = true,\n computeRightSingularVectors = true,\n autoTranspose = false,\n } = options;\n\n let wantu = Boolean(computeLeftSingularVectors);\n let wantv = Boolean(computeRightSingularVectors);\n\n let swapped = false;\n let 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 let aux = wantu;\n wantu = wantv;\n wantv = aux;\n }\n } else {\n a = value.clone();\n }\n\n let nu = Math.min(m, n);\n let ni = Math.min(m + 1, n);\n let s = new Float64Array(ni);\n let U = new Matrix(m, nu);\n let V = new Matrix(n, n);\n\n let e = new Float64Array(n);\n let work = new Float64Array(m);\n\n let si = new Float64Array(ni);\n for (let i = 0; i < ni; i++) si[i] = i;\n\n let nct = Math.min(m - 1, n);\n let nrt = Math.max(0, Math.min(n - 2, m));\n let 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.get(i, k));\n }\n if (s[k] !== 0) {\n if (a.get(k, k) < 0) {\n s[k] = -s[k];\n }\n for (let i = k; i < m; i++) {\n a.set(i, k, a.get(i, k) / s[k]);\n }\n a.set(k, k, a.get(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.get(i, k) * a.get(i, j);\n }\n t = -t / a.get(k, k);\n for (let i = k; i < m; i++) {\n a.set(i, j, a.get(i, j) + t * a.get(i, k));\n }\n }\n e[j] = a.get(k, j);\n }\n\n if (wantu && k < nct) {\n for (let i = k; i < m; i++) {\n U.set(i, k, a.get(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.get(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.set(i, j, a.get(i, j) + t * work[i]);\n }\n }\n }\n if (wantv) {\n for (let i = k + 1; i < n; i++) {\n V.set(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.get(nct, nct);\n }\n if (m < p) {\n s[p - 1] = 0;\n }\n if (nrt + 1 < p) {\n e[nrt] = a.get(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.set(i, j, 0);\n }\n U.set(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.get(i, k) * U.get(i, j);\n }\n t = -t / U.get(k, k);\n for (let i = k; i < m; i++) {\n U.set(i, j, U.get(i, j) + t * U.get(i, k));\n }\n }\n for (let i = k; i < m; i++) {\n U.set(i, k, -U.get(i, k));\n }\n U.set(k, k, 1 + U.get(k, k));\n for (let i = 0; i < k - 1; i++) {\n U.set(i, k, 0);\n }\n } else {\n for (let i = 0; i < m; i++) {\n U.set(i, k, 0);\n }\n U.set(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.get(i, k) * V.get(i, j);\n }\n t = -t / V.get(k + 1, k);\n for (let i = k + 1; i < n; i++) {\n V.set(i, j, V.get(i, j) + t * V.get(i, k));\n }\n }\n }\n for (let i = 0; i < n; i++) {\n V.set(i, k, 0);\n }\n V.set(k, k, 1);\n }\n }\n\n let pp = p - 1;\n let iter = 0;\n let 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.get(i, j) + sn * V.get(i, p - 1);\n V.set(i, p - 1, -sn * V.get(i, j) + cs * V.get(i, p - 1));\n V.set(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.get(i, j) + sn * U.get(i, k - 1);\n U.set(i, k - 1, -sn * U.get(i, j) + cs * U.get(i, k - 1));\n U.set(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.get(i, j) + sn * V.get(i, j + 1);\n V.set(i, j + 1, -sn * V.get(i, j) + cs * V.get(i, j + 1));\n V.set(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.get(i, j) + sn * U.get(i, j + 1);\n U.set(i, j + 1, -sn * U.get(i, j) + cs * U.get(i, j + 1));\n U.set(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.set(i, k, -V.get(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.get(i, k + 1);\n V.set(i, k + 1, V.get(i, k));\n V.set(i, k, t);\n }\n }\n if (wantu && k < m - 1) {\n for (let i = 0; i < m; i++) {\n t = U.get(i, k + 1);\n U.set(i, k + 1, U.get(i, k));\n U.set(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 let 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 solve(value) {\n let Y = value;\n let e = this.threshold;\n let scols = this.s.length;\n let Ls = Matrix.zeros(scols, scols);\n\n for (let i = 0; i < scols; i++) {\n if (Math.abs(this.s[i]) <= e) {\n Ls.set(i, i, 0);\n } else {\n Ls.set(i, i, 1 / this.s[i]);\n }\n }\n\n let U = this.U;\n let V = this.rightSingularVectors;\n\n let VL = V.mmul(Ls);\n let vrows = V.rows;\n let urows = U.rows;\n let 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.get(i, k) * U.get(j, k);\n }\n VLU.set(i, j, sum);\n }\n }\n\n return VLU.mmul(Y);\n }\n\n solveForDiagonal(value) {\n return this.solve(Matrix.diag(value));\n }\n\n inverse() {\n let V = this.V;\n let e = this.threshold;\n let vrows = V.rows;\n let vcols = V.columns;\n let 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.set(i, j, V.get(i, j) / this.s[j]);\n }\n }\n }\n\n let U = this.U;\n\n let urows = U.rows;\n let ucols = U.columns;\n let 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.get(i, k) * U.get(j, k);\n }\n Y.set(i, j, sum);\n }\n }\n\n return Y;\n }\n\n get condition() {\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\n }\n\n get norm2() {\n return this.s[0];\n }\n\n get rank() {\n let tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON;\n let r = 0;\n let s = this.s;\n for (let i = 0, ii = s.length; i < ii; i++) {\n if (s[i] > tol) {\n r++;\n }\n }\n return r;\n }\n\n get diagonal() {\n return Array.from(this.s);\n }\n\n get threshold() {\n return (Number.EPSILON / 2) * Math.max(this.m, this.n) * this.s[0];\n }\n\n get leftSingularVectors() {\n return this.U;\n }\n\n get rightSingularVectors() {\n return this.V;\n }\n\n get diagonalMatrix() {\n return Matrix.diag(this.s);\n }\n}\n","import LuDecomposition from './dc/lu';\nimport QrDecomposition from './dc/qr';\nimport SingularValueDecomposition from './dc/svd';\nimport Matrix from './matrix';\nimport WrapperMatrix2D from './wrap/WrapperMatrix2D';\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\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","import Matrix from './matrix';\nimport LuDecomposition from './dc/lu';\nimport MatrixSelectionView from './views/selection';\n\nexport function determinant(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (matrix.isSquare()) {\n let a, b, c, d;\n if (matrix.columns === 2) {\n // 2 x 2 matrix\n a = matrix.get(0, 0);\n b = matrix.get(0, 1);\n c = matrix.get(1, 0);\n d = matrix.get(1, 1);\n\n return a * d - b * c;\n } else if (matrix.columns === 3) {\n // 3 x 3 matrix\n let subMatrix0, subMatrix1, subMatrix2;\n subMatrix0 = new MatrixSelectionView(matrix, [1, 2], [1, 2]);\n subMatrix1 = new MatrixSelectionView(matrix, [1, 2], [0, 2]);\n subMatrix2 = new MatrixSelectionView(matrix, [1, 2], [0, 1]);\n a = matrix.get(0, 0);\n b = matrix.get(0, 1);\n c = matrix.get(0, 2);\n\n return (\n a * determinant(subMatrix0) -\n b * determinant(subMatrix1) +\n c * determinant(subMatrix2)\n );\n } else {\n // general purpose determinant using the LU decomposition\n return new LuDecomposition(matrix).determinant;\n }\n } else {\n throw Error('determinant can only be calculated for a square matrix');\n }\n}\n","import Matrix from './matrix';\nimport SingularValueDecomposition from './dc/svd';\n\nfunction xrange(n, exception) {\n let range = [];\n for (let i = 0; i < n; i++) {\n if (i !== exception) {\n range.push(i);\n }\n }\n return range;\n}\n\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 let returnArray = matrix.addRow(index, [0]);\n for (let 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\nexport function linearDependencies(matrix, options = {}) {\n const { thresholdValue = 10e-10, thresholdError = 10e-10 } = options;\n matrix = Matrix.checkMatrix(matrix);\n\n let n = matrix.rows;\n let results = new Matrix(n, n);\n\n for (let i = 0; i < n; i++) {\n let b = Matrix.columnVector(matrix.getRow(i));\n let Abis = matrix.subMatrixRow(xrange(n, i)).transpose();\n let svd = new SingularValueDecomposition(Abis);\n let x = svd.solve(b);\n let error = Matrix.sub(b, Abis.mmul(x))\n .abs()\n .max();\n results.setRow(\n i,\n dependenciesOneRow(error, x, i, thresholdValue, thresholdError),\n );\n }\n return results;\n}\n","import SVD from './dc/svd';\nimport Matrix from './matrix';\n\nexport function pseudoInverse(matrix, threshold = Number.EPSILON) {\n matrix = Matrix.checkMatrix(matrix);\n let svdSolution = new SVD(matrix, { autoTranspose: true });\n\n let U = svdSolution.leftSingularVectors;\n let V = svdSolution.rightSingularVectors;\n let s = svdSolution.diagonal;\n\n for (let 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 return V.mmul(Matrix.diag(s).mmul(U.transpose()));\n}\n","import Matrix from './matrix';\n\nexport function covariance(xMatrix, yMatrix = xMatrix, options = {}) {\n xMatrix = Matrix.checkMatrix(xMatrix);\n let yIsSame = false;\n if (\n typeof yMatrix === 'object' &&\n !Matrix.isMatrix(yMatrix) &&\n !Array.isArray(yMatrix)\n ) {\n options = yMatrix;\n yMatrix = xMatrix;\n yIsSame = true;\n } else {\n yMatrix = Matrix.checkMatrix(yMatrix);\n }\n if (xMatrix.rows !== yMatrix.rows) {\n throw new TypeError('Both matrices must have the same number of rows');\n }\n const { center = true } = options;\n if (center) {\n xMatrix = xMatrix.center('column');\n if (!yIsSame) {\n yMatrix = yMatrix.center('column');\n }\n }\n const cov = xMatrix.transpose().mmul(yMatrix);\n for (let i = 0; i < cov.rows; i++) {\n for (let j = 0; j < cov.columns; j++) {\n cov.set(i, j, cov.get(i, j) * (1 / (xMatrix.rows - 1)));\n }\n }\n return cov;\n}\n","import Matrix from './matrix';\n\nexport function correlation(xMatrix, yMatrix = xMatrix, options = {}) {\n xMatrix = Matrix.checkMatrix(xMatrix);\n let yIsSame = false;\n if (\n typeof yMatrix === 'object' &&\n !Matrix.isMatrix(yMatrix) &&\n !Array.isArray(yMatrix)\n ) {\n options = yMatrix;\n yMatrix = xMatrix;\n yIsSame = true;\n } else {\n yMatrix = Matrix.checkMatrix(yMatrix);\n }\n if (xMatrix.rows !== yMatrix.rows) {\n throw new TypeError('Both matrices must have the same number of rows');\n }\n\n const { center = true, scale = true } = options;\n if (center) {\n xMatrix.center('column');\n if (!yIsSame) {\n yMatrix.center('column');\n }\n }\n if (scale) {\n xMatrix.scale('column');\n if (!yIsSame) {\n yMatrix.scale('column');\n }\n }\n\n const sdx = xMatrix.standardDeviation('column', { unbiased: true });\n const sdy = yIsSame\n ? sdx\n : yMatrix.standardDeviation('column', { unbiased: true });\n\n const corr = xMatrix.transpose().mmul(yMatrix);\n for (let i = 0; i < corr.rows; i++) {\n for (let j = 0; j < corr.columns; j++) {\n corr.set(\n i,\n j,\n corr.get(i, j) * (1 / (sdx[i] * sdy[j])) * (1 / (xMatrix.rows - 1)),\n );\n }\n }\n return corr;\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\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 let n = matrix.columns;\n let V = new Matrix(n, n);\n let d = new Float64Array(n);\n let e = new Float64Array(n);\n let value = matrix;\n let i, j;\n\n let 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.set(i, j, value.get(i, j));\n }\n }\n tred2(n, e, d, V);\n tql2(n, e, d, V);\n } else {\n let H = new Matrix(n, n);\n let ort = new Float64Array(n);\n for (j = 0; j < n; j++) {\n for (i = 0; i < n; i++) {\n H.set(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 get realEigenvalues() {\n return Array.from(this.d);\n }\n\n get imaginaryEigenvalues() {\n return Array.from(this.e);\n }\n\n get eigenvectorMatrix() {\n return this.V;\n }\n\n get diagonalMatrix() {\n let n = this.n;\n let e = this.e;\n let d = this.d;\n let X = new Matrix(n, n);\n let i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n X.set(i, j, 0);\n }\n X.set(i, i, d[i]);\n if (e[i] > 0) {\n X.set(i, i + 1, e[i]);\n } else if (e[i] < 0) {\n X.set(i, i - 1, e[i]);\n }\n }\n return X;\n }\n}\n\nfunction tred2(n, e, d, V) {\n let f, g, h, i, j, k, hh, scale;\n\n for (j = 0; j < n; j++) {\n d[j] = V.get(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.get(i - 1, j);\n V.set(i, j, 0);\n V.set(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.set(j, i, f);\n g = e[j] + V.get(j, j) * f;\n for (k = j + 1; k <= i - 1; k++) {\n g += V.get(k, j) * d[k];\n e[k] += V.get(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.set(k, j, V.get(k, j) - (f * e[k] + g * d[k]));\n }\n d[j] = V.get(i - 1, j);\n V.set(i, j, 0);\n }\n }\n d[i] = h;\n }\n\n for (i = 0; i < n - 1; i++) {\n V.set(n - 1, i, V.get(i, i));\n V.set(i, i, 1);\n h = d[i + 1];\n if (h !== 0) {\n for (k = 0; k <= i; k++) {\n d[k] = V.get(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.get(k, i + 1) * V.get(k, j);\n }\n for (k = 0; k <= i; k++) {\n V.set(k, j, V.get(k, j) - g * d[k]);\n }\n }\n }\n\n for (k = 0; k <= i; k++) {\n V.set(k, i + 1, 0);\n }\n }\n\n for (j = 0; j < n; j++) {\n d[j] = V.get(n - 1, j);\n V.set(n - 1, j, 0);\n }\n\n V.set(n - 1, n - 1, 1);\n e[0] = 0;\n}\n\nfunction tql2(n, e, d, V) {\n let 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 let f = 0;\n let tst1 = 0;\n let 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.get(k, i + 1);\n V.set(k, i + 1, s * V.get(k, i) + c * h);\n V.set(k, i, c * V.get(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.get(j, i);\n V.set(j, i, V.get(j, k));\n V.set(j, k, p);\n }\n }\n }\n}\n\nfunction orthes(n, H, ort, V) {\n let low = 0;\n let high = n - 1;\n let f, g, h, i, j, m;\n let 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.get(i, m - 1));\n }\n\n if (scale !== 0) {\n h = 0;\n for (i = high; i >= m; i--) {\n ort[i] = H.get(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.get(i, j);\n }\n\n f = f / h;\n for (i = m; i <= high; i++) {\n H.set(i, j, H.get(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.get(i, j);\n }\n\n f = f / h;\n for (j = m; j <= high; j++) {\n H.set(i, j, H.get(i, j) - f * ort[j]);\n }\n }\n\n ort[m] = scale * ort[m];\n H.set(m, m - 1, scale * g);\n }\n }\n\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V.set(i, j, i === j ? 1 : 0);\n }\n }\n\n for (m = high - 1; m >= low + 1; m--) {\n if (H.get(m, m - 1) !== 0) {\n for (i = m + 1; i <= high; i++) {\n ort[i] = H.get(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.get(i, j);\n }\n\n g = g / ort[m] / H.get(m, m - 1);\n for (i = m; i <= high; i++) {\n V.set(i, j, V.get(i, j) + g * ort[i]);\n }\n }\n }\n }\n}\n\nfunction hqr2(nn, e, d, V, H) {\n let n = nn - 1;\n let low = 0;\n let high = nn - 1;\n let eps = Number.EPSILON;\n let exshift = 0;\n let norm = 0;\n let p = 0;\n let q = 0;\n let r = 0;\n let s = 0;\n let z = 0;\n let iter = 0;\n let i, j, k, l, m, t, w, x, y;\n let ra, sa, vr, vi;\n let notlast, cdivres;\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n d[i] = H.get(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.get(i, j));\n }\n }\n\n while (n >= low) {\n l = n;\n while (l > low) {\n s = Math.abs(H.get(l - 1, l - 1)) + Math.abs(H.get(l, l));\n if (s === 0) {\n s = norm;\n }\n if (Math.abs(H.get(l, l - 1)) < eps * s) {\n break;\n }\n l--;\n }\n\n if (l === n) {\n H.set(n, n, H.get(n, n) + exshift);\n d[n] = H.get(n, n);\n e[n] = 0;\n n--;\n iter = 0;\n } else if (l === n - 1) {\n w = H.get(n, n - 1) * H.get(n - 1, n);\n p = (H.get(n - 1, n - 1) - H.get(n, n)) / 2;\n q = p * p + w;\n z = Math.sqrt(Math.abs(q));\n H.set(n, n, H.get(n, n) + exshift);\n H.set(n - 1, n - 1, H.get(n - 1, n - 1) + exshift);\n x = H.get(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.get(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.get(n - 1, j);\n H.set(n - 1, j, q * z + p * H.get(n, j));\n H.set(n, j, q * H.get(n, j) - p * z);\n }\n\n for (i = 0; i <= n; i++) {\n z = H.get(i, n - 1);\n H.set(i, n - 1, q * z + p * H.get(i, n));\n H.set(i, n, q * H.get(i, n) - p * z);\n }\n\n for (i = low; i <= high; i++) {\n z = V.get(i, n - 1);\n V.set(i, n - 1, q * z + p * V.get(i, n));\n V.set(i, n, q * V.get(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.get(n, n);\n y = 0;\n w = 0;\n if (l < n) {\n y = H.get(n - 1, n - 1);\n w = H.get(n, n - 1) * H.get(n - 1, n);\n }\n\n if (iter === 10) {\n exshift += x;\n for (i = low; i <= n; i++) {\n H.set(i, i, H.get(i, i) - x);\n }\n s = Math.abs(H.get(n, n - 1)) + Math.abs(H.get(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.set(i, i, H.get(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.get(m, m);\n r = x - z;\n s = y - z;\n p = (r * s - w) / H.get(m + 1, m) + H.get(m, m + 1);\n q = H.get(m + 1, m + 1) - z - r - s;\n r = H.get(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.get(m, m - 1)) * (Math.abs(q) + Math.abs(r)) <\n eps *\n (Math.abs(p) *\n (Math.abs(H.get(m - 1, m - 1)) +\n Math.abs(z) +\n Math.abs(H.get(m + 1, m + 1))))\n ) {\n break;\n }\n m--;\n }\n\n for (i = m + 2; i <= n; i++) {\n H.set(i, i - 2, 0);\n if (i > m + 2) {\n H.set(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.get(k, k - 1);\n q = H.get(k + 1, k - 1);\n r = notlast ? H.get(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.set(k, k - 1, -s * x);\n } else if (l !== m) {\n H.set(k, k - 1, -H.get(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.get(k, j) + q * H.get(k + 1, j);\n if (notlast) {\n p = p + r * H.get(k + 2, j);\n H.set(k + 2, j, H.get(k + 2, j) - p * z);\n }\n\n H.set(k, j, H.get(k, j) - p * x);\n H.set(k + 1, j, H.get(k + 1, j) - p * y);\n }\n\n for (i = 0; i <= Math.min(n, k + 3); i++) {\n p = x * H.get(i, k) + y * H.get(i, k + 1);\n if (notlast) {\n p = p + z * H.get(i, k + 2);\n H.set(i, k + 2, H.get(i, k + 2) - p * r);\n }\n\n H.set(i, k, H.get(i, k) - p);\n H.set(i, k + 1, H.get(i, k + 1) - p * q);\n }\n\n for (i = low; i <= high; i++) {\n p = x * V.get(i, k) + y * V.get(i, k + 1);\n if (notlast) {\n p = p + z * V.get(i, k + 2);\n V.set(i, k + 2, V.get(i, k + 2) - p * r);\n }\n\n V.set(i, k, V.get(i, k) - p);\n V.set(i, k + 1, V.get(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.set(n, n, 1);\n for (i = n - 1; i >= 0; i--) {\n w = H.get(i, i) - p;\n r = 0;\n for (j = l; j <= n; j++) {\n r = r + H.get(i, j) * H.get(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.set(i, n, w !== 0 ? -r / w : -r / (eps * norm));\n } else {\n x = H.get(i, i + 1);\n y = H.get(i + 1, i);\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\n t = (x * s - z * r) / q;\n H.set(i, n, t);\n H.set(\n i + 1,\n n,\n Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z,\n );\n }\n\n t = Math.abs(H.get(i, n));\n if (eps * t * t > 1) {\n for (j = i; j <= n; j++) {\n H.set(j, n, H.get(j, n) / t);\n }\n }\n }\n }\n } else if (q < 0) {\n l = n - 1;\n\n if (Math.abs(H.get(n, n - 1)) > Math.abs(H.get(n - 1, n))) {\n H.set(n - 1, n - 1, q / H.get(n, n - 1));\n H.set(n - 1, n, -(H.get(n, n) - p) / H.get(n, n - 1));\n } else {\n cdivres = cdiv(0, -H.get(n - 1, n), H.get(n - 1, n - 1) - p, q);\n H.set(n - 1, n - 1, cdivres[0]);\n H.set(n - 1, n, cdivres[1]);\n }\n\n H.set(n, n - 1, 0);\n H.set(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.get(i, j) * H.get(j, n - 1);\n sa = sa + H.get(i, j) * H.get(j, n);\n }\n\n w = H.get(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.set(i, n - 1, cdivres[0]);\n H.set(i, n, cdivres[1]);\n } else {\n x = H.get(i, i + 1);\n y = H.get(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.set(i, n - 1, cdivres[0]);\n H.set(i, n, cdivres[1]);\n if (Math.abs(x) > Math.abs(z) + Math.abs(q)) {\n H.set(\n i + 1,\n n - 1,\n (-ra - w * H.get(i, n - 1) + q * H.get(i, n)) / x,\n );\n H.set(\n i + 1,\n n,\n (-sa - w * H.get(i, n) - q * H.get(i, n - 1)) / x,\n );\n } else {\n cdivres = cdiv(\n -r - y * H.get(i, n - 1),\n -s - y * H.get(i, n),\n z,\n q,\n );\n H.set(i + 1, n - 1, cdivres[0]);\n H.set(i + 1, n, cdivres[1]);\n }\n }\n\n t = Math.max(Math.abs(H.get(i, n - 1)), Math.abs(H.get(i, n)));\n if (eps * t * t > 1) {\n for (j = i; j <= n; j++) {\n H.set(j, n - 1, H.get(j, n - 1) / t);\n H.set(j, n, H.get(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.set(i, j, H.get(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.get(i, k) * H.get(k, j);\n }\n V.set(i, j, z);\n }\n }\n}\n\nfunction cdiv(xr, xi, yr, yi) {\n let 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","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\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 let a = value;\n let dimension = a.rows;\n let l = new Matrix(dimension, dimension);\n let positiveDefinite = true;\n let i, j, k;\n\n for (j = 0; j < dimension; j++) {\n let d = 0;\n for (k = 0; k < j; k++) {\n let s = 0;\n for (i = 0; i < k; i++) {\n s += l.get(k, i) * l.get(j, i);\n }\n s = (a.get(j, k) - s) / l.get(k, k);\n l.set(j, k, s);\n d = d + s * s;\n }\n\n d = a.get(j, j) - d;\n\n positiveDefinite &= d > 0;\n l.set(j, j, Math.sqrt(Math.max(d, 0)));\n for (k = j + 1; k < dimension; k++) {\n l.set(j, k, 0);\n }\n }\n\n this.L = l;\n this.positiveDefinite = Boolean(positiveDefinite);\n }\n\n isPositiveDefinite() {\n return this.positiveDefinite;\n }\n\n solve(value) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n let l = this.L;\n let dimension = l.rows;\n\n if (value.rows !== dimension) {\n throw new Error('Matrix dimensions do not match');\n }\n if (this.isPositiveDefinite() === false) {\n throw new Error('Matrix is not positive definite');\n }\n\n let count = value.columns;\n let B = value.clone();\n let 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.set(k, j, B.get(k, j) - B.get(i, j) * l.get(k, i));\n }\n B.set(k, j, B.get(k, j) / l.get(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.set(k, j, B.get(k, j) - B.get(i, j) * l.get(i, k));\n }\n B.set(k, j, B.get(k, j) / l.get(k, k));\n }\n }\n\n return B;\n }\n\n get lowerTriangularMatrix() {\n return this.L;\n }\n}\n","import WrapperMatrix2D from '../wrap/WrapperMatrix2D';\nimport Matrix from '../matrix';\n\nexport default class nipals {\n constructor(X, options = {}) {\n X = WrapperMatrix2D.checkMatrix(X);\n let { Y } = options;\n const {\n scaleScores = false,\n maxIterations = 1000,\n terminationCriteria = 1e-10,\n } = options;\n\n let u;\n if (Y) {\n if (Array.isArray(Y) && typeof Y[0] === 'number') {\n Y = Matrix.columnVector(Y);\n } else {\n Y = WrapperMatrix2D.checkMatrix(Y);\n }\n if (!Y.isColumnVector() || Y.rows !== X.rows) {\n throw new Error('Y must be a column vector of length X.rows');\n }\n u = Y;\n } else {\n u = X.getColumnVector(0);\n }\n\n let diff = 1;\n let t, q, w, tOld;\n\n for (\n let counter = 0;\n counter < maxIterations && diff > terminationCriteria;\n counter++\n ) {\n w = X.transpose()\n .mmul(u)\n .div(\n u\n .transpose()\n .mmul(u)\n .get(0, 0),\n );\n w = w.div(w.norm());\n\n t = X.mmul(w).div(\n w\n .transpose()\n .mmul(w)\n .get(0, 0),\n );\n\n if (counter > 0) {\n diff = t\n .clone()\n .sub(tOld)\n .pow(2)\n .sum();\n }\n tOld = t.clone();\n\n if (Y) {\n q = Y.transpose()\n .mmul(t)\n .div(\n t\n .transpose()\n .mmul(t)\n .get(0, 0),\n );\n q = q.div(q.norm());\n\n u = Y.mmul(q).div(\n q\n .transpose()\n .mmul(q)\n .get(0, 0),\n );\n } else {\n u = t;\n }\n }\n\n if (Y) {\n let p = X.transpose()\n .mmul(t)\n .div(\n t\n .transpose()\n .mmul(t)\n .get(0, 0),\n );\n p = p.div(p.norm());\n let xResidual = X.clone().sub(t.clone().mmul(p.transpose()));\n let residual = u\n .transpose()\n .mmul(t)\n .div(\n t\n .transpose()\n .mmul(t)\n .get(0, 0),\n );\n let yResidual = Y.clone().sub(\n t\n .clone()\n .mulS(residual.get(0, 0))\n .mmul(q.transpose()),\n );\n\n this.t = t;\n this.p = p.transpose();\n this.w = w.transpose();\n this.q = q;\n this.u = u;\n this.s = t.transpose().mmul(t);\n this.xResidual = xResidual;\n this.yResidual = yResidual;\n this.betas = residual;\n } else {\n this.w = w.transpose();\n this.s = t\n .transpose()\n .mmul(t)\n .sqrt();\n if (scaleScores) {\n this.t = t.clone().div(this.s.get(0, 0));\n } else {\n this.t = t;\n }\n this.xResidual = X.sub(t.mmul(w.transpose()));\n }\n }\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 sum(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 sumValue = 0;\n\n for (var i = 0; i < input.length; i++) {\n sumValue += input[i];\n }\n\n return sumValue;\n}\n\nexport default sum;\n","import sum from 'ml-array-sum';\n\n/**\n * Computes the mean of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction mean(input) {\n return sum(input) / input.length;\n}\n\nexport default mean;\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 let counts = new Array(numberOfClasses).fill(0);\n for (let 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 let probabilities = toDiscreteDistribution(\n array,\n getNumberOfClasses(array),\n ).getRow(0);\n\n let sum = 0.0;\n for (let 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\n .filter(function(val, i, arr) {\n return arr.indexOf(val) === i;\n })\n .map((val) => val + 1)\n .reduce((a, b) => Math.max(a, b));\n}\n\n/**\n * @private\n * Calculates the Gini Gain of an array of predictions and those predictions splitted by a feature.\n * @param {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 let splitsImpurity = 0.0;\n let splits = ['greater', 'lesser'];\n\n for (let i = 0; i < splits.length; ++i) {\n let currentSplit = splitted[splits[i]];\n splitsImpurity +=\n (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 let l = array.length;\n\n let m = meanArray(array);\n let error = 0.0;\n\n for (let i = 0; i < l; ++i) {\n let currentElement = array[i];\n error += (currentElement - m) * (currentElement - m);\n }\n\n return error;\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 let error = 0.0;\n let splits = ['greater', 'lesser'];\n\n for (let i = 0; i < splits.length; ++i) {\n let 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 let lesserX = [];\n let greaterX = [];\n let lesserY = [];\n let greaterY = [];\n\n for (let i = 0; i < X.rows; ++i) {\n if (X.get(i, column) < value) {\n lesserX.push(X.getRow(i));\n lesserY.push(y[i]);\n } else {\n greaterX.push(X.getRow(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(\n `Error on zip: the size of a: ${a.length} is different from b: ${b.length}`,\n );\n }\n\n let ret = new Array(a.length);\n for (let 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 mean from 'ml-array-mean';\n\nimport * as Utils from './utils';\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 * @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 // Depending in the node tree class, we set the variables to check information gain (to classify)\n // or error (for regression)\n\n let bestGain = this.kind === 'classifier' ? -Infinity : Infinity;\n let check = this.kind === 'classifier' ? (a, b) => a > b : (a, b) => a < b;\n\n let maxColumn;\n let maxValue;\n\n for (let i = 0; i < XTranspose.rows; ++i) {\n let currentFeature = XTranspose.getRow(i);\n let splitValues = this.featureSplit(currentFeature, y);\n for (let j = 0; j < splitValues.length; ++j) {\n let currentSplitVal = splitValues[j];\n let splitted = this.split(currentFeature, y, currentSplitVal);\n\n let 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 split(x, y, splitValue) {\n let lesser = [];\n let greater = [];\n\n for (let 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 let splitValues = [];\n let arr = Utils.zip(x, y);\n arr.sort(function(a, b) {\n return a[0] - b[0];\n });\n\n for (let i = 1; i < arr.length; ++i) {\n if (arr[i - 1][1] !== arr[i][1]) {\n splitValues.push(\n splitFunctions[this.splitFunction](arr[i - 1][0], arr[i][0]),\n );\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(\n y,\n Utils.getNumberOfClasses(y),\n );\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 let XTranspose = X.transpose();\n let split = this.bestSplit(XTranspose, y);\n\n this.splitValue = split.maxValue;\n this.splitColumn = split.maxColumn;\n this.gain = split.maxGain;\n\n let splittedMatrix = Utils.matrixSplitter(\n X,\n y,\n this.splitColumn,\n this.splitValue,\n );\n\n if (\n currentDepth < this.maxDepth &&\n (this.gain > 0.01 && this.gain !== parentGain) &&\n (splittedMatrix.lesserX.length > 0 && splittedMatrix.greaterX.length > 0)\n ) {\n this.left = new TreeNode(this);\n this.right = new TreeNode(this);\n\n let lesserX = new Matrix(splittedMatrix.lesserX);\n let greaterX = new Matrix(splittedMatrix.greaterX);\n\n this.left.train(\n lesserX,\n splittedMatrix.lesserY,\n currentDepth + 1,\n this.gain,\n );\n this.right.train(\n greaterX,\n splittedMatrix.greaterY,\n currentDepth + 1,\n this.gain,\n );\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 =\n node.distribution.constructor === Array\n ? 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';\n\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 * 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 let predictions = new Array(toPredict.rows);\n\n for (let i = 0; i < toPredict.rows; ++i) {\n predictions[i] = this.root\n .classify(toPredict.getRow(i))\n .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';\n\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 * 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 (\n typeof trainingSet[0] !== 'undefined' &&\n trainingSet[0].length === undefined\n ) {\n trainingSet = Matrix.columnVector(trainingSet);\n } else {\n trainingSet = Matrix.checkMatrix(trainingSet);\n }\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 (\n typeof toPredict[0] !== 'undefined' &&\n toPredict[0].length === undefined\n ) {\n toPredict = Matrix.columnVector(toPredict);\n }\n toPredict = Matrix.checkMatrix(toPredict);\n\n let predictions = new Array(toPredict.rows);\n for (let 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","const SMALLEST_UNSAFE_INTEGER = 0x20000000000000;\r\nconst LARGEST_SAFE_INTEGER = SMALLEST_UNSAFE_INTEGER - 1;\r\nconst UINT32_MAX = -1 >>> 0;\r\nconst UINT32_SIZE = UINT32_MAX + 1;\r\nconst INT32_SIZE = UINT32_SIZE / 2;\r\nconst INT32_MAX = INT32_SIZE - 1;\r\nconst UINT21_SIZE = 1 << 21;\r\nconst UINT21_MAX = UINT21_SIZE - 1;\n\n/**\r\n * Returns a value within [-0x80000000, 0x7fffffff]\r\n */\r\nfunction int32(engine) {\r\n return engine.next() | 0;\r\n}\n\nfunction add(distribution, addend) {\r\n if (addend === 0) {\r\n return distribution;\r\n }\r\n else {\r\n return engine => distribution(engine) + addend;\r\n }\r\n}\n\n/**\r\n * Returns a value within [-0x20000000000000, 0x1fffffffffffff]\r\n */\r\nfunction int53(engine) {\r\n const high = engine.next() | 0;\r\n const low = engine.next() >>> 0;\r\n return ((high & UINT21_MAX) * UINT32_SIZE +\r\n low +\r\n (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0));\r\n}\n\n/**\r\n * Returns a value within [-0x20000000000000, 0x20000000000000]\r\n */\r\nfunction int53Full(engine) {\r\n while (true) {\r\n const high = engine.next() | 0;\r\n if (high & 0x400000) {\r\n if ((high & 0x7fffff) === 0x400000 && (engine.next() | 0) === 0) {\r\n return SMALLEST_UNSAFE_INTEGER;\r\n }\r\n }\r\n else {\r\n const low = engine.next() >>> 0;\r\n return ((high & UINT21_MAX) * UINT32_SIZE +\r\n low +\r\n (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0));\r\n }\r\n }\r\n}\n\n/**\r\n * Returns a value within [0, 0xffffffff]\r\n */\r\nfunction uint32(engine) {\r\n return engine.next() >>> 0;\r\n}\n\n/**\r\n * Returns a value within [0, 0x1fffffffffffff]\r\n */\r\nfunction uint53(engine) {\r\n const high = engine.next() & UINT21_MAX;\r\n const low = engine.next() >>> 0;\r\n return high * UINT32_SIZE + low;\r\n}\n\n/**\r\n * Returns a value within [0, 0x20000000000000]\r\n */\r\nfunction uint53Full(engine) {\r\n while (true) {\r\n const high = engine.next() | 0;\r\n if (high & UINT21_SIZE) {\r\n if ((high & UINT21_MAX) === 0 && (engine.next() | 0) === 0) {\r\n return SMALLEST_UNSAFE_INTEGER;\r\n }\r\n }\r\n else {\r\n const low = engine.next() >>> 0;\r\n return (high & UINT21_MAX) * UINT32_SIZE + low;\r\n }\r\n }\r\n}\n\nfunction isPowerOfTwoMinusOne(value) {\r\n return ((value + 1) & value) === 0;\r\n}\r\nfunction bitmask(masking) {\r\n return (engine) => engine.next() & masking;\r\n}\r\nfunction downscaleToLoopCheckedRange(range) {\r\n const extendedRange = range + 1;\r\n const maximum = extendedRange * Math.floor(UINT32_SIZE / extendedRange);\r\n return engine => {\r\n let value = 0;\r\n do {\r\n value = engine.next() >>> 0;\r\n } while (value >= maximum);\r\n return value % extendedRange;\r\n };\r\n}\r\nfunction downscaleToRange(range) {\r\n if (isPowerOfTwoMinusOne(range)) {\r\n return bitmask(range);\r\n }\r\n else {\r\n return downscaleToLoopCheckedRange(range);\r\n }\r\n}\r\nfunction isEvenlyDivisibleByMaxInt32(value) {\r\n return (value | 0) === 0;\r\n}\r\nfunction upscaleWithHighMasking(masking) {\r\n return engine => {\r\n const high = engine.next() & masking;\r\n const low = engine.next() >>> 0;\r\n return high * UINT32_SIZE + low;\r\n };\r\n}\r\nfunction upscaleToLoopCheckedRange(extendedRange) {\r\n const maximum = extendedRange * Math.floor(SMALLEST_UNSAFE_INTEGER / extendedRange);\r\n return engine => {\r\n let ret = 0;\r\n do {\r\n const high = engine.next() & UINT21_MAX;\r\n const low = engine.next() >>> 0;\r\n ret = high * UINT32_SIZE + low;\r\n } while (ret >= maximum);\r\n return ret % extendedRange;\r\n };\r\n}\r\nfunction upscaleWithinU53(range) {\r\n const extendedRange = range + 1;\r\n if (isEvenlyDivisibleByMaxInt32(extendedRange)) {\r\n const highRange = ((extendedRange / UINT32_SIZE) | 0) - 1;\r\n if (isPowerOfTwoMinusOne(highRange)) {\r\n return upscaleWithHighMasking(highRange);\r\n }\r\n }\r\n return upscaleToLoopCheckedRange(extendedRange);\r\n}\r\nfunction upscaleWithinI53AndLoopCheck(min, max) {\r\n return engine => {\r\n let ret = 0;\r\n do {\r\n const high = engine.next() | 0;\r\n const low = engine.next() >>> 0;\r\n ret =\r\n (high & UINT21_MAX) * UINT32_SIZE +\r\n low +\r\n (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0);\r\n } while (ret < min || ret > max);\r\n return ret;\r\n };\r\n}\r\n/**\r\n * Returns a Distribution to return a value within [min, max]\r\n * @param min The minimum integer value, inclusive. No less than -0x20000000000000.\r\n * @param max The maximum integer value, inclusive. No greater than 0x20000000000000.\r\n */\r\nfunction integer(min, max) {\r\n min = Math.floor(min);\r\n max = Math.floor(max);\r\n if (min < -SMALLEST_UNSAFE_INTEGER || !isFinite(min)) {\r\n throw new RangeError(`Expected min to be at least ${-SMALLEST_UNSAFE_INTEGER}`);\r\n }\r\n else if (max > SMALLEST_UNSAFE_INTEGER || !isFinite(max)) {\r\n throw new RangeError(`Expected max to be at most ${SMALLEST_UNSAFE_INTEGER}`);\r\n }\r\n const range = max - min;\r\n if (range <= 0 || !isFinite(range)) {\r\n return () => min;\r\n }\r\n else if (range === UINT32_MAX) {\r\n if (min === 0) {\r\n return uint32;\r\n }\r\n else {\r\n return add(int32, min + INT32_SIZE);\r\n }\r\n }\r\n else if (range < UINT32_MAX) {\r\n return add(downscaleToRange(range), min);\r\n }\r\n else if (range === LARGEST_SAFE_INTEGER) {\r\n return add(uint53, min);\r\n }\r\n else if (range < LARGEST_SAFE_INTEGER) {\r\n return add(upscaleWithinU53(range), min);\r\n }\r\n else if (max - 1 - min === LARGEST_SAFE_INTEGER) {\r\n return add(uint53Full, min);\r\n }\r\n else if (min === -SMALLEST_UNSAFE_INTEGER &&\r\n max === SMALLEST_UNSAFE_INTEGER) {\r\n return int53Full;\r\n }\r\n else if (min === -SMALLEST_UNSAFE_INTEGER && max === LARGEST_SAFE_INTEGER) {\r\n return int53;\r\n }\r\n else if (min === -LARGEST_SAFE_INTEGER && max === SMALLEST_UNSAFE_INTEGER) {\r\n return add(int53, 1);\r\n }\r\n else if (max === SMALLEST_UNSAFE_INTEGER) {\r\n return add(upscaleWithinI53AndLoopCheck(min - 1, max - 1), 1);\r\n }\r\n else {\r\n return upscaleWithinI53AndLoopCheck(min, max);\r\n }\r\n}\n\nfunction isLeastBitTrue(engine) {\r\n return (engine.next() & 1) === 1;\r\n}\r\nfunction lessThan(distribution, value) {\r\n return engine => distribution(engine) < value;\r\n}\r\nfunction probability(percentage) {\r\n if (percentage <= 0) {\r\n return () => false;\r\n }\r\n else if (percentage >= 1) {\r\n return () => true;\r\n }\r\n else {\r\n const scaled = percentage * UINT32_SIZE;\r\n if (scaled % 1 === 0) {\r\n return lessThan(int32, (scaled - INT32_SIZE) | 0);\r\n }\r\n else {\r\n return lessThan(uint53, Math.round(percentage * SMALLEST_UNSAFE_INTEGER));\r\n }\r\n }\r\n}\r\nfunction bool(numerator, denominator) {\r\n if (denominator == null) {\r\n if (numerator == null) {\r\n return isLeastBitTrue;\r\n }\r\n return probability(numerator);\r\n }\r\n else {\r\n if (numerator <= 0) {\r\n return () => false;\r\n }\r\n else if (numerator >= denominator) {\r\n return () => true;\r\n }\r\n return lessThan(integer(0, denominator - 1), numerator);\r\n }\r\n}\n\n/**\r\n * Returns a Distribution that returns a random `Date` within the inclusive\r\n * range of [`start`, `end`].\r\n * @param start The minimum `Date`\r\n * @param end The maximum `Date`\r\n */\r\nfunction date(start, end) {\r\n const distribution = integer(+start, +end);\r\n return engine => new Date(distribution(engine));\r\n}\n\n/**\r\n * Returns a Distribution to return a value within [1, sideCount]\r\n * @param sideCount The number of sides of the die\r\n */\r\nfunction die(sideCount) {\r\n return integer(1, sideCount);\r\n}\n\n/**\r\n * Returns a distribution that returns an array of length `dieCount` of values\r\n * within [1, `sideCount`]\r\n * @param sideCount The number of sides of each die\r\n * @param dieCount The number of dice\r\n */\r\nfunction dice(sideCount, dieCount) {\r\n const distribution = die(sideCount);\r\n return engine => {\r\n const result = [];\r\n for (let i = 0; i < dieCount; ++i) {\r\n result.push(distribution(engine));\r\n }\r\n return result;\r\n };\r\n}\n\n// tslint:disable:unified-signatures\r\n// has 2**x chars, for faster uniform distribution\r\nconst DEFAULT_STRING_POOL = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-\";\r\nfunction string(pool = DEFAULT_STRING_POOL) {\r\n const poolLength = pool.length;\r\n if (!poolLength) {\r\n throw new Error(\"Expected pool not to be an empty string\");\r\n }\r\n const distribution = integer(0, poolLength - 1);\r\n return (engine, length) => {\r\n let result = \"\";\r\n for (let i = 0; i < length; ++i) {\r\n const j = distribution(engine);\r\n result += pool.charAt(j);\r\n }\r\n return result;\r\n };\r\n}\n\nconst LOWER_HEX_POOL = \"0123456789abcdef\";\r\nconst lowerHex = string(LOWER_HEX_POOL);\r\nconst upperHex = string(LOWER_HEX_POOL.toUpperCase());\r\n/**\r\n * Returns a Distribution that returns a random string comprised of numbers\r\n * or the characters `abcdef` (or `ABCDEF`) of length `length`.\r\n * @param length Length of the result string\r\n * @param uppercase Whether the string should use `ABCDEF` instead of `abcdef`\r\n */\r\nfunction hex(uppercase) {\r\n if (uppercase) {\r\n return upperHex;\r\n }\r\n else {\r\n return lowerHex;\r\n }\r\n}\n\nfunction convertSliceArgument(value, length) {\r\n if (value < 0) {\r\n return Math.max(value + length, 0);\r\n }\r\n else {\r\n return Math.min(value, length);\r\n }\r\n}\n\nfunction toInteger(value) {\r\n const num = +value;\r\n if (num < 0) {\r\n return Math.ceil(num);\r\n }\r\n else {\r\n return Math.floor(num);\r\n }\r\n}\n\n/**\r\n * Returns a random value within the provided `source` within the sliced\r\n * bounds of `begin` and `end`.\r\n * @param source an array of items to pick from\r\n * @param begin the beginning slice index (defaults to `0`)\r\n * @param end the ending slice index (defaults to `source.length`)\r\n */\r\nfunction pick(engine, source, begin, end) {\r\n const length = source.length;\r\n if (length === 0) {\r\n throw new RangeError(\"Cannot pick from an empty array\");\r\n }\r\n const start = begin == null ? 0 : convertSliceArgument(toInteger(begin), length);\r\n const finish = end === void 0 ? length : convertSliceArgument(toInteger(end), length);\r\n if (start >= finish) {\r\n throw new RangeError(`Cannot pick between bounds ${start} and ${finish}`);\r\n }\r\n const distribution = integer(start, finish - 1);\r\n return source[distribution(engine)];\r\n}\n\nfunction multiply(distribution, multiplier) {\r\n if (multiplier === 1) {\r\n return distribution;\r\n }\r\n else if (multiplier === 0) {\r\n return () => 0;\r\n }\r\n else {\r\n return engine => distribution(engine) * multiplier;\r\n }\r\n}\n\n/**\r\n * Returns a floating-point value within [0.0, 1.0)\r\n */\r\nfunction realZeroToOneExclusive(engine) {\r\n return uint53(engine) / SMALLEST_UNSAFE_INTEGER;\r\n}\n\n/**\r\n * Returns a floating-point value within [0.0, 1.0]\r\n */\r\nfunction realZeroToOneInclusive(engine) {\r\n return uint53Full(engine) / SMALLEST_UNSAFE_INTEGER;\r\n}\n\n/**\r\n * Returns a floating-point value within [min, max) or [min, max]\r\n * @param min The minimum floating-point value, inclusive.\r\n * @param max The maximum floating-point value.\r\n * @param inclusive If true, `max` will be inclusive.\r\n */\r\nfunction real(min, max, inclusive = false) {\r\n if (!isFinite(min)) {\r\n throw new RangeError(\"Expected min to be a finite number\");\r\n }\r\n else if (!isFinite(max)) {\r\n throw new RangeError(\"Expected max to be a finite number\");\r\n }\r\n return add(multiply(inclusive ? realZeroToOneInclusive : realZeroToOneExclusive, max - min), min);\r\n}\n\nconst sliceArray = Array.prototype.slice;\n\n/**\r\n * Shuffles an array in-place\r\n * @param engine The Engine to use when choosing random values\r\n * @param array The array to shuffle\r\n * @param downTo minimum index to shuffle. Only used internally.\r\n */\r\nfunction shuffle(engine, array, downTo = 0) {\r\n const length = array.length;\r\n if (length) {\r\n for (let i = (length - 1) >>> 0; i > downTo; --i) {\r\n const distribution = integer(0, i);\r\n const j = distribution(engine);\r\n if (i !== j) {\r\n const tmp = array[i];\r\n array[i] = array[j];\r\n array[j] = tmp;\r\n }\r\n }\r\n }\r\n return array;\r\n}\n\n/**\r\n * From the population array, produce an array with sampleSize elements that\r\n * are randomly chosen without repeats.\r\n * @param engine The Engine to use when choosing random values\r\n * @param population An array that has items to choose a sample from\r\n * @param sampleSize The size of the result array\r\n */\r\nfunction sample(engine, population, sampleSize) {\r\n if (sampleSize < 0 ||\r\n sampleSize > population.length ||\r\n !isFinite(sampleSize)) {\r\n throw new RangeError(\"Expected sampleSize to be within 0 and the length of the population\");\r\n }\r\n if (sampleSize === 0) {\r\n return [];\r\n }\r\n const clone = sliceArray.call(population);\r\n const length = clone.length;\r\n if (length === sampleSize) {\r\n return shuffle(engine, clone, 0);\r\n }\r\n const tailLength = length - sampleSize;\r\n return shuffle(engine, clone, tailLength - 1).slice(tailLength);\r\n}\n\nconst stringRepeat = (() => {\r\n try {\r\n if (\"x\".repeat(3) === \"xxx\") {\r\n return (pattern, count) => pattern.repeat(count);\r\n }\r\n }\r\n catch (_) {\r\n // nothing to do here\r\n }\r\n return (pattern, count) => {\r\n let result = \"\";\r\n while (count > 0) {\r\n if (count & 1) {\r\n result += pattern;\r\n }\r\n count >>= 1;\r\n pattern += pattern;\r\n }\r\n return result;\r\n };\r\n})();\n\nfunction zeroPad(text, zeroCount) {\r\n return stringRepeat(\"0\", zeroCount - text.length) + text;\r\n}\r\n/**\r\n * Returns a Universally Unique Identifier Version 4.\r\n *\r\n * See http://en.wikipedia.org/wiki/Universally_unique_identifier\r\n */\r\nfunction uuid4(engine) {\r\n const a = engine.next() >>> 0;\r\n const b = engine.next() | 0;\r\n const c = engine.next() | 0;\r\n const d = engine.next() >>> 0;\r\n return (zeroPad(a.toString(16), 8) +\r\n \"-\" +\r\n zeroPad((b & 0xffff).toString(16), 4) +\r\n \"-\" +\r\n zeroPad((((b >> 4) & 0x0fff) | 0x4000).toString(16), 4) +\r\n \"-\" +\r\n zeroPad(((c & 0x3fff) | 0x8000).toString(16), 4) +\r\n \"-\" +\r\n zeroPad(((c >> 4) & 0xffff).toString(16), 4) +\r\n zeroPad(d.toString(16), 8));\r\n}\n\n/**\r\n * An int32-producing Engine that uses `Math.random()`\r\n */\r\nconst nativeMath = {\r\n next() {\r\n return (Math.random() * UINT32_SIZE) | 0;\r\n }\r\n};\n\n// tslint:disable:unified-signatures\r\n/**\r\n * A wrapper around an Engine that provides easy-to-use methods for\r\n * producing values based on known distributions\r\n */\r\nclass Random {\r\n /**\r\n * Creates a new Random wrapper\r\n * @param engine The engine to use (defaults to a `Math.random`-based implementation)\r\n */\r\n constructor(engine = nativeMath) {\r\n this.engine = engine;\r\n }\r\n /**\r\n * Returns a value within [-0x80000000, 0x7fffffff]\r\n */\r\n int32() {\r\n return int32(this.engine);\r\n }\r\n /**\r\n * Returns a value within [0, 0xffffffff]\r\n */\r\n uint32() {\r\n return uint32(this.engine);\r\n }\r\n /**\r\n * Returns a value within [0, 0x1fffffffffffff]\r\n */\r\n uint53() {\r\n return uint53(this.engine);\r\n }\r\n /**\r\n * Returns a value within [0, 0x20000000000000]\r\n */\r\n uint53Full() {\r\n return uint53Full(this.engine);\r\n }\r\n /**\r\n * Returns a value within [-0x20000000000000, 0x1fffffffffffff]\r\n */\r\n int53() {\r\n return int53(this.engine);\r\n }\r\n /**\r\n * Returns a value within [-0x20000000000000, 0x20000000000000]\r\n */\r\n int53Full() {\r\n return int53Full(this.engine);\r\n }\r\n /**\r\n * Returns a value within [min, max]\r\n * @param min The minimum integer value, inclusive. No less than -0x20000000000000.\r\n * @param max The maximum integer value, inclusive. No greater than 0x20000000000000.\r\n */\r\n integer(min, max) {\r\n return integer(min, max)(this.engine);\r\n }\r\n /**\r\n * Returns a floating-point value within [0.0, 1.0]\r\n */\r\n realZeroToOneInclusive() {\r\n return realZeroToOneInclusive(this.engine);\r\n }\r\n /**\r\n * Returns a floating-point value within [0.0, 1.0)\r\n */\r\n realZeroToOneExclusive() {\r\n return realZeroToOneExclusive(this.engine);\r\n }\r\n /**\r\n * Returns a floating-point value within [min, max) or [min, max]\r\n * @param min The minimum floating-point value, inclusive.\r\n * @param max The maximum floating-point value.\r\n * @param inclusive If true, `max` will be inclusive.\r\n */\r\n real(min, max, inclusive = false) {\r\n return real(min, max, inclusive)(this.engine);\r\n }\r\n bool(numerator, denominator) {\r\n return bool(numerator, denominator)(this.engine);\r\n }\r\n /**\r\n * Return a random value within the provided `source` within the sliced\r\n * bounds of `begin` and `end`.\r\n * @param source an array of items to pick from\r\n * @param begin the beginning slice index (defaults to `0`)\r\n * @param end the ending slice index (defaults to `source.length`)\r\n */\r\n pick(source, begin, end) {\r\n return pick(this.engine, source, begin, end);\r\n }\r\n /**\r\n * Shuffles an array in-place\r\n * @param array The array to shuffle\r\n */\r\n shuffle(array) {\r\n return shuffle(this.engine, array);\r\n }\r\n /**\r\n * From the population array, returns an array with sampleSize elements that\r\n * are randomly chosen without repeats.\r\n * @param population An array that has items to choose a sample from\r\n * @param sampleSize The size of the result array\r\n */\r\n sample(population, sampleSize) {\r\n return sample(this.engine, population, sampleSize);\r\n }\r\n /**\r\n * Returns a value within [1, sideCount]\r\n * @param sideCount The number of sides of the die\r\n */\r\n die(sideCount) {\r\n return die(sideCount)(this.engine);\r\n }\r\n /**\r\n * Returns an array of length `dieCount` of values within [1, sideCount]\r\n * @param sideCount The number of sides of each die\r\n * @param dieCount The number of dice\r\n */\r\n dice(sideCount, dieCount) {\r\n return dice(sideCount, dieCount)(this.engine);\r\n }\r\n /**\r\n * Returns a Universally Unique Identifier Version 4.\r\n *\r\n * See http://en.wikipedia.org/wiki/Universally_unique_identifier\r\n */\r\n uuid4() {\r\n return uuid4(this.engine);\r\n }\r\n string(length, pool) {\r\n return string(pool)(this.engine, length);\r\n }\r\n /**\r\n * Returns a random string comprised of numbers or the characters `abcdef`\r\n * (or `ABCDEF`) of length `length`.\r\n * @param length Length of the result string\r\n * @param uppercase Whether the string should use `ABCDEF` instead of `abcdef`\r\n */\r\n hex(length, uppercase) {\r\n return hex(uppercase)(this.engine, length);\r\n }\r\n /**\r\n * Returns a random `Date` within the inclusive range of [`start`, `end`].\r\n * @param start The minimum `Date`\r\n * @param end The maximum `Date`\r\n */\r\n date(start, end) {\r\n return date(start, end)(this.engine);\r\n }\r\n}\n\n/**\r\n * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array\r\n */\r\nconst I32Array = (() => {\r\n try {\r\n const buffer = new ArrayBuffer(4);\r\n const view = new Int32Array(buffer);\r\n view[0] = INT32_SIZE;\r\n if (view[0] === -INT32_SIZE) {\r\n return Int32Array;\r\n }\r\n }\r\n catch (_) {\r\n // nothing to do here\r\n }\r\n return Array;\r\n})();\n\nlet data = null;\r\nconst COUNT = 128;\r\nlet index = COUNT;\r\n/**\r\n * An Engine that relies on the globally-available `crypto.getRandomValues`,\r\n * which is typically available in modern browsers.\r\n *\r\n * See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues\r\n *\r\n * If unavailable or otherwise non-functioning, then `browserCrypto` will\r\n * likely `throw` on the first call to `next()`.\r\n */\r\nconst browserCrypto = {\r\n next() {\r\n if (index >= COUNT) {\r\n if (data === null) {\r\n data = new I32Array(COUNT);\r\n }\r\n crypto.getRandomValues(data);\r\n index = 0;\r\n }\r\n return data[index++] | 0;\r\n }\r\n};\n\n/**\r\n * Returns an array of random int32 values, based on current time\r\n * and a random number engine\r\n *\r\n * @param engine an Engine to pull random values from, default `nativeMath`\r\n * @param length the length of the Array, minimum 1, default 16\r\n */\r\nfunction createEntropy(engine = nativeMath, length = 16) {\r\n const array = [];\r\n array.push(new Date().getTime() | 0);\r\n for (let i = 1; i < length; ++i) {\r\n array[i] = engine.next() | 0;\r\n }\r\n return array;\r\n}\n\n/**\r\n * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul\r\n */\r\nconst imul = (() => {\r\n try {\r\n if (Math.imul(UINT32_MAX, 5) === -5) {\r\n return Math.imul;\r\n }\r\n }\r\n catch (_) {\r\n // nothing to do here\r\n }\r\n const UINT16_MAX = 0xffff;\r\n return (a, b) => {\r\n const ah = (a >>> 16) & UINT16_MAX;\r\n const al = a & UINT16_MAX;\r\n const bh = (b >>> 16) & UINT16_MAX;\r\n const bl = b & UINT16_MAX;\r\n // the shift by 0 fixes the sign on the high part\r\n // the final |0 converts the unsigned value into a signed value\r\n return (al * bl + (((ah * bl + al * bh) << 16) >>> 0)) | 0;\r\n };\r\n})();\n\nconst ARRAY_SIZE = 624;\r\nconst ARRAY_MAX = ARRAY_SIZE - 1;\r\nconst M = 397;\r\nconst ARRAY_SIZE_MINUS_M = ARRAY_SIZE - M;\r\nconst A = 0x9908b0df;\r\n/**\r\n * An Engine that is a pseudorandom number generator using the Mersenne\r\n * Twister algorithm based on the prime 2**19937 − 1\r\n *\r\n * See http://en.wikipedia.org/wiki/Mersenne_twister\r\n */\r\nclass MersenneTwister19937 {\r\n /**\r\n * MersenneTwister19937 should not be instantiated directly.\r\n * Instead, use the static methods `seed`, `seedWithArray`, or `autoSeed`.\r\n */\r\n constructor() {\r\n this.data = new I32Array(ARRAY_SIZE);\r\n this.index = 0; // integer within [0, 624]\r\n this.uses = 0;\r\n }\r\n /**\r\n * Returns a MersenneTwister19937 seeded with an initial int32 value\r\n * @param initial the initial seed value\r\n */\r\n static seed(initial) {\r\n return new MersenneTwister19937().seed(initial);\r\n }\r\n /**\r\n * Returns a MersenneTwister19937 seeded with zero or more int32 values\r\n * @param source A series of int32 values\r\n */\r\n static seedWithArray(source) {\r\n return new MersenneTwister19937().seedWithArray(source);\r\n }\r\n /**\r\n * Returns a MersenneTwister19937 seeded with the current time and\r\n * a series of natively-generated random values\r\n */\r\n static autoSeed() {\r\n return MersenneTwister19937.seedWithArray(createEntropy());\r\n }\r\n /**\r\n * Returns the next int32 value of the sequence\r\n */\r\n next() {\r\n if ((this.index | 0) >= ARRAY_SIZE) {\r\n refreshData(this.data);\r\n this.index = 0;\r\n }\r\n const value = this.data[this.index];\r\n this.index = (this.index + 1) | 0;\r\n this.uses += 1;\r\n return temper(value) | 0;\r\n }\r\n /**\r\n * Returns the number of times that the Engine has been used.\r\n *\r\n * This can be provided to an unused MersenneTwister19937 with the same\r\n * seed, bringing it to the exact point that was left off.\r\n */\r\n getUseCount() {\r\n return this.uses;\r\n }\r\n /**\r\n * Discards one or more items from the engine\r\n * @param count The count of items to discard\r\n */\r\n discard(count) {\r\n if (count <= 0) {\r\n return this;\r\n }\r\n this.uses += count;\r\n if ((this.index | 0) >= ARRAY_SIZE) {\r\n refreshData(this.data);\r\n this.index = 0;\r\n }\r\n while (count + this.index > ARRAY_SIZE) {\r\n count -= ARRAY_SIZE - this.index;\r\n refreshData(this.data);\r\n this.index = 0;\r\n }\r\n this.index = (this.index + count) | 0;\r\n return this;\r\n }\r\n seed(initial) {\r\n let previous = 0;\r\n this.data[0] = previous = initial | 0;\r\n for (let i = 1; i < ARRAY_SIZE; i = (i + 1) | 0) {\r\n this.data[i] = previous =\r\n (imul(previous ^ (previous >>> 30), 0x6c078965) + i) | 0;\r\n }\r\n this.index = ARRAY_SIZE;\r\n this.uses = 0;\r\n return this;\r\n }\r\n seedWithArray(source) {\r\n this.seed(0x012bd6aa);\r\n seedWithArray(this.data, source);\r\n return this;\r\n }\r\n}\r\nfunction refreshData(data) {\r\n let k = 0;\r\n let tmp = 0;\r\n for (; (k | 0) < ARRAY_SIZE_MINUS_M; k = (k + 1) | 0) {\r\n tmp = (data[k] & INT32_SIZE) | (data[(k + 1) | 0] & INT32_MAX);\r\n data[k] = data[(k + M) | 0] ^ (tmp >>> 1) ^ (tmp & 0x1 ? A : 0);\r\n }\r\n for (; (k | 0) < ARRAY_MAX; k = (k + 1) | 0) {\r\n tmp = (data[k] & INT32_SIZE) | (data[(k + 1) | 0] & INT32_MAX);\r\n data[k] =\r\n data[(k - ARRAY_SIZE_MINUS_M) | 0] ^ (tmp >>> 1) ^ (tmp & 0x1 ? A : 0);\r\n }\r\n tmp = (data[ARRAY_MAX] & INT32_SIZE) | (data[0] & INT32_MAX);\r\n data[ARRAY_MAX] = data[M - 1] ^ (tmp >>> 1) ^ (tmp & 0x1 ? A : 0);\r\n}\r\nfunction temper(value) {\r\n value ^= value >>> 11;\r\n value ^= (value << 7) & 0x9d2c5680;\r\n value ^= (value << 15) & 0xefc60000;\r\n return value ^ (value >>> 18);\r\n}\r\nfunction seedWithArray(data, source) {\r\n let i = 1;\r\n let j = 0;\r\n const sourceLength = source.length;\r\n let k = Math.max(sourceLength, ARRAY_SIZE) | 0;\r\n let previous = data[0] | 0;\r\n for (; (k | 0) > 0; --k) {\r\n data[i] = previous =\r\n ((data[i] ^ imul(previous ^ (previous >>> 30), 0x0019660d)) +\r\n (source[j] | 0) +\r\n (j | 0)) |\r\n 0;\r\n i = (i + 1) | 0;\r\n ++j;\r\n if ((i | 0) > ARRAY_MAX) {\r\n data[0] = data[ARRAY_MAX];\r\n i = 1;\r\n }\r\n if (j >= sourceLength) {\r\n j = 0;\r\n }\r\n }\r\n for (k = ARRAY_MAX; (k | 0) > 0; --k) {\r\n data[i] = previous =\r\n ((data[i] ^ imul(previous ^ (previous >>> 30), 0x5d588b65)) - i) | 0;\r\n i = (i + 1) | 0;\r\n if ((i | 0) > ARRAY_MAX) {\r\n data[0] = data[ARRAY_MAX];\r\n i = 1;\r\n }\r\n }\r\n data[0] = INT32_SIZE;\r\n}\n\nlet data$1 = null;\r\nconst COUNT$1 = 128;\r\nlet index$1 = COUNT$1;\r\n/**\r\n * An Engine that relies on the node-available\r\n * `require('crypto').randomBytes`, which has been available since 0.58.\r\n *\r\n * See https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback\r\n *\r\n * If unavailable or otherwise non-functioning, then `nodeCrypto` will\r\n * likely `throw` on the first call to `next()`.\r\n */\r\nconst nodeCrypto = {\r\n next() {\r\n if (index$1 >= COUNT$1) {\r\n data$1 = new Int32Array(new Int8Array(require(\"crypto\").randomBytes(4 * COUNT$1)).buffer);\r\n index$1 = 0;\r\n }\r\n return data$1[index$1++] | 0;\r\n }\r\n};\n\n/**\r\n * Returns a Distribution to random value within the provided `source`\r\n * within the sliced bounds of `begin` and `end`.\r\n * @param source an array of items to pick from\r\n * @param begin the beginning slice index (defaults to `0`)\r\n * @param end the ending slice index (defaults to `source.length`)\r\n */\r\nfunction picker(source, begin, end) {\r\n const clone = sliceArray.call(source, begin, end);\r\n if (clone.length === 0) {\r\n throw new RangeError(`Cannot pick from a source with no items`);\r\n }\r\n const distribution = integer(0, clone.length - 1);\r\n return engine => clone[distribution(engine)];\r\n}\n\nexport { Random, browserCrypto, nativeMath, MersenneTwister19937, nodeCrypto, bool, date, dice, die, hex, int32, int53, int53Full, integer, pick, picker, real, realZeroToOneExclusive, realZeroToOneInclusive, sample, shuffle, string, uint32, uint53, uint53Full, uuid4, createEntropy };\n//# sourceMappingURL=random-js.esm.js.map\n","import * as 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(\n trainingSet,\n trainingValue,\n seed,\n) {\n let engine;\n let distribution = Random.integer(0, trainingSet.rows - 1);\n if (seed === undefined) {\n engine = Random.MersenneTwister19937.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = Random.MersenneTwister19937.seed(seed);\n } else {\n throw new RangeError(\n `Expected seed must be undefined or integer not ${seed}`,\n );\n }\n\n let Xr = new Array(trainingSet.rows);\n let yr = new Array(trainingSet.rows);\n\n for (let i = 0; i < trainingSet.rows; ++i) {\n let index = distribution(engine);\n Xr[i] = trainingSet.getRow(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 'N should be less or equal to the number of columns of X',\n );\n }\n\n let distribution = Random.integer(0, trainingSet.columns - 1);\n let engine;\n if (seed === undefined) {\n engine = Random.MersenneTwister19937.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = Random.MersenneTwister19937.seed(seed);\n } else {\n throw new RangeError(\n `Expected seed must be undefined or integer not ${seed}`,\n );\n }\n\n let toRet = new Matrix(trainingSet.rows, n);\n\n let usedIndex;\n let index;\n if (replacement) {\n usedIndex = new Array(n);\n for (let i = 0; i < n; ++i) {\n 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 (let 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 {\n Matrix,\n WrapperMatrix2D,\n MatrixTransposeView,\n MatrixColumnSelectionView,\n} 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 let 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(\n `The maxFeatures parameter should be less than ${trainingSet.columns}`,\n );\n } else {\n this.n = this.maxFeatures;\n }\n } else {\n throw new RangeError(\n `Cannot process the maxFeatures parameter ${this.maxFeatures}`,\n );\n }\n\n let Estimator;\n if (this.isClassifier) {\n 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 (let i = 0; i < this.nEstimators; ++i) {\n let res = this.useSampleBagging\n ? Utils.examplesBaggingWithReplacement(\n trainingSet,\n trainingValues,\n this.seed,\n )\n : { X: trainingSet, y: trainingValues };\n let X = res.X;\n let 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 let predictionValues = new Array(this.nEstimators);\n toPredict = Matrix.checkMatrix(toPredict);\n for (let i = 0; i < this.nEstimators; ++i) {\n let X = new MatrixColumnSelectionView(toPredict, this.indexes[i]); // get features for estimator\n predictionValues[i] = this.estimators[i].predict(X);\n }\n\n predictionValues = new MatrixTransposeView(\n new WrapperMatrix2D(predictionValues),\n );\n let predictions = new Array(predictionValues.rows);\n for (let 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 let 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\n .sort(\n (a, b) =>\n arr.filter((v) => v === a).length - arr.filter((v) => v === b).length,\n )\n .pop();\n}\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","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","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 (\n !(\n options.selectionMethod === 'mean' ||\n options.selectionMethod === 'median'\n )\n ) {\n throw new RangeError(\n `Unsupported selection method ${options.selectionMethod}`,\n );\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 let 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","import { Matrix, MatrixTransposeView, EVD, SVD, NIPALS } from 'ml-matrix';\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 {string} [options.method='SVD'] - select which method to use: SVD (default), covarianceMatrirx or NIPALS.\n * @param {number} [options.nCompNIPALS=2] - number of components to be computed with NIPALS.\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 * @param {boolean} [options.ignoreZeroVariance=false] - ignore columns with zero variance if `scale` is `true`.\n * */\nexport class 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 this.R = model.R;\n this.excludedFeatures = model.excludedFeatures || [];\n return;\n }\n\n dataset = new Matrix(dataset);\n\n const {\n isCovarianceMatrix = false,\n method = 'SVD',\n nCompNIPALS = 2,\n center = true,\n scale = false,\n ignoreZeroVariance = false,\n } = options;\n\n this.center = center;\n this.scale = scale;\n this.means = null;\n this.stdevs = null;\n this.excludedFeatures = [];\n\n if (isCovarianceMatrix) {\n // User provided a covariance matrix instead of dataset.\n this._computeFromCovarianceMatrix(dataset);\n return;\n }\n\n this._adjust(dataset, ignoreZeroVariance);\n switch (method) {\n case 'covarianceMatrix': {\n // User provided a dataset but wants us to compute and use the covariance matrix.\n const covarianceMatrix = new MatrixTransposeView(dataset)\n .mmul(dataset)\n .div(dataset.rows - 1);\n this._computeFromCovarianceMatrix(covarianceMatrix);\n break;\n }\n case 'NIPALS': {\n this._computeWithNIPALS(dataset, nCompNIPALS);\n break;\n }\n case 'SVD': {\n const 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 = [];\n for (const singularValue of singularValues) {\n eigenvalues.push((singularValue * singularValue) / (dataset.rows - 1));\n }\n this.S = eigenvalues;\n break;\n }\n default: {\n throw new Error(`unknown method: ${method}`);\n }\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 (typeof model.name !== 'string') {\n throw new TypeError('model must have a name property');\n }\n if (model.name !== 'PCA') {\n throw new RangeError(`invalid model: ${model.name}`);\n }\n return new PCA(true, model);\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 { nComponents = this.U.columns } = options;\n dataset = new Matrix(dataset);\n if (this.center) {\n dataset.subRowVector(this.means);\n if (this.scale) {\n for (let i of this.excludedFeatures) {\n dataset.removeColumn(i);\n }\n dataset.divRowVector(this.stdevs);\n }\n }\n var predictions = dataset.mmul(this.U);\n return predictions.subMatrix(0, predictions.rows - 1, 0, nComponents - 1);\n }\n\n /**\n * Calculates the inverse PCA transform\n * @param {Matrix} dataset\n * @return {Matrix} dataset projected in the PCA space\n */\n invert(dataset) {\n dataset = Matrix.checkMatrix(dataset);\n\n var inverse = dataset.mmul(this.U.transpose());\n\n if (this.center) {\n if (this.scale) {\n inverse.mulRowVector(this.stdevs);\n }\n inverse.addRowVector(this.means);\n }\n\n return inverse;\n }\n\n\n /**\n * Returns the proportion of variance for each component\n * @return {[number]}\n */\n getExplainedVariance() {\n var sum = 0;\n for (const s of this.S) {\n sum += s;\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 excludedFeatures: this.excludedFeatures,\n };\n }\n\n _adjust(dataset, ignoreZeroVariance) {\n if (this.center) {\n const mean = dataset.mean('column');\n const stdevs = this.scale\n ? dataset.standardDeviation('column', { mean })\n : null;\n this.means = mean;\n dataset.subRowVector(mean);\n if (this.scale) {\n for (let i = 0; i < stdevs.length; i++) {\n if (stdevs[i] === 0) {\n if (ignoreZeroVariance) {\n dataset.removeColumn(i);\n stdevs.splice(i, 1);\n this.excludedFeatures.push(i);\n i--;\n } else {\n throw new RangeError(\n `Cannot scale the dataset (standard deviation is zero at index ${i}`,\n );\n }\n }\n }\n this.stdevs = stdevs;\n dataset.divRowVector(stdevs);\n }\n }\n }\n\n _computeFromCovarianceMatrix(dataset) {\n const evd = new EVD(dataset, { assumeSymmetric: true });\n this.U = evd.eigenvectorMatrix;\n this.U.flipRows();\n this.S = evd.realEigenvalues;\n this.S.reverse();\n }\n\n _computeWithNIPALS(dataset, nCompNIPALS) {\n this.U = new Matrix(nCompNIPALS, dataset.columns);\n this.S = [];\n\n let x = dataset;\n for (let i = 0; i < nCompNIPALS; i++) {\n let dc = new NIPALS(x);\n\n this.U.setRow(i, dc.w.transpose());\n this.S.push(Math.pow(dc.s.get(0, 0), 2));\n\n x = dc.xResidual;\n }\n this.U = this.U.transpose(); // to be compatible with API\n }\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","/**\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 distance/similarity matrix. The matrix is square and has a size equal to the length of\n * the data array\n */\nexport default function distanceMatrix(data, distanceFn) {\n const result = getMatrix(data.length);\n\n // Compute upper distance matrix\n for (let i = 0; i < data.length; i++) {\n for (let j = 0; j <= i; j++) {\n result[i][j] = distanceFn(data[i], data[j]);\n result[j][i] = result[i][j];\n }\n }\n\n return result;\n}\n\nfunction getMatrix(size) {\n const matrix = [];\n for (let i = 0; i < size; i++) {\n const row = [];\n matrix.push(row);\n for (let j = 0; j < size; j++) {\n row.push(0);\n }\n }\n return matrix;\n}\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","module.exports = require('./lib/heap');\n","import Heap from 'heap';\n\nexport default class Cluster {\n constructor() {\n this.children = [];\n this.height = 0;\n this.size = 1;\n this.index = -1;\n this.isLeaf = false;\n }\n\n /**\n * Creates an array of clusters where the maximum height is smaller than the threshold\n * @param {number} threshold\n * @return {Array}\n */\n cut(threshold) {\n if (typeof threshold !== 'number') {\n throw new TypeError('threshold must be a number');\n }\n if (threshold < 0) {\n throw new RangeError('threshold must be a positive number');\n }\n let list = [this];\n const ans = [];\n while (list.length > 0) {\n const aux = list.shift();\n if (threshold >= aux.height) {\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 `groups` number of clusters.\n * @param {number} groups - Them number of children the first level of the tree should have.\n * @return {Cluster}\n */\n group(groups) {\n if (!Number.isInteger(groups) || groups < 1) {\n throw new RangeError('groups must be a positive integer');\n }\n\n const heap = new Heap((a, b) => {\n return b.height - a.height;\n });\n\n heap.push(this);\n\n while (heap.size() < groups) {\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.height = this.height;\n\n return root;\n }\n\n /**\n * Traverses the tree depth-first and calls the provided callback with each individual node\n * @param {function} cb - The callback to be called on each node encounter\n */\n traverse(cb) {\n function visit(root, callback) {\n callback(root);\n if (root.children) {\n for (const child of root.children) {\n visit(child, callback);\n }\n }\n }\n visit(this, cb);\n }\n\n /**\n * Returns a list of indices for all the leaves of this cluster.\n * The list is ordered in such a way that a dendrogram could be drawn without crossing branches.\n * @returns {Array}\n */\n indices() {\n const result = [];\n this.traverse((cluster) => {\n if (cluster.isLeaf) {\n result.push(cluster.index);\n }\n });\n return result;\n }\n}\n","import { euclidean } from 'ml-distance-euclidean';\nimport getDistanceMatrix from 'ml-distance-matrix';\nimport { Matrix } from 'ml-matrix';\n\nimport Cluster from './Cluster';\n\nfunction singleLink(dKI, dKJ) {\n return Math.min(dKI, dKJ);\n}\n\nfunction completeLink(dKI, dKJ) {\n return Math.max(dKI, dKJ);\n}\n\nfunction averageLink(dKI, dKJ, dIJ, ni, nj) {\n const ai = ni / (ni + nj);\n const aj = nj / (ni + nj);\n return ai * dKI + aj * dKJ;\n}\n\nfunction weightedAverageLink(dKI, dKJ) {\n return (dKI + dKJ) / 2;\n}\n\nfunction centroidLink(dKI, dKJ, dIJ, ni, nj) {\n const ai = ni / (ni + nj);\n const aj = nj / (ni + nj);\n const b = -(ni * nj) / (ni + nj) ** 2;\n return ai * dKI + aj * dKJ + b * dIJ;\n}\n\nfunction medianLink(dKI, dKJ, dIJ) {\n return dKI / 2 + dKJ / 2 - dIJ / 4;\n}\n\nfunction wardLink(dKI, dKJ, dIJ, ni, nj, nk) {\n const ai = (ni + nk) / (ni + nj + nk);\n const aj = (nj + nk) / (ni + nj + nk);\n const b = -nk / (ni + nj + nk);\n return ai * dKI + aj * dKJ + b * dIJ;\n}\n\nfunction wardLink2(dKI, dKJ, dIJ, ni, nj, nk) {\n const ai = (ni + nk) / (ni + nj + nk);\n const aj = (nj + nk) / (ni + nj + nk);\n const b = -nk / (ni + nj + nk);\n return Math.sqrt(ai * dKI * dKI + aj * dKJ * dKJ + b * dIJ * dIJ);\n}\n\n/**\n * Continuously merge nodes that have the least dissimilarity\n * @param {Array>} data - Array of points to be clustered\n * @param {object} [options]\n * @param {Function} [options.distanceFunction]\n * @param {string} [options.method] - Default: `'complete'`\n * @param {boolean} [options.isDistanceMatrix] - Is the input already a distance matrix?\n * @constructor\n */\nexport function agnes(data, options = {}) {\n const {\n distanceFunction = euclidean,\n method = 'complete',\n isDistanceMatrix = false,\n } = options;\n\n let updateFunc;\n if (!isDistanceMatrix) {\n data = getDistanceMatrix(data, distanceFunction);\n }\n let distanceMatrix = new Matrix(data);\n const numLeaves = distanceMatrix.rows;\n\n // allows to use a string or a given function\n if (typeof method === 'string') {\n switch (method.toLowerCase()) {\n case 'single':\n updateFunc = singleLink;\n break;\n case 'complete':\n updateFunc = completeLink;\n break;\n case 'average':\n case 'upgma':\n updateFunc = averageLink;\n break;\n case 'wpgma':\n updateFunc = weightedAverageLink;\n break;\n case 'centroid':\n case 'upgmc':\n updateFunc = centroidLink;\n break;\n case 'median':\n case 'wpgmc':\n updateFunc = medianLink;\n break;\n case 'ward':\n updateFunc = wardLink;\n break;\n case 'ward2':\n updateFunc = wardLink2;\n break;\n default:\n throw new RangeError(`unknown clustering method: ${method}`);\n }\n } else if (typeof method !== 'function') {\n throw new TypeError('method must be a string or function');\n }\n\n let clusters = [];\n for (let i = 0; i < numLeaves; i++) {\n const cluster = new Cluster();\n cluster.isLeaf = true;\n cluster.index = i;\n clusters.push(cluster);\n }\n\n for (let n = 0; n < numLeaves - 1; n++) {\n const [row, column, distance] = getSmallestDistance(distanceMatrix);\n const cluster1 = clusters[row];\n const cluster2 = clusters[column];\n const newCluster = new Cluster();\n newCluster.size = cluster1.size + cluster2.size;\n newCluster.children.push(cluster1, cluster2);\n newCluster.height = distance;\n\n const newClusters = [newCluster];\n const newDistanceMatrix = new Matrix(\n distanceMatrix.rows - 1,\n distanceMatrix.rows - 1,\n );\n const previous = (newIndex) =>\n getPreviousIndex(newIndex, Math.min(row, column), Math.max(row, column));\n\n for (let i = 1; i < newDistanceMatrix.rows; i++) {\n const prevI = previous(i);\n const prevICluster = clusters[prevI];\n newClusters.push(prevICluster);\n for (let j = 0; j < i; j++) {\n if (j === 0) {\n const dKI = distanceMatrix.get(row, prevI);\n const dKJ = distanceMatrix.get(prevI, column);\n const val = updateFunc(\n dKI,\n dKJ,\n distance,\n cluster1.size,\n cluster2.size,\n prevICluster.size,\n );\n newDistanceMatrix.set(i, j, val);\n newDistanceMatrix.set(j, i, val);\n } else {\n // Just copy distance from previous matrix\n const val = distanceMatrix.get(prevI, previous(j));\n newDistanceMatrix.set(i, j, val);\n newDistanceMatrix.set(j, i, val);\n }\n }\n }\n\n clusters = newClusters;\n distanceMatrix = newDistanceMatrix;\n }\n\n return clusters[0];\n}\n\nfunction getSmallestDistance(distance) {\n let smallest = Infinity;\n let smallestI = 0;\n let smallestJ = 0;\n for (let i = 1; i < distance.rows; i++) {\n for (let j = 0; j < i; j++) {\n if (distance.get(i, j) < smallest) {\n smallest = distance.get(i, j);\n smallestI = i;\n smallestJ = j;\n }\n }\n }\n return [smallestI, smallestJ, smallest];\n}\n\nfunction getPreviousIndex(newIndex, prev1, prev2) {\n newIndex -= 1;\n if (newIndex >= prev1) newIndex++;\n if (newIndex >= prev2) newIndex++;\n return newIndex;\n}\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","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","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","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.rows;\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.getRow(firstCenterIdx));\n\n // Init closest distances\n let closestDistSquared = new Matrix(1, X.rows);\n for (let i = 0; i < X.rows; i++) {\n closestDistSquared.set(0, i, squaredEuclidean(X.getRow(i), centers[0]));\n }\n let cumSumClosestDistSquared = [cumSum(closestDistSquared.getRow(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.columns));\n const distanceToCandidates = euclideanDistances(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.getRow(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.getRow(bestCandidate);\n closestDistSquared = bestDistSquared;\n cumSumClosestDistSquared = [cumSum(closestDistSquared.getRow(0))];\n probabilities = Matrix.mul(\n closestDistSquared,\n 1 / cumSumClosestDistSquared[0][nSamples - 1]\n );\n }\n return centers;\n}\n\nfunction euclideanDistances(A, B) {\n const result = new Matrix(A.rows, B.rows);\n for (let i = 0; i < A.rows; i++) {\n for (let j = 0; j < B.rows; 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 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';\n\nimport { separateClasses } from './utils';\n\nexport class GaussianNB {\n /**\n * Constructor for the Gaussian Naive Bayes classifier, the parameters here is just for loading purposes.\n * @constructor\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);\n\n if (trainingSet.rows !== trainingLabels.length) {\n throw new RangeError(\n 'the size of the training set and the training labels must be the same.'\n );\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 = separatedClasses[i].mean('column');\n var std = separatedClasses[i].standardDeviation('column', {\n mean: means\n });\n\n var logPriorProbability = Math.log(\n separatedClasses[i].rows / trainingSet.rows\n );\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] = [\n 1 / (C1 * currentStd),\n -2 * currentStd * currentStd\n ];\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 dataset = Matrix.checkMatrix(dataset);\n if (dataset.rows === this.calculateProbabilities[0].length) {\n throw new RangeError(\n 'the dataset must have the same features as the training set'\n );\n }\n\n var predictions = new Array(dataset.rows);\n\n for (var i = 0; i < predictions.length; ++i) {\n predictions[i] = getCurrentClass(\n dataset.getRow(i),\n this.means,\n this.calculateProbabilities\n );\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(\n 'The current model is not a Multinomial Naive Bayes, current model:',\n model.name\n );\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(\n currentCase[j - 1],\n mean[i][j - 1],\n classes[i][j][0],\n classes[i][j][1]\n );\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';\n\nimport { separateClasses } from './utils';\n\nexport class MultinomialNB {\n /**\n * Constructor for Multinomial Naive Bayes, the model parameter is for load purposes.\n * @constructor\n * @param {object} model - for load purposes.\n */\n constructor(model) {\n if (model) {\n this.conditionalProbability = Matrix.checkMatrix(\n model.conditionalProbability\n );\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(\n 'the size of the training set and the training labels must be the same.'\n );\n }\n\n var separateClass = separateClasses(trainingSet, trainingLabels);\n\n this.priorProbability = new Matrix(separateClass.length, 1);\n\n for (var i = 0; i < separateClass.length; ++i) {\n this.priorProbability.set(i, 0, Math.log(\n separateClass[i].rows / trainingSet.rows\n ));\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(\n i,\n Matrix.rowVector(classValues\n .sum('column'))\n .add(1)\n .div(divisor)\n .apply(matrixLog)\n );\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 const v = Matrix.columnVector(this.conditionalProbability\n .clone()\n .mulRowVector(currentElement)\n .sum('row'));\n predictions[i] = v\n .add(this.priorProbability)\n .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.set(i, j, Math.log(this.get(i, j)));\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(function (e) {\n return -e[1];\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, linearDistance, otherChild, 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 (\n bestNodes.size() < maxNodes ||\n Math.abs(linearDistance) < bestNodes.peek()[1]\n ) {\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 {\n // 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 { euclidean as euclideanDistance } from 'ml-distance-euclidean';\n\nimport KDTree from './KDTree';\n\nexport default class KNN {\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 { distance = euclideanDistance, k = classes.size + 1 } = 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(\n 'a custom distance function was used to create the model. Please provide it again'\n );\n }\n if (model.isEuclidean && distance !== euclideanDistance) {\n throw new Error(\n 'the model was created with the default distance function. Do not load it with another one'\n );\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 (\n Array.isArray(dataset[0]) &&\n typeof dataset[0][0] === 'number'\n ) {\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","import Matrix from 'ml-matrix';\n\n/**\n * @private\n * Function that given vector, returns its 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.set(i, j, this.get(i, j) ** 2);\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 = dataset.mean('column');\n var std = dataset.standardDeviation('column', { mean: means, unbiased: 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';\n\nimport * as Utils from './utils';\n\n/**\n * @class PLS\n */\nexport class PLS {\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 = trainingSet.mean('column');\n this.stdDevX = trainingSet.standardDeviation('column', { mean: this.meanX, unbiased: true });\n this.meanY = trainingValues.mean('column');\n this.stdDevY = trainingValues.standardDeviation('column', { mean: this.meanY, unbiased: true });\n\n if (this.scale) {\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.rows - 1, trainingSet.columns);\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().mul(trainingSet));\n var uIndex = maxSumColIndex(trainingValues.clone().mul(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).get(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).get(0, 0);\n var b = num.div(den).get(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.set(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).get(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 Matrix.rowVector(data.sum('column')).maxIndex()[0];\n}\n","import { Matrix, SingularValueDecomposition, inverse } from 'ml-matrix';\n\nimport { initializeMatrices } from './utils';\n\n/**\n * @class KOPLS\n */\nexport class KOPLS {\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 Array(this.orthogonalComp + 1);\n for (let i = 0; i < this.orthogonalComp + 1; i++) {\n kernelX[i] = new Array(this.orthogonalComp + 1);\n }\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.get(i, j) === Infinity) {\n this.set(i, j, 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.get(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 var KTestTrain = this.kernel.compute(toPredict, this.trainingSet);\n\n var temp = KTestTrain;\n KTestTrain = new Array(this.orthogonalComp + 1);\n for (let i = 0; i < this.orthogonalComp + 1; i++) {\n KTestTrain[i] = new Array(this.orthogonalComp + 1);\n }\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 * 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';\nconst defaultOptions = {\n mode: 'index'\n};\n\nmodule.exports = function *(M, N, options) {\n options = Object.assign({}, defaultOptions, options);\n var a = new Array(N);\n var c = new Array(M);\n var b = new Array(N);\n var p = new Array(N + 2);\n var x, y, z;\n\n // init a and b\n for (var i = 0; i < N; i++) {\n a[i] = i;\n if (i < N - M) b[i] = 0;\n else b[i] = 1;\n }\n\n // init c\n for (i = 0; i < M; i++) {\n c[i] = N - M + i;\n }\n\n // init p\n for (i = 0; i < p.length; i++) {\n if (i === 0) p[i] = N + 1;\n else if (i <= N - M) p[i] = 0;\n else if (i <= N) p[i] = i - N + M;\n else p[i] = -2;\n }\n\n function twiddle() {\n var i, j, k;\n j = 1;\n while (p[j] <= 0) {\n j++;\n }\n if (p[j - 1] === 0) {\n for (i = j - 1; i !== 1; i--) {\n p[i] = -1;\n }\n p[j] = 0;\n x = z = 0;\n p[1] = 1;\n y = j - 1;\n } else {\n if (j > 1) {\n p[j - 1] = 0;\n }\n do {\n j++;\n }\n while (p[j] > 0);\n k = j - 1;\n i = j;\n while (p[i] === 0) {\n p[i++] = -1;\n }\n if (p[i] === -1) {\n p[i] = p[k];\n z = p[k] - 1;\n x = i - 1;\n y = k - 1;\n p[k] = -1;\n } else {\n if (i === p[0]) {\n return 0;\n } else {\n p[j] = p[i];\n z = p[i] - 1;\n p[i] = 0;\n x = j - 1;\n y = i - 1;\n }\n }\n }\n return 1;\n }\n\n if (options.mode === 'index') {\n yield c.slice();\n while (twiddle()) {\n c[z] = a[x];\n yield c.slice();\n }\n } else if (options.mode === 'mask') {\n yield b.slice();\n while (twiddle()) {\n b[x] = 1;\n b[y] = 0;\n yield b.slice();\n }\n } else {\n throw new Error('Invalid mode');\n }\n};\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","'use strict';\n\nvar mlMatrix = require('ml-matrix');\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\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.set(i, j, actFunction(this.get(i, j)));\n };\n this.derivate = function (i, j) {\n this.set(i, j, derFunction(this.get(i, j)));\n };\n\n if (options.model) {\n // load model\n this.W = mlMatrix.Matrix.checkMatrix(options.W);\n this.b = mlMatrix.Matrix.checkMatrix(options.b);\n } else {\n // default constructor\n this.W = mlMatrix.Matrix.rand(this.inputSize, this.outputSize);\n this.b = mlMatrix.Matrix.zeros(1, this.outputSize);\n\n this.W.apply(function (i, j) {\n this.set(i, j, this.get(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.transpose().mmul(delta);\n this.db = mlMatrix.Matrix.rowVector(delta.sum('column'));\n\n var aCopy = a.clone();\n return delta.mmul(this.W.transpose()).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\nclass OutputLayer extends Layer {\n constructor(options) {\n super(options);\n\n this.activationFunction = function (i, j) {\n this.set(i, j, Math.exp(this.get(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\nclass FeedForwardNeuralNetworks {\n /**\n * Create a new Feedforward 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 = mlMatrix.Matrix.checkMatrix(features);\n this.dicts = dictOutputs(labels);\n\n var inputSize = features.columns;\n var outputSize = Object.keys(this.dicts.inputs).length;\n\n if (!this.model) {\n this.buildNetwork(inputSize, outputSize);\n }\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 input = this.model[i].forward(input);\n }\n\n // get probabilities\n return input.divColumnVector(input.sum('row'));\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.rows; ++i) {\n probabilities.set(i, this.dicts.inputs[labels[i]], probabilities.get(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 = mlMatrix.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\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 = FeedForwardNeuralNetworks;\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;","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 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;","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 = [];\n for (let i = 0; i < x.length; i++) {\n y.push(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 (n * xY - xSum * ySum) /\n 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: Math.sqrt(rmsd / n)\n };\n }\n}\n","import BaseRegression, {\n checkArrayLength,\n maybeToPrecision\n} from 'ml-regression-base';\nimport { Matrix, MatrixTransposeView, 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 =\n `${maybeToPrecision(this.coefficients[k], precision) + times}x`;\n } else {\n str =\n `${maybeToPrecision(this.coefficients[k], precision) +\n times\n }x${\n sup\n }${this.powers[k]\n }${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.set(i, k, 1);\n } else {\n F.set(i, k, Math.pow(x[i], powers[k]));\n }\n }\n }\n\n const FT = new MatrixTransposeView(F);\n const A = FT.mmul(F);\n const B = FT.mmul(new MatrixTransposeView(Y));\n\n pr.degree = degree - 1;\n pr.powers = powers;\n pr.coefficients = solve(A, B).to1DArray();\n}\n","import BaseRegression, {\n checkArrayLength,\n maybeToPrecision\n} 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 !== 0) {\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, {\n checkArrayLength,\n maybeToPrecision\n} 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 (\n `f(x) = ${\n maybeToPrecision(this.B, precision)\n } * e^(${\n maybeToPrecision(this.A, precision)\n } * x)`\n );\n }\n\n toLaTeX(precision) {\n if (this.A >= 0) {\n return (\n `f(x) = ${\n maybeToPrecision(this.B, precision)\n }e^{${\n maybeToPrecision(this.A, precision)\n }x}`\n );\n } else {\n return (\n `f(x) = \\\\frac{${\n maybeToPrecision(this.B, precision)\n }}{e^{${\n maybeToPrecision(-this.A, precision)\n }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, {\n checkArrayLength,\n maybeToPrecision\n} 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) {\n // 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(\n this.A,\n precision\n )} * x^${maybeToPrecision(this.B, precision)}`;\n }\n\n toLaTeX(precision) {\n let latex = '';\n if (this.B >= 0) {\n latex = `f(x) = ${maybeToPrecision(\n this.A,\n precision\n )}x^{${maybeToPrecision(this.B, precision)}}`;\n } else {\n latex = `f(x) = \\\\frac{${maybeToPrecision(\n this.A,\n precision\n )}}{x^{${maybeToPrecision(-this.B, precision)}}}`;\n }\n latex = latex.replace(/e([+-]?[0-9]+)/g, 'e^{$1}');\n return latex;\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, pseudoInverse } from 'ml-matrix';\n\nexport default class MultivariateLinearRegression {\n constructor(x, y, options = {}) {\n const { intercept = true, statistics = true } = options;\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 y = new Matrix(y);\n if (intercept) {\n x.addColumn(new Array(x.rows).fill(1));\n }\n let xt = x.transpose();\n const xx = xt\n .mmul(x);\n const xy = xt\n .mmul(y);\n const invxx = new SVD(xx)\n .inverse();\n const beta = xy\n .transpose()\n .mmul(invxx)\n .transpose();\n this.weights = beta.to2DArray();\n this.inputs = x.columns;\n this.outputs = y.columns;\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 = y.clone().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.rows - x.columns);\n this.stdError = Math.sqrt(variance);\n this.stdErrorMatrix = pseudoInverse(xx).mul(variance);\n this.stdErrors = this.stdErrorMatrix\n .diagonal()\n .map((d) => Math.sqrt(d));\n this.tStats = this.weights.map((d, i) =>\n (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 } else if (Matrix.isMatrix(x)) {\n const y = new Matrix(x.rows, this.outputs);\n for (let i = 0; i < x.rows; i++) {\n y.setRow(i, this._predict(x.getRow(i)));\n }\n return y;\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","'use strict';\n\nconst { squaredEuclidean } = require('ml-distance-euclidean');\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 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 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 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(\n Math.exp(\n -this.sigma *\n Math.pow(Math.pow(x[i - 1], i) - Math.pow(y[i - 1], i), 2)\n ),\n this.degree\n );\n }\n return sum;\n }\n}\n\nmodule.exports = ANOVAKernel;\n","'use strict';\n\nconst { squaredEuclidean } = require('ml-distance-euclidean');\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');\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');\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 { Matrix, MatrixTransposeView } = require('ml-matrix');\nconst GaussianKernel = require('ml-kernel-gaussian');\nconst PolynomialKernel = require('ml-kernel-polynomial');\nconst SigmoidKernel = require('ml-kernel-sigmoid');\n\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');\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(\n 'first argument must be a valid kernel type or instance'\n );\n }\n }\n\n compute(inputs, landmarks) {\n inputs = Matrix.checkMatrix(inputs);\n if (landmarks === undefined) {\n landmarks = inputs;\n } else {\n landmarks = Matrix.checkMatrix(landmarks);\n }\n if (this.kernelType === 'linear') {\n return inputs.mmul(new MatrixTransposeView(landmarks));\n }\n\n const kernelMatrix = new Matrix(inputs.rows, landmarks.rows);\n if (inputs === landmarks) {\n // fast path, matrix is symmetric\n for (let i = 0; i < inputs.rows; i++) {\n for (let j = i; j < inputs.rows; j++) {\n const value = this.kernelFunction.compute(\n inputs.getRow(i),\n inputs.getRow(j)\n );\n kernelMatrix.set(i, j, value);\n kernelMatrix.set(j, i, value);\n }\n }\n } else {\n for (let i = 0; i < inputs.rows; i++) {\n for (let j = 0; j < landmarks.rows; j++) {\n kernelMatrix.set(\n i,\n j,\n this.kernelFunction.compute(inputs.getRow(i), landmarks.getRow(j))\n );\n }\n }\n }\n return kernelMatrix;\n }\n}\n\nmodule.exports = Kernel;\n","import BaseRegression, {\n checkArrayLength,\n maybeToPrecision\n} from 'ml-regression-base';\nimport median from 'ml-array-median';\n\nexport default class TheilSenRegression extends BaseRegression {\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 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 +=\n ` ${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, {\n checkArrayLength,\n maybeToPrecision\n} from 'ml-regression-base';\nimport { solve } from 'ml-matrix';\n\n/**\n * @class RobustPolynomialRegression\n * @param {Array} x\n * @param {Array} y\n * @param {number} degree - polynomial degree\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 /**\n * Display the formula\n * @param {number} precision - precision for the numbers\n * @return {string}\n */\n toString(precision) {\n return this._toFormula(precision, false);\n }\n\n /**\n * Display the formula in LaTeX format\n * @param {number} precision - precision for the numbers\n * @return {string}\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) +\n times}x`;\n } else {\n str = `${maybeToPrecision(this.coefficients[k], precision) +\n 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 = Array(degree)\n .fill(0)\n .map((_, index) => index);\n\n const tuples = getRandomTuples(x, y, degree);\n\n var min;\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 {\n x: x[i],\n y: y[i]\n }\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 return l % 2 === 0 ? residuals[half - 1] : residuals[half];\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 */\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","/**\n * Returns a new array based on extraction of specific indices of an array\n * @private\n * @param {Array} vector\n * @param {Array} indices\n */\nexport default function selection(vector, indices) {\n let u = []; //new Float64Array(indices.length);\n for (let i = 0; i < indices.length; i++) {\n u[i] = vector[indices[i]];\n }\n return u;\n}\n","/**\n *\n * @private\n * @param {Array of arrays} collection\n */\nexport default function sortCollectionSet(collection) {\n let objectCollection = collection\n .map((value, index) => {\n let key = BigInt(0);\n value.forEach((item) => (key |= BigInt(1) << BigInt(item)));\n return { value, index, key };\n })\n .sort((a, b) => {\n if (a.key - b.key < 0) return -1;\n return 1;\n });\n\n let sorted = [];\n let indices = [];\n\n let key;\n for (let set of objectCollection) {\n if (set.key !== key) {\n key = set.key;\n indices.push([]);\n sorted.push(set.value);\n }\n indices[indices.length - 1].push(set.index);\n }\n\n let result = {\n values: sorted,\n indices: indices,\n };\n return result;\n}\n","import {\n Matrix,\n LuDecomposition,\n solve,\n CholeskyDecomposition,\n} from 'ml-matrix';\n\nimport sortCollectionSet from './util/sortCollectionSet';\n\n/**\n * (Combinatorial Subspace Least Squares) - subfunction for the FC-NNLS\n * @private\n * @param {Matrix} XtX\n * @param {Matrix} XtY\n * @param {Array} Pset\n * @param {Numbers} l\n * @param {Numbers} p\n */\nexport default function cssls(XtX, XtY, Pset, l, p) {\n // Solves the set of equation XtX*K = XtY for the variables in Pset\n // if XtX (or XtX(vars,vars)) is singular, performs the svd and find pseudoinverse, otherwise (even if ill-conditioned) finds inverse with LU decomposition and solves the set of equation\n // it is consistent with matlab results for ill-conditioned matrices (at least consistent with test 'ill-conditionned square X rank 2, Y 3x1' in cssls.test)\n\n let K = Matrix.zeros(l, p);\n if (Pset === null) {\n let choXtX = new CholeskyDecomposition(XtX);\n if (choXtX.isPositiveDefinite() === true) {\n K = choXtX.solve(XtY);\n } else {\n let luXtX = new LuDecomposition(XtX);\n if (luXtX.isSingular() === false) {\n K = luXtX.solve(Matrix.eye(l)).mmul(XtY);\n } else {\n K = solve(XtX, XtY, { useSVD: true });\n }\n }\n } else {\n let sortedPset = sortCollectionSet(Pset).values;\n let sortedEset = sortCollectionSet(Pset).indices;\n if (\n sortedPset.length === 1 &&\n sortedPset[0].length === 0 &&\n sortedEset[0].length === p\n ) {\n return K;\n } else if (\n sortedPset.length === 1 &&\n sortedPset[0].length === l &&\n sortedEset[0].length === p\n ) {\n let choXtX = new CholeskyDecomposition(XtX);\n if (choXtX.isPositiveDefinite() === true) {\n K = choXtX.solve(XtY);\n } else {\n let luXtX = new LuDecomposition(XtX);\n if (luXtX.isSingular() === false) {\n K = luXtX.solve(Matrix.eye(l)).mmul(XtY);\n } else {\n K = solve(XtX, XtY, { useSVD: true });\n }\n }\n } else {\n for (let k = 0; k < sortedPset.length; k++) {\n let cols2Solve = sortedEset[k];\n let vars = sortedPset[k];\n let L;\n let choXtX = new CholeskyDecomposition(XtX.selection(vars, vars));\n if (choXtX.isPositiveDefinite() === true) {\n L = choXtX.solve(XtY.selection(vars, cols2Solve));\n } else {\n let luXtX = new LuDecomposition(XtX.selection(vars, vars));\n if (luXtX.isSingular() === false) {\n L = luXtX\n .solve(Matrix.eye(vars.length))\n .mmul(XtY.selection(vars, cols2Solve));\n } else {\n L = solve(\n XtX.selection(vars, vars),\n XtY.selection(vars, cols2Solve),\n { useSVD: true },\n );\n }\n }\n for (let i = 0; i < L.rows; i++) {\n for (let j = 0; j < L.columns; j++) {\n K.set(vars[i], cols2Solve[j], L.get(i, j));\n }\n }\n }\n }\n }\n return K;\n}\n","import { Matrix } from 'ml-matrix';\n\nimport cssls from './cssls';\n\nexport default function initialisation(X, Y) {\n let n = X.rows;\n let l = X.columns;\n let p = Y.columns;\n let iter = 0;\n\n if (Y.rows !== n) throw new Error('ERROR: matrix size not compatible');\n\n let W = Matrix.zeros(l, p);\n\n // precomputes part of pseudoinverse\n let XtX = X.transpose().mmul(X);\n let XtY = X.transpose().mmul(Y);\n\n let K = cssls(XtX, XtY, null, l, p); // K is lxp\n let Pset = [];\n for (let j = 0; j < p; j++) {\n Pset[j] = [];\n for (let i = 0; i < l; i++) {\n if (K.get(i, j) > 0) {\n Pset[j].push(i);\n } else {\n K.set(i, j, 0);\n } //This is our initial solution, it's the solution found by overwriting the unconstrained least square solution\n }\n }\n let Fset = [];\n for (let j = 0; j < p; j++) {\n if (Pset[j].length !== l) {\n Fset.push(j);\n }\n }\n\n let D = K.clone();\n\n return { n, l, p, iter, W, XtX, XtY, K, Pset, Fset, D };\n}\n","/**\n * Computes the set difference A\\B\n * @private\n * @param {A} set A as an array\n * @param {B} set B as an array\n */\nexport default function setDifference(A, B) {\n let C = [];\n for (let i of A) {\n if (!B.includes(i)) C.push(i);\n }\n return C;\n}\n","import setDifference from './util/setDifference';\n\n// Makes sure the solution has converged\nexport default function optimality(\n iter,\n maxIter,\n XtX,\n XtY,\n Fset,\n Pset,\n W,\n K,\n l,\n p,\n D,\n) {\n if (iter === maxIter) {\n throw new Error('Maximum number of iterations exceeded');\n }\n\n // Check solution for optimality\n let V = XtY.subMatrixColumn(Fset).subtract(XtX.mmul(K.subMatrixColumn(Fset)));\n for (let j = 0; j < Fset.length; j++) {\n W.setColumn(Fset[j], V.subMatrixColumn([j]));\n }\n let Jset = [];\n let fullSet = [];\n for (let i = 0; i < l; i++) {\n fullSet.push(i);\n }\n for (let j = 0; j < Fset.length; j++) {\n let notPset = setDifference(fullSet, Pset[Fset[j]]);\n if (notPset.length === 0) {\n Jset.push(Fset[j]);\n } else if (W.selection(notPset, [Fset[j]]).max() <= 0) {\n Jset.push(Fset[j]);\n }\n }\n Fset = setDifference(Fset, Jset);\n\n // For non-optimal solutions, add the appropriate variables to Pset\n if (Fset.length !== 0) {\n for (let j = 0; j < Fset.length; j++) {\n for (let i = 0; i < l; i++) {\n if (Pset[Fset[j]].includes(i)) W.set(i, Fset[j], -Infinity);\n }\n Pset[Fset[j]].push(W.subMatrixColumn(Fset).maxColumnIndex(j)[0]);\n }\n for (let j = 0; j < Fset.length; j++) {\n D.setColumn(Fset[j], K.getColumn(Fset[j]));\n }\n }\n for (let j = 0; j < p; j++) {\n Pset[j].sort((a, b) => a - b);\n }\n return { Pset, Fset, W };\n}\n","import { Matrix } from 'ml-matrix';\n\nimport selection from './util/selection';\nimport cssls from './cssls';\nimport initialisation from './initialisation';\nimport optimality from './optimality';\n\n/**\n * Fast Combinatorial Non-negative Least Squares with multiple Right Hand Side\n * @param {Matrix|number[][]} X\n * @param {Matrix|number[][]} Y\n * @param {object} [options={}]\n * @param {number} [options.maxIterations] if empty maxIterations is set at 3 times the number of columns of X\n * @returns {Matrix} K\n */\nexport default function fcnnls(X, Y, options = {}) {\n X = Matrix.checkMatrix(X);\n Y = Matrix.checkMatrix(Y);\n let { l, p, iter, W, XtX, XtY, K, Pset, Fset, D } = initialisation(X, Y);\n const { maxIterations = X.columns * 3 } = options;\n\n // Active set algorithm for NNLS main loop\n while (Fset.length > 0) {\n // Solves for the passive variables (uses subroutine below)\n let L = cssls(\n XtX,\n XtY.subMatrixColumn(Fset),\n selection(Pset, Fset),\n l,\n Fset.length,\n );\n for (let i = 0; i < l; i++) {\n for (let j = 0; j < Fset.length; j++) {\n K.set(i, Fset[j], L.get(i, j));\n }\n }\n\n // Finds any infeasible solutions\n let infeasIndex = [];\n for (let j = 0; j < Fset.length; j++) {\n for (let i = 0; i < l; i++) {\n if (L.get(i, j) < 0) {\n infeasIndex.push(j);\n break;\n }\n }\n }\n let Hset = selection(Fset, infeasIndex);\n\n // Makes infeasible solutions feasible (standard NNLS inner loop)\n if (Hset.length > 0) {\n let m = Hset.length;\n let alpha = Matrix.ones(l, m);\n\n while (m > 0 && iter < maxIterations) {\n iter++;\n\n alpha.mul(Infinity);\n\n // Finds indices of negative variables in passive set\n let hRowColIdx = [[], []]; // Indexes work in pairs, each pair reprensents a single element, first array is row index, second array is column index\n let negRowColIdx = [[], []]; // Same as before\n for (let j = 0; j < m; j++) {\n for (let i = 0; i < Pset[Hset[j]].length; i++) {\n if (K.get(Pset[Hset[j]][i], Hset[j]) < 0) {\n hRowColIdx[0].push(Pset[Hset[j]][i]); // i\n hRowColIdx[1].push(j);\n negRowColIdx[0].push(Pset[Hset[j]][i]); // i\n negRowColIdx[1].push(Hset[j]);\n } // Compared to matlab, here we keep the row/column indexing (we are not taking the linear indexing)\n }\n }\n\n for (let k = 0; k < hRowColIdx[0].length; k++) {\n // could be hRowColIdx[1].length as well\n alpha.set(\n hRowColIdx[0][k],\n hRowColIdx[1][k],\n D.get(negRowColIdx[0][k], negRowColIdx[1][k]) /\n (D.get(negRowColIdx[0][k], negRowColIdx[1][k]) -\n K.get(negRowColIdx[0][k], negRowColIdx[1][k])),\n );\n }\n\n let alphaMin = [];\n let minIdx = [];\n for (let j = 0; j < m; j++) {\n alphaMin[j] = alpha.minColumn(j);\n minIdx[j] = alpha.minColumnIndex(j)[0];\n }\n\n alphaMin = Matrix.rowVector(alphaMin);\n for (let i = 0; i < l; i++) {\n alpha.setSubMatrix(alphaMin, i, 0);\n }\n\n let E = new Matrix(l, m);\n E = D.subMatrixColumn(Hset).subtract(\n alpha\n .subMatrix(0, l - 1, 0, m - 1)\n .mul(D.subMatrixColumn(Hset).subtract(K.subMatrixColumn(Hset))),\n );\n for (let j = 0; j < m; j++) {\n D.setColumn(Hset[j], E.subMatrixColumn([j]));\n }\n\n let idx2zero = [minIdx, Hset];\n for (let k = 0; k < m; k++) {\n D.set(idx2zero[0][k], idx2zero[1][k], 0);\n }\n\n for (let j = 0; j < m; j++) {\n Pset[Hset[j]].splice(\n Pset[Hset[j]].findIndex((item) => item === minIdx[j]),\n 1,\n );\n }\n\n L = cssls(XtX, XtY.subMatrixColumn(Hset), selection(Pset, Hset), l, m);\n for (let j = 0; j < m; j++) {\n K.setColumn(Hset[j], L.subMatrixColumn([j]));\n }\n\n Hset = [];\n for (let j = 0; j < K.columns; j++) {\n for (let i = 0; i < l; i++) {\n if (K.get(i, j) < 0) {\n Hset.push(j);\n\n break;\n }\n }\n }\n m = Hset.length;\n }\n }\n\n let newParam = optimality(\n iter,\n maxIterations,\n XtX,\n XtY,\n Fset,\n Pset,\n W,\n K,\n l,\n p,\n D,\n );\n Pset = newParam.Pset;\n Fset = newParam.Fset;\n W = newParam.W;\n }\n\n return K;\n}\n","import { Matrix } from 'ml-matrix';\n\nimport fcnnls from './fcnnls';\n\n/**\n * Fast Combinatorial Non-negative Least Squares with single Right Hand Side\n * @param {Matrix|number[][]} X\n * @param {number[]} y\n * @param {object} [options={}]\n * @param {boolean} [maxIterations] if true or empty maxIterations is set at 3 times the number of columns of X\n * @returns {Array} k\n */\nexport default function fcnnlsVector(X, y, options = {}) {\n if (Array.isArray(y) === false) {\n throw new TypeError('y must be a 1D Array');\n }\n let Y = Matrix.columnVector(y);\n let K = fcnnls(X, Y, options);\n let k = K.to1DArray();\n return k;\n}\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 // The naive `low + high >>> 1` could fail for array lengths > 2**31\n // because `>>>` converts its operands to int32. `low + (high - low >>> 1)`\n // works for array lengths <= 2**32-1 which is also Javascript's max array\n // length.\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';\n\nfunction assertNumber(number) {\n\tif (typeof number !== 'number' || Number.isNaN(number)) {\n\t\tthrow new TypeError('Expected a number');\n\t}\n}\n\nexports.ascending = (left, right) => {\n\tassertNumber(left);\n\tassertNumber(right);\n\treturn left - right;\n};\n\nexports.descending = (left, right) => {\n\tassertNumber(left);\n\tassertNumber(right);\n\treturn right - left;\n};\n","import binarySearch from 'binary-search';\nimport { ascending } from 'num-sort';\n\nexport const largestPrime = 0x7fffffff;\n\nconst primeNumbers = [\n // chunk #0\n largestPrime, // 2^31-1\n\n // chunk #1\n 5,\n 11,\n 23,\n 47,\n 97,\n 197,\n 397,\n 797,\n 1597,\n 3203,\n 6421,\n 12853,\n 25717,\n 51437,\n 102877,\n 205759,\n 411527,\n 823117,\n 1646237,\n 3292489,\n 6584983,\n 13169977,\n 26339969,\n 52679969,\n 105359939,\n 210719881,\n 421439783,\n 842879579,\n 1685759167,\n\n // chunk #2\n 433,\n 877,\n 1759,\n 3527,\n 7057,\n 14143,\n 28289,\n 56591,\n 113189,\n 226379,\n 452759,\n 905551,\n 1811107,\n 3622219,\n 7244441,\n 14488931,\n 28977863,\n 57955739,\n 115911563,\n 231823147,\n 463646329,\n 927292699,\n 1854585413,\n\n // chunk #3\n 953,\n 1907,\n 3821,\n 7643,\n 15287,\n 30577,\n 61169,\n 122347,\n 244703,\n 489407,\n 978821,\n 1957651,\n 3915341,\n 7830701,\n 15661423,\n 31322867,\n 62645741,\n 125291483,\n 250582987,\n 501165979,\n 1002331963,\n 2004663929,\n\n // chunk #4\n 1039,\n 2081,\n 4177,\n 8363,\n 16729,\n 33461,\n 66923,\n 133853,\n 267713,\n 535481,\n 1070981,\n 2141977,\n 4283963,\n 8567929,\n 17135863,\n 34271747,\n 68543509,\n 137087021,\n 274174111,\n 548348231,\n 1096696463,\n\n // chunk #5\n 31,\n 67,\n 137,\n 277,\n 557,\n 1117,\n 2237,\n 4481,\n 8963,\n 17929,\n 35863,\n 71741,\n 143483,\n 286973,\n 573953,\n 1147921,\n 2295859,\n 4591721,\n 9183457,\n 18366923,\n 36733847,\n 73467739,\n 146935499,\n 293871013,\n 587742049,\n 1175484103,\n\n // chunk #6\n 599,\n 1201,\n 2411,\n 4831,\n 9677,\n 19373,\n 38747,\n 77509,\n 155027,\n 310081,\n 620171,\n 1240361,\n 2480729,\n 4961459,\n 9922933,\n 19845871,\n 39691759,\n 79383533,\n 158767069,\n 317534141,\n 635068283,\n 1270136683,\n\n // chunk #7\n 311,\n 631,\n 1277,\n 2557,\n 5119,\n 10243,\n 20507,\n 41017,\n 82037,\n 164089,\n 328213,\n 656429,\n 1312867,\n 2625761,\n 5251529,\n 10503061,\n 21006137,\n 42012281,\n 84024581,\n 168049163,\n 336098327,\n 672196673,\n 1344393353,\n\n // chunk #8\n 3,\n 7,\n 17,\n 37,\n 79,\n 163,\n 331,\n 673,\n 1361,\n 2729,\n 5471,\n 10949,\n 21911,\n 43853,\n 87719,\n 175447,\n 350899,\n 701819,\n 1403641,\n 2807303,\n 5614657,\n 11229331,\n 22458671,\n 44917381,\n 89834777,\n 179669557,\n 359339171,\n 718678369,\n 1437356741,\n\n // chunk #9\n 43,\n 89,\n 179,\n 359,\n 719,\n 1439,\n 2879,\n 5779,\n 11579,\n 23159,\n 46327,\n 92657,\n 185323,\n 370661,\n 741337,\n 1482707,\n 2965421,\n 5930887,\n 11861791,\n 23723597,\n 47447201,\n 94894427,\n 189788857,\n 379577741,\n 759155483,\n 1518310967,\n\n // chunk #10\n 379,\n 761,\n 1523,\n 3049,\n 6101,\n 12203,\n 24407,\n 48817,\n 97649,\n 195311,\n 390647,\n 781301,\n 1562611,\n 3125257,\n 6250537,\n 12501169,\n 25002389,\n 50004791,\n 100009607,\n 200019221,\n 400038451,\n 800076929,\n 1600153859,\n\n // chunk #11\n 13,\n 29,\n 59,\n 127,\n 257,\n 521,\n 1049,\n 2099,\n 4201,\n 8419,\n 16843,\n 33703,\n 67409,\n 134837,\n 269683,\n 539389,\n 1078787,\n 2157587,\n 4315183,\n 8630387,\n 17260781,\n 34521589,\n 69043189,\n 138086407,\n 276172823,\n 552345671,\n 1104691373,\n\n // chunk #12\n 19,\n 41,\n 83,\n 167,\n 337,\n 677,\n 1361,\n 2729,\n 5471,\n 10949,\n 21911,\n 43853,\n 87719,\n 175447,\n 350899,\n 701819,\n 1403641,\n 2807303,\n 5614657,\n 11229331,\n 22458671,\n 44917381,\n 89834777,\n 179669557,\n 359339171,\n 718678369,\n 1437356741,\n\n // chunk #13\n 53,\n 107,\n 223,\n 449,\n 907,\n 1823,\n 3659,\n 7321,\n 14653,\n 29311,\n 58631,\n 117269,\n 234539,\n 469099,\n 938207,\n 1876417,\n 3752839,\n 7505681,\n 15011389,\n 30022781,\n 60045577,\n 120091177,\n 240182359,\n 480364727,\n 960729461,\n 1921458943\n];\n\nprimeNumbers.sort(ascending);\n\nexport function nextPrime(value) {\n let index = binarySearch(primeNumbers, value, ascending);\n if (index < 0) {\n index = ~index;\n }\n return primeNumbers[index];\n}\n","import { largestPrime, nextPrime } from './primeFinder';\n\nconst FREE = 0;\nconst FULL = 1;\nconst REMOVED = 2;\n\nconst defaultInitialCapacity = 150;\nconst defaultMinLoadFactor = 1 / 6;\nconst defaultMaxLoadFactor = 2 / 3;\n\nexport default class 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 =\n options.initialCapacity === undefined\n ? defaultInitialCapacity\n : options.initialCapacity;\n if (initialCapacity < 0) {\n throw new RangeError(\n `initial capacity must not be less than zero: ${initialCapacity}`\n );\n }\n\n const minLoadFactor =\n options.minLoadFactor === undefined\n ? defaultMinLoadFactor\n : options.minLoadFactor;\n const maxLoadFactor =\n options.maxLoadFactor === undefined\n ? defaultMaxLoadFactor\n : 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(\n `minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`\n );\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);\n this.values = newArray(capacity);\n this.state = newArray(capacity);\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(\n this.distinct + 1,\n this.minLoadFactor,\n this.maxLoadFactor\n );\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(\n this.distinct + 1,\n this.minLoadFactor,\n this.maxLoadFactor\n );\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(\n this.distinct,\n this.minLoadFactor,\n this.maxLoadFactor\n );\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 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);\n const newValues = newArray(newCapacity);\n const newState = newArray(newCapacity);\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\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(\n Math.max(size + 1, ((4 * size) / (3 * minLoad + maxLoad)) | 0)\n );\n}\n\nfunction chooseShrinkCapacity(size, minLoad, maxLoad) {\n return nextPrime(\n Math.max(size + 1, ((4 * size) / (minLoad + 3 * maxLoad)) | 0)\n );\n}\n\nfunction newArray(size) {\n return Array(size).fill(0);\n}\n","import HashTable from 'ml-hash-table';\n\nexport class SparseMatrix {\n constructor(rows, columns, options = {}) {\n if (rows instanceof SparseMatrix) {\n // clone\n const other = rows;\n this._init(\n other.rows,\n other.columns,\n other.elements.clone(),\n other.threshold\n );\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(\n 'Number of columns of left matrix are not equal to number of rows of right matrix.'\n );\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, {\n initialCapacity: this.cardinality\n });\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(\n fillTemplateFunction(inplaceOperator, {\n name: operator[i],\n op: operator[0]\n })\n );\n SparseMatrix.prototype[`${operator[i]}S`] = eval(\n fillTemplateFunction(inplaceOperatorScalar, {\n name: `${operator[i]}S`,\n op: operator[0]\n })\n );\n SparseMatrix.prototype[`${operator[i]}M`] = eval(\n fillTemplateFunction(inplaceOperatorMatrix, {\n name: `${operator[i]}M`,\n op: operator[0]\n })\n );\n\n SparseMatrix[operator[i]] = eval(\n fillTemplateFunction(staticOperator, { name: operator[i] })\n );\n }\n}\n\nvar methods = [['~', 'not']];\n\n[\n 'abs',\n 'acos',\n 'acosh',\n 'asin',\n 'asinh',\n 'atan',\n 'atanh',\n 'cbrt',\n 'ceil',\n 'clz32',\n 'cos',\n 'cosh',\n 'exp',\n 'expm1',\n 'floor',\n 'fround',\n 'log',\n 'log1p',\n 'log10',\n 'log2',\n 'round',\n 'sign',\n 'sin',\n 'sinh',\n 'sqrt',\n 'tan',\n 'tanh',\n '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(\n fillTemplateFunction(inplaceMethod, {\n name: method[i],\n method: method[0]\n })\n );\n SparseMatrix[method[i]] = eval(\n fillTemplateFunction(staticMethod, { name: method[i] })\n );\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","export default function additiveSymmetric(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function avg(a, b) {\n var ii = a.length;\n var max = 0;\n var ans = 0;\n var 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","export default function bhattacharyya(a, b) {\n var ii = a.length;\n var 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","export default function canberra(a, b) {\n var ii = a.length;\n var 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","export default function chebyshev(a, b) {\n var ii = a.length;\n var max = 0;\n var 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","export default function clark(a, b) {\n var i = 0;\n var ii = a.length;\n var d = 0;\n for (; i < ii; i++) {\n d += Math.sqrt(\n ((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i]))\n );\n }\n return 2 * d;\n}\n","export default 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","import czekanowskiSimilarity from '../similarities/czekanowski';\n\nexport default function czekanowskiDistance(a, b) {\n return 1 - czekanowskiSimilarity(a, b);\n}\n","export default function dice(a, b) {\n var ii = a.length;\n var p = 0;\n var q1 = 0;\n var 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","export default function divergence(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function fidelity(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return ans;\n}\n","export default function gower(a, b) {\n var ii = a.length;\n var 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","export default function harmonicMean(a, b) {\n var ii = a.length;\n var 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","export default function hellinger(a, b) {\n var ii = a.length;\n var 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","export default function innerProduct(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans += a[i] * b[i];\n }\n return ans;\n}\n","export default function intersection(a, b) {\n var ii = a.length;\n var 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","export default function jaccard(a, b) {\n var ii = a.length;\n var p1 = 0;\n var p2 = 0;\n var q1 = 0;\n var 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","export default function jeffreys(a, b) {\n var ii = a.length;\n var 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","export default function jensenDifference(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n (a[i] * Math.log(a[i]) + b[i] * Math.log(b[i])) / 2 -\n ((a[i] + b[i]) / 2) * Math.log((a[i] + b[i]) / 2);\n }\n return ans;\n}\n","export default function jensenShannon(a, b) {\n var ii = a.length;\n var p = 0;\n var 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","export default function kdivergence(a, b) {\n var ii = a.length;\n var 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","export default function kulczynski(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function kullbackLeibler(a, b) {\n var ii = a.length;\n var 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","export default function kumarHassebrook(a, b) {\n var ii = a.length;\n var p = 0;\n var p2 = 0;\n var 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","export default function kumarJohnson(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n 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","export default function lorentzian(a, b) {\n var ii = a.length;\n var 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","export default function manhattan(a, b) {\n var i = 0;\n var ii = a.length;\n var d = 0;\n for (; i < ii; i++) {\n d += Math.abs(a[i] - b[i]);\n }\n return d;\n}\n","export default function matusita(a, b) {\n var ii = a.length;\n var 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","export default function minkowski(a, b, p) {\n var i = 0;\n var ii = a.length;\n var 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","export default function motyka(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function neyman(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function pearson(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function probabilisticSymmetric(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function ruzicka(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function soergel(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function sorensen(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function squared(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function squaredChord(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i]));\n }\n return ans;\n}\n","export default function taneja(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n ((a[i] + b[i]) / 2) *\n Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i])));\n }\n return ans;\n}\n","export default function tanimoto(a, b, bitvector) {\n if (bitvector) {\n var inter = 0;\n var 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 }\n return inter / union;\n } else {\n var ii = a.length;\n var p = 0;\n var q = 0;\n var 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","import tanimotoS from '../similarities/tanimoto';\n\nexport default function tanimoto(a, b, bitvector) {\n if (bitvector) {\n return 1 - tanimotoS(a, b, bitvector);\n } else {\n var ii = a.length;\n var p = 0;\n var q = 0;\n var 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","export default function topsoe(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n a[i] * Math.log((2 * a[i]) / (a[i] + b[i])) +\n b[i] * Math.log((2 * b[i]) / (a[i] + b[i]));\n }\n return ans;\n}\n","export default function waveHedges(a, b) {\n var ii = a.length;\n var 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","import binarySearch from 'binary-search';\nimport { ascending } from 'num-sort';\n\n/**\n * Function that creates the tree\n * @param {Array>} spectrum\n * @param {object} [options]\n * @return {Tree|null}\n * left and right have the same structure than the parent,\n * or are null if they are leaves\n */\nexport function createTree(spectrum, options = {}) {\n var X = spectrum[0];\n const {\n minWindow = 0.16,\n threshold = 0.01,\n from = X[0],\n to = X[X.length - 1]\n } = options;\n\n return mainCreateTree(\n spectrum[0],\n spectrum[1],\n from,\n to,\n minWindow,\n threshold\n );\n}\n\nfunction mainCreateTree(X, Y, from, to, minWindow, threshold) {\n if (to - from < minWindow) {\n return null;\n }\n\n // search first point\n var start = binarySearch(X, from, ascending);\n if (start < 0) {\n start = ~start;\n }\n\n // stop at last point\n var sum = 0;\n var center = 0;\n for (var i = start; i < X.length; i++) {\n if (X[i] >= to) {\n break;\n }\n sum += Y[i];\n center += X[i] * Y[i];\n }\n\n if (sum < threshold) {\n return null;\n }\n\n center /= sum;\n if (center - from < 1e-6 || to - center < 1e-6) {\n return null;\n }\n if (center - from < minWindow / 4) {\n return mainCreateTree(X, Y, center, to, minWindow, threshold);\n } else {\n if (to - center < minWindow / 4) {\n return mainCreateTree(X, Y, from, center, minWindow, threshold);\n } else {\n return new Tree(\n sum,\n center,\n mainCreateTree(X, Y, from, center, minWindow, threshold),\n mainCreateTree(X, Y, center, to, minWindow, threshold)\n );\n }\n }\n}\n\nclass Tree {\n constructor(sum, center, left, right) {\n this.sum = sum;\n this.center = center;\n this.left = left;\n this.right = right;\n }\n}\n","import { createTree } from './createTree';\n\n/**\n * Similarity between two nodes\n * @param {Tree|Array>} a - tree A node\n * @param {Tree|Array>} b - tree B node\n * @param {object} [options]\n * @return {number} similarity measure between tree nodes\n */\nexport function getSimilarity(a, b, options = {}) {\n const { alpha = 0.1, beta = 0.33, gamma = 0.001 } = options;\n\n if (a === null || b === null) {\n return 0;\n }\n if (Array.isArray(a)) {\n a = createTree(a);\n }\n if (Array.isArray(b)) {\n b = createTree(b);\n }\n\n var C =\n (alpha * Math.min(a.sum, b.sum)) / Math.max(a.sum, b.sum) +\n (1 - alpha) * Math.exp(-gamma * Math.abs(a.center - b.center));\n\n return (\n beta * C +\n ((1 - beta) *\n (getSimilarity(a.left, b.left, options) +\n getSimilarity(a.right, b.right, options))) /\n 2\n );\n}\n","import { getSimilarity } from './getSimilarity';\n\nexport { createTree } from './createTree';\n\nexport function treeSimilarity(A, B, options = {}) {\n return getSimilarity(A, B, options);\n}\n\nexport function getFunction(options = {}) {\n return (A, B) => getSimilarity(A, B, options);\n}\n","export default function cosine(a, b) {\n var ii = a.length;\n var p = 0;\n var p2 = 0;\n var 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","import diceD from '../distances/dice';\n\nexport default function dice(a, b) {\n return 1 - diceD(a, b);\n}\n","import intersectionD from '../distances/intersection';\n\nexport default function intersection(a, b) {\n return 1 - intersectionD(a, b);\n}\n","import jaccardD from '../distances/jaccard';\n\nexport default function jaccard(a, b) {\n return 1 - jaccardD(a, b);\n}\n","import kulczynskiD from '../distances/kulczynski';\n\nexport default function kulczynski(a, b) {\n return 1 / kulczynskiD(a, b);\n}\n","import motykaD from '../distances/motyka';\n\nexport default function motyka(a, b) {\n return 1 - motykaD(a, b);\n}\n","import mean from 'ml-array-mean';\n\nimport cosine from './cosine';\n\nexport default function pearson(a, b) {\n var avgA = mean(a);\n var avgB = mean(b);\n\n var newA = new Array(a.length);\n var newB = new Array(b.length);\n for (var i = 0; i < newA.length; i++) {\n newA[i] = a[i] - avgA;\n newB[i] = b[i] - avgB;\n }\n\n return cosine(newA, newB);\n}\n","import squaredChordD from '../distances/squaredChord';\n\nexport default function squaredChord(a, b) {\n return 1 - squaredChordD(a, b);\n}\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\nconst measures = require('./measures');\n\nclass Performance {\n /**\n *\n * @param prediction - The prediction matrix\n * @param target - The target matrix (values: truthy for same class, falsy for different class)\n * @param options\n *\n * @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)\n * @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)\n */\n constructor(prediction, target, options) {\n options = options || {};\n if (prediction.length !== target.length || prediction[0].length !== target[0].length) {\n throw new Error('dimensions of prediction and target do not match');\n }\n const rows = prediction.length;\n const columns = prediction[0].length;\n const isDistance = !options.max;\n\n const predP = [];\n\n if (options.all) {\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n predP.push({\n pred: prediction[i][j],\n targ: target[i][j]\n });\n }\n }\n } else {\n if (rows < 3 || rows !== columns) {\n throw new Error('When \"all\" option is false, the prediction matrix must be square and have at least 3 columns');\n }\n for (var i = 0; i < rows - 1; i++) {\n for (var j = i + 1; j < columns; j++) {\n predP.push({\n pred: prediction[i][j],\n targ: target[i][j]\n });\n }\n }\n }\n\n if (isDistance) {\n predP.sort((a, b) => 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\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\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 }\n output = options.output;\n } else {\n output = new Array(cond);\n }\n\n var i;\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 } else if (options.value === 'replicate') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0]) output[i] = data[0];\n else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];\n else output[i] = data[len - 1];\n }\n } else if (options.value === 'symmetric') {\n if (options.size[0] > len || options.size[1] > len) {\n throw new RangeError(\n 'expanded value should not be bigger than the data length'\n );\n }\n for (i = 0; i < cond; i++) {\n if (i < options.size[0]) output[i] = data[options.size[0] - 1 - i];\n else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];\n else output[i] = data[2 * len + options.size[0] - i - 1];\n }\n } else {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0]) output[i] = options.value;\n else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];\n else 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 }\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 = Object.assign({}, defaultOptions, options);\n if (Array.isArray(data)) {\n if (Array.isArray(data[0])) return matrixCase(data, options);\n else return arrayCase(data, options);\n } else {\n throw new TypeError('data should be an array');\n }\n}\n\nmodule.exports = padArray;\n","import { Matrix, MatrixTransposeView, inverse } from 'ml-matrix';\nimport padArray from 'ml-pad-array';\n\nconst 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 */\nexport default function savitzkyGolay(data, h, options) {\n options = Object.assign({}, defaultOptions, options);\n if (\n options.windowSize % 2 === 0 ||\n options.windowSize < 5 ||\n !Number.isInteger(options.windowSize)\n ) {\n throw new RangeError(\n 'Invalid window size (should be odd and at least 5 integer number)',\n );\n }\n if (options.derivative < 0 || !Number.isInteger(options.derivative)) {\n throw new RangeError('Derivative should be a positive integer');\n }\n if (options.polynomial < 1 || !Number.isInteger(options.polynomial)) {\n throw new RangeError('Polynomial should be a positive integer');\n }\n\n let C, norm;\n let step = Math.floor(options.windowSize / 2);\n\n if (options.pad === 'pre') {\n data = padArray(data, { size: step, value: options.padValue });\n }\n\n let ans = new Array(data.length - 2 * step);\n\n if (\n options.windowSize === 5 &&\n options.polynomial === 2 &&\n (options.derivative === 1 || options.derivative === 2)\n ) {\n if (options.derivative === 1) {\n C = [-2, -1, 0, 1, 2];\n norm = 10;\n } else {\n C = [2, -1, -2, -1, 2];\n norm = 7;\n }\n } else {\n let J = Matrix.ones(options.windowSize, options.polynomial + 1);\n let inic = -(options.windowSize - 1) / 2;\n for (let i = 0; i < J.rows; i++) {\n for (let j = 0; j < J.columns; j++) {\n if (inic + 1 !== 0 || j !== 0) J.set(i, j, Math.pow(inic + i, j));\n }\n }\n let Jtranspose = new MatrixTransposeView(J);\n let Jinv = inverse(Jtranspose.mmul(J));\n C = Jinv.mmul(Jtranspose);\n C = C.getRow(options.derivative);\n norm = 1;\n }\n let det = norm * Math.pow(h, options.derivative);\n for (let k = step; k < data.length - step; k++) {\n let d = 0;\n for (let l = 0; l < C.length; l++) 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","// 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\nvar eightBits = require('./creator');\n\n/**\n * Count the number of true values in an array\n * @param {Array} arr\n * @return {number}\n */\nfunction count(arr) {\n var c = 0;\n for (var i = 0; i < arr.length; i++) {\n c += eightBits[arr[i] & 0xff] + eightBits[(arr[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","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","import max from 'ml-array-max';\nimport sum from 'ml-array-sum';\n\n/**\n * Computes the norm of the given values\n * @param {Array} input\n * @param {object} [options={}]\n * @param {string} [options.algorithm='absolute'] absolute, sum or max\n * @return {number}\n */\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 {\n var absoluteSumValue = absoluteSum(input);\n if (absoluteSumValue === 0) return input.slice(0);\n return input.map(function (element) {\n return element / absoluteSumValue;\n });\n }\n\n case 'max':\n {\n var maxValue = max(input);\n if (maxValue === 0) return input.slice(0);\n return input.map(function (element) {\n return element / maxValue;\n });\n }\n\n case 'sum':\n {\n var sumValue = sum(input);\n if (sumValue === 0) return input.slice(0);\n return input.map(function (element) {\n return element / sumValue;\n });\n }\n\n default:\n throw new Error(\"norm: unknown algorithm: \".concat(algorithm));\n }\n}\n\nfunction absoluteSum(input) {\n var sumValue = 0;\n\n for (var i = 0; i < input.length; i++) {\n sumValue += Math.abs(input[i]);\n }\n\n return sumValue;\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 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","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 { ascending, descending } 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, descending);\n } else {\n index = binarySearch(x, target, ascending);\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","import mean from 'ml-array-mean';\n\n/**\n *\n * @param {object} points\n * @param {Array} points.x\n * @param {Array} points.y\n * @param {object} [options]\n * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n.\n * @return {number}\n */\nexport default function covariance(points, options = {}) {\n const { x, y } = points;\n const { unbiased = true } = options;\n\n const meanX = mean(x);\n const meanY = mean(y);\n\n var error = 0;\n\n for (let i = 0; i < x.length; i++) {\n error += (x[i] - meanX) * (y[i] - meanY);\n }\n\n if (unbiased) {\n return error / (x.length - 1);\n } else {\n return error / x.length;\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 { ascending, descending } 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, descending);\n } else {\n index = binarySearch(x, value, ascending);\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","/**\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 if (numberOfPoints < 2) {\n throw new RangeError(\"'numberOfPoints' option must be greater than 1\");\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 = xResult.concat(zoneResult.x);\n yResult = yResult.concat(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, 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","import { DecisionTreeClassifier, DecisionTreeRegression } from 'ml-cart';\nimport {\n RandomForestClassifier,\n RandomForestRegression\n} from 'ml-random-forest';\n\n// Try to keep this list in the same structure as the README.\n\n// Unsupervised learning\nexport { PCA } from 'ml-pca';\nimport * as HClust from 'ml-hclust';\nexport { HClust };\nexport { default as KMeans } from 'ml-kmeans';\n\n// Supervised learning\nimport * as NaiveBayes from 'ml-naivebayes';\nexport { NaiveBayes };\nexport { default as KNN } from 'ml-knn';\nexport { PLS, KOPLS } from 'ml-pls';\nexport { default as CrossValidation } from 'ml-cross-validation';\nexport { default as ConfusionMatrix } from 'ml-confusion-matrix';\nexport { DecisionTreeClassifier };\nexport { RandomForestClassifier };\n\n// Artificial neural networks\nexport { default as FNN } from 'ml-fnn';\nexport { default as SOM } from 'ml-som';\n\n// Regression\nexport {\n SimpleLinearRegression,\n PolynomialRegression,\n MultivariateLinearRegression,\n PowerRegression,\n ExponentialRegression,\n TheilSenRegression,\n RobustPolynomialRegression\n} from 'ml-regression';\nexport { DecisionTreeRegression };\nexport { RandomForestRegression };\n\n// Optimization\nexport { default as levenbergMarquardt } from 'ml-levenberg-marquardt';\nimport * as FCNNLS from 'ml-fcnnls';\nexport { FCNNLS };\n\n// Math\nimport * as MatrixLib from 'ml-matrix';\nconst {\n Matrix,\n SVD,\n EVD,\n CholeskyDecomposition,\n LuDecomposition,\n QrDecomposition\n} = MatrixLib;\nexport {\n MatrixLib,\n Matrix,\n SVD,\n EVD,\n CholeskyDecomposition,\n LuDecomposition,\n QrDecomposition\n};\n\nexport { SparseMatrix } from 'ml-sparse-matrix';\nexport { default as Kernel } from 'ml-kernel';\nimport { distance, similarity } from 'ml-distance';\nexport { distance as Distance, similarity as Similarity };\nexport { default as distanceMatrix } from 'ml-distance-matrix';\nexport { default as XSadd } from 'ml-xsadd';\n\n// Statistics\nexport { default as Performance } from 'ml-performance';\n\n// Data preprocessing\nexport { default as savitzkyGolay } from 'ml-savitzky-golay';\n\n// Utility\nexport { default as BitArray } from 'ml-bit-array';\nexport { default as HashTable } from 'ml-hash-table';\nexport { default as padArray } from 'ml-pad-array';\nexport { default as binarySearch } from 'binary-search';\nimport * as numSort from 'num-sort';\nexport { numSort };\nexport { default as Random } from 'ml-random';\n\nimport min from 'ml-array-min';\nimport max from 'ml-array-max';\nimport median from 'ml-array-median';\nimport mean from 'ml-array-mean';\nimport mode from 'ml-array-mode';\nimport normed from 'ml-array-normed';\nimport rescale from 'ml-array-rescale';\nimport sequentialFill from 'ml-array-sequential-fill';\nimport sum from 'ml-array-sum';\nimport standardDeviation from 'ml-array-standard-deviation';\nimport variance from 'ml-array-variance';\nexport const Array = {\n min,\n max,\n median,\n mean,\n mode,\n normed,\n rescale,\n sequentialFill,\n standardDeviation,\n sum,\n variance\n};\n\nimport centroidsMerge from 'ml-array-xy-centroids-merge';\nimport closestX from 'ml-arrayxy-closestx';\nimport covariance from 'ml-array-xy-covariance';\nimport maxMerge from 'ml-array-xy-max-merge';\nimport maxY from 'ml-array-xy-max-y';\nimport sortX from 'ml-array-xy-sort-x';\nimport uniqueX from 'ml-arrayxy-uniquex';\nimport weightedMerge from 'ml-array-xy-weighted-merge';\nimport equallySpaced from 'ml-array-xy-equally-spaced';\nimport filterX from 'ml-array-xy-filter-x';\nexport const ArrayXY = {\n centroidsMerge,\n closestX,\n covariance,\n maxMerge,\n maxY,\n sortX,\n uniqueX,\n weightedMerge,\n equallySpaced,\n filterX\n};\n"],"names":["toString","Object","prototype","isAnyArray","object","call","endsWith","max","input","isArray","TypeError","length","maxValue","i","min","minValue","rescale","output","options","arguments","undefined","Array","currentMin","currentMax","RangeError","_options$min","autoMinMax","_options$max","factor","checkRowIndex","matrix","index","outer","rows","checkColumnIndex","columns","checkRowVector","vector","to1DArray","checkColumnVector","checkIndices","rowIndices","columnIndices","row","checkRowIndices","column","checkColumnIndices","some","r","from","c","checkRange","startRow","endRow","startColumn","endColumn","checkNumber","newArray","value","array","push","name","sumByRow","sum","j","get","sumByColumn","sumAll","v","productByRow","productByColumn","productAll","varianceByRow","unbiased","mean","cols","variance","sum1","sum2","x","varianceByColumn","varianceAll","size","centerByRow","set","centerByColumn","centerAll","getScaleByRow","scale","Math","pow","sqrt","scaleByRow","getScaleByColumn","scaleByColumn","getScaleAll","divider","scaleAll","inspectMatrix","indent","repeat","indentData","this","constructor","inspectData","maxRows","maxColumns","maxNumSize","maxI","maxJ","result","line","formatNumber","join","num","numStr","String","padEnd","precise","toPrecision","exponential","toExponential","eIndex","indexOf","e","substring","installMathOperations","AbstractMatrix","Matrix","add","addS","addM","checkMatrix","sub","subS","subM","subtract","subtractS","subtractM","mul","mulS","mulM","multiply","multiplyS","multiplyM","div","divS","divM","divide","divideS","divideM","mod","modS","modM","modulus","modulusS","modulusM","and","andS","andM","or","orS","orM","xor","xorS","xorM","leftShift","leftShiftS","leftShiftM","signPropagatingRightShift","signPropagatingRightShiftS","signPropagatingRightShiftM","rightShift","rightShiftS","rightShiftM","zeroFillRightShift","zeroFillRightShiftS","zeroFillRightShiftM","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","tan","tanh","trunc","arg0","powS","powM","newRows","newColumns","newData","newMatrix","fill","random","Number","isInteger","interval","zeros","data","l","matrix1","matrix2","isMatrix","klass","apply","callback","to2DArray","copy","toJSON","isRowVector","isColumnVector","isVector","isSquare","isSymmetric","isEchelonForm","previousColumn","checked","isReducedEchelonForm","k","echelonForm","clone","h","iMax","swapRows","tmp","reducedEchelonForm","m","n","maxRow","p","pivot","Error","setSubMatrix","neg","getRow","getRowVector","rowVector","setRow","row1","row2","temp","getColumn","getColumnVector","columnVector","setColumn","swapColumns","column1","column2","addRowVector","subRowVector","mulRowVector","divRowVector","addColumnVector","subColumnVector","mulColumnVector","divColumnVector","mulRow","mulColumn","maxIndex","idx","minIndex","maxRowIndex","minRow","minRowIndex","maxColumn","maxColumnIndex","minColumn","minColumnIndex","diag","norm","type","cumulativeSum","dot","vector2","vector1","mmul","other","Bcolj","Float64Array","s","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","r1","c1","r2","c2","embed","mat","resultat","console","warn","blockMult","a","b","halfRows","parseInt","halfCols","subMatrix","scaleRows","isFinite","scaleColumns","flipRows","middle","first","last","flipColumns","kroneckerProduct","q","transpose","sortRows","compareFunction","compareNumbers","sort","sortColumns","subMatrixRow","indices","subMatrixColumn","selection","rowIndex","columnIndex","trace","by","product","standardDeviation","center","Symbol","for","rand","randomInt","randInt","diagonal","identity","eye","negate","tensorProduct","nRows","nColumns","arrayData","removeRow","splice","addRow","removeColumn","newRow","addColumn","BaseView","MatrixColumnView","MatrixColumnSelectionView","MatrixFlipColumnView","MatrixFlipRowView","MatrixRowView","MatrixRowSelectionView","MatrixSelectionView","MatrixSubView","MatrixTransposeView","WrapperMatrix1D","_calculateIndex","WrapperMatrix2D","wrap","LuDecomposition","t","LUcolj","kmax","lu","pivotVector","pivotSign","LU","isSingular","col","solve","count","X","determinant","hypotenuse","QrDecomposition","qr","rdiag","nrm","QR","Rdiag","isFullRank","SingularValueDecomposition","computeLeftSingularVectors","computeRightSingularVectors","autoTranspose","wantu","Boolean","wantv","swapped","aux","nu","ni","U","V","work","si","nct","nrt","mrc","pp","eps","EPSILON","kase","alpha","MIN_VALUE","isNaN","ks","f","cs","sn","sp","spm1","epm1","sk","ek","shift","g","Y","threshold","scols","Ls","rightSingularVectors","VL","vrows","urows","VLU","solveForDiagonal","inverse","vcols","ucols","tol","ii","useSVD","leftHandSide","rightHandSide","d","subMatrix0","subMatrix1","subMatrix2","xrange","exception","range","dependenciesOneRow","error","thresholdValue","returnArray","linearDependencies","thresholdError","results","Abis","pseudoInverse","svdSolution","SVD","leftSingularVectors","covariance","xMatrix","yMatrix","yIsSame","cov","correlation","sdx","sdy","corr","EigenvalueDecomposition","assumeSymmetric","tred2","tql2","H","ort","orthes","hqr2","hh","dl1","c3","el1","s2","tst1","high","low","nn","w","ra","sa","vr","vi","notlast","cdivres","exshift","z","iter","cdiv","xr","xi","yr","yi","CholeskyDecomposition","dimension","positiveDefinite","L","isPositiveDefinite","B","nipals","scaleScores","maxIterations","terminationCriteria","u","tOld","diff","counter","xResidual","residual","yResidual","betas","sumValue","toDiscreteDistribution","numberOfClasses","counts","giniImpurity","probabilities","getNumberOfClasses","filter","val","arr","map","reduce","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","Infinity","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","DecisionTreeRegression","trainingValues","SMALLEST_UNSAFE_INTEGER","LARGEST_SAFE_INTEGER","UINT32_MAX","UINT32_SIZE","INT32_SIZE","INT32_MAX","UINT21_SIZE","UINT21_MAX","int32","engine","next","addend","int53","int53Full","uint32","uint53","uint53Full","isPowerOfTwoMinusOne","bitmask","masking","downscaleToLoopCheckedRange","extendedRange","maximum","downscaleToRange","isEvenlyDivisibleByMaxInt32","upscaleWithHighMasking","upscaleToLoopCheckedRange","upscaleWithinU53","highRange","upscaleWithinI53AndLoopCheck","integer","DEFAULT_STRING_POOL","string","pool","poolLength","charAt","LOWER_HEX_POOL","lowerHex","upperHex","toUpperCase","stringRepeat","pattern","_","nativeMath","I32Array","buffer","ArrayBuffer","view","Int32Array","createEntropy","Date","getTime","imul","al","bl","ARRAY_SIZE","ARRAY_MAX","M","ARRAY_SIZE_MINUS_M","A","MersenneTwister19937","uses","initial","seed","source","seedWithArray","refreshData","temper","getUseCount","discard","previous","sourceLength","checkFloat","examplesBaggingWithReplacement","trainingValue","Random","autoSeed","Xr","featureBagging","replacement","usedIndex","toRet","Set","has","RandomForestBase","maxFeatures","nEstimators","treeOptions","isClassifier","indexes","useSampleBagging","Estimator","DTClassifier","DTRegression","estimators","est","load","res","values","predictionValues","RandomForestClassifier","baseModel","mode","super","pop","_ref","module","exports","window","median","quickSelectMedian","slice","selectionMethods","arrayMean","arrayMedian","selectionMethod","RandomForestRegression","PCA","dataset","means","stdevs","S","R","excludedFeatures","isCovarianceMatrix","method","nCompNIPALS","ignoreZeroVariance","_computeFromCovarianceMatrix","_adjust","covarianceMatrix","_computeWithNIPALS","svd","singularValues","eigenvalues","singularValue","nComponents","invert","getExplainedVariance","getCumulativeVariance","explained","getEigenvectors","getEigenvalues","getStandardDeviations","getLoadings","evd","EVD","eigenvectorMatrix","realEigenvalues","reverse","dc","NIPALS","squaredEuclidean","euclidean","distanceMatrix","distanceFn","getMatrix","Heap","defaultCmp","heapify","heappop","heappush","heappushpop","heapreplace","insort","nlargest","nsmallest","updateItem","_siftdown","_siftup","lo","hi","cmp","mid","concat","item","lastelt","returnitem","_i","_j","_ref1","_results","_results1","_len","pos","elem","los","startpos","newitem","parent","parentpos","childpos","endpos","rightpos","nodes","replace","pushpop","peek","contains","clear","empty","heap","toArray","insert","top","front","require$$0","Cluster","children","height","isLeaf","cut","list","ans","group","groups","forEach","child","traverse","cb","visit","cluster","singleLink","dKI","dKJ","completeLink","averageLink","dIJ","nj","weightedAverageLink","centroidLink","medianLink","wardLink","nk","wardLink2","ai","aj","agnes","distanceFunction","isDistanceMatrix","updateFunc","getDistanceMatrix","numLeaves","toLowerCase","clusters","distance","getSmallestDistance","cluster1","cluster2","newCluster","newClusters","newDistanceMatrix","newIndex","getPreviousIndex","prevI","prevICluster","smallest","smallestI","smallestJ","prev1","prev2","nearestVector","listVectors","similarityFunction","vectorIndex","maxSim","sim","minDist","MAX_VALUE","dist","calculateDistanceMatrix","updateClusterID","centers","clusterID","updateCenters","prevCenters","K","nDim","centersLen","dim","id","hasConverged","oldCenters","tolerance","LOOP","FLOAT_MUL","sh1","sh2","sh3","multiply_uint32","nlo","XSadd","now","state","Uint32Array","init","getFloat","bind","getUint32","nextState","periodCertification","PROB_TOLERANCE","randomChoice","valuesArr","cumSum","getArray","randomIndex","seedOrRandom","xsadd","XSAdd","randomGenerator","choice","randomSample","mostDistant","maxDist","minDistCent","kmeanspp","nSamples","localTrials","firstCenterIdx","closestDistSquared","cumSumClosestDistSquared","candidateIdx","distanceToCandidates","euclideanDistances","bestCandidate","bestPot","bestDistSquared","newDistSquared","newPot","distanceSymbol","KMeansResult","centroids","converged","iterations","nearest","centroid","computeInformation","enrichedCentroids","withIterations","initialization","step","newCenters","kmeansGenerator","stepResult","stepNumber","kmeans","separateClasses","features","classes","totalPerClasses","separatedClasses","currentIndex","GaussianNB","reload","calculateProbabilities","C1","PI","std","logPriorProbability","currentStd","getCurrentClass","modelName","currentCase","maxProbability","predictedClass","currentProbability","calculateLogProbability","C2","MultinomialNB","conditionalProbability","priorProbability","separateClass","classValues","divisor","matrixLog","Node","obj","KDTree","points","metric","dimensions","buildTree","restoreParent","toJSONImpl","point","maxNodes","maxDistance","bestNodes","BinaryHeap","nearestSearch","ownDistance","linearPoint","bestChild","linearDistance","otherChild","saveNode","content","src","dest","depth","scoreFunction","element","bubbleUp","end","sinkDown","parentN","elemScore","child2N","child1N","swap","child1","child1Score","child2","KNN","labels","kdTree","isEuclidean","euclideanDistance","getSinglePrediction","knn","nearestPoints","pointsPerClass","maxPoints","lastElement","currentClass","currentPoints","pow2array","initializeMatrices","PLS","meanX","stdDevX","meanY","stdDevY","PBQ","R2X","scaleMethod","latentVectors","rx","cx","ry","cy","ssqXcal","sumOfSquaresY","T","P","Q","W","transposeX","transposeY","tIndex","maxSumColIndex","uIndex","t1","den","pnorm","ssqYcal","E","F","KOPLS","YLoadingMat","SigmaPow","YScoreMat","predScoreMat","YOrthLoadingVec","YOrthEigen","YOrthScoreMat","toNorm","TURegressionCoeff","kernelX","kernel","orthogonalComp","predictiveComp","predictiveComponents","orthogonalComponents","compute","Identity","Sigma","diagonalMatrix","YOrthScoreNorm","TpiPrime","CoTemp","SoTemp","toiPrime","ITo","lastScoreMat","lastTpPrime","KTestTrain","YOrthScoreVector","scoreMatPrime","p1","p2","p3","prediction","predYOrthVectors","ConfusionMatrix","actual","predicted","distinctLabels","actualIdx","predictedIdx","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","N","twiddle","CV","initMatrix","getDistinct","validate","Classifier","classifierOptions","testIdx","trainIdx","confusionMatrix","distinct","testFeatures","trainFeatures","testLabels","trainLabels","getTrainTest","classifier","updateConfusionMatrix","validateWithCallback","predictedLabels","leaveOneOut","leavePOut","gen","combinations","allIdx","kFold","current","folds","randi","logistic","expELU","param","softExponential","softExponentialPrime","ACTIVATION_FUNCTIONS","activation","derivate","arctan","softsign","relu","softplus","bent","sinusoid","sinc","gaussian","Layer","inputSize","outputSize","regularization","epsilon","activationParam","selectedFunction","params","actFunction","derFunction","activationFunction","mlMatrix","forward","backpropagation","delta","dW","db","aCopy","update","OutputLayer","FeedForwardNeuralNetworks","hiddenLayers","learningRate","dicts","layers","keys","buildNetwork","dictOutputs","inputs","propagate","outputs","NodeSquare","weights","som","neighbors","adjustWeights","target","influence","getDistance","otherNode","getDistanceTorus","distX","distY","gridDim","getNeighbors","xy","torus","getPos","bestNeighbor","direction","simA","simB","getPosition","NodeHexagonal","hX","distZ","fields","randomizer","squareEuclidean","gridType","SOM","hasOwnProperty","numWeights","converters","getConverters","extractor","creator","nodeType","hx","distanceMethod","getMaxDistance","times","findBMU","adjust","iterationCount","startLearningRate","mapRadius","algorithmMethod","_initNodes","done","normalizers","denormalizers","getNormalizer","getDenormalizer","minMax","getRandomValue","zero","one","loadModel","eval","export","includeDistance","initNodes","setTraining","convertedSet","numIterations","timeConstant","trainOne","neighbourhoodRadius","trainingSetFactor","bmu","_findBestMatchingUnit","now2","radiusLimit","xMin","xMax","yMin","yMax","theX","theY","getConvertedNodes","candidate","lowest","computePosition","self","_predict","getQuantizationError","fit","getFit","maybeToPrecision","digits","checkArraySize","BaseRegression","toLaTeX","score","y2","xSum","ySum","chi2","rmsd","xSquared","ySquared","xY","PolynomialRegression","degree","powers","coefficients","checkArrayLength","regress","precision","_toFormula","isLaTeX","sup","closeSup","fn","str","json","pr","FT","SimpleLinearRegression","slope","intercept","computeX","xFactor","absIntercept","operator","slr","numerator","ExponentialRegression","er","yl","linear","PowerRegression","newInputs","latex","xl","MultivariateLinearRegression","statistics","xt","xx","invxx","beta","fittedValues","ri","stdError","stdErrorMatrix","stdErrors","tStats","summary","regressionStatistics","standardError","observations","variables","tStat","sigma","GaussianKernel","constant","PolynomialKernel","SigmoidKernel","ANOVAKernel","len","CauchyKernel","ExponentialKernel","HistogramIntersectionKernel","LaplacianKernel","MultiquadraticKernel","RationalQuadraticKernel","kernelType","rbf","polynomial","poly","anova","cauchy","histogram","HistogramKernel","laplacian","multiquadratic","rational","RationalKernel","sigmoid","mlp","Kernel","KernelConstructor","kernelFunction","landmarks","kernelMatrix","TheilSenRegression","theilSen","slopes","medianSlope","cuts","RobustPolynomialRegression","robustPolynomial","tuples","getRandomTuples","calcCoefficients","residuals","residualsMedian","tuple","half","errorCalculation","parameters","parameterizedFunction","func","gradientFunction","evaluatedData","gradientDifference","paramFunction","auxParams","funcParam","matrixFunction","damping","gradientFunc","matrixFunc","inverseMatrix","levenbergMarquardt","errorTolerance","minValues","maxValues","initialValues","parLen","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","iteration","parameterValues","parameterError","sortCollectionSet","collection","key","objectCollection","BigInt","sorted","cssls","XtX","XtY","Pset","choXtX","luXtX","sortedPset","sortedEset","cols2Solve","vars","initialisation","Fset","D","setDifference","C","includes","optimality","maxIter","Jset","fullSet","notPset","fcnnls","infeasIndex","Hset","ones","hRowColIdx","negRowColIdx","alphaMin","minIdx","idx2zero","findIndex","newParam","fcnnlsVector","haystack","needle","comparator","assertNumber","number","largestPrime","primeNumbers","nextPrime","binarySearch","ascending","FREE","FULL","REMOVED","defaultInitialCapacity","defaultMinLoadFactor","defaultMaxLoadFactor","HashTable","table","minLoadFactor","maxLoadFactor","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","SparseMatrix","_init","elements","symmetric","forEachNonZero","bandWidth","isBanded","width","v1","v2","cardinality","getNonZeros","setThreshold","newThreshold","trans","inplaceOperator","inplaceOperatorScalar","inplaceOperatorMatrix","staticOperator","inplaceMethod","staticMethod","operators","fillTemplateFunction","op","methods","mathMethod","template","RegExp","additiveSymmetric","avg","bhattacharyya","canberra","chebyshev","clark","czekanowskiSimilarity","up","down","czekanowskiDistance","dice","q1","q2","divergence","fidelity","gower","harmonicMean","hellinger","innerProduct","intersection","jaccard","jeffreys","jensenDifference","jensenShannon","kdivergence","kulczynski","kullbackLeibler","kumarHassebrook","kumarJohnson","lorentzian","manhattan","matusita","minkowski","motyka","neyman","pearson","probabilisticSymmetric","ruzicka","soergel","sorensen","squared","squaredChord","taneja","tanimoto","bitvector","inter","union","tanimotoS","topsoe","waveHedges","createTree","spectrum","minWindow","to","mainCreateTree","start","getSimilarity","gamma","treeSimilarity","getFunction","cosine","diceD","intersectionD","jaccardD","kulczynskiD","motykaD","avgA","avgB","newA","newB","squaredChordD","pred","cutoffs","tn","tp","fp","nNeg","nPos","nPosPred","nNegPred","Performance","isDistance","predP","all","targ","currentPred","nTp","nFp","getMeasure","measure","measures","getAURC","auc","getAUDC","getDistribution","cutLength","cutLow","cutHigh","xLabels","interValues","intraValues","interCumPercent","intraCumPercent","nTP","currentTP","nFP","currentFP","thisTP","thisFP","names","acc","err","fpr","tpr","fnr","tnr","ppv","npv","pcfall","pcmiss","lift","rpp","rnp","arrayCase","cond","matrixCase","padArray","windowSize","derivative","pad","padValue","savitzkyGolay","J","inic","Jtranspose","det","eightBits","arr1","arr2","getBit","mask","setBit","toBinaryString","substr","parseBinaryString","toHexString","parseHexString","toDebug","binary","maxCount","_options$algorithm","algorithm","absoluteSumValue","absoluteSum","_typeof","iterator","sequentialFill","_options","_options$from","_options$to","_options$size","_options$unbiased","_options$mean","sqrError","mergeByCentroids","originalPoints","mergedPoints","originalIndex","mergedIndex","closestX","descending","maxMerge","groupWidth","merged","maxAbscissa","maxY","calculateIndex","sortX","sortFunc","grouped","response","uniqueX","weightedMerge","weightedAbscissa","integral","x0","x1","equallySpacedSmooth","numberOfPoints","xLength","halfStep","initialOriginalStep","lastOriginalStep","previousX","previousY","nextX","nextY","currentValue","sumAtMin","sumAtMax","main","equallySpacedSlot","lastStep","frontOutsideSpectra","backOutsideSpectra","getZones","exclusions","exclusion","JSON","parse","stringify","toRemove","unitsPerPoint","zones","currentFrom","totalPoints","currentNbPoints","equallySpaced","arrayXY","variant","xResult","yResult","zone","zoneResult","processZone","filterX","currentZoneIndex","newX","newY","position","MatrixLib","normed","ArrayXY","centroidsMerge"],"mappings":"sMAEA,MAAMA,SAAWC,OAAOC,UAAUF,SAElC,SAASG,WAAWC,UACXJ,SAASK,KAAKD,GAAQE,SAAS,UAGxC,QAAiBH,WCAjB,SAASI,IAAIC,OACNC,IAAQD,SACL,IAAIE,UAAU,6BAGD,IAAjBF,EAAMG,aACF,IAAID,UAAU,mCAG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AAM/R,GAAQD,EAAOC,IAAS,IACGg+B,EAAQjsB,EAAKgsB,IAGrC,EACP/9B,EAAO+R,EAAM,MAGV,CAAA,KAAGD,EAAM,GAKZ,OAAOC,EAJPhS,EAAOgS,EAAM,SAQT/R,GCzCV,SAASk+B,aAAaC,MACC,iBAAXA,GAAuB3yC,OAAO+P,MAAM4iC,SACxC,IAAIx/C,UAAU,qBAItB,cAAoB,CAACqnB,EAAMC,KAC1Bi4B,aAAal4B,GACbk4B,aAAaj4B,GACND,EAAOC,cAGM,CAACD,EAAMC,KAC3Bi4B,aAAal4B,GACbk4B,aAAaj4B,GACNA,EAAQD,iLCdT,MAAMo4B,aAAe,WAEtBC,aAAe,CAEnBD,aAGA,EACA,GACA,GACA,GACA,GACA,IACA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,UACA,WAGA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,UACA,WAGA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,WACA,WAGA,KACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,GACA,GACA,IACA,IACA,IACA,KACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,IACA,KACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,EACA,EACA,GACA,GACA,GACA,IACA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,GACA,GACA,IACA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,UACA,WAGA,GACA,GACA,GACA,IACA,IACA,IACA,KACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,GACA,GACA,GACA,IACA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,GACA,IACA,IACA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,UACA,YAKK,SAASE,UAAU38C,OACpB3B,EAAQu+C,aAAaF,aAAc18C,EAAO68C,kBAC1Cx+C,EAAQ,IACVA,GAASA,GAEJq+C,aAAar+C,GAPtBq+C,aAAa1oC,KAAK6oC,WCtWlB,MAAMC,KAAO,EACPC,KAAO,EACPC,QAAU,EAEVC,uBAAyB,IACzBC,qBAAuB,EAAI,EAC3BC,qBAAuB,EAAI,EAElB,MAAMC,UACnBv6C,kBAAYrF,yDAAU,MAChBA,aAAmB4/C,sBAChBC,MAAQ7/C,EAAQ6/C,MAAM/wB,aACtBb,OAASjuB,EAAQiuB,OAAOa,aACxBsL,MAAQp6B,EAAQo6B,MAAMtL,aACtBgxB,cAAgB9/C,EAAQ8/C,mB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uD,EAAMslD,EAAIyJ,GAG3BoB,EAAmB,EACnBC,EAAO,GACPC,EAAO,GACPC,EAAW,OACRA,EAAWxuD,EAAEpE,QAAQ,IAExBoE,EAAEwuD,IAAahB,EAAMa,GAAkB7K,IACvCxjD,EAAEwuD,IAAahB,EAAMa,GAAkBnwD,KAEvCowD,EAAKzvD,KAAKmB,EAAEwuD,IACZD,EAAK1vD,KAAK+R,EAAE49C,YAERxuD,EAAEwuD,GAAYhB,EAAMa,GAAkB7K,KAEnCgK,IADLa,GAC8B,MAGlCG,UAGK,CACLxuD,EAAGsuD,EACH19C,EAAG29C,gBCMLtrD,SADIqY,IAEJA,IAFI8R,IAGJA,0BACAnP,wCACAxI,kCACAe,mBACEi4C,UA4CSnyD,QAAQ,CACnBP,IAAAA,IACAP,IAAAA,IACAuvB,OAAAA,OACAprB,KAAAA,UACA6qB,cACAkkC,OACAzyD,QAAAA,QACA8tD,eAAAA,eACAz2C,kBAAAA,kBACAtU,IAAAA,IACAa,SAAAA,UAaW8uD,QAAU,gBACrBC,iBACAhE,SAAAA,oBACApvC,aACAsvC,SAAAA,SACAI,KAAAA,KACAE,MAAAA,MACAI,QAAAA,QACAC,cAAAA,cACAmC,cAAAA,cACAQ,QAAAA"} \ No newline at end of file +{"version":3,"file":"ml.min.js","sources":["../node_modules/ml-array-rescale/node_modules/is-any-array/src/index.js","../node_modules/ml-array-rescale/node_modules/ml-array-max/lib-es6/index.js","../node_modules/ml-array-rescale/node_modules/ml-array-min/lib-es6/index.js","../node_modules/ml-array-rescale/lib-es6/index.js","../node_modules/ml-matrix/src/inspect.js","../node_modules/ml-matrix/src/mathOperations.js","../node_modules/ml-matrix/src/util.js","../node_modules/ml-matrix/src/stat.js","../node_modules/ml-matrix/src/matrix.js","../node_modules/ml-matrix/src/views/base.js","../node_modules/ml-matrix/src/views/column.js","../node_modules/ml-matrix/src/views/columnSelection.js","../node_modules/ml-matrix/src/views/flipColumn.js","../node_modules/ml-matrix/src/views/flipRow.js","../node_modules/ml-matrix/src/views/row.js","../node_modules/ml-matrix/src/views/rowSelection.js","../node_modules/ml-matrix/src/views/selection.js","../node_modules/ml-matrix/src/views/sub.js","../node_modules/ml-matrix/src/views/transpose.js","../node_modules/ml-matrix/src/wrap/WrapperMatrix1D.js","../node_modules/ml-matrix/src/wrap/WrapperMatrix2D.js","../node_modules/ml-matrix/src/wrap/wrap.js","../node_modules/ml-matrix/src/dc/lu.js","../node_modules/ml-matrix/src/dc/util.js","../node_modules/ml-matrix/src/dc/qr.js","../node_modules/ml-matrix/src/dc/svd.js","../node_modules/ml-matrix/src/decompositions.js","../node_modules/ml-matrix/src/determinant.js","../node_modules/ml-matrix/src/linearDependencies.js","../node_modules/ml-matrix/src/pseudoInverse.js","../node_modules/ml-matrix/src/covariance.js","../node_modules/ml-matrix/src/correlation.js","../node_modules/ml-matrix/src/dc/evd.js","../node_modules/ml-matrix/src/dc/cholesky.js","../node_modules/ml-matrix/src/dc/nipals.js","../node_modules/ml-array-sum/node_modules/is-any-array/src/index.js","../node_modules/ml-array-sum/lib-es6/index.js","../node_modules/ml-array-mean/lib-es6/index.js","../node_modules/ml-cart/src/utils.js","../node_modules/ml-cart/src/TreeNode.js","../node_modules/ml-cart/src/DecisionTreeClassifier.js","../node_modules/ml-cart/src/DecisionTreeRegression.js","../node_modules/random-js/dist/random-js.esm.js","../node_modules/ml-random-forest/src/utils.js","../node_modules/ml-random-forest/src/RandomForestBase.js","../node_modules/ml-random-forest/src/RandomForestClassifier.js","../node_modules/ml-array-median/node_modules/is-any-array/src/index.js","../node_modules/median-quickselect/lib/median-quickselect.min.js","../node_modules/ml-array-median/lib-es6/index.js","../node_modules/ml-random-forest/src/RandomForestRegression.js","../node_modules/ml-pca/src/pca.js","../node_modules/ml-distance-euclidean/lib-es6/euclidean.js","../node_modules/ml-distance-matrix/src/index.js","../node_modules/heap/lib/heap.js","../node_modules/heap/index.js","../node_modules/ml-hclust/src/Cluster.js","../node_modules/ml-hclust/src/agnes.js","../node_modules/ml-nearest-vector/lib-es6/index.js","../node_modules/ml-kmeans/src/utils.js","../node_modules/ml-xsadd/lib-es6/xsadd.js","../node_modules/ml-random/lib-es6/choice.js","../node_modules/ml-random/lib-es6/index.js","../node_modules/ml-kmeans/src/initialization.js","../node_modules/ml-kmeans/src/KMeansResult.js","../node_modules/ml-kmeans/src/kmeans.js","../node_modules/ml-naivebayes/src/utils.js","../node_modules/ml-naivebayes/src/GaussianNB.js","../node_modules/ml-naivebayes/src/MultinomialNB.js","../node_modules/ml-knn/src/KDTree.js","../node_modules/ml-knn/src/index.js","../node_modules/ml-pls/src/util/utils.js","../node_modules/ml-pls/src/PLS.js","../node_modules/ml-pls/src/KOPLS.js","../node_modules/ml-confusion-matrix/src/index.js","../node_modules/ml-combinations/lib/index.js","../node_modules/ml-cross-validation/src/getFolds.js","../node_modules/ml-cross-validation/src/sampleAClass.js","../node_modules/ml-cross-validation/src/index.js","../node_modules/ml-pls/src/OPLSNipals.js","../node_modules/ml-pls/src/util/tss.js","../node_modules/ml-pls/src/OPLS.js","../node_modules/ml-fnn/FeedForwardNeuralNetwork.js","../node_modules/ml-som/src/node-square.js","../node_modules/ml-som/src/node-hexagonal.js","../node_modules/ml-som/src/index.js","../node_modules/ml-regression-base/src/maybeToPrecision.js","../node_modules/ml-regression-base/src/checkArrayLength.js","../node_modules/ml-regression-base/src/index.js","../node_modules/ml-regression-polynomial/src/index.js","../node_modules/ml-regression-simple-linear/src/index.js","../node_modules/ml-regression-exponential/src/index.js","../node_modules/ml-regression-power/src/index.js","../node_modules/ml-regression-multivariate-linear/src/index.js","../node_modules/ml-kernel-gaussian/gaussian-kernel.js","../node_modules/ml-kernel-polynomial/polynomial-kernel.js","../node_modules/ml-kernel-sigmoid/sigmoid-kernel.js","../node_modules/ml-kernel/src/kernels/anova-kernel.js","../node_modules/ml-kernel/src/kernels/cauchy-kernel.js","../node_modules/ml-kernel/src/kernels/exponential-kernel.js","../node_modules/ml-kernel/src/kernels/histogram-intersection-kernel.js","../node_modules/ml-kernel/src/kernels/laplacian-kernel.js","../node_modules/ml-kernel/src/kernels/multiquadratic-kernel.js","../node_modules/ml-kernel/src/kernels/rational-quadratic-kernel.js","../node_modules/ml-kernel/src/kernel.js","../node_modules/ml-regression-theil-sen/src/index.js","../node_modules/ml-regression-robust-polynomial/src/index.js","../node_modules/ml-levenberg-marquardt/node_modules/is-any-array/src/index.js","../node_modules/ml-levenberg-marquardt/src/errorCalculation.js","../node_modules/ml-levenberg-marquardt/src/step.js","../node_modules/ml-levenberg-marquardt/src/index.js","../node_modules/ml-fcnnls/src/util/selection.js","../node_modules/ml-fcnnls/src/util/sortCollectionSet.js","../node_modules/ml-fcnnls/src/cssls.js","../node_modules/ml-fcnnls/src/initialisation.js","../node_modules/ml-fcnnls/src/util/setDifference.js","../node_modules/ml-fcnnls/src/optimality.js","../node_modules/ml-fcnnls/src/fcnnls.js","../node_modules/ml-fcnnls/src/fcnnlsVector.js","../node_modules/binary-search/index.js","../node_modules/num-sort/index.js","../node_modules/ml-hash-table/src/primeFinder.js","../node_modules/ml-hash-table/src/HashTable.js","../node_modules/ml-sparse-matrix/src/index.js","../node_modules/ml-distance/src/distances/additiveSymmetric.js","../node_modules/ml-distance/src/distances/avg.js","../node_modules/ml-distance/src/distances/bhattacharyya.js","../node_modules/ml-distance/src/distances/canberra.js","../node_modules/ml-distance/src/distances/chebyshev.js","../node_modules/ml-distance/src/distances/clark.js","../node_modules/ml-distance/src/similarities/czekanowski.js","../node_modules/ml-distance/src/distances/czekanowski.js","../node_modules/ml-distance/src/distances/dice.js","../node_modules/ml-distance/src/distances/divergence.js","../node_modules/ml-distance/src/distances/fidelity.js","../node_modules/ml-distance/src/distances/gower.js","../node_modules/ml-distance/src/distances/harmonicMean.js","../node_modules/ml-distance/src/distances/hellinger.js","../node_modules/ml-distance/src/distances/innerProduct.js","../node_modules/ml-distance/src/distances/intersection.js","../node_modules/ml-distance/src/distances/jaccard.js","../node_modules/ml-distance/src/distances/jeffreys.js","../node_modules/ml-distance/src/distances/jensenDifference.js","../node_modules/ml-distance/src/distances/jensenShannon.js","../node_modules/ml-distance/src/distances/kdivergence.js","../node_modules/ml-distance/src/distances/kulczynski.js","../node_modules/ml-distance/src/distances/kullbackLeibler.js","../node_modules/ml-distance/src/distances/kumarHassebrook.js","../node_modules/ml-distance/src/distances/kumarJohnson.js","../node_modules/ml-distance/src/distances/lorentzian.js","../node_modules/ml-distance/src/distances/manhattan.js","../node_modules/ml-distance/src/distances/matusita.js","../node_modules/ml-distance/src/distances/minkowski.js","../node_modules/ml-distance/src/distances/motyka.js","../node_modules/ml-distance/src/distances/neyman.js","../node_modules/ml-distance/src/distances/pearson.js","../node_modules/ml-distance/src/distances/probabilisticSymmetric.js","../node_modules/ml-distance/src/distances/ruzicka.js","../node_modules/ml-distance/src/distances/soergel.js","../node_modules/ml-distance/src/distances/sorensen.js","../node_modules/ml-distance/src/distances/squared.js","../node_modules/ml-distance/src/distances/squaredChord.js","../node_modules/ml-distance/src/distances/taneja.js","../node_modules/ml-distance/src/similarities/tanimoto.js","../node_modules/ml-distance/src/distances/tanimoto.js","../node_modules/ml-distance/src/distances/topsoe.js","../node_modules/ml-distance/src/distances/waveHedges.js","../node_modules/ml-tree-similarity/src/createTree.js","../node_modules/ml-tree-similarity/src/getSimilarity.js","../node_modules/ml-tree-similarity/src/index.js","../node_modules/ml-distance/src/similarities/cosine.js","../node_modules/ml-distance/src/similarities/dice.js","../node_modules/ml-distance/src/similarities/intersection.js","../node_modules/ml-distance/src/similarities/jaccard.js","../node_modules/ml-distance/src/similarities/kulczynski.js","../node_modules/ml-distance/src/similarities/motyka.js","../node_modules/ml-distance/src/similarities/pearson.js","../node_modules/ml-distance/src/similarities/squaredChord.js","../node_modules/ml-performance/src/measures.js","../node_modules/ml-performance/src/index.js","../node_modules/ml-pad-array/src/index.js","../node_modules/ml-savitzky-golay/src/index.js","../node_modules/ml-bit-array/src/creator.js","../node_modules/ml-bit-array/src/index.js","../node_modules/ml-gsd/node_modules/ml-savitzky-golay-generalized/src/index.js","../node_modules/ml-gsd/src/gsd.js","../node_modules/ml-optimize-lorentzian/src/sumOfGaussians.js","../node_modules/ml-optimize-lorentzian/src/optimizeGaussianSum.js","../node_modules/ml-optimize-lorentzian/src/singleGaussian.js","../node_modules/ml-optimize-lorentzian/src/optimizeSingleGaussian.js","../node_modules/ml-optimize-lorentzian/src/sumOfLorentzians.js","../node_modules/ml-optimize-lorentzian/src/optimizeLorentzianSum.js","../node_modules/ml-optimize-lorentzian/src/singleLorentzian.js","../node_modules/ml-optimize-lorentzian/src/optimizeSingleLorentzian.js","../node_modules/ml-gsd/src/post/optimizePeaks.js","../node_modules/ml-gsd/src/post/joinBroadPeaks.js","../node_modules/ml-gsd/src/post/broadenPeaks.js","../node_modules/is-any-array/src/index.js","../node_modules/ml-array-min/lib-es6/index.js","../node_modules/ml-array-max/lib-es6/index.js","../node_modules/ml-array-mode/lib-es6/index.js","../node_modules/ml-array-normed/node_modules/is-any-array/src/index.js","../node_modules/ml-array-normed/node_modules/ml-array-max/lib-es6/index.js","../node_modules/ml-array-normed/lib-es6/index.js","../node_modules/ml-array-sequential-fill/lib-es6/index.js","../node_modules/ml-array-variance/node_modules/is-any-array/src/index.js","../node_modules/ml-array-variance/lib-es6/index.js","../node_modules/ml-array-standard-deviation/lib-es6/index.js","../node_modules/ml-array-xy-centroids-merge/src/index.js","../node_modules/ml-arrayxy-closestx/src/index.js","../node_modules/ml-array-xy-covariance/src/index.js","../node_modules/ml-array-xy-max-merge/src/index.js","../node_modules/ml-array-xy-max-y/src/index.js","../node_modules/ml-array-xy-sort-x/src/index.js","../node_modules/ml-arrayxy-uniquex/src/index.js","../node_modules/ml-array-xy-weighted-merge/src/index.js","../node_modules/ml-zones/src/normalize.js","../node_modules/ml-zones/src/invert.js","../node_modules/ml-zones/src/zonesWithPoints.js","../node_modules/ml-array-xy-equally-spaced/src/integral.js","../node_modules/ml-array-xy-equally-spaced/src/equallySpacedSmooth.js","../node_modules/ml-array-xy-equally-spaced/src/equallySpacedSlot.js","../node_modules/ml-array-xy-equally-spaced/src/index.js","../node_modules/ml-array-xy-filter-x/src/getZones.js","../node_modules/ml-array-xy-filter-x/src/index.js","../src/index.js"],"sourcesContent":["const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n","import isArray from 'is-any-array';\n\nfunction max(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 }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var _options$fromIndex = options.fromIndex,\n fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,\n _options$toIndex = options.toIndex,\n toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;\n\n if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {\n throw new Error('fromIndex must be a positive integer smaller than length');\n }\n\n if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {\n throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');\n }\n\n var maxValue = input[fromIndex];\n\n for (var i = fromIndex + 1; i < toIndex; i++) {\n if (input[i] > maxValue) maxValue = input[i];\n }\n\n return maxValue;\n}\n\nexport default max;\n","import isArray from 'is-any-array';\n\nfunction min(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 }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var _options$fromIndex = options.fromIndex,\n fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,\n _options$toIndex = options.toIndex,\n toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;\n\n if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {\n throw new Error('fromIndex must be a positive integer smaller than length');\n }\n\n if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {\n throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');\n }\n\n var minValue = input[fromIndex];\n\n for (var i = fromIndex + 1; i < toIndex; i++) {\n if (input[i] < minValue) minValue = input[i];\n }\n\n return minValue;\n}\n\nexport default min;\n","import isArray from 'is-any-array';\nimport max from 'ml-array-max';\nimport min from 'ml-array-min';\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","const indent = ' '.repeat(2);\nconst indentData = ' '.repeat(4);\n\nexport function inspectMatrix() {\n return inspectMatrixWithOptions(this);\n}\n\nexport function inspectMatrixWithOptions(matrix, options = {}) {\n const { maxRows = 15, maxColumns = 10, maxNumSize = 8 } = options;\n return `${matrix.constructor.name} {\n${indent}[\n${indentData}${inspectData(matrix, maxRows, maxColumns, maxNumSize)}\n${indent}]\n${indent}rows: ${matrix.rows}\n${indent}columns: ${matrix.columns}\n}`;\n}\n\nfunction inspectData(matrix, maxRows, maxColumns, maxNumSize) {\n const { rows, columns } = matrix;\n const maxI = Math.min(rows, maxRows);\n const maxJ = Math.min(columns, maxColumns);\n const result = [];\n for (let i = 0; i < maxI; i++) {\n let line = [];\n for (let j = 0; j < maxJ; j++) {\n line.push(formatNumber(matrix.get(i, j), maxNumSize));\n }\n result.push(`${line.join(' ')}`);\n }\n if (maxJ !== columns) {\n result[result.length - 1] += ` ... ${columns - maxColumns} more columns`;\n }\n if (maxI !== rows) {\n result.push(`... ${rows - maxRows} more rows`);\n }\n return result.join(`\\n${indentData}`);\n}\n\nfunction formatNumber(num, maxNumSize) {\n const numStr = String(num);\n if (numStr.length <= maxNumSize) {\n return numStr.padEnd(maxNumSize, ' ');\n }\n const precise = num.toPrecision(maxNumSize - 2);\n if (precise.length <= maxNumSize) {\n return precise;\n }\n const exponential = num.toExponential(maxNumSize - 2);\n const eIndex = exponential.indexOf('e');\n const e = exponential.slice(eIndex);\n return exponential.slice(0, maxNumSize - e.length) + e;\n}\n","export function installMathOperations(AbstractMatrix, Matrix) {\r\n AbstractMatrix.prototype.add = function add(value) {\r\n if (typeof value === 'number') return this.addS(value);\r\n return this.addM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.addS = function addS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) + value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.addM = function addM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) + matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.add = function add(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.add(value);\r\n };\r\n\r\n AbstractMatrix.prototype.sub = function sub(value) {\r\n if (typeof value === 'number') return this.subS(value);\r\n return this.subM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.subS = function subS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) - value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.subM = function subM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) - matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.sub = function sub(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.sub(value);\r\n };\r\n AbstractMatrix.prototype.subtract = AbstractMatrix.prototype.sub;\r\n AbstractMatrix.prototype.subtractS = AbstractMatrix.prototype.subS;\r\n AbstractMatrix.prototype.subtractM = AbstractMatrix.prototype.subM;\r\n AbstractMatrix.subtract = AbstractMatrix.sub;\r\n\r\n AbstractMatrix.prototype.mul = function mul(value) {\r\n if (typeof value === 'number') return this.mulS(value);\r\n return this.mulM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.mulS = function mulS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) * value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.mulM = function mulM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) * matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.mul = function mul(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.mul(value);\r\n };\r\n AbstractMatrix.prototype.multiply = AbstractMatrix.prototype.mul;\r\n AbstractMatrix.prototype.multiplyS = AbstractMatrix.prototype.mulS;\r\n AbstractMatrix.prototype.multiplyM = AbstractMatrix.prototype.mulM;\r\n AbstractMatrix.multiply = AbstractMatrix.mul;\r\n\r\n AbstractMatrix.prototype.div = function div(value) {\r\n if (typeof value === 'number') return this.divS(value);\r\n return this.divM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.divS = function divS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) / value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.divM = function divM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) / matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.div = function div(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.div(value);\r\n };\r\n AbstractMatrix.prototype.divide = AbstractMatrix.prototype.div;\r\n AbstractMatrix.prototype.divideS = AbstractMatrix.prototype.divS;\r\n AbstractMatrix.prototype.divideM = AbstractMatrix.prototype.divM;\r\n AbstractMatrix.divide = AbstractMatrix.div;\r\n\r\n AbstractMatrix.prototype.mod = function mod(value) {\r\n if (typeof value === 'number') return this.modS(value);\r\n return this.modM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.modS = function modS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) % value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.modM = function modM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) % matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.mod = function mod(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.mod(value);\r\n };\r\n AbstractMatrix.prototype.modulus = AbstractMatrix.prototype.mod;\r\n AbstractMatrix.prototype.modulusS = AbstractMatrix.prototype.modS;\r\n AbstractMatrix.prototype.modulusM = AbstractMatrix.prototype.modM;\r\n AbstractMatrix.modulus = AbstractMatrix.mod;\r\n\r\n AbstractMatrix.prototype.and = function and(value) {\r\n if (typeof value === 'number') return this.andS(value);\r\n return this.andM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.andS = function andS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) & value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.andM = function andM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) & matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.and = function and(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.and(value);\r\n };\r\n\r\n AbstractMatrix.prototype.or = function or(value) {\r\n if (typeof value === 'number') return this.orS(value);\r\n return this.orM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.orS = function orS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) | value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.orM = function orM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) | matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.or = function or(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.or(value);\r\n };\r\n\r\n AbstractMatrix.prototype.xor = function xor(value) {\r\n if (typeof value === 'number') return this.xorS(value);\r\n return this.xorM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.xorS = function xorS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) ^ value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.xorM = function xorM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) ^ matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.xor = function xor(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.xor(value);\r\n };\r\n\r\n AbstractMatrix.prototype.leftShift = function leftShift(value) {\r\n if (typeof value === 'number') return this.leftShiftS(value);\r\n return this.leftShiftM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.leftShiftS = function leftShiftS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) << value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.leftShiftM = function leftShiftM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) << matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.leftShift = function leftShift(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.leftShift(value);\r\n };\r\n\r\n AbstractMatrix.prototype.signPropagatingRightShift = function signPropagatingRightShift(value) {\r\n if (typeof value === 'number') return this.signPropagatingRightShiftS(value);\r\n return this.signPropagatingRightShiftM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.signPropagatingRightShiftS = function signPropagatingRightShiftS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) >> value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.signPropagatingRightShiftM = function signPropagatingRightShiftM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) >> matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.signPropagatingRightShift = function signPropagatingRightShift(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.signPropagatingRightShift(value);\r\n };\r\n\r\n AbstractMatrix.prototype.rightShift = function rightShift(value) {\r\n if (typeof value === 'number') return this.rightShiftS(value);\r\n return this.rightShiftM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.rightShiftS = function rightShiftS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) >>> value);\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.rightShiftM = function rightShiftM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, this.get(i, j) >>> matrix.get(i, j));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.rightShift = function rightShift(matrix, value) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.rightShift(value);\r\n };\r\n AbstractMatrix.prototype.zeroFillRightShift = AbstractMatrix.prototype.rightShift;\r\n AbstractMatrix.prototype.zeroFillRightShiftS = AbstractMatrix.prototype.rightShiftS;\r\n AbstractMatrix.prototype.zeroFillRightShiftM = AbstractMatrix.prototype.rightShiftM;\r\n AbstractMatrix.zeroFillRightShift = AbstractMatrix.rightShift;\r\n\r\n AbstractMatrix.prototype.not = function not() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, ~(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.not = function not(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.not();\r\n };\r\n\r\n AbstractMatrix.prototype.abs = function abs() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.abs(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.abs = function abs(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.abs();\r\n };\r\n\r\n AbstractMatrix.prototype.acos = function acos() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.acos(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.acos = function acos(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.acos();\r\n };\r\n\r\n AbstractMatrix.prototype.acosh = function acosh() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.acosh(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.acosh = function acosh(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.acosh();\r\n };\r\n\r\n AbstractMatrix.prototype.asin = function asin() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.asin(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.asin = function asin(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.asin();\r\n };\r\n\r\n AbstractMatrix.prototype.asinh = function asinh() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.asinh(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.asinh = function asinh(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.asinh();\r\n };\r\n\r\n AbstractMatrix.prototype.atan = function atan() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.atan(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.atan = function atan(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.atan();\r\n };\r\n\r\n AbstractMatrix.prototype.atanh = function atanh() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.atanh(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.atanh = function atanh(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.atanh();\r\n };\r\n\r\n AbstractMatrix.prototype.cbrt = function cbrt() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.cbrt(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.cbrt = function cbrt(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.cbrt();\r\n };\r\n\r\n AbstractMatrix.prototype.ceil = function ceil() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.ceil(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.ceil = function ceil(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.ceil();\r\n };\r\n\r\n AbstractMatrix.prototype.clz32 = function clz32() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.clz32(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.clz32 = function clz32(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.clz32();\r\n };\r\n\r\n AbstractMatrix.prototype.cos = function cos() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.cos(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.cos = function cos(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.cos();\r\n };\r\n\r\n AbstractMatrix.prototype.cosh = function cosh() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.cosh(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.cosh = function cosh(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.cosh();\r\n };\r\n\r\n AbstractMatrix.prototype.exp = function exp() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.exp(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.exp = function exp(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.exp();\r\n };\r\n\r\n AbstractMatrix.prototype.expm1 = function expm1() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.expm1(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.expm1 = function expm1(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.expm1();\r\n };\r\n\r\n AbstractMatrix.prototype.floor = function floor() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.floor(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.floor = function floor(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.floor();\r\n };\r\n\r\n AbstractMatrix.prototype.fround = function fround() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.fround(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.fround = function fround(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.fround();\r\n };\r\n\r\n AbstractMatrix.prototype.log = function log() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.log(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.log = function log(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.log();\r\n };\r\n\r\n AbstractMatrix.prototype.log1p = function log1p() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.log1p(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.log1p = function log1p(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.log1p();\r\n };\r\n\r\n AbstractMatrix.prototype.log10 = function log10() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.log10(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.log10 = function log10(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.log10();\r\n };\r\n\r\n AbstractMatrix.prototype.log2 = function log2() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.log2(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.log2 = function log2(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.log2();\r\n };\r\n\r\n AbstractMatrix.prototype.round = function round() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.round(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.round = function round(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.round();\r\n };\r\n\r\n AbstractMatrix.prototype.sign = function sign() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.sign(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.sign = function sign(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.sign();\r\n };\r\n\r\n AbstractMatrix.prototype.sin = function sin() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.sin(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.sin = function sin(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.sin();\r\n };\r\n\r\n AbstractMatrix.prototype.sinh = function sinh() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.sinh(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.sinh = function sinh(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.sinh();\r\n };\r\n\r\n AbstractMatrix.prototype.sqrt = function sqrt() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.sqrt(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.sqrt = function sqrt(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.sqrt();\r\n };\r\n\r\n AbstractMatrix.prototype.tan = function tan() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.tan(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.tan = function tan(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.tan();\r\n };\r\n\r\n AbstractMatrix.prototype.tanh = function tanh() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.tanh(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.tanh = function tanh(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.tanh();\r\n };\r\n\r\n AbstractMatrix.prototype.trunc = function trunc() {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.trunc(this.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.trunc = function trunc(matrix) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.trunc();\r\n };\r\n\r\n AbstractMatrix.pow = function pow(matrix, arg0) {\r\n const newMatrix = new Matrix(matrix);\r\n return newMatrix.pow(arg0);\r\n };\r\n\r\n AbstractMatrix.prototype.pow = function pow(value) {\r\n if (typeof value === 'number') return this.powS(value);\r\n return this.powM(value);\r\n };\r\n\r\n AbstractMatrix.prototype.powS = function powS(value) {\r\n for (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.pow(this.get(i, j), value));\r\n }\r\n }\r\n return this;\r\n };\r\n\r\n AbstractMatrix.prototype.powM = function powM(matrix) {\r\n matrix = Matrix.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 (let i = 0; i < this.rows; i++) {\r\n for (let j = 0; j < this.columns; j++) {\r\n this.set(i, j, Math.pow(this.get(i, j), matrix.get(i, j)));\r\n }\r\n }\r\n return this;\r\n };\r\n}\r\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 let 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 let 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 let 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 let 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 newArray(length, value = 0) {\n let array = [];\n for (let i = 0; i < length; i++) {\n array.push(value);\n }\n return array;\n}\n\nfunction checkNumber(name, value) {\n if (typeof value !== 'number') {\n throw new TypeError(`${name} must be a number`);\n }\n}\n","import { newArray } from './util';\n\nexport function sumByRow(matrix) {\n let sum = newArray(matrix.rows);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[i] += matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function sumByColumn(matrix) {\n let sum = newArray(matrix.columns);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[j] += matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function sumAll(matrix) {\n let v = 0;\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n v += matrix.get(i, j);\n }\n }\n return v;\n}\n\nexport function productByRow(matrix) {\n let sum = newArray(matrix.rows, 1);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[i] *= matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function productByColumn(matrix) {\n let sum = newArray(matrix.columns, 1);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[j] *= matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function productAll(matrix) {\n let v = 1;\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n v *= matrix.get(i, j);\n }\n }\n return v;\n}\n\nexport function varianceByRow(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const variance = [];\n\n for (let i = 0; i < rows; i++) {\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let j = 0; j < cols; j++) {\n x = matrix.get(i, j) - mean[i];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n variance.push((sum2 - (sum1 * sum1) / cols) / (cols - 1));\n } else {\n variance.push((sum2 - (sum1 * sum1) / cols) / cols);\n }\n }\n return variance;\n}\n\nexport function varianceByColumn(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const variance = [];\n\n for (let j = 0; j < cols; j++) {\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let i = 0; i < rows; i++) {\n x = matrix.get(i, j) - mean[j];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n variance.push((sum2 - (sum1 * sum1) / rows) / (rows - 1));\n } else {\n variance.push((sum2 - (sum1 * sum1) / rows) / rows);\n }\n }\n return variance;\n}\n\nexport function varianceAll(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const size = rows * cols;\n\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n x = matrix.get(i, j) - mean;\n sum1 += x;\n sum2 += x * x;\n }\n }\n if (unbiased) {\n return (sum2 - (sum1 * sum1) / size) / (size - 1);\n } else {\n return (sum2 - (sum1 * sum1) / size) / size;\n }\n}\n\nexport function centerByRow(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean[i]);\n }\n }\n}\n\nexport function centerByColumn(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean[j]);\n }\n }\n}\n\nexport function centerAll(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean);\n }\n }\n}\n\nexport function getScaleByRow(matrix) {\n const scale = [];\n for (let i = 0; i < matrix.rows; i++) {\n let sum = 0;\n for (let j = 0; j < matrix.columns; j++) {\n sum += Math.pow(matrix.get(i, j), 2) / (matrix.columns - 1);\n }\n scale.push(Math.sqrt(sum));\n }\n return scale;\n}\n\nexport function scaleByRow(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale[i]);\n }\n }\n}\n\nexport function getScaleByColumn(matrix) {\n const scale = [];\n for (let j = 0; j < matrix.columns; j++) {\n let sum = 0;\n for (let i = 0; i < matrix.rows; i++) {\n sum += Math.pow(matrix.get(i, j), 2) / (matrix.rows - 1);\n }\n scale.push(Math.sqrt(sum));\n }\n return scale;\n}\n\nexport function scaleByColumn(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale[j]);\n }\n }\n}\n\nexport function getScaleAll(matrix) {\n const divider = matrix.size - 1;\n let sum = 0;\n for (let j = 0; j < matrix.columns; j++) {\n for (let i = 0; i < matrix.rows; i++) {\n sum += Math.pow(matrix.get(i, j), 2) / divider;\n }\n }\n return Math.sqrt(sum);\n}\n\nexport function scaleAll(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale);\n }\n }\n}\n","import rescale from 'ml-array-rescale';\n\nimport { inspectMatrix, inspectMatrixWithOptions } from './inspect';\nimport { installMathOperations } from './mathOperations';\nimport {\n sumByRow,\n sumByColumn,\n sumAll,\n productByRow,\n productByColumn,\n productAll,\n varianceByRow,\n varianceByColumn,\n varianceAll,\n centerByRow,\n centerByColumn,\n centerAll,\n scaleByRow,\n scaleByColumn,\n scaleAll,\n getScaleByRow,\n getScaleByColumn,\n getScaleAll,\n} from './stat';\nimport {\n checkRowVector,\n checkRowIndex,\n checkColumnIndex,\n checkColumnVector,\n checkRange,\n checkIndices,\n} from './util';\n\nexport class AbstractMatrix {\n static from1DArray(newRows, newColumns, newData) {\n let length = newRows * newColumns;\n if (length !== newData.length) {\n throw new RangeError('data length does not match given dimensions');\n }\n let newMatrix = new Matrix(newRows, newColumns);\n for (let row = 0; row < newRows; row++) {\n for (let column = 0; column < newColumns; column++) {\n newMatrix.set(row, column, newData[row * newColumns + column]);\n }\n }\n return newMatrix;\n }\n\n static rowVector(newData) {\n let vector = new Matrix(1, newData.length);\n for (let i = 0; i < newData.length; i++) {\n vector.set(0, i, newData[i]);\n }\n return vector;\n }\n\n static columnVector(newData) {\n let vector = new Matrix(newData.length, 1);\n for (let i = 0; i < newData.length; i++) {\n vector.set(i, 0, newData[i]);\n }\n return vector;\n }\n\n static zeros(rows, columns) {\n return new Matrix(rows, columns);\n }\n\n static ones(rows, columns) {\n return new Matrix(rows, columns).fill(1);\n }\n\n static rand(rows, columns, options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { random = Math.random } = options;\n let matrix = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n matrix.set(i, j, random());\n }\n }\n return matrix;\n }\n\n static randInt(rows, columns, options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1000, random = Math.random } = options;\n if (!Number.isInteger(min)) throw new TypeError('min must be an integer');\n if (!Number.isInteger(max)) throw new TypeError('max must be an integer');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let interval = max - min;\n let matrix = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n let value = min + Math.round(random() * interval);\n matrix.set(i, j, value);\n }\n }\n return matrix;\n }\n\n static eye(rows, columns, value) {\n if (columns === undefined) columns = rows;\n if (value === undefined) value = 1;\n let min = Math.min(rows, columns);\n let matrix = this.zeros(rows, columns);\n for (let i = 0; i < min; i++) {\n matrix.set(i, i, value);\n }\n return matrix;\n }\n\n static diag(data, rows, columns) {\n let l = data.length;\n if (rows === undefined) rows = l;\n if (columns === undefined) columns = rows;\n let min = Math.min(l, rows, columns);\n let matrix = this.zeros(rows, columns);\n for (let i = 0; i < min; i++) {\n matrix.set(i, i, data[i]);\n }\n return matrix;\n }\n\n static min(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n let rows = matrix1.rows;\n let columns = matrix1.columns;\n let result = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let 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 static max(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n let rows = matrix1.rows;\n let columns = matrix1.columns;\n let result = new this(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let 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 static checkMatrix(value) {\n return AbstractMatrix.isMatrix(value) ? value : new Matrix(value);\n }\n\n static isMatrix(value) {\n return value != null && value.klass === 'Matrix';\n }\n\n get size() {\n return this.rows * this.columns;\n }\n\n apply(callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('callback must be a function');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n callback.call(this, i, j);\n }\n }\n return this;\n }\n\n to1DArray() {\n let array = [];\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n array.push(this.get(i, j));\n }\n }\n return array;\n }\n\n to2DArray() {\n let copy = [];\n for (let i = 0; i < this.rows; i++) {\n copy.push([]);\n for (let j = 0; j < this.columns; j++) {\n copy[i].push(this.get(i, j));\n }\n }\n return copy;\n }\n\n toJSON() {\n return this.to2DArray();\n }\n\n isRowVector() {\n return this.rows === 1;\n }\n\n isColumnVector() {\n return this.columns === 1;\n }\n\n isVector() {\n return this.rows === 1 || this.columns === 1;\n }\n\n isSquare() {\n return this.rows === this.columns;\n }\n\n isSymmetric() {\n if (this.isSquare()) {\n for (let i = 0; i < this.rows; i++) {\n for (let 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 isEchelonForm() {\n let i = 0;\n let j = 0;\n let previousColumn = -1;\n let isEchelonForm = true;\n let checked = false;\n while (i < this.rows && isEchelonForm) {\n j = 0;\n checked = false;\n while (j < this.columns && checked === false) {\n if (this.get(i, j) === 0) {\n j++;\n } else if (this.get(i, j) === 1 && j > previousColumn) {\n checked = true;\n previousColumn = j;\n } else {\n isEchelonForm = false;\n checked = true;\n }\n }\n i++;\n }\n return isEchelonForm;\n }\n\n isReducedEchelonForm() {\n let i = 0;\n let j = 0;\n let previousColumn = -1;\n let isReducedEchelonForm = true;\n let checked = false;\n while (i < this.rows && isReducedEchelonForm) {\n j = 0;\n checked = false;\n while (j < this.columns && checked === false) {\n if (this.get(i, j) === 0) {\n j++;\n } else if (this.get(i, j) === 1 && j > previousColumn) {\n checked = true;\n previousColumn = j;\n } else {\n isReducedEchelonForm = false;\n checked = true;\n }\n }\n for (let k = j + 1; k < this.rows; k++) {\n if (this.get(i, k) !== 0) {\n isReducedEchelonForm = false;\n }\n }\n i++;\n }\n return isReducedEchelonForm;\n }\n\n echelonForm() {\n let result = this.clone();\n let h = 0;\n let k = 0;\n while (h < result.rows && k < result.columns) {\n let iMax = h;\n for (let i = h; i < result.rows; i++) {\n if (result.get(i, k) > result.get(iMax, k)) {\n iMax = i;\n }\n }\n if (result.get(iMax, k) === 0) {\n k++;\n } else {\n result.swapRows(h, iMax);\n let tmp = result.get(h, k);\n for (let j = k; j < result.columns; j++) {\n result.set(h, j, result.get(h, j) / tmp);\n }\n for (let i = h + 1; i < result.rows; i++) {\n let factor = result.get(i, k) / result.get(h, k);\n result.set(i, k, 0);\n for (let j = k + 1; j < result.columns; j++) {\n result.set(i, j, result.get(i, j) - result.get(h, j) * factor);\n }\n }\n h++;\n k++;\n }\n }\n return result;\n }\n\n reducedEchelonForm() {\n let result = this.echelonForm();\n let m = result.columns;\n let n = result.rows;\n let h = n - 1;\n while (h >= 0) {\n if (result.maxRow(h) === 0) {\n h--;\n } else {\n let p = 0;\n let pivot = false;\n while (p < n && pivot === false) {\n if (result.get(h, p) === 1) {\n pivot = true;\n } else {\n p++;\n }\n }\n for (let i = 0; i < h; i++) {\n let factor = result.get(i, p);\n for (let j = p; j < m; j++) {\n let tmp = result.get(i, j) - factor * result.get(h, j);\n result.set(i, j, tmp);\n }\n }\n h--;\n }\n }\n return result;\n }\n\n set() {\n throw new Error('set method is unimplemented');\n }\n\n get() {\n throw new Error('get method is unimplemented');\n }\n\n repeat(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { rows = 1, columns = 1 } = options;\n if (!Number.isInteger(rows) || rows <= 0) {\n throw new TypeError('rows must be a positive integer');\n }\n if (!Number.isInteger(columns) || columns <= 0) {\n throw new TypeError('columns must be a positive integer');\n }\n let matrix = new Matrix(this.rows * rows, this.columns * columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\n }\n }\n return matrix;\n }\n\n fill(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, value);\n }\n }\n return this;\n }\n\n neg() {\n return this.mulS(-1);\n }\n\n getRow(index) {\n checkRowIndex(this, index);\n let row = [];\n for (let i = 0; i < this.columns; i++) {\n row.push(this.get(index, i));\n }\n return row;\n }\n\n getRowVector(index) {\n return Matrix.rowVector(this.getRow(index));\n }\n\n setRow(index, array) {\n checkRowIndex(this, index);\n array = checkRowVector(this, array);\n for (let i = 0; i < this.columns; i++) {\n this.set(index, i, array[i]);\n }\n return this;\n }\n\n swapRows(row1, row2) {\n checkRowIndex(this, row1);\n checkRowIndex(this, row2);\n for (let i = 0; i < this.columns; i++) {\n let 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 getColumn(index) {\n checkColumnIndex(this, index);\n let column = [];\n for (let i = 0; i < this.rows; i++) {\n column.push(this.get(i, index));\n }\n return column;\n }\n\n getColumnVector(index) {\n return Matrix.columnVector(this.getColumn(index));\n }\n\n setColumn(index, array) {\n checkColumnIndex(this, index);\n array = checkColumnVector(this, array);\n for (let i = 0; i < this.rows; i++) {\n this.set(i, index, array[i]);\n }\n return this;\n }\n\n swapColumns(column1, column2) {\n checkColumnIndex(this, column1);\n checkColumnIndex(this, column2);\n for (let i = 0; i < this.rows; i++) {\n let 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 addRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 subRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 mulRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 divRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 addColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 subColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 mulColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 divColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 mulRow(index, value) {\n checkRowIndex(this, index);\n for (let i = 0; i < this.columns; i++) {\n this.set(index, i, this.get(index, i) * value);\n }\n return this;\n }\n\n mulColumn(index, value) {\n checkColumnIndex(this, index);\n for (let i = 0; i < this.rows; i++) {\n this.set(i, index, this.get(i, index) * value);\n }\n return this;\n }\n\n max() {\n let v = this.get(0, 0);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 maxIndex() {\n let v = this.get(0, 0);\n let idx = [0, 0];\n for (let i = 0; i < this.rows; i++) {\n for (let 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 min() {\n let v = this.get(0, 0);\n for (let i = 0; i < this.rows; i++) {\n for (let 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 minIndex() {\n let v = this.get(0, 0);\n let idx = [0, 0];\n for (let i = 0; i < this.rows; i++) {\n for (let 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 maxRow(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n for (let 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 maxRowIndex(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n let idx = [row, 0];\n for (let 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 minRow(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n for (let 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 minRowIndex(row) {\n checkRowIndex(this, row);\n let v = this.get(row, 0);\n let idx = [row, 0];\n for (let 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 maxColumn(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n for (let 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 maxColumnIndex(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n let idx = [0, column];\n for (let 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 minColumn(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n for (let 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 minColumnIndex(column) {\n checkColumnIndex(this, column);\n let v = this.get(0, column);\n let idx = [0, column];\n for (let 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 diag() {\n let min = Math.min(this.rows, this.columns);\n let diag = [];\n for (let i = 0; i < min; i++) {\n diag.push(this.get(i, i));\n }\n return diag;\n }\n\n norm(type = 'frobenius') {\n let result = 0;\n if (type === 'max') {\n return this.max();\n } else if (type === 'frobenius') {\n for (let i = 0; i < this.rows; i++) {\n for (let 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 cumulativeSum() {\n let sum = 0;\n for (let i = 0; i < this.rows; i++) {\n for (let 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 dot(vector2) {\n if (AbstractMatrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\n let vector1 = this.to1DArray();\n if (vector1.length !== vector2.length) {\n throw new RangeError('vectors do not have the same size');\n }\n let dot = 0;\n for (let i = 0; i < vector1.length; i++) {\n dot += vector1[i] * vector2[i];\n }\n return dot;\n }\n\n mmul(other) {\n other = Matrix.checkMatrix(other);\n\n let m = this.rows;\n let n = this.columns;\n let p = other.columns;\n\n let result = new Matrix(m, p);\n\n let Bcolj = new Float64Array(n);\n for (let j = 0; j < p; j++) {\n for (let k = 0; k < n; k++) {\n Bcolj[k] = other.get(k, j);\n }\n\n for (let i = 0; i < m; i++) {\n let s = 0;\n for (let 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 other = Matrix.checkMatrix(other);\n let result = new Matrix(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 other = Matrix.checkMatrix(other);\n let result = new Matrix(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 mmulStrassen(y) {\n y = Matrix.checkMatrix(y);\n let x = this.clone();\n let r1 = x.rows;\n let c1 = x.columns;\n let r2 = y.rows;\n let c2 = y.columns;\n if (c1 !== r2) {\n // eslint-disable-next-line no-console\n console.warn(\n `Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`,\n );\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 let r = mat.rows;\n let c = mat.columns;\n if (r === rows && c === cols) {\n return mat;\n } else {\n let resultat = AbstractMatrix.zeros(rows, cols);\n resultat = resultat.setSubMatrix(mat, 0, 0);\n return resultat;\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 let r = Math.max(r1, r2);\n let 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 let halfRows = parseInt(a.rows / 2, 10);\n let halfCols = parseInt(a.columns / 2, 10);\n // Subdivide input matrices.\n let a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n let b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n\n let a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\n let b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\n\n let a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\n let b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\n\n let a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\n let b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\n\n // Compute intermediate values.\n let m1 = blockMult(\n AbstractMatrix.add(a11, a22),\n AbstractMatrix.add(b11, b22),\n halfRows,\n halfCols,\n );\n let m2 = blockMult(AbstractMatrix.add(a21, a22), b11, halfRows, halfCols);\n let m3 = blockMult(a11, AbstractMatrix.sub(b12, b22), halfRows, halfCols);\n let m4 = blockMult(a22, AbstractMatrix.sub(b21, b11), halfRows, halfCols);\n let m5 = blockMult(AbstractMatrix.add(a11, a12), b22, halfRows, halfCols);\n let m6 = blockMult(\n AbstractMatrix.sub(a21, a11),\n AbstractMatrix.add(b11, b12),\n halfRows,\n halfCols,\n );\n let m7 = blockMult(\n AbstractMatrix.sub(a12, a22),\n AbstractMatrix.add(b21, b22),\n halfRows,\n halfCols,\n );\n\n // Combine intermediate values into the output.\n let c11 = AbstractMatrix.add(m1, m4);\n c11.sub(m5);\n c11.add(m7);\n let c12 = AbstractMatrix.add(m3, m5);\n let c21 = AbstractMatrix.add(m2, m4);\n let c22 = AbstractMatrix.sub(m1, m2);\n c22.add(m3);\n c22.add(m6);\n\n // Crop output to the desired size (undo dynamic padding).\n let resultat = AbstractMatrix.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 scaleRows(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1 } = options;\n if (!Number.isFinite(min)) throw new TypeError('min must be a number');\n if (!Number.isFinite(max)) throw new TypeError('max must be a number');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let i = 0; i < this.rows; i++) {\n const row = this.getRow(i);\n rescale(row, { min, max, output: row });\n newMatrix.setRow(i, row);\n }\n return newMatrix;\n }\n\n scaleColumns(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1 } = options;\n if (!Number.isFinite(min)) throw new TypeError('min must be a number');\n if (!Number.isFinite(max)) throw new TypeError('max must be a number');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let i = 0; i < this.columns; i++) {\n const column = this.getColumn(i);\n rescale(column, {\n min: min,\n max: max,\n output: column,\n });\n newMatrix.setColumn(i, column);\n }\n return newMatrix;\n }\n\n flipRows() {\n const middle = Math.ceil(this.columns / 2);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < middle; j++) {\n let first = this.get(i, j);\n let last = this.get(i, this.columns - 1 - j);\n this.set(i, j, last);\n this.set(i, this.columns - 1 - j, first);\n }\n }\n return this;\n }\n\n flipColumns() {\n const middle = Math.ceil(this.rows / 2);\n for (let j = 0; j < this.columns; j++) {\n for (let i = 0; i < middle; i++) {\n let first = this.get(i, j);\n let last = this.get(this.rows - 1 - i, j);\n this.set(i, j, last);\n this.set(this.rows - 1 - i, j, first);\n }\n }\n return this;\n }\n\n kroneckerProduct(other) {\n other = Matrix.checkMatrix(other);\n\n let m = this.rows;\n let n = this.columns;\n let p = other.rows;\n let q = other.columns;\n\n let result = new Matrix(m * p, n * q);\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n for (let k = 0; k < p; k++) {\n for (let l = 0; l < q; l++) {\n result.set(p * i + k, q * j + l, this.get(i, j) * other.get(k, l));\n }\n }\n }\n }\n return result;\n }\n\n transpose() {\n let result = new Matrix(this.columns, this.rows);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n result.set(j, i, this.get(i, j));\n }\n }\n return result;\n }\n\n sortRows(compareFunction = compareNumbers) {\n for (let i = 0; i < this.rows; i++) {\n this.setRow(i, this.getRow(i).sort(compareFunction));\n }\n return this;\n }\n\n sortColumns(compareFunction = compareNumbers) {\n for (let i = 0; i < this.columns; i++) {\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\n }\n return this;\n }\n\n subMatrix(startRow, endRow, startColumn, endColumn) {\n checkRange(this, startRow, endRow, startColumn, endColumn);\n let newMatrix = new Matrix(\n endRow - startRow + 1,\n endColumn - startColumn + 1,\n );\n for (let i = startRow; i <= endRow; i++) {\n for (let j = startColumn; j <= endColumn; j++) {\n newMatrix.set(i - startRow, j - startColumn, this.get(i, j));\n }\n }\n return newMatrix;\n }\n\n subMatrixRow(indices, startColumn, endColumn) {\n if (startColumn === undefined) startColumn = 0;\n if (endColumn === undefined) endColumn = this.columns - 1;\n if (\n startColumn > endColumn ||\n startColumn < 0 ||\n startColumn >= this.columns ||\n endColumn < 0 ||\n endColumn >= this.columns\n ) {\n throw new RangeError('Argument out of range');\n }\n\n let newMatrix = new Matrix(indices.length, endColumn - startColumn + 1);\n for (let i = 0; i < indices.length; i++) {\n for (let 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 subMatrixColumn(indices, startRow, endRow) {\n if (startRow === undefined) startRow = 0;\n if (endRow === undefined) endRow = this.rows - 1;\n if (\n startRow > endRow ||\n startRow < 0 ||\n startRow >= this.rows ||\n endRow < 0 ||\n endRow >= this.rows\n ) {\n throw new RangeError('Argument out of range');\n }\n\n let newMatrix = new Matrix(endRow - startRow + 1, indices.length);\n for (let i = 0; i < indices.length; i++) {\n for (let 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 setSubMatrix(matrix, startRow, startColumn) {\n matrix = Matrix.checkMatrix(matrix);\n let endRow = startRow + matrix.rows - 1;\n let endColumn = startColumn + matrix.columns - 1;\n checkRange(this, startRow, endRow, startColumn, endColumn);\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n this.set(startRow + i, startColumn + j, matrix.get(i, j));\n }\n }\n return this;\n }\n\n selection(rowIndices, columnIndices) {\n let indices = checkIndices(this, rowIndices, columnIndices);\n let newMatrix = new Matrix(rowIndices.length, columnIndices.length);\n for (let i = 0; i < indices.row.length; i++) {\n let rowIndex = indices.row[i];\n for (let j = 0; j < indices.column.length; j++) {\n let columnIndex = indices.column[j];\n newMatrix.set(i, j, this.get(rowIndex, columnIndex));\n }\n }\n return newMatrix;\n }\n\n trace() {\n let min = Math.min(this.rows, this.columns);\n let trace = 0;\n for (let i = 0; i < min; i++) {\n trace += this.get(i, i);\n }\n return trace;\n }\n\n clone() {\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let row = 0; row < this.rows; row++) {\n for (let column = 0; column < this.columns; column++) {\n newMatrix.set(row, column, this.get(row, column));\n }\n }\n return newMatrix;\n }\n\n sum(by) {\n switch (by) {\n case 'row':\n return sumByRow(this);\n case 'column':\n return sumByColumn(this);\n case undefined:\n return sumAll(this);\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n product(by) {\n switch (by) {\n case 'row':\n return productByRow(this);\n case 'column':\n return productByColumn(this);\n case undefined:\n return productAll(this);\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n mean(by) {\n const sum = this.sum(by);\n switch (by) {\n case 'row': {\n for (let i = 0; i < this.rows; i++) {\n sum[i] /= this.columns;\n }\n return sum;\n }\n case 'column': {\n for (let i = 0; i < this.columns; i++) {\n sum[i] /= this.rows;\n }\n return sum;\n }\n case undefined:\n return sum / this.size;\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n variance(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { unbiased = true, mean = this.mean(by) } = options;\n if (typeof unbiased !== 'boolean') {\n throw new TypeError('unbiased must be a boolean');\n }\n switch (by) {\n case 'row': {\n if (!Array.isArray(mean)) {\n throw new TypeError('mean must be an array');\n }\n return varianceByRow(this, unbiased, mean);\n }\n case 'column': {\n if (!Array.isArray(mean)) {\n throw new TypeError('mean must be an array');\n }\n return varianceByColumn(this, unbiased, mean);\n }\n case undefined: {\n if (typeof mean !== 'number') {\n throw new TypeError('mean must be a number');\n }\n return varianceAll(this, unbiased, mean);\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n standardDeviation(by, options) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n const variance = this.variance(by, options);\n if (by === undefined) {\n return Math.sqrt(variance);\n } else {\n for (let i = 0; i < variance.length; i++) {\n variance[i] = Math.sqrt(variance[i]);\n }\n return variance;\n }\n }\n\n center(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { center = this.mean(by) } = options;\n switch (by) {\n case 'row': {\n if (!Array.isArray(center)) {\n throw new TypeError('center must be an array');\n }\n centerByRow(this, center);\n return this;\n }\n case 'column': {\n if (!Array.isArray(center)) {\n throw new TypeError('center must be an array');\n }\n centerByColumn(this, center);\n return this;\n }\n case undefined: {\n if (typeof center !== 'number') {\n throw new TypeError('center must be a number');\n }\n centerAll(this, center);\n return this;\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n scale(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n let scale = options.scale;\n switch (by) {\n case 'row': {\n if (scale === undefined) {\n scale = getScaleByRow(this);\n } else if (!Array.isArray(scale)) {\n throw new TypeError('scale must be an array');\n }\n scaleByRow(this, scale);\n return this;\n }\n case 'column': {\n if (scale === undefined) {\n scale = getScaleByColumn(this);\n } else if (!Array.isArray(scale)) {\n throw new TypeError('scale must be an array');\n }\n scaleByColumn(this, scale);\n return this;\n }\n case undefined: {\n if (scale === undefined) {\n scale = getScaleAll(this);\n } else if (typeof scale !== 'number') {\n throw new TypeError('scale must be a number');\n }\n scaleAll(this, scale);\n return this;\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n toString(options) {\n return inspectMatrixWithOptions(this, options);\n }\n}\n\nAbstractMatrix.prototype.klass = 'Matrix';\nif (typeof Symbol !== 'undefined') {\n AbstractMatrix.prototype[\n Symbol.for('nodejs.util.inspect.custom')\n ] = inspectMatrix;\n}\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\n// Synonyms\nAbstractMatrix.random = AbstractMatrix.rand;\nAbstractMatrix.randomInt = AbstractMatrix.randInt;\nAbstractMatrix.diagonal = AbstractMatrix.diag;\nAbstractMatrix.prototype.diagonal = AbstractMatrix.prototype.diag;\nAbstractMatrix.identity = AbstractMatrix.eye;\nAbstractMatrix.prototype.negate = AbstractMatrix.prototype.neg;\nAbstractMatrix.prototype.tensorProduct =\n AbstractMatrix.prototype.kroneckerProduct;\n\nexport default class Matrix extends AbstractMatrix {\n constructor(nRows, nColumns) {\n super();\n if (Matrix.isMatrix(nRows)) {\n return nRows.clone();\n } else if (Number.isInteger(nRows) && nRows > 0) {\n // Create an empty matrix\n this.data = [];\n if (Number.isInteger(nColumns) && nColumns > 0) {\n for (let i = 0; i < nRows; i++) {\n this.data.push(new Float64Array(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 arrayData = nRows;\n nRows = arrayData.length;\n nColumns = arrayData[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 this.data = [];\n for (let i = 0; i < nRows; i++) {\n if (arrayData[i].length !== nColumns) {\n throw new RangeError('Inconsistent array dimensions');\n }\n this.data.push(Float64Array.from(arrayData[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.data[rowIndex][columnIndex] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.data[rowIndex][columnIndex];\n }\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.data.splice(index, 1);\n this.rows -= 1;\n return this;\n }\n\n addRow(index, array) {\n if (array === undefined) {\n array = index;\n index = this.rows;\n }\n checkRowIndex(this, index, true);\n array = Float64Array.from(checkRowVector(this, array, true));\n this.data.splice(index, 0, array);\n this.rows += 1;\n return this;\n }\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 (let i = 0; i < this.rows; i++) {\n const newRow = new Float64Array(this.columns - 1);\n for (let j = 0; j < index; j++) {\n newRow[j] = this.data[i][j];\n }\n for (let j = index + 1; j < this.columns; j++) {\n newRow[j - 1] = this.data[i][j];\n }\n this.data[i] = newRow;\n }\n this.columns -= 1;\n return this;\n }\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 (let i = 0; i < this.rows; i++) {\n const newRow = new Float64Array(this.columns + 1);\n let j = 0;\n for (; j < index; j++) {\n newRow[j] = this.data[i][j];\n }\n newRow[j++] = array[i];\n for (; j < this.columns + 1; j++) {\n newRow[j] = this.data[i][j - 1];\n }\n this.data[i] = newRow;\n }\n this.columns += 1;\n return this;\n }\n}\n\ninstallMathOperations(AbstractMatrix, Matrix);\n","import { AbstractMatrix } 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","import { checkColumnIndex } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixColumnView extends BaseView {\n constructor(matrix, column) {\n checkColumnIndex(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","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","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","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","import { checkRowIndex } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixRowView extends BaseView {\n constructor(matrix, row) {\n checkRowIndex(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","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","import { checkIndices } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixSelectionView extends BaseView {\n constructor(matrix, rowIndices, columnIndices) {\n let 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","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","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","import { AbstractMatrix } from '../matrix';\n\nexport default class WrapperMatrix1D extends AbstractMatrix {\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 let index = this._calculateIndex(rowIndex, columnIndex);\n this.data[index] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n let 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","import { AbstractMatrix } from '../matrix';\n\nexport default class WrapperMatrix2D extends AbstractMatrix {\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","import WrapperMatrix1D from './WrapperMatrix1D';\nimport WrapperMatrix2D from './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","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nexport default class LuDecomposition {\n constructor(matrix) {\n matrix = WrapperMatrix2D.checkMatrix(matrix);\n\n let lu = matrix.clone();\n let rows = lu.rows;\n let columns = lu.columns;\n let pivotVector = new Float64Array(rows);\n let pivotSign = 1;\n let i, j, k, p, s, t, v;\n let LUcolj, kmax;\n\n for (i = 0; i < rows; i++) {\n pivotVector[i] = i;\n }\n\n LUcolj = new Float64Array(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 isSingular() {\n let data = this.LU;\n let col = data.columns;\n for (let j = 0; j < col; j++) {\n if (data.get(j, j) === 0) {\n return true;\n }\n }\n return false;\n }\n\n solve(value) {\n value = Matrix.checkMatrix(value);\n\n let lu = this.LU;\n let 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 let count = value.columns;\n let X = value.subMatrixRow(this.pivotVector, 0, count - 1);\n let columns = lu.columns;\n let 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.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));\n }\n }\n }\n for (k = columns - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X.set(k, j, X.get(k, j) / lu.get(k, k));\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));\n }\n }\n }\n return X;\n }\n\n get determinant() {\n let data = this.LU;\n if (!data.isSquare()) {\n throw new Error('Matrix must be square');\n }\n let determinant = this.pivotSign;\n let col = data.columns;\n for (let j = 0; j < col; j++) {\n determinant *= data.get(j, j);\n }\n return determinant;\n }\n\n get lowerTriangularMatrix() {\n let data = this.LU;\n let rows = data.rows;\n let columns = data.columns;\n let X = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n if (i > j) {\n X.set(i, j, data.get(i, j));\n } else if (i === j) {\n X.set(i, j, 1);\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get upperTriangularMatrix() {\n let data = this.LU;\n let rows = data.rows;\n let columns = data.columns;\n let X = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n if (i <= j) {\n X.set(i, j, data.get(i, j));\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get pivotPermutationVector() {\n return Array.from(this.pivotVector);\n }\n}\n","export function hypotenuse(a, b) {\n let 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","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\n\nexport default class QrDecomposition {\n constructor(value) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n let qr = value.clone();\n let m = value.rows;\n let n = value.columns;\n let rdiag = new Float64Array(n);\n let i, j, k, s;\n\n for (k = 0; k < n; k++) {\n let 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 solve(value) {\n value = Matrix.checkMatrix(value);\n\n let qr = this.QR;\n let 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 let count = value.columns;\n let X = value.clone();\n let n = qr.columns;\n let 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.get(i, k) * X.get(i, j);\n }\n s = -s / qr.get(k, k);\n for (i = k; i < m; i++) {\n X.set(i, j, X.get(i, j) + s * qr.get(i, k));\n }\n }\n }\n for (k = n - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X.set(k, j, X.get(k, j) / this.Rdiag[k]);\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X.set(i, j, X.get(i, j) - X.get(k, j) * qr.get(i, k));\n }\n }\n }\n\n return X.subMatrix(0, n - 1, 0, count - 1);\n }\n\n isFullRank() {\n let columns = this.QR.columns;\n for (let i = 0; i < columns; i++) {\n if (this.Rdiag[i] === 0) {\n return false;\n }\n }\n return true;\n }\n\n get upperTriangularMatrix() {\n let qr = this.QR;\n let n = qr.columns;\n let X = new Matrix(n, n);\n let i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n if (i < j) {\n X.set(i, j, qr.get(i, j));\n } else if (i === j) {\n X.set(i, j, this.Rdiag[i]);\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get orthogonalMatrix() {\n let qr = this.QR;\n let rows = qr.rows;\n let columns = qr.columns;\n let X = new Matrix(rows, columns);\n let i, j, k, s;\n\n for (k = columns - 1; k >= 0; k--) {\n for (i = 0; i < rows; i++) {\n X.set(i, k, 0);\n }\n X.set(k, k, 1);\n for (j = k; j < columns; j++) {\n if (qr.get(k, k) !== 0) {\n s = 0;\n for (i = k; i < rows; i++) {\n s += qr.get(i, k) * X.get(i, j);\n }\n\n s = -s / qr.get(k, k);\n\n for (i = k; i < rows; i++) {\n X.set(i, j, X.get(i, j) + s * qr.get(i, k));\n }\n }\n }\n }\n return X;\n }\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\n\nexport default class SingularValueDecomposition {\n constructor(value, options = {}) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n let m = value.rows;\n let n = value.columns;\n\n const {\n computeLeftSingularVectors = true,\n computeRightSingularVectors = true,\n autoTranspose = false,\n } = options;\n\n let wantu = Boolean(computeLeftSingularVectors);\n let wantv = Boolean(computeRightSingularVectors);\n\n let swapped = false;\n let 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 let aux = wantu;\n wantu = wantv;\n wantv = aux;\n }\n } else {\n a = value.clone();\n }\n\n let nu = Math.min(m, n);\n let ni = Math.min(m + 1, n);\n let s = new Float64Array(ni);\n let U = new Matrix(m, nu);\n let V = new Matrix(n, n);\n\n let e = new Float64Array(n);\n let work = new Float64Array(m);\n\n let si = new Float64Array(ni);\n for (let i = 0; i < ni; i++) si[i] = i;\n\n let nct = Math.min(m - 1, n);\n let nrt = Math.max(0, Math.min(n - 2, m));\n let 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.get(i, k));\n }\n if (s[k] !== 0) {\n if (a.get(k, k) < 0) {\n s[k] = -s[k];\n }\n for (let i = k; i < m; i++) {\n a.set(i, k, a.get(i, k) / s[k]);\n }\n a.set(k, k, a.get(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.get(i, k) * a.get(i, j);\n }\n t = -t / a.get(k, k);\n for (let i = k; i < m; i++) {\n a.set(i, j, a.get(i, j) + t * a.get(i, k));\n }\n }\n e[j] = a.get(k, j);\n }\n\n if (wantu && k < nct) {\n for (let i = k; i < m; i++) {\n U.set(i, k, a.get(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.get(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.set(i, j, a.get(i, j) + t * work[i]);\n }\n }\n }\n if (wantv) {\n for (let i = k + 1; i < n; i++) {\n V.set(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.get(nct, nct);\n }\n if (m < p) {\n s[p - 1] = 0;\n }\n if (nrt + 1 < p) {\n e[nrt] = a.get(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.set(i, j, 0);\n }\n U.set(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.get(i, k) * U.get(i, j);\n }\n t = -t / U.get(k, k);\n for (let i = k; i < m; i++) {\n U.set(i, j, U.get(i, j) + t * U.get(i, k));\n }\n }\n for (let i = k; i < m; i++) {\n U.set(i, k, -U.get(i, k));\n }\n U.set(k, k, 1 + U.get(k, k));\n for (let i = 0; i < k - 1; i++) {\n U.set(i, k, 0);\n }\n } else {\n for (let i = 0; i < m; i++) {\n U.set(i, k, 0);\n }\n U.set(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.get(i, k) * V.get(i, j);\n }\n t = -t / V.get(k + 1, k);\n for (let i = k + 1; i < n; i++) {\n V.set(i, j, V.get(i, j) + t * V.get(i, k));\n }\n }\n }\n for (let i = 0; i < n; i++) {\n V.set(i, k, 0);\n }\n V.set(k, k, 1);\n }\n }\n\n let pp = p - 1;\n let iter = 0;\n let 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.get(i, j) + sn * V.get(i, p - 1);\n V.set(i, p - 1, -sn * V.get(i, j) + cs * V.get(i, p - 1));\n V.set(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.get(i, j) + sn * U.get(i, k - 1);\n U.set(i, k - 1, -sn * U.get(i, j) + cs * U.get(i, k - 1));\n U.set(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.get(i, j) + sn * V.get(i, j + 1);\n V.set(i, j + 1, -sn * V.get(i, j) + cs * V.get(i, j + 1));\n V.set(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.get(i, j) + sn * U.get(i, j + 1);\n U.set(i, j + 1, -sn * U.get(i, j) + cs * U.get(i, j + 1));\n U.set(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.set(i, k, -V.get(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.get(i, k + 1);\n V.set(i, k + 1, V.get(i, k));\n V.set(i, k, t);\n }\n }\n if (wantu && k < m - 1) {\n for (let i = 0; i < m; i++) {\n t = U.get(i, k + 1);\n U.set(i, k + 1, U.get(i, k));\n U.set(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 let 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 solve(value) {\n let Y = value;\n let e = this.threshold;\n let scols = this.s.length;\n let Ls = Matrix.zeros(scols, scols);\n\n for (let i = 0; i < scols; i++) {\n if (Math.abs(this.s[i]) <= e) {\n Ls.set(i, i, 0);\n } else {\n Ls.set(i, i, 1 / this.s[i]);\n }\n }\n\n let U = this.U;\n let V = this.rightSingularVectors;\n\n let VL = V.mmul(Ls);\n let vrows = V.rows;\n let urows = U.rows;\n let 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.get(i, k) * U.get(j, k);\n }\n VLU.set(i, j, sum);\n }\n }\n\n return VLU.mmul(Y);\n }\n\n solveForDiagonal(value) {\n return this.solve(Matrix.diag(value));\n }\n\n inverse() {\n let V = this.V;\n let e = this.threshold;\n let vrows = V.rows;\n let vcols = V.columns;\n let 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.set(i, j, V.get(i, j) / this.s[j]);\n }\n }\n }\n\n let U = this.U;\n\n let urows = U.rows;\n let ucols = U.columns;\n let 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.get(i, k) * U.get(j, k);\n }\n Y.set(i, j, sum);\n }\n }\n\n return Y;\n }\n\n get condition() {\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\n }\n\n get norm2() {\n return this.s[0];\n }\n\n get rank() {\n let tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON;\n let r = 0;\n let s = this.s;\n for (let i = 0, ii = s.length; i < ii; i++) {\n if (s[i] > tol) {\n r++;\n }\n }\n return r;\n }\n\n get diagonal() {\n return Array.from(this.s);\n }\n\n get threshold() {\n return (Number.EPSILON / 2) * Math.max(this.m, this.n) * this.s[0];\n }\n\n get leftSingularVectors() {\n return this.U;\n }\n\n get rightSingularVectors() {\n return this.V;\n }\n\n get diagonalMatrix() {\n return Matrix.diag(this.s);\n }\n}\n","import LuDecomposition from './dc/lu';\nimport QrDecomposition from './dc/qr';\nimport SingularValueDecomposition from './dc/svd';\nimport Matrix from './matrix';\nimport WrapperMatrix2D from './wrap/WrapperMatrix2D';\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\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","import LuDecomposition from './dc/lu';\nimport Matrix from './matrix';\nimport MatrixSelectionView from './views/selection';\n\nexport function determinant(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (matrix.isSquare()) {\n let a, b, c, d;\n if (matrix.columns === 2) {\n // 2 x 2 matrix\n a = matrix.get(0, 0);\n b = matrix.get(0, 1);\n c = matrix.get(1, 0);\n d = matrix.get(1, 1);\n\n return a * d - b * c;\n } else if (matrix.columns === 3) {\n // 3 x 3 matrix\n let subMatrix0, subMatrix1, subMatrix2;\n subMatrix0 = new MatrixSelectionView(matrix, [1, 2], [1, 2]);\n subMatrix1 = new MatrixSelectionView(matrix, [1, 2], [0, 2]);\n subMatrix2 = new MatrixSelectionView(matrix, [1, 2], [0, 1]);\n a = matrix.get(0, 0);\n b = matrix.get(0, 1);\n c = matrix.get(0, 2);\n\n return (\n a * determinant(subMatrix0) -\n b * determinant(subMatrix1) +\n c * determinant(subMatrix2)\n );\n } else {\n // general purpose determinant using the LU decomposition\n return new LuDecomposition(matrix).determinant;\n }\n } else {\n throw Error('determinant can only be calculated for a square matrix');\n }\n}\n","import SingularValueDecomposition from './dc/svd';\nimport Matrix from './matrix';\n\nfunction xrange(n, exception) {\n let range = [];\n for (let i = 0; i < n; i++) {\n if (i !== exception) {\n range.push(i);\n }\n }\n return range;\n}\n\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 let returnArray = matrix.addRow(index, [0]);\n for (let 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\nexport function linearDependencies(matrix, options = {}) {\n const { thresholdValue = 10e-10, thresholdError = 10e-10 } = options;\n matrix = Matrix.checkMatrix(matrix);\n\n let n = matrix.rows;\n let results = new Matrix(n, n);\n\n for (let i = 0; i < n; i++) {\n let b = Matrix.columnVector(matrix.getRow(i));\n let Abis = matrix.subMatrixRow(xrange(n, i)).transpose();\n let svd = new SingularValueDecomposition(Abis);\n let x = svd.solve(b);\n let error = Matrix.sub(b, Abis.mmul(x)).abs().max();\n results.setRow(\n i,\n dependenciesOneRow(error, x, i, thresholdValue, thresholdError),\n );\n }\n return results;\n}\n","import SVD from './dc/svd';\nimport Matrix from './matrix';\n\nexport function pseudoInverse(matrix, threshold = Number.EPSILON) {\n matrix = Matrix.checkMatrix(matrix);\n let svdSolution = new SVD(matrix, { autoTranspose: true });\n\n let U = svdSolution.leftSingularVectors;\n let V = svdSolution.rightSingularVectors;\n let s = svdSolution.diagonal;\n\n for (let 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 return V.mmul(Matrix.diag(s).mmul(U.transpose()));\n}\n","import Matrix from './matrix';\n\nexport function covariance(xMatrix, yMatrix = xMatrix, options = {}) {\n xMatrix = new Matrix(xMatrix);\n let yIsSame = false;\n if (\n typeof yMatrix === 'object' &&\n !Matrix.isMatrix(yMatrix) &&\n !Array.isArray(yMatrix)\n ) {\n options = yMatrix;\n yMatrix = xMatrix;\n yIsSame = true;\n } else {\n yMatrix = new Matrix(yMatrix);\n }\n if (xMatrix.rows !== yMatrix.rows) {\n throw new TypeError('Both matrices must have the same number of rows');\n }\n const { center = true } = options;\n if (center) {\n xMatrix = xMatrix.center('column');\n if (!yIsSame) {\n yMatrix = yMatrix.center('column');\n }\n }\n const cov = xMatrix.transpose().mmul(yMatrix);\n for (let i = 0; i < cov.rows; i++) {\n for (let j = 0; j < cov.columns; j++) {\n cov.set(i, j, cov.get(i, j) * (1 / (xMatrix.rows - 1)));\n }\n }\n return cov;\n}\n","import Matrix from './matrix';\n\nexport function correlation(xMatrix, yMatrix = xMatrix, options = {}) {\n xMatrix = new Matrix(xMatrix);\n let yIsSame = false;\n if (\n typeof yMatrix === 'object' &&\n !Matrix.isMatrix(yMatrix) &&\n !Array.isArray(yMatrix)\n ) {\n options = yMatrix;\n yMatrix = xMatrix;\n yIsSame = true;\n } else {\n yMatrix = new Matrix(yMatrix);\n }\n if (xMatrix.rows !== yMatrix.rows) {\n throw new TypeError('Both matrices must have the same number of rows');\n }\n\n const { center = true, scale = true } = options;\n if (center) {\n xMatrix.center('column');\n if (!yIsSame) {\n yMatrix.center('column');\n }\n }\n if (scale) {\n xMatrix.scale('column');\n if (!yIsSame) {\n yMatrix.scale('column');\n }\n }\n\n const sdx = xMatrix.standardDeviation('column', { unbiased: true });\n const sdy = yIsSame\n ? sdx\n : yMatrix.standardDeviation('column', { unbiased: true });\n\n const corr = xMatrix.transpose().mmul(yMatrix);\n for (let i = 0; i < corr.rows; i++) {\n for (let j = 0; j < corr.columns; j++) {\n corr.set(\n i,\n j,\n corr.get(i, j) * (1 / (sdx[i] * sdy[j])) * (1 / (xMatrix.rows - 1)),\n );\n }\n }\n return corr;\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\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 let n = matrix.columns;\n let V = new Matrix(n, n);\n let d = new Float64Array(n);\n let e = new Float64Array(n);\n let value = matrix;\n let i, j;\n\n let 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.set(i, j, value.get(i, j));\n }\n }\n tred2(n, e, d, V);\n tql2(n, e, d, V);\n } else {\n let H = new Matrix(n, n);\n let ort = new Float64Array(n);\n for (j = 0; j < n; j++) {\n for (i = 0; i < n; i++) {\n H.set(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 get realEigenvalues() {\n return Array.from(this.d);\n }\n\n get imaginaryEigenvalues() {\n return Array.from(this.e);\n }\n\n get eigenvectorMatrix() {\n return this.V;\n }\n\n get diagonalMatrix() {\n let n = this.n;\n let e = this.e;\n let d = this.d;\n let X = new Matrix(n, n);\n let i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n X.set(i, j, 0);\n }\n X.set(i, i, d[i]);\n if (e[i] > 0) {\n X.set(i, i + 1, e[i]);\n } else if (e[i] < 0) {\n X.set(i, i - 1, e[i]);\n }\n }\n return X;\n }\n}\n\nfunction tred2(n, e, d, V) {\n let f, g, h, i, j, k, hh, scale;\n\n for (j = 0; j < n; j++) {\n d[j] = V.get(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.get(i - 1, j);\n V.set(i, j, 0);\n V.set(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.set(j, i, f);\n g = e[j] + V.get(j, j) * f;\n for (k = j + 1; k <= i - 1; k++) {\n g += V.get(k, j) * d[k];\n e[k] += V.get(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.set(k, j, V.get(k, j) - (f * e[k] + g * d[k]));\n }\n d[j] = V.get(i - 1, j);\n V.set(i, j, 0);\n }\n }\n d[i] = h;\n }\n\n for (i = 0; i < n - 1; i++) {\n V.set(n - 1, i, V.get(i, i));\n V.set(i, i, 1);\n h = d[i + 1];\n if (h !== 0) {\n for (k = 0; k <= i; k++) {\n d[k] = V.get(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.get(k, i + 1) * V.get(k, j);\n }\n for (k = 0; k <= i; k++) {\n V.set(k, j, V.get(k, j) - g * d[k]);\n }\n }\n }\n\n for (k = 0; k <= i; k++) {\n V.set(k, i + 1, 0);\n }\n }\n\n for (j = 0; j < n; j++) {\n d[j] = V.get(n - 1, j);\n V.set(n - 1, j, 0);\n }\n\n V.set(n - 1, n - 1, 1);\n e[0] = 0;\n}\n\nfunction tql2(n, e, d, V) {\n let 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 let f = 0;\n let tst1 = 0;\n let 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.get(k, i + 1);\n V.set(k, i + 1, s * V.get(k, i) + c * h);\n V.set(k, i, c * V.get(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.get(j, i);\n V.set(j, i, V.get(j, k));\n V.set(j, k, p);\n }\n }\n }\n}\n\nfunction orthes(n, H, ort, V) {\n let low = 0;\n let high = n - 1;\n let f, g, h, i, j, m;\n let 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.get(i, m - 1));\n }\n\n if (scale !== 0) {\n h = 0;\n for (i = high; i >= m; i--) {\n ort[i] = H.get(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.get(i, j);\n }\n\n f = f / h;\n for (i = m; i <= high; i++) {\n H.set(i, j, H.get(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.get(i, j);\n }\n\n f = f / h;\n for (j = m; j <= high; j++) {\n H.set(i, j, H.get(i, j) - f * ort[j]);\n }\n }\n\n ort[m] = scale * ort[m];\n H.set(m, m - 1, scale * g);\n }\n }\n\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V.set(i, j, i === j ? 1 : 0);\n }\n }\n\n for (m = high - 1; m >= low + 1; m--) {\n if (H.get(m, m - 1) !== 0) {\n for (i = m + 1; i <= high; i++) {\n ort[i] = H.get(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.get(i, j);\n }\n\n g = g / ort[m] / H.get(m, m - 1);\n for (i = m; i <= high; i++) {\n V.set(i, j, V.get(i, j) + g * ort[i]);\n }\n }\n }\n }\n}\n\nfunction hqr2(nn, e, d, V, H) {\n let n = nn - 1;\n let low = 0;\n let high = nn - 1;\n let eps = Number.EPSILON;\n let exshift = 0;\n let norm = 0;\n let p = 0;\n let q = 0;\n let r = 0;\n let s = 0;\n let z = 0;\n let iter = 0;\n let i, j, k, l, m, t, w, x, y;\n let ra, sa, vr, vi;\n let notlast, cdivres;\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n d[i] = H.get(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.get(i, j));\n }\n }\n\n while (n >= low) {\n l = n;\n while (l > low) {\n s = Math.abs(H.get(l - 1, l - 1)) + Math.abs(H.get(l, l));\n if (s === 0) {\n s = norm;\n }\n if (Math.abs(H.get(l, l - 1)) < eps * s) {\n break;\n }\n l--;\n }\n\n if (l === n) {\n H.set(n, n, H.get(n, n) + exshift);\n d[n] = H.get(n, n);\n e[n] = 0;\n n--;\n iter = 0;\n } else if (l === n - 1) {\n w = H.get(n, n - 1) * H.get(n - 1, n);\n p = (H.get(n - 1, n - 1) - H.get(n, n)) / 2;\n q = p * p + w;\n z = Math.sqrt(Math.abs(q));\n H.set(n, n, H.get(n, n) + exshift);\n H.set(n - 1, n - 1, H.get(n - 1, n - 1) + exshift);\n x = H.get(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.get(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.get(n - 1, j);\n H.set(n - 1, j, q * z + p * H.get(n, j));\n H.set(n, j, q * H.get(n, j) - p * z);\n }\n\n for (i = 0; i <= n; i++) {\n z = H.get(i, n - 1);\n H.set(i, n - 1, q * z + p * H.get(i, n));\n H.set(i, n, q * H.get(i, n) - p * z);\n }\n\n for (i = low; i <= high; i++) {\n z = V.get(i, n - 1);\n V.set(i, n - 1, q * z + p * V.get(i, n));\n V.set(i, n, q * V.get(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.get(n, n);\n y = 0;\n w = 0;\n if (l < n) {\n y = H.get(n - 1, n - 1);\n w = H.get(n, n - 1) * H.get(n - 1, n);\n }\n\n if (iter === 10) {\n exshift += x;\n for (i = low; i <= n; i++) {\n H.set(i, i, H.get(i, i) - x);\n }\n s = Math.abs(H.get(n, n - 1)) + Math.abs(H.get(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.set(i, i, H.get(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.get(m, m);\n r = x - z;\n s = y - z;\n p = (r * s - w) / H.get(m + 1, m) + H.get(m, m + 1);\n q = H.get(m + 1, m + 1) - z - r - s;\n r = H.get(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.get(m, m - 1)) * (Math.abs(q) + Math.abs(r)) <\n eps *\n (Math.abs(p) *\n (Math.abs(H.get(m - 1, m - 1)) +\n Math.abs(z) +\n Math.abs(H.get(m + 1, m + 1))))\n ) {\n break;\n }\n m--;\n }\n\n for (i = m + 2; i <= n; i++) {\n H.set(i, i - 2, 0);\n if (i > m + 2) {\n H.set(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.get(k, k - 1);\n q = H.get(k + 1, k - 1);\n r = notlast ? H.get(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.set(k, k - 1, -s * x);\n } else if (l !== m) {\n H.set(k, k - 1, -H.get(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.get(k, j) + q * H.get(k + 1, j);\n if (notlast) {\n p = p + r * H.get(k + 2, j);\n H.set(k + 2, j, H.get(k + 2, j) - p * z);\n }\n\n H.set(k, j, H.get(k, j) - p * x);\n H.set(k + 1, j, H.get(k + 1, j) - p * y);\n }\n\n for (i = 0; i <= Math.min(n, k + 3); i++) {\n p = x * H.get(i, k) + y * H.get(i, k + 1);\n if (notlast) {\n p = p + z * H.get(i, k + 2);\n H.set(i, k + 2, H.get(i, k + 2) - p * r);\n }\n\n H.set(i, k, H.get(i, k) - p);\n H.set(i, k + 1, H.get(i, k + 1) - p * q);\n }\n\n for (i = low; i <= high; i++) {\n p = x * V.get(i, k) + y * V.get(i, k + 1);\n if (notlast) {\n p = p + z * V.get(i, k + 2);\n V.set(i, k + 2, V.get(i, k + 2) - p * r);\n }\n\n V.set(i, k, V.get(i, k) - p);\n V.set(i, k + 1, V.get(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.set(n, n, 1);\n for (i = n - 1; i >= 0; i--) {\n w = H.get(i, i) - p;\n r = 0;\n for (j = l; j <= n; j++) {\n r = r + H.get(i, j) * H.get(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.set(i, n, w !== 0 ? -r / w : -r / (eps * norm));\n } else {\n x = H.get(i, i + 1);\n y = H.get(i + 1, i);\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\n t = (x * s - z * r) / q;\n H.set(i, n, t);\n H.set(\n i + 1,\n n,\n Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z,\n );\n }\n\n t = Math.abs(H.get(i, n));\n if (eps * t * t > 1) {\n for (j = i; j <= n; j++) {\n H.set(j, n, H.get(j, n) / t);\n }\n }\n }\n }\n } else if (q < 0) {\n l = n - 1;\n\n if (Math.abs(H.get(n, n - 1)) > Math.abs(H.get(n - 1, n))) {\n H.set(n - 1, n - 1, q / H.get(n, n - 1));\n H.set(n - 1, n, -(H.get(n, n) - p) / H.get(n, n - 1));\n } else {\n cdivres = cdiv(0, -H.get(n - 1, n), H.get(n - 1, n - 1) - p, q);\n H.set(n - 1, n - 1, cdivres[0]);\n H.set(n - 1, n, cdivres[1]);\n }\n\n H.set(n, n - 1, 0);\n H.set(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.get(i, j) * H.get(j, n - 1);\n sa = sa + H.get(i, j) * H.get(j, n);\n }\n\n w = H.get(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.set(i, n - 1, cdivres[0]);\n H.set(i, n, cdivres[1]);\n } else {\n x = H.get(i, i + 1);\n y = H.get(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.set(i, n - 1, cdivres[0]);\n H.set(i, n, cdivres[1]);\n if (Math.abs(x) > Math.abs(z) + Math.abs(q)) {\n H.set(\n i + 1,\n n - 1,\n (-ra - w * H.get(i, n - 1) + q * H.get(i, n)) / x,\n );\n H.set(\n i + 1,\n n,\n (-sa - w * H.get(i, n) - q * H.get(i, n - 1)) / x,\n );\n } else {\n cdivres = cdiv(\n -r - y * H.get(i, n - 1),\n -s - y * H.get(i, n),\n z,\n q,\n );\n H.set(i + 1, n - 1, cdivres[0]);\n H.set(i + 1, n, cdivres[1]);\n }\n }\n\n t = Math.max(Math.abs(H.get(i, n - 1)), Math.abs(H.get(i, n)));\n if (eps * t * t > 1) {\n for (j = i; j <= n; j++) {\n H.set(j, n - 1, H.get(j, n - 1) / t);\n H.set(j, n, H.get(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.set(i, j, H.get(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.get(i, k) * H.get(k, j);\n }\n V.set(i, j, z);\n }\n }\n}\n\nfunction cdiv(xr, xi, yr, yi) {\n let 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","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\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 let a = value;\n let dimension = a.rows;\n let l = new Matrix(dimension, dimension);\n let positiveDefinite = true;\n let i, j, k;\n\n for (j = 0; j < dimension; j++) {\n let d = 0;\n for (k = 0; k < j; k++) {\n let s = 0;\n for (i = 0; i < k; i++) {\n s += l.get(k, i) * l.get(j, i);\n }\n s = (a.get(j, k) - s) / l.get(k, k);\n l.set(j, k, s);\n d = d + s * s;\n }\n\n d = a.get(j, j) - d;\n\n positiveDefinite &= d > 0;\n l.set(j, j, Math.sqrt(Math.max(d, 0)));\n for (k = j + 1; k < dimension; k++) {\n l.set(j, k, 0);\n }\n }\n\n this.L = l;\n this.positiveDefinite = Boolean(positiveDefinite);\n }\n\n isPositiveDefinite() {\n return this.positiveDefinite;\n }\n\n solve(value) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n let l = this.L;\n let dimension = l.rows;\n\n if (value.rows !== dimension) {\n throw new Error('Matrix dimensions do not match');\n }\n if (this.isPositiveDefinite() === false) {\n throw new Error('Matrix is not positive definite');\n }\n\n let count = value.columns;\n let B = value.clone();\n let 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.set(k, j, B.get(k, j) - B.get(i, j) * l.get(k, i));\n }\n B.set(k, j, B.get(k, j) / l.get(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.set(k, j, B.get(k, j) - B.get(i, j) * l.get(i, k));\n }\n B.set(k, j, B.get(k, j) / l.get(k, k));\n }\n }\n\n return B;\n }\n\n get lowerTriangularMatrix() {\n return this.L;\n }\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nexport default class nipals {\n constructor(X, options = {}) {\n X = WrapperMatrix2D.checkMatrix(X);\n let { Y } = options;\n const {\n scaleScores = false,\n maxIterations = 1000,\n terminationCriteria = 1e-10,\n } = options;\n\n let u;\n if (Y) {\n if (Array.isArray(Y) && typeof Y[0] === 'number') {\n Y = Matrix.columnVector(Y);\n } else {\n Y = WrapperMatrix2D.checkMatrix(Y);\n }\n if (!Y.isColumnVector() || Y.rows !== X.rows) {\n throw new Error('Y must be a column vector of length X.rows');\n }\n u = Y;\n } else {\n u = X.getColumnVector(0);\n }\n\n let diff = 1;\n let t, q, w, tOld;\n\n for (\n let counter = 0;\n counter < maxIterations && diff > terminationCriteria;\n counter++\n ) {\n w = X.transpose().mmul(u).div(u.transpose().mmul(u).get(0, 0));\n w = w.div(w.norm());\n\n t = X.mmul(w).div(w.transpose().mmul(w).get(0, 0));\n\n if (counter > 0) {\n diff = t.clone().sub(tOld).pow(2).sum();\n }\n tOld = t.clone();\n\n if (Y) {\n q = Y.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));\n q = q.div(q.norm());\n\n u = Y.mmul(q).div(q.transpose().mmul(q).get(0, 0));\n } else {\n u = t;\n }\n }\n\n if (Y) {\n let p = X.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));\n p = p.div(p.norm());\n let xResidual = X.clone().sub(t.clone().mmul(p.transpose()));\n let residual = u.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));\n let yResidual = Y.clone().sub(\n t.clone().mulS(residual.get(0, 0)).mmul(q.transpose()),\n );\n\n this.t = t;\n this.p = p.transpose();\n this.w = w.transpose();\n this.q = q;\n this.u = u;\n this.s = t.transpose().mmul(t);\n this.xResidual = xResidual;\n this.yResidual = yResidual;\n this.betas = residual;\n } else {\n this.w = w.transpose();\n this.s = t.transpose().mmul(t).sqrt();\n if (scaleScores) {\n this.t = t.clone().div(this.s.get(0, 0));\n } else {\n this.t = t;\n }\n this.xResidual = X.sub(t.mmul(w.transpose()));\n }\n }\n}\n","const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n","import isArray from 'is-any-array';\n\nfunction sum(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 sumValue = 0;\n\n for (var i = 0; i < input.length; i++) {\n sumValue += input[i];\n }\n\n return sumValue;\n}\n\nexport default sum;\n","import sum from 'ml-array-sum';\n\nfunction mean(input) {\n return sum(input) / input.length;\n}\n\nexport default mean;\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 let counts = new Array(numberOfClasses).fill(0);\n for (let 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 let probabilities = toDiscreteDistribution(\n array,\n getNumberOfClasses(array),\n ).getRow(0);\n\n let sum = 0.0;\n for (let 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\n .filter(function(val, i, arr) {\n return arr.indexOf(val) === i;\n })\n .map((val) => val + 1)\n .reduce((a, b) => Math.max(a, b));\n}\n\n/**\n * @private\n * Calculates the Gini Gain of an array of predictions and those predictions splitted by a feature.\n * @param {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 let splitsImpurity = 0.0;\n let splits = ['greater', 'lesser'];\n\n for (let i = 0; i < splits.length; ++i) {\n let currentSplit = splitted[splits[i]];\n splitsImpurity +=\n (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 let l = array.length;\n\n let m = meanArray(array);\n let error = 0.0;\n\n for (let i = 0; i < l; ++i) {\n let currentElement = array[i];\n error += (currentElement - m) * (currentElement - m);\n }\n\n return error;\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 let error = 0.0;\n let splits = ['greater', 'lesser'];\n\n for (let i = 0; i < splits.length; ++i) {\n let 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 let lesserX = [];\n let greaterX = [];\n let lesserY = [];\n let greaterY = [];\n\n for (let i = 0; i < X.rows; ++i) {\n if (X.get(i, column) < value) {\n lesserX.push(X.getRow(i));\n lesserY.push(y[i]);\n } else {\n greaterX.push(X.getRow(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(\n `Error on zip: the size of a: ${a.length} is different from b: ${b.length}`,\n );\n }\n\n let ret = new Array(a.length);\n for (let 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 mean from 'ml-array-mean';\n\nimport * as Utils from './utils';\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 * @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 // Depending in the node tree class, we set the variables to check information gain (to classify)\n // or error (for regression)\n\n let bestGain = this.kind === 'classifier' ? -Infinity : Infinity;\n let check = this.kind === 'classifier' ? (a, b) => a > b : (a, b) => a < b;\n\n let maxColumn;\n let maxValue;\n\n for (let i = 0; i < XTranspose.rows; ++i) {\n let currentFeature = XTranspose.getRow(i);\n let splitValues = this.featureSplit(currentFeature, y);\n for (let j = 0; j < splitValues.length; ++j) {\n let currentSplitVal = splitValues[j];\n let splitted = this.split(currentFeature, y, currentSplitVal);\n\n let 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 split(x, y, splitValue) {\n let lesser = [];\n let greater = [];\n\n for (let 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 let splitValues = [];\n let arr = Utils.zip(x, y);\n arr.sort(function(a, b) {\n return a[0] - b[0];\n });\n\n for (let i = 1; i < arr.length; ++i) {\n if (arr[i - 1][1] !== arr[i][1]) {\n splitValues.push(\n splitFunctions[this.splitFunction](arr[i - 1][0], arr[i][0]),\n );\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(\n y,\n Utils.getNumberOfClasses(y),\n );\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 let XTranspose = X.transpose();\n let split = this.bestSplit(XTranspose, y);\n\n this.splitValue = split.maxValue;\n this.splitColumn = split.maxColumn;\n this.gain = split.maxGain;\n\n let splittedMatrix = Utils.matrixSplitter(\n X,\n y,\n this.splitColumn,\n this.splitValue,\n );\n\n if (\n currentDepth < this.maxDepth &&\n (this.gain > 0.01 && this.gain !== parentGain) &&\n (splittedMatrix.lesserX.length > 0 && splittedMatrix.greaterX.length > 0)\n ) {\n this.left = new TreeNode(this);\n this.right = new TreeNode(this);\n\n let lesserX = new Matrix(splittedMatrix.lesserX);\n let greaterX = new Matrix(splittedMatrix.greaterX);\n\n this.left.train(\n lesserX,\n splittedMatrix.lesserY,\n currentDepth + 1,\n this.gain,\n );\n this.right.train(\n greaterX,\n splittedMatrix.greaterY,\n currentDepth + 1,\n this.gain,\n );\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 =\n node.distribution.constructor === Array\n ? 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';\n\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 * 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 let predictions = new Array(toPredict.rows);\n\n for (let i = 0; i < toPredict.rows; ++i) {\n predictions[i] = this.root\n .classify(toPredict.getRow(i))\n .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';\n\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 * 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 (\n typeof trainingSet[0] !== 'undefined' &&\n trainingSet[0].length === undefined\n ) {\n trainingSet = Matrix.columnVector(trainingSet);\n } else {\n trainingSet = Matrix.checkMatrix(trainingSet);\n }\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 (\n typeof toPredict[0] !== 'undefined' &&\n toPredict[0].length === undefined\n ) {\n toPredict = Matrix.columnVector(toPredict);\n }\n toPredict = Matrix.checkMatrix(toPredict);\n\n let predictions = new Array(toPredict.rows);\n for (let 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","const SMALLEST_UNSAFE_INTEGER = 0x20000000000000;\r\nconst LARGEST_SAFE_INTEGER = SMALLEST_UNSAFE_INTEGER - 1;\r\nconst UINT32_MAX = -1 >>> 0;\r\nconst UINT32_SIZE = UINT32_MAX + 1;\r\nconst INT32_SIZE = UINT32_SIZE / 2;\r\nconst INT32_MAX = INT32_SIZE - 1;\r\nconst UINT21_SIZE = 1 << 21;\r\nconst UINT21_MAX = UINT21_SIZE - 1;\n\n/**\r\n * Returns a value within [-0x80000000, 0x7fffffff]\r\n */\r\nfunction int32(engine) {\r\n return engine.next() | 0;\r\n}\n\nfunction add(distribution, addend) {\r\n if (addend === 0) {\r\n return distribution;\r\n }\r\n else {\r\n return engine => distribution(engine) + addend;\r\n }\r\n}\n\n/**\r\n * Returns a value within [-0x20000000000000, 0x1fffffffffffff]\r\n */\r\nfunction int53(engine) {\r\n const high = engine.next() | 0;\r\n const low = engine.next() >>> 0;\r\n return ((high & UINT21_MAX) * UINT32_SIZE +\r\n low +\r\n (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0));\r\n}\n\n/**\r\n * Returns a value within [-0x20000000000000, 0x20000000000000]\r\n */\r\nfunction int53Full(engine) {\r\n while (true) {\r\n const high = engine.next() | 0;\r\n if (high & 0x400000) {\r\n if ((high & 0x7fffff) === 0x400000 && (engine.next() | 0) === 0) {\r\n return SMALLEST_UNSAFE_INTEGER;\r\n }\r\n }\r\n else {\r\n const low = engine.next() >>> 0;\r\n return ((high & UINT21_MAX) * UINT32_SIZE +\r\n low +\r\n (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0));\r\n }\r\n }\r\n}\n\n/**\r\n * Returns a value within [0, 0xffffffff]\r\n */\r\nfunction uint32(engine) {\r\n return engine.next() >>> 0;\r\n}\n\n/**\r\n * Returns a value within [0, 0x1fffffffffffff]\r\n */\r\nfunction uint53(engine) {\r\n const high = engine.next() & UINT21_MAX;\r\n const low = engine.next() >>> 0;\r\n return high * UINT32_SIZE + low;\r\n}\n\n/**\r\n * Returns a value within [0, 0x20000000000000]\r\n */\r\nfunction uint53Full(engine) {\r\n while (true) {\r\n const high = engine.next() | 0;\r\n if (high & UINT21_SIZE) {\r\n if ((high & UINT21_MAX) === 0 && (engine.next() | 0) === 0) {\r\n return SMALLEST_UNSAFE_INTEGER;\r\n }\r\n }\r\n else {\r\n const low = engine.next() >>> 0;\r\n return (high & UINT21_MAX) * UINT32_SIZE + low;\r\n }\r\n }\r\n}\n\nfunction isPowerOfTwoMinusOne(value) {\r\n return ((value + 1) & value) === 0;\r\n}\r\nfunction bitmask(masking) {\r\n return (engine) => engine.next() & masking;\r\n}\r\nfunction downscaleToLoopCheckedRange(range) {\r\n const extendedRange = range + 1;\r\n const maximum = extendedRange * Math.floor(UINT32_SIZE / extendedRange);\r\n return engine => {\r\n let value = 0;\r\n do {\r\n value = engine.next() >>> 0;\r\n } while (value >= maximum);\r\n return value % extendedRange;\r\n };\r\n}\r\nfunction downscaleToRange(range) {\r\n if (isPowerOfTwoMinusOne(range)) {\r\n return bitmask(range);\r\n }\r\n else {\r\n return downscaleToLoopCheckedRange(range);\r\n }\r\n}\r\nfunction isEvenlyDivisibleByMaxInt32(value) {\r\n return (value | 0) === 0;\r\n}\r\nfunction upscaleWithHighMasking(masking) {\r\n return engine => {\r\n const high = engine.next() & masking;\r\n const low = engine.next() >>> 0;\r\n return high * UINT32_SIZE + low;\r\n };\r\n}\r\nfunction upscaleToLoopCheckedRange(extendedRange) {\r\n const maximum = extendedRange * Math.floor(SMALLEST_UNSAFE_INTEGER / extendedRange);\r\n return engine => {\r\n let ret = 0;\r\n do {\r\n const high = engine.next() & UINT21_MAX;\r\n const low = engine.next() >>> 0;\r\n ret = high * UINT32_SIZE + low;\r\n } while (ret >= maximum);\r\n return ret % extendedRange;\r\n };\r\n}\r\nfunction upscaleWithinU53(range) {\r\n const extendedRange = range + 1;\r\n if (isEvenlyDivisibleByMaxInt32(extendedRange)) {\r\n const highRange = ((extendedRange / UINT32_SIZE) | 0) - 1;\r\n if (isPowerOfTwoMinusOne(highRange)) {\r\n return upscaleWithHighMasking(highRange);\r\n }\r\n }\r\n return upscaleToLoopCheckedRange(extendedRange);\r\n}\r\nfunction upscaleWithinI53AndLoopCheck(min, max) {\r\n return engine => {\r\n let ret = 0;\r\n do {\r\n const high = engine.next() | 0;\r\n const low = engine.next() >>> 0;\r\n ret =\r\n (high & UINT21_MAX) * UINT32_SIZE +\r\n low +\r\n (high & UINT21_SIZE ? -SMALLEST_UNSAFE_INTEGER : 0);\r\n } while (ret < min || ret > max);\r\n return ret;\r\n };\r\n}\r\n/**\r\n * Returns a Distribution to return a value within [min, max]\r\n * @param min The minimum integer value, inclusive. No less than -0x20000000000000.\r\n * @param max The maximum integer value, inclusive. No greater than 0x20000000000000.\r\n */\r\nfunction integer(min, max) {\r\n min = Math.floor(min);\r\n max = Math.floor(max);\r\n if (min < -SMALLEST_UNSAFE_INTEGER || !isFinite(min)) {\r\n throw new RangeError(`Expected min to be at least ${-SMALLEST_UNSAFE_INTEGER}`);\r\n }\r\n else if (max > SMALLEST_UNSAFE_INTEGER || !isFinite(max)) {\r\n throw new RangeError(`Expected max to be at most ${SMALLEST_UNSAFE_INTEGER}`);\r\n }\r\n const range = max - min;\r\n if (range <= 0 || !isFinite(range)) {\r\n return () => min;\r\n }\r\n else if (range === UINT32_MAX) {\r\n if (min === 0) {\r\n return uint32;\r\n }\r\n else {\r\n return add(int32, min + INT32_SIZE);\r\n }\r\n }\r\n else if (range < UINT32_MAX) {\r\n return add(downscaleToRange(range), min);\r\n }\r\n else if (range === LARGEST_SAFE_INTEGER) {\r\n return add(uint53, min);\r\n }\r\n else if (range < LARGEST_SAFE_INTEGER) {\r\n return add(upscaleWithinU53(range), min);\r\n }\r\n else if (max - 1 - min === LARGEST_SAFE_INTEGER) {\r\n return add(uint53Full, min);\r\n }\r\n else if (min === -SMALLEST_UNSAFE_INTEGER &&\r\n max === SMALLEST_UNSAFE_INTEGER) {\r\n return int53Full;\r\n }\r\n else if (min === -SMALLEST_UNSAFE_INTEGER && max === LARGEST_SAFE_INTEGER) {\r\n return int53;\r\n }\r\n else if (min === -LARGEST_SAFE_INTEGER && max === SMALLEST_UNSAFE_INTEGER) {\r\n return add(int53, 1);\r\n }\r\n else if (max === SMALLEST_UNSAFE_INTEGER) {\r\n return add(upscaleWithinI53AndLoopCheck(min - 1, max - 1), 1);\r\n }\r\n else {\r\n return upscaleWithinI53AndLoopCheck(min, max);\r\n }\r\n}\n\nfunction isLeastBitTrue(engine) {\r\n return (engine.next() & 1) === 1;\r\n}\r\nfunction lessThan(distribution, value) {\r\n return engine => distribution(engine) < value;\r\n}\r\nfunction probability(percentage) {\r\n if (percentage <= 0) {\r\n return () => false;\r\n }\r\n else if (percentage >= 1) {\r\n return () => true;\r\n }\r\n else {\r\n const scaled = percentage * UINT32_SIZE;\r\n if (scaled % 1 === 0) {\r\n return lessThan(int32, (scaled - INT32_SIZE) | 0);\r\n }\r\n else {\r\n return lessThan(uint53, Math.round(percentage * SMALLEST_UNSAFE_INTEGER));\r\n }\r\n }\r\n}\r\nfunction bool(numerator, denominator) {\r\n if (denominator == null) {\r\n if (numerator == null) {\r\n return isLeastBitTrue;\r\n }\r\n return probability(numerator);\r\n }\r\n else {\r\n if (numerator <= 0) {\r\n return () => false;\r\n }\r\n else if (numerator >= denominator) {\r\n return () => true;\r\n }\r\n return lessThan(integer(0, denominator - 1), numerator);\r\n }\r\n}\n\n/**\r\n * Returns a Distribution that returns a random `Date` within the inclusive\r\n * range of [`start`, `end`].\r\n * @param start The minimum `Date`\r\n * @param end The maximum `Date`\r\n */\r\nfunction date(start, end) {\r\n const distribution = integer(+start, +end);\r\n return engine => new Date(distribution(engine));\r\n}\n\n/**\r\n * Returns a Distribution to return a value within [1, sideCount]\r\n * @param sideCount The number of sides of the die\r\n */\r\nfunction die(sideCount) {\r\n return integer(1, sideCount);\r\n}\n\n/**\r\n * Returns a distribution that returns an array of length `dieCount` of values\r\n * within [1, `sideCount`]\r\n * @param sideCount The number of sides of each die\r\n * @param dieCount The number of dice\r\n */\r\nfunction dice(sideCount, dieCount) {\r\n const distribution = die(sideCount);\r\n return engine => {\r\n const result = [];\r\n for (let i = 0; i < dieCount; ++i) {\r\n result.push(distribution(engine));\r\n }\r\n return result;\r\n };\r\n}\n\n// tslint:disable:unified-signatures\r\n// has 2**x chars, for faster uniform distribution\r\nconst DEFAULT_STRING_POOL = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-\";\r\nfunction string(pool = DEFAULT_STRING_POOL) {\r\n const poolLength = pool.length;\r\n if (!poolLength) {\r\n throw new Error(\"Expected pool not to be an empty string\");\r\n }\r\n const distribution = integer(0, poolLength - 1);\r\n return (engine, length) => {\r\n let result = \"\";\r\n for (let i = 0; i < length; ++i) {\r\n const j = distribution(engine);\r\n result += pool.charAt(j);\r\n }\r\n return result;\r\n };\r\n}\n\nconst LOWER_HEX_POOL = \"0123456789abcdef\";\r\nconst lowerHex = string(LOWER_HEX_POOL);\r\nconst upperHex = string(LOWER_HEX_POOL.toUpperCase());\r\n/**\r\n * Returns a Distribution that returns a random string comprised of numbers\r\n * or the characters `abcdef` (or `ABCDEF`) of length `length`.\r\n * @param length Length of the result string\r\n * @param uppercase Whether the string should use `ABCDEF` instead of `abcdef`\r\n */\r\nfunction hex(uppercase) {\r\n if (uppercase) {\r\n return upperHex;\r\n }\r\n else {\r\n return lowerHex;\r\n }\r\n}\n\nfunction convertSliceArgument(value, length) {\r\n if (value < 0) {\r\n return Math.max(value + length, 0);\r\n }\r\n else {\r\n return Math.min(value, length);\r\n }\r\n}\n\nfunction toInteger(value) {\r\n const num = +value;\r\n if (num < 0) {\r\n return Math.ceil(num);\r\n }\r\n else {\r\n return Math.floor(num);\r\n }\r\n}\n\n/**\r\n * Returns a random value within the provided `source` within the sliced\r\n * bounds of `begin` and `end`.\r\n * @param source an array of items to pick from\r\n * @param begin the beginning slice index (defaults to `0`)\r\n * @param end the ending slice index (defaults to `source.length`)\r\n */\r\nfunction pick(engine, source, begin, end) {\r\n const length = source.length;\r\n if (length === 0) {\r\n throw new RangeError(\"Cannot pick from an empty array\");\r\n }\r\n const start = begin == null ? 0 : convertSliceArgument(toInteger(begin), length);\r\n const finish = end === void 0 ? length : convertSliceArgument(toInteger(end), length);\r\n if (start >= finish) {\r\n throw new RangeError(`Cannot pick between bounds ${start} and ${finish}`);\r\n }\r\n const distribution = integer(start, finish - 1);\r\n return source[distribution(engine)];\r\n}\n\nfunction multiply(distribution, multiplier) {\r\n if (multiplier === 1) {\r\n return distribution;\r\n }\r\n else if (multiplier === 0) {\r\n return () => 0;\r\n }\r\n else {\r\n return engine => distribution(engine) * multiplier;\r\n }\r\n}\n\n/**\r\n * Returns a floating-point value within [0.0, 1.0)\r\n */\r\nfunction realZeroToOneExclusive(engine) {\r\n return uint53(engine) / SMALLEST_UNSAFE_INTEGER;\r\n}\n\n/**\r\n * Returns a floating-point value within [0.0, 1.0]\r\n */\r\nfunction realZeroToOneInclusive(engine) {\r\n return uint53Full(engine) / SMALLEST_UNSAFE_INTEGER;\r\n}\n\n/**\r\n * Returns a floating-point value within [min, max) or [min, max]\r\n * @param min The minimum floating-point value, inclusive.\r\n * @param max The maximum floating-point value.\r\n * @param inclusive If true, `max` will be inclusive.\r\n */\r\nfunction real(min, max, inclusive = false) {\r\n if (!isFinite(min)) {\r\n throw new RangeError(\"Expected min to be a finite number\");\r\n }\r\n else if (!isFinite(max)) {\r\n throw new RangeError(\"Expected max to be a finite number\");\r\n }\r\n return add(multiply(inclusive ? realZeroToOneInclusive : realZeroToOneExclusive, max - min), min);\r\n}\n\nconst sliceArray = Array.prototype.slice;\n\n/**\r\n * Shuffles an array in-place\r\n * @param engine The Engine to use when choosing random values\r\n * @param array The array to shuffle\r\n * @param downTo minimum index to shuffle. Only used internally.\r\n */\r\nfunction shuffle(engine, array, downTo = 0) {\r\n const length = array.length;\r\n if (length) {\r\n for (let i = (length - 1) >>> 0; i > downTo; --i) {\r\n const distribution = integer(0, i);\r\n const j = distribution(engine);\r\n if (i !== j) {\r\n const tmp = array[i];\r\n array[i] = array[j];\r\n array[j] = tmp;\r\n }\r\n }\r\n }\r\n return array;\r\n}\n\n/**\r\n * From the population array, produce an array with sampleSize elements that\r\n * are randomly chosen without repeats.\r\n * @param engine The Engine to use when choosing random values\r\n * @param population An array that has items to choose a sample from\r\n * @param sampleSize The size of the result array\r\n */\r\nfunction sample(engine, population, sampleSize) {\r\n if (sampleSize < 0 ||\r\n sampleSize > population.length ||\r\n !isFinite(sampleSize)) {\r\n throw new RangeError(\"Expected sampleSize to be within 0 and the length of the population\");\r\n }\r\n if (sampleSize === 0) {\r\n return [];\r\n }\r\n const clone = sliceArray.call(population);\r\n const length = clone.length;\r\n if (length === sampleSize) {\r\n return shuffle(engine, clone, 0);\r\n }\r\n const tailLength = length - sampleSize;\r\n return shuffle(engine, clone, tailLength - 1).slice(tailLength);\r\n}\n\nconst stringRepeat = (() => {\r\n try {\r\n if (\"x\".repeat(3) === \"xxx\") {\r\n return (pattern, count) => pattern.repeat(count);\r\n }\r\n }\r\n catch (_) {\r\n // nothing to do here\r\n }\r\n return (pattern, count) => {\r\n let result = \"\";\r\n while (count > 0) {\r\n if (count & 1) {\r\n result += pattern;\r\n }\r\n count >>= 1;\r\n pattern += pattern;\r\n }\r\n return result;\r\n };\r\n})();\n\nfunction zeroPad(text, zeroCount) {\r\n return stringRepeat(\"0\", zeroCount - text.length) + text;\r\n}\r\n/**\r\n * Returns a Universally Unique Identifier Version 4.\r\n *\r\n * See http://en.wikipedia.org/wiki/Universally_unique_identifier\r\n */\r\nfunction uuid4(engine) {\r\n const a = engine.next() >>> 0;\r\n const b = engine.next() | 0;\r\n const c = engine.next() | 0;\r\n const d = engine.next() >>> 0;\r\n return (zeroPad(a.toString(16), 8) +\r\n \"-\" +\r\n zeroPad((b & 0xffff).toString(16), 4) +\r\n \"-\" +\r\n zeroPad((((b >> 4) & 0x0fff) | 0x4000).toString(16), 4) +\r\n \"-\" +\r\n zeroPad(((c & 0x3fff) | 0x8000).toString(16), 4) +\r\n \"-\" +\r\n zeroPad(((c >> 4) & 0xffff).toString(16), 4) +\r\n zeroPad(d.toString(16), 8));\r\n}\n\n/**\r\n * An int32-producing Engine that uses `Math.random()`\r\n */\r\nconst nativeMath = {\r\n next() {\r\n return (Math.random() * UINT32_SIZE) | 0;\r\n }\r\n};\n\n// tslint:disable:unified-signatures\r\n/**\r\n * A wrapper around an Engine that provides easy-to-use methods for\r\n * producing values based on known distributions\r\n */\r\nclass Random {\r\n /**\r\n * Creates a new Random wrapper\r\n * @param engine The engine to use (defaults to a `Math.random`-based implementation)\r\n */\r\n constructor(engine = nativeMath) {\r\n this.engine = engine;\r\n }\r\n /**\r\n * Returns a value within [-0x80000000, 0x7fffffff]\r\n */\r\n int32() {\r\n return int32(this.engine);\r\n }\r\n /**\r\n * Returns a value within [0, 0xffffffff]\r\n */\r\n uint32() {\r\n return uint32(this.engine);\r\n }\r\n /**\r\n * Returns a value within [0, 0x1fffffffffffff]\r\n */\r\n uint53() {\r\n return uint53(this.engine);\r\n }\r\n /**\r\n * Returns a value within [0, 0x20000000000000]\r\n */\r\n uint53Full() {\r\n return uint53Full(this.engine);\r\n }\r\n /**\r\n * Returns a value within [-0x20000000000000, 0x1fffffffffffff]\r\n */\r\n int53() {\r\n return int53(this.engine);\r\n }\r\n /**\r\n * Returns a value within [-0x20000000000000, 0x20000000000000]\r\n */\r\n int53Full() {\r\n return int53Full(this.engine);\r\n }\r\n /**\r\n * Returns a value within [min, max]\r\n * @param min The minimum integer value, inclusive. No less than -0x20000000000000.\r\n * @param max The maximum integer value, inclusive. No greater than 0x20000000000000.\r\n */\r\n integer(min, max) {\r\n return integer(min, max)(this.engine);\r\n }\r\n /**\r\n * Returns a floating-point value within [0.0, 1.0]\r\n */\r\n realZeroToOneInclusive() {\r\n return realZeroToOneInclusive(this.engine);\r\n }\r\n /**\r\n * Returns a floating-point value within [0.0, 1.0)\r\n */\r\n realZeroToOneExclusive() {\r\n return realZeroToOneExclusive(this.engine);\r\n }\r\n /**\r\n * Returns a floating-point value within [min, max) or [min, max]\r\n * @param min The minimum floating-point value, inclusive.\r\n * @param max The maximum floating-point value.\r\n * @param inclusive If true, `max` will be inclusive.\r\n */\r\n real(min, max, inclusive = false) {\r\n return real(min, max, inclusive)(this.engine);\r\n }\r\n bool(numerator, denominator) {\r\n return bool(numerator, denominator)(this.engine);\r\n }\r\n /**\r\n * Return a random value within the provided `source` within the sliced\r\n * bounds of `begin` and `end`.\r\n * @param source an array of items to pick from\r\n * @param begin the beginning slice index (defaults to `0`)\r\n * @param end the ending slice index (defaults to `source.length`)\r\n */\r\n pick(source, begin, end) {\r\n return pick(this.engine, source, begin, end);\r\n }\r\n /**\r\n * Shuffles an array in-place\r\n * @param array The array to shuffle\r\n */\r\n shuffle(array) {\r\n return shuffle(this.engine, array);\r\n }\r\n /**\r\n * From the population array, returns an array with sampleSize elements that\r\n * are randomly chosen without repeats.\r\n * @param population An array that has items to choose a sample from\r\n * @param sampleSize The size of the result array\r\n */\r\n sample(population, sampleSize) {\r\n return sample(this.engine, population, sampleSize);\r\n }\r\n /**\r\n * Returns a value within [1, sideCount]\r\n * @param sideCount The number of sides of the die\r\n */\r\n die(sideCount) {\r\n return die(sideCount)(this.engine);\r\n }\r\n /**\r\n * Returns an array of length `dieCount` of values within [1, sideCount]\r\n * @param sideCount The number of sides of each die\r\n * @param dieCount The number of dice\r\n */\r\n dice(sideCount, dieCount) {\r\n return dice(sideCount, dieCount)(this.engine);\r\n }\r\n /**\r\n * Returns a Universally Unique Identifier Version 4.\r\n *\r\n * See http://en.wikipedia.org/wiki/Universally_unique_identifier\r\n */\r\n uuid4() {\r\n return uuid4(this.engine);\r\n }\r\n string(length, pool) {\r\n return string(pool)(this.engine, length);\r\n }\r\n /**\r\n * Returns a random string comprised of numbers or the characters `abcdef`\r\n * (or `ABCDEF`) of length `length`.\r\n * @param length Length of the result string\r\n * @param uppercase Whether the string should use `ABCDEF` instead of `abcdef`\r\n */\r\n hex(length, uppercase) {\r\n return hex(uppercase)(this.engine, length);\r\n }\r\n /**\r\n * Returns a random `Date` within the inclusive range of [`start`, `end`].\r\n * @param start The minimum `Date`\r\n * @param end The maximum `Date`\r\n */\r\n date(start, end) {\r\n return date(start, end)(this.engine);\r\n }\r\n}\n\n/**\r\n * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array\r\n */\r\nconst I32Array = (() => {\r\n try {\r\n const buffer = new ArrayBuffer(4);\r\n const view = new Int32Array(buffer);\r\n view[0] = INT32_SIZE;\r\n if (view[0] === -INT32_SIZE) {\r\n return Int32Array;\r\n }\r\n }\r\n catch (_) {\r\n // nothing to do here\r\n }\r\n return Array;\r\n})();\n\nlet data = null;\r\nconst COUNT = 128;\r\nlet index = COUNT;\r\n/**\r\n * An Engine that relies on the globally-available `crypto.getRandomValues`,\r\n * which is typically available in modern browsers.\r\n *\r\n * See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues\r\n *\r\n * If unavailable or otherwise non-functioning, then `browserCrypto` will\r\n * likely `throw` on the first call to `next()`.\r\n */\r\nconst browserCrypto = {\r\n next() {\r\n if (index >= COUNT) {\r\n if (data === null) {\r\n data = new I32Array(COUNT);\r\n }\r\n crypto.getRandomValues(data);\r\n index = 0;\r\n }\r\n return data[index++] | 0;\r\n }\r\n};\n\n/**\r\n * Returns an array of random int32 values, based on current time\r\n * and a random number engine\r\n *\r\n * @param engine an Engine to pull random values from, default `nativeMath`\r\n * @param length the length of the Array, minimum 1, default 16\r\n */\r\nfunction createEntropy(engine = nativeMath, length = 16) {\r\n const array = [];\r\n array.push(new Date().getTime() | 0);\r\n for (let i = 1; i < length; ++i) {\r\n array[i] = engine.next() | 0;\r\n }\r\n return array;\r\n}\n\n/**\r\n * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul\r\n */\r\nconst imul = (() => {\r\n try {\r\n if (Math.imul(UINT32_MAX, 5) === -5) {\r\n return Math.imul;\r\n }\r\n }\r\n catch (_) {\r\n // nothing to do here\r\n }\r\n const UINT16_MAX = 0xffff;\r\n return (a, b) => {\r\n const ah = (a >>> 16) & UINT16_MAX;\r\n const al = a & UINT16_MAX;\r\n const bh = (b >>> 16) & UINT16_MAX;\r\n const bl = b & UINT16_MAX;\r\n // the shift by 0 fixes the sign on the high part\r\n // the final |0 converts the unsigned value into a signed value\r\n return (al * bl + (((ah * bl + al * bh) << 16) >>> 0)) | 0;\r\n };\r\n})();\n\nconst ARRAY_SIZE = 624;\r\nconst ARRAY_MAX = ARRAY_SIZE - 1;\r\nconst M = 397;\r\nconst ARRAY_SIZE_MINUS_M = ARRAY_SIZE - M;\r\nconst A = 0x9908b0df;\r\n/**\r\n * An Engine that is a pseudorandom number generator using the Mersenne\r\n * Twister algorithm based on the prime 2**19937 − 1\r\n *\r\n * See http://en.wikipedia.org/wiki/Mersenne_twister\r\n */\r\nclass MersenneTwister19937 {\r\n /**\r\n * MersenneTwister19937 should not be instantiated directly.\r\n * Instead, use the static methods `seed`, `seedWithArray`, or `autoSeed`.\r\n */\r\n constructor() {\r\n this.data = new I32Array(ARRAY_SIZE);\r\n this.index = 0; // integer within [0, 624]\r\n this.uses = 0;\r\n }\r\n /**\r\n * Returns a MersenneTwister19937 seeded with an initial int32 value\r\n * @param initial the initial seed value\r\n */\r\n static seed(initial) {\r\n return new MersenneTwister19937().seed(initial);\r\n }\r\n /**\r\n * Returns a MersenneTwister19937 seeded with zero or more int32 values\r\n * @param source A series of int32 values\r\n */\r\n static seedWithArray(source) {\r\n return new MersenneTwister19937().seedWithArray(source);\r\n }\r\n /**\r\n * Returns a MersenneTwister19937 seeded with the current time and\r\n * a series of natively-generated random values\r\n */\r\n static autoSeed() {\r\n return MersenneTwister19937.seedWithArray(createEntropy());\r\n }\r\n /**\r\n * Returns the next int32 value of the sequence\r\n */\r\n next() {\r\n if ((this.index | 0) >= ARRAY_SIZE) {\r\n refreshData(this.data);\r\n this.index = 0;\r\n }\r\n const value = this.data[this.index];\r\n this.index = (this.index + 1) | 0;\r\n this.uses += 1;\r\n return temper(value) | 0;\r\n }\r\n /**\r\n * Returns the number of times that the Engine has been used.\r\n *\r\n * This can be provided to an unused MersenneTwister19937 with the same\r\n * seed, bringing it to the exact point that was left off.\r\n */\r\n getUseCount() {\r\n return this.uses;\r\n }\r\n /**\r\n * Discards one or more items from the engine\r\n * @param count The count of items to discard\r\n */\r\n discard(count) {\r\n if (count <= 0) {\r\n return this;\r\n }\r\n this.uses += count;\r\n if ((this.index | 0) >= ARRAY_SIZE) {\r\n refreshData(this.data);\r\n this.index = 0;\r\n }\r\n while (count + this.index > ARRAY_SIZE) {\r\n count -= ARRAY_SIZE - this.index;\r\n refreshData(this.data);\r\n this.index = 0;\r\n }\r\n this.index = (this.index + count) | 0;\r\n return this;\r\n }\r\n seed(initial) {\r\n let previous = 0;\r\n this.data[0] = previous = initial | 0;\r\n for (let i = 1; i < ARRAY_SIZE; i = (i + 1) | 0) {\r\n this.data[i] = previous =\r\n (imul(previous ^ (previous >>> 30), 0x6c078965) + i) | 0;\r\n }\r\n this.index = ARRAY_SIZE;\r\n this.uses = 0;\r\n return this;\r\n }\r\n seedWithArray(source) {\r\n this.seed(0x012bd6aa);\r\n seedWithArray(this.data, source);\r\n return this;\r\n }\r\n}\r\nfunction refreshData(data) {\r\n let k = 0;\r\n let tmp = 0;\r\n for (; (k | 0) < ARRAY_SIZE_MINUS_M; k = (k + 1) | 0) {\r\n tmp = (data[k] & INT32_SIZE) | (data[(k + 1) | 0] & INT32_MAX);\r\n data[k] = data[(k + M) | 0] ^ (tmp >>> 1) ^ (tmp & 0x1 ? A : 0);\r\n }\r\n for (; (k | 0) < ARRAY_MAX; k = (k + 1) | 0) {\r\n tmp = (data[k] & INT32_SIZE) | (data[(k + 1) | 0] & INT32_MAX);\r\n data[k] =\r\n data[(k - ARRAY_SIZE_MINUS_M) | 0] ^ (tmp >>> 1) ^ (tmp & 0x1 ? A : 0);\r\n }\r\n tmp = (data[ARRAY_MAX] & INT32_SIZE) | (data[0] & INT32_MAX);\r\n data[ARRAY_MAX] = data[M - 1] ^ (tmp >>> 1) ^ (tmp & 0x1 ? A : 0);\r\n}\r\nfunction temper(value) {\r\n value ^= value >>> 11;\r\n value ^= (value << 7) & 0x9d2c5680;\r\n value ^= (value << 15) & 0xefc60000;\r\n return value ^ (value >>> 18);\r\n}\r\nfunction seedWithArray(data, source) {\r\n let i = 1;\r\n let j = 0;\r\n const sourceLength = source.length;\r\n let k = Math.max(sourceLength, ARRAY_SIZE) | 0;\r\n let previous = data[0] | 0;\r\n for (; (k | 0) > 0; --k) {\r\n data[i] = previous =\r\n ((data[i] ^ imul(previous ^ (previous >>> 30), 0x0019660d)) +\r\n (source[j] | 0) +\r\n (j | 0)) |\r\n 0;\r\n i = (i + 1) | 0;\r\n ++j;\r\n if ((i | 0) > ARRAY_MAX) {\r\n data[0] = data[ARRAY_MAX];\r\n i = 1;\r\n }\r\n if (j >= sourceLength) {\r\n j = 0;\r\n }\r\n }\r\n for (k = ARRAY_MAX; (k | 0) > 0; --k) {\r\n data[i] = previous =\r\n ((data[i] ^ imul(previous ^ (previous >>> 30), 0x5d588b65)) - i) | 0;\r\n i = (i + 1) | 0;\r\n if ((i | 0) > ARRAY_MAX) {\r\n data[0] = data[ARRAY_MAX];\r\n i = 1;\r\n }\r\n }\r\n data[0] = INT32_SIZE;\r\n}\n\nlet data$1 = null;\r\nconst COUNT$1 = 128;\r\nlet index$1 = COUNT$1;\r\n/**\r\n * An Engine that relies on the node-available\r\n * `require('crypto').randomBytes`, which has been available since 0.58.\r\n *\r\n * See https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback\r\n *\r\n * If unavailable or otherwise non-functioning, then `nodeCrypto` will\r\n * likely `throw` on the first call to `next()`.\r\n */\r\nconst nodeCrypto = {\r\n next() {\r\n if (index$1 >= COUNT$1) {\r\n data$1 = new Int32Array(new Int8Array(require(\"crypto\").randomBytes(4 * COUNT$1)).buffer);\r\n index$1 = 0;\r\n }\r\n return data$1[index$1++] | 0;\r\n }\r\n};\n\n/**\r\n * Returns a Distribution to random value within the provided `source`\r\n * within the sliced bounds of `begin` and `end`.\r\n * @param source an array of items to pick from\r\n * @param begin the beginning slice index (defaults to `0`)\r\n * @param end the ending slice index (defaults to `source.length`)\r\n */\r\nfunction picker(source, begin, end) {\r\n const clone = sliceArray.call(source, begin, end);\r\n if (clone.length === 0) {\r\n throw new RangeError(`Cannot pick from a source with no items`);\r\n }\r\n const distribution = integer(0, clone.length - 1);\r\n return engine => clone[distribution(engine)];\r\n}\n\nexport { Random, browserCrypto, nativeMath, MersenneTwister19937, nodeCrypto, bool, date, dice, die, hex, int32, int53, int53Full, integer, pick, picker, real, realZeroToOneExclusive, realZeroToOneInclusive, sample, shuffle, string, uint32, uint53, uint53Full, uuid4, createEntropy };\n//# sourceMappingURL=random-js.esm.js.map\n","import * as 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(\n trainingSet,\n trainingValue,\n seed,\n) {\n let engine;\n let distribution = Random.integer(0, trainingSet.rows - 1);\n if (seed === undefined) {\n engine = Random.MersenneTwister19937.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = Random.MersenneTwister19937.seed(seed);\n } else {\n throw new RangeError(\n `Expected seed must be undefined or integer not ${seed}`,\n );\n }\n\n let Xr = new Array(trainingSet.rows);\n let yr = new Array(trainingSet.rows);\n\n for (let i = 0; i < trainingSet.rows; ++i) {\n let index = distribution(engine);\n Xr[i] = trainingSet.getRow(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 'N should be less or equal to the number of columns of X',\n );\n }\n\n let distribution = Random.integer(0, trainingSet.columns - 1);\n let engine;\n if (seed === undefined) {\n engine = Random.MersenneTwister19937.autoSeed();\n } else if (Number.isInteger(seed)) {\n engine = Random.MersenneTwister19937.seed(seed);\n } else {\n throw new RangeError(\n `Expected seed must be undefined or integer not ${seed}`,\n );\n }\n\n let toRet = new Matrix(trainingSet.rows, n);\n\n let usedIndex;\n let index;\n if (replacement) {\n usedIndex = new Array(n);\n for (let i = 0; i < n; ++i) {\n 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 (let 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 {\n Matrix,\n WrapperMatrix2D,\n MatrixTransposeView,\n MatrixColumnSelectionView,\n} 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 let 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(\n `The maxFeatures parameter should be less than ${trainingSet.columns}`,\n );\n } else {\n this.n = this.maxFeatures;\n }\n } else {\n throw new RangeError(\n `Cannot process the maxFeatures parameter ${this.maxFeatures}`,\n );\n }\n\n let Estimator;\n if (this.isClassifier) {\n 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 (let i = 0; i < this.nEstimators; ++i) {\n let res = this.useSampleBagging\n ? Utils.examplesBaggingWithReplacement(\n trainingSet,\n trainingValues,\n this.seed,\n )\n : { X: trainingSet, y: trainingValues };\n let X = res.X;\n let 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 let predictionValues = new Array(this.nEstimators);\n toPredict = Matrix.checkMatrix(toPredict);\n for (let i = 0; i < this.nEstimators; ++i) {\n let X = new MatrixColumnSelectionView(toPredict, this.indexes[i]); // get features for estimator\n predictionValues[i] = this.estimators[i].predict(X);\n }\n\n predictionValues = new MatrixTransposeView(\n new WrapperMatrix2D(predictionValues),\n );\n let predictions = new Array(predictionValues.rows);\n for (let 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 let 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\n .sort(\n (a, b) =>\n arr.filter((v) => v === a).length - arr.filter((v) => v === b).length,\n )\n .pop();\n}\n","const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\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","import isArray from 'is-any-array';\nimport quickSelectMedian from 'median-quickselect';\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","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 (\n !(\n options.selectionMethod === 'mean' ||\n options.selectionMethod === 'median'\n )\n ) {\n throw new RangeError(\n `Unsupported selection method ${options.selectionMethod}`,\n );\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 let 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","import { Matrix, MatrixTransposeView, EVD, SVD, NIPALS } from 'ml-matrix';\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 {string} [options.method='SVD'] - select which method to use: SVD (default), covarianceMatrirx or NIPALS.\n * @param {number} [options.nCompNIPALS=2] - number of components to be computed with NIPALS.\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 * @param {boolean} [options.ignoreZeroVariance=false] - ignore columns with zero variance if `scale` is `true`.\n * */\nexport class 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 this.R = model.R;\n this.excludedFeatures = model.excludedFeatures || [];\n return;\n }\n\n dataset = new Matrix(dataset);\n\n const {\n isCovarianceMatrix = false,\n method = 'SVD',\n nCompNIPALS = 2,\n center = true,\n scale = false,\n ignoreZeroVariance = false,\n } = options;\n\n this.center = center;\n this.scale = scale;\n this.means = null;\n this.stdevs = null;\n this.excludedFeatures = [];\n\n if (isCovarianceMatrix) {\n // User provided a covariance matrix instead of dataset.\n this._computeFromCovarianceMatrix(dataset);\n return;\n }\n\n this._adjust(dataset, ignoreZeroVariance);\n switch (method) {\n case 'covarianceMatrix': {\n // User provided a dataset but wants us to compute and use the covariance matrix.\n const covarianceMatrix = new MatrixTransposeView(dataset)\n .mmul(dataset)\n .div(dataset.rows - 1);\n this._computeFromCovarianceMatrix(covarianceMatrix);\n break;\n }\n case 'NIPALS': {\n this._computeWithNIPALS(dataset, nCompNIPALS);\n break;\n }\n case 'SVD': {\n const 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 = [];\n for (const singularValue of singularValues) {\n eigenvalues.push((singularValue * singularValue) / (dataset.rows - 1));\n }\n this.S = eigenvalues;\n break;\n }\n default: {\n throw new Error(`unknown method: ${method}`);\n }\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 (typeof model.name !== 'string') {\n throw new TypeError('model must have a name property');\n }\n if (model.name !== 'PCA') {\n throw new RangeError(`invalid model: ${model.name}`);\n }\n return new PCA(true, model);\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 { nComponents = this.U.columns } = options;\n dataset = new Matrix(dataset);\n if (this.center) {\n dataset.subRowVector(this.means);\n if (this.scale) {\n for (let i of this.excludedFeatures) {\n dataset.removeColumn(i);\n }\n dataset.divRowVector(this.stdevs);\n }\n }\n var predictions = dataset.mmul(this.U);\n return predictions.subMatrix(0, predictions.rows - 1, 0, nComponents - 1);\n }\n\n /**\n * Calculates the inverse PCA transform\n * @param {Matrix} dataset\n * @return {Matrix} dataset projected in the PCA space\n */\n invert(dataset) {\n dataset = Matrix.checkMatrix(dataset);\n\n var inverse = dataset.mmul(this.U.transpose());\n\n if (this.center) {\n if (this.scale) {\n inverse.mulRowVector(this.stdevs);\n }\n inverse.addRowVector(this.means);\n }\n\n return inverse;\n }\n\n\n /**\n * Returns the proportion of variance for each component\n * @return {[number]}\n */\n getExplainedVariance() {\n var sum = 0;\n for (const s of this.S) {\n sum += s;\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 excludedFeatures: this.excludedFeatures,\n };\n }\n\n _adjust(dataset, ignoreZeroVariance) {\n if (this.center) {\n const mean = dataset.mean('column');\n const stdevs = this.scale\n ? dataset.standardDeviation('column', { mean })\n : null;\n this.means = mean;\n dataset.subRowVector(mean);\n if (this.scale) {\n for (let i = 0; i < stdevs.length; i++) {\n if (stdevs[i] === 0) {\n if (ignoreZeroVariance) {\n dataset.removeColumn(i);\n stdevs.splice(i, 1);\n this.excludedFeatures.push(i);\n i--;\n } else {\n throw new RangeError(\n `Cannot scale the dataset (standard deviation is zero at index ${i}`,\n );\n }\n }\n }\n this.stdevs = stdevs;\n dataset.divRowVector(stdevs);\n }\n }\n }\n\n _computeFromCovarianceMatrix(dataset) {\n const evd = new EVD(dataset, { assumeSymmetric: true });\n this.U = evd.eigenvectorMatrix;\n this.U.flipRows();\n this.S = evd.realEigenvalues;\n this.S.reverse();\n }\n\n _computeWithNIPALS(dataset, nCompNIPALS) {\n this.U = new Matrix(nCompNIPALS, dataset.columns);\n this.S = [];\n\n let x = dataset;\n for (let i = 0; i < nCompNIPALS; i++) {\n let dc = new NIPALS(x);\n\n this.U.setRow(i, dc.w.transpose());\n this.S.push(Math.pow(dc.s.get(0, 0), 2));\n\n x = dc.xResidual;\n }\n this.U = this.U.transpose(); // to be compatible with API\n }\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","/**\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 distance/similarity matrix. The matrix is square and has a size equal to the length of\n * the data array\n */\nexport default function distanceMatrix(data, distanceFn) {\n const result = getMatrix(data.length);\n\n // Compute upper distance matrix\n for (let i = 0; i < data.length; i++) {\n for (let j = 0; j <= i; j++) {\n result[i][j] = distanceFn(data[i], data[j]);\n result[j][i] = result[i][j];\n }\n }\n\n return result;\n}\n\nfunction getMatrix(size) {\n const matrix = [];\n for (let i = 0; i < size; i++) {\n const row = [];\n matrix.push(row);\n for (let j = 0; j < size; j++) {\n row.push(0);\n }\n }\n return matrix;\n}\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","module.exports = require('./lib/heap');\n","import Heap from 'heap';\n\nexport default class Cluster {\n constructor() {\n this.children = [];\n this.height = 0;\n this.size = 1;\n this.index = -1;\n this.isLeaf = false;\n }\n\n /**\n * Creates an array of clusters where the maximum height is smaller than the threshold\n * @param {number} threshold\n * @return {Array}\n */\n cut(threshold) {\n if (typeof threshold !== 'number') {\n throw new TypeError('threshold must be a number');\n }\n if (threshold < 0) {\n throw new RangeError('threshold must be a positive number');\n }\n let list = [this];\n const ans = [];\n while (list.length > 0) {\n const aux = list.shift();\n if (threshold >= aux.height) {\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 `groups` number of clusters.\n * @param {number} groups - Them number of children the first level of the tree should have.\n * @return {Cluster}\n */\n group(groups) {\n if (!Number.isInteger(groups) || groups < 1) {\n throw new RangeError('groups must be a positive integer');\n }\n\n const heap = new Heap((a, b) => {\n return b.height - a.height;\n });\n\n heap.push(this);\n\n while (heap.size() < groups) {\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.height = this.height;\n\n return root;\n }\n\n /**\n * Traverses the tree depth-first and calls the provided callback with each individual node\n * @param {function} cb - The callback to be called on each node encounter\n */\n traverse(cb) {\n function visit(root, callback) {\n callback(root);\n if (root.children) {\n for (const child of root.children) {\n visit(child, callback);\n }\n }\n }\n visit(this, cb);\n }\n\n /**\n * Returns a list of indices for all the leaves of this cluster.\n * The list is ordered in such a way that a dendrogram could be drawn without crossing branches.\n * @returns {Array}\n */\n indices() {\n const result = [];\n this.traverse((cluster) => {\n if (cluster.isLeaf) {\n result.push(cluster.index);\n }\n });\n return result;\n }\n}\n","import { euclidean } from 'ml-distance-euclidean';\nimport getDistanceMatrix from 'ml-distance-matrix';\nimport { Matrix } from 'ml-matrix';\n\nimport Cluster from './Cluster';\n\nfunction singleLink(dKI, dKJ) {\n return Math.min(dKI, dKJ);\n}\n\nfunction completeLink(dKI, dKJ) {\n return Math.max(dKI, dKJ);\n}\n\nfunction averageLink(dKI, dKJ, dIJ, ni, nj) {\n const ai = ni / (ni + nj);\n const aj = nj / (ni + nj);\n return ai * dKI + aj * dKJ;\n}\n\nfunction weightedAverageLink(dKI, dKJ) {\n return (dKI + dKJ) / 2;\n}\n\nfunction centroidLink(dKI, dKJ, dIJ, ni, nj) {\n const ai = ni / (ni + nj);\n const aj = nj / (ni + nj);\n const b = -(ni * nj) / (ni + nj) ** 2;\n return ai * dKI + aj * dKJ + b * dIJ;\n}\n\nfunction medianLink(dKI, dKJ, dIJ) {\n return dKI / 2 + dKJ / 2 - dIJ / 4;\n}\n\nfunction wardLink(dKI, dKJ, dIJ, ni, nj, nk) {\n const ai = (ni + nk) / (ni + nj + nk);\n const aj = (nj + nk) / (ni + nj + nk);\n const b = -nk / (ni + nj + nk);\n return ai * dKI + aj * dKJ + b * dIJ;\n}\n\nfunction wardLink2(dKI, dKJ, dIJ, ni, nj, nk) {\n const ai = (ni + nk) / (ni + nj + nk);\n const aj = (nj + nk) / (ni + nj + nk);\n const b = -nk / (ni + nj + nk);\n return Math.sqrt(ai * dKI * dKI + aj * dKJ * dKJ + b * dIJ * dIJ);\n}\n\n/**\n * Continuously merge nodes that have the least dissimilarity\n * @param {Array>} data - Array of points to be clustered\n * @param {object} [options]\n * @param {Function} [options.distanceFunction]\n * @param {string} [options.method] - Default: `'complete'`\n * @param {boolean} [options.isDistanceMatrix] - Is the input already a distance matrix?\n * @constructor\n */\nexport function agnes(data, options = {}) {\n const {\n distanceFunction = euclidean,\n method = 'complete',\n isDistanceMatrix = false,\n } = options;\n\n let updateFunc;\n if (!isDistanceMatrix) {\n data = getDistanceMatrix(data, distanceFunction);\n }\n let distanceMatrix = new Matrix(data);\n const numLeaves = distanceMatrix.rows;\n\n // allows to use a string or a given function\n if (typeof method === 'string') {\n switch (method.toLowerCase()) {\n case 'single':\n updateFunc = singleLink;\n break;\n case 'complete':\n updateFunc = completeLink;\n break;\n case 'average':\n case 'upgma':\n updateFunc = averageLink;\n break;\n case 'wpgma':\n updateFunc = weightedAverageLink;\n break;\n case 'centroid':\n case 'upgmc':\n updateFunc = centroidLink;\n break;\n case 'median':\n case 'wpgmc':\n updateFunc = medianLink;\n break;\n case 'ward':\n updateFunc = wardLink;\n break;\n case 'ward2':\n updateFunc = wardLink2;\n break;\n default:\n throw new RangeError(`unknown clustering method: ${method}`);\n }\n } else if (typeof method !== 'function') {\n throw new TypeError('method must be a string or function');\n }\n\n let clusters = [];\n for (let i = 0; i < numLeaves; i++) {\n const cluster = new Cluster();\n cluster.isLeaf = true;\n cluster.index = i;\n clusters.push(cluster);\n }\n\n for (let n = 0; n < numLeaves - 1; n++) {\n const [row, column, distance] = getSmallestDistance(distanceMatrix);\n const cluster1 = clusters[row];\n const cluster2 = clusters[column];\n const newCluster = new Cluster();\n newCluster.size = cluster1.size + cluster2.size;\n newCluster.children.push(cluster1, cluster2);\n newCluster.height = distance;\n\n const newClusters = [newCluster];\n const newDistanceMatrix = new Matrix(\n distanceMatrix.rows - 1,\n distanceMatrix.rows - 1,\n );\n const previous = (newIndex) =>\n getPreviousIndex(newIndex, Math.min(row, column), Math.max(row, column));\n\n for (let i = 1; i < newDistanceMatrix.rows; i++) {\n const prevI = previous(i);\n const prevICluster = clusters[prevI];\n newClusters.push(prevICluster);\n for (let j = 0; j < i; j++) {\n if (j === 0) {\n const dKI = distanceMatrix.get(row, prevI);\n const dKJ = distanceMatrix.get(prevI, column);\n const val = updateFunc(\n dKI,\n dKJ,\n distance,\n cluster1.size,\n cluster2.size,\n prevICluster.size,\n );\n newDistanceMatrix.set(i, j, val);\n newDistanceMatrix.set(j, i, val);\n } else {\n // Just copy distance from previous matrix\n const val = distanceMatrix.get(prevI, previous(j));\n newDistanceMatrix.set(i, j, val);\n newDistanceMatrix.set(j, i, val);\n }\n }\n }\n\n clusters = newClusters;\n distanceMatrix = newDistanceMatrix;\n }\n\n return clusters[0];\n}\n\nfunction getSmallestDistance(distance) {\n let smallest = Infinity;\n let smallestI = 0;\n let smallestJ = 0;\n for (let i = 1; i < distance.rows; i++) {\n for (let j = 0; j < i; j++) {\n if (distance.get(i, j) < smallest) {\n smallest = distance.get(i, j);\n smallestI = i;\n smallestJ = j;\n }\n }\n }\n return [smallestI, smallestJ, smallest];\n}\n\nfunction getPreviousIndex(newIndex, prev1, prev2) {\n newIndex -= 1;\n if (newIndex >= prev1) newIndex++;\n if (newIndex >= prev2) newIndex++;\n return newIndex;\n}\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","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","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","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.rows;\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.getRow(firstCenterIdx));\n\n // Init closest distances\n let closestDistSquared = new Matrix(1, X.rows);\n for (let i = 0; i < X.rows; i++) {\n closestDistSquared.set(0, i, squaredEuclidean(X.getRow(i), centers[0]));\n }\n let cumSumClosestDistSquared = [cumSum(closestDistSquared.getRow(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.columns));\n const distanceToCandidates = euclideanDistances(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.getRow(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.getRow(bestCandidate);\n closestDistSquared = bestDistSquared;\n cumSumClosestDistSquared = [cumSum(closestDistSquared.getRow(0))];\n probabilities = Matrix.mul(\n closestDistSquared,\n 1 / cumSumClosestDistSquared[0][nSamples - 1]\n );\n }\n return centers;\n}\n\nfunction euclideanDistances(A, B) {\n const result = new Matrix(A.rows, B.rows);\n for (let i = 0; i < A.rows; i++) {\n for (let j = 0; j < B.rows; 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 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';\n\nimport { separateClasses } from './utils';\n\nexport class GaussianNB {\n /**\n * Constructor for the Gaussian Naive Bayes classifier, the parameters here is just for loading purposes.\n * @constructor\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);\n\n if (trainingSet.rows !== trainingLabels.length) {\n throw new RangeError(\n 'the size of the training set and the training labels must be the same.'\n );\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 = separatedClasses[i].mean('column');\n var std = separatedClasses[i].standardDeviation('column', {\n mean: means\n });\n\n var logPriorProbability = Math.log(\n separatedClasses[i].rows / trainingSet.rows\n );\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] = [\n 1 / (C1 * currentStd),\n -2 * currentStd * currentStd\n ];\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 dataset = Matrix.checkMatrix(dataset);\n if (dataset.rows === this.calculateProbabilities[0].length) {\n throw new RangeError(\n 'the dataset must have the same features as the training set'\n );\n }\n\n var predictions = new Array(dataset.rows);\n\n for (var i = 0; i < predictions.length; ++i) {\n predictions[i] = getCurrentClass(\n dataset.getRow(i),\n this.means,\n this.calculateProbabilities\n );\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(\n 'The current model is not a Multinomial Naive Bayes, current model:',\n model.name\n );\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(\n currentCase[j - 1],\n mean[i][j - 1],\n classes[i][j][0],\n classes[i][j][1]\n );\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';\n\nimport { separateClasses } from './utils';\n\nexport class MultinomialNB {\n /**\n * Constructor for Multinomial Naive Bayes, the model parameter is for load purposes.\n * @constructor\n * @param {object} model - for load purposes.\n */\n constructor(model) {\n if (model) {\n this.conditionalProbability = Matrix.checkMatrix(\n model.conditionalProbability\n );\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(\n 'the size of the training set and the training labels must be the same.'\n );\n }\n\n var separateClass = separateClasses(trainingSet, trainingLabels);\n\n this.priorProbability = new Matrix(separateClass.length, 1);\n\n for (var i = 0; i < separateClass.length; ++i) {\n this.priorProbability.set(i, 0, Math.log(\n separateClass[i].rows / trainingSet.rows\n ));\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(\n i,\n Matrix.rowVector(classValues\n .sum('column'))\n .add(1)\n .div(divisor)\n .apply(matrixLog)\n );\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 const v = Matrix.columnVector(this.conditionalProbability\n .clone()\n .mulRowVector(currentElement)\n .sum('row'));\n predictions[i] = v\n .add(this.priorProbability)\n .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.set(i, j, Math.log(this.get(i, j)));\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(function (e) {\n return -e[1];\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, linearDistance, otherChild, 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 (\n bestNodes.size() < maxNodes ||\n Math.abs(linearDistance) < bestNodes.peek()[1]\n ) {\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 {\n // 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 { euclidean as euclideanDistance } from 'ml-distance-euclidean';\n\nimport KDTree from './KDTree';\n\nexport default class KNN {\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 { distance = euclideanDistance, k = classes.size + 1 } = 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(\n 'a custom distance function was used to create the model. Please provide it again'\n );\n }\n if (model.isEuclidean && distance !== euclideanDistance) {\n throw new Error(\n 'the model was created with the default distance function. Do not load it with another one'\n );\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 (\n Array.isArray(dataset[0]) &&\n typeof dataset[0][0] === 'number'\n ) {\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","import Matrix from 'ml-matrix';\n\n/**\n * @private\n * Function that given vector, returns its norm\n * @param {Vector} X\n * @return {number} Norm of the vector\n */\nexport function norm(X) {\n return Math.sqrt(\n X.clone()\n .apply(pow2array)\n .sum(),\n );\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.set(i, j, this.get(i, j) ** 2);\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 let means = dataset.mean('column');\n let std = dataset.standardDeviation('column', {\n mean: means,\n unbiased: true,\n });\n let 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 (let i = 0; i < array.length; ++i) {\n for (let j = 0; j < array[i].length; ++j) {\n let elem = array[i][j];\n array[i][j] = elem !== null ? new Matrix(array[i][j]) : undefined;\n }\n }\n } else {\n for (let 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';\n\nimport * as Utils from './util/utils';\n\n/**\n * @class PLS\n */\nexport class PLS {\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 let { tolerance = 1e-5, scale = true } = 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(\n 'The number of X rows must be equal to the number of Y rows',\n );\n }\n\n this.meanX = trainingSet.mean('column');\n this.stdDevX = trainingSet.standardDeviation('column', {\n mean: this.meanX,\n unbiased: true,\n });\n this.meanY = trainingValues.mean('column');\n this.stdDevY = trainingValues.standardDeviation('column', {\n mean: this.meanY,\n unbiased: true,\n });\n\n if (this.scale) {\n trainingSet = trainingSet\n .clone()\n .subRowVector(this.meanX)\n .divRowVector(this.stdDevX);\n trainingValues = trainingValues\n .clone()\n .subRowVector(this.meanY)\n .divRowVector(this.stdDevY);\n }\n\n if (this.latentVectors === undefined) {\n this.latentVectors = Math.min(trainingSet.rows - 1, trainingSet.columns);\n }\n\n let rx = trainingSet.rows;\n let cx = trainingSet.columns;\n let ry = trainingValues.rows;\n let cy = trainingValues.columns;\n\n let ssqXcal = trainingSet\n .clone()\n .mul(trainingSet)\n .sum(); // for the r²\n let sumOfSquaresY = trainingValues\n .clone()\n .mul(trainingValues)\n .sum();\n\n let tolerance = this.tolerance;\n let n = this.latentVectors;\n let T = Matrix.zeros(rx, n);\n let P = Matrix.zeros(cx, n);\n let U = Matrix.zeros(ry, n);\n let Q = Matrix.zeros(cy, n);\n let B = Matrix.zeros(n, n);\n let W = P.clone();\n let k = 0;\n let t;\n let w;\n let q;\n let p;\n\n while (Utils.norm(trainingValues) > tolerance && k < n) {\n let transposeX = trainingSet.transpose();\n let transposeY = trainingValues.transpose();\n\n let tIndex = maxSumColIndex(trainingSet.clone().mul(trainingSet));\n let uIndex = maxSumColIndex(trainingValues.clone().mul(trainingValues));\n\n let t1 = trainingSet.getColumnVector(tIndex);\n let u = trainingValues.getColumnVector(uIndex);\n t = Matrix.zeros(rx, 1);\n\n while (Utils.norm(t1.clone().sub(t)) > tolerance) {\n w = transposeX.mmul(u);\n w.div(Utils.norm(w));\n t = t1;\n t1 = trainingSet.mmul(w);\n q = transposeY.mmul(t1);\n q.div(Utils.norm(q));\n u = trainingValues.mmul(q);\n }\n\n t = t1;\n let num = transposeX.mmul(t);\n let den = t\n .transpose()\n .mmul(t)\n .get(0, 0);\n p = num.div(den);\n let 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\n .transpose()\n .mmul(t)\n .get(0, 0);\n let b = num.div(den).get(0, 0);\n trainingSet.sub(t.mmul(p.transpose()));\n trainingValues.sub(\n t\n .clone()\n .mul(b)\n .mmul(q.transpose()),\n );\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.set(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 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\n .transpose()\n .mmul(t)\n .mmul(p.transpose().mmul(p))\n .div(ssqXcal)\n .get(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 let X = Matrix.checkMatrix(dataset);\n if (this.scale) {\n X = X.subRowVector(this.meanX).divRowVector(this.stdDevX);\n }\n let 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 Matrix.rowVector(data.sum('column')).maxIndex()[0];\n}\n","import { Matrix, SingularValueDecomposition, inverse } from 'ml-matrix';\n\nimport { initializeMatrices } from './util/utils';\n\n/**\n * @class KOPLS\n */\nexport class KOPLS {\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(\n model.TURegressionCoeff,\n false,\n );\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 let kernelX = this.kernel.compute(trainingSet);\n\n let Identity = Matrix.eye(kernelX.rows, kernelX.rows, 1);\n let temp = kernelX;\n kernelX = new Array(this.orthogonalComp + 1);\n for (let i = 0; i < this.orthogonalComp + 1; i++) {\n kernelX[i] = new Array(this.orthogonalComp + 1);\n }\n kernelX[0][0] = temp;\n\n let result = new SingularValueDecomposition(\n trainingValues\n .transpose()\n .mmul(kernelX[0][0])\n .mmul(trainingValues),\n {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: false,\n },\n );\n let YLoadingMat = result.leftSingularVectors;\n let Sigma = result.diagonalMatrix;\n\n YLoadingMat = YLoadingMat.subMatrix(\n 0,\n YLoadingMat.rows - 1,\n 0,\n this.predictiveComp - 1,\n );\n Sigma = Sigma.subMatrix(\n 0,\n this.predictiveComp - 1,\n 0,\n this.predictiveComp - 1,\n );\n\n let YScoreMat = trainingValues.mmul(YLoadingMat);\n\n let predScoreMat = new Array(this.orthogonalComp + 1);\n let TURegressionCoeff = new Array(this.orthogonalComp + 1);\n let YOrthScoreMat = new Array(this.orthogonalComp);\n let YOrthLoadingVec = new Array(this.orthogonalComp);\n let YOrthEigen = new Array(this.orthogonalComp);\n let YOrthScoreNorm = new Array(this.orthogonalComp);\n\n let SigmaPow = Matrix.pow(Sigma, -0.5);\n // to avoid errors, check infinity\n SigmaPow.apply(function(i, j) {\n if (this.get(i, j) === Infinity) {\n this.set(i, j, 0);\n }\n });\n\n for (let i = 0; i < this.orthogonalComp; ++i) {\n predScoreMat[i] = kernelX[0][i]\n .transpose()\n .mmul(YScoreMat)\n .mmul(SigmaPow);\n\n let TpiPrime = predScoreMat[i].transpose();\n TURegressionCoeff[i] = inverse(TpiPrime.mmul(predScoreMat[i]))\n .mmul(TpiPrime)\n .mmul(YScoreMat);\n\n result = new SingularValueDecomposition(\n TpiPrime.mmul(\n Matrix.sub(kernelX[i][i], predScoreMat[i].mmul(TpiPrime)),\n ).mmul(predScoreMat[i]),\n {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: false,\n },\n );\n let CoTemp = result.leftSingularVectors;\n let SoTemp = result.diagonalMatrix;\n\n YOrthLoadingVec[i] = CoTemp.subMatrix(0, CoTemp.rows - 1, 0, 0);\n YOrthEigen[i] = SoTemp.get(0, 0);\n\n YOrthScoreMat[i] = Matrix.sub(\n kernelX[i][i],\n predScoreMat[i].mmul(TpiPrime),\n )\n .mmul(predScoreMat[i])\n .mmul(YOrthLoadingVec[i])\n .mul(Math.pow(YOrthEigen[i], -0.5));\n\n let toiPrime = YOrthScoreMat[i].transpose();\n YOrthScoreNorm[i] = Matrix.sqrt(toiPrime.mmul(YOrthScoreMat[i]));\n\n YOrthScoreMat[i] = YOrthScoreMat[i].divRowVector(YOrthScoreNorm[i]);\n\n let ITo = Matrix.sub(\n Identity,\n YOrthScoreMat[i].mmul(YOrthScoreMat[i].transpose()),\n );\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 let lastScoreMat = (predScoreMat[this.orthogonalComp] = kernelX[0][\n this.orthogonalComp\n ]\n .transpose()\n .mmul(YScoreMat)\n .mmul(SigmaPow));\n\n let lastTpPrime = lastScoreMat.transpose();\n TURegressionCoeff[this.orthogonalComp] = inverse(\n lastTpPrime.mmul(lastScoreMat),\n )\n .mmul(lastTpPrime)\n .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 let KTestTrain = this.kernel.compute(toPredict, this.trainingSet);\n\n let temp = KTestTrain;\n KTestTrain = new Array(this.orthogonalComp + 1);\n for (let i = 0; i < this.orthogonalComp + 1; i++) {\n KTestTrain[i] = new Array(this.orthogonalComp + 1);\n }\n KTestTrain[0][0] = temp;\n\n let YOrthScoreVector = new Array(this.orthogonalComp);\n let predScoreMat = new Array(this.orthogonalComp);\n\n let i;\n for (i = 0; i < this.orthogonalComp; ++i) {\n predScoreMat[i] = KTestTrain[i][0]\n .mmul(this.YScoreMat)\n .mmul(this.SigmaPow);\n\n YOrthScoreVector[i] = Matrix.sub(\n KTestTrain[i][i],\n predScoreMat[i].mmul(this.predScoreMat[i].transpose()),\n )\n .mmul(this.predScoreMat[i])\n .mmul(this.YOrthLoadingVec[i])\n .mul(Math.pow(this.YOrthEigen[i], -0.5));\n\n YOrthScoreVector[i] = YOrthScoreVector[i].divRowVector(this.toNorm[i]);\n\n let scoreMatPrime = this.YOrthScoreMat[i].transpose();\n KTestTrain[i + 1][0] = Matrix.sub(\n KTestTrain[i][0],\n YOrthScoreVector[i]\n .mmul(scoreMatPrime)\n .mmul(this.kernelX[0][i].transpose()),\n );\n\n let p1 = Matrix.sub(\n KTestTrain[i][0],\n KTestTrain[i][i].mmul(this.YOrthScoreMat[i]).mmul(scoreMatPrime),\n );\n let p2 = YOrthScoreVector[i].mmul(scoreMatPrime).mmul(this.kernelX[i][i]);\n let 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 let prediction = predScoreMat[i]\n .mmul(this.TURegressionCoeff[i])\n .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 * 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 */\nexport default class 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(\n 'Confusion matrix and labels should have the same length',\n );\n }\n this.labels = labels;\n this.matrix = matrix;\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 (let i = 0; i < this.matrix.length; i++) {\n for (let 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 let count = 0;\n for (let 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 let count = 0;\n for (let i = 0; i < this.matrix.length; i++) {\n for (let 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 let count = 0;\n for (let 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 let count = 0;\n for (let 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 (\n (2 * TP) /\n (2 * TP +\n this.getFalsePositiveCount(label) +\n this.getFalseNegativeCount(label))\n );\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 (\n (TP * TN - FP * FN) /\n Math.sqrt((TP + FP) * (TP + FN) * (TN + FP) * (TN + FN))\n );\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 (\n this.getTruePositiveRate(label) + this.getTrueNegativeRate(label) - 1\n );\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 (\n this.getPositivePredictiveValue(label) +\n this.getNegativePredictiveValue(label) -\n 1\n );\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 [this.getTruePositiveCount(label), this.getFalseNegativeCount(label)],\n [this.getFalsePositiveCount(label), this.getTrueNegativeCount(label)],\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 (let i = 0; i < this.matrix.length; i++) {\n for (let 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 * 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","(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 * get folds indexes\n * @param {Array} features\n * @param {Number} k - number of folds, a\n */\nexport function getFolds(features, k = 5) {\n let N = features.length;\n let allIdx = new Array(N);\n for (let i = 0; i < N; i++) {\n allIdx[i] = i;\n }\n\n let l = Math.floor(N / k);\n // create random k-folds\n let current = [];\n let folds = [];\n while (allIdx.length) {\n let 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 // we push the remaining to the last fold so that the total length is\n // preserved. Otherwise the Q2 will fail.\n if (current.length) current.forEach((e) => folds[k - 1].push(e));\n folds = folds.slice(0, k);\n\n let foldsIndex = folds.map((x, idx) => ({\n testIndex: x,\n trainIndex: [].concat(...folds.filter((el, idx2) => idx2 !== idx)),\n }));\n return foldsIndex;\n}\n","/**\n * A function to sample a dataset maintaining classes equilibrated\n * @param {Array} classVector - an array containing class or group information\n * @param {Number} fraction - a fraction of the class to sample\n * @return {Object} - an object with indexes\n */\n\nexport function sampleAClass(classVector, fraction) {\n // sort the vector\n let classVectorSorted = JSON.parse(JSON.stringify(classVector));\n let result = Array.from(Array(classVectorSorted.length).keys()).sort((a, b) =>\n classVectorSorted[a] < classVectorSorted[b]\n ? -1\n : (classVectorSorted[b] < classVectorSorted[a]) | 0,\n );\n classVectorSorted.sort((a, b) => (a < b ? -1 : (b < a) | 0));\n\n // counts the class elements\n let counts = {};\n classVectorSorted.forEach((x) => (counts[x] = (counts[x] || 0) + 1));\n\n // pick a few per class\n let indexOfSelected = [];\n\n Object.keys(counts).forEach((e, i) => {\n let shift = [];\n Object.values(counts).reduce((a, c, item) => (shift[item] = a + c), 0);\n\n let arr = [...Array(counts[e]).keys()];\n\n let r = [];\n for (let j = 0; j < Math.floor(counts[e] * fraction); j++) {\n let n = arr[Math.floor(Math.random() * arr.length)];\n r.push(n);\n let ind = arr.indexOf(n);\n arr.splice(ind, 1);\n }\n\n if (i === 0) {\n indexOfSelected = indexOfSelected.concat(r);\n } else {\n indexOfSelected = indexOfSelected.concat(r.map((x) => x + shift[i - 1]));\n }\n });\n\n // sort back the index\n let trainIndex = [];\n indexOfSelected.forEach((e) => trainIndex.push(result[e]));\n\n let testIndex = [];\n let mask = [];\n classVector.forEach((el, idx) => {\n if (trainIndex.includes(idx)) {\n mask.push(true);\n } else {\n mask.push(false);\n testIndex.push(idx);\n }\n });\n return { trainIndex, testIndex, mask };\n}\n","import ConfusionMatrix from 'ml-confusion-matrix';\nimport combinations from 'ml-combinations';\n\nimport { getFolds } from './getFolds.js';\n\nexport { sampleAClass } from './sampleAClass.js';\nexport { getFolds } from './getFolds.js';\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 */\n\nexport function leaveOneOut(Classifier, features, labels, classifierOptions) {\n if (typeof labels === 'function') {\n let callback = labels;\n labels = features;\n features = Classifier;\n return leavePOut(features, labels, 1, callback);\n }\n return leavePOut(Classifier, features, labels, classifierOptions, 1);\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 */\nexport function leavePOut(Classifier, features, labels, classifierOptions, p) {\n let callback;\n if (typeof classifierOptions === 'function') {\n 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 let N = features.length;\n let gen = combinations(p, N);\n let allIdx = new Array(N);\n for (let i = 0; i < N; i++) {\n allIdx[i] = i;\n }\n for (const testIdx of gen) {\n let 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(\n features,\n labels,\n testIdx,\n trainIdx,\n confusionMatrix,\n distinct,\n callback,\n );\n } else {\n validate(\n Classifier,\n features,\n labels,\n classifierOptions,\n testIdx,\n trainIdx,\n confusionMatrix,\n 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 */\nexport function kFold(Classifier, features, labels, classifierOptions, k) {\n let callback;\n if (typeof classifierOptions === 'function') {\n 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\n let folds = getFolds(features, k);\n\n for (let i = 0; i < folds.length; i++) {\n let testIdx = folds[i].testIndex;\n let trainIdx = folds[i].trainIndex;\n\n if (callback) {\n validateWithCallback(\n features,\n labels,\n testIdx,\n trainIdx,\n confusionMatrix,\n distinct,\n callback,\n );\n } else {\n validate(\n Classifier,\n features,\n labels,\n classifierOptions,\n testIdx,\n trainIdx,\n confusionMatrix,\n distinct,\n );\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 let 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(\n Classifier,\n features,\n labels,\n classifierOptions,\n testIdx,\n trainIdx,\n confusionMatrix,\n distinct,\n) {\n const { testFeatures, trainFeatures, testLabels, trainLabels } = getTrainTest(\n features,\n labels,\n testIdx,\n trainIdx,\n );\n\n let 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 let predictedLabels = classifier.predict(testFeatures);\n updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct);\n}\n\nfunction validateWithCallback(\n features,\n labels,\n testIdx,\n trainIdx,\n confusionMatrix,\n distinct,\n callback,\n) {\n const { testFeatures, trainFeatures, testLabels, trainLabels } = getTrainTest(\n features,\n labels,\n testIdx,\n trainIdx,\n );\n const predictedLabels = callback(trainFeatures, trainLabels, testFeatures);\n updateConfusionMatrix(confusionMatrix, testLabels, predictedLabels, distinct);\n}\n\nfunction updateConfusionMatrix(\n confusionMatrix,\n testLabels,\n predictedLabels,\n distinct,\n) {\n for (let 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\nexport function 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","import Matrix from 'ml-matrix';\n\nimport { norm } from './util/utils.js';\n\n/**\n * OPLS loop\n * @param {Array} x a matrix with features\n * @param {Array} y an array of labels (dependent variable)\n * @param {Object} options an object with options\n * @return {Object} an object with model (filteredX: err,\n loadingsXOrtho: pOrtho,\n scoresXOrtho: tOrtho,\n weightsXOrtho: wOrtho,\n weightsPred: w,\n loadingsXpred: p,\n scoresXpred: t,\n loadingsY:)\n */\nexport function OPLSNipals(x, y, options = {}) {\n const { numberOSC = 100 } = options;\n\n let X = Matrix.checkMatrix(x);\n let Y = Matrix.checkMatrix(y);\n\n let u = Y.getColumnVector(0);\n\n let diff = 1;\n let t, c, w, uNew;\n for (let i = 0; i < numberOSC && diff > 1e-10; i++) {\n w = u\n .transpose()\n .mmul(X)\n .div(\n u\n .transpose()\n .mmul(u)\n .get(0, 0),\n );\n w = w.transpose().div(norm(w));\n\n t = X.mmul(w).div(\n w\n .transpose()\n .mmul(w)\n .get(0, 0),\n ); // t_h paso 3\n\n // calc loading\n c = t\n .transpose()\n .mmul(Y)\n .div(\n t\n .transpose()\n .mmul(t)\n .get(0, 0),\n );\n\n // calc new u and compare with one in previus iteration (stop criterion)\n uNew = Y.mmul(c.transpose());\n uNew = uNew.div(\n c\n .transpose()\n .mmul(c)\n .get(0, 0),\n );\n\n if (i > 0) {\n diff =\n uNew\n .clone()\n .sub(u)\n .pow(2)\n .sum() /\n uNew\n .clone()\n .pow(2)\n .sum();\n }\n\n u = uNew.clone();\n }\n\n // calc loadings\n let p = t\n .transpose()\n .mmul(X)\n .div(\n t\n .transpose()\n .mmul(t)\n .get(0, 0),\n );\n\n let wOrtho = p.clone().sub(\n w\n .transpose()\n .mmul(p.transpose())\n .div(\n w\n .transpose()\n .mmul(w)\n .get(0, 0),\n )\n .mmul(w.transpose()),\n );\n wOrtho.div(norm(wOrtho));\n\n // orthogonal scores\n let tOrtho = X.mmul(wOrtho.transpose()).div(\n wOrtho.mmul(wOrtho.transpose()).get(0, 0),\n );\n\n // orthogonal loadings\n let pOrtho = tOrtho\n .transpose()\n .mmul(X)\n .div(\n tOrtho\n .transpose()\n .mmul(tOrtho)\n .get(0, 0),\n );\n\n // filtered data\n let err = X.clone().sub(tOrtho.mmul(pOrtho));\n return {\n filteredX: err,\n weightsXOrtho: wOrtho,\n loadingsXOrtho: pOrtho,\n scoresXOrtho: tOrtho,\n weightsXPred: w,\n loadingsXpred: p,\n scoresXpred: t,\n loadingsY: c,\n };\n}\n","import { Matrix } from 'ml-matrix';\n\n/**\n * Get total sum of square\n * @param {Array} x an array\n * @return {Number} - the sum of the squares\n */\nexport function tss(x) {\n return Matrix.mul(x, x).sum();\n}\n","import { Matrix, NIPALS } from 'ml-matrix';\nimport ConfusionMatrix from 'ml-confusion-matrix';\nimport { getFolds } from 'ml-cross-validation';\n\nimport { OPLSNipals } from './OPLSNipals.js';\nimport { tss } from './util/tss.js';\n\n/**\n * Creates new OPLS (orthogonal partial latent structures) from features and labels.\n * @param {Matrix} data - matrix containing data (X).\n * @param {Array} labels - 1D Array containing metadata (Y).\n * @param {Object} [options]\n * @param {number} [options.nComp = 3] - number of latent structures computed.\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 * @param {Array} [options.cvFolds = []] - allows to provide folds as 2D array for testing purpose.\n * */\n\nexport class OPLS {\n constructor(data, labels, options = {}) {\n if (data === true) {\n const opls = options;\n this.center = opls.center;\n this.scale = opls.scale;\n this.means = opls.means;\n this.meansY = opls.meansY;\n this.stdevs = opls.stdevs;\n this.stdevs = opls.stdevsY;\n this.model = opls.model;\n this.tCV = opls.tCV;\n this.tOrthCV = opls.tOrthCV;\n this.yHatCV = opls.yHatCV;\n this.mode = opls.mode;\n return;\n }\n\n let features = data.clone();\n // set default values\n // cvFolds allows to define folds for testing purpose\n const { nComp = 3, center = true, scale = true, cvFolds = [] } = options;\n\n let group;\n if (typeof labels[0] === 'number') {\n // numeric labels: OPLS regression is used\n this.mode = 'regression';\n group = Matrix.from1DArray(labels.length, 1, labels);\n } else if (typeof labels[0] === 'string') {\n // non-numeric labels: OPLS-DA is used\n this.mode = 'discriminantAnalysis';\n group = labels;\n throw new Error('discriminant analysis is not yet supported');\n }\n\n // check types of features and labels\n if (features.constructor.name !== 'Matrix') {\n throw new TypeError('features must be of class Matrix');\n }\n // getting center and scale the features (all)\n this.center = center;\n if (this.center) {\n this.means = features.mean('column');\n this.meansY = group.mean('column');\n } else {\n this.stdevs = null;\n }\n this.scale = scale;\n if (this.scale) {\n this.stdevs = features.standardDeviation('column');\n this.stdevsY = group.standardDeviation('column');\n } else {\n this.means = null;\n }\n\n // check and remove for features with sd = 0 TODO here\n // check opls.R line 70\n\n let folds;\n if (cvFolds.length > 0) {\n folds = cvFolds;\n } else {\n folds = getFolds(labels, 5);\n }\n\n let Q2 = [];\n this.model = [];\n\n this.tCV = [];\n this.tOrthCV = [];\n this.yHatCV = [];\n let oplsCV = [];\n\n let modelNC = [];\n\n // this code could be made more efficient by reverting the order of the loops\n // this is a legacy loop to be consistent with R code from MetaboMate package\n // this allows for having statistic (R2) from CV to decide wether to continue\n // with more latent structures\n let nc;\n for (nc = 0; nc < nComp; nc++) {\n let yHatk = new Matrix(group.rows, 1);\n let tPredk = new Matrix(group.rows, 1);\n let tOrthk = new Matrix(group.rows, 1);\n let oplsk = [];\n\n let f = 0;\n for (let fold of folds) {\n let trainTest = this._getTrainTest(features, group, fold);\n let testXk = trainTest.testFeatures;\n let Xk = trainTest.trainFeatures;\n let Yk = trainTest.trainLabels;\n\n // determine center and scale of training set\n let dataCenter = Xk.mean('column');\n let dataSD = Xk.standardDeviation('column');\n\n // center and scale training set\n if (center) {\n Xk.center('column');\n Yk.center('column');\n }\n\n if (scale) {\n Xk.scale('column');\n Yk.scale('column');\n }\n\n // perform opls\n if (nc === 0) {\n oplsk[f] = OPLSNipals(Xk, Yk);\n } else {\n oplsk[f] = OPLSNipals(oplsCV[nc - 1][f].filteredX, Yk);\n }\n // store model for next component\n oplsCV[nc] = oplsk;\n\n let plsCV = new NIPALS(oplsk[f].filteredX, { Y: Yk });\n\n // scaling the test dataset with respect to the train\n testXk.center('column', { center: dataCenter });\n testXk.scale('column', { scale: dataSD });\n\n let Eh = testXk;\n // removing the orthogonal components from PLS\n let scores;\n for (let idx = 0; idx < nc + 1; idx++) {\n scores = Eh.mmul(oplsCV[idx][f].weightsXOrtho.transpose()); // ok\n Eh.sub(scores.mmul(oplsCV[idx][f].loadingsXOrtho));\n }\n\n // prediction\n let tPred = Eh.mmul(plsCV.w.transpose());\n // this should be summed over ncomp (pls_prediction.R line 23)\n let yHat = tPred.mmul(plsCV.betas); // ok\n\n // adding all prediction from all folds\n for (let i = 0; i < fold.testIndex.length; i++) {\n yHatk.setRow(fold.testIndex[i], [yHat.get(i, 0)]);\n tPredk.setRow(fold.testIndex[i], [tPred.get(i, 0)]);\n tOrthk.setRow(fold.testIndex[i], [scores.get(i, 0)]);\n }\n f++;\n } // end of loop over folds\n\n this.tCV.push(tPredk);\n this.tOrthCV.push(tOrthk);\n this.yHatCV.push(yHatk);\n\n // calculate Q2y for all the prediction (all folds)\n // ROC for DA is not implemented (check opls.R line 183) TODO\n if (this.mode === 'regression') {\n let tssy = tss(group.center('column').scale('column'));\n let press = tss(group.clone().sub(yHatk));\n let Q2y = 1 - press / tssy;\n Q2.push(Q2y);\n } else if (this.mode === 'discriminantAnalysis') {\n throw new Error('discriminant analysis is not yet supported');\n }\n\n // calculate the R2y for the complete data\n if (nc === 0) {\n modelNC = this._predictAll(features, group);\n } else {\n modelNC = this._predictAll(\n modelNC.xRes,\n group,\n (options = { scale: false, center: false }),\n );\n }\n\n // adding the predictive statistics from CV\n modelNC.Q2y = Q2;\n // store the model for each component\n this.model.push(modelNC);\n // console.warn(`OPLS iteration over # of Components: ${nc + 1}`);\n } // end of loop over nc\n\n // store scores from CV\n let tCV = this.tCV;\n let tOrthCV = this.tOrthCV;\n\n let m = this.model[nc - 1];\n let XOrth = m.XOrth;\n let FeaturesCS = features.center('column').scale('column');\n let labelsCS = group.center('column').scale('column');\n let Xres = FeaturesCS.clone().sub(XOrth);\n let plsCall = new NIPALS(Xres, { Y: labelsCS });\n let E = Xres.clone().sub(plsCall.t.mmul(plsCall.p));\n\n let R2x = this.model.map((x) => x.R2x);\n let R2y = this.model.map((x) => x.R2y);\n\n this.output = {\n Q2y: Q2,\n R2x,\n R2y,\n tPred: m.plsC.t,\n pPred: m.plsC.p,\n wPred: m.plsC.w,\n betasPred: m.plsC.betas,\n Qpc: m.plsC.q,\n tCV,\n tOrthCV,\n tOrth: m.tOrth,\n pOrth: m.pOrth,\n wOrth: m.wOrth,\n XOrth,\n yHat: m.totalPred,\n Yres: m.plsC.yResidual,\n E,\n };\n }\n\n /**\n * get access to all the computed elements\n * Mainly for debug and testing\n * @return {Object} output object\n */\n getLogs() {\n return this.output;\n }\n\n getScores() {\n let scoresX = this.tCV.map((x) => x.to1DArray());\n let scoresY = this.tOrthCV.map((x) => x.to1DArray());\n return { scoresX, scoresY };\n }\n\n /**\n * Load an OPLS model from JSON\n * @param {Object} model\n * @return {OPLS}\n */\n static load(model) {\n if (typeof model.name !== 'string') {\n throw new TypeError('model must have a name property');\n }\n if (model.name !== 'OPLS') {\n throw new RangeError(`invalid model: ${model.name}`);\n }\n return new OPLS(true, [], model);\n }\n\n /**\n * Export the current model to a JSON object\n * @return {Object} model\n */\n toJSON() {\n return {\n name: 'OPLS',\n center: this.center,\n scale: this.scale,\n means: this.means,\n stdevs: this.stdevs,\n model: this.model,\n tCV: this.tCV,\n tOrthCV: this.tOrthCV,\n yHatCV: this.yHatCV,\n };\n }\n\n /**\n * Predict scores for new data\n * @param {Matrix} features - a matrix containing new data\n * @param {Object} [options]\n * @param {Array} [options.trueLabel] - an array with true values to compute confusion matrix\n * @param {Number} [options.nc] - the number of components to be used\n * @return {Object} - predictions\n */\n predict(newData, options = {}) {\n let { trueLabels = [], nc = 1 } = options;\n let labels = [];\n if (trueLabels.length > 0) {\n trueLabels = Matrix.from1DArray(trueLabels.length, 1, trueLabels);\n labels = trueLabels.clone();\n }\n\n let features = newData.clone();\n\n // scaling the test dataset with respect to the train\n if (this.center) {\n features.center('column', { center: this.means });\n if (labels.rows > 0 && this.mode === 'regression') {\n labels.center('column', { center: this.meansY });\n }\n }\n if (this.scale) {\n features.scale('column', { scale: this.stdevs });\n if (labels.rows > 0 && this.mode === 'regression') {\n labels.scale('column', { scale: this.stdevsY });\n }\n }\n\n let Eh = features.clone();\n // removing the orthogonal components from PLS\n let tOrth;\n let wOrth;\n let pOrth;\n let yHat;\n let tPred;\n\n for (let idx = 0; idx < nc; idx++) {\n wOrth = this.model[idx].wOrth.transpose();\n pOrth = this.model[idx].pOrth;\n tOrth = Eh.mmul(wOrth);\n Eh.sub(tOrth.mmul(pOrth));\n // prediction\n tPred = Eh.mmul(this.model[idx].plsC.w.transpose());\n // this should be summed over ncomp (pls_prediction.R line 23)\n yHat = tPred.mmul(this.model[idx].plsC.betas);\n }\n\n if (labels.rows > 0) {\n if (this.mode === 'regression') {\n let tssy = tss(labels);\n let press = tss(labels.clone().sub(yHat));\n let Q2y = 1 - press / tssy;\n\n return { tPred, tOrth, yHat, Q2y };\n } else if (this.mode === 'discriminantAnalysis') {\n let confusionMatrix = [];\n confusionMatrix = ConfusionMatrix.fromLabels(\n trueLabels.to1DArray(),\n yHat.to1DArray(),\n );\n\n return { tPred, tOrth, yHat, confusionMatrix };\n }\n } else {\n return { tPred, tOrth, yHat };\n }\n }\n\n _predictAll(features, labels, options = {}) {\n // cannot use the global this.center here\n // since it is used in the NC loop and\n // centering and scaling should only be\n // performed once\n const { center = true, scale = true } = options;\n\n if (center) {\n features.center('column');\n labels.center('column');\n }\n\n if (scale) {\n features.scale('column');\n labels.scale('column');\n // reevaluate tssy and tssx after scaling\n // must be global because re-used for next nc iteration\n // tssx is only evaluate the first time\n this.tssy = tss(labels);\n this.tssx = tss(features);\n }\n\n let oplsC = OPLSNipals(features, labels);\n let plsC = new NIPALS(oplsC.filteredX, { Y: labels });\n\n let tPred = oplsC.filteredX.mmul(plsC.w.transpose());\n let yHat = tPred.mmul(plsC.betas);\n\n let rss = tss(labels.clone().sub(yHat));\n let R2y = 1 - rss / this.tssy;\n\n let xEx = plsC.t.mmul(plsC.p);\n let rssx = tss(xEx);\n let R2x = rssx / this.tssx;\n\n return {\n R2y,\n R2x,\n xRes: oplsC.filteredX,\n tOrth: oplsC.scoresXOrtho,\n pOrth: oplsC.loadingsXOrtho,\n wOrth: oplsC.weightsXOrtho,\n tPred: tPred,\n totalPred: yHat,\n XOrth: oplsC.scoresXOrtho.mmul(oplsC.loadingsXOrtho),\n oplsC,\n plsC,\n };\n }\n /**\n *\n * @param {*} X - dataset matrix object\n * @param {*} group - labels matrix object\n * @param {*} index - train and test index (output from getFold())\n */\n _getTrainTest(X, group, index) {\n let testFeatures = new Matrix(index.testIndex.length, X.columns);\n let testLabels = new Matrix(index.testIndex.length, 1);\n index.testIndex.forEach((el, idx) => {\n testFeatures.setRow(idx, X.getRow(el));\n testLabels.setRow(idx, group.getRow(el));\n });\n\n let trainFeatures = new Matrix(index.trainIndex.length, X.columns);\n let trainLabels = new Matrix(index.trainIndex.length, 1);\n index.trainIndex.forEach((el, idx) => {\n trainFeatures.setRow(idx, X.getRow(el));\n trainLabels.setRow(idx, group.getRow(el));\n });\n\n return {\n trainFeatures,\n testFeatures,\n trainLabels,\n testLabels,\n };\n }\n}\n","'use strict';\n\nvar mlMatrix = require('ml-matrix');\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\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.set(i, j, actFunction(this.get(i, j)));\n };\n this.derivate = function (i, j) {\n this.set(i, j, derFunction(this.get(i, j)));\n };\n\n if (options.model) {\n // load model\n this.W = mlMatrix.Matrix.checkMatrix(options.W);\n this.b = mlMatrix.Matrix.checkMatrix(options.b);\n } else {\n // default constructor\n this.W = mlMatrix.Matrix.rand(this.inputSize, this.outputSize);\n this.b = mlMatrix.Matrix.zeros(1, this.outputSize);\n\n this.W.apply(function (i, j) {\n this.set(i, j, this.get(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.transpose().mmul(delta);\n this.db = mlMatrix.Matrix.rowVector(delta.sum('column'));\n\n var aCopy = a.clone();\n return delta.mmul(this.W.transpose()).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\nclass OutputLayer extends Layer {\n constructor(options) {\n super(options);\n\n this.activationFunction = function (i, j) {\n this.set(i, j, Math.exp(this.get(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\nclass FeedForwardNeuralNetworks {\n /**\n * Create a new Feedforward 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 = mlMatrix.Matrix.checkMatrix(features);\n this.dicts = dictOutputs(labels);\n\n var inputSize = features.columns;\n var outputSize = Object.keys(this.dicts.inputs).length;\n\n if (!this.model) {\n this.buildNetwork(inputSize, outputSize);\n }\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 input = this.model[i].forward(input);\n }\n\n // get probabilities\n return input.divColumnVector(input.sum('row'));\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.rows; ++i) {\n probabilities.set(i, this.dicts.inputs[labels[i]], probabilities.get(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 = mlMatrix.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\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 = FeedForwardNeuralNetworks;\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;","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 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;","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 = [];\n for (let i = 0; i < x.length; i++) {\n y.push(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 (n * xY - xSum * ySum) /\n 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: Math.sqrt(rmsd / n)\n };\n }\n}\n","import BaseRegression, {\n checkArrayLength,\n maybeToPrecision\n} from 'ml-regression-base';\nimport { Matrix, MatrixTransposeView, 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 =\n `${maybeToPrecision(this.coefficients[k], precision) + times}x`;\n } else {\n str =\n `${maybeToPrecision(this.coefficients[k], precision) +\n times\n }x${\n sup\n }${this.powers[k]\n }${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.set(i, k, 1);\n } else {\n F.set(i, k, Math.pow(x[i], powers[k]));\n }\n }\n }\n\n const FT = new MatrixTransposeView(F);\n const A = FT.mmul(F);\n const B = FT.mmul(new MatrixTransposeView(Y));\n\n pr.degree = degree - 1;\n pr.powers = powers;\n pr.coefficients = solve(A, B).to1DArray();\n}\n","import BaseRegression, {\n checkArrayLength,\n maybeToPrecision\n} 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 !== 0) {\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, {\n checkArrayLength,\n maybeToPrecision\n} 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 (\n `f(x) = ${\n maybeToPrecision(this.B, precision)\n } * e^(${\n maybeToPrecision(this.A, precision)\n } * x)`\n );\n }\n\n toLaTeX(precision) {\n if (this.A >= 0) {\n return (\n `f(x) = ${\n maybeToPrecision(this.B, precision)\n }e^{${\n maybeToPrecision(this.A, precision)\n }x}`\n );\n } else {\n return (\n `f(x) = \\\\frac{${\n maybeToPrecision(this.B, precision)\n }}{e^{${\n maybeToPrecision(-this.A, precision)\n }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, {\n checkArrayLength,\n maybeToPrecision\n} 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) {\n // 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(\n this.A,\n precision\n )} * x^${maybeToPrecision(this.B, precision)}`;\n }\n\n toLaTeX(precision) {\n let latex = '';\n if (this.B >= 0) {\n latex = `f(x) = ${maybeToPrecision(\n this.A,\n precision\n )}x^{${maybeToPrecision(this.B, precision)}}`;\n } else {\n latex = `f(x) = \\\\frac{${maybeToPrecision(\n this.A,\n precision\n )}}{x^{${maybeToPrecision(-this.B, precision)}}}`;\n }\n latex = latex.replace(/e([+-]?[0-9]+)/g, 'e^{$1}');\n return latex;\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, pseudoInverse } from 'ml-matrix';\n\nexport default class MultivariateLinearRegression {\n constructor(x, y, options = {}) {\n const { intercept = true, statistics = true } = options;\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 y = new Matrix(y);\n if (intercept) {\n x.addColumn(new Array(x.rows).fill(1));\n }\n let xt = x.transpose();\n const xx = xt\n .mmul(x);\n const xy = xt\n .mmul(y);\n const invxx = new SVD(xx)\n .inverse();\n const beta = xy\n .transpose()\n .mmul(invxx)\n .transpose();\n this.weights = beta.to2DArray();\n this.inputs = x.columns;\n this.outputs = y.columns;\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 = y.clone().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.rows - x.columns);\n this.stdError = Math.sqrt(variance);\n this.stdErrorMatrix = pseudoInverse(xx).mul(variance);\n this.stdErrors = this.stdErrorMatrix\n .diagonal()\n .map((d) => Math.sqrt(d));\n this.tStats = this.weights.map((d, i) =>\n (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 } else if (Matrix.isMatrix(x)) {\n const y = new Matrix(x.rows, this.outputs);\n for (let i = 0; i < x.rows; i++) {\n y.setRow(i, this._predict(x.getRow(i)));\n }\n return y;\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","'use strict';\n\nconst { squaredEuclidean } = require('ml-distance-euclidean');\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 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 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 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(\n Math.exp(\n -this.sigma *\n Math.pow(Math.pow(x[i - 1], i) - Math.pow(y[i - 1], i), 2)\n ),\n this.degree\n );\n }\n return sum;\n }\n}\n\nmodule.exports = ANOVAKernel;\n","'use strict';\n\nconst { squaredEuclidean } = require('ml-distance-euclidean');\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');\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');\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 { Matrix, MatrixTransposeView } = require('ml-matrix');\nconst GaussianKernel = require('ml-kernel-gaussian');\nconst PolynomialKernel = require('ml-kernel-polynomial');\nconst SigmoidKernel = require('ml-kernel-sigmoid');\n\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');\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(\n 'first argument must be a valid kernel type or instance'\n );\n }\n }\n\n compute(inputs, landmarks) {\n inputs = Matrix.checkMatrix(inputs);\n if (landmarks === undefined) {\n landmarks = inputs;\n } else {\n landmarks = Matrix.checkMatrix(landmarks);\n }\n if (this.kernelType === 'linear') {\n return inputs.mmul(new MatrixTransposeView(landmarks));\n }\n\n const kernelMatrix = new Matrix(inputs.rows, landmarks.rows);\n if (inputs === landmarks) {\n // fast path, matrix is symmetric\n for (let i = 0; i < inputs.rows; i++) {\n for (let j = i; j < inputs.rows; j++) {\n const value = this.kernelFunction.compute(\n inputs.getRow(i),\n inputs.getRow(j)\n );\n kernelMatrix.set(i, j, value);\n kernelMatrix.set(j, i, value);\n }\n }\n } else {\n for (let i = 0; i < inputs.rows; i++) {\n for (let j = 0; j < landmarks.rows; j++) {\n kernelMatrix.set(\n i,\n j,\n this.kernelFunction.compute(inputs.getRow(i), landmarks.getRow(j))\n );\n }\n }\n }\n return kernelMatrix;\n }\n}\n\nmodule.exports = Kernel;\n","import BaseRegression, {\n checkArrayLength,\n maybeToPrecision\n} from 'ml-regression-base';\nimport median from 'ml-array-median';\n\nexport default class TheilSenRegression extends BaseRegression {\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 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 +=\n ` ${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, {\n checkArrayLength,\n maybeToPrecision\n} from 'ml-regression-base';\nimport { solve } from 'ml-matrix';\n\n/**\n * @class RobustPolynomialRegression\n * @param {Array} x\n * @param {Array} y\n * @param {number} degree - polynomial degree\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 /**\n * Display the formula\n * @param {number} precision - precision for the numbers\n * @return {string}\n */\n toString(precision) {\n return this._toFormula(precision, false);\n }\n\n /**\n * Display the formula in LaTeX format\n * @param {number} precision - precision for the numbers\n * @return {string}\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) +\n times}x`;\n } else {\n str = `${maybeToPrecision(this.coefficients[k], precision) +\n 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 = Array(degree)\n .fill(0)\n .map((_, index) => index);\n\n const tuples = getRandomTuples(x, y, degree);\n\n var min;\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 {\n x: x[i],\n y: y[i]\n }\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 return l % 2 === 0 ? residuals[half - 1] : residuals[half];\n}\n","const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\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 */\nexport default function errorCalculation(\n data,\n parameters,\n parameterizedFunction,\n) {\n let error = 0;\n const func = parameterizedFunction(parameters);\n\n for (let 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 let ans = new Array(n);\n\n for (let param = 0; param < n; param++) {\n ans[param] = new Array(m);\n let auxParams = params.slice();\n auxParams[param] += gradientDifference;\n let funcParam = paramFunction(auxParams);\n\n for (let 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 let ans = new Array(m);\n\n for (let 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 let value = damping * gradientDifference * gradientDifference;\n let identity = Matrix.eye(params.length, params.length, value);\n\n const func = parameterizedFunction(params);\n\n let evaluatedData = new Float64Array(data.x.length);\n for (let i = 0; i < data.x.length; i++) {\n evaluatedData[i] = func(data.x[i]);\n }\n\n let gradientFunc = gradientFunction(\n data,\n evaluatedData,\n params,\n gradientDifference,\n parameterizedFunction,\n );\n let matrixFunc = matrixFunction(data, evaluatedData);\n let 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 isArray from 'is-any-array';\n\nimport 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 !isArray(data.x) ||\n data.x.length < 2 ||\n !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 let 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 (!isArray(parameters)) {\n throw new Error('initialValues must be an array');\n }\n\n let error = errorCalculation(data, parameters, parameterizedFunction);\n\n let converged = error <= errorTolerance;\n\n let iteration;\n for (iteration = 0; iteration < maxIterations && !converged; iteration++) {\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","/**\n * Returns a new array based on extraction of specific indices of an array\n * @private\n * @param {Array} vector\n * @param {Array} indices\n */\nexport default function selection(vector, indices) {\n let u = []; //new Float64Array(indices.length);\n for (let i = 0; i < indices.length; i++) {\n u[i] = vector[indices[i]];\n }\n return u;\n}\n","/**\n *\n * @private\n * @param {Array of arrays} collection\n */\nexport default function sortCollectionSet(collection) {\n let objectCollection = collection\n .map((value, index) => {\n let key = BigInt(0);\n value.forEach((item) => (key |= BigInt(1) << BigInt(item)));\n return { value, index, key };\n })\n .sort((a, b) => {\n if (a.key - b.key < 0) return -1;\n return 1;\n });\n\n let sorted = [];\n let indices = [];\n\n let key;\n for (let set of objectCollection) {\n if (set.key !== key) {\n key = set.key;\n indices.push([]);\n sorted.push(set.value);\n }\n indices[indices.length - 1].push(set.index);\n }\n\n let result = {\n values: sorted,\n indices: indices,\n };\n return result;\n}\n","import {\n Matrix,\n LuDecomposition,\n solve,\n CholeskyDecomposition,\n} from 'ml-matrix';\n\nimport sortCollectionSet from './util/sortCollectionSet';\n\n/**\n * (Combinatorial Subspace Least Squares) - subfunction for the FC-NNLS\n * @private\n * @param {Matrix} XtX\n * @param {Matrix} XtY\n * @param {Array} Pset\n * @param {Numbers} l\n * @param {Numbers} p\n */\nexport default function cssls(XtX, XtY, Pset, l, p) {\n // Solves the set of equation XtX*K = XtY for the variables in Pset\n // if XtX (or XtX(vars,vars)) is singular, performs the svd and find pseudoinverse, otherwise (even if ill-conditioned) finds inverse with LU decomposition and solves the set of equation\n // it is consistent with matlab results for ill-conditioned matrices (at least consistent with test 'ill-conditionned square X rank 2, Y 3x1' in cssls.test)\n\n let K = Matrix.zeros(l, p);\n if (Pset === null) {\n let choXtX = new CholeskyDecomposition(XtX);\n if (choXtX.isPositiveDefinite() === true) {\n K = choXtX.solve(XtY);\n } else {\n let luXtX = new LuDecomposition(XtX);\n if (luXtX.isSingular() === false) {\n K = luXtX.solve(Matrix.eye(l)).mmul(XtY);\n } else {\n K = solve(XtX, XtY, { useSVD: true });\n }\n }\n } else {\n let sortedPset = sortCollectionSet(Pset).values;\n let sortedEset = sortCollectionSet(Pset).indices;\n if (\n sortedPset.length === 1 &&\n sortedPset[0].length === 0 &&\n sortedEset[0].length === p\n ) {\n return K;\n } else if (\n sortedPset.length === 1 &&\n sortedPset[0].length === l &&\n sortedEset[0].length === p\n ) {\n let choXtX = new CholeskyDecomposition(XtX);\n if (choXtX.isPositiveDefinite() === true) {\n K = choXtX.solve(XtY);\n } else {\n let luXtX = new LuDecomposition(XtX);\n if (luXtX.isSingular() === false) {\n K = luXtX.solve(Matrix.eye(l)).mmul(XtY);\n } else {\n K = solve(XtX, XtY, { useSVD: true });\n }\n }\n } else {\n for (let k = 0; k < sortedPset.length; k++) {\n let cols2Solve = sortedEset[k];\n let vars = sortedPset[k];\n let L;\n let choXtX = new CholeskyDecomposition(XtX.selection(vars, vars));\n if (choXtX.isPositiveDefinite() === true) {\n L = choXtX.solve(XtY.selection(vars, cols2Solve));\n } else {\n let luXtX = new LuDecomposition(XtX.selection(vars, vars));\n if (luXtX.isSingular() === false) {\n L = luXtX\n .solve(Matrix.eye(vars.length))\n .mmul(XtY.selection(vars, cols2Solve));\n } else {\n L = solve(\n XtX.selection(vars, vars),\n XtY.selection(vars, cols2Solve),\n { useSVD: true },\n );\n }\n }\n for (let i = 0; i < L.rows; i++) {\n for (let j = 0; j < L.columns; j++) {\n K.set(vars[i], cols2Solve[j], L.get(i, j));\n }\n }\n }\n }\n }\n return K;\n}\n","import { Matrix } from 'ml-matrix';\n\nimport cssls from './cssls';\n\nexport default function initialisation(X, Y) {\n let n = X.rows;\n let l = X.columns;\n let p = Y.columns;\n let iter = 0;\n\n if (Y.rows !== n) throw new Error('ERROR: matrix size not compatible');\n\n let W = Matrix.zeros(l, p);\n\n // precomputes part of pseudoinverse\n let XtX = X.transpose().mmul(X);\n let XtY = X.transpose().mmul(Y);\n\n let K = cssls(XtX, XtY, null, l, p); // K is lxp\n let Pset = [];\n for (let j = 0; j < p; j++) {\n Pset[j] = [];\n for (let i = 0; i < l; i++) {\n if (K.get(i, j) > 0) {\n Pset[j].push(i);\n } else {\n K.set(i, j, 0);\n } //This is our initial solution, it's the solution found by overwriting the unconstrained least square solution\n }\n }\n let Fset = [];\n for (let j = 0; j < p; j++) {\n if (Pset[j].length !== l) {\n Fset.push(j);\n }\n }\n\n let D = K.clone();\n\n return { n, l, p, iter, W, XtX, XtY, K, Pset, Fset, D };\n}\n","/**\n * Computes the set difference A\\B\n * @private\n * @param {A} set A as an array\n * @param {B} set B as an array\n */\nexport default function setDifference(A, B) {\n let C = [];\n for (let i of A) {\n if (!B.includes(i)) C.push(i);\n }\n return C;\n}\n","import setDifference from './util/setDifference';\n\n// Makes sure the solution has converged\nexport default function optimality(\n iter,\n maxIter,\n XtX,\n XtY,\n Fset,\n Pset,\n W,\n K,\n l,\n p,\n D,\n) {\n if (iter === maxIter) {\n throw new Error('Maximum number of iterations exceeded');\n }\n\n // Check solution for optimality\n let V = XtY.subMatrixColumn(Fset).subtract(XtX.mmul(K.subMatrixColumn(Fset)));\n for (let j = 0; j < Fset.length; j++) {\n W.setColumn(Fset[j], V.subMatrixColumn([j]));\n }\n let Jset = [];\n let fullSet = [];\n for (let i = 0; i < l; i++) {\n fullSet.push(i);\n }\n for (let j = 0; j < Fset.length; j++) {\n let notPset = setDifference(fullSet, Pset[Fset[j]]);\n if (notPset.length === 0) {\n Jset.push(Fset[j]);\n } else if (W.selection(notPset, [Fset[j]]).max() <= 0) {\n Jset.push(Fset[j]);\n }\n }\n Fset = setDifference(Fset, Jset);\n\n // For non-optimal solutions, add the appropriate variables to Pset\n if (Fset.length !== 0) {\n for (let j = 0; j < Fset.length; j++) {\n for (let i = 0; i < l; i++) {\n if (Pset[Fset[j]].includes(i)) W.set(i, Fset[j], -Infinity);\n }\n Pset[Fset[j]].push(W.subMatrixColumn(Fset).maxColumnIndex(j)[0]);\n }\n for (let j = 0; j < Fset.length; j++) {\n D.setColumn(Fset[j], K.getColumn(Fset[j]));\n }\n }\n for (let j = 0; j < p; j++) {\n Pset[j].sort((a, b) => a - b);\n }\n return { Pset, Fset, W };\n}\n","import { Matrix } from 'ml-matrix';\n\nimport selection from './util/selection';\nimport cssls from './cssls';\nimport initialisation from './initialisation';\nimport optimality from './optimality';\n\n/**\n * Fast Combinatorial Non-negative Least Squares with multiple Right Hand Side\n * @param {Matrix|number[][]} X\n * @param {Matrix|number[][]} Y\n * @param {object} [options={}]\n * @param {number} [options.maxIterations] if empty maxIterations is set at 3 times the number of columns of X\n * @returns {Matrix} K\n */\nexport default function fcnnls(X, Y, options = {}) {\n X = Matrix.checkMatrix(X);\n Y = Matrix.checkMatrix(Y);\n let { l, p, iter, W, XtX, XtY, K, Pset, Fset, D } = initialisation(X, Y);\n const { maxIterations = X.columns * 3 } = options;\n\n // Active set algorithm for NNLS main loop\n while (Fset.length > 0) {\n // Solves for the passive variables (uses subroutine below)\n let L = cssls(\n XtX,\n XtY.subMatrixColumn(Fset),\n selection(Pset, Fset),\n l,\n Fset.length,\n );\n for (let i = 0; i < l; i++) {\n for (let j = 0; j < Fset.length; j++) {\n K.set(i, Fset[j], L.get(i, j));\n }\n }\n\n // Finds any infeasible solutions\n let infeasIndex = [];\n for (let j = 0; j < Fset.length; j++) {\n for (let i = 0; i < l; i++) {\n if (L.get(i, j) < 0) {\n infeasIndex.push(j);\n break;\n }\n }\n }\n let Hset = selection(Fset, infeasIndex);\n\n // Makes infeasible solutions feasible (standard NNLS inner loop)\n if (Hset.length > 0) {\n let m = Hset.length;\n let alpha = Matrix.ones(l, m);\n\n while (m > 0 && iter < maxIterations) {\n iter++;\n\n alpha.mul(Infinity);\n\n // Finds indices of negative variables in passive set\n let hRowColIdx = [[], []]; // Indexes work in pairs, each pair reprensents a single element, first array is row index, second array is column index\n let negRowColIdx = [[], []]; // Same as before\n for (let j = 0; j < m; j++) {\n for (let i = 0; i < Pset[Hset[j]].length; i++) {\n if (K.get(Pset[Hset[j]][i], Hset[j]) < 0) {\n hRowColIdx[0].push(Pset[Hset[j]][i]); // i\n hRowColIdx[1].push(j);\n negRowColIdx[0].push(Pset[Hset[j]][i]); // i\n negRowColIdx[1].push(Hset[j]);\n } // Compared to matlab, here we keep the row/column indexing (we are not taking the linear indexing)\n }\n }\n\n for (let k = 0; k < hRowColIdx[0].length; k++) {\n // could be hRowColIdx[1].length as well\n alpha.set(\n hRowColIdx[0][k],\n hRowColIdx[1][k],\n D.get(negRowColIdx[0][k], negRowColIdx[1][k]) /\n (D.get(negRowColIdx[0][k], negRowColIdx[1][k]) -\n K.get(negRowColIdx[0][k], negRowColIdx[1][k])),\n );\n }\n\n let alphaMin = [];\n let minIdx = [];\n for (let j = 0; j < m; j++) {\n alphaMin[j] = alpha.minColumn(j);\n minIdx[j] = alpha.minColumnIndex(j)[0];\n }\n\n alphaMin = Matrix.rowVector(alphaMin);\n for (let i = 0; i < l; i++) {\n alpha.setSubMatrix(alphaMin, i, 0);\n }\n\n let E = new Matrix(l, m);\n E = D.subMatrixColumn(Hset).subtract(\n alpha\n .subMatrix(0, l - 1, 0, m - 1)\n .mul(D.subMatrixColumn(Hset).subtract(K.subMatrixColumn(Hset))),\n );\n for (let j = 0; j < m; j++) {\n D.setColumn(Hset[j], E.subMatrixColumn([j]));\n }\n\n let idx2zero = [minIdx, Hset];\n for (let k = 0; k < m; k++) {\n D.set(idx2zero[0][k], idx2zero[1][k], 0);\n }\n\n for (let j = 0; j < m; j++) {\n Pset[Hset[j]].splice(\n Pset[Hset[j]].findIndex((item) => item === minIdx[j]),\n 1,\n );\n }\n\n L = cssls(XtX, XtY.subMatrixColumn(Hset), selection(Pset, Hset), l, m);\n for (let j = 0; j < m; j++) {\n K.setColumn(Hset[j], L.subMatrixColumn([j]));\n }\n\n Hset = [];\n for (let j = 0; j < K.columns; j++) {\n for (let i = 0; i < l; i++) {\n if (K.get(i, j) < 0) {\n Hset.push(j);\n\n break;\n }\n }\n }\n m = Hset.length;\n }\n }\n\n let newParam = optimality(\n iter,\n maxIterations,\n XtX,\n XtY,\n Fset,\n Pset,\n W,\n K,\n l,\n p,\n D,\n );\n Pset = newParam.Pset;\n Fset = newParam.Fset;\n W = newParam.W;\n }\n\n return K;\n}\n","import { Matrix } from 'ml-matrix';\n\nimport fcnnls from './fcnnls';\n\n/**\n * Fast Combinatorial Non-negative Least Squares with single Right Hand Side\n * @param {Matrix|number[][]} X\n * @param {number[]} y\n * @param {object} [options={}]\n * @param {boolean} [maxIterations] if true or empty maxIterations is set at 3 times the number of columns of X\n * @returns {Array} k\n */\nexport default function fcnnlsVector(X, y, options = {}) {\n if (Array.isArray(y) === false) {\n throw new TypeError('y must be a 1D Array');\n }\n let Y = Matrix.columnVector(y);\n let K = fcnnls(X, Y, options);\n let k = K.to1DArray();\n return k;\n}\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 // The naive `low + high >>> 1` could fail for array lengths > 2**31\n // because `>>>` converts its operands to int32. `low + (high - low >>> 1)`\n // works for array lengths <= 2**32-1 which is also Javascript's max array\n // length.\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';\n\nfunction assertNumber(number) {\n\tif (typeof number !== 'number') {\n\t\tthrow new TypeError('Expected a number');\n\t}\n}\n\nexports.ascending = (left, right) => {\n\tassertNumber(left);\n\tassertNumber(right);\n\n\tif (Number.isNaN(left)) {\n\t\treturn -1;\n\t}\n\n\tif (Number.isNaN(right)) {\n\t\treturn 1;\n\t}\n\n\treturn left - right;\n};\n\nexports.descending = (left, right) => {\n\tassertNumber(left);\n\tassertNumber(right);\n\n\tif (Number.isNaN(left)) {\n\t\treturn 1;\n\t}\n\n\tif (Number.isNaN(right)) {\n\t\treturn -1;\n\t}\n\n\treturn right - left;\n};\n","import binarySearch from 'binary-search';\nimport { ascending } from 'num-sort';\n\nexport const largestPrime = 0x7fffffff;\n\nconst primeNumbers = [\n // chunk #0\n largestPrime, // 2^31-1\n\n // chunk #1\n 5,\n 11,\n 23,\n 47,\n 97,\n 197,\n 397,\n 797,\n 1597,\n 3203,\n 6421,\n 12853,\n 25717,\n 51437,\n 102877,\n 205759,\n 411527,\n 823117,\n 1646237,\n 3292489,\n 6584983,\n 13169977,\n 26339969,\n 52679969,\n 105359939,\n 210719881,\n 421439783,\n 842879579,\n 1685759167,\n\n // chunk #2\n 433,\n 877,\n 1759,\n 3527,\n 7057,\n 14143,\n 28289,\n 56591,\n 113189,\n 226379,\n 452759,\n 905551,\n 1811107,\n 3622219,\n 7244441,\n 14488931,\n 28977863,\n 57955739,\n 115911563,\n 231823147,\n 463646329,\n 927292699,\n 1854585413,\n\n // chunk #3\n 953,\n 1907,\n 3821,\n 7643,\n 15287,\n 30577,\n 61169,\n 122347,\n 244703,\n 489407,\n 978821,\n 1957651,\n 3915341,\n 7830701,\n 15661423,\n 31322867,\n 62645741,\n 125291483,\n 250582987,\n 501165979,\n 1002331963,\n 2004663929,\n\n // chunk #4\n 1039,\n 2081,\n 4177,\n 8363,\n 16729,\n 33461,\n 66923,\n 133853,\n 267713,\n 535481,\n 1070981,\n 2141977,\n 4283963,\n 8567929,\n 17135863,\n 34271747,\n 68543509,\n 137087021,\n 274174111,\n 548348231,\n 1096696463,\n\n // chunk #5\n 31,\n 67,\n 137,\n 277,\n 557,\n 1117,\n 2237,\n 4481,\n 8963,\n 17929,\n 35863,\n 71741,\n 143483,\n 286973,\n 573953,\n 1147921,\n 2295859,\n 4591721,\n 9183457,\n 18366923,\n 36733847,\n 73467739,\n 146935499,\n 293871013,\n 587742049,\n 1175484103,\n\n // chunk #6\n 599,\n 1201,\n 2411,\n 4831,\n 9677,\n 19373,\n 38747,\n 77509,\n 155027,\n 310081,\n 620171,\n 1240361,\n 2480729,\n 4961459,\n 9922933,\n 19845871,\n 39691759,\n 79383533,\n 158767069,\n 317534141,\n 635068283,\n 1270136683,\n\n // chunk #7\n 311,\n 631,\n 1277,\n 2557,\n 5119,\n 10243,\n 20507,\n 41017,\n 82037,\n 164089,\n 328213,\n 656429,\n 1312867,\n 2625761,\n 5251529,\n 10503061,\n 21006137,\n 42012281,\n 84024581,\n 168049163,\n 336098327,\n 672196673,\n 1344393353,\n\n // chunk #8\n 3,\n 7,\n 17,\n 37,\n 79,\n 163,\n 331,\n 673,\n 1361,\n 2729,\n 5471,\n 10949,\n 21911,\n 43853,\n 87719,\n 175447,\n 350899,\n 701819,\n 1403641,\n 2807303,\n 5614657,\n 11229331,\n 22458671,\n 44917381,\n 89834777,\n 179669557,\n 359339171,\n 718678369,\n 1437356741,\n\n // chunk #9\n 43,\n 89,\n 179,\n 359,\n 719,\n 1439,\n 2879,\n 5779,\n 11579,\n 23159,\n 46327,\n 92657,\n 185323,\n 370661,\n 741337,\n 1482707,\n 2965421,\n 5930887,\n 11861791,\n 23723597,\n 47447201,\n 94894427,\n 189788857,\n 379577741,\n 759155483,\n 1518310967,\n\n // chunk #10\n 379,\n 761,\n 1523,\n 3049,\n 6101,\n 12203,\n 24407,\n 48817,\n 97649,\n 195311,\n 390647,\n 781301,\n 1562611,\n 3125257,\n 6250537,\n 12501169,\n 25002389,\n 50004791,\n 100009607,\n 200019221,\n 400038451,\n 800076929,\n 1600153859,\n\n // chunk #11\n 13,\n 29,\n 59,\n 127,\n 257,\n 521,\n 1049,\n 2099,\n 4201,\n 8419,\n 16843,\n 33703,\n 67409,\n 134837,\n 269683,\n 539389,\n 1078787,\n 2157587,\n 4315183,\n 8630387,\n 17260781,\n 34521589,\n 69043189,\n 138086407,\n 276172823,\n 552345671,\n 1104691373,\n\n // chunk #12\n 19,\n 41,\n 83,\n 167,\n 337,\n 677,\n 1361,\n 2729,\n 5471,\n 10949,\n 21911,\n 43853,\n 87719,\n 175447,\n 350899,\n 701819,\n 1403641,\n 2807303,\n 5614657,\n 11229331,\n 22458671,\n 44917381,\n 89834777,\n 179669557,\n 359339171,\n 718678369,\n 1437356741,\n\n // chunk #13\n 53,\n 107,\n 223,\n 449,\n 907,\n 1823,\n 3659,\n 7321,\n 14653,\n 29311,\n 58631,\n 117269,\n 234539,\n 469099,\n 938207,\n 1876417,\n 3752839,\n 7505681,\n 15011389,\n 30022781,\n 60045577,\n 120091177,\n 240182359,\n 480364727,\n 960729461,\n 1921458943\n];\n\nprimeNumbers.sort(ascending);\n\nexport function nextPrime(value) {\n let index = binarySearch(primeNumbers, value, ascending);\n if (index < 0) {\n index = ~index;\n }\n return primeNumbers[index];\n}\n","import { largestPrime, nextPrime } from './primeFinder';\n\nconst FREE = 0;\nconst FULL = 1;\nconst REMOVED = 2;\n\nconst defaultInitialCapacity = 150;\nconst defaultMinLoadFactor = 1 / 6;\nconst defaultMaxLoadFactor = 2 / 3;\n\nexport default class 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 =\n options.initialCapacity === undefined\n ? defaultInitialCapacity\n : options.initialCapacity;\n if (initialCapacity < 0) {\n throw new RangeError(\n `initial capacity must not be less than zero: ${initialCapacity}`\n );\n }\n\n const minLoadFactor =\n options.minLoadFactor === undefined\n ? defaultMinLoadFactor\n : options.minLoadFactor;\n const maxLoadFactor =\n options.maxLoadFactor === undefined\n ? defaultMaxLoadFactor\n : 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(\n `minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`\n );\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);\n this.values = newArray(capacity);\n this.state = newArray(capacity);\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(\n this.distinct + 1,\n this.minLoadFactor,\n this.maxLoadFactor\n );\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(\n this.distinct + 1,\n this.minLoadFactor,\n this.maxLoadFactor\n );\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(\n this.distinct,\n this.minLoadFactor,\n this.maxLoadFactor\n );\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 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);\n const newValues = newArray(newCapacity);\n const newState = newArray(newCapacity);\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\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(\n Math.max(size + 1, ((4 * size) / (3 * minLoad + maxLoad)) | 0)\n );\n}\n\nfunction chooseShrinkCapacity(size, minLoad, maxLoad) {\n return nextPrime(\n Math.max(size + 1, ((4 * size) / (minLoad + 3 * maxLoad)) | 0)\n );\n}\n\nfunction newArray(size) {\n return Array(size).fill(0);\n}\n","import HashTable from 'ml-hash-table';\n\nexport class SparseMatrix {\n constructor(rows, columns, options = {}) {\n if (rows instanceof SparseMatrix) {\n // clone\n const other = rows;\n this._init(\n other.rows,\n other.columns,\n other.elements.clone(),\n other.threshold\n );\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(\n 'Number of columns of left matrix are not equal to number of rows of right matrix.'\n );\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, {\n initialCapacity: this.cardinality\n });\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(\n fillTemplateFunction(inplaceOperator, {\n name: operator[i],\n op: operator[0]\n })\n );\n SparseMatrix.prototype[`${operator[i]}S`] = eval(\n fillTemplateFunction(inplaceOperatorScalar, {\n name: `${operator[i]}S`,\n op: operator[0]\n })\n );\n SparseMatrix.prototype[`${operator[i]}M`] = eval(\n fillTemplateFunction(inplaceOperatorMatrix, {\n name: `${operator[i]}M`,\n op: operator[0]\n })\n );\n\n SparseMatrix[operator[i]] = eval(\n fillTemplateFunction(staticOperator, { name: operator[i] })\n );\n }\n}\n\nvar methods = [['~', 'not']];\n\n[\n 'abs',\n 'acos',\n 'acosh',\n 'asin',\n 'asinh',\n 'atan',\n 'atanh',\n 'cbrt',\n 'ceil',\n 'clz32',\n 'cos',\n 'cosh',\n 'exp',\n 'expm1',\n 'floor',\n 'fround',\n 'log',\n 'log1p',\n 'log10',\n 'log2',\n 'round',\n 'sign',\n 'sin',\n 'sinh',\n 'sqrt',\n 'tan',\n 'tanh',\n '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(\n fillTemplateFunction(inplaceMethod, {\n name: method[i],\n method: method[0]\n })\n );\n SparseMatrix[method[i]] = eval(\n fillTemplateFunction(staticMethod, { name: method[i] })\n );\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","export default function additiveSymmetric(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function avg(a, b) {\n var ii = a.length;\n var max = 0;\n var ans = 0;\n var 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","export default function bhattacharyya(a, b) {\n var ii = a.length;\n var 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","export default function canberra(a, b) {\n var ii = a.length;\n var 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","export default function chebyshev(a, b) {\n var ii = a.length;\n var max = 0;\n var 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","export default function clark(a, b) {\n var i = 0;\n var ii = a.length;\n var d = 0;\n for (; i < ii; i++) {\n d += Math.sqrt(\n ((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i]))\n );\n }\n return 2 * d;\n}\n","export default 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","import czekanowskiSimilarity from '../similarities/czekanowski';\n\nexport default function czekanowskiDistance(a, b) {\n return 1 - czekanowskiSimilarity(a, b);\n}\n","export default function dice(a, b) {\n var ii = a.length;\n var p = 0;\n var q1 = 0;\n var 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","export default function divergence(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function fidelity(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return ans;\n}\n","export default function gower(a, b) {\n var ii = a.length;\n var 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","export default function harmonicMean(a, b) {\n var ii = a.length;\n var 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","export default function hellinger(a, b) {\n var ii = a.length;\n var 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","export default function innerProduct(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans += a[i] * b[i];\n }\n return ans;\n}\n","export default function intersection(a, b) {\n var ii = a.length;\n var 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","export default function jaccard(a, b) {\n var ii = a.length;\n var p1 = 0;\n var p2 = 0;\n var q1 = 0;\n var 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","export default function jeffreys(a, b) {\n var ii = a.length;\n var 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","export default function jensenDifference(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n (a[i] * Math.log(a[i]) + b[i] * Math.log(b[i])) / 2 -\n ((a[i] + b[i]) / 2) * Math.log((a[i] + b[i]) / 2);\n }\n return ans;\n}\n","export default function jensenShannon(a, b) {\n var ii = a.length;\n var p = 0;\n var 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","export default function kdivergence(a, b) {\n var ii = a.length;\n var 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","export default function kulczynski(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function kullbackLeibler(a, b) {\n var ii = a.length;\n var 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","export default function kumarHassebrook(a, b) {\n var ii = a.length;\n var p = 0;\n var p2 = 0;\n var 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","export default function kumarJohnson(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n 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","export default function lorentzian(a, b) {\n var ii = a.length;\n var 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","export default function manhattan(a, b) {\n var i = 0;\n var ii = a.length;\n var d = 0;\n for (; i < ii; i++) {\n d += Math.abs(a[i] - b[i]);\n }\n return d;\n}\n","export default function matusita(a, b) {\n var ii = a.length;\n var 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","export default function minkowski(a, b, p) {\n var i = 0;\n var ii = a.length;\n var 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","export default function motyka(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function neyman(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function pearson(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function probabilisticSymmetric(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function ruzicka(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function soergel(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function sorensen(a, b) {\n var ii = a.length;\n var up = 0;\n var 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","export default function squared(a, b) {\n var i = 0;\n var ii = a.length;\n var 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","export default function squaredChord(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i]));\n }\n return ans;\n}\n","export default function taneja(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n ((a[i] + b[i]) / 2) *\n Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i])));\n }\n return ans;\n}\n","export default function tanimoto(a, b, bitvector) {\n if (bitvector) {\n var inter = 0;\n var 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 }\n return inter / union;\n } else {\n var ii = a.length;\n var p = 0;\n var q = 0;\n var 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","import tanimotoS from '../similarities/tanimoto';\n\nexport default function tanimoto(a, b, bitvector) {\n if (bitvector) {\n return 1 - tanimotoS(a, b, bitvector);\n } else {\n var ii = a.length;\n var p = 0;\n var q = 0;\n var 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","export default function topsoe(a, b) {\n var ii = a.length;\n var ans = 0;\n for (var i = 0; i < ii; i++) {\n ans +=\n a[i] * Math.log((2 * a[i]) / (a[i] + b[i])) +\n b[i] * Math.log((2 * b[i]) / (a[i] + b[i]));\n }\n return ans;\n}\n","export default function waveHedges(a, b) {\n var ii = a.length;\n var 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","import binarySearch from 'binary-search';\nimport { ascending } from 'num-sort';\n\n/**\n * Function that creates the tree\n * @param {Array>} spectrum\n * @param {object} [options]\n * @return {Tree|null}\n * left and right have the same structure than the parent,\n * or are null if they are leaves\n */\nexport function createTree(spectrum, options = {}) {\n var X = spectrum[0];\n const {\n minWindow = 0.16,\n threshold = 0.01,\n from = X[0],\n to = X[X.length - 1]\n } = options;\n\n return mainCreateTree(\n spectrum[0],\n spectrum[1],\n from,\n to,\n minWindow,\n threshold\n );\n}\n\nfunction mainCreateTree(X, Y, from, to, minWindow, threshold) {\n if (to - from < minWindow) {\n return null;\n }\n\n // search first point\n var start = binarySearch(X, from, ascending);\n if (start < 0) {\n start = ~start;\n }\n\n // stop at last point\n var sum = 0;\n var center = 0;\n for (var i = start; i < X.length; i++) {\n if (X[i] >= to) {\n break;\n }\n sum += Y[i];\n center += X[i] * Y[i];\n }\n\n if (sum < threshold) {\n return null;\n }\n\n center /= sum;\n if (center - from < 1e-6 || to - center < 1e-6) {\n return null;\n }\n if (center - from < minWindow / 4) {\n return mainCreateTree(X, Y, center, to, minWindow, threshold);\n } else {\n if (to - center < minWindow / 4) {\n return mainCreateTree(X, Y, from, center, minWindow, threshold);\n } else {\n return new Tree(\n sum,\n center,\n mainCreateTree(X, Y, from, center, minWindow, threshold),\n mainCreateTree(X, Y, center, to, minWindow, threshold)\n );\n }\n }\n}\n\nclass Tree {\n constructor(sum, center, left, right) {\n this.sum = sum;\n this.center = center;\n this.left = left;\n this.right = right;\n }\n}\n","import { createTree } from './createTree';\n\n/**\n * Similarity between two nodes\n * @param {Tree|Array>} a - tree A node\n * @param {Tree|Array>} b - tree B node\n * @param {object} [options]\n * @return {number} similarity measure between tree nodes\n */\nexport function getSimilarity(a, b, options = {}) {\n const { alpha = 0.1, beta = 0.33, gamma = 0.001 } = options;\n\n if (a === null || b === null) {\n return 0;\n }\n if (Array.isArray(a)) {\n a = createTree(a);\n }\n if (Array.isArray(b)) {\n b = createTree(b);\n }\n\n var C =\n (alpha * Math.min(a.sum, b.sum)) / Math.max(a.sum, b.sum) +\n (1 - alpha) * Math.exp(-gamma * Math.abs(a.center - b.center));\n\n return (\n beta * C +\n ((1 - beta) *\n (getSimilarity(a.left, b.left, options) +\n getSimilarity(a.right, b.right, options))) /\n 2\n );\n}\n","import { getSimilarity } from './getSimilarity';\n\nexport { createTree } from './createTree';\n\nexport function treeSimilarity(A, B, options = {}) {\n return getSimilarity(A, B, options);\n}\n\nexport function getFunction(options = {}) {\n return (A, B) => getSimilarity(A, B, options);\n}\n","export default function cosine(a, b) {\n var ii = a.length;\n var p = 0;\n var p2 = 0;\n var 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","import diceD from '../distances/dice';\n\nexport default function dice(a, b) {\n return 1 - diceD(a, b);\n}\n","import intersectionD from '../distances/intersection';\n\nexport default function intersection(a, b) {\n return 1 - intersectionD(a, b);\n}\n","import jaccardD from '../distances/jaccard';\n\nexport default function jaccard(a, b) {\n return 1 - jaccardD(a, b);\n}\n","import kulczynskiD from '../distances/kulczynski';\n\nexport default function kulczynski(a, b) {\n return 1 / kulczynskiD(a, b);\n}\n","import motykaD from '../distances/motyka';\n\nexport default function motyka(a, b) {\n return 1 - motykaD(a, b);\n}\n","import mean from 'ml-array-mean';\n\nimport cosine from './cosine';\n\nexport default function pearson(a, b) {\n var avgA = mean(a);\n var avgB = mean(b);\n\n var newA = new Array(a.length);\n var newB = new Array(b.length);\n for (var i = 0; i < newA.length; i++) {\n newA[i] = a[i] - avgA;\n newB[i] = b[i] - avgB;\n }\n\n return cosine(newA, newB);\n}\n","import squaredChordD from '../distances/squaredChord';\n\nexport default function squaredChord(a, b) {\n return 1 - squaredChordD(a, b);\n}\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\nconst measures = require('./measures');\n\nclass Performance {\n /**\n *\n * @param prediction - The prediction matrix\n * @param target - The target matrix (values: truthy for same class, falsy for different class)\n * @param options\n *\n * @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)\n * @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)\n */\n constructor(prediction, target, options) {\n options = options || {};\n if (prediction.length !== target.length || prediction[0].length !== target[0].length) {\n throw new Error('dimensions of prediction and target do not match');\n }\n const rows = prediction.length;\n const columns = prediction[0].length;\n const isDistance = !options.max;\n\n const predP = [];\n\n if (options.all) {\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n predP.push({\n pred: prediction[i][j],\n targ: target[i][j]\n });\n }\n }\n } else {\n if (rows < 3 || rows !== columns) {\n throw new Error('When \"all\" option is false, the prediction matrix must be square and have at least 3 columns');\n }\n for (var i = 0; i < rows - 1; i++) {\n for (var j = i + 1; j < columns; j++) {\n predP.push({\n pred: prediction[i][j],\n targ: target[i][j]\n });\n }\n }\n }\n\n if (isDistance) {\n predP.sort((a, b) => 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\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\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 }\n output = options.output;\n } else {\n output = new Array(cond);\n }\n\n var i;\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 } else if (options.value === 'replicate') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0]) output[i] = data[0];\n else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];\n else output[i] = data[len - 1];\n }\n } else if (options.value === 'symmetric') {\n if (options.size[0] > len || options.size[1] > len) {\n throw new RangeError(\n 'expanded value should not be bigger than the data length'\n );\n }\n for (i = 0; i < cond; i++) {\n if (i < options.size[0]) output[i] = data[options.size[0] - 1 - i];\n else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];\n else output[i] = data[2 * len + options.size[0] - i - 1];\n }\n } else {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0]) output[i] = options.value;\n else if (i < options.size[0] + len) output[i] = data[i - options.size[0]];\n else 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 }\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 = Object.assign({}, defaultOptions, options);\n if (Array.isArray(data)) {\n if (Array.isArray(data[0])) return matrixCase(data, options);\n else return arrayCase(data, options);\n } else {\n throw new TypeError('data should be an array');\n }\n}\n\nmodule.exports = padArray;\n","import { Matrix, MatrixTransposeView, inverse } from 'ml-matrix';\nimport padArray from 'ml-pad-array';\n\n/**\n * Factorial of a number\n * @ignore\n * @param n\n * @return {number}\n */\nfunction factorial(n) {\n let r = 1;\n while (n > 0) r *= n--;\n return r;\n}\n\nconst 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 */\nexport default function savitzkyGolay(data, h, options) {\n options = Object.assign({}, defaultOptions, options);\n if (\n options.windowSize % 2 === 0 ||\n options.windowSize < 5 ||\n !Number.isInteger(options.windowSize)\n ) {\n throw new RangeError(\n 'Invalid window size (should be odd and at least 5 integer number)',\n );\n }\n if (options.derivative < 0 || !Number.isInteger(options.derivative)) {\n throw new RangeError('Derivative should be a positive integer');\n }\n if (options.polynomial < 1 || !Number.isInteger(options.polynomial)) {\n throw new RangeError('Polynomial should be a positive integer');\n }\n\n let C, norm;\n let step = Math.floor(options.windowSize / 2);\n\n if (options.pad === 'pre') {\n data = padArray(data, { size: step, value: options.padValue });\n }\n\n let ans = new Array(data.length - 2 * step);\n\n if (\n options.windowSize === 5 &&\n options.polynomial === 2 &&\n (options.derivative === 1 || options.derivative === 2)\n ) {\n if (options.derivative === 1) {\n C = [-2, -1, 0, 1, 2];\n norm = 10;\n } else {\n C = [2, -1, -2, -1, 2];\n norm = 7;\n }\n } else {\n let J = Matrix.ones(options.windowSize, options.polynomial + 1);\n let inic = -(options.windowSize - 1) / 2;\n for (let i = 0; i < J.rows; i++) {\n for (let j = 0; j < J.columns; j++) {\n if (inic + 1 !== 0 || j !== 0) J.set(i, j, Math.pow(inic + i, j));\n }\n }\n let Jtranspose = new MatrixTransposeView(J);\n let Jinv = inverse(Jtranspose.mmul(J));\n C = Jinv.mmul(Jtranspose);\n C = C.getRow(options.derivative);\n norm = 1 / factorial(options.derivative);\n }\n let det = norm * Math.pow(h, options.derivative);\n for (let k = step; k < data.length - step; k++) {\n let d = 0;\n for (let l = 0; l < C.length; l++) 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","// 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\nvar eightBits = require('./creator');\n\n/**\n * Count the number of true values in an array\n * @param {Array} arr\n * @return {number}\n */\nfunction count(arr) {\n var c = 0;\n for (var i = 0; i < arr.length; i++) {\n c += eightBits[arr[i] & 0xff] + eightBits[(arr[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","export default function SavitzkyGolay(data, h, options = {}) {\n let { windowSize = 9, derivative = 0, polynomial = 3 } = options;\n\n if (windowSize % 2 === 0 || windowSize < 5 || !Number.isInteger(windowSize)) {\n throw new RangeError(\n 'Invalid window size (should be odd and at least 5 integer number)',\n );\n }\n if (windowSize > data.length) {\n throw new RangeError(\n `Window size is higher than the data length ${windowSize}>${data.length}`,\n );\n }\n if (derivative < 0 || !Number.isInteger(derivative)) {\n throw new RangeError('Derivative should be a positive integer');\n }\n if (polynomial < 1 || !Number.isInteger(polynomial)) {\n throw new RangeError('Polynomial should be a positive integer');\n }\n if (polynomial >= 6) {\n // eslint-disable-next-line no-console\n console.warn(\n '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 }\n\n let half = Math.floor(windowSize / 2);\n let np = data.length;\n let ans = new Array(np);\n let weights = fullWeights(windowSize, polynomial, derivative);\n let hs = 0;\n let constantH = true;\n if (Array.isArray(h)) {\n constantH = false;\n } else {\n hs = Math.pow(h, derivative);\n }\n\n //For the borders\n for (let i = 0; i < half; i++) {\n let wg1 = weights[half - i - 1];\n let wg2 = weights[half + i + 1];\n let d1 = 0;\n let d2 = 0;\n for (let l = 0; l < windowSize; l++) {\n d1 += wg1[l] * data[l];\n d2 += wg2[l] * data[np - windowSize + l];\n }\n if (constantH) {\n ans[half - i - 1] = d1 / hs;\n ans[np - half + i] = d2 / hs;\n } else {\n hs = getHs(h, half - i - 1, half, derivative);\n ans[half - i - 1] = d1 / hs;\n hs = getHs(h, np - half + i, half, derivative);\n ans[np - half + i] = d2 / hs;\n }\n }\n\n //For the internal points\n let wg = weights[half];\n for (let i = windowSize; i <= np; i++) {\n let d = 0;\n for (let l = 0; l < windowSize; l++) d += wg[l] * data[l + i - windowSize];\n if (!constantH) hs = getHs(h, i - half - 1, half, derivative);\n ans[i - half - 1] = d / hs;\n }\n return ans;\n}\n\nfunction getHs(h, center, half, derivative) {\n let hs = 0;\n let count = 0;\n for (let i = center - half; i < center + half; i++) {\n if (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 let Grampoly = 0;\n if (k > 0) {\n Grampoly =\n ((4 * k - 2) / (k * (2 * m - k + 1))) *\n (i * GramPoly(i, m, k - 1, s) + s * GramPoly(i, m, k - 1, s - 1)) -\n (((k - 1) * (2 * m + k)) / (k * (2 * m - k + 1))) *\n GramPoly(i, m, k - 2, s);\n } else {\n if (k === 0 && s === 0) {\n Grampoly = 1;\n } else {\n Grampoly = 0;\n }\n }\n return Grampoly;\n}\n\nfunction GenFact(a, b) {\n let gf = 1;\n if (a >= b) {\n for (let 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 let sum = 0;\n for (let k = 0; k <= n; k++) {\n //console.log(k);\n sum +=\n (2 * k + 1) *\n (GenFact(2 * m, k) / GenFact(2 * m + k + 1, k + 1)) *\n GramPoly(i, m, k, 0) *\n 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 let weights = new Array(m);\n let np = Math.floor(m / 2);\n for (let t = -np; t <= np; t++) {\n weights[t + np] = new Array(m);\n for (let 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} x - Independent variable\n * @param {Array} yIn - Dependent variable\n * @param {object} [options] - Options object\n * @param {object} [options.sgOptions] - Options object for Savitzky-Golay filter. See https://github.com/mljs/savitzky-golay-generalized#options\n * @param {number} [options.sgOptions.windowSize = 9] - points to use in the approximations\n * @param {number} [options.sgOptions.polynomial = 3] - degree of the polynomial to use in the approximations\n * @param {number} [options.minMaxRatio = 0.00025] - Threshold to determine if a given peak should be considered as a noise\n * @param {number} [options.broadRatio = 0.00] - If `broadRatio` is higher than 0, then all the peaks which second derivative\n * smaller than `broadRatio * maxAbsSecondDerivative` will be marked with the soft mask equal to true.\n * @param {number} [options.noiseLevel = 0] - Noise threshold in spectrum units\n * @param {boolean} [options.maxCriteria = true] - Peaks are local maximum(true) or minimum(false)\n * @param {boolean} [options.smoothY = true] - Select the peak intensities from a smoothed version of the independent variables\n * @param {boolean} [options.realTopDetection = false] - Use a quadratic optimizations with the peak and its 3 closest neighbors\n * to determine the true x,y values of the peak?\n * @param {number} [options.heightFactor = 0] - Factor to multiply the calculated height (usually 2)\n * @param {number} [options.derivativeThreshold = -1] - Filters based on the amplitude of the first derivative\n * @return {Array}\n */\nexport function gsd(x, yIn, options = {}) {\n let {\n noiseLevel,\n sgOptions = {\n windowSize: 9,\n polynomial: 3,\n },\n smoothY = true,\n heightFactor = 0,\n broadRatio = 0.0,\n maxCriteria = true,\n minMaxRatio = 0.00025,\n derivativeThreshold = -1,\n realTopDetection = false,\n } = options;\n\n const y = yIn.slice();\n let equalSpaced = isEqualSpaced(x);\n\n if (noiseLevel === undefined) {\n noiseLevel = equalSpaced ? getNoiseLevel(y) : 0;\n }\n\n const yCorrection = { m: 1, b: noiseLevel };\n\n if (!maxCriteria) {\n yCorrection.m = -1;\n yCorrection.b *= -1;\n }\n\n for (let i = 0; i < y.length; i++) {\n y[i] = yCorrection.m * y[i] - yCorrection.b;\n }\n\n for (let i = 0; i < y.length; i++) {\n if (y[i] < 0) {\n y[i] = 0;\n }\n }\n // If the max difference between delta x is less than 5%, then,\n // we can assume it to be equally spaced variable\n let yData = y;\n let dY, ddY;\n const { windowSize, polynomial } = sgOptions;\n\n if (equalSpaced) {\n if (smoothY) {\n yData = SG(y, x[1] - x[0], {\n windowSize,\n polynomial,\n derivative: 0,\n });\n }\n dY = SG(y, x[1] - x[0], {\n windowSize,\n polynomial,\n derivative: 1,\n });\n ddY = SG(y, x[1] - x[0], {\n windowSize,\n polynomial,\n derivative: 2,\n });\n } else {\n if (smoothY) {\n yData = SG(y, x, {\n windowSize,\n polynomial,\n derivative: 0,\n });\n }\n dY = SG(y, x, {\n windowSize,\n polynomial,\n derivative: 1,\n });\n ddY = SG(y, x, {\n windowSize,\n polynomial,\n derivative: 2,\n });\n }\n\n const xData = x;\n const dX = x[1] - x[0];\n let maxDdy = 0;\n let maxY = 0;\n for (let i = 0; i < yData.length; i++) {\n if (Math.abs(ddY[i]) > maxDdy) {\n maxDdy = Math.abs(ddY[i]);\n }\n if (Math.abs(yData[i]) > maxY) {\n maxY = Math.abs(yData[i]);\n }\n }\n\n let lastMax = null;\n let lastMin = null;\n let minddY = new Array(yData.length - 2);\n let intervalL = new Array(yData.length);\n let intervalR = new Array(yData.length);\n let broadMask = new Array(yData.length - 2);\n let minddYLen = 0;\n let intervalLLen = 0;\n let intervalRLen = 0;\n let broadMaskLen = 0;\n // By the intermediate value theorem We cannot find 2 consecutive maximum or minimum\n for (let i = 1; i < yData.length - 1; ++i) {\n // filter based on derivativeThreshold\n // console.log('pasa', y[i], dY[i], ddY[i]);\n if (Math.abs(dY[i]) > derivativeThreshold) {\n // Minimum in first derivative\n if (\n (dY[i] < dY[i - 1] && dY[i] <= dY[i + 1]) ||\n (dY[i] <= dY[i - 1] && dY[i] < dY[i + 1])\n ) {\n lastMin = {\n x: xData[i],\n index: i,\n };\n if (dX > 0 && lastMax !== null) {\n intervalL[intervalLLen++] = lastMax;\n intervalR[intervalRLen++] = lastMin;\n }\n }\n\n // Maximum in first derivative\n if (\n (dY[i] >= dY[i - 1] && dY[i] > dY[i + 1]) ||\n (dY[i] > dY[i - 1] && dY[i] >= dY[i + 1])\n ) {\n lastMax = {\n x: xData[i],\n index: i,\n };\n if (dX < 0 && lastMin !== null) {\n intervalL[intervalLLen++] = lastMax;\n intervalR[intervalRLen++] = lastMin;\n }\n }\n }\n\n // Minimum in second derivative\n if (ddY[i] < ddY[i - 1] && ddY[i] < ddY[i + 1]) {\n // TODO should we change this to have 3 arrays ? Huge overhead creating arrays\n minddY[minddYLen++] = i; // ( [xData[i], yData[i], i] );\n broadMask[broadMaskLen++] = Math.abs(ddY[i]) <= broadRatio * maxDdy;\n }\n }\n minddY.length = minddYLen;\n intervalL.length = intervalLLen;\n intervalR.length = intervalRLen;\n broadMask.length = broadMaskLen;\n\n let signals = new Array(minddY.length);\n let signalsLen = 0;\n let lastK = -1;\n let possible, frequency, distanceJ, minDistance, gettingCloser;\n for (let j = 0; j < minddY.length; ++j) {\n frequency = xData[minddY[j]];\n possible = -1;\n let k = lastK + 1;\n minDistance = Number.MAX_VALUE;\n distanceJ = 0;\n gettingCloser = true;\n while (possible === -1 && k < intervalL.length && gettingCloser) {\n distanceJ = Math.abs(frequency - (intervalL[k].x + intervalR[k].x) / 2);\n\n // Still getting closer?\n if (distanceJ < minDistance) {\n minDistance = distanceJ;\n } else {\n gettingCloser = false;\n }\n if (distanceJ < Math.abs(intervalL[k].x - intervalR[k].x) / 2) {\n possible = k;\n lastK = k;\n }\n ++k;\n }\n\n if (possible !== -1) {\n if (Math.abs(yData[minddY[j]]) > minMaxRatio * maxY) {\n signals[signalsLen++] = {\n index: minddY[j],\n x: frequency,\n y: (yData[minddY[j]] + yCorrection.b) / yCorrection.m,\n width: Math.abs(intervalR[possible].x - intervalL[possible].x), // widthCorrection\n soft: broadMask[j],\n };\n\n signals[signalsLen - 1].left = intervalL[possible];\n signals[signalsLen - 1].right = intervalR[possible];\n\n if (heightFactor) {\n let yLeft = yData[intervalL[possible].index];\n let yRight = yData[intervalR[possible].index];\n signals[signalsLen - 1].height =\n heightFactor * (signals[signalsLen - 1].y - (yLeft + yRight) / 2);\n }\n }\n }\n }\n signals.length = signalsLen;\n\n if (realTopDetection) {\n determineRealTop(signals, xData, yData);\n }\n\n // Correct the values to fit the original spectra data\n for (let j = 0; j < signals.length; j++) {\n signals[j].base = noiseLevel;\n }\n\n signals.sort(function (a, b) {\n return a.x - b.x;\n });\n\n return signals;\n}\n\nconst isEqualSpaced = (x) => {\n let tmp;\n let maxDx = 0;\n let minDx = Number.MAX_SAFE_INTEGER;\n for (let i = 0; i < x.length - 1; ++i) {\n tmp = Math.abs(x[i + 1] - x[i]);\n if (tmp < minDx) {\n minDx = tmp;\n }\n if (tmp > maxDx) {\n maxDx = tmp;\n }\n }\n return (maxDx - minDx) / maxDx < 0.05;\n};\n\nconst getNoiseLevel = (y) => {\n let mean = 0;\n\n let stddev = 0;\n let length = y.length;\n for (let i = 0; i < length; ++i) {\n mean += y[i];\n }\n mean /= length;\n let averageDeviations = new Array(length);\n for (let i = 0; i < length; ++i) {\n averageDeviations[i] = Math.abs(y[i] - mean);\n }\n averageDeviations.sort((a, b) => a - b);\n if (length % 2 === 1) {\n stddev = averageDeviations[(length - 1) / 2] / 0.6745;\n } else {\n stddev =\n (0.5 *\n (averageDeviations[length / 2] + averageDeviations[length / 2 - 1])) /\n 0.6745;\n }\n\n return stddev;\n};\n\nconst determineRealTop = (peakList, x, y) => {\n let alpha, beta, gamma, p, currentPoint;\n for (let j = 0; j < peakList.length; j++) {\n currentPoint = peakList[j].index; // peakList[j][2];\n // The detected peak could be moved 1 or 2 units to left or right.\n if (\n y[currentPoint - 1] >= y[currentPoint - 2] &&\n y[currentPoint - 1] >= y[currentPoint]\n ) {\n currentPoint--;\n } else {\n if (\n y[currentPoint + 1] >= y[currentPoint] &&\n y[currentPoint + 1] >= y[currentPoint + 2]\n ) {\n currentPoint++;\n } else {\n if (\n y[currentPoint - 2] >= y[currentPoint - 3] &&\n y[currentPoint - 2] >= y[currentPoint - 1]\n ) {\n currentPoint -= 2;\n } else {\n if (\n y[currentPoint + 2] >= y[currentPoint + 1] &&\n y[currentPoint + 2] >= y[currentPoint + 3]\n ) {\n currentPoint += 2;\n }\n }\n }\n }\n // interpolation to a sin() function\n if (\n y[currentPoint - 1] > 0 &&\n y[currentPoint + 1] > 0 &&\n y[currentPoint] >= y[currentPoint - 1] &&\n y[currentPoint] >= y[currentPoint + 1] &&\n (y[currentPoint] !== y[currentPoint - 1] ||\n y[currentPoint] !== y[currentPoint + 1])\n ) {\n alpha = 20 * Math.log10(y[currentPoint - 1]);\n beta = 20 * Math.log10(y[currentPoint]);\n gamma = 20 * Math.log10(y[currentPoint + 1]);\n p = (0.5 * (alpha - gamma)) / (alpha - 2 * beta + gamma);\n // console.log(alpha, beta, gamma, `p: ${p}`);\n // console.log(x[currentPoint]+\" \"+tmp+\" \"+currentPoint);\n peakList[j].x =\n x[currentPoint] + (x[currentPoint] - x[currentPoint - 1]) * p;\n peakList[j].y =\n y[currentPoint] -\n 0.25 * (y[currentPoint - 1] - y[currentPoint + 1]) * p;\n }\n }\n};\n","/**\n * This function calculates the spectrum as a sum of gaussian functions. The Gaussian\n * parameters are divided in 3 batches. 1st: centers; 2nd: height; 3th: std's;\n * @param t Ordinate values\n * @param p Gaussian parameters\n * @param c Constant parameters(Not used)\n * @returns {*}\n */\nexport function sumOfGaussians(p) {\n return function (t) {\n let nL = p.length / 3;\n let factor;\n let rows = t.length;\n let result = rows === undefined ? 0 : new Float64Array(rows).fill(0);\n for (let i = 0; i < nL; i++) {\n factor = Math.pow(p[i + nL * 2], 2) * 2;\n if (rows === undefined) {\n result += p[i + nL] * Math.exp(-Math.pow(t - p[i], 2) / factor);\n } else {\n for (let j = 0; j < rows; j++) {\n result[j] += p[i + nL] * Math.exp(-Math.pow(t[j] - p[i], 2) / factor);\n }\n }\n }\n return result;\n };\n}\n","import LM from 'ml-levenberg-marquardt';\n\nimport { sumOfGaussians } from './sumOfGaussians';\n\n/**\n *\n * @param xy A two column matrix containing the x and y data to be fitted\n * @param group A set of initial lorentzian parameters to be optimized [center, heigth, half_width_at_half_height]\n * @returns {Array} A set of final lorentzian parameters [center, heigth, hwhh*2]\n */\nexport function optimizeGaussianSum(xy, group, opts = {}) {\n let t = xy[0];\n let yData = xy[1];\n let maxY = Math.max(...yData);\n yData.forEach((x, i, arr) => (arr[i] /= maxY));\n let nL = group.length;\n let pInit = new Float64Array(nL * 3);\n let pMin = new Float64Array(nL * 3);\n let pMax = new Float64Array(nL * 3);\n let dt = Math.abs(t[0] - t[1]);\n\n for (let i = 0; i < nL; i++) {\n pInit[i] = group[i].x;\n pInit[i + nL] = group[i].y / maxY;\n pInit[i + 2 * nL] = group[i].width;\n\n pMin[i] = group[i].x - dt;\n pMin[i + nL] = 0;\n pMin[i + 2 * nL] = group[i].width / 4;\n\n pMax[i] = group[i].x + dt;\n pMax[i + nL] = (group[i].y * 1.2) / maxY;\n pMax[i + 2 * nL] = group[i].width * 4;\n }\n\n let data = {\n x: t,\n y: yData,\n };\n let result = new Array(nL);\n\n let lmOptions = {\n damping: 1.5,\n initialValues: pInit,\n minValues: pMin,\n maxValues: pMax,\n gradientDifference: dt / 10000,\n maxIterations: 100,\n errorTolerance: 10e-5,\n };\n\n opts = Object.assign({}, lmOptions, opts);\n\n let pFit = LM(data, sumOfGaussians, opts);\n for (let i = 0; i < nL; i++) {\n result[i] = {\n parameters: [\n pFit.parameterValues[i],\n pFit.parameterValues[i + nL] * maxY,\n pFit.parameterValues[i + nL * 2],\n ],\n error: pFit.parameterError,\n };\n }\n return result;\n}\n","/**\n * Single 3 parameter gaussian function\n * @param t Ordinate values\n * @param p Gaussian parameters [mean, height, std]\n * @param c Constant parameters(Not used)\n * @returns {*}\n */\n\nexport function singleGaussian(p) {\n return function (t) {\n let factor2 = (p[2] * p[2]) / 2;\n let rows = t.length;\n if (!rows) return p[1] * Math.exp((-(t - p[0]) * (t - p[0])) / factor2);\n let result = new Float64Array(t.length);\n for (let i = 0; i < t.length; i++) {\n result[i] = p[1] * Math.exp((-(t[i] - p[0]) * (t[i] - p[0])) / factor2);\n }\n return result;\n };\n}\n","import LM from 'ml-levenberg-marquardt';\n\nimport { singleGaussian } from './singleGaussian';\n\n/**\n * Fits a set of points to a gaussian bell. Returns the mean of the peak, the std and the height of the signal.\n * @param data,[y]\n * @returns {*[]}\n */\nexport function optimizeSingleGaussian(xy, peak, opts = {}) {\n let t = xy[0];\n let yData = xy[1];\n let maxY = Math.max(...yData);\n yData.forEach((x, i, arr) => (arr[i] /= maxY));\n let dt = Math.abs(t[0] - t[1]);\n let pInit = new Float64Array([peak.x, 1, peak.width]);\n let pMin = new Float64Array([peak.x - dt, 0, peak.width / 4]);\n let pMax = new Float64Array([peak.x + dt, 1.25, peak.width * 4]);\n\n let data = {\n x: t,\n y: yData,\n };\n\n let lmOptions = {\n damping: 1.5,\n initialValues: pInit,\n minValues: pMin,\n maxValues: pMax,\n gradientDifference: dt / 10000,\n maxIterations: 100,\n errorTolerance: 10e-5,\n };\n\n opts = Object.assign({}, lmOptions, opts);\n let pFit = LM(data, singleGaussian, opts);\n return {\n parameters: [\n pFit.parameterValues[0],\n pFit.parameterValues[1] * maxY,\n pFit.parameterValues[2],\n ],\n error: pFit.parameterError,\n };\n}\n","/**\n * This function calculates the spectrum as a sum of lorentzian functions. The Lorentzian\n * parameters are divided in 3 batches. 1st: centers; 2nd: heights; 3th: widths;\n * @param t Ordinate values\n * @param p Lorentzian parameters\n * @returns {*}\n */\n\nexport function sumOfLorentzians(p) {\n return function (t) {\n let nL = p.length / 3;\n let factor;\n let p2;\n let rows = t.length;\n let result = rows === undefined ? 0 : new Float64Array(rows).fill(0);\n for (let i = 0; i < nL; i++) {\n p2 = Math.pow(p[i + nL * 2] / 2, 2);\n factor = p[i + nL] * p2;\n if (rows === undefined) {\n result += factor / (Math.pow(t - p[i], 2) + p2);\n } else {\n for (let j = 0; j < rows; j++) {\n result[j] += factor / (Math.pow(t[j] - p[i], 2) + p2);\n }\n }\n }\n return result;\n };\n}\n","import LM from 'ml-levenberg-marquardt';\n\nimport { sumOfLorentzians } from './sumOfLorentzians';\n\n/**\n *\n * @param xy A two column matrix containing the x and y data to be fitted\n * @param group A set of initial lorentzian parameters to be optimized [center, heigth, half_width_at_half_height]\n * @returns {Array} A set of final lorentzian parameters [center, heigth, hwhh*2]\n */\nexport function optimizeLorentzianSum(xy, group, opts = {}) {\n let t = xy[0];\n let yData = xy[1];\n let maxY = Math.max(...yData);\n yData.forEach((x, i, arr) => (arr[i] /= maxY));\n\n let nL = group.length;\n let pInit = new Float64Array(nL * 3);\n let pMin = new Float64Array(nL * 3);\n let pMax = new Float64Array(nL * 3);\n let dt = Math.abs(t[0] - t[1]);\n\n for (let i = 0; i < nL; i++) {\n pInit[i] = group[i].x;\n pInit[i + nL] = 1;\n pInit[i + 2 * nL] = group[i].width;\n\n pMin[i] = group[i].x - dt;\n pMin[i + nL] = 0;\n pMin[i + 2 * nL] = group[i].width / 4;\n\n pMax[i] = group[i].x + dt;\n pMax[i + nL] = 1.5;\n pMax[i + 2 * nL] = group[i].width * 4;\n }\n\n let data = {\n x: t,\n y: yData,\n };\n\n let result = new Array(nL);\n\n let lmOptions = {\n damping: 1.5,\n initialValues: pInit,\n minValues: pMin,\n maxValues: pMax,\n gradientDifference: dt / 10000,\n maxIterations: 100,\n errorTolerance: 10e-5,\n };\n\n opts = Object.assign({}, lmOptions, opts);\n\n let pFit = LM(data, sumOfLorentzians, opts);\n for (let i = 0; i < nL; i++) {\n result[i] = {\n parameters: [\n pFit.parameterValues[i],\n pFit.parameterValues[i + nL] * maxY,\n pFit.parameterValues[i + nL * 2],\n ],\n error: pFit.parameterError,\n };\n }\n return result;\n}\n","/**\n * Single 4 parameter lorentzian function\n * @param t Ordinate values\n * @param p Lorentzian parameters\n * @param c Constant parameters(Not used)\n * @returns {*}\n */\n\nexport function singleLorentzian(p) {\n return function (t) {\n let factor = p[1] * Math.pow(p[2] / 2, 2);\n let rows = t.length;\n if (!rows) return factor / (Math.pow(t - p[0], 2) + Math.pow(p[2] / 2, 2));\n let result = new Float64Array(rows);\n for (let i = 0; i < rows; i++) {\n result[i] = factor / (Math.pow(t[i] - p[0], 2) + Math.pow(p[2] / 2, 2));\n }\n return result;\n };\n}\n","import LM from 'ml-levenberg-marquardt';\n\nimport { singleLorentzian } from './singleLorentzian';\n\n/**\n * * Fits a set of points to a Lorentzian function. Returns the center of the peak, the width at half height, and the height of the signal.\n * @param data,[y]\n * @returns {*[]}\n */\nexport function optimizeSingleLorentzian(xy, peak, opts = {}) {\n let t = xy[0];\n let yData = xy[1];\n let maxY = Math.max(...yData);\n yData.forEach((x, i, arr) => (arr[i] /= maxY));\n let dt = Math.abs(t[0] - t[1]);\n let pInit = new Float64Array([peak.x, 1, peak.width]);\n let pMin = new Float64Array([peak.x - dt, 0.75, peak.width / 4]);\n let pMax = new Float64Array([peak.x + dt, 1.25, peak.width * 4]);\n\n let data = {\n x: t,\n y: yData,\n };\n\n let lmOptions = {\n damping: 1.5,\n initialValues: pInit,\n minValues: pMin,\n maxValues: pMax,\n gradientDifference: dt / 10000,\n maxIterations: 100,\n errorTolerance: 10e-5,\n };\n opts = Object.assign({}, lmOptions, opts);\n let pFit = LM(data, singleLorentzian, opts);\n return {\n parameters: [\n pFit.parameterValues[0],\n pFit.parameterValues[1] * maxY,\n pFit.parameterValues[2],\n ],\n error: pFit.parameterError,\n };\n}\n","import {\n optimizeGaussianSum,\n optimizeLorentzianSum,\n optimizeSingleGaussian,\n optimizeSingleLorentzian,\n} from 'ml-optimize-lorentzian';\n\nexport function optimizePeaks(peakList, x, y, options = {}) {\n const {\n functionName = 'gaussian',\n factorWidth = 4,\n optimizationOptions = {\n damping: 1.5,\n maxIterations: 100,\n errorTolerance: 10e-5,\n },\n } = options;\n\n let lastIndex = [0];\n let groups = groupPeaks(peakList, factorWidth);\n let result = [];\n let factor = 1;\n if (functionName === 'gaussian') {\n factor = 1.17741;\n } // From https://en.wikipedia.org/wiki/Gaussian_function#Properties\n let sampling;\n for (let i = 0; i < groups.length; i++) {\n let peaks = groups[i].group;\n if (peaks.length > 1) {\n // Multiple peaks\n sampling = sampleFunction(\n groups[i].limits[0] - groups[i].limits[1],\n groups[i].limits[0] + groups[i].limits[1],\n x,\n y,\n lastIndex,\n );\n if (sampling[0].length > 5) {\n let optPeaks = [];\n if (functionName === 'gaussian') {\n optPeaks = optimizeGaussianSum(sampling, peaks, optimizationOptions);\n } else {\n if (functionName === 'lorentzian') {\n optPeaks = optimizeLorentzianSum(\n sampling,\n peaks,\n optimizationOptions,\n );\n }\n }\n\n for (let j = 0; j < optPeaks.length; j++) {\n let { parameters } = optPeaks[j];\n result.push({\n x: parameters[0],\n y: parameters[1],\n width: parameters[2] * factor,\n index: peaks[j].index,\n });\n }\n }\n } else {\n // Single peak\n peaks = peaks[0];\n sampling = sampleFunction(\n peaks.x - factorWidth * peaks.width,\n peaks.x + factorWidth * peaks.width,\n x,\n y,\n lastIndex,\n );\n\n if (sampling[0].length > 5) {\n let fitResult = [];\n if (functionName === 'gaussian') {\n fitResult = optimizeSingleGaussian(\n [sampling[0], sampling[1]],\n peaks,\n optimizationOptions,\n );\n } else {\n if (functionName === 'lorentzian') {\n fitResult = optimizeSingleLorentzian(\n [sampling[0], sampling[1]],\n peaks,\n optimizationOptions,\n );\n }\n }\n\n let { parameters } = fitResult;\n result.push({\n x: parameters[0],\n y: parameters[1],\n width: parameters[2] * factor,\n index: peaks.index,\n }); // From https://en.wikipedia.org/wiki/Gaussian_function#Properties}\n }\n }\n }\n return result;\n}\n\nfunction sampleFunction(from, to, x, y, lastIndex) {\n let nbPoints = x.length;\n let sampleX = [];\n let sampleY = [];\n let direction = Math.sign(x[1] - x[0]); // Direction of the derivative\n if (direction === -1) {\n lastIndex[0] = x.length - 1;\n }\n\n let delta = Math.abs(to - from) / 2;\n let mid = (from + to) / 2;\n let stop = false;\n let index = lastIndex[0];\n while (!stop && index < nbPoints && index >= 0) {\n if (Math.abs(x[index] - mid) <= delta) {\n sampleX.push(x[index]);\n sampleY.push(y[index]);\n index += direction;\n } else {\n // It is outside the range.\n if (Math.sign(mid - x[index]) === 1) {\n // We'll reach the mid going in the current direction\n index += direction;\n } else {\n // There is not more peaks in the current range\n stop = true;\n }\n }\n }\n lastIndex[0] = index;\n return [sampleX, sampleY];\n}\n\nfunction groupPeaks(peakList, nL) {\n let group = [];\n let groups = [];\n let limits = [peakList[0].x, nL * peakList[0].width];\n let upperLimit, lowerLimit;\n // Merge forward\n for (let i = 0; i < peakList.length; i++) {\n // If the 2 things overlaps\n if (\n Math.abs(peakList[i].x - limits[0]) <\n nL * peakList[i].width + limits[1]\n ) {\n // Add the peak to the group\n group.push(peakList[i]);\n // Update the group limits\n upperLimit = limits[0] + limits[1];\n if (peakList[i].x + nL * peakList[i].width > upperLimit) {\n upperLimit = peakList[i].x + nL * peakList[i].width;\n }\n lowerLimit = limits[0] - limits[1];\n if (peakList[i].x - nL * peakList[i].width < lowerLimit) {\n lowerLimit = peakList[i].x - nL * peakList[i].width;\n }\n limits = [\n (upperLimit + lowerLimit) / 2,\n Math.abs(upperLimit - lowerLimit) / 2,\n ];\n } else {\n groups.push({ limits: limits, group: group });\n // var optmimalPeak = fitSpectrum(group,limits,spectrum);\n group = [peakList[i]];\n limits = [peakList[i].x, nL * peakList[i].width];\n }\n }\n groups.push({ limits: limits, group: group });\n // Merge backward\n for (let i = groups.length - 2; i >= 0; i--) {\n // The groups overlaps\n if (\n Math.abs(groups[i].limits[0] - groups[i + 1].limits[0]) <\n (groups[i].limits[1] + groups[i + 1].limits[1]) / 2\n ) {\n for (let j = 0; j < groups[i + 1].group.length; j++) {\n groups[i].group.push(groups[i + 1].group[j]);\n }\n upperLimit = groups[i].limits[0] + groups[i].limits[1];\n if (groups[i + 1].limits[0] + groups[i + 1].limits[1] > upperLimit) {\n upperLimit = groups[i + 1].limits[0] + groups[i + 1].limits[1];\n }\n lowerLimit = groups[i].limits[0] - groups[i].limits[1];\n if (groups[i + 1].limits[0] - groups[i + 1].limits[1] < lowerLimit) {\n lowerLimit = groups[i + 1].limits[0] - groups[i + 1].limits[1];\n }\n\n groups[i].limits = [\n (upperLimit + lowerLimit) / 2,\n Math.abs(upperLimit - lowerLimit) / 2,\n ];\n\n groups.splice(i + 1, 1);\n }\n }\n return groups;\n}\n","import { optimizeSingleLorentzian } from 'ml-optimize-lorentzian';\n\n/**\n * This function try to join the peaks that seems to belong to a broad signal in a single broad peak.\n * @param peakList\n * @param options\n */\nexport function joinBroadPeaks(peakList, options = {}) {\n let width = options.width;\n let broadLines = [];\n // Optimize the possible broad lines\n let max = 0;\n\n let maxI = 0;\n\n let count = 1;\n for (let i = peakList.length - 1; i >= 0; i--) {\n if (peakList[i].soft) {\n broadLines.push(peakList.splice(i, 1)[0]);\n }\n }\n // Push a feke peak\n broadLines.push({ x: Number.MAX_VALUE });\n\n let candidates = [[broadLines[0].x, broadLines[0].y]];\n let indexes = [broadLines[0].index];\n\n for (let i = 1; i < broadLines.length; i++) {\n // console.log(broadLines[i-1].x+\" \"+broadLines[i].x);\n if (Math.abs(broadLines[i - 1].x - broadLines[i].x) < width) {\n candidates.push([broadLines[i].x, broadLines[i].y]);\n if (broadLines[i].y > max) {\n max = broadLines[i].y;\n maxI = i;\n }\n indexes.push(broadLines[i].index);\n count++;\n } else {\n if (count > 2) {\n let fitted = optimizeSingleLorentzian(candidates, {\n x: broadLines[maxI].x,\n y: max,\n width: Math.abs(\n candidates[0][0] - candidates[candidates.length - 1][0],\n ),\n });\n let { parameters } = fitted;\n peakList.push({\n x: parameters[0],\n y: parameters[1],\n width: parameters[2],\n index: Math.floor(\n indexes.reduce((a, b) => a + b, 0) / indexes.length,\n ),\n soft: false,\n });\n } else {\n // Put back the candidates to the signals list\n indexes.forEach((index) => {\n peakList.push(broadLines[index]);\n });\n }\n candidates = [[broadLines[i].x, broadLines[i].y]];\n indexes = [i];\n max = broadLines[i].y;\n maxI = i;\n count = 1;\n }\n }\n\n peakList.sort(function (a, b) {\n return a.x - b.x;\n });\n\n return peakList;\n}\n","/**\n * This method will allow to enlarge peaks and prevent overlap between peaks\n * Because peaks may not be symmetric after we add 2 properties, from and to.\n * @param {Array} peakList\n * @param {object} [options={}]\n * @param {number} [factor=2]\n * @param {boolean} [overlap=false] by default we don't allow overlap\n * @return {Array} peakList\n */\nexport function broadenPeaks(peakList, options = {}) {\n const { factor = 2, overlap = false } = options;\n\n for (let peak of peakList) {\n if (!peak.right || !peak.left) {\n peak.from = peak.x - (peak.width / 2) * factor;\n peak.to = peak.x + (peak.width / 2) * factor;\n } else {\n peak.from = peak.x - (peak.x - peak.left.x) * factor;\n peak.to = peak.x + (peak.right.x - peak.x) * factor;\n }\n }\n\n if (!overlap) {\n for (let i = 0; i < peakList.length - 1; i++) {\n let peak = peakList[i];\n let nextPeak = peakList[i + 1];\n if (peak.to > nextPeak.from) {\n peak.to = nextPeak.from = (peak.to + nextPeak.from) / 2;\n }\n }\n }\n\n for (let peak of peakList) {\n peak.width = peak.to - peak.from;\n }\n\n return peakList;\n}\n","const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n","import isArray from 'is-any-array';\n\nfunction min(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 }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var _options$fromIndex = options.fromIndex,\n fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,\n _options$toIndex = options.toIndex,\n toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;\n\n if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {\n throw new Error('fromIndex must be a positive integer smaller than length');\n }\n\n if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {\n throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');\n }\n\n var minValue = input[fromIndex];\n\n for (var i = fromIndex + 1; i < toIndex; i++) {\n if (input[i] < minValue) minValue = input[i];\n }\n\n return minValue;\n}\n\nexport default min;\n","import isArray from 'is-any-array';\n\nfunction max(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 }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var _options$fromIndex = options.fromIndex,\n fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,\n _options$toIndex = options.toIndex,\n toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;\n\n if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {\n throw new Error('fromIndex must be a positive integer smaller than length');\n }\n\n if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {\n throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');\n }\n\n var maxValue = input[fromIndex];\n\n for (var i = fromIndex + 1; i < toIndex; i++) {\n if (input[i] > maxValue) maxValue = input[i];\n }\n\n return maxValue;\n}\n\nexport default max;\n","import isArray from 'is-any-array';\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","const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n","import isArray from 'is-any-array';\n\nfunction max(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 }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var _options$fromIndex = options.fromIndex,\n fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,\n _options$toIndex = options.toIndex,\n toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;\n\n if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {\n throw new Error('fromIndex must be a positive integer smaller than length');\n }\n\n if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {\n throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');\n }\n\n var maxValue = input[fromIndex];\n\n for (var i = fromIndex + 1; i < toIndex; i++) {\n if (input[i] > maxValue) maxValue = input[i];\n }\n\n return maxValue;\n}\n\nexport default max;\n","import isArray from 'is-any-array';\nimport max from 'ml-array-max';\nimport sum from 'ml-array-sum';\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 _options$sumValue = options.sumValue,\n sumValue = _options$sumValue === void 0 ? 1 : _options$sumValue,\n _options$maxValue = options.maxValue,\n maxValue = _options$maxValue === void 0 ? 1 : _options$maxValue;\n\n if (!isArray(input)) {\n throw new Error('input must be an array');\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 if (input.length === 0) {\n throw new Error('input must not be empty');\n }\n\n switch (algorithm.toLowerCase()) {\n case 'absolute':\n {\n var absoluteSumValue = absoluteSum(input) / sumValue;\n if (absoluteSumValue === 0) return input.slice(0);\n\n for (var i = 0; i < input.length; i++) {\n output[i] = input[i] / absoluteSumValue;\n }\n\n return output;\n }\n\n case 'max':\n {\n var currentMaxValue = max(input);\n if (currentMaxValue === 0) return input.slice(0);\n var factor = maxValue / currentMaxValue;\n\n for (var _i = 0; _i < input.length; _i++) {\n output[_i] = input[_i] * factor;\n }\n\n return output;\n }\n\n case 'sum':\n {\n var sumFactor = sum(input) / sumValue;\n if (sumFactor === 0) return input.slice(0);\n\n for (var _i2 = 0; _i2 < input.length; _i2++) {\n output[_i2] = input[_i2] / sumFactor;\n }\n\n return output;\n }\n\n default:\n throw new Error(\"norm: unknown algorithm: \".concat(algorithm));\n }\n}\n\nfunction absoluteSum(input) {\n var sumValue = 0;\n\n for (var i = 0; i < input.length; i++) {\n sumValue += Math.abs(input[i]);\n }\n\n return sumValue;\n}\n\nexport default norm;\n","import isArray from 'is-any-array';\n\nfunction _typeof(obj) {\n \"@babel/helpers - typeof\";\n\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/**\r\n * Fill an array with sequential numbers\r\n * @param {Array} [input] - optional destination array (if not provided a new array will be created)\r\n * @param {object} [options={}]\r\n * @param {number} [options.from=0] - first value in the array\r\n * @param {number} [options.to=10] - last value in the array\r\n * @param {number} [options.size=input.length] - size of the array (if not provided calculated from step)\r\n * @param {number} [options.step] - if not provided calculated from size\r\n * @return {Array}\r\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 !== 0 && 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 // only works with normal array\n input.length = 0;\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","const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n","import isArray from 'is-any-array';\nimport arrayMean from 'ml-array-mean';\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","import variance from 'ml-array-variance';\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 { ascending, descending } 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, descending);\n } else {\n index = binarySearch(x, target, ascending);\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","import mean from 'ml-array-mean';\n\n/**\n *\n * @param {object} points\n * @param {Array} points.x\n * @param {Array} points.y\n * @param {object} [options]\n * @param {boolean} [options.unbiased = true] - if true, divide by (n-1); if false, divide by n.\n * @return {number}\n */\nexport default function covariance(points, options = {}) {\n const { x, y } = points;\n const { unbiased = true } = options;\n\n const meanX = mean(x);\n const meanY = mean(y);\n\n var error = 0;\n\n for (let i = 0; i < x.length; i++) {\n error += (x[i] - meanX) * (y[i] - meanY);\n }\n\n if (unbiased) {\n return error / (x.length - 1);\n } else {\n return error / x.length;\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 { ascending, descending } 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, descending);\n } else {\n index = binarySearch(x, value, ascending);\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","/**\n * Normalize an array of zones:\n * - ensure than from < to\n * - merge overlapping zones\n *\n * The method will always check if from if lower than to and will swap if required.\n * @param {Array} [zones=[]]\n * @param {object} [options={}]\n * @param {number} [options.from=Number.NEGATIVE_INFINITY] Specify min value of a zone\n * @param {number} [options.to=Number.POSITIVE_INFINITY] Specify max value of a zone\n */\n\nexport function normalize(zones = [], options = {}) {\n if (zones.length === 0) return [];\n let {\n from = Number.NEGATIVE_INFINITY,\n to = Number.POSITIVE_INFINITY,\n } = options;\n if (from > to) [from, to] = [to, from];\n\n zones = JSON.parse(JSON.stringify(zones)).map((zone) =>\n zone.from > zone.to ? { from: zone.to, to: zone.from } : zone,\n );\n zones = zones.sort((a, b) => {\n if (a.from !== b.from) return a.from - b.from;\n return a.to - b.to;\n });\n\n zones.forEach((zone) => {\n if (from > zone.from) zone.from = from;\n if (to < zone.to) zone.to = to;\n });\n\n zones = zones.filter((zone) => zone.from <= zone.to);\n if (zones.length === 0) return [];\n\n let currentZone = zones[0];\n let result = [currentZone];\n for (let i = 1; i < zones.length; i++) {\n let zone = zones[i];\n if (zone.from <= currentZone.to) {\n currentZone.to = zone.to;\n } else {\n currentZone = zone;\n result.push(currentZone);\n }\n }\n return result;\n}\n","import { normalize } from './normalize';\n\n/**\n * Convert an array of exclusions and keep only from / to\n *\n * The method will always check if from if lower than to and will swap if required.\n * @param {Array} [exclusions=[]]\n * @param {object} [options={}]\n * @param {number} [options.from=Number.NEGATIVE_INFINITY] Specify min value of zones (after inversion)\n * @param {number} [options.to=Number.POSITIVE_INFINITY] Specify max value of zones (after inversion)\n */\n\nexport function invert(exclusions = [], options = {}) {\n let {\n from = Number.NEGATIVE_INFINITY,\n to = Number.POSITIVE_INFINITY,\n } = options;\n if (from > to) [from, to] = [to, from];\n\n exclusions = normalize(exclusions, { from, to });\n if (exclusions.length === 0) return [{ from, to }];\n\n let zones = [];\n for (let i = 0; i < exclusions.length; i++) {\n let exclusion = exclusions[i];\n let nextExclusion = exclusions[i + 1];\n if (i === 0) {\n if (exclusion.from > from) {\n zones.push({ from, to: exclusion.from });\n }\n }\n if (i === exclusions.length - 1) {\n if (exclusion.to < to) {\n zones.push({ from: exclusion.to, to });\n }\n } else {\n zones.push({ from: exclusion.to, to: nextExclusion.from });\n }\n }\n\n return zones;\n}\n","import { normalize } from './normalize';\n\n/**\n * Add the number of points per zone to reach a specified total\n * @param {Array} [zones=[]]\n * @param {number} [numberOfPoints] Total number of points to distribute between zones\n * @param {object} [options={}]\n * @param {number} [options.from=Number.NEGATIVE_INFINITY] Specify min value of a zone\n * @param {number} [options.to=Number.POSITIVE_INFINITY] Specify max value of a zone\n */\n\nexport function zonesWithPoints(zones, numberOfPoints, options = {}) {\n if (zones.length === 0) return zones;\n zones = normalize(zones, options);\n\n const totalSize = zones.reduce((previous, current) => {\n return previous + (current.to - current.from);\n }, 0);\n\n let unitsPerPoint = totalSize / numberOfPoints;\n let currentTotal = 0;\n for (let i = 0; i < zones.length - 1; i++) {\n let zone = zones[i];\n zone.numberOfPoints = Math.min(\n Math.round((zone.to - zone.from) / unitsPerPoint),\n numberOfPoints - currentTotal,\n );\n currentTotal += zone.numberOfPoints;\n }\n\n zones[zones.length - 1].numberOfPoints = numberOfPoints - currentTotal;\n\n return zones;\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 {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 let xLength = x.length;\n\n let step = (to - from) / (numberOfPoints - 1);\n let halfStep = step / 2;\n\n let output = new Array(numberOfPoints);\n\n let initialOriginalStep = x[1] - x[0];\n let lastOriginalStep = x[xLength - 1] - x[xLength - 2];\n\n // Init main variables\n let min = from - halfStep;\n let max = from + halfStep;\n\n let previousX = Number.MIN_VALUE;\n let previousY = 0;\n let nextX = x[0] - initialOriginalStep;\n let nextY = 0;\n\n let currentValue = 0;\n let slope = 0;\n let intercept = 0;\n let sumAtMin = 0;\n let sumAtMax = 0;\n\n let i = 0; // index of input\n let j = 0; // index of output\n\n function getSlope(x0, y0, x1, y1) {\n return (y1 - y0) / (x1 - x0);\n }\n\n let add = 0;\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 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 let xLength = x.length;\n\n let step = (to - from) / (numberOfPoints - 1);\n let halfStep = step / 2;\n let lastStep = x[x.length - 1] - x[x.length - 2];\n\n let start = from - halfStep;\n let output = new Array(numberOfPoints);\n\n // Init main variables\n let min = start;\n let max = start + step;\n\n let previousX = -Number.MAX_VALUE;\n let previousY = 0;\n let nextX = x[0];\n let nextY = y[0];\n let frontOutsideSpectra = 0;\n let backOutsideSpectra = true;\n\n let currentValue = 0;\n\n // for slot algorithm\n let currentPoints = 0;\n\n let i = 1; // index of input\n let 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 sequentialFill from 'ml-array-sequential-fill';\nimport { zonesWithPoints, invert } from 'ml-zones';\n\nimport equallySpacedSmooth from './equallySpacedSmooth';\nimport equallySpacedSlot from './equallySpacedSlot';\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 * If exclusions zone are present, zones are ignored !\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 * @param {Array} [options.zones=[]] array of from / to that should be kept\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 zones = [],\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 if (numberOfPoints < 2) {\n throw new RangeError(\"'numberOfPoints' option must be greater than 1\");\n }\n\n if (zones.length === 0) {\n zones = invert(exclusions, { from, to });\n }\n\n zones = zonesWithPoints(zones, numberOfPoints, { from, to });\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\n xResult = xResult.concat(zoneResult.x);\n yResult = yResult.concat(zoneResult.y);\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 let 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, 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","import { DecisionTreeClassifier, DecisionTreeRegression } from \"ml-cart\";\nimport {\n RandomForestClassifier,\n RandomForestRegression\n} from \"ml-random-forest\";\n\n// Try to keep this list in the same structure as the README.\n\n// Unsupervised learning\nexport { PCA } from \"ml-pca\";\nimport * as HClust from \"ml-hclust\";\nexport { HClust };\nexport { default as KMeans } from \"ml-kmeans\";\n\n// Supervised learning\nimport * as NaiveBayes from \"ml-naivebayes\";\nexport { NaiveBayes };\nexport { default as KNN } from \"ml-knn\";\nexport { PLS, KOPLS, OPLS, OPLSNipals } from \"ml-pls\";\nimport * as CrossValidation from \"ml-cross-validation\";\nexport { CrossValidation };\nexport { default as ConfusionMatrix } from \"ml-confusion-matrix\";\nexport { DecisionTreeClassifier };\nexport { RandomForestClassifier };\n\n// Artificial neural networks\nexport { default as FNN } from \"ml-fnn\";\nexport { default as SOM } from \"ml-som\";\n\n// Regression\nexport {\n SimpleLinearRegression,\n PolynomialRegression,\n MultivariateLinearRegression,\n PowerRegression,\n ExponentialRegression,\n TheilSenRegression,\n RobustPolynomialRegression\n} from \"ml-regression\";\nexport { DecisionTreeRegression };\nexport { RandomForestRegression };\n\n// Optimization\nexport { default as levenbergMarquardt } from \"ml-levenberg-marquardt\";\nimport * as FCNNLS from \"ml-fcnnls\";\nexport { FCNNLS };\n\n// Math\nimport * as MatrixLib from \"ml-matrix\";\nconst {\n Matrix,\n SVD,\n EVD,\n CholeskyDecomposition,\n LuDecomposition,\n QrDecomposition\n} = MatrixLib;\nexport {\n MatrixLib,\n Matrix,\n SVD,\n EVD,\n CholeskyDecomposition,\n LuDecomposition,\n QrDecomposition\n};\n\nexport { SparseMatrix } from \"ml-sparse-matrix\";\nexport { default as Kernel } from \"ml-kernel\";\nimport { distance, similarity } from \"ml-distance\";\nexport { distance as Distance, similarity as Similarity };\nexport { default as distanceMatrix } from \"ml-distance-matrix\";\nexport { default as XSadd } from \"ml-xsadd\";\n\n// Statistics\nexport { default as Performance } from \"ml-performance\";\n\n// Data preprocessing\nexport { default as savitzkyGolay } from \"ml-savitzky-golay\";\n\n// Utility\nexport { default as BitArray } from \"ml-bit-array\";\nexport { default as HashTable } from \"ml-hash-table\";\nexport { default as padArray } from \"ml-pad-array\";\nexport { default as binarySearch } from \"binary-search\";\nimport * as numSort from \"num-sort\";\nexport { numSort };\nexport { default as Random } from \"ml-random\";\nimport * as GSD from 'ml-gsd';\nexport { GSD };\n\nimport min from \"ml-array-min\";\nimport max from \"ml-array-max\";\nimport median from \"ml-array-median\";\nimport mean from \"ml-array-mean\";\nimport mode from \"ml-array-mode\";\nimport normed from \"ml-array-normed\";\nimport rescale from \"ml-array-rescale\";\nimport sequentialFill from \"ml-array-sequential-fill\";\nimport sum from \"ml-array-sum\";\nimport standardDeviation from \"ml-array-standard-deviation\";\nimport variance from \"ml-array-variance\";\nexport const Array = {\n min,\n max,\n median,\n mean,\n mode,\n normed,\n rescale,\n sequentialFill,\n standardDeviation,\n sum,\n variance\n};\n\nimport centroidsMerge from \"ml-array-xy-centroids-merge\";\nimport closestX from \"ml-arrayxy-closestx\";\nimport covariance from \"ml-array-xy-covariance\";\nimport maxMerge from \"ml-array-xy-max-merge\";\nimport maxY from \"ml-array-xy-max-y\";\nimport sortX from \"ml-array-xy-sort-x\";\nimport uniqueX from \"ml-arrayxy-uniquex\";\nimport weightedMerge from \"ml-array-xy-weighted-merge\";\nimport equallySpaced from \"ml-array-xy-equally-spaced\";\nimport filterX from \"ml-array-xy-filter-x\";\nexport const ArrayXY = {\n centroidsMerge,\n closestX,\n covariance,\n maxMerge,\n maxY,\n sortX,\n uniqueX,\n weightedMerge,\n equallySpaced,\n filterX\n};\n"],"names":["toString","Object","prototype","isAnyArray","object","call","endsWith","max","input","options","arguments","length","undefined","isArray","TypeError","_options$fromIndex","fromIndex","_options$toIndex","toIndex","Number","isInteger","Error","maxValue","i","min","minValue","rescale","output","Array","currentMin","currentMax","RangeError","_options$min","autoMinMax","_options$max","factor","indent","repeat","indentData","inspectMatrix","inspectMatrixWithOptions","this","matrix","maxRows","maxColumns","maxNumSize","constructor","name","inspectData","rows","columns","maxI","Math","maxJ","result","line","j","push","formatNumber","get","join","num","numStr","String","padEnd","precise","toPrecision","exponential","toExponential","eIndex","indexOf","e","slice","installMathOperations","AbstractMatrix","Matrix","add","value","addS","addM","set","checkMatrix","sub","subS","subM","subtract","subtractS","subtractM","mul","mulS","mulM","multiply","multiplyS","multiplyM","div","divS","divM","divide","divideS","divideM","mod","modS","modM","modulus","modulusS","modulusM","and","andS","andM","or","orS","orM","xor","xorS","xorM","leftShift","leftShiftS","leftShiftM","signPropagatingRightShift","signPropagatingRightShiftS","signPropagatingRightShiftM","rightShift","rightShiftS","rightShiftM","zeroFillRightShift","zeroFillRightShiftS","zeroFillRightShiftM","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","pow","arg0","powS","powM","checkRowIndex","index","outer","checkColumnIndex","checkRowVector","vector","to1DArray","checkColumnVector","checkIndices","rowIndices","columnIndices","row","checkRowIndices","column","checkColumnIndices","some","r","from","c","checkRange","startRow","endRow","startColumn","endColumn","checkNumber","newArray","array","sumByRow","sum","sumByColumn","sumAll","v","productByRow","productByColumn","productAll","varianceByRow","unbiased","mean","cols","variance","sum1","sum2","x","varianceByColumn","varianceAll","size","centerByRow","centerByColumn","centerAll","getScaleByRow","scale","scaleByRow","getScaleByColumn","scaleByColumn","getScaleAll","divider","scaleAll","newRows","newColumns","newData","newMatrix","fill","random","interval","zeros","data","l","matrix1","matrix2","isMatrix","klass","apply","callback","to2DArray","copy","toJSON","isRowVector","isColumnVector","isVector","isSquare","isSymmetric","isEchelonForm","previousColumn","checked","isReducedEchelonForm","k","echelonForm","clone","h","iMax","swapRows","tmp","reducedEchelonForm","m","n","maxRow","p","pivot","setSubMatrix","neg","getRow","getRowVector","rowVector","setRow","row1","row2","temp","getColumn","getColumnVector","columnVector","setColumn","swapColumns","column1","column2","addRowVector","subRowVector","mulRowVector","divRowVector","addColumnVector","subColumnVector","mulColumnVector","divColumnVector","mulRow","mulColumn","maxIndex","idx","minIndex","maxRowIndex","minRow","minRowIndex","maxColumn","maxColumnIndex","minColumn","minColumnIndex","diag","norm","type","cumulativeSum","dot","vector2","vector1","mmul","other","Bcolj","Float64Array","s","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","r1","c1","r2","c2","embed","mat","resultat","console","warn","blockMult","a","b","halfRows","parseInt","halfCols","subMatrix","scaleRows","isFinite","scaleColumns","flipRows","middle","first","last","flipColumns","kroneckerProduct","q","transpose","sortRows","compareFunction","compareNumbers","sort","sortColumns","subMatrixRow","indices","subMatrixColumn","selection","rowIndex","columnIndex","trace","by","product","standardDeviation","center","Symbol","for","rand","randomInt","randInt","diagonal","identity","eye","negate","tensorProduct","nRows","nColumns","arrayData","removeRow","splice","addRow","removeColumn","newRow","addColumn","BaseView","MatrixColumnView","MatrixColumnSelectionView","MatrixFlipColumnView","MatrixFlipRowView","MatrixRowView","MatrixRowSelectionView","MatrixSelectionView","MatrixSubView","MatrixTransposeView","WrapperMatrix1D","_calculateIndex","WrapperMatrix2D","wrap","LuDecomposition","t","LUcolj","kmax","lu","pivotVector","pivotSign","LU","isSingular","col","solve","count","X","determinant","hypotenuse","QrDecomposition","qr","rdiag","nrm","QR","Rdiag","isFullRank","SingularValueDecomposition","computeLeftSingularVectors","computeRightSingularVectors","autoTranspose","wantu","Boolean","wantv","swapped","aux","nu","ni","U","V","work","si","nct","nrt","mrc","pp","eps","EPSILON","kase","alpha","MIN_VALUE","isNaN","ks","f","cs","sn","sp","spm1","epm1","sk","ek","shift","g","Y","threshold","scols","Ls","rightSingularVectors","VL","vrows","urows","VLU","solveForDiagonal","inverse","vcols","ucols","tol","ii","useSVD","leftHandSide","rightHandSide","d","subMatrix0","subMatrix1","subMatrix2","xrange","exception","range","dependenciesOneRow","error","thresholdValue","thresholdError","returnArray","linearDependencies","results","Abis","pseudoInverse","svdSolution","SVD","leftSingularVectors","covariance","xMatrix","yMatrix","yIsSame","cov","correlation","sdx","sdy","corr","EigenvalueDecomposition","assumeSymmetric","tred2","tql2","H","ort","orthes","hqr2","hh","dl1","c3","el1","s2","tst1","high","low","nn","w","ra","sa","vr","vi","notlast","cdivres","exshift","z","iter","cdiv","xr","xi","yr","yi","CholeskyDecomposition","dimension","positiveDefinite","L","isPositiveDefinite","B","nipals","scaleScores","maxIterations","terminationCriteria","u","tOld","diff","counter","xResidual","residual","yResidual","betas","sumValue","toDiscreteDistribution","numberOfClasses","counts","giniImpurity","probabilities","getNumberOfClasses","filter","val","arr","map","reduce","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","Infinity","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","DecisionTreeRegression","trainingValues","SMALLEST_UNSAFE_INTEGER","LARGEST_SAFE_INTEGER","UINT32_MAX","UINT32_SIZE","INT32_SIZE","INT32_MAX","UINT21_SIZE","UINT21_MAX","checkFloat","examplesBaggingWithReplacement","trainingValue","seed","engine","Random","autoSeed","Xr","featureBagging","replacement","usedIndex","toRet","Set","has","RandomForestBase","maxFeatures","nEstimators","treeOptions","isClassifier","indexes","useSampleBagging","Estimator","DTClassifier","DTRegression","estimators","est","load","res","values","predictionValues","RandomForestClassifier","baseModel","mode","super","pop","_ref","module","exports","window","median","quickSelectMedian","selectionMethods","arrayMean","arrayMedian","selectionMethod","RandomForestRegression","PCA","dataset","means","stdevs","S","R","excludedFeatures","isCovarianceMatrix","method","nCompNIPALS","ignoreZeroVariance","_computeFromCovarianceMatrix","_adjust","covarianceMatrix","_computeWithNIPALS","svd","singularValues","eigenvalues","singularValue","nComponents","invert","getExplainedVariance","getCumulativeVariance","explained","getEigenvectors","getEigenvalues","getStandardDeviations","getLoadings","evd","EVD","eigenvectorMatrix","realEigenvalues","reverse","dc","NIPALS","squaredEuclidean","euclidean","distanceMatrix","distanceFn","getMatrix","Heap","defaultCmp","heapify","heappop","heappush","heappushpop","heapreplace","insort","nlargest","nsmallest","updateItem","_siftdown","_siftup","lo","hi","cmp","mid","concat","item","lastelt","returnitem","_i","_len","_ref1","_results","_results1","_j","pos","elem","los","startpos","newitem","parent","parentpos","childpos","endpos","rightpos","nodes","replace","pushpop","peek","contains","clear","empty","heap","toArray","insert","top","front","require$$0","Cluster","children","height","isLeaf","cut","list","ans","group","groups","forEach","child","traverse","cb","visit","cluster","singleLink","dKI","dKJ","completeLink","averageLink","dIJ","nj","weightedAverageLink","centroidLink","medianLink","wardLink","nk","wardLink2","ai","aj","agnes","distanceFunction","isDistanceMatrix","updateFunc","getDistanceMatrix","numLeaves","toLowerCase","clusters","distance","getSmallestDistance","cluster1","cluster2","newCluster","newClusters","newDistanceMatrix","previous","newIndex","getPreviousIndex","prevI","prevICluster","smallest","smallestI","smallestJ","prev1","prev2","nearestVector","listVectors","similarityFunction","vectorIndex","maxSim","sim","minDist","MAX_VALUE","dist","calculateDistanceMatrix","updateClusterID","centers","clusterID","updateCenters","prevCenters","K","nDim","centersLen","dim","id","hasConverged","oldCenters","tolerance","LOOP","FLOAT_MUL","sh1","sh2","sh3","multiply_uint32","nlo","XSadd","Date","now","state","Uint32Array","init","getFloat","bind","getUint32","nextState","periodCertification","PROB_TOLERANCE","randomChoice","valuesArr","cumSum","getArray","randomIndex","seedOrRandom","xsadd","XSAdd","randomGenerator","choice","randomSample","mostDistant","maxDist","minDistCent","kmeanspp","nSamples","localTrials","firstCenterIdx","closestDistSquared","cumSumClosestDistSquared","candidateIdx","distanceToCandidates","euclideanDistances","bestCandidate","bestPot","bestDistSquared","newDistSquared","newPot","A","distanceSymbol","KMeansResult","centroids","converged","iterations","nearest","centroid","computeInformation","enrichedCentroids","withIterations","initialization","step","newCenters","kmeansGenerator","stepResult","stepNumber","kmeans","separateClasses","features","classes","totalPerClasses","separatedClasses","currentIndex","GaussianNB","reload","calculateProbabilities","C1","PI","std","logPriorProbability","currentStd","getCurrentClass","modelName","currentCase","maxProbability","predictedClass","currentProbability","calculateLogProbability","C2","MultinomialNB","conditionalProbability","priorProbability","separateClass","classValues","divisor","matrixLog","Node","obj","KDTree","points","metric","dimensions","buildTree","restoreParent","toJSONImpl","point","maxNodes","maxDistance","bestNodes","BinaryHeap","nearestSearch","ownDistance","linearPoint","bestChild","linearDistance","otherChild","saveNode","content","src","dest","depth","scoreFunction","element","bubbleUp","end","sinkDown","parentN","elemScore","child2N","child1N","swap","child1","child1Score","child2","KNN","labels","kdTree","isEuclidean","euclideanDistance","getSinglePrediction","knn","nearestPoints","pointsPerClass","maxPoints","lastElement","currentClass","currentPoints","pow2array","initializeMatrices","PLS","meanX","stdDevX","meanY","stdDevY","PBQ","R2X","scaleMethod","latentVectors","rx","cx","ry","cy","ssqXcal","sumOfSquaresY","T","P","Q","W","transposeX","transposeY","tIndex","maxSumColIndex","uIndex","t1","den","pnorm","ssqYcal","E","F","KOPLS","YLoadingMat","SigmaPow","YScoreMat","predScoreMat","YOrthLoadingVec","YOrthEigen","YOrthScoreMat","toNorm","TURegressionCoeff","kernelX","kernel","orthogonalComp","predictiveComp","predictiveComponents","orthogonalComponents","compute","Identity","Sigma","diagonalMatrix","YOrthScoreNorm","TpiPrime","CoTemp","SoTemp","toiPrime","ITo","lastScoreMat","lastTpPrime","KTestTrain","YOrthScoreVector","scoreMatPrime","p1","p2","p3","prediction","predYOrthVectors","ConfusionMatrix","actual","predicted","distinctLabels","actualIdx","predictedIdx","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","createCommonjsModule","fn","runtime","global","Op","hasOwn","hasOwnProperty","$Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","regeneratorRuntime","GenStateSuspendedStart","GenStateSuspendedYield","GenStateExecuting","GenStateCompleted","ContinueSentinel","IteratorPrototype","getProto","getPrototypeOf","NativeIteratorPrototype","Gp","GeneratorFunctionPrototype","Generator","create","GeneratorFunction","displayName","isGeneratorFunction","genFun","ctor","mark","setPrototypeOf","__proto__","awrap","arg","__await","defineIteratorMethods","AsyncIterator","async","innerFn","outerFn","self","tryLocsList","next","then","done","keys","key","Context","reset","skipTempReset","prev","sent","_sent","delegate","tryEntries","resetTryEntry","charAt","stop","rootRecord","completion","rval","dispatchException","context","handle","loc","caught","record","entry","tryLoc","hasCatch","hasFinally","catchLoc","finallyLoc","abrupt","finallyEntry","complete","afterLoc","finish","thrown","delegateYield","iterable","resultName","nextLoc","protoGenerator","generator","_invoke","makeInvokeMethod","tryCatch","err","invoke","resolve","reject","Promise","unwrapped","previousPromise","enqueue","callInvokeWithMethodAndArg","doneResult","delegateResult","maybeInvokeDelegate","return","info","pushTryEntry","locs","iteratorMethod","Function","hadRuntime","getOwnPropertyNames","oldRuntime","runtimeModule","regenerator","_callee","M","N","twiddle","_context","factory","getFolds","allIdx","current","folds","randi","testIndex","trainIndex","el","idx2","sampleAClass","classVector","fraction","classVectorSorted","JSON","parse","stringify","indexOfSelected","ind","mask","includes","leaveOneOut","Classifier","classifierOptions","leavePOut","distinct","getDistinct","confusionMatrix","initMatrix","gen","combinations","testIdx","trainIdx","validateWithCallback","validate","kFold","testFeatures","trainFeatures","testLabels","trainLabels","getTrainTest","classifier","updateConfusionMatrix","predictedLabels","OPLSNipals","numberOSC","uNew","wOrtho","tOrtho","pOrtho","filteredX","weightsXOrtho","loadingsXOrtho","scoresXOrtho","weightsXPred","loadingsXpred","scoresXpred","loadingsY","tss","OPLS","opls","meansY","stdevsY","tCV","tOrthCV","yHatCV","nComp","cvFolds","from1DArray","Q2","nc","oplsCV","modelNC","yHatk","tPredk","tOrthk","oplsk","fold","trainTest","_getTrainTest","testXk","Xk","Yk","dataCenter","dataSD","plsCV","scores","Eh","tPred","yHat","tssy","Q2y","_predictAll","xRes","XOrth","FeaturesCS","labelsCS","Xres","plsCall","R2x","R2y","plsC","pPred","wPred","betasPred","Qpc","tOrth","pOrth","wOrth","totalPred","Yres","getLogs","getScores","scoresX","scoresY","trueLabels","fromLabels","tssx","oplsC","logistic","expELU","param","softExponential","softExponentialPrime","ACTIVATION_FUNCTIONS","activation","derivate","arctan","softsign","relu","softplus","bent","sinusoid","sinc","gaussian","Layer","inputSize","outputSize","regularization","epsilon","activationParam","selectedFunction","params","actFunction","derFunction","activationFunction","mlMatrix","forward","backpropagation","delta","dW","db","aCopy","update","OutputLayer","FeedForwardNeuralNetworks","hiddenLayers","learningRate","dicts","layers","buildNetwork","dictOutputs","inputs","propagate","outputs","NodeSquare","weights","som","neighbors","adjustWeights","target","influence","getDistance","otherNode","getDistanceTorus","distX","distY","gridDim","getNeighbors","xy","torus","getPos","bestNeighbor","direction","simA","simB","getPosition","NodeHexagonal","hX","distZ","fields","randomizer","squareEuclidean","gridType","SOM","numWeights","converters","getConverters","extractor","creator","nodeType","hx","distanceMethod","getMaxDistance","times","findBMU","adjust","iterationCount","startLearningRate","mapRadius","algorithmMethod","_initNodes","normalizers","denormalizers","getNormalizer","getDenormalizer","minMax","getRandomValue","zero","one","loadModel","eval","export","includeDistance","initNodes","setTraining","convertedSet","numIterations","timeConstant","trainOne","neighbourhoodRadius","trainingSetFactor","bmu","_findBestMatchingUnit","now2","radiusLimit","xMin","xMax","yMin","yMax","theX","theY","getConvertedNodes","candidate","lowest","computePosition","_predict","getQuantizationError","fit","getFit","maybeToPrecision","digits","checkArraySize","BaseRegression","toLaTeX","score","y2","xSum","ySum","chi2","rmsd","xSquared","ySquared","xY","PolynomialRegression","degree","powers","coefficients","checkArrayLength","regress","precision","_toFormula","isLaTeX","sup","closeSup","str","json","pr","FT","SimpleLinearRegression","slope","intercept","computeX","xFactor","absIntercept","slr","numerator","ExponentialRegression","er","yl","linear","PowerRegression","newInputs","latex","xl","MultivariateLinearRegression","statistics","xt","xx","invxx","beta","fittedValues","ri","stdError","stdErrorMatrix","stdErrors","tStats","summary","regressionStatistics","standardError","observations","variables","tStat","sigma","GaussianKernel","constant","PolynomialKernel","SigmoidKernel","ANOVAKernel","len","CauchyKernel","ExponentialKernel","HistogramIntersectionKernel","LaplacianKernel","MultiquadraticKernel","RationalQuadraticKernel","kernelType","rbf","polynomial","poly","anova","cauchy","histogram","HistogramKernel","laplacian","multiquadratic","rational","RationalKernel","sigmoid","mlp","Kernel","KernelConstructor","kernelFunction","landmarks","kernelMatrix","TheilSenRegression","theilSen","slopes","medianSlope","cuts","RobustPolynomialRegression","robustPolynomial","_","tuples","getRandomTuples","calcCoefficients","residuals","residualsMedian","tuple","half","errorCalculation","parameters","parameterizedFunction","func","gradientFunction","evaluatedData","gradientDifference","paramFunction","auxParams","funcParam","matrixFunction","damping","gradientFunc","matrixFunc","inverseMatrix","levenbergMarquardt","errorTolerance","minValues","maxValues","initialValues","parLen","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","iteration","parameterValues","parameterError","sortCollectionSet","collection","objectCollection","BigInt","sorted","cssls","XtX","XtY","Pset","choXtX","luXtX","sortedPset","sortedEset","cols2Solve","vars","initialisation","Fset","D","setDifference","C","optimality","maxIter","Jset","fullSet","notPset","fcnnls","infeasIndex","Hset","ones","hRowColIdx","negRowColIdx","alphaMin","minIdx","idx2zero","findIndex","newParam","fcnnlsVector","haystack","needle","comparator","assertNumber","number","largestPrime","primeNumbers","nextPrime","binarySearch","ascending","FREE","FULL","REMOVED","defaultInitialCapacity","defaultMinLoadFactor","defaultMaxLoadFactor","HashTable","table","minLoadFactor","maxLoadFactor","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","SparseMatrix","_init","elements","symmetric","forEachNonZero","bandWidth","isBanded","width","v1","v2","cardinality","getNonZeros","setThreshold","newThreshold","trans","inplaceOperator","inplaceOperatorScalar","inplaceOperatorMatrix","staticOperator","inplaceMethod","staticMethod","operators","operator","fillTemplateFunction","op","methods","mathMethod","template","RegExp","additiveSymmetric","avg","bhattacharyya","canberra","chebyshev","clark","czekanowskiSimilarity","up","down","czekanowskiDistance","dice","q1","q2","divergence","fidelity","gower","harmonicMean","hellinger","innerProduct","intersection","jaccard","jeffreys","jensenDifference","jensenShannon","kdivergence","kulczynski","kullbackLeibler","kumarHassebrook","kumarJohnson","lorentzian","manhattan","matusita","minkowski","motyka","neyman","pearson","probabilisticSymmetric","ruzicka","soergel","sorensen","squared","squaredChord","taneja","tanimoto","bitvector","inter","union","tanimotoS","topsoe","waveHedges","createTree","spectrum","minWindow","to","mainCreateTree","start","getSimilarity","gamma","treeSimilarity","getFunction","cosine","diceD","intersectionD","jaccardD","kulczynskiD","motykaD","avgA","avgB","newA","newB","squaredChordD","pred","cutoffs","tn","tp","fp","nNeg","nPos","nPosPred","nNegPred","Performance","isDistance","predP","all","targ","currentPred","nTp","nFp","getMeasure","measure","measures","getAURC","auc","getAUDC","getDistribution","cutLength","cutLow","cutHigh","xLabels","interValues","intraValues","interCumPercent","intraCumPercent","nTP","currentTP","nFP","currentFP","thisTP","thisFP","names","acc","fpr","tpr","fnr","tnr","ppv","npv","pcfall","pcmiss","lift","rpp","rnp","arrayCase","cond","matrixCase","padArray","factorial","windowSize","derivative","pad","padValue","savitzkyGolay","J","inic","Jtranspose","det","eightBits","arr1","arr2","getBit","setBit","toBinaryString","substr","parseBinaryString","toHexString","parseHexString","toDebug","binary","SavitzkyGolay","np","fullWeights","hs","constantH","wg1","wg2","d1","d2","getHs","wg","GramPoly","Grampoly","GenFact","gf","Weight","gsd","yIn","noiseLevel","sgOptions","smoothY","heightFactor","broadRatio","maxCriteria","minMaxRatio","derivativeThreshold","realTopDetection","equalSpaced","isEqualSpaced","getNoiseLevel","yCorrection","dY","ddY","yData","SG","xData","dX","maxDdy","maxY","lastMax","lastMin","minddY","intervalL","intervalR","broadMask","minddYLen","intervalLLen","intervalRLen","broadMaskLen","possible","frequency","distanceJ","minDistance","gettingCloser","signals","signalsLen","lastK","soft","yLeft","yRight","determineRealTop","base","maxDx","minDx","stddev","averageDeviations","peakList","currentPoint","sumOfGaussians","nL","optimizeGaussianSum","opts","pInit","pMin","pMax","dt","lmOptions","pFit","LM","singleGaussian","factor2","optimizeSingleGaussian","peak","sumOfLorentzians","optimizeLorentzianSum","singleLorentzian","optimizeSingleLorentzian","optimizePeaks","functionName","factorWidth","optimizationOptions","sampling","lastIndex","groupPeaks","peaks","sampleFunction","limits","optPeaks","fitResult","nbPoints","sampleX","sampleY","upperLimit","lowerLimit","joinBroadPeaks","broadLines","candidates","fitted","broadenPeaks","overlap","nextPeak","maxCount","_options$algorithm","algorithm","_options$sumValue","_options$maxValue","absoluteSumValue","absoluteSum","currentMaxValue","sumFactor","_i2","_typeof","sequentialFill","_options","_options$from","_options$to","_options$size","_options$unbiased","_options$mean","sqrError","mergeByCentroids","originalPoints","mergedPoints","originalIndex","mergedIndex","closestX","descending","maxMerge","groupWidth","merged","maxAbscissa","calculateIndex","sortX","sortFunc","grouped","response","uniqueX","weightedMerge","weightedAbscissa","normalize","zones","NEGATIVE_INFINITY","POSITIVE_INFINITY","zone","currentZone","exclusions","exclusion","nextExclusion","zonesWithPoints","numberOfPoints","unitsPerPoint","currentTotal","integral","x0","x1","equallySpacedSmooth","xLength","halfStep","initialOriginalStep","lastOriginalStep","previousX","previousY","nextX","nextY","currentValue","sumAtMin","sumAtMax","main","equallySpacedSlot","lastStep","frontOutsideSpectra","backOutsideSpectra","equallySpaced","arrayXY","variant","xResult","yResult","zoneResult","processZone","getZones","currentFrom","filterX","currentZoneIndex","newX","newY","position","MatrixLib","normed","ArrayXY","centroidsMerge"],"mappings":"gPAAA,MAAMA,SAAWC,OAAOC,UAAUF,SAEnB,SAASG,WAAWC,UAC1BJ,SAASK,KAAKD,GAAQE,SAAS,UCDxC,SAASC,IAAIC,OACPC,EAAUC,UAAUC,OAAS,QAAsBC,IAAjBF,UAAU,GAAmBA,UAAU,GAAK,OAE7EG,WAAQL,SACL,IAAIM,UAAU,6BAGD,IAAjBN,EAAMG,aACF,IAAIG,UAAU,+BAGlBC,EAAqBN,EAAQO,UAC7BA,OAAmC,IAAvBD,EAAgC,EAAIA,EAChDE,EAAmBR,EAAQS,QAC3BA,OAA+B,IAArBD,EAA8BT,EAAMG,OAASM,KAEvDD,EAAY,GAAKA,GAAaR,EAAMG,SAAWQ,OAAOC,UAAUJ,SAC5D,IAAIK,MAAM,+DAGdH,GAAWF,GAAaE,EAAUV,EAAMG,SAAWQ,OAAOC,UAAUF,SAChE,IAAIG,MAAM,yFAGdC,EAAWd,EAAMQ,GAEZO,EAAIP,EAAY,EAAGO,EAAIL,EAASK,IACnCf,EAAMe,GAAKD,IAAUA,EAAWd,EAAMe,WAGrCD,EC9BT,SAASE,IAAIhB,OACPC,EAAUC,UAAUC,OAAS,QAAsBC,IAAjBF,UAAU,GAAmBA,UAAU,GAAK,OAE7EG,WAAQL,SACL,IAAIM,UAAU,6BAGD,IAAjBN,EAAMG,aACF,IAAIG,UAAU,+BAGlBC,EAAqBN,EAAQO,UAC7BA,OAAmC,IAAvBD,EAAgC,EAAIA,EAChDE,EAAmBR,EAAQS,QAC3BA,OAA+B,IAArBD,EAA8BT,EAAMG,OAASM,KAEvDD,EAAY,GAAKA,GAAaR,EAAMG,SAAWQ,OAAOC,UAAUJ,SAC5D,IAAIK,MAAM,+DAGdH,GAAWF,GAAaE,EAAUV,EAAMG,SAAWQ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AAa/gC,GAETlnB,OAAOwc,MAAMyK,IACR,EAGLjnB,OAAOwc,MAAM0K,GACT,EAGDD,EAAOC,cAGM,CAACD,EAAMC,KAC3B+gC,aAAahhC,GACbghC,aAAa/gC,GAETlnB,OAAOwc,MAAMyK,GACT,EAGJjnB,OAAOwc,MAAM0K,IACR,EAGFA,EAAQD,qLChCT,MAAMkhC,aAAe,WAEtBC,aAAe,CAEnBD,aAGA,EACA,GACA,GACA,GACA,GACA,IACA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,UACA,WAGA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,UACA,WAGA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,WACA,WAGA,KACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,GACA,GACA,IACA,IACA,IACA,KACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,IACA,KACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,EACA,EACA,GACA,GACA,GACA,IACA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,GACA,GACA,IACA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,UACA,WAGA,GACA,GACA,GACA,IACA,IACA,IACA,KACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,GACA,GACA,GACA,IACA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,SACA,UACA,UACA,UACA,WAGA,GACA,IACA,IACA,IACA,IACA,KACA,KACA,KACA,MACA,MACA,MACA,OACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,SACA,SACA,UACA,UACA,UACA,UACA,YAKK,SAASE,UAAU3kD,OACpBoF,EAAQw/C,aAAaF,aAAc1kD,EAAO6kD,kBAC1Cz/C,EAAQ,IACVA,GAASA,GAEJs/C,aAAat/C,GAPtBs/C,aAAaxxC,KAAK2xC,WCtWlB,MAAMC,KAAO,EACPC,KAAO,EACPC,QAAU,EAEVC,uBAAyB,IACzBC,qBAAuB,EAAI,EAC3BC,qBAAuB,EAAI,EAElB,MAAMC,UACnBnnD,YAAYrC,EAAU,OAChBA,aAAmBwpD,sBAChBC,MAAQzpD,EAAQypD,MAAM1lD,aACtBknB,OAASjrB,EAAQirB,OAAOlnB,aACxBszB,MAAQr3B,EAAQq3B,MAAMtzB,aACtB2lD,cAAgB1pD,EAAQ0pD,mBACxBC,cAAgB3pD,EAAQ2pD,mBACxBja,SAAW1vC,EAAQ0vC,cACnBka,YAAc5pD,EAAQ4pD,iBACtBC,aAAe7pD,EAAQ6pD,uBACvBC,cAAgB9pD,EAAQ2pD,qBAIzBI,OACwB5pD,IAA5BH,EAAQ+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AAEm3D,IAAa7C,EAAM0C,GAAkBz4D,KAEvC04D,EAAKlgE,KAAKiJ,EAAEm3D,IACZD,EAAKngE,KAAKuS,EAAE6tD,YAERn3D,EAAEm3D,GAAY7C,EAAM0C,GAAkB/R,KACxC+R,KACK1C,EAAM0C,IAAmB,MAGlCG,UAGK,CACLn3D,EAAGi3D,EACH3tD,EAAG4tD,gBCOLj/D,SADI+b,IAEJA,IAFI+N,IAGJA,0BACApL,wCACAxI,kCACAe,mBACEkoD,UA8CSliE,QAAQ,KACnBJ,UACAjB,MACA8rB,OAAAA,OACAhgB,KAAAA,UACAyf,cACAi4C,OACAriE,QAAAA,QACA09D,eAAAA,eACA1mD,kBAAAA,kBACA9M,IAAAA,IACAW,SAAAA,UAaWy3D,QAAU,gBACrBC,iBACAhE,SAAAA,oBACAr/C,aACAu/C,SAAAA,SACAnG,KAAAA,KACAwG,MAAAA,MACAI,QAAAA,QACAC,cAAAA,cACAmC,cAAAA,cACAS,QAAAA"} \ No newline at end of file diff --git a/package.json b/package.json index 477bdf5..dabfd6c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ml", - "version": "5.1.1", + "version": "5.2.0", "description": "Machine learning tools", "main": "src/index.js", "scripts": { @@ -37,14 +37,14 @@ "homepage": "https://github.com/mljs/ml", "dependencies": { "binary-search": "^1.3.6", - "ml-array-max": "^1.1.2", + "ml-array-max": "^1.2.0", "ml-array-mean": "^1.1.3", "ml-array-median": "^1.1.3", - "ml-array-min": "^1.1.2", - "ml-array-mode": "^1.1.2", + "ml-array-min": "^1.2.0", + "ml-array-mode": "^1.1.3", "ml-array-normed": "^1.3.1", "ml-array-rescale": "^1.3.1", - "ml-array-sequential-fill": "^1.1.2", + "ml-array-sequential-fill": "^1.1.3", "ml-array-standard-deviation": "^1.1.4", "ml-array-variance": "^1.1.4", "ml-array-xy-centroids-merge": "^1.0.1",